xref: /netbsd-src/external/apache2/llvm/dist/clang/lib/Sema/SemaDecl.cpp (revision 7330f729ccf0bd976a06f95fad452fe774fc7fd1)
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 // Determine whether the previous declaration was a definition, implicit
2997 // declaration, or a declaration.
2998 template <typename T>
2999 static std::pair<diag::kind, SourceLocation>
3000 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3001   diag::kind PrevDiag;
3002   SourceLocation OldLocation = Old->getLocation();
3003   if (Old->isThisDeclarationADefinition())
3004     PrevDiag = diag::note_previous_definition;
3005   else if (Old->isImplicit()) {
3006     PrevDiag = diag::note_previous_implicit_declaration;
3007     if (OldLocation.isInvalid())
3008       OldLocation = New->getLocation();
3009   } else
3010     PrevDiag = diag::note_previous_declaration;
3011   return std::make_pair(PrevDiag, OldLocation);
3012 }
3013 
3014 /// canRedefineFunction - checks if a function can be redefined. Currently,
3015 /// only extern inline functions can be redefined, and even then only in
3016 /// GNU89 mode.
3017 static bool canRedefineFunction(const FunctionDecl *FD,
3018                                 const LangOptions& LangOpts) {
3019   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3020           !LangOpts.CPlusPlus &&
3021           FD->isInlineSpecified() &&
3022           FD->getStorageClass() == SC_Extern);
3023 }
3024 
3025 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3026   const AttributedType *AT = T->getAs<AttributedType>();
3027   while (AT && !AT->isCallingConv())
3028     AT = AT->getModifiedType()->getAs<AttributedType>();
3029   return AT;
3030 }
3031 
3032 template <typename T>
3033 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3034   const DeclContext *DC = Old->getDeclContext();
3035   if (DC->isRecord())
3036     return false;
3037 
3038   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3039   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3040     return true;
3041   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3042     return true;
3043   return false;
3044 }
3045 
3046 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3047 static bool isExternC(VarTemplateDecl *) { return false; }
3048 
3049 /// Check whether a redeclaration of an entity introduced by a
3050 /// using-declaration is valid, given that we know it's not an overload
3051 /// (nor a hidden tag declaration).
3052 template<typename ExpectedDecl>
3053 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3054                                    ExpectedDecl *New) {
3055   // C++11 [basic.scope.declarative]p4:
3056   //   Given a set of declarations in a single declarative region, each of
3057   //   which specifies the same unqualified name,
3058   //   -- they shall all refer to the same entity, or all refer to functions
3059   //      and function templates; or
3060   //   -- exactly one declaration shall declare a class name or enumeration
3061   //      name that is not a typedef name and the other declarations shall all
3062   //      refer to the same variable or enumerator, or all refer to functions
3063   //      and function templates; in this case the class name or enumeration
3064   //      name is hidden (3.3.10).
3065 
3066   // C++11 [namespace.udecl]p14:
3067   //   If a function declaration in namespace scope or block scope has the
3068   //   same name and the same parameter-type-list as a function introduced
3069   //   by a using-declaration, and the declarations do not declare the same
3070   //   function, the program is ill-formed.
3071 
3072   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3073   if (Old &&
3074       !Old->getDeclContext()->getRedeclContext()->Equals(
3075           New->getDeclContext()->getRedeclContext()) &&
3076       !(isExternC(Old) && isExternC(New)))
3077     Old = nullptr;
3078 
3079   if (!Old) {
3080     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3081     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3082     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
3083     return true;
3084   }
3085   return false;
3086 }
3087 
3088 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3089                                             const FunctionDecl *B) {
3090   assert(A->getNumParams() == B->getNumParams());
3091 
3092   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3093     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3094     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3095     if (AttrA == AttrB)
3096       return true;
3097     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3098            AttrA->isDynamic() == AttrB->isDynamic();
3099   };
3100 
3101   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3102 }
3103 
3104 /// If necessary, adjust the semantic declaration context for a qualified
3105 /// declaration to name the correct inline namespace within the qualifier.
3106 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3107                                                DeclaratorDecl *OldD) {
3108   // The only case where we need to update the DeclContext is when
3109   // redeclaration lookup for a qualified name finds a declaration
3110   // in an inline namespace within the context named by the qualifier:
3111   //
3112   //   inline namespace N { int f(); }
3113   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3114   //
3115   // For unqualified declarations, the semantic context *can* change
3116   // along the redeclaration chain (for local extern declarations,
3117   // extern "C" declarations, and friend declarations in particular).
3118   if (!NewD->getQualifier())
3119     return;
3120 
3121   // NewD is probably already in the right context.
3122   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3123   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3124   if (NamedDC->Equals(SemaDC))
3125     return;
3126 
3127   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3128           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3129          "unexpected context for redeclaration");
3130 
3131   auto *LexDC = NewD->getLexicalDeclContext();
3132   auto FixSemaDC = [=](NamedDecl *D) {
3133     if (!D)
3134       return;
3135     D->setDeclContext(SemaDC);
3136     D->setLexicalDeclContext(LexDC);
3137   };
3138 
3139   FixSemaDC(NewD);
3140   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3141     FixSemaDC(FD->getDescribedFunctionTemplate());
3142   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3143     FixSemaDC(VD->getDescribedVarTemplate());
3144 }
3145 
3146 /// MergeFunctionDecl - We just parsed a function 'New' from
3147 /// declarator D which has the same name and scope as a previous
3148 /// declaration 'Old'.  Figure out how to resolve this situation,
3149 /// merging decls or emitting diagnostics as appropriate.
3150 ///
3151 /// In C++, New and Old must be declarations that are not
3152 /// overloaded. Use IsOverload to determine whether New and Old are
3153 /// overloaded, and to select the Old declaration that New should be
3154 /// merged with.
3155 ///
3156 /// Returns true if there was an error, false otherwise.
3157 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3158                              Scope *S, bool MergeTypeWithOld) {
3159   // Verify the old decl was also a function.
3160   FunctionDecl *Old = OldD->getAsFunction();
3161   if (!Old) {
3162     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3163       if (New->getFriendObjectKind()) {
3164         Diag(New->getLocation(), diag::err_using_decl_friend);
3165         Diag(Shadow->getTargetDecl()->getLocation(),
3166              diag::note_using_decl_target);
3167         Diag(Shadow->getUsingDecl()->getLocation(),
3168              diag::note_using_decl) << 0;
3169         return true;
3170       }
3171 
3172       // Check whether the two declarations might declare the same function.
3173       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3174         return true;
3175       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3176     } else {
3177       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3178         << New->getDeclName();
3179       notePreviousDefinition(OldD, New->getLocation());
3180       return true;
3181     }
3182   }
3183 
3184   // If the old declaration is invalid, just give up here.
3185   if (Old->isInvalidDecl())
3186     return true;
3187 
3188   // Disallow redeclaration of some builtins.
3189   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3190     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3191     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3192         << Old << Old->getType();
3193     return true;
3194   }
3195 
3196   diag::kind PrevDiag;
3197   SourceLocation OldLocation;
3198   std::tie(PrevDiag, OldLocation) =
3199       getNoteDiagForInvalidRedeclaration(Old, New);
3200 
3201   // Don't complain about this if we're in GNU89 mode and the old function
3202   // is an extern inline function.
3203   // Don't complain about specializations. They are not supposed to have
3204   // storage classes.
3205   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3206       New->getStorageClass() == SC_Static &&
3207       Old->hasExternalFormalLinkage() &&
3208       !New->getTemplateSpecializationInfo() &&
3209       !canRedefineFunction(Old, getLangOpts())) {
3210     if (getLangOpts().MicrosoftExt) {
3211       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3212       Diag(OldLocation, PrevDiag);
3213     } else {
3214       Diag(New->getLocation(), diag::err_static_non_static) << New;
3215       Diag(OldLocation, PrevDiag);
3216       return true;
3217     }
3218   }
3219 
3220   if (New->hasAttr<InternalLinkageAttr>() &&
3221       !Old->hasAttr<InternalLinkageAttr>()) {
3222     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3223         << New->getDeclName();
3224     notePreviousDefinition(Old, New->getLocation());
3225     New->dropAttr<InternalLinkageAttr>();
3226   }
3227 
3228   if (CheckRedeclarationModuleOwnership(New, Old))
3229     return true;
3230 
3231   if (!getLangOpts().CPlusPlus) {
3232     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3233     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3234       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3235         << New << OldOvl;
3236 
3237       // Try our best to find a decl that actually has the overloadable
3238       // attribute for the note. In most cases (e.g. programs with only one
3239       // broken declaration/definition), this won't matter.
3240       //
3241       // FIXME: We could do this if we juggled some extra state in
3242       // OverloadableAttr, rather than just removing it.
3243       const Decl *DiagOld = Old;
3244       if (OldOvl) {
3245         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3246           const auto *A = D->getAttr<OverloadableAttr>();
3247           return A && !A->isImplicit();
3248         });
3249         // If we've implicitly added *all* of the overloadable attrs to this
3250         // chain, emitting a "previous redecl" note is pointless.
3251         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3252       }
3253 
3254       if (DiagOld)
3255         Diag(DiagOld->getLocation(),
3256              diag::note_attribute_overloadable_prev_overload)
3257           << OldOvl;
3258 
3259       if (OldOvl)
3260         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3261       else
3262         New->dropAttr<OverloadableAttr>();
3263     }
3264   }
3265 
3266   // If a function is first declared with a calling convention, but is later
3267   // declared or defined without one, all following decls assume the calling
3268   // convention of the first.
3269   //
3270   // It's OK if a function is first declared without a calling convention,
3271   // but is later declared or defined with the default calling convention.
3272   //
3273   // To test if either decl has an explicit calling convention, we look for
3274   // AttributedType sugar nodes on the type as written.  If they are missing or
3275   // were canonicalized away, we assume the calling convention was implicit.
3276   //
3277   // Note also that we DO NOT return at this point, because we still have
3278   // other tests to run.
3279   QualType OldQType = Context.getCanonicalType(Old->getType());
3280   QualType NewQType = Context.getCanonicalType(New->getType());
3281   const FunctionType *OldType = cast<FunctionType>(OldQType);
3282   const FunctionType *NewType = cast<FunctionType>(NewQType);
3283   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3284   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3285   bool RequiresAdjustment = false;
3286 
3287   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3288     FunctionDecl *First = Old->getFirstDecl();
3289     const FunctionType *FT =
3290         First->getType().getCanonicalType()->castAs<FunctionType>();
3291     FunctionType::ExtInfo FI = FT->getExtInfo();
3292     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3293     if (!NewCCExplicit) {
3294       // Inherit the CC from the previous declaration if it was specified
3295       // there but not here.
3296       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3297       RequiresAdjustment = true;
3298     } else if (New->getBuiltinID()) {
3299       // Calling Conventions on a Builtin aren't really useful and setting a
3300       // default calling convention and cdecl'ing some builtin redeclarations is
3301       // common, so warn and ignore the calling convention on the redeclaration.
3302       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3303           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3304           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3305       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3306       RequiresAdjustment = true;
3307     } else {
3308       // Calling conventions aren't compatible, so complain.
3309       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3310       Diag(New->getLocation(), diag::err_cconv_change)
3311         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3312         << !FirstCCExplicit
3313         << (!FirstCCExplicit ? "" :
3314             FunctionType::getNameForCallConv(FI.getCC()));
3315 
3316       // Put the note on the first decl, since it is the one that matters.
3317       Diag(First->getLocation(), diag::note_previous_declaration);
3318       return true;
3319     }
3320   }
3321 
3322   // FIXME: diagnose the other way around?
3323   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3324     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3325     RequiresAdjustment = true;
3326   }
3327 
3328   // Merge regparm attribute.
3329   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3330       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3331     if (NewTypeInfo.getHasRegParm()) {
3332       Diag(New->getLocation(), diag::err_regparm_mismatch)
3333         << NewType->getRegParmType()
3334         << OldType->getRegParmType();
3335       Diag(OldLocation, diag::note_previous_declaration);
3336       return true;
3337     }
3338 
3339     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3340     RequiresAdjustment = true;
3341   }
3342 
3343   // Merge ns_returns_retained attribute.
3344   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3345     if (NewTypeInfo.getProducesResult()) {
3346       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3347           << "'ns_returns_retained'";
3348       Diag(OldLocation, diag::note_previous_declaration);
3349       return true;
3350     }
3351 
3352     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3353     RequiresAdjustment = true;
3354   }
3355 
3356   if (OldTypeInfo.getNoCallerSavedRegs() !=
3357       NewTypeInfo.getNoCallerSavedRegs()) {
3358     if (NewTypeInfo.getNoCallerSavedRegs()) {
3359       AnyX86NoCallerSavedRegistersAttr *Attr =
3360         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3361       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3362       Diag(OldLocation, diag::note_previous_declaration);
3363       return true;
3364     }
3365 
3366     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3367     RequiresAdjustment = true;
3368   }
3369 
3370   if (RequiresAdjustment) {
3371     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3372     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3373     New->setType(QualType(AdjustedType, 0));
3374     NewQType = Context.getCanonicalType(New->getType());
3375   }
3376 
3377   // If this redeclaration makes the function inline, we may need to add it to
3378   // UndefinedButUsed.
3379   if (!Old->isInlined() && New->isInlined() &&
3380       !New->hasAttr<GNUInlineAttr>() &&
3381       !getLangOpts().GNUInline &&
3382       Old->isUsed(false) &&
3383       !Old->isDefined() && !New->isThisDeclarationADefinition())
3384     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3385                                            SourceLocation()));
3386 
3387   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3388   // about it.
3389   if (New->hasAttr<GNUInlineAttr>() &&
3390       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3391     UndefinedButUsed.erase(Old->getCanonicalDecl());
3392   }
3393 
3394   // If pass_object_size params don't match up perfectly, this isn't a valid
3395   // redeclaration.
3396   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3397       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3398     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3399         << New->getDeclName();
3400     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3401     return true;
3402   }
3403 
3404   if (getLangOpts().CPlusPlus) {
3405     // C++1z [over.load]p2
3406     //   Certain function declarations cannot be overloaded:
3407     //     -- Function declarations that differ only in the return type,
3408     //        the exception specification, or both cannot be overloaded.
3409 
3410     // Check the exception specifications match. This may recompute the type of
3411     // both Old and New if it resolved exception specifications, so grab the
3412     // types again after this. Because this updates the type, we do this before
3413     // any of the other checks below, which may update the "de facto" NewQType
3414     // but do not necessarily update the type of New.
3415     if (CheckEquivalentExceptionSpec(Old, New))
3416       return true;
3417     OldQType = Context.getCanonicalType(Old->getType());
3418     NewQType = Context.getCanonicalType(New->getType());
3419 
3420     // Go back to the type source info to compare the declared return types,
3421     // per C++1y [dcl.type.auto]p13:
3422     //   Redeclarations or specializations of a function or function template
3423     //   with a declared return type that uses a placeholder type shall also
3424     //   use that placeholder, not a deduced type.
3425     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3426     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3427     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3428         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3429                                        OldDeclaredReturnType)) {
3430       QualType ResQT;
3431       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3432           OldDeclaredReturnType->isObjCObjectPointerType())
3433         // FIXME: This does the wrong thing for a deduced return type.
3434         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3435       if (ResQT.isNull()) {
3436         if (New->isCXXClassMember() && New->isOutOfLine())
3437           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3438               << New << New->getReturnTypeSourceRange();
3439         else
3440           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3441               << New->getReturnTypeSourceRange();
3442         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3443                                     << Old->getReturnTypeSourceRange();
3444         return true;
3445       }
3446       else
3447         NewQType = ResQT;
3448     }
3449 
3450     QualType OldReturnType = OldType->getReturnType();
3451     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3452     if (OldReturnType != NewReturnType) {
3453       // If this function has a deduced return type and has already been
3454       // defined, copy the deduced value from the old declaration.
3455       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3456       if (OldAT && OldAT->isDeduced()) {
3457         New->setType(
3458             SubstAutoType(New->getType(),
3459                           OldAT->isDependentType() ? Context.DependentTy
3460                                                    : OldAT->getDeducedType()));
3461         NewQType = Context.getCanonicalType(
3462             SubstAutoType(NewQType,
3463                           OldAT->isDependentType() ? Context.DependentTy
3464                                                    : OldAT->getDeducedType()));
3465       }
3466     }
3467 
3468     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3469     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3470     if (OldMethod && NewMethod) {
3471       // Preserve triviality.
3472       NewMethod->setTrivial(OldMethod->isTrivial());
3473 
3474       // MSVC allows explicit template specialization at class scope:
3475       // 2 CXXMethodDecls referring to the same function will be injected.
3476       // We don't want a redeclaration error.
3477       bool IsClassScopeExplicitSpecialization =
3478                               OldMethod->isFunctionTemplateSpecialization() &&
3479                               NewMethod->isFunctionTemplateSpecialization();
3480       bool isFriend = NewMethod->getFriendObjectKind();
3481 
3482       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3483           !IsClassScopeExplicitSpecialization) {
3484         //    -- Member function declarations with the same name and the
3485         //       same parameter types cannot be overloaded if any of them
3486         //       is a static member function declaration.
3487         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3488           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3489           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3490           return true;
3491         }
3492 
3493         // C++ [class.mem]p1:
3494         //   [...] A member shall not be declared twice in the
3495         //   member-specification, except that a nested class or member
3496         //   class template can be declared and then later defined.
3497         if (!inTemplateInstantiation()) {
3498           unsigned NewDiag;
3499           if (isa<CXXConstructorDecl>(OldMethod))
3500             NewDiag = diag::err_constructor_redeclared;
3501           else if (isa<CXXDestructorDecl>(NewMethod))
3502             NewDiag = diag::err_destructor_redeclared;
3503           else if (isa<CXXConversionDecl>(NewMethod))
3504             NewDiag = diag::err_conv_function_redeclared;
3505           else
3506             NewDiag = diag::err_member_redeclared;
3507 
3508           Diag(New->getLocation(), NewDiag);
3509         } else {
3510           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3511             << New << New->getType();
3512         }
3513         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3514         return true;
3515 
3516       // Complain if this is an explicit declaration of a special
3517       // member that was initially declared implicitly.
3518       //
3519       // As an exception, it's okay to befriend such methods in order
3520       // to permit the implicit constructor/destructor/operator calls.
3521       } else if (OldMethod->isImplicit()) {
3522         if (isFriend) {
3523           NewMethod->setImplicit();
3524         } else {
3525           Diag(NewMethod->getLocation(),
3526                diag::err_definition_of_implicitly_declared_member)
3527             << New << getSpecialMember(OldMethod);
3528           return true;
3529         }
3530       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3531         Diag(NewMethod->getLocation(),
3532              diag::err_definition_of_explicitly_defaulted_member)
3533           << getSpecialMember(OldMethod);
3534         return true;
3535       }
3536     }
3537 
3538     // C++11 [dcl.attr.noreturn]p1:
3539     //   The first declaration of a function shall specify the noreturn
3540     //   attribute if any declaration of that function specifies the noreturn
3541     //   attribute.
3542     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3543     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3544       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3545       Diag(Old->getFirstDecl()->getLocation(),
3546            diag::note_noreturn_missing_first_decl);
3547     }
3548 
3549     // C++11 [dcl.attr.depend]p2:
3550     //   The first declaration of a function shall specify the
3551     //   carries_dependency attribute for its declarator-id if any declaration
3552     //   of the function specifies the carries_dependency attribute.
3553     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3554     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3555       Diag(CDA->getLocation(),
3556            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3557       Diag(Old->getFirstDecl()->getLocation(),
3558            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3559     }
3560 
3561     // (C++98 8.3.5p3):
3562     //   All declarations for a function shall agree exactly in both the
3563     //   return type and the parameter-type-list.
3564     // We also want to respect all the extended bits except noreturn.
3565 
3566     // noreturn should now match unless the old type info didn't have it.
3567     QualType OldQTypeForComparison = OldQType;
3568     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3569       auto *OldType = OldQType->castAs<FunctionProtoType>();
3570       const FunctionType *OldTypeForComparison
3571         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3572       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3573       assert(OldQTypeForComparison.isCanonical());
3574     }
3575 
3576     if (haveIncompatibleLanguageLinkages(Old, New)) {
3577       // As a special case, retain the language linkage from previous
3578       // declarations of a friend function as an extension.
3579       //
3580       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3581       // and is useful because there's otherwise no way to specify language
3582       // linkage within class scope.
3583       //
3584       // Check cautiously as the friend object kind isn't yet complete.
3585       if (New->getFriendObjectKind() != Decl::FOK_None) {
3586         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3587         Diag(OldLocation, PrevDiag);
3588       } else {
3589         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3590         Diag(OldLocation, PrevDiag);
3591         return true;
3592       }
3593     }
3594 
3595     // If the function types are compatible, merge the declarations. Ignore the
3596     // exception specifier because it was already checked above in
3597     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3598     // about incompatible types under -fms-compatibility.
3599     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3600                                                          NewQType))
3601       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3602 
3603     // If the types are imprecise (due to dependent constructs in friends or
3604     // local extern declarations), it's OK if they differ. We'll check again
3605     // during instantiation.
3606     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3607       return false;
3608 
3609     // Fall through for conflicting redeclarations and redefinitions.
3610   }
3611 
3612   // C: Function types need to be compatible, not identical. This handles
3613   // duplicate function decls like "void f(int); void f(enum X);" properly.
3614   if (!getLangOpts().CPlusPlus &&
3615       Context.typesAreCompatible(OldQType, NewQType)) {
3616     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3617     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3618     const FunctionProtoType *OldProto = nullptr;
3619     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3620         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3621       // The old declaration provided a function prototype, but the
3622       // new declaration does not. Merge in the prototype.
3623       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3624       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3625       NewQType =
3626           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3627                                   OldProto->getExtProtoInfo());
3628       New->setType(NewQType);
3629       New->setHasInheritedPrototype();
3630 
3631       // Synthesize parameters with the same types.
3632       SmallVector<ParmVarDecl*, 16> Params;
3633       for (const auto &ParamType : OldProto->param_types()) {
3634         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3635                                                  SourceLocation(), nullptr,
3636                                                  ParamType, /*TInfo=*/nullptr,
3637                                                  SC_None, nullptr);
3638         Param->setScopeInfo(0, Params.size());
3639         Param->setImplicit();
3640         Params.push_back(Param);
3641       }
3642 
3643       New->setParams(Params);
3644     }
3645 
3646     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3647   }
3648 
3649   // GNU C permits a K&R definition to follow a prototype declaration
3650   // if the declared types of the parameters in the K&R definition
3651   // match the types in the prototype declaration, even when the
3652   // promoted types of the parameters from the K&R definition differ
3653   // from the types in the prototype. GCC then keeps the types from
3654   // the prototype.
3655   //
3656   // If a variadic prototype is followed by a non-variadic K&R definition,
3657   // the K&R definition becomes variadic.  This is sort of an edge case, but
3658   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3659   // C99 6.9.1p8.
3660   if (!getLangOpts().CPlusPlus &&
3661       Old->hasPrototype() && !New->hasPrototype() &&
3662       New->getType()->getAs<FunctionProtoType>() &&
3663       Old->getNumParams() == New->getNumParams()) {
3664     SmallVector<QualType, 16> ArgTypes;
3665     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3666     const FunctionProtoType *OldProto
3667       = Old->getType()->getAs<FunctionProtoType>();
3668     const FunctionProtoType *NewProto
3669       = New->getType()->getAs<FunctionProtoType>();
3670 
3671     // Determine whether this is the GNU C extension.
3672     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3673                                                NewProto->getReturnType());
3674     bool LooseCompatible = !MergedReturn.isNull();
3675     for (unsigned Idx = 0, End = Old->getNumParams();
3676          LooseCompatible && Idx != End; ++Idx) {
3677       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3678       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3679       if (Context.typesAreCompatible(OldParm->getType(),
3680                                      NewProto->getParamType(Idx))) {
3681         ArgTypes.push_back(NewParm->getType());
3682       } else if (Context.typesAreCompatible(OldParm->getType(),
3683                                             NewParm->getType(),
3684                                             /*CompareUnqualified=*/true)) {
3685         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3686                                            NewProto->getParamType(Idx) };
3687         Warnings.push_back(Warn);
3688         ArgTypes.push_back(NewParm->getType());
3689       } else
3690         LooseCompatible = false;
3691     }
3692 
3693     if (LooseCompatible) {
3694       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3695         Diag(Warnings[Warn].NewParm->getLocation(),
3696              diag::ext_param_promoted_not_compatible_with_prototype)
3697           << Warnings[Warn].PromotedType
3698           << Warnings[Warn].OldParm->getType();
3699         if (Warnings[Warn].OldParm->getLocation().isValid())
3700           Diag(Warnings[Warn].OldParm->getLocation(),
3701                diag::note_previous_declaration);
3702       }
3703 
3704       if (MergeTypeWithOld)
3705         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3706                                              OldProto->getExtProtoInfo()));
3707       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3708     }
3709 
3710     // Fall through to diagnose conflicting types.
3711   }
3712 
3713   // A function that has already been declared has been redeclared or
3714   // defined with a different type; show an appropriate diagnostic.
3715 
3716   // If the previous declaration was an implicitly-generated builtin
3717   // declaration, then at the very least we should use a specialized note.
3718   unsigned BuiltinID;
3719   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3720     // If it's actually a library-defined builtin function like 'malloc'
3721     // or 'printf', just warn about the incompatible redeclaration.
3722     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3723       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3724       Diag(OldLocation, diag::note_previous_builtin_declaration)
3725         << Old << Old->getType();
3726 
3727       // If this is a global redeclaration, just forget hereafter
3728       // about the "builtin-ness" of the function.
3729       //
3730       // Doing this for local extern declarations is problematic.  If
3731       // the builtin declaration remains visible, a second invalid
3732       // local declaration will produce a hard error; if it doesn't
3733       // remain visible, a single bogus local redeclaration (which is
3734       // actually only a warning) could break all the downstream code.
3735       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3736         New->getIdentifier()->revertBuiltin();
3737 
3738       return false;
3739     }
3740 
3741     PrevDiag = diag::note_previous_builtin_declaration;
3742   }
3743 
3744   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3745   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3746   return true;
3747 }
3748 
3749 /// Completes the merge of two function declarations that are
3750 /// known to be compatible.
3751 ///
3752 /// This routine handles the merging of attributes and other
3753 /// properties of function declarations from the old declaration to
3754 /// the new declaration, once we know that New is in fact a
3755 /// redeclaration of Old.
3756 ///
3757 /// \returns false
3758 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3759                                         Scope *S, bool MergeTypeWithOld) {
3760   // Merge the attributes
3761   mergeDeclAttributes(New, Old);
3762 
3763   // Merge "pure" flag.
3764   if (Old->isPure())
3765     New->setPure();
3766 
3767   // Merge "used" flag.
3768   if (Old->getMostRecentDecl()->isUsed(false))
3769     New->setIsUsed();
3770 
3771   // Merge attributes from the parameters.  These can mismatch with K&R
3772   // declarations.
3773   if (New->getNumParams() == Old->getNumParams())
3774       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3775         ParmVarDecl *NewParam = New->getParamDecl(i);
3776         ParmVarDecl *OldParam = Old->getParamDecl(i);
3777         mergeParamDeclAttributes(NewParam, OldParam, *this);
3778         mergeParamDeclTypes(NewParam, OldParam, *this);
3779       }
3780 
3781   if (getLangOpts().CPlusPlus)
3782     return MergeCXXFunctionDecl(New, Old, S);
3783 
3784   // Merge the function types so the we get the composite types for the return
3785   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3786   // was visible.
3787   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3788   if (!Merged.isNull() && MergeTypeWithOld)
3789     New->setType(Merged);
3790 
3791   return false;
3792 }
3793 
3794 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3795                                 ObjCMethodDecl *oldMethod) {
3796   // Merge the attributes, including deprecated/unavailable
3797   AvailabilityMergeKind MergeKind =
3798     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3799       ? AMK_ProtocolImplementation
3800       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3801                                                        : AMK_Override;
3802 
3803   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3804 
3805   // Merge attributes from the parameters.
3806   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3807                                        oe = oldMethod->param_end();
3808   for (ObjCMethodDecl::param_iterator
3809          ni = newMethod->param_begin(), ne = newMethod->param_end();
3810        ni != ne && oi != oe; ++ni, ++oi)
3811     mergeParamDeclAttributes(*ni, *oi, *this);
3812 
3813   CheckObjCMethodOverride(newMethod, oldMethod);
3814 }
3815 
3816 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3817   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3818 
3819   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3820          ? diag::err_redefinition_different_type
3821          : diag::err_redeclaration_different_type)
3822     << New->getDeclName() << New->getType() << Old->getType();
3823 
3824   diag::kind PrevDiag;
3825   SourceLocation OldLocation;
3826   std::tie(PrevDiag, OldLocation)
3827     = getNoteDiagForInvalidRedeclaration(Old, New);
3828   S.Diag(OldLocation, PrevDiag);
3829   New->setInvalidDecl();
3830 }
3831 
3832 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3833 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3834 /// emitting diagnostics as appropriate.
3835 ///
3836 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3837 /// to here in AddInitializerToDecl. We can't check them before the initializer
3838 /// is attached.
3839 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3840                              bool MergeTypeWithOld) {
3841   if (New->isInvalidDecl() || Old->isInvalidDecl())
3842     return;
3843 
3844   QualType MergedT;
3845   if (getLangOpts().CPlusPlus) {
3846     if (New->getType()->isUndeducedType()) {
3847       // We don't know what the new type is until the initializer is attached.
3848       return;
3849     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3850       // These could still be something that needs exception specs checked.
3851       return MergeVarDeclExceptionSpecs(New, Old);
3852     }
3853     // C++ [basic.link]p10:
3854     //   [...] the types specified by all declarations referring to a given
3855     //   object or function shall be identical, except that declarations for an
3856     //   array object can specify array types that differ by the presence or
3857     //   absence of a major array bound (8.3.4).
3858     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3859       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3860       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3861 
3862       // We are merging a variable declaration New into Old. If it has an array
3863       // bound, and that bound differs from Old's bound, we should diagnose the
3864       // mismatch.
3865       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3866         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3867              PrevVD = PrevVD->getPreviousDecl()) {
3868           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3869           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3870             continue;
3871 
3872           if (!Context.hasSameType(NewArray, PrevVDTy))
3873             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3874         }
3875       }
3876 
3877       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3878         if (Context.hasSameType(OldArray->getElementType(),
3879                                 NewArray->getElementType()))
3880           MergedT = New->getType();
3881       }
3882       // FIXME: Check visibility. New is hidden but has a complete type. If New
3883       // has no array bound, it should not inherit one from Old, if Old is not
3884       // visible.
3885       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3886         if (Context.hasSameType(OldArray->getElementType(),
3887                                 NewArray->getElementType()))
3888           MergedT = Old->getType();
3889       }
3890     }
3891     else if (New->getType()->isObjCObjectPointerType() &&
3892                Old->getType()->isObjCObjectPointerType()) {
3893       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3894                                               Old->getType());
3895     }
3896   } else {
3897     // C 6.2.7p2:
3898     //   All declarations that refer to the same object or function shall have
3899     //   compatible type.
3900     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3901   }
3902   if (MergedT.isNull()) {
3903     // It's OK if we couldn't merge types if either type is dependent, for a
3904     // block-scope variable. In other cases (static data members of class
3905     // templates, variable templates, ...), we require the types to be
3906     // equivalent.
3907     // FIXME: The C++ standard doesn't say anything about this.
3908     if ((New->getType()->isDependentType() ||
3909          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3910       // If the old type was dependent, we can't merge with it, so the new type
3911       // becomes dependent for now. We'll reproduce the original type when we
3912       // instantiate the TypeSourceInfo for the variable.
3913       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3914         New->setType(Context.DependentTy);
3915       return;
3916     }
3917     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3918   }
3919 
3920   // Don't actually update the type on the new declaration if the old
3921   // declaration was an extern declaration in a different scope.
3922   if (MergeTypeWithOld)
3923     New->setType(MergedT);
3924 }
3925 
3926 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3927                                   LookupResult &Previous) {
3928   // C11 6.2.7p4:
3929   //   For an identifier with internal or external linkage declared
3930   //   in a scope in which a prior declaration of that identifier is
3931   //   visible, if the prior declaration specifies internal or
3932   //   external linkage, the type of the identifier at the later
3933   //   declaration becomes the composite type.
3934   //
3935   // If the variable isn't visible, we do not merge with its type.
3936   if (Previous.isShadowed())
3937     return false;
3938 
3939   if (S.getLangOpts().CPlusPlus) {
3940     // C++11 [dcl.array]p3:
3941     //   If there is a preceding declaration of the entity in the same
3942     //   scope in which the bound was specified, an omitted array bound
3943     //   is taken to be the same as in that earlier declaration.
3944     return NewVD->isPreviousDeclInSameBlockScope() ||
3945            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3946             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3947   } else {
3948     // If the old declaration was function-local, don't merge with its
3949     // type unless we're in the same function.
3950     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3951            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3952   }
3953 }
3954 
3955 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3956 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3957 /// situation, merging decls or emitting diagnostics as appropriate.
3958 ///
3959 /// Tentative definition rules (C99 6.9.2p2) are checked by
3960 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3961 /// definitions here, since the initializer hasn't been attached.
3962 ///
3963 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3964   // If the new decl is already invalid, don't do any other checking.
3965   if (New->isInvalidDecl())
3966     return;
3967 
3968   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3969     return;
3970 
3971   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3972 
3973   // Verify the old decl was also a variable or variable template.
3974   VarDecl *Old = nullptr;
3975   VarTemplateDecl *OldTemplate = nullptr;
3976   if (Previous.isSingleResult()) {
3977     if (NewTemplate) {
3978       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3979       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3980 
3981       if (auto *Shadow =
3982               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3983         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3984           return New->setInvalidDecl();
3985     } else {
3986       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3987 
3988       if (auto *Shadow =
3989               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3990         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3991           return New->setInvalidDecl();
3992     }
3993   }
3994   if (!Old) {
3995     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3996         << New->getDeclName();
3997     notePreviousDefinition(Previous.getRepresentativeDecl(),
3998                            New->getLocation());
3999     return New->setInvalidDecl();
4000   }
4001 
4002   // Ensure the template parameters are compatible.
4003   if (NewTemplate &&
4004       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4005                                       OldTemplate->getTemplateParameters(),
4006                                       /*Complain=*/true, TPL_TemplateMatch))
4007     return New->setInvalidDecl();
4008 
4009   // C++ [class.mem]p1:
4010   //   A member shall not be declared twice in the member-specification [...]
4011   //
4012   // Here, we need only consider static data members.
4013   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4014     Diag(New->getLocation(), diag::err_duplicate_member)
4015       << New->getIdentifier();
4016     Diag(Old->getLocation(), diag::note_previous_declaration);
4017     New->setInvalidDecl();
4018   }
4019 
4020   mergeDeclAttributes(New, Old);
4021   // Warn if an already-declared variable is made a weak_import in a subsequent
4022   // declaration
4023   if (New->hasAttr<WeakImportAttr>() &&
4024       Old->getStorageClass() == SC_None &&
4025       !Old->hasAttr<WeakImportAttr>()) {
4026     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4027     notePreviousDefinition(Old, New->getLocation());
4028     // Remove weak_import attribute on new declaration.
4029     New->dropAttr<WeakImportAttr>();
4030   }
4031 
4032   if (New->hasAttr<InternalLinkageAttr>() &&
4033       !Old->hasAttr<InternalLinkageAttr>()) {
4034     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
4035         << New->getDeclName();
4036     notePreviousDefinition(Old, New->getLocation());
4037     New->dropAttr<InternalLinkageAttr>();
4038   }
4039 
4040   // Merge the types.
4041   VarDecl *MostRecent = Old->getMostRecentDecl();
4042   if (MostRecent != Old) {
4043     MergeVarDeclTypes(New, MostRecent,
4044                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4045     if (New->isInvalidDecl())
4046       return;
4047   }
4048 
4049   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4050   if (New->isInvalidDecl())
4051     return;
4052 
4053   diag::kind PrevDiag;
4054   SourceLocation OldLocation;
4055   std::tie(PrevDiag, OldLocation) =
4056       getNoteDiagForInvalidRedeclaration(Old, New);
4057 
4058   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4059   if (New->getStorageClass() == SC_Static &&
4060       !New->isStaticDataMember() &&
4061       Old->hasExternalFormalLinkage()) {
4062     if (getLangOpts().MicrosoftExt) {
4063       Diag(New->getLocation(), diag::ext_static_non_static)
4064           << New->getDeclName();
4065       Diag(OldLocation, PrevDiag);
4066     } else {
4067       Diag(New->getLocation(), diag::err_static_non_static)
4068           << New->getDeclName();
4069       Diag(OldLocation, PrevDiag);
4070       return New->setInvalidDecl();
4071     }
4072   }
4073   // C99 6.2.2p4:
4074   //   For an identifier declared with the storage-class specifier
4075   //   extern in a scope in which a prior declaration of that
4076   //   identifier is visible,23) if the prior declaration specifies
4077   //   internal or external linkage, the linkage of the identifier at
4078   //   the later declaration is the same as the linkage specified at
4079   //   the prior declaration. If no prior declaration is visible, or
4080   //   if the prior declaration specifies no linkage, then the
4081   //   identifier has external linkage.
4082   if (New->hasExternalStorage() && Old->hasLinkage())
4083     /* Okay */;
4084   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4085            !New->isStaticDataMember() &&
4086            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4087     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4088     Diag(OldLocation, PrevDiag);
4089     return New->setInvalidDecl();
4090   }
4091 
4092   // Check if extern is followed by non-extern and vice-versa.
4093   if (New->hasExternalStorage() &&
4094       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4095     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4096     Diag(OldLocation, PrevDiag);
4097     return New->setInvalidDecl();
4098   }
4099   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4100       !New->hasExternalStorage()) {
4101     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4102     Diag(OldLocation, PrevDiag);
4103     return New->setInvalidDecl();
4104   }
4105 
4106   if (CheckRedeclarationModuleOwnership(New, Old))
4107     return;
4108 
4109   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4110 
4111   // FIXME: The test for external storage here seems wrong? We still
4112   // need to check for mismatches.
4113   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4114       // Don't complain about out-of-line definitions of static members.
4115       !(Old->getLexicalDeclContext()->isRecord() &&
4116         !New->getLexicalDeclContext()->isRecord())) {
4117     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4118     Diag(OldLocation, PrevDiag);
4119     return New->setInvalidDecl();
4120   }
4121 
4122   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4123     if (VarDecl *Def = Old->getDefinition()) {
4124       // C++1z [dcl.fcn.spec]p4:
4125       //   If the definition of a variable appears in a translation unit before
4126       //   its first declaration as inline, the program is ill-formed.
4127       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4128       Diag(Def->getLocation(), diag::note_previous_definition);
4129     }
4130   }
4131 
4132   // If this redeclaration makes the variable inline, we may need to add it to
4133   // UndefinedButUsed.
4134   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4135       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4136     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4137                                            SourceLocation()));
4138 
4139   if (New->getTLSKind() != Old->getTLSKind()) {
4140     if (!Old->getTLSKind()) {
4141       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4142       Diag(OldLocation, PrevDiag);
4143     } else if (!New->getTLSKind()) {
4144       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4145       Diag(OldLocation, PrevDiag);
4146     } else {
4147       // Do not allow redeclaration to change the variable between requiring
4148       // static and dynamic initialization.
4149       // FIXME: GCC allows this, but uses the TLS keyword on the first
4150       // declaration to determine the kind. Do we need to be compatible here?
4151       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4152         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4153       Diag(OldLocation, PrevDiag);
4154     }
4155   }
4156 
4157   // C++ doesn't have tentative definitions, so go right ahead and check here.
4158   if (getLangOpts().CPlusPlus &&
4159       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4160     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4161         Old->getCanonicalDecl()->isConstexpr()) {
4162       // This definition won't be a definition any more once it's been merged.
4163       Diag(New->getLocation(),
4164            diag::warn_deprecated_redundant_constexpr_static_def);
4165     } else if (VarDecl *Def = Old->getDefinition()) {
4166       if (checkVarDeclRedefinition(Def, New))
4167         return;
4168     }
4169   }
4170 
4171   if (haveIncompatibleLanguageLinkages(Old, New)) {
4172     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4173     Diag(OldLocation, PrevDiag);
4174     New->setInvalidDecl();
4175     return;
4176   }
4177 
4178   // Merge "used" flag.
4179   if (Old->getMostRecentDecl()->isUsed(false))
4180     New->setIsUsed();
4181 
4182   // Keep a chain of previous declarations.
4183   New->setPreviousDecl(Old);
4184   if (NewTemplate)
4185     NewTemplate->setPreviousDecl(OldTemplate);
4186   adjustDeclContextForDeclaratorDecl(New, Old);
4187 
4188   // Inherit access appropriately.
4189   New->setAccess(Old->getAccess());
4190   if (NewTemplate)
4191     NewTemplate->setAccess(New->getAccess());
4192 
4193   if (Old->isInline())
4194     New->setImplicitlyInline();
4195 }
4196 
4197 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4198   SourceManager &SrcMgr = getSourceManager();
4199   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4200   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4201   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4202   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4203   auto &HSI = PP.getHeaderSearchInfo();
4204   StringRef HdrFilename =
4205       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4206 
4207   auto noteFromModuleOrInclude = [&](Module *Mod,
4208                                      SourceLocation IncLoc) -> bool {
4209     // Redefinition errors with modules are common with non modular mapped
4210     // headers, example: a non-modular header H in module A that also gets
4211     // included directly in a TU. Pointing twice to the same header/definition
4212     // is confusing, try to get better diagnostics when modules is on.
4213     if (IncLoc.isValid()) {
4214       if (Mod) {
4215         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4216             << HdrFilename.str() << Mod->getFullModuleName();
4217         if (!Mod->DefinitionLoc.isInvalid())
4218           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4219               << Mod->getFullModuleName();
4220       } else {
4221         Diag(IncLoc, diag::note_redefinition_include_same_file)
4222             << HdrFilename.str();
4223       }
4224       return true;
4225     }
4226 
4227     return false;
4228   };
4229 
4230   // Is it the same file and same offset? Provide more information on why
4231   // this leads to a redefinition error.
4232   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4233     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4234     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4235     bool EmittedDiag =
4236         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4237     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4238 
4239     // If the header has no guards, emit a note suggesting one.
4240     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4241       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4242 
4243     if (EmittedDiag)
4244       return;
4245   }
4246 
4247   // Redefinition coming from different files or couldn't do better above.
4248   if (Old->getLocation().isValid())
4249     Diag(Old->getLocation(), diag::note_previous_definition);
4250 }
4251 
4252 /// We've just determined that \p Old and \p New both appear to be definitions
4253 /// of the same variable. Either diagnose or fix the problem.
4254 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4255   if (!hasVisibleDefinition(Old) &&
4256       (New->getFormalLinkage() == InternalLinkage ||
4257        New->isInline() ||
4258        New->getDescribedVarTemplate() ||
4259        New->getNumTemplateParameterLists() ||
4260        New->getDeclContext()->isDependentContext())) {
4261     // The previous definition is hidden, and multiple definitions are
4262     // permitted (in separate TUs). Demote this to a declaration.
4263     New->demoteThisDefinitionToDeclaration();
4264 
4265     // Make the canonical definition visible.
4266     if (auto *OldTD = Old->getDescribedVarTemplate())
4267       makeMergedDefinitionVisible(OldTD);
4268     makeMergedDefinitionVisible(Old);
4269     return false;
4270   } else {
4271     Diag(New->getLocation(), diag::err_redefinition) << New;
4272     notePreviousDefinition(Old, New->getLocation());
4273     New->setInvalidDecl();
4274     return true;
4275   }
4276 }
4277 
4278 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4279 /// no declarator (e.g. "struct foo;") is parsed.
4280 Decl *
4281 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4282                                  RecordDecl *&AnonRecord) {
4283   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4284                                     AnonRecord);
4285 }
4286 
4287 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4288 // disambiguate entities defined in different scopes.
4289 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4290 // compatibility.
4291 // We will pick our mangling number depending on which version of MSVC is being
4292 // targeted.
4293 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4294   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4295              ? S->getMSCurManglingNumber()
4296              : S->getMSLastManglingNumber();
4297 }
4298 
4299 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4300   if (!Context.getLangOpts().CPlusPlus)
4301     return;
4302 
4303   if (isa<CXXRecordDecl>(Tag->getParent())) {
4304     // If this tag is the direct child of a class, number it if
4305     // it is anonymous.
4306     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4307       return;
4308     MangleNumberingContext &MCtx =
4309         Context.getManglingNumberContext(Tag->getParent());
4310     Context.setManglingNumber(
4311         Tag, MCtx.getManglingNumber(
4312                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4313     return;
4314   }
4315 
4316   // If this tag isn't a direct child of a class, number it if it is local.
4317   MangleNumberingContext *MCtx;
4318   Decl *ManglingContextDecl;
4319   std::tie(MCtx, ManglingContextDecl) =
4320       getCurrentMangleNumberContext(Tag->getDeclContext());
4321   if (MCtx) {
4322     Context.setManglingNumber(
4323         Tag, MCtx->getManglingNumber(
4324                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4325   }
4326 }
4327 
4328 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4329                                         TypedefNameDecl *NewTD) {
4330   if (TagFromDeclSpec->isInvalidDecl())
4331     return;
4332 
4333   // Do nothing if the tag already has a name for linkage purposes.
4334   if (TagFromDeclSpec->hasNameForLinkage())
4335     return;
4336 
4337   // A well-formed anonymous tag must always be a TUK_Definition.
4338   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4339 
4340   // The type must match the tag exactly;  no qualifiers allowed.
4341   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4342                            Context.getTagDeclType(TagFromDeclSpec))) {
4343     if (getLangOpts().CPlusPlus)
4344       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4345     return;
4346   }
4347 
4348   // If we've already computed linkage for the anonymous tag, then
4349   // adding a typedef name for the anonymous decl can change that
4350   // linkage, which might be a serious problem.  Diagnose this as
4351   // unsupported and ignore the typedef name.  TODO: we should
4352   // pursue this as a language defect and establish a formal rule
4353   // for how to handle it.
4354   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4355     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4356 
4357     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4358     tagLoc = getLocForEndOfToken(tagLoc);
4359 
4360     llvm::SmallString<40> textToInsert;
4361     textToInsert += ' ';
4362     textToInsert += NewTD->getIdentifier()->getName();
4363     Diag(tagLoc, diag::note_typedef_changes_linkage)
4364         << FixItHint::CreateInsertion(tagLoc, textToInsert);
4365     return;
4366   }
4367 
4368   // Otherwise, set this is the anon-decl typedef for the tag.
4369   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4370 }
4371 
4372 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4373   switch (T) {
4374   case DeclSpec::TST_class:
4375     return 0;
4376   case DeclSpec::TST_struct:
4377     return 1;
4378   case DeclSpec::TST_interface:
4379     return 2;
4380   case DeclSpec::TST_union:
4381     return 3;
4382   case DeclSpec::TST_enum:
4383     return 4;
4384   default:
4385     llvm_unreachable("unexpected type specifier");
4386   }
4387 }
4388 
4389 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4390 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4391 /// parameters to cope with template friend declarations.
4392 Decl *
4393 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4394                                  MultiTemplateParamsArg TemplateParams,
4395                                  bool IsExplicitInstantiation,
4396                                  RecordDecl *&AnonRecord) {
4397   Decl *TagD = nullptr;
4398   TagDecl *Tag = nullptr;
4399   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4400       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4401       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4402       DS.getTypeSpecType() == DeclSpec::TST_union ||
4403       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4404     TagD = DS.getRepAsDecl();
4405 
4406     if (!TagD) // We probably had an error
4407       return nullptr;
4408 
4409     // Note that the above type specs guarantee that the
4410     // type rep is a Decl, whereas in many of the others
4411     // it's a Type.
4412     if (isa<TagDecl>(TagD))
4413       Tag = cast<TagDecl>(TagD);
4414     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4415       Tag = CTD->getTemplatedDecl();
4416   }
4417 
4418   if (Tag) {
4419     handleTagNumbering(Tag, S);
4420     Tag->setFreeStanding();
4421     if (Tag->isInvalidDecl())
4422       return Tag;
4423   }
4424 
4425   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4426     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4427     // or incomplete types shall not be restrict-qualified."
4428     if (TypeQuals & DeclSpec::TQ_restrict)
4429       Diag(DS.getRestrictSpecLoc(),
4430            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4431            << DS.getSourceRange();
4432   }
4433 
4434   if (DS.isInlineSpecified())
4435     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4436         << getLangOpts().CPlusPlus17;
4437 
4438   if (DS.hasConstexprSpecifier()) {
4439     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4440     // and definitions of functions and variables.
4441     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4442     // the declaration of a function or function template
4443     if (Tag)
4444       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4445           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4446           << DS.getConstexprSpecifier();
4447     else
4448       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4449           << DS.getConstexprSpecifier();
4450     // Don't emit warnings after this error.
4451     return TagD;
4452   }
4453 
4454   DiagnoseFunctionSpecifiers(DS);
4455 
4456   if (DS.isFriendSpecified()) {
4457     // If we're dealing with a decl but not a TagDecl, assume that
4458     // whatever routines created it handled the friendship aspect.
4459     if (TagD && !Tag)
4460       return nullptr;
4461     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4462   }
4463 
4464   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4465   bool IsExplicitSpecialization =
4466     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4467   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4468       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4469       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4470     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4471     // nested-name-specifier unless it is an explicit instantiation
4472     // or an explicit specialization.
4473     //
4474     // FIXME: We allow class template partial specializations here too, per the
4475     // obvious intent of DR1819.
4476     //
4477     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4478     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4479         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4480     return nullptr;
4481   }
4482 
4483   // Track whether this decl-specifier declares anything.
4484   bool DeclaresAnything = true;
4485 
4486   // Handle anonymous struct definitions.
4487   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4488     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4489         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4490       if (getLangOpts().CPlusPlus ||
4491           Record->getDeclContext()->isRecord()) {
4492         // If CurContext is a DeclContext that can contain statements,
4493         // RecursiveASTVisitor won't visit the decls that
4494         // BuildAnonymousStructOrUnion() will put into CurContext.
4495         // Also store them here so that they can be part of the
4496         // DeclStmt that gets created in this case.
4497         // FIXME: Also return the IndirectFieldDecls created by
4498         // BuildAnonymousStructOr union, for the same reason?
4499         if (CurContext->isFunctionOrMethod())
4500           AnonRecord = Record;
4501         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4502                                            Context.getPrintingPolicy());
4503       }
4504 
4505       DeclaresAnything = false;
4506     }
4507   }
4508 
4509   // C11 6.7.2.1p2:
4510   //   A struct-declaration that does not declare an anonymous structure or
4511   //   anonymous union shall contain a struct-declarator-list.
4512   //
4513   // This rule also existed in C89 and C99; the grammar for struct-declaration
4514   // did not permit a struct-declaration without a struct-declarator-list.
4515   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4516       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4517     // Check for Microsoft C extension: anonymous struct/union member.
4518     // Handle 2 kinds of anonymous struct/union:
4519     //   struct STRUCT;
4520     //   union UNION;
4521     // and
4522     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4523     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4524     if ((Tag && Tag->getDeclName()) ||
4525         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4526       RecordDecl *Record = nullptr;
4527       if (Tag)
4528         Record = dyn_cast<RecordDecl>(Tag);
4529       else if (const RecordType *RT =
4530                    DS.getRepAsType().get()->getAsStructureType())
4531         Record = RT->getDecl();
4532       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4533         Record = UT->getDecl();
4534 
4535       if (Record && getLangOpts().MicrosoftExt) {
4536         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4537             << Record->isUnion() << DS.getSourceRange();
4538         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4539       }
4540 
4541       DeclaresAnything = false;
4542     }
4543   }
4544 
4545   // Skip all the checks below if we have a type error.
4546   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4547       (TagD && TagD->isInvalidDecl()))
4548     return TagD;
4549 
4550   if (getLangOpts().CPlusPlus &&
4551       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4552     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4553       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4554           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4555         DeclaresAnything = false;
4556 
4557   if (!DS.isMissingDeclaratorOk()) {
4558     // Customize diagnostic for a typedef missing a name.
4559     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4560       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4561           << DS.getSourceRange();
4562     else
4563       DeclaresAnything = false;
4564   }
4565 
4566   if (DS.isModulePrivateSpecified() &&
4567       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4568     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4569       << Tag->getTagKind()
4570       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4571 
4572   ActOnDocumentableDecl(TagD);
4573 
4574   // C 6.7/2:
4575   //   A declaration [...] shall declare at least a declarator [...], a tag,
4576   //   or the members of an enumeration.
4577   // C++ [dcl.dcl]p3:
4578   //   [If there are no declarators], and except for the declaration of an
4579   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4580   //   names into the program, or shall redeclare a name introduced by a
4581   //   previous declaration.
4582   if (!DeclaresAnything) {
4583     // In C, we allow this as a (popular) extension / bug. Don't bother
4584     // producing further diagnostics for redundant qualifiers after this.
4585     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4586     return TagD;
4587   }
4588 
4589   // C++ [dcl.stc]p1:
4590   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4591   //   init-declarator-list of the declaration shall not be empty.
4592   // C++ [dcl.fct.spec]p1:
4593   //   If a cv-qualifier appears in a decl-specifier-seq, the
4594   //   init-declarator-list of the declaration shall not be empty.
4595   //
4596   // Spurious qualifiers here appear to be valid in C.
4597   unsigned DiagID = diag::warn_standalone_specifier;
4598   if (getLangOpts().CPlusPlus)
4599     DiagID = diag::ext_standalone_specifier;
4600 
4601   // Note that a linkage-specification sets a storage class, but
4602   // 'extern "C" struct foo;' is actually valid and not theoretically
4603   // useless.
4604   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4605     if (SCS == DeclSpec::SCS_mutable)
4606       // Since mutable is not a viable storage class specifier in C, there is
4607       // no reason to treat it as an extension. Instead, diagnose as an error.
4608       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4609     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4610       Diag(DS.getStorageClassSpecLoc(), DiagID)
4611         << DeclSpec::getSpecifierName(SCS);
4612   }
4613 
4614   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4615     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4616       << DeclSpec::getSpecifierName(TSCS);
4617   if (DS.getTypeQualifiers()) {
4618     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4619       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4620     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4621       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4622     // Restrict is covered above.
4623     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4624       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4625     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4626       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4627   }
4628 
4629   // Warn about ignored type attributes, for example:
4630   // __attribute__((aligned)) struct A;
4631   // Attributes should be placed after tag to apply to type declaration.
4632   if (!DS.getAttributes().empty()) {
4633     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4634     if (TypeSpecType == DeclSpec::TST_class ||
4635         TypeSpecType == DeclSpec::TST_struct ||
4636         TypeSpecType == DeclSpec::TST_interface ||
4637         TypeSpecType == DeclSpec::TST_union ||
4638         TypeSpecType == DeclSpec::TST_enum) {
4639       for (const ParsedAttr &AL : DS.getAttributes())
4640         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4641             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4642     }
4643   }
4644 
4645   return TagD;
4646 }
4647 
4648 /// We are trying to inject an anonymous member into the given scope;
4649 /// check if there's an existing declaration that can't be overloaded.
4650 ///
4651 /// \return true if this is a forbidden redeclaration
4652 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4653                                          Scope *S,
4654                                          DeclContext *Owner,
4655                                          DeclarationName Name,
4656                                          SourceLocation NameLoc,
4657                                          bool IsUnion) {
4658   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4659                  Sema::ForVisibleRedeclaration);
4660   if (!SemaRef.LookupName(R, S)) return false;
4661 
4662   // Pick a representative declaration.
4663   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4664   assert(PrevDecl && "Expected a non-null Decl");
4665 
4666   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4667     return false;
4668 
4669   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4670     << IsUnion << Name;
4671   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4672 
4673   return true;
4674 }
4675 
4676 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4677 /// anonymous struct or union AnonRecord into the owning context Owner
4678 /// and scope S. This routine will be invoked just after we realize
4679 /// that an unnamed union or struct is actually an anonymous union or
4680 /// struct, e.g.,
4681 ///
4682 /// @code
4683 /// union {
4684 ///   int i;
4685 ///   float f;
4686 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4687 ///    // f into the surrounding scope.x
4688 /// @endcode
4689 ///
4690 /// This routine is recursive, injecting the names of nested anonymous
4691 /// structs/unions into the owning context and scope as well.
4692 static bool
4693 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4694                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4695                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4696   bool Invalid = false;
4697 
4698   // Look every FieldDecl and IndirectFieldDecl with a name.
4699   for (auto *D : AnonRecord->decls()) {
4700     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4701         cast<NamedDecl>(D)->getDeclName()) {
4702       ValueDecl *VD = cast<ValueDecl>(D);
4703       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4704                                        VD->getLocation(),
4705                                        AnonRecord->isUnion())) {
4706         // C++ [class.union]p2:
4707         //   The names of the members of an anonymous union shall be
4708         //   distinct from the names of any other entity in the
4709         //   scope in which the anonymous union is declared.
4710         Invalid = true;
4711       } else {
4712         // C++ [class.union]p2:
4713         //   For the purpose of name lookup, after the anonymous union
4714         //   definition, the members of the anonymous union are
4715         //   considered to have been defined in the scope in which the
4716         //   anonymous union is declared.
4717         unsigned OldChainingSize = Chaining.size();
4718         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4719           Chaining.append(IF->chain_begin(), IF->chain_end());
4720         else
4721           Chaining.push_back(VD);
4722 
4723         assert(Chaining.size() >= 2);
4724         NamedDecl **NamedChain =
4725           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4726         for (unsigned i = 0; i < Chaining.size(); i++)
4727           NamedChain[i] = Chaining[i];
4728 
4729         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4730             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4731             VD->getType(), {NamedChain, Chaining.size()});
4732 
4733         for (const auto *Attr : VD->attrs())
4734           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4735 
4736         IndirectField->setAccess(AS);
4737         IndirectField->setImplicit();
4738         SemaRef.PushOnScopeChains(IndirectField, S);
4739 
4740         // That includes picking up the appropriate access specifier.
4741         if (AS != AS_none) IndirectField->setAccess(AS);
4742 
4743         Chaining.resize(OldChainingSize);
4744       }
4745     }
4746   }
4747 
4748   return Invalid;
4749 }
4750 
4751 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4752 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4753 /// illegal input values are mapped to SC_None.
4754 static StorageClass
4755 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4756   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4757   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4758          "Parser allowed 'typedef' as storage class VarDecl.");
4759   switch (StorageClassSpec) {
4760   case DeclSpec::SCS_unspecified:    return SC_None;
4761   case DeclSpec::SCS_extern:
4762     if (DS.isExternInLinkageSpec())
4763       return SC_None;
4764     return SC_Extern;
4765   case DeclSpec::SCS_static:         return SC_Static;
4766   case DeclSpec::SCS_auto:           return SC_Auto;
4767   case DeclSpec::SCS_register:       return SC_Register;
4768   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4769     // Illegal SCSs map to None: error reporting is up to the caller.
4770   case DeclSpec::SCS_mutable:        // Fall through.
4771   case DeclSpec::SCS_typedef:        return SC_None;
4772   }
4773   llvm_unreachable("unknown storage class specifier");
4774 }
4775 
4776 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4777   assert(Record->hasInClassInitializer());
4778 
4779   for (const auto *I : Record->decls()) {
4780     const auto *FD = dyn_cast<FieldDecl>(I);
4781     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4782       FD = IFD->getAnonField();
4783     if (FD && FD->hasInClassInitializer())
4784       return FD->getLocation();
4785   }
4786 
4787   llvm_unreachable("couldn't find in-class initializer");
4788 }
4789 
4790 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4791                                       SourceLocation DefaultInitLoc) {
4792   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4793     return;
4794 
4795   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4796   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4797 }
4798 
4799 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4800                                       CXXRecordDecl *AnonUnion) {
4801   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4802     return;
4803 
4804   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4805 }
4806 
4807 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4808 /// anonymous structure or union. Anonymous unions are a C++ feature
4809 /// (C++ [class.union]) and a C11 feature; anonymous structures
4810 /// are a C11 feature and GNU C++ extension.
4811 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4812                                         AccessSpecifier AS,
4813                                         RecordDecl *Record,
4814                                         const PrintingPolicy &Policy) {
4815   DeclContext *Owner = Record->getDeclContext();
4816 
4817   // Diagnose whether this anonymous struct/union is an extension.
4818   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4819     Diag(Record->getLocation(), diag::ext_anonymous_union);
4820   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4821     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4822   else if (!Record->isUnion() && !getLangOpts().C11)
4823     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4824 
4825   // C and C++ require different kinds of checks for anonymous
4826   // structs/unions.
4827   bool Invalid = false;
4828   if (getLangOpts().CPlusPlus) {
4829     const char *PrevSpec = nullptr;
4830     if (Record->isUnion()) {
4831       // C++ [class.union]p6:
4832       // C++17 [class.union.anon]p2:
4833       //   Anonymous unions declared in a named namespace or in the
4834       //   global namespace shall be declared static.
4835       unsigned DiagID;
4836       DeclContext *OwnerScope = Owner->getRedeclContext();
4837       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4838           (OwnerScope->isTranslationUnit() ||
4839            (OwnerScope->isNamespace() &&
4840             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
4841         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4842           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4843 
4844         // Recover by adding 'static'.
4845         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4846                                PrevSpec, DiagID, Policy);
4847       }
4848       // C++ [class.union]p6:
4849       //   A storage class is not allowed in a declaration of an
4850       //   anonymous union in a class scope.
4851       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4852                isa<RecordDecl>(Owner)) {
4853         Diag(DS.getStorageClassSpecLoc(),
4854              diag::err_anonymous_union_with_storage_spec)
4855           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4856 
4857         // Recover by removing the storage specifier.
4858         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4859                                SourceLocation(),
4860                                PrevSpec, DiagID, Context.getPrintingPolicy());
4861       }
4862     }
4863 
4864     // Ignore const/volatile/restrict qualifiers.
4865     if (DS.getTypeQualifiers()) {
4866       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4867         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4868           << Record->isUnion() << "const"
4869           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4870       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4871         Diag(DS.getVolatileSpecLoc(),
4872              diag::ext_anonymous_struct_union_qualified)
4873           << Record->isUnion() << "volatile"
4874           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4875       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4876         Diag(DS.getRestrictSpecLoc(),
4877              diag::ext_anonymous_struct_union_qualified)
4878           << Record->isUnion() << "restrict"
4879           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4880       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4881         Diag(DS.getAtomicSpecLoc(),
4882              diag::ext_anonymous_struct_union_qualified)
4883           << Record->isUnion() << "_Atomic"
4884           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4885       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4886         Diag(DS.getUnalignedSpecLoc(),
4887              diag::ext_anonymous_struct_union_qualified)
4888           << Record->isUnion() << "__unaligned"
4889           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4890 
4891       DS.ClearTypeQualifiers();
4892     }
4893 
4894     // C++ [class.union]p2:
4895     //   The member-specification of an anonymous union shall only
4896     //   define non-static data members. [Note: nested types and
4897     //   functions cannot be declared within an anonymous union. ]
4898     for (auto *Mem : Record->decls()) {
4899       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4900         // C++ [class.union]p3:
4901         //   An anonymous union shall not have private or protected
4902         //   members (clause 11).
4903         assert(FD->getAccess() != AS_none);
4904         if (FD->getAccess() != AS_public) {
4905           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4906             << Record->isUnion() << (FD->getAccess() == AS_protected);
4907           Invalid = true;
4908         }
4909 
4910         // C++ [class.union]p1
4911         //   An object of a class with a non-trivial constructor, a non-trivial
4912         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4913         //   assignment operator cannot be a member of a union, nor can an
4914         //   array of such objects.
4915         if (CheckNontrivialField(FD))
4916           Invalid = true;
4917       } else if (Mem->isImplicit()) {
4918         // Any implicit members are fine.
4919       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4920         // This is a type that showed up in an
4921         // elaborated-type-specifier inside the anonymous struct or
4922         // union, but which actually declares a type outside of the
4923         // anonymous struct or union. It's okay.
4924       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4925         if (!MemRecord->isAnonymousStructOrUnion() &&
4926             MemRecord->getDeclName()) {
4927           // Visual C++ allows type definition in anonymous struct or union.
4928           if (getLangOpts().MicrosoftExt)
4929             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4930               << Record->isUnion();
4931           else {
4932             // This is a nested type declaration.
4933             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4934               << Record->isUnion();
4935             Invalid = true;
4936           }
4937         } else {
4938           // This is an anonymous type definition within another anonymous type.
4939           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4940           // not part of standard C++.
4941           Diag(MemRecord->getLocation(),
4942                diag::ext_anonymous_record_with_anonymous_type)
4943             << Record->isUnion();
4944         }
4945       } else if (isa<AccessSpecDecl>(Mem)) {
4946         // Any access specifier is fine.
4947       } else if (isa<StaticAssertDecl>(Mem)) {
4948         // In C++1z, static_assert declarations are also fine.
4949       } else {
4950         // We have something that isn't a non-static data
4951         // member. Complain about it.
4952         unsigned DK = diag::err_anonymous_record_bad_member;
4953         if (isa<TypeDecl>(Mem))
4954           DK = diag::err_anonymous_record_with_type;
4955         else if (isa<FunctionDecl>(Mem))
4956           DK = diag::err_anonymous_record_with_function;
4957         else if (isa<VarDecl>(Mem))
4958           DK = diag::err_anonymous_record_with_static;
4959 
4960         // Visual C++ allows type definition in anonymous struct or union.
4961         if (getLangOpts().MicrosoftExt &&
4962             DK == diag::err_anonymous_record_with_type)
4963           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4964             << Record->isUnion();
4965         else {
4966           Diag(Mem->getLocation(), DK) << Record->isUnion();
4967           Invalid = true;
4968         }
4969       }
4970     }
4971 
4972     // C++11 [class.union]p8 (DR1460):
4973     //   At most one variant member of a union may have a
4974     //   brace-or-equal-initializer.
4975     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4976         Owner->isRecord())
4977       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4978                                 cast<CXXRecordDecl>(Record));
4979   }
4980 
4981   if (!Record->isUnion() && !Owner->isRecord()) {
4982     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4983       << getLangOpts().CPlusPlus;
4984     Invalid = true;
4985   }
4986 
4987   // C++ [dcl.dcl]p3:
4988   //   [If there are no declarators], and except for the declaration of an
4989   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4990   //   names into the program
4991   // C++ [class.mem]p2:
4992   //   each such member-declaration shall either declare at least one member
4993   //   name of the class or declare at least one unnamed bit-field
4994   //
4995   // For C this is an error even for a named struct, and is diagnosed elsewhere.
4996   if (getLangOpts().CPlusPlus && Record->field_empty())
4997     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4998 
4999   // Mock up a declarator.
5000   Declarator Dc(DS, DeclaratorContext::MemberContext);
5001   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5002   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5003 
5004   // Create a declaration for this anonymous struct/union.
5005   NamedDecl *Anon = nullptr;
5006   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5007     Anon = FieldDecl::Create(
5008         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5009         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5010         /*BitWidth=*/nullptr, /*Mutable=*/false,
5011         /*InitStyle=*/ICIS_NoInit);
5012     Anon->setAccess(AS);
5013     if (getLangOpts().CPlusPlus)
5014       FieldCollector->Add(cast<FieldDecl>(Anon));
5015   } else {
5016     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5017     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5018     if (SCSpec == DeclSpec::SCS_mutable) {
5019       // mutable can only appear on non-static class members, so it's always
5020       // an error here
5021       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5022       Invalid = true;
5023       SC = SC_None;
5024     }
5025 
5026     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5027                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5028                            Context.getTypeDeclType(Record), TInfo, SC);
5029 
5030     // Default-initialize the implicit variable. This initialization will be
5031     // trivial in almost all cases, except if a union member has an in-class
5032     // initializer:
5033     //   union { int n = 0; };
5034     ActOnUninitializedDecl(Anon);
5035   }
5036   Anon->setImplicit();
5037 
5038   // Mark this as an anonymous struct/union type.
5039   Record->setAnonymousStructOrUnion(true);
5040 
5041   // Add the anonymous struct/union object to the current
5042   // context. We'll be referencing this object when we refer to one of
5043   // its members.
5044   Owner->addDecl(Anon);
5045 
5046   // Inject the members of the anonymous struct/union into the owning
5047   // context and into the identifier resolver chain for name lookup
5048   // purposes.
5049   SmallVector<NamedDecl*, 2> Chain;
5050   Chain.push_back(Anon);
5051 
5052   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5053     Invalid = true;
5054 
5055   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5056     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5057       MangleNumberingContext *MCtx;
5058       Decl *ManglingContextDecl;
5059       std::tie(MCtx, ManglingContextDecl) =
5060           getCurrentMangleNumberContext(NewVD->getDeclContext());
5061       if (MCtx) {
5062         Context.setManglingNumber(
5063             NewVD, MCtx->getManglingNumber(
5064                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5065         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5066       }
5067     }
5068   }
5069 
5070   if (Invalid)
5071     Anon->setInvalidDecl();
5072 
5073   return Anon;
5074 }
5075 
5076 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5077 /// Microsoft C anonymous structure.
5078 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5079 /// Example:
5080 ///
5081 /// struct A { int a; };
5082 /// struct B { struct A; int b; };
5083 ///
5084 /// void foo() {
5085 ///   B var;
5086 ///   var.a = 3;
5087 /// }
5088 ///
5089 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5090                                            RecordDecl *Record) {
5091   assert(Record && "expected a record!");
5092 
5093   // Mock up a declarator.
5094   Declarator Dc(DS, DeclaratorContext::TypeNameContext);
5095   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5096   assert(TInfo && "couldn't build declarator info for anonymous struct");
5097 
5098   auto *ParentDecl = cast<RecordDecl>(CurContext);
5099   QualType RecTy = Context.getTypeDeclType(Record);
5100 
5101   // Create a declaration for this anonymous struct.
5102   NamedDecl *Anon =
5103       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5104                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5105                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5106                         /*InitStyle=*/ICIS_NoInit);
5107   Anon->setImplicit();
5108 
5109   // Add the anonymous struct object to the current context.
5110   CurContext->addDecl(Anon);
5111 
5112   // Inject the members of the anonymous struct into the current
5113   // context and into the identifier resolver chain for name lookup
5114   // purposes.
5115   SmallVector<NamedDecl*, 2> Chain;
5116   Chain.push_back(Anon);
5117 
5118   RecordDecl *RecordDef = Record->getDefinition();
5119   if (RequireCompleteType(Anon->getLocation(), RecTy,
5120                           diag::err_field_incomplete) ||
5121       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5122                                           AS_none, Chain)) {
5123     Anon->setInvalidDecl();
5124     ParentDecl->setInvalidDecl();
5125   }
5126 
5127   return Anon;
5128 }
5129 
5130 /// GetNameForDeclarator - Determine the full declaration name for the
5131 /// given Declarator.
5132 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5133   return GetNameFromUnqualifiedId(D.getName());
5134 }
5135 
5136 /// Retrieves the declaration name from a parsed unqualified-id.
5137 DeclarationNameInfo
5138 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5139   DeclarationNameInfo NameInfo;
5140   NameInfo.setLoc(Name.StartLocation);
5141 
5142   switch (Name.getKind()) {
5143 
5144   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5145   case UnqualifiedIdKind::IK_Identifier:
5146     NameInfo.setName(Name.Identifier);
5147     return NameInfo;
5148 
5149   case UnqualifiedIdKind::IK_DeductionGuideName: {
5150     // C++ [temp.deduct.guide]p3:
5151     //   The simple-template-id shall name a class template specialization.
5152     //   The template-name shall be the same identifier as the template-name
5153     //   of the simple-template-id.
5154     // These together intend to imply that the template-name shall name a
5155     // class template.
5156     // FIXME: template<typename T> struct X {};
5157     //        template<typename T> using Y = X<T>;
5158     //        Y(int) -> Y<int>;
5159     //   satisfies these rules but does not name a class template.
5160     TemplateName TN = Name.TemplateName.get().get();
5161     auto *Template = TN.getAsTemplateDecl();
5162     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5163       Diag(Name.StartLocation,
5164            diag::err_deduction_guide_name_not_class_template)
5165         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5166       if (Template)
5167         Diag(Template->getLocation(), diag::note_template_decl_here);
5168       return DeclarationNameInfo();
5169     }
5170 
5171     NameInfo.setName(
5172         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5173     return NameInfo;
5174   }
5175 
5176   case UnqualifiedIdKind::IK_OperatorFunctionId:
5177     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5178                                            Name.OperatorFunctionId.Operator));
5179     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
5180       = Name.OperatorFunctionId.SymbolLocations[0];
5181     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
5182       = Name.EndLocation.getRawEncoding();
5183     return NameInfo;
5184 
5185   case UnqualifiedIdKind::IK_LiteralOperatorId:
5186     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5187                                                            Name.Identifier));
5188     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5189     return NameInfo;
5190 
5191   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5192     TypeSourceInfo *TInfo;
5193     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5194     if (Ty.isNull())
5195       return DeclarationNameInfo();
5196     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5197                                                Context.getCanonicalType(Ty)));
5198     NameInfo.setNamedTypeInfo(TInfo);
5199     return NameInfo;
5200   }
5201 
5202   case UnqualifiedIdKind::IK_ConstructorName: {
5203     TypeSourceInfo *TInfo;
5204     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5205     if (Ty.isNull())
5206       return DeclarationNameInfo();
5207     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5208                                               Context.getCanonicalType(Ty)));
5209     NameInfo.setNamedTypeInfo(TInfo);
5210     return NameInfo;
5211   }
5212 
5213   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5214     // In well-formed code, we can only have a constructor
5215     // template-id that refers to the current context, so go there
5216     // to find the actual type being constructed.
5217     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5218     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5219       return DeclarationNameInfo();
5220 
5221     // Determine the type of the class being constructed.
5222     QualType CurClassType = Context.getTypeDeclType(CurClass);
5223 
5224     // FIXME: Check two things: that the template-id names the same type as
5225     // CurClassType, and that the template-id does not occur when the name
5226     // was qualified.
5227 
5228     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5229                                     Context.getCanonicalType(CurClassType)));
5230     // FIXME: should we retrieve TypeSourceInfo?
5231     NameInfo.setNamedTypeInfo(nullptr);
5232     return NameInfo;
5233   }
5234 
5235   case UnqualifiedIdKind::IK_DestructorName: {
5236     TypeSourceInfo *TInfo;
5237     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5238     if (Ty.isNull())
5239       return DeclarationNameInfo();
5240     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5241                                               Context.getCanonicalType(Ty)));
5242     NameInfo.setNamedTypeInfo(TInfo);
5243     return NameInfo;
5244   }
5245 
5246   case UnqualifiedIdKind::IK_TemplateId: {
5247     TemplateName TName = Name.TemplateId->Template.get();
5248     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5249     return Context.getNameForTemplate(TName, TNameLoc);
5250   }
5251 
5252   } // switch (Name.getKind())
5253 
5254   llvm_unreachable("Unknown name kind");
5255 }
5256 
5257 static QualType getCoreType(QualType Ty) {
5258   do {
5259     if (Ty->isPointerType() || Ty->isReferenceType())
5260       Ty = Ty->getPointeeType();
5261     else if (Ty->isArrayType())
5262       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5263     else
5264       return Ty.withoutLocalFastQualifiers();
5265   } while (true);
5266 }
5267 
5268 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5269 /// and Definition have "nearly" matching parameters. This heuristic is
5270 /// used to improve diagnostics in the case where an out-of-line function
5271 /// definition doesn't match any declaration within the class or namespace.
5272 /// Also sets Params to the list of indices to the parameters that differ
5273 /// between the declaration and the definition. If hasSimilarParameters
5274 /// returns true and Params is empty, then all of the parameters match.
5275 static bool hasSimilarParameters(ASTContext &Context,
5276                                      FunctionDecl *Declaration,
5277                                      FunctionDecl *Definition,
5278                                      SmallVectorImpl<unsigned> &Params) {
5279   Params.clear();
5280   if (Declaration->param_size() != Definition->param_size())
5281     return false;
5282   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5283     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5284     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5285 
5286     // The parameter types are identical
5287     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5288       continue;
5289 
5290     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5291     QualType DefParamBaseTy = getCoreType(DefParamTy);
5292     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5293     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5294 
5295     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5296         (DeclTyName && DeclTyName == DefTyName))
5297       Params.push_back(Idx);
5298     else  // The two parameters aren't even close
5299       return false;
5300   }
5301 
5302   return true;
5303 }
5304 
5305 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5306 /// declarator needs to be rebuilt in the current instantiation.
5307 /// Any bits of declarator which appear before the name are valid for
5308 /// consideration here.  That's specifically the type in the decl spec
5309 /// and the base type in any member-pointer chunks.
5310 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5311                                                     DeclarationName Name) {
5312   // The types we specifically need to rebuild are:
5313   //   - typenames, typeofs, and decltypes
5314   //   - types which will become injected class names
5315   // Of course, we also need to rebuild any type referencing such a
5316   // type.  It's safest to just say "dependent", but we call out a
5317   // few cases here.
5318 
5319   DeclSpec &DS = D.getMutableDeclSpec();
5320   switch (DS.getTypeSpecType()) {
5321   case DeclSpec::TST_typename:
5322   case DeclSpec::TST_typeofType:
5323   case DeclSpec::TST_underlyingType:
5324   case DeclSpec::TST_atomic: {
5325     // Grab the type from the parser.
5326     TypeSourceInfo *TSI = nullptr;
5327     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5328     if (T.isNull() || !T->isDependentType()) break;
5329 
5330     // Make sure there's a type source info.  This isn't really much
5331     // of a waste; most dependent types should have type source info
5332     // attached already.
5333     if (!TSI)
5334       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5335 
5336     // Rebuild the type in the current instantiation.
5337     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5338     if (!TSI) return true;
5339 
5340     // Store the new type back in the decl spec.
5341     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5342     DS.UpdateTypeRep(LocType);
5343     break;
5344   }
5345 
5346   case DeclSpec::TST_decltype:
5347   case DeclSpec::TST_typeofExpr: {
5348     Expr *E = DS.getRepAsExpr();
5349     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5350     if (Result.isInvalid()) return true;
5351     DS.UpdateExprRep(Result.get());
5352     break;
5353   }
5354 
5355   default:
5356     // Nothing to do for these decl specs.
5357     break;
5358   }
5359 
5360   // It doesn't matter what order we do this in.
5361   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5362     DeclaratorChunk &Chunk = D.getTypeObject(I);
5363 
5364     // The only type information in the declarator which can come
5365     // before the declaration name is the base type of a member
5366     // pointer.
5367     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5368       continue;
5369 
5370     // Rebuild the scope specifier in-place.
5371     CXXScopeSpec &SS = Chunk.Mem.Scope();
5372     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5373       return true;
5374   }
5375 
5376   return false;
5377 }
5378 
5379 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5380   D.setFunctionDefinitionKind(FDK_Declaration);
5381   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5382 
5383   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5384       Dcl && Dcl->getDeclContext()->isFileContext())
5385     Dcl->setTopLevelDeclInObjCContainer();
5386 
5387   if (getLangOpts().OpenCL)
5388     setCurrentOpenCLExtensionForDecl(Dcl);
5389 
5390   return Dcl;
5391 }
5392 
5393 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5394 ///   If T is the name of a class, then each of the following shall have a
5395 ///   name different from T:
5396 ///     - every static data member of class T;
5397 ///     - every member function of class T
5398 ///     - every member of class T that is itself a type;
5399 /// \returns true if the declaration name violates these rules.
5400 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5401                                    DeclarationNameInfo NameInfo) {
5402   DeclarationName Name = NameInfo.getName();
5403 
5404   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5405   while (Record && Record->isAnonymousStructOrUnion())
5406     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5407   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5408     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5409     return true;
5410   }
5411 
5412   return false;
5413 }
5414 
5415 /// Diagnose a declaration whose declarator-id has the given
5416 /// nested-name-specifier.
5417 ///
5418 /// \param SS The nested-name-specifier of the declarator-id.
5419 ///
5420 /// \param DC The declaration context to which the nested-name-specifier
5421 /// resolves.
5422 ///
5423 /// \param Name The name of the entity being declared.
5424 ///
5425 /// \param Loc The location of the name of the entity being declared.
5426 ///
5427 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5428 /// we're declaring an explicit / partial specialization / instantiation.
5429 ///
5430 /// \returns true if we cannot safely recover from this error, false otherwise.
5431 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5432                                         DeclarationName Name,
5433                                         SourceLocation Loc, bool IsTemplateId) {
5434   DeclContext *Cur = CurContext;
5435   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5436     Cur = Cur->getParent();
5437 
5438   // If the user provided a superfluous scope specifier that refers back to the
5439   // class in which the entity is already declared, diagnose and ignore it.
5440   //
5441   // class X {
5442   //   void X::f();
5443   // };
5444   //
5445   // Note, it was once ill-formed to give redundant qualification in all
5446   // contexts, but that rule was removed by DR482.
5447   if (Cur->Equals(DC)) {
5448     if (Cur->isRecord()) {
5449       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5450                                       : diag::err_member_extra_qualification)
5451         << Name << FixItHint::CreateRemoval(SS.getRange());
5452       SS.clear();
5453     } else {
5454       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5455     }
5456     return false;
5457   }
5458 
5459   // Check whether the qualifying scope encloses the scope of the original
5460   // declaration. For a template-id, we perform the checks in
5461   // CheckTemplateSpecializationScope.
5462   if (!Cur->Encloses(DC) && !IsTemplateId) {
5463     if (Cur->isRecord())
5464       Diag(Loc, diag::err_member_qualification)
5465         << Name << SS.getRange();
5466     else if (isa<TranslationUnitDecl>(DC))
5467       Diag(Loc, diag::err_invalid_declarator_global_scope)
5468         << Name << SS.getRange();
5469     else if (isa<FunctionDecl>(Cur))
5470       Diag(Loc, diag::err_invalid_declarator_in_function)
5471         << Name << SS.getRange();
5472     else if (isa<BlockDecl>(Cur))
5473       Diag(Loc, diag::err_invalid_declarator_in_block)
5474         << Name << SS.getRange();
5475     else
5476       Diag(Loc, diag::err_invalid_declarator_scope)
5477       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5478 
5479     return true;
5480   }
5481 
5482   if (Cur->isRecord()) {
5483     // Cannot qualify members within a class.
5484     Diag(Loc, diag::err_member_qualification)
5485       << Name << SS.getRange();
5486     SS.clear();
5487 
5488     // C++ constructors and destructors with incorrect scopes can break
5489     // our AST invariants by having the wrong underlying types. If
5490     // that's the case, then drop this declaration entirely.
5491     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5492          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5493         !Context.hasSameType(Name.getCXXNameType(),
5494                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5495       return true;
5496 
5497     return false;
5498   }
5499 
5500   // C++11 [dcl.meaning]p1:
5501   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5502   //   not begin with a decltype-specifer"
5503   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5504   while (SpecLoc.getPrefix())
5505     SpecLoc = SpecLoc.getPrefix();
5506   if (dyn_cast_or_null<DecltypeType>(
5507         SpecLoc.getNestedNameSpecifier()->getAsType()))
5508     Diag(Loc, diag::err_decltype_in_declarator)
5509       << SpecLoc.getTypeLoc().getSourceRange();
5510 
5511   return false;
5512 }
5513 
5514 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5515                                   MultiTemplateParamsArg TemplateParamLists) {
5516   // TODO: consider using NameInfo for diagnostic.
5517   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5518   DeclarationName Name = NameInfo.getName();
5519 
5520   // All of these full declarators require an identifier.  If it doesn't have
5521   // one, the ParsedFreeStandingDeclSpec action should be used.
5522   if (D.isDecompositionDeclarator()) {
5523     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5524   } else if (!Name) {
5525     if (!D.isInvalidType())  // Reject this if we think it is valid.
5526       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5527           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5528     return nullptr;
5529   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5530     return nullptr;
5531 
5532   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5533   // we find one that is.
5534   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5535          (S->getFlags() & Scope::TemplateParamScope) != 0)
5536     S = S->getParent();
5537 
5538   DeclContext *DC = CurContext;
5539   if (D.getCXXScopeSpec().isInvalid())
5540     D.setInvalidType();
5541   else if (D.getCXXScopeSpec().isSet()) {
5542     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5543                                         UPPC_DeclarationQualifier))
5544       return nullptr;
5545 
5546     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5547     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5548     if (!DC || isa<EnumDecl>(DC)) {
5549       // If we could not compute the declaration context, it's because the
5550       // declaration context is dependent but does not refer to a class,
5551       // class template, or class template partial specialization. Complain
5552       // and return early, to avoid the coming semantic disaster.
5553       Diag(D.getIdentifierLoc(),
5554            diag::err_template_qualified_declarator_no_match)
5555         << D.getCXXScopeSpec().getScopeRep()
5556         << D.getCXXScopeSpec().getRange();
5557       return nullptr;
5558     }
5559     bool IsDependentContext = DC->isDependentContext();
5560 
5561     if (!IsDependentContext &&
5562         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5563       return nullptr;
5564 
5565     // If a class is incomplete, do not parse entities inside it.
5566     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5567       Diag(D.getIdentifierLoc(),
5568            diag::err_member_def_undefined_record)
5569         << Name << DC << D.getCXXScopeSpec().getRange();
5570       return nullptr;
5571     }
5572     if (!D.getDeclSpec().isFriendSpecified()) {
5573       if (diagnoseQualifiedDeclaration(
5574               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5575               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5576         if (DC->isRecord())
5577           return nullptr;
5578 
5579         D.setInvalidType();
5580       }
5581     }
5582 
5583     // Check whether we need to rebuild the type of the given
5584     // declaration in the current instantiation.
5585     if (EnteringContext && IsDependentContext &&
5586         TemplateParamLists.size() != 0) {
5587       ContextRAII SavedContext(*this, DC);
5588       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5589         D.setInvalidType();
5590     }
5591   }
5592 
5593   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5594   QualType R = TInfo->getType();
5595 
5596   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5597                                       UPPC_DeclarationType))
5598     D.setInvalidType();
5599 
5600   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5601                         forRedeclarationInCurContext());
5602 
5603   // See if this is a redefinition of a variable in the same scope.
5604   if (!D.getCXXScopeSpec().isSet()) {
5605     bool IsLinkageLookup = false;
5606     bool CreateBuiltins = false;
5607 
5608     // If the declaration we're planning to build will be a function
5609     // or object with linkage, then look for another declaration with
5610     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5611     //
5612     // If the declaration we're planning to build will be declared with
5613     // external linkage in the translation unit, create any builtin with
5614     // the same name.
5615     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5616       /* Do nothing*/;
5617     else if (CurContext->isFunctionOrMethod() &&
5618              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5619               R->isFunctionType())) {
5620       IsLinkageLookup = true;
5621       CreateBuiltins =
5622           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5623     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5624                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5625       CreateBuiltins = true;
5626 
5627     if (IsLinkageLookup) {
5628       Previous.clear(LookupRedeclarationWithLinkage);
5629       Previous.setRedeclarationKind(ForExternalRedeclaration);
5630     }
5631 
5632     LookupName(Previous, S, CreateBuiltins);
5633   } else { // Something like "int foo::x;"
5634     LookupQualifiedName(Previous, DC);
5635 
5636     // C++ [dcl.meaning]p1:
5637     //   When the declarator-id is qualified, the declaration shall refer to a
5638     //  previously declared member of the class or namespace to which the
5639     //  qualifier refers (or, in the case of a namespace, of an element of the
5640     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5641     //  thereof; [...]
5642     //
5643     // Note that we already checked the context above, and that we do not have
5644     // enough information to make sure that Previous contains the declaration
5645     // we want to match. For example, given:
5646     //
5647     //   class X {
5648     //     void f();
5649     //     void f(float);
5650     //   };
5651     //
5652     //   void X::f(int) { } // ill-formed
5653     //
5654     // In this case, Previous will point to the overload set
5655     // containing the two f's declared in X, but neither of them
5656     // matches.
5657 
5658     // C++ [dcl.meaning]p1:
5659     //   [...] the member shall not merely have been introduced by a
5660     //   using-declaration in the scope of the class or namespace nominated by
5661     //   the nested-name-specifier of the declarator-id.
5662     RemoveUsingDecls(Previous);
5663   }
5664 
5665   if (Previous.isSingleResult() &&
5666       Previous.getFoundDecl()->isTemplateParameter()) {
5667     // Maybe we will complain about the shadowed template parameter.
5668     if (!D.isInvalidType())
5669       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5670                                       Previous.getFoundDecl());
5671 
5672     // Just pretend that we didn't see the previous declaration.
5673     Previous.clear();
5674   }
5675 
5676   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5677     // Forget that the previous declaration is the injected-class-name.
5678     Previous.clear();
5679 
5680   // In C++, the previous declaration we find might be a tag type
5681   // (class or enum). In this case, the new declaration will hide the
5682   // tag type. Note that this applies to functions, function templates, and
5683   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5684   if (Previous.isSingleTagDecl() &&
5685       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5686       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5687     Previous.clear();
5688 
5689   // Check that there are no default arguments other than in the parameters
5690   // of a function declaration (C++ only).
5691   if (getLangOpts().CPlusPlus)
5692     CheckExtraCXXDefaultArguments(D);
5693 
5694   NamedDecl *New;
5695 
5696   bool AddToScope = true;
5697   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5698     if (TemplateParamLists.size()) {
5699       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5700       return nullptr;
5701     }
5702 
5703     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5704   } else if (R->isFunctionType()) {
5705     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5706                                   TemplateParamLists,
5707                                   AddToScope);
5708   } else {
5709     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5710                                   AddToScope);
5711   }
5712 
5713   if (!New)
5714     return nullptr;
5715 
5716   // If this has an identifier and is not a function template specialization,
5717   // add it to the scope stack.
5718   if (New->getDeclName() && AddToScope)
5719     PushOnScopeChains(New, S);
5720 
5721   if (isInOpenMPDeclareTargetContext())
5722     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5723 
5724   return New;
5725 }
5726 
5727 /// Helper method to turn variable array types into constant array
5728 /// types in certain situations which would otherwise be errors (for
5729 /// GCC compatibility).
5730 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5731                                                     ASTContext &Context,
5732                                                     bool &SizeIsNegative,
5733                                                     llvm::APSInt &Oversized) {
5734   // This method tries to turn a variable array into a constant
5735   // array even when the size isn't an ICE.  This is necessary
5736   // for compatibility with code that depends on gcc's buggy
5737   // constant expression folding, like struct {char x[(int)(char*)2];}
5738   SizeIsNegative = false;
5739   Oversized = 0;
5740 
5741   if (T->isDependentType())
5742     return QualType();
5743 
5744   QualifierCollector Qs;
5745   const Type *Ty = Qs.strip(T);
5746 
5747   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5748     QualType Pointee = PTy->getPointeeType();
5749     QualType FixedType =
5750         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5751                                             Oversized);
5752     if (FixedType.isNull()) return FixedType;
5753     FixedType = Context.getPointerType(FixedType);
5754     return Qs.apply(Context, FixedType);
5755   }
5756   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5757     QualType Inner = PTy->getInnerType();
5758     QualType FixedType =
5759         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5760                                             Oversized);
5761     if (FixedType.isNull()) return FixedType;
5762     FixedType = Context.getParenType(FixedType);
5763     return Qs.apply(Context, FixedType);
5764   }
5765 
5766   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5767   if (!VLATy)
5768     return QualType();
5769   // FIXME: We should probably handle this case
5770   if (VLATy->getElementType()->isVariablyModifiedType())
5771     return QualType();
5772 
5773   Expr::EvalResult Result;
5774   if (!VLATy->getSizeExpr() ||
5775       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5776     return QualType();
5777 
5778   llvm::APSInt Res = Result.Val.getInt();
5779 
5780   // Check whether the array size is negative.
5781   if (Res.isSigned() && Res.isNegative()) {
5782     SizeIsNegative = true;
5783     return QualType();
5784   }
5785 
5786   // Check whether the array is too large to be addressed.
5787   unsigned ActiveSizeBits
5788     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5789                                               Res);
5790   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5791     Oversized = Res;
5792     return QualType();
5793   }
5794 
5795   return Context.getConstantArrayType(
5796       VLATy->getElementType(), Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
5797 }
5798 
5799 static void
5800 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5801   SrcTL = SrcTL.getUnqualifiedLoc();
5802   DstTL = DstTL.getUnqualifiedLoc();
5803   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5804     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5805     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5806                                       DstPTL.getPointeeLoc());
5807     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5808     return;
5809   }
5810   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5811     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5812     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5813                                       DstPTL.getInnerLoc());
5814     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5815     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5816     return;
5817   }
5818   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5819   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5820   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5821   TypeLoc DstElemTL = DstATL.getElementLoc();
5822   DstElemTL.initializeFullCopy(SrcElemTL);
5823   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5824   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5825   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5826 }
5827 
5828 /// Helper method to turn variable array types into constant array
5829 /// types in certain situations which would otherwise be errors (for
5830 /// GCC compatibility).
5831 static TypeSourceInfo*
5832 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5833                                               ASTContext &Context,
5834                                               bool &SizeIsNegative,
5835                                               llvm::APSInt &Oversized) {
5836   QualType FixedTy
5837     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5838                                           SizeIsNegative, Oversized);
5839   if (FixedTy.isNull())
5840     return nullptr;
5841   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5842   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5843                                     FixedTInfo->getTypeLoc());
5844   return FixedTInfo;
5845 }
5846 
5847 /// Register the given locally-scoped extern "C" declaration so
5848 /// that it can be found later for redeclarations. We include any extern "C"
5849 /// declaration that is not visible in the translation unit here, not just
5850 /// function-scope declarations.
5851 void
5852 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5853   if (!getLangOpts().CPlusPlus &&
5854       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5855     // Don't need to track declarations in the TU in C.
5856     return;
5857 
5858   // Note that we have a locally-scoped external with this name.
5859   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5860 }
5861 
5862 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5863   // FIXME: We can have multiple results via __attribute__((overloadable)).
5864   auto Result = Context.getExternCContextDecl()->lookup(Name);
5865   return Result.empty() ? nullptr : *Result.begin();
5866 }
5867 
5868 /// Diagnose function specifiers on a declaration of an identifier that
5869 /// does not identify a function.
5870 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5871   // FIXME: We should probably indicate the identifier in question to avoid
5872   // confusion for constructs like "virtual int a(), b;"
5873   if (DS.isVirtualSpecified())
5874     Diag(DS.getVirtualSpecLoc(),
5875          diag::err_virtual_non_function);
5876 
5877   if (DS.hasExplicitSpecifier())
5878     Diag(DS.getExplicitSpecLoc(),
5879          diag::err_explicit_non_function);
5880 
5881   if (DS.isNoreturnSpecified())
5882     Diag(DS.getNoreturnSpecLoc(),
5883          diag::err_noreturn_non_function);
5884 }
5885 
5886 NamedDecl*
5887 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5888                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5889   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5890   if (D.getCXXScopeSpec().isSet()) {
5891     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5892       << D.getCXXScopeSpec().getRange();
5893     D.setInvalidType();
5894     // Pretend we didn't see the scope specifier.
5895     DC = CurContext;
5896     Previous.clear();
5897   }
5898 
5899   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5900 
5901   if (D.getDeclSpec().isInlineSpecified())
5902     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5903         << getLangOpts().CPlusPlus17;
5904   if (D.getDeclSpec().hasConstexprSpecifier())
5905     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5906         << 1 << D.getDeclSpec().getConstexprSpecifier();
5907 
5908   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
5909     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
5910       Diag(D.getName().StartLocation,
5911            diag::err_deduction_guide_invalid_specifier)
5912           << "typedef";
5913     else
5914       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5915           << D.getName().getSourceRange();
5916     return nullptr;
5917   }
5918 
5919   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5920   if (!NewTD) return nullptr;
5921 
5922   // Handle attributes prior to checking for duplicates in MergeVarDecl
5923   ProcessDeclAttributes(S, NewTD, D);
5924 
5925   CheckTypedefForVariablyModifiedType(S, NewTD);
5926 
5927   bool Redeclaration = D.isRedeclaration();
5928   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5929   D.setRedeclaration(Redeclaration);
5930   return ND;
5931 }
5932 
5933 void
5934 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5935   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5936   // then it shall have block scope.
5937   // Note that variably modified types must be fixed before merging the decl so
5938   // that redeclarations will match.
5939   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5940   QualType T = TInfo->getType();
5941   if (T->isVariablyModifiedType()) {
5942     setFunctionHasBranchProtectedScope();
5943 
5944     if (S->getFnParent() == nullptr) {
5945       bool SizeIsNegative;
5946       llvm::APSInt Oversized;
5947       TypeSourceInfo *FixedTInfo =
5948         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5949                                                       SizeIsNegative,
5950                                                       Oversized);
5951       if (FixedTInfo) {
5952         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5953         NewTD->setTypeSourceInfo(FixedTInfo);
5954       } else {
5955         if (SizeIsNegative)
5956           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5957         else if (T->isVariableArrayType())
5958           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5959         else if (Oversized.getBoolValue())
5960           Diag(NewTD->getLocation(), diag::err_array_too_large)
5961             << Oversized.toString(10);
5962         else
5963           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5964         NewTD->setInvalidDecl();
5965       }
5966     }
5967   }
5968 }
5969 
5970 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5971 /// declares a typedef-name, either using the 'typedef' type specifier or via
5972 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5973 NamedDecl*
5974 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5975                            LookupResult &Previous, bool &Redeclaration) {
5976 
5977   // Find the shadowed declaration before filtering for scope.
5978   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5979 
5980   // Merge the decl with the existing one if appropriate. If the decl is
5981   // in an outer scope, it isn't the same thing.
5982   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5983                        /*AllowInlineNamespace*/false);
5984   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5985   if (!Previous.empty()) {
5986     Redeclaration = true;
5987     MergeTypedefNameDecl(S, NewTD, Previous);
5988   } else {
5989     inferGslPointerAttribute(NewTD);
5990   }
5991 
5992   if (ShadowedDecl && !Redeclaration)
5993     CheckShadow(NewTD, ShadowedDecl, Previous);
5994 
5995   // If this is the C FILE type, notify the AST context.
5996   if (IdentifierInfo *II = NewTD->getIdentifier())
5997     if (!NewTD->isInvalidDecl() &&
5998         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5999       if (II->isStr("FILE"))
6000         Context.setFILEDecl(NewTD);
6001       else if (II->isStr("jmp_buf"))
6002         Context.setjmp_bufDecl(NewTD);
6003       else if (II->isStr("sigjmp_buf"))
6004         Context.setsigjmp_bufDecl(NewTD);
6005       else if (II->isStr("ucontext_t"))
6006         Context.setucontext_tDecl(NewTD);
6007     }
6008 
6009   return NewTD;
6010 }
6011 
6012 /// Determines whether the given declaration is an out-of-scope
6013 /// previous declaration.
6014 ///
6015 /// This routine should be invoked when name lookup has found a
6016 /// previous declaration (PrevDecl) that is not in the scope where a
6017 /// new declaration by the same name is being introduced. If the new
6018 /// declaration occurs in a local scope, previous declarations with
6019 /// linkage may still be considered previous declarations (C99
6020 /// 6.2.2p4-5, C++ [basic.link]p6).
6021 ///
6022 /// \param PrevDecl the previous declaration found by name
6023 /// lookup
6024 ///
6025 /// \param DC the context in which the new declaration is being
6026 /// declared.
6027 ///
6028 /// \returns true if PrevDecl is an out-of-scope previous declaration
6029 /// for a new delcaration with the same name.
6030 static bool
6031 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6032                                 ASTContext &Context) {
6033   if (!PrevDecl)
6034     return false;
6035 
6036   if (!PrevDecl->hasLinkage())
6037     return false;
6038 
6039   if (Context.getLangOpts().CPlusPlus) {
6040     // C++ [basic.link]p6:
6041     //   If there is a visible declaration of an entity with linkage
6042     //   having the same name and type, ignoring entities declared
6043     //   outside the innermost enclosing namespace scope, the block
6044     //   scope declaration declares that same entity and receives the
6045     //   linkage of the previous declaration.
6046     DeclContext *OuterContext = DC->getRedeclContext();
6047     if (!OuterContext->isFunctionOrMethod())
6048       // This rule only applies to block-scope declarations.
6049       return false;
6050 
6051     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6052     if (PrevOuterContext->isRecord())
6053       // We found a member function: ignore it.
6054       return false;
6055 
6056     // Find the innermost enclosing namespace for the new and
6057     // previous declarations.
6058     OuterContext = OuterContext->getEnclosingNamespaceContext();
6059     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6060 
6061     // The previous declaration is in a different namespace, so it
6062     // isn't the same function.
6063     if (!OuterContext->Equals(PrevOuterContext))
6064       return false;
6065   }
6066 
6067   return true;
6068 }
6069 
6070 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6071   CXXScopeSpec &SS = D.getCXXScopeSpec();
6072   if (!SS.isSet()) return;
6073   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6074 }
6075 
6076 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6077   QualType type = decl->getType();
6078   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6079   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6080     // Various kinds of declaration aren't allowed to be __autoreleasing.
6081     unsigned kind = -1U;
6082     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6083       if (var->hasAttr<BlocksAttr>())
6084         kind = 0; // __block
6085       else if (!var->hasLocalStorage())
6086         kind = 1; // global
6087     } else if (isa<ObjCIvarDecl>(decl)) {
6088       kind = 3; // ivar
6089     } else if (isa<FieldDecl>(decl)) {
6090       kind = 2; // field
6091     }
6092 
6093     if (kind != -1U) {
6094       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6095         << kind;
6096     }
6097   } else if (lifetime == Qualifiers::OCL_None) {
6098     // Try to infer lifetime.
6099     if (!type->isObjCLifetimeType())
6100       return false;
6101 
6102     lifetime = type->getObjCARCImplicitLifetime();
6103     type = Context.getLifetimeQualifiedType(type, lifetime);
6104     decl->setType(type);
6105   }
6106 
6107   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6108     // Thread-local variables cannot have lifetime.
6109     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6110         var->getTLSKind()) {
6111       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6112         << var->getType();
6113       return true;
6114     }
6115   }
6116 
6117   return false;
6118 }
6119 
6120 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6121   // Ensure that an auto decl is deduced otherwise the checks below might cache
6122   // the wrong linkage.
6123   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6124 
6125   // 'weak' only applies to declarations with external linkage.
6126   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6127     if (!ND.isExternallyVisible()) {
6128       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6129       ND.dropAttr<WeakAttr>();
6130     }
6131   }
6132   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6133     if (ND.isExternallyVisible()) {
6134       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6135       ND.dropAttr<WeakRefAttr>();
6136       ND.dropAttr<AliasAttr>();
6137     }
6138   }
6139 
6140   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6141     if (VD->hasInit()) {
6142       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6143         assert(VD->isThisDeclarationADefinition() &&
6144                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6145         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6146         VD->dropAttr<AliasAttr>();
6147       }
6148     }
6149   }
6150 
6151   // 'selectany' only applies to externally visible variable declarations.
6152   // It does not apply to functions.
6153   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6154     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6155       S.Diag(Attr->getLocation(),
6156              diag::err_attribute_selectany_non_extern_data);
6157       ND.dropAttr<SelectAnyAttr>();
6158     }
6159   }
6160 
6161   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6162     auto *VD = dyn_cast<VarDecl>(&ND);
6163     bool IsAnonymousNS = false;
6164     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6165     if (VD) {
6166       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6167       while (NS && !IsAnonymousNS) {
6168         IsAnonymousNS = NS->isAnonymousNamespace();
6169         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6170       }
6171     }
6172     // dll attributes require external linkage. Static locals may have external
6173     // linkage but still cannot be explicitly imported or exported.
6174     // In Microsoft mode, a variable defined in anonymous namespace must have
6175     // external linkage in order to be exported.
6176     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6177     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6178         (!AnonNSInMicrosoftMode &&
6179          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6180       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6181         << &ND << Attr;
6182       ND.setInvalidDecl();
6183     }
6184   }
6185 
6186   // Virtual functions cannot be marked as 'notail'.
6187   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
6188     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
6189       if (MD->isVirtual()) {
6190         S.Diag(ND.getLocation(),
6191                diag::err_invalid_attribute_on_virtual_function)
6192             << Attr;
6193         ND.dropAttr<NotTailCalledAttr>();
6194       }
6195 
6196   // Check the attributes on the function type, if any.
6197   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6198     // Don't declare this variable in the second operand of the for-statement;
6199     // GCC miscompiles that by ending its lifetime before evaluating the
6200     // third operand. See gcc.gnu.org/PR86769.
6201     AttributedTypeLoc ATL;
6202     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6203          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6204          TL = ATL.getModifiedLoc()) {
6205       // The [[lifetimebound]] attribute can be applied to the implicit object
6206       // parameter of a non-static member function (other than a ctor or dtor)
6207       // by applying it to the function type.
6208       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6209         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6210         if (!MD || MD->isStatic()) {
6211           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6212               << !MD << A->getRange();
6213         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6214           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6215               << isa<CXXDestructorDecl>(MD) << A->getRange();
6216         }
6217       }
6218     }
6219   }
6220 }
6221 
6222 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6223                                            NamedDecl *NewDecl,
6224                                            bool IsSpecialization,
6225                                            bool IsDefinition) {
6226   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6227     return;
6228 
6229   bool IsTemplate = false;
6230   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6231     OldDecl = OldTD->getTemplatedDecl();
6232     IsTemplate = true;
6233     if (!IsSpecialization)
6234       IsDefinition = false;
6235   }
6236   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6237     NewDecl = NewTD->getTemplatedDecl();
6238     IsTemplate = true;
6239   }
6240 
6241   if (!OldDecl || !NewDecl)
6242     return;
6243 
6244   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6245   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6246   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6247   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6248 
6249   // dllimport and dllexport are inheritable attributes so we have to exclude
6250   // inherited attribute instances.
6251   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6252                     (NewExportAttr && !NewExportAttr->isInherited());
6253 
6254   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6255   // the only exception being explicit specializations.
6256   // Implicitly generated declarations are also excluded for now because there
6257   // is no other way to switch these to use dllimport or dllexport.
6258   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6259 
6260   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6261     // Allow with a warning for free functions and global variables.
6262     bool JustWarn = false;
6263     if (!OldDecl->isCXXClassMember()) {
6264       auto *VD = dyn_cast<VarDecl>(OldDecl);
6265       if (VD && !VD->getDescribedVarTemplate())
6266         JustWarn = true;
6267       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6268       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6269         JustWarn = true;
6270     }
6271 
6272     // We cannot change a declaration that's been used because IR has already
6273     // been emitted. Dllimported functions will still work though (modulo
6274     // address equality) as they can use the thunk.
6275     if (OldDecl->isUsed())
6276       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6277         JustWarn = false;
6278 
6279     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6280                                : diag::err_attribute_dll_redeclaration;
6281     S.Diag(NewDecl->getLocation(), DiagID)
6282         << NewDecl
6283         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6284     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6285     if (!JustWarn) {
6286       NewDecl->setInvalidDecl();
6287       return;
6288     }
6289   }
6290 
6291   // A redeclaration is not allowed to drop a dllimport attribute, the only
6292   // exceptions being inline function definitions (except for function
6293   // templates), local extern declarations, qualified friend declarations or
6294   // special MSVC extension: in the last case, the declaration is treated as if
6295   // it were marked dllexport.
6296   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6297   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6298   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6299     // Ignore static data because out-of-line definitions are diagnosed
6300     // separately.
6301     IsStaticDataMember = VD->isStaticDataMember();
6302     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6303                    VarDecl::DeclarationOnly;
6304   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6305     IsInline = FD->isInlined();
6306     IsQualifiedFriend = FD->getQualifier() &&
6307                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6308   }
6309 
6310   if (OldImportAttr && !HasNewAttr &&
6311       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6312       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6313     if (IsMicrosoft && IsDefinition) {
6314       S.Diag(NewDecl->getLocation(),
6315              diag::warn_redeclaration_without_import_attribute)
6316           << NewDecl;
6317       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6318       NewDecl->dropAttr<DLLImportAttr>();
6319       NewDecl->addAttr(
6320           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6321     } else {
6322       S.Diag(NewDecl->getLocation(),
6323              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6324           << NewDecl << OldImportAttr;
6325       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6326       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6327       OldDecl->dropAttr<DLLImportAttr>();
6328       NewDecl->dropAttr<DLLImportAttr>();
6329     }
6330   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6331     // In MinGW, seeing a function declared inline drops the dllimport
6332     // attribute.
6333     OldDecl->dropAttr<DLLImportAttr>();
6334     NewDecl->dropAttr<DLLImportAttr>();
6335     S.Diag(NewDecl->getLocation(),
6336            diag::warn_dllimport_dropped_from_inline_function)
6337         << NewDecl << OldImportAttr;
6338   }
6339 
6340   // A specialization of a class template member function is processed here
6341   // since it's a redeclaration. If the parent class is dllexport, the
6342   // specialization inherits that attribute. This doesn't happen automatically
6343   // since the parent class isn't instantiated until later.
6344   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6345     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6346         !NewImportAttr && !NewExportAttr) {
6347       if (const DLLExportAttr *ParentExportAttr =
6348               MD->getParent()->getAttr<DLLExportAttr>()) {
6349         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6350         NewAttr->setInherited(true);
6351         NewDecl->addAttr(NewAttr);
6352       }
6353     }
6354   }
6355 }
6356 
6357 /// Given that we are within the definition of the given function,
6358 /// will that definition behave like C99's 'inline', where the
6359 /// definition is discarded except for optimization purposes?
6360 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6361   // Try to avoid calling GetGVALinkageForFunction.
6362 
6363   // All cases of this require the 'inline' keyword.
6364   if (!FD->isInlined()) return false;
6365 
6366   // This is only possible in C++ with the gnu_inline attribute.
6367   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6368     return false;
6369 
6370   // Okay, go ahead and call the relatively-more-expensive function.
6371   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6372 }
6373 
6374 /// Determine whether a variable is extern "C" prior to attaching
6375 /// an initializer. We can't just call isExternC() here, because that
6376 /// will also compute and cache whether the declaration is externally
6377 /// visible, which might change when we attach the initializer.
6378 ///
6379 /// This can only be used if the declaration is known to not be a
6380 /// redeclaration of an internal linkage declaration.
6381 ///
6382 /// For instance:
6383 ///
6384 ///   auto x = []{};
6385 ///
6386 /// Attaching the initializer here makes this declaration not externally
6387 /// visible, because its type has internal linkage.
6388 ///
6389 /// FIXME: This is a hack.
6390 template<typename T>
6391 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6392   if (S.getLangOpts().CPlusPlus) {
6393     // In C++, the overloadable attribute negates the effects of extern "C".
6394     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6395       return false;
6396 
6397     // So do CUDA's host/device attributes.
6398     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6399                                  D->template hasAttr<CUDAHostAttr>()))
6400       return false;
6401   }
6402   return D->isExternC();
6403 }
6404 
6405 static bool shouldConsiderLinkage(const VarDecl *VD) {
6406   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6407   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6408       isa<OMPDeclareMapperDecl>(DC))
6409     return VD->hasExternalStorage();
6410   if (DC->isFileContext())
6411     return true;
6412   if (DC->isRecord())
6413     return false;
6414   llvm_unreachable("Unexpected context");
6415 }
6416 
6417 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6418   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6419   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6420       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6421     return true;
6422   if (DC->isRecord())
6423     return false;
6424   llvm_unreachable("Unexpected context");
6425 }
6426 
6427 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6428                           ParsedAttr::Kind Kind) {
6429   // Check decl attributes on the DeclSpec.
6430   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6431     return true;
6432 
6433   // Walk the declarator structure, checking decl attributes that were in a type
6434   // position to the decl itself.
6435   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6436     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6437       return true;
6438   }
6439 
6440   // Finally, check attributes on the decl itself.
6441   return PD.getAttributes().hasAttribute(Kind);
6442 }
6443 
6444 /// Adjust the \c DeclContext for a function or variable that might be a
6445 /// function-local external declaration.
6446 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6447   if (!DC->isFunctionOrMethod())
6448     return false;
6449 
6450   // If this is a local extern function or variable declared within a function
6451   // template, don't add it into the enclosing namespace scope until it is
6452   // instantiated; it might have a dependent type right now.
6453   if (DC->isDependentContext())
6454     return true;
6455 
6456   // C++11 [basic.link]p7:
6457   //   When a block scope declaration of an entity with linkage is not found to
6458   //   refer to some other declaration, then that entity is a member of the
6459   //   innermost enclosing namespace.
6460   //
6461   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6462   // semantically-enclosing namespace, not a lexically-enclosing one.
6463   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6464     DC = DC->getParent();
6465   return true;
6466 }
6467 
6468 /// Returns true if given declaration has external C language linkage.
6469 static bool isDeclExternC(const Decl *D) {
6470   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6471     return FD->isExternC();
6472   if (const auto *VD = dyn_cast<VarDecl>(D))
6473     return VD->isExternC();
6474 
6475   llvm_unreachable("Unknown type of decl!");
6476 }
6477 
6478 NamedDecl *Sema::ActOnVariableDeclarator(
6479     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6480     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6481     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6482   QualType R = TInfo->getType();
6483   DeclarationName Name = GetNameForDeclarator(D).getName();
6484 
6485   IdentifierInfo *II = Name.getAsIdentifierInfo();
6486 
6487   if (D.isDecompositionDeclarator()) {
6488     // Take the name of the first declarator as our name for diagnostic
6489     // purposes.
6490     auto &Decomp = D.getDecompositionDeclarator();
6491     if (!Decomp.bindings().empty()) {
6492       II = Decomp.bindings()[0].Name;
6493       Name = II;
6494     }
6495   } else if (!II) {
6496     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6497     return nullptr;
6498   }
6499 
6500   if (getLangOpts().OpenCL) {
6501     // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6502     // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6503     // argument.
6504     if (R->isImageType() || R->isPipeType()) {
6505       Diag(D.getIdentifierLoc(),
6506            diag::err_opencl_type_can_only_be_used_as_function_parameter)
6507           << R;
6508       D.setInvalidType();
6509       return nullptr;
6510     }
6511 
6512     // OpenCL v1.2 s6.9.r:
6513     // The event type cannot be used to declare a program scope variable.
6514     // OpenCL v2.0 s6.9.q:
6515     // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6516     if (NULL == S->getParent()) {
6517       if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6518         Diag(D.getIdentifierLoc(),
6519              diag::err_invalid_type_for_program_scope_var) << R;
6520         D.setInvalidType();
6521         return nullptr;
6522       }
6523     }
6524 
6525     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6526     QualType NR = R;
6527     while (NR->isPointerType()) {
6528       if (NR->isFunctionPointerType()) {
6529         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6530         D.setInvalidType();
6531         break;
6532       }
6533       NR = NR->getPointeeType();
6534     }
6535 
6536     if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6537       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6538       // half array type (unless the cl_khr_fp16 extension is enabled).
6539       if (Context.getBaseElementType(R)->isHalfType()) {
6540         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6541         D.setInvalidType();
6542       }
6543     }
6544 
6545     if (R->isSamplerT()) {
6546       // OpenCL v1.2 s6.9.b p4:
6547       // The sampler type cannot be used with the __local and __global address
6548       // space qualifiers.
6549       if (R.getAddressSpace() == LangAS::opencl_local ||
6550           R.getAddressSpace() == LangAS::opencl_global) {
6551         Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6552       }
6553 
6554       // OpenCL v1.2 s6.12.14.1:
6555       // A global sampler must be declared with either the constant address
6556       // space qualifier or with the const qualifier.
6557       if (DC->isTranslationUnit() &&
6558           !(R.getAddressSpace() == LangAS::opencl_constant ||
6559           R.isConstQualified())) {
6560         Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6561         D.setInvalidType();
6562       }
6563     }
6564 
6565     // OpenCL v1.2 s6.9.r:
6566     // The event type cannot be used with the __local, __constant and __global
6567     // address space qualifiers.
6568     if (R->isEventT()) {
6569       if (R.getAddressSpace() != LangAS::opencl_private) {
6570         Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6571         D.setInvalidType();
6572       }
6573     }
6574 
6575     // C++ for OpenCL does not allow the thread_local storage qualifier.
6576     // OpenCL C does not support thread_local either, and
6577     // also reject all other thread storage class specifiers.
6578     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6579     if (TSC != TSCS_unspecified) {
6580       bool IsCXX = getLangOpts().OpenCLCPlusPlus;
6581       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6582            diag::err_opencl_unknown_type_specifier)
6583           << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString()
6584           << DeclSpec::getSpecifierName(TSC) << 1;
6585       D.setInvalidType();
6586       return nullptr;
6587     }
6588   }
6589 
6590   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6591   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6592 
6593   // dllimport globals without explicit storage class are treated as extern. We
6594   // have to change the storage class this early to get the right DeclContext.
6595   if (SC == SC_None && !DC->isRecord() &&
6596       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6597       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6598     SC = SC_Extern;
6599 
6600   DeclContext *OriginalDC = DC;
6601   bool IsLocalExternDecl = SC == SC_Extern &&
6602                            adjustContextForLocalExternDecl(DC);
6603 
6604   if (SCSpec == DeclSpec::SCS_mutable) {
6605     // mutable can only appear on non-static class members, so it's always
6606     // an error here
6607     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6608     D.setInvalidType();
6609     SC = SC_None;
6610   }
6611 
6612   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6613       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6614                               D.getDeclSpec().getStorageClassSpecLoc())) {
6615     // In C++11, the 'register' storage class specifier is deprecated.
6616     // Suppress the warning in system macros, it's used in macros in some
6617     // popular C system headers, such as in glibc's htonl() macro.
6618     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6619          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6620                                    : diag::warn_deprecated_register)
6621       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6622   }
6623 
6624   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6625 
6626   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6627     // C99 6.9p2: The storage-class specifiers auto and register shall not
6628     // appear in the declaration specifiers in an external declaration.
6629     // Global Register+Asm is a GNU extension we support.
6630     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6631       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6632       D.setInvalidType();
6633     }
6634   }
6635 
6636   bool IsMemberSpecialization = false;
6637   bool IsVariableTemplateSpecialization = false;
6638   bool IsPartialSpecialization = false;
6639   bool IsVariableTemplate = false;
6640   VarDecl *NewVD = nullptr;
6641   VarTemplateDecl *NewTemplate = nullptr;
6642   TemplateParameterList *TemplateParams = nullptr;
6643   if (!getLangOpts().CPlusPlus) {
6644     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6645                             II, R, TInfo, SC);
6646 
6647     if (R->getContainedDeducedType())
6648       ParsingInitForAutoVars.insert(NewVD);
6649 
6650     if (D.isInvalidType())
6651       NewVD->setInvalidDecl();
6652 
6653     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
6654         NewVD->hasLocalStorage())
6655       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
6656                             NTCUC_AutoVar, NTCUK_Destruct);
6657   } else {
6658     bool Invalid = false;
6659 
6660     if (DC->isRecord() && !CurContext->isRecord()) {
6661       // This is an out-of-line definition of a static data member.
6662       switch (SC) {
6663       case SC_None:
6664         break;
6665       case SC_Static:
6666         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6667              diag::err_static_out_of_line)
6668           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6669         break;
6670       case SC_Auto:
6671       case SC_Register:
6672       case SC_Extern:
6673         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6674         // to names of variables declared in a block or to function parameters.
6675         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6676         // of class members
6677 
6678         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6679              diag::err_storage_class_for_static_member)
6680           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6681         break;
6682       case SC_PrivateExtern:
6683         llvm_unreachable("C storage class in c++!");
6684       }
6685     }
6686 
6687     if (SC == SC_Static && CurContext->isRecord()) {
6688       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6689         if (RD->isLocalClass())
6690           Diag(D.getIdentifierLoc(),
6691                diag::err_static_data_member_not_allowed_in_local_class)
6692             << Name << RD->getDeclName();
6693 
6694         // C++98 [class.union]p1: If a union contains a static data member,
6695         // the program is ill-formed. C++11 drops this restriction.
6696         if (RD->isUnion())
6697           Diag(D.getIdentifierLoc(),
6698                getLangOpts().CPlusPlus11
6699                  ? diag::warn_cxx98_compat_static_data_member_in_union
6700                  : diag::ext_static_data_member_in_union) << Name;
6701         // We conservatively disallow static data members in anonymous structs.
6702         else if (!RD->getDeclName())
6703           Diag(D.getIdentifierLoc(),
6704                diag::err_static_data_member_not_allowed_in_anon_struct)
6705             << Name << RD->isUnion();
6706       }
6707     }
6708 
6709     // Match up the template parameter lists with the scope specifier, then
6710     // determine whether we have a template or a template specialization.
6711     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6712         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6713         D.getCXXScopeSpec(),
6714         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6715             ? D.getName().TemplateId
6716             : nullptr,
6717         TemplateParamLists,
6718         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6719 
6720     if (TemplateParams) {
6721       if (!TemplateParams->size() &&
6722           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6723         // There is an extraneous 'template<>' for this variable. Complain
6724         // about it, but allow the declaration of the variable.
6725         Diag(TemplateParams->getTemplateLoc(),
6726              diag::err_template_variable_noparams)
6727           << II
6728           << SourceRange(TemplateParams->getTemplateLoc(),
6729                          TemplateParams->getRAngleLoc());
6730         TemplateParams = nullptr;
6731       } else {
6732         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6733           // This is an explicit specialization or a partial specialization.
6734           // FIXME: Check that we can declare a specialization here.
6735           IsVariableTemplateSpecialization = true;
6736           IsPartialSpecialization = TemplateParams->size() > 0;
6737         } else { // if (TemplateParams->size() > 0)
6738           // This is a template declaration.
6739           IsVariableTemplate = true;
6740 
6741           // Check that we can declare a template here.
6742           if (CheckTemplateDeclScope(S, TemplateParams))
6743             return nullptr;
6744 
6745           // Only C++1y supports variable templates (N3651).
6746           Diag(D.getIdentifierLoc(),
6747                getLangOpts().CPlusPlus14
6748                    ? diag::warn_cxx11_compat_variable_template
6749                    : diag::ext_variable_template);
6750         }
6751       }
6752     } else {
6753       assert((Invalid ||
6754               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
6755              "should have a 'template<>' for this decl");
6756     }
6757 
6758     if (IsVariableTemplateSpecialization) {
6759       SourceLocation TemplateKWLoc =
6760           TemplateParamLists.size() > 0
6761               ? TemplateParamLists[0]->getTemplateLoc()
6762               : SourceLocation();
6763       DeclResult Res = ActOnVarTemplateSpecialization(
6764           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6765           IsPartialSpecialization);
6766       if (Res.isInvalid())
6767         return nullptr;
6768       NewVD = cast<VarDecl>(Res.get());
6769       AddToScope = false;
6770     } else if (D.isDecompositionDeclarator()) {
6771       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
6772                                         D.getIdentifierLoc(), R, TInfo, SC,
6773                                         Bindings);
6774     } else
6775       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
6776                               D.getIdentifierLoc(), II, R, TInfo, SC);
6777 
6778     // If this is supposed to be a variable template, create it as such.
6779     if (IsVariableTemplate) {
6780       NewTemplate =
6781           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6782                                   TemplateParams, NewVD);
6783       NewVD->setDescribedVarTemplate(NewTemplate);
6784     }
6785 
6786     // If this decl has an auto type in need of deduction, make a note of the
6787     // Decl so we can diagnose uses of it in its own initializer.
6788     if (R->getContainedDeducedType())
6789       ParsingInitForAutoVars.insert(NewVD);
6790 
6791     if (D.isInvalidType() || Invalid) {
6792       NewVD->setInvalidDecl();
6793       if (NewTemplate)
6794         NewTemplate->setInvalidDecl();
6795     }
6796 
6797     SetNestedNameSpecifier(*this, NewVD, D);
6798 
6799     // If we have any template parameter lists that don't directly belong to
6800     // the variable (matching the scope specifier), store them.
6801     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6802     if (TemplateParamLists.size() > VDTemplateParamLists)
6803       NewVD->setTemplateParameterListsInfo(
6804           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6805   }
6806 
6807   if (D.getDeclSpec().isInlineSpecified()) {
6808     if (!getLangOpts().CPlusPlus) {
6809       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6810           << 0;
6811     } else if (CurContext->isFunctionOrMethod()) {
6812       // 'inline' is not allowed on block scope variable declaration.
6813       Diag(D.getDeclSpec().getInlineSpecLoc(),
6814            diag::err_inline_declaration_block_scope) << Name
6815         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6816     } else {
6817       Diag(D.getDeclSpec().getInlineSpecLoc(),
6818            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
6819                                      : diag::ext_inline_variable);
6820       NewVD->setInlineSpecified();
6821     }
6822   }
6823 
6824   // Set the lexical context. If the declarator has a C++ scope specifier, the
6825   // lexical context will be different from the semantic context.
6826   NewVD->setLexicalDeclContext(CurContext);
6827   if (NewTemplate)
6828     NewTemplate->setLexicalDeclContext(CurContext);
6829 
6830   if (IsLocalExternDecl) {
6831     if (D.isDecompositionDeclarator())
6832       for (auto *B : Bindings)
6833         B->setLocalExternDecl();
6834     else
6835       NewVD->setLocalExternDecl();
6836   }
6837 
6838   bool EmitTLSUnsupportedError = false;
6839   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6840     // C++11 [dcl.stc]p4:
6841     //   When thread_local is applied to a variable of block scope the
6842     //   storage-class-specifier static is implied if it does not appear
6843     //   explicitly.
6844     // Core issue: 'static' is not implied if the variable is declared
6845     //   'extern'.
6846     if (NewVD->hasLocalStorage() &&
6847         (SCSpec != DeclSpec::SCS_unspecified ||
6848          TSCS != DeclSpec::TSCS_thread_local ||
6849          !DC->isFunctionOrMethod()))
6850       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6851            diag::err_thread_non_global)
6852         << DeclSpec::getSpecifierName(TSCS);
6853     else if (!Context.getTargetInfo().isTLSSupported()) {
6854       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6855         // Postpone error emission until we've collected attributes required to
6856         // figure out whether it's a host or device variable and whether the
6857         // error should be ignored.
6858         EmitTLSUnsupportedError = true;
6859         // We still need to mark the variable as TLS so it shows up in AST with
6860         // proper storage class for other tools to use even if we're not going
6861         // to emit any code for it.
6862         NewVD->setTSCSpec(TSCS);
6863       } else
6864         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6865              diag::err_thread_unsupported);
6866     } else
6867       NewVD->setTSCSpec(TSCS);
6868   }
6869 
6870   switch (D.getDeclSpec().getConstexprSpecifier()) {
6871   case CSK_unspecified:
6872     break;
6873 
6874   case CSK_consteval:
6875     Diag(D.getDeclSpec().getConstexprSpecLoc(),
6876         diag::err_constexpr_wrong_decl_kind)
6877       << D.getDeclSpec().getConstexprSpecifier();
6878     LLVM_FALLTHROUGH;
6879 
6880   case CSK_constexpr:
6881     NewVD->setConstexpr(true);
6882     // C++1z [dcl.spec.constexpr]p1:
6883     //   A static data member declared with the constexpr specifier is
6884     //   implicitly an inline variable.
6885     if (NewVD->isStaticDataMember() &&
6886         (getLangOpts().CPlusPlus17 ||
6887          Context.getTargetInfo().getCXXABI().isMicrosoft()))
6888       NewVD->setImplicitlyInline();
6889     break;
6890 
6891   case CSK_constinit:
6892     if (!NewVD->hasGlobalStorage())
6893       Diag(D.getDeclSpec().getConstexprSpecLoc(),
6894            diag::err_constinit_local_variable);
6895     else
6896       NewVD->addAttr(ConstInitAttr::Create(
6897           Context, D.getDeclSpec().getConstexprSpecLoc(),
6898           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
6899     break;
6900   }
6901 
6902   // C99 6.7.4p3
6903   //   An inline definition of a function with external linkage shall
6904   //   not contain a definition of a modifiable object with static or
6905   //   thread storage duration...
6906   // We only apply this when the function is required to be defined
6907   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6908   // that a local variable with thread storage duration still has to
6909   // be marked 'static'.  Also note that it's possible to get these
6910   // semantics in C++ using __attribute__((gnu_inline)).
6911   if (SC == SC_Static && S->getFnParent() != nullptr &&
6912       !NewVD->getType().isConstQualified()) {
6913     FunctionDecl *CurFD = getCurFunctionDecl();
6914     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6915       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6916            diag::warn_static_local_in_extern_inline);
6917       MaybeSuggestAddingStaticToDecl(CurFD);
6918     }
6919   }
6920 
6921   if (D.getDeclSpec().isModulePrivateSpecified()) {
6922     if (IsVariableTemplateSpecialization)
6923       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6924           << (IsPartialSpecialization ? 1 : 0)
6925           << FixItHint::CreateRemoval(
6926                  D.getDeclSpec().getModulePrivateSpecLoc());
6927     else if (IsMemberSpecialization)
6928       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6929         << 2
6930         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6931     else if (NewVD->hasLocalStorage())
6932       Diag(NewVD->getLocation(), diag::err_module_private_local)
6933         << 0 << NewVD->getDeclName()
6934         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6935         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6936     else {
6937       NewVD->setModulePrivate();
6938       if (NewTemplate)
6939         NewTemplate->setModulePrivate();
6940       for (auto *B : Bindings)
6941         B->setModulePrivate();
6942     }
6943   }
6944 
6945   // Handle attributes prior to checking for duplicates in MergeVarDecl
6946   ProcessDeclAttributes(S, NewVD, D);
6947 
6948   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6949     if (EmitTLSUnsupportedError &&
6950         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
6951          (getLangOpts().OpenMPIsDevice &&
6952           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
6953       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6954            diag::err_thread_unsupported);
6955     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6956     // storage [duration]."
6957     if (SC == SC_None && S->getFnParent() != nullptr &&
6958         (NewVD->hasAttr<CUDASharedAttr>() ||
6959          NewVD->hasAttr<CUDAConstantAttr>())) {
6960       NewVD->setStorageClass(SC_Static);
6961     }
6962   }
6963 
6964   // Ensure that dllimport globals without explicit storage class are treated as
6965   // extern. The storage class is set above using parsed attributes. Now we can
6966   // check the VarDecl itself.
6967   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6968          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6969          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6970 
6971   // In auto-retain/release, infer strong retension for variables of
6972   // retainable type.
6973   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6974     NewVD->setInvalidDecl();
6975 
6976   // Handle GNU asm-label extension (encoded as an attribute).
6977   if (Expr *E = (Expr*)D.getAsmLabel()) {
6978     // The parser guarantees this is a string.
6979     StringLiteral *SE = cast<StringLiteral>(E);
6980     StringRef Label = SE->getString();
6981     if (S->getFnParent() != nullptr) {
6982       switch (SC) {
6983       case SC_None:
6984       case SC_Auto:
6985         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6986         break;
6987       case SC_Register:
6988         // Local Named register
6989         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6990             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6991           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6992         break;
6993       case SC_Static:
6994       case SC_Extern:
6995       case SC_PrivateExtern:
6996         break;
6997       }
6998     } else if (SC == SC_Register) {
6999       // Global Named register
7000       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7001         const auto &TI = Context.getTargetInfo();
7002         bool HasSizeMismatch;
7003 
7004         if (!TI.isValidGCCRegisterName(Label))
7005           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7006         else if (!TI.validateGlobalRegisterVariable(Label,
7007                                                     Context.getTypeSize(R),
7008                                                     HasSizeMismatch))
7009           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7010         else if (HasSizeMismatch)
7011           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7012       }
7013 
7014       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7015         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7016         NewVD->setInvalidDecl(true);
7017       }
7018     }
7019 
7020     NewVD->addAttr(::new (Context) AsmLabelAttr(
7021         Context, SE->getStrTokenLoc(0), Label, /*IsLiteralLabel=*/true));
7022   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7023     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7024       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7025     if (I != ExtnameUndeclaredIdentifiers.end()) {
7026       if (isDeclExternC(NewVD)) {
7027         NewVD->addAttr(I->second);
7028         ExtnameUndeclaredIdentifiers.erase(I);
7029       } else
7030         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7031             << /*Variable*/1 << NewVD;
7032     }
7033   }
7034 
7035   // Find the shadowed declaration before filtering for scope.
7036   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7037                                 ? getShadowedDeclaration(NewVD, Previous)
7038                                 : nullptr;
7039 
7040   // Don't consider existing declarations that are in a different
7041   // scope and are out-of-semantic-context declarations (if the new
7042   // declaration has linkage).
7043   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7044                        D.getCXXScopeSpec().isNotEmpty() ||
7045                        IsMemberSpecialization ||
7046                        IsVariableTemplateSpecialization);
7047 
7048   // Check whether the previous declaration is in the same block scope. This
7049   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7050   if (getLangOpts().CPlusPlus &&
7051       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7052     NewVD->setPreviousDeclInSameBlockScope(
7053         Previous.isSingleResult() && !Previous.isShadowed() &&
7054         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7055 
7056   if (!getLangOpts().CPlusPlus) {
7057     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7058   } else {
7059     // If this is an explicit specialization of a static data member, check it.
7060     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7061         CheckMemberSpecialization(NewVD, Previous))
7062       NewVD->setInvalidDecl();
7063 
7064     // Merge the decl with the existing one if appropriate.
7065     if (!Previous.empty()) {
7066       if (Previous.isSingleResult() &&
7067           isa<FieldDecl>(Previous.getFoundDecl()) &&
7068           D.getCXXScopeSpec().isSet()) {
7069         // The user tried to define a non-static data member
7070         // out-of-line (C++ [dcl.meaning]p1).
7071         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7072           << D.getCXXScopeSpec().getRange();
7073         Previous.clear();
7074         NewVD->setInvalidDecl();
7075       }
7076     } else if (D.getCXXScopeSpec().isSet()) {
7077       // No previous declaration in the qualifying scope.
7078       Diag(D.getIdentifierLoc(), diag::err_no_member)
7079         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7080         << D.getCXXScopeSpec().getRange();
7081       NewVD->setInvalidDecl();
7082     }
7083 
7084     if (!IsVariableTemplateSpecialization)
7085       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7086 
7087     if (NewTemplate) {
7088       VarTemplateDecl *PrevVarTemplate =
7089           NewVD->getPreviousDecl()
7090               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7091               : nullptr;
7092 
7093       // Check the template parameter list of this declaration, possibly
7094       // merging in the template parameter list from the previous variable
7095       // template declaration.
7096       if (CheckTemplateParameterList(
7097               TemplateParams,
7098               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7099                               : nullptr,
7100               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7101                DC->isDependentContext())
7102                   ? TPC_ClassTemplateMember
7103                   : TPC_VarTemplate))
7104         NewVD->setInvalidDecl();
7105 
7106       // If we are providing an explicit specialization of a static variable
7107       // template, make a note of that.
7108       if (PrevVarTemplate &&
7109           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7110         PrevVarTemplate->setMemberSpecialization();
7111     }
7112   }
7113 
7114   // Diagnose shadowed variables iff this isn't a redeclaration.
7115   if (ShadowedDecl && !D.isRedeclaration())
7116     CheckShadow(NewVD, ShadowedDecl, Previous);
7117 
7118   ProcessPragmaWeak(S, NewVD);
7119 
7120   // If this is the first declaration of an extern C variable, update
7121   // the map of such variables.
7122   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7123       isIncompleteDeclExternC(*this, NewVD))
7124     RegisterLocallyScopedExternCDecl(NewVD, S);
7125 
7126   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7127     MangleNumberingContext *MCtx;
7128     Decl *ManglingContextDecl;
7129     std::tie(MCtx, ManglingContextDecl) =
7130         getCurrentMangleNumberContext(NewVD->getDeclContext());
7131     if (MCtx) {
7132       Context.setManglingNumber(
7133           NewVD, MCtx->getManglingNumber(
7134                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7135       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7136     }
7137   }
7138 
7139   // Special handling of variable named 'main'.
7140   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7141       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7142       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7143 
7144     // C++ [basic.start.main]p3
7145     // A program that declares a variable main at global scope is ill-formed.
7146     if (getLangOpts().CPlusPlus)
7147       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7148 
7149     // In C, and external-linkage variable named main results in undefined
7150     // behavior.
7151     else if (NewVD->hasExternalFormalLinkage())
7152       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7153   }
7154 
7155   if (D.isRedeclaration() && !Previous.empty()) {
7156     NamedDecl *Prev = Previous.getRepresentativeDecl();
7157     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7158                                    D.isFunctionDefinition());
7159   }
7160 
7161   if (NewTemplate) {
7162     if (NewVD->isInvalidDecl())
7163       NewTemplate->setInvalidDecl();
7164     ActOnDocumentableDecl(NewTemplate);
7165     return NewTemplate;
7166   }
7167 
7168   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7169     CompleteMemberSpecialization(NewVD, Previous);
7170 
7171   return NewVD;
7172 }
7173 
7174 /// Enum describing the %select options in diag::warn_decl_shadow.
7175 enum ShadowedDeclKind {
7176   SDK_Local,
7177   SDK_Global,
7178   SDK_StaticMember,
7179   SDK_Field,
7180   SDK_Typedef,
7181   SDK_Using
7182 };
7183 
7184 /// Determine what kind of declaration we're shadowing.
7185 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7186                                                 const DeclContext *OldDC) {
7187   if (isa<TypeAliasDecl>(ShadowedDecl))
7188     return SDK_Using;
7189   else if (isa<TypedefDecl>(ShadowedDecl))
7190     return SDK_Typedef;
7191   else if (isa<RecordDecl>(OldDC))
7192     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7193 
7194   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7195 }
7196 
7197 /// Return the location of the capture if the given lambda captures the given
7198 /// variable \p VD, or an invalid source location otherwise.
7199 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7200                                          const VarDecl *VD) {
7201   for (const Capture &Capture : LSI->Captures) {
7202     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7203       return Capture.getLocation();
7204   }
7205   return SourceLocation();
7206 }
7207 
7208 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7209                                      const LookupResult &R) {
7210   // Only diagnose if we're shadowing an unambiguous field or variable.
7211   if (R.getResultKind() != LookupResult::Found)
7212     return false;
7213 
7214   // Return false if warning is ignored.
7215   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7216 }
7217 
7218 /// Return the declaration shadowed by the given variable \p D, or null
7219 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7220 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7221                                         const LookupResult &R) {
7222   if (!shouldWarnIfShadowedDecl(Diags, R))
7223     return nullptr;
7224 
7225   // Don't diagnose declarations at file scope.
7226   if (D->hasGlobalStorage())
7227     return nullptr;
7228 
7229   NamedDecl *ShadowedDecl = R.getFoundDecl();
7230   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
7231              ? ShadowedDecl
7232              : nullptr;
7233 }
7234 
7235 /// Return the declaration shadowed by the given typedef \p D, or null
7236 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7237 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7238                                         const LookupResult &R) {
7239   // Don't warn if typedef declaration is part of a class
7240   if (D->getDeclContext()->isRecord())
7241     return nullptr;
7242 
7243   if (!shouldWarnIfShadowedDecl(Diags, R))
7244     return nullptr;
7245 
7246   NamedDecl *ShadowedDecl = R.getFoundDecl();
7247   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7248 }
7249 
7250 /// Diagnose variable or built-in function shadowing.  Implements
7251 /// -Wshadow.
7252 ///
7253 /// This method is called whenever a VarDecl is added to a "useful"
7254 /// scope.
7255 ///
7256 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7257 /// \param R the lookup of the name
7258 ///
7259 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7260                        const LookupResult &R) {
7261   DeclContext *NewDC = D->getDeclContext();
7262 
7263   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7264     // Fields are not shadowed by variables in C++ static methods.
7265     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7266       if (MD->isStatic())
7267         return;
7268 
7269     // Fields shadowed by constructor parameters are a special case. Usually
7270     // the constructor initializes the field with the parameter.
7271     if (isa<CXXConstructorDecl>(NewDC))
7272       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7273         // Remember that this was shadowed so we can either warn about its
7274         // modification or its existence depending on warning settings.
7275         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7276         return;
7277       }
7278   }
7279 
7280   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7281     if (shadowedVar->isExternC()) {
7282       // For shadowing external vars, make sure that we point to the global
7283       // declaration, not a locally scoped extern declaration.
7284       for (auto I : shadowedVar->redecls())
7285         if (I->isFileVarDecl()) {
7286           ShadowedDecl = I;
7287           break;
7288         }
7289     }
7290 
7291   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7292 
7293   unsigned WarningDiag = diag::warn_decl_shadow;
7294   SourceLocation CaptureLoc;
7295   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7296       isa<CXXMethodDecl>(NewDC)) {
7297     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7298       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7299         if (RD->getLambdaCaptureDefault() == LCD_None) {
7300           // Try to avoid warnings for lambdas with an explicit capture list.
7301           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7302           // Warn only when the lambda captures the shadowed decl explicitly.
7303           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7304           if (CaptureLoc.isInvalid())
7305             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7306         } else {
7307           // Remember that this was shadowed so we can avoid the warning if the
7308           // shadowed decl isn't captured and the warning settings allow it.
7309           cast<LambdaScopeInfo>(getCurFunction())
7310               ->ShadowingDecls.push_back(
7311                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7312           return;
7313         }
7314       }
7315 
7316       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7317         // A variable can't shadow a local variable in an enclosing scope, if
7318         // they are separated by a non-capturing declaration context.
7319         for (DeclContext *ParentDC = NewDC;
7320              ParentDC && !ParentDC->Equals(OldDC);
7321              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7322           // Only block literals, captured statements, and lambda expressions
7323           // can capture; other scopes don't.
7324           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7325               !isLambdaCallOperator(ParentDC)) {
7326             return;
7327           }
7328         }
7329       }
7330     }
7331   }
7332 
7333   // Only warn about certain kinds of shadowing for class members.
7334   if (NewDC && NewDC->isRecord()) {
7335     // In particular, don't warn about shadowing non-class members.
7336     if (!OldDC->isRecord())
7337       return;
7338 
7339     // TODO: should we warn about static data members shadowing
7340     // static data members from base classes?
7341 
7342     // TODO: don't diagnose for inaccessible shadowed members.
7343     // This is hard to do perfectly because we might friend the
7344     // shadowing context, but that's just a false negative.
7345   }
7346 
7347 
7348   DeclarationName Name = R.getLookupName();
7349 
7350   // Emit warning and note.
7351   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7352     return;
7353   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7354   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7355   if (!CaptureLoc.isInvalid())
7356     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7357         << Name << /*explicitly*/ 1;
7358   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7359 }
7360 
7361 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7362 /// when these variables are captured by the lambda.
7363 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7364   for (const auto &Shadow : LSI->ShadowingDecls) {
7365     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7366     // Try to avoid the warning when the shadowed decl isn't captured.
7367     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7368     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7369     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7370                                        ? diag::warn_decl_shadow_uncaptured_local
7371                                        : diag::warn_decl_shadow)
7372         << Shadow.VD->getDeclName()
7373         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7374     if (!CaptureLoc.isInvalid())
7375       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7376           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7377     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7378   }
7379 }
7380 
7381 /// Check -Wshadow without the advantage of a previous lookup.
7382 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7383   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7384     return;
7385 
7386   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7387                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7388   LookupName(R, S);
7389   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7390     CheckShadow(D, ShadowedDecl, R);
7391 }
7392 
7393 /// Check if 'E', which is an expression that is about to be modified, refers
7394 /// to a constructor parameter that shadows a field.
7395 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7396   // Quickly ignore expressions that can't be shadowing ctor parameters.
7397   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7398     return;
7399   E = E->IgnoreParenImpCasts();
7400   auto *DRE = dyn_cast<DeclRefExpr>(E);
7401   if (!DRE)
7402     return;
7403   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7404   auto I = ShadowingDecls.find(D);
7405   if (I == ShadowingDecls.end())
7406     return;
7407   const NamedDecl *ShadowedDecl = I->second;
7408   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7409   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7410   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7411   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7412 
7413   // Avoid issuing multiple warnings about the same decl.
7414   ShadowingDecls.erase(I);
7415 }
7416 
7417 /// Check for conflict between this global or extern "C" declaration and
7418 /// previous global or extern "C" declarations. This is only used in C++.
7419 template<typename T>
7420 static bool checkGlobalOrExternCConflict(
7421     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7422   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7423   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7424 
7425   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7426     // The common case: this global doesn't conflict with any extern "C"
7427     // declaration.
7428     return false;
7429   }
7430 
7431   if (Prev) {
7432     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7433       // Both the old and new declarations have C language linkage. This is a
7434       // redeclaration.
7435       Previous.clear();
7436       Previous.addDecl(Prev);
7437       return true;
7438     }
7439 
7440     // This is a global, non-extern "C" declaration, and there is a previous
7441     // non-global extern "C" declaration. Diagnose if this is a variable
7442     // declaration.
7443     if (!isa<VarDecl>(ND))
7444       return false;
7445   } else {
7446     // The declaration is extern "C". Check for any declaration in the
7447     // translation unit which might conflict.
7448     if (IsGlobal) {
7449       // We have already performed the lookup into the translation unit.
7450       IsGlobal = false;
7451       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7452            I != E; ++I) {
7453         if (isa<VarDecl>(*I)) {
7454           Prev = *I;
7455           break;
7456         }
7457       }
7458     } else {
7459       DeclContext::lookup_result R =
7460           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7461       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7462            I != E; ++I) {
7463         if (isa<VarDecl>(*I)) {
7464           Prev = *I;
7465           break;
7466         }
7467         // FIXME: If we have any other entity with this name in global scope,
7468         // the declaration is ill-formed, but that is a defect: it breaks the
7469         // 'stat' hack, for instance. Only variables can have mangled name
7470         // clashes with extern "C" declarations, so only they deserve a
7471         // diagnostic.
7472       }
7473     }
7474 
7475     if (!Prev)
7476       return false;
7477   }
7478 
7479   // Use the first declaration's location to ensure we point at something which
7480   // is lexically inside an extern "C" linkage-spec.
7481   assert(Prev && "should have found a previous declaration to diagnose");
7482   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7483     Prev = FD->getFirstDecl();
7484   else
7485     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7486 
7487   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7488     << IsGlobal << ND;
7489   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7490     << IsGlobal;
7491   return false;
7492 }
7493 
7494 /// Apply special rules for handling extern "C" declarations. Returns \c true
7495 /// if we have found that this is a redeclaration of some prior entity.
7496 ///
7497 /// Per C++ [dcl.link]p6:
7498 ///   Two declarations [for a function or variable] with C language linkage
7499 ///   with the same name that appear in different scopes refer to the same
7500 ///   [entity]. An entity with C language linkage shall not be declared with
7501 ///   the same name as an entity in global scope.
7502 template<typename T>
7503 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7504                                                   LookupResult &Previous) {
7505   if (!S.getLangOpts().CPlusPlus) {
7506     // In C, when declaring a global variable, look for a corresponding 'extern'
7507     // variable declared in function scope. We don't need this in C++, because
7508     // we find local extern decls in the surrounding file-scope DeclContext.
7509     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7510       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7511         Previous.clear();
7512         Previous.addDecl(Prev);
7513         return true;
7514       }
7515     }
7516     return false;
7517   }
7518 
7519   // A declaration in the translation unit can conflict with an extern "C"
7520   // declaration.
7521   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7522     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7523 
7524   // An extern "C" declaration can conflict with a declaration in the
7525   // translation unit or can be a redeclaration of an extern "C" declaration
7526   // in another scope.
7527   if (isIncompleteDeclExternC(S,ND))
7528     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7529 
7530   // Neither global nor extern "C": nothing to do.
7531   return false;
7532 }
7533 
7534 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7535   // If the decl is already known invalid, don't check it.
7536   if (NewVD->isInvalidDecl())
7537     return;
7538 
7539   QualType T = NewVD->getType();
7540 
7541   // Defer checking an 'auto' type until its initializer is attached.
7542   if (T->isUndeducedType())
7543     return;
7544 
7545   if (NewVD->hasAttrs())
7546     CheckAlignasUnderalignment(NewVD);
7547 
7548   if (T->isObjCObjectType()) {
7549     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7550       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7551     T = Context.getObjCObjectPointerType(T);
7552     NewVD->setType(T);
7553   }
7554 
7555   // Emit an error if an address space was applied to decl with local storage.
7556   // This includes arrays of objects with address space qualifiers, but not
7557   // automatic variables that point to other address spaces.
7558   // ISO/IEC TR 18037 S5.1.2
7559   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7560       T.getAddressSpace() != LangAS::Default) {
7561     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7562     NewVD->setInvalidDecl();
7563     return;
7564   }
7565 
7566   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7567   // scope.
7568   if (getLangOpts().OpenCLVersion == 120 &&
7569       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7570       NewVD->isStaticLocal()) {
7571     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7572     NewVD->setInvalidDecl();
7573     return;
7574   }
7575 
7576   if (getLangOpts().OpenCL) {
7577     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7578     if (NewVD->hasAttr<BlocksAttr>()) {
7579       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7580       return;
7581     }
7582 
7583     if (T->isBlockPointerType()) {
7584       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7585       // can't use 'extern' storage class.
7586       if (!T.isConstQualified()) {
7587         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7588             << 0 /*const*/;
7589         NewVD->setInvalidDecl();
7590         return;
7591       }
7592       if (NewVD->hasExternalStorage()) {
7593         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7594         NewVD->setInvalidDecl();
7595         return;
7596       }
7597     }
7598     // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7599     // __constant address space.
7600     // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7601     // variables inside a function can also be declared in the global
7602     // address space.
7603     // C++ for OpenCL inherits rule from OpenCL C v2.0.
7604     // FIXME: Adding local AS in C++ for OpenCL might make sense.
7605     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7606         NewVD->hasExternalStorage()) {
7607       if (!T->isSamplerT() &&
7608           !(T.getAddressSpace() == LangAS::opencl_constant ||
7609             (T.getAddressSpace() == LangAS::opencl_global &&
7610              (getLangOpts().OpenCLVersion == 200 ||
7611               getLangOpts().OpenCLCPlusPlus)))) {
7612         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7613         if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7614           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7615               << Scope << "global or constant";
7616         else
7617           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7618               << Scope << "constant";
7619         NewVD->setInvalidDecl();
7620         return;
7621       }
7622     } else {
7623       if (T.getAddressSpace() == LangAS::opencl_global) {
7624         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7625             << 1 /*is any function*/ << "global";
7626         NewVD->setInvalidDecl();
7627         return;
7628       }
7629       if (T.getAddressSpace() == LangAS::opencl_constant ||
7630           T.getAddressSpace() == LangAS::opencl_local) {
7631         FunctionDecl *FD = getCurFunctionDecl();
7632         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7633         // in functions.
7634         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7635           if (T.getAddressSpace() == LangAS::opencl_constant)
7636             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7637                 << 0 /*non-kernel only*/ << "constant";
7638           else
7639             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7640                 << 0 /*non-kernel only*/ << "local";
7641           NewVD->setInvalidDecl();
7642           return;
7643         }
7644         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7645         // in the outermost scope of a kernel function.
7646         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7647           if (!getCurScope()->isFunctionScope()) {
7648             if (T.getAddressSpace() == LangAS::opencl_constant)
7649               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7650                   << "constant";
7651             else
7652               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7653                   << "local";
7654             NewVD->setInvalidDecl();
7655             return;
7656           }
7657         }
7658       } else if (T.getAddressSpace() != LangAS::opencl_private &&
7659                  // If we are parsing a template we didn't deduce an addr
7660                  // space yet.
7661                  T.getAddressSpace() != LangAS::Default) {
7662         // Do not allow other address spaces on automatic variable.
7663         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7664         NewVD->setInvalidDecl();
7665         return;
7666       }
7667     }
7668   }
7669 
7670   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7671       && !NewVD->hasAttr<BlocksAttr>()) {
7672     if (getLangOpts().getGC() != LangOptions::NonGC)
7673       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7674     else {
7675       assert(!getLangOpts().ObjCAutoRefCount);
7676       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7677     }
7678   }
7679 
7680   bool isVM = T->isVariablyModifiedType();
7681   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7682       NewVD->hasAttr<BlocksAttr>())
7683     setFunctionHasBranchProtectedScope();
7684 
7685   if ((isVM && NewVD->hasLinkage()) ||
7686       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7687     bool SizeIsNegative;
7688     llvm::APSInt Oversized;
7689     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7690         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7691     QualType FixedT;
7692     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
7693       FixedT = FixedTInfo->getType();
7694     else if (FixedTInfo) {
7695       // Type and type-as-written are canonically different. We need to fix up
7696       // both types separately.
7697       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7698                                                    Oversized);
7699     }
7700     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7701       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7702       // FIXME: This won't give the correct result for
7703       // int a[10][n];
7704       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7705 
7706       if (NewVD->isFileVarDecl())
7707         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7708         << SizeRange;
7709       else if (NewVD->isStaticLocal())
7710         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7711         << SizeRange;
7712       else
7713         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7714         << SizeRange;
7715       NewVD->setInvalidDecl();
7716       return;
7717     }
7718 
7719     if (!FixedTInfo) {
7720       if (NewVD->isFileVarDecl())
7721         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7722       else
7723         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7724       NewVD->setInvalidDecl();
7725       return;
7726     }
7727 
7728     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7729     NewVD->setType(FixedT);
7730     NewVD->setTypeSourceInfo(FixedTInfo);
7731   }
7732 
7733   if (T->isVoidType()) {
7734     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7735     //                    of objects and functions.
7736     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7737       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7738         << T;
7739       NewVD->setInvalidDecl();
7740       return;
7741     }
7742   }
7743 
7744   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7745     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7746     NewVD->setInvalidDecl();
7747     return;
7748   }
7749 
7750   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7751     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7752     NewVD->setInvalidDecl();
7753     return;
7754   }
7755 
7756   if (NewVD->isConstexpr() && !T->isDependentType() &&
7757       RequireLiteralType(NewVD->getLocation(), T,
7758                          diag::err_constexpr_var_non_literal)) {
7759     NewVD->setInvalidDecl();
7760     return;
7761   }
7762 }
7763 
7764 /// Perform semantic checking on a newly-created variable
7765 /// declaration.
7766 ///
7767 /// This routine performs all of the type-checking required for a
7768 /// variable declaration once it has been built. It is used both to
7769 /// check variables after they have been parsed and their declarators
7770 /// have been translated into a declaration, and to check variables
7771 /// that have been instantiated from a template.
7772 ///
7773 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7774 ///
7775 /// Returns true if the variable declaration is a redeclaration.
7776 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7777   CheckVariableDeclarationType(NewVD);
7778 
7779   // If the decl is already known invalid, don't check it.
7780   if (NewVD->isInvalidDecl())
7781     return false;
7782 
7783   // If we did not find anything by this name, look for a non-visible
7784   // extern "C" declaration with the same name.
7785   if (Previous.empty() &&
7786       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7787     Previous.setShadowed();
7788 
7789   if (!Previous.empty()) {
7790     MergeVarDecl(NewVD, Previous);
7791     return true;
7792   }
7793   return false;
7794 }
7795 
7796 namespace {
7797 struct FindOverriddenMethod {
7798   Sema *S;
7799   CXXMethodDecl *Method;
7800 
7801   /// Member lookup function that determines whether a given C++
7802   /// method overrides a method in a base class, to be used with
7803   /// CXXRecordDecl::lookupInBases().
7804   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7805     RecordDecl *BaseRecord =
7806         Specifier->getType()->castAs<RecordType>()->getDecl();
7807 
7808     DeclarationName Name = Method->getDeclName();
7809 
7810     // FIXME: Do we care about other names here too?
7811     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7812       // We really want to find the base class destructor here.
7813       QualType T = S->Context.getTypeDeclType(BaseRecord);
7814       CanQualType CT = S->Context.getCanonicalType(T);
7815 
7816       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7817     }
7818 
7819     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7820          Path.Decls = Path.Decls.slice(1)) {
7821       NamedDecl *D = Path.Decls.front();
7822       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7823         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7824           return true;
7825       }
7826     }
7827 
7828     return false;
7829   }
7830 };
7831 
7832 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7833 } // end anonymous namespace
7834 
7835 /// Report an error regarding overriding, along with any relevant
7836 /// overridden methods.
7837 ///
7838 /// \param DiagID the primary error to report.
7839 /// \param MD the overriding method.
7840 /// \param OEK which overrides to include as notes.
7841 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7842                             OverrideErrorKind OEK = OEK_All) {
7843   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7844   for (const CXXMethodDecl *O : MD->overridden_methods()) {
7845     // This check (& the OEK parameter) could be replaced by a predicate, but
7846     // without lambdas that would be overkill. This is still nicer than writing
7847     // out the diag loop 3 times.
7848     if ((OEK == OEK_All) ||
7849         (OEK == OEK_NonDeleted && !O->isDeleted()) ||
7850         (OEK == OEK_Deleted && O->isDeleted()))
7851       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7852   }
7853 }
7854 
7855 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7856 /// and if so, check that it's a valid override and remember it.
7857 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7858   // Look for methods in base classes that this method might override.
7859   CXXBasePaths Paths;
7860   FindOverriddenMethod FOM;
7861   FOM.Method = MD;
7862   FOM.S = this;
7863   bool hasDeletedOverridenMethods = false;
7864   bool hasNonDeletedOverridenMethods = false;
7865   bool AddedAny = false;
7866   if (DC->lookupInBases(FOM, Paths)) {
7867     for (auto *I : Paths.found_decls()) {
7868       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7869         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7870         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7871             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7872             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7873             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7874           hasDeletedOverridenMethods |= OldMD->isDeleted();
7875           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7876           AddedAny = true;
7877         }
7878       }
7879     }
7880   }
7881 
7882   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7883     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7884   }
7885   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7886     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7887   }
7888 
7889   return AddedAny;
7890 }
7891 
7892 namespace {
7893   // Struct for holding all of the extra arguments needed by
7894   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7895   struct ActOnFDArgs {
7896     Scope *S;
7897     Declarator &D;
7898     MultiTemplateParamsArg TemplateParamLists;
7899     bool AddToScope;
7900   };
7901 } // end anonymous namespace
7902 
7903 namespace {
7904 
7905 // Callback to only accept typo corrections that have a non-zero edit distance.
7906 // Also only accept corrections that have the same parent decl.
7907 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
7908  public:
7909   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7910                             CXXRecordDecl *Parent)
7911       : Context(Context), OriginalFD(TypoFD),
7912         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7913 
7914   bool ValidateCandidate(const TypoCorrection &candidate) override {
7915     if (candidate.getEditDistance() == 0)
7916       return false;
7917 
7918     SmallVector<unsigned, 1> MismatchedParams;
7919     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7920                                           CDeclEnd = candidate.end();
7921          CDecl != CDeclEnd; ++CDecl) {
7922       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7923 
7924       if (FD && !FD->hasBody() &&
7925           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7926         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7927           CXXRecordDecl *Parent = MD->getParent();
7928           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7929             return true;
7930         } else if (!ExpectedParent) {
7931           return true;
7932         }
7933       }
7934     }
7935 
7936     return false;
7937   }
7938 
7939   std::unique_ptr<CorrectionCandidateCallback> clone() override {
7940     return std::make_unique<DifferentNameValidatorCCC>(*this);
7941   }
7942 
7943  private:
7944   ASTContext &Context;
7945   FunctionDecl *OriginalFD;
7946   CXXRecordDecl *ExpectedParent;
7947 };
7948 
7949 } // end anonymous namespace
7950 
7951 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
7952   TypoCorrectedFunctionDefinitions.insert(F);
7953 }
7954 
7955 /// Generate diagnostics for an invalid function redeclaration.
7956 ///
7957 /// This routine handles generating the diagnostic messages for an invalid
7958 /// function redeclaration, including finding possible similar declarations
7959 /// or performing typo correction if there are no previous declarations with
7960 /// the same name.
7961 ///
7962 /// Returns a NamedDecl iff typo correction was performed and substituting in
7963 /// the new declaration name does not cause new errors.
7964 static NamedDecl *DiagnoseInvalidRedeclaration(
7965     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7966     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7967   DeclarationName Name = NewFD->getDeclName();
7968   DeclContext *NewDC = NewFD->getDeclContext();
7969   SmallVector<unsigned, 1> MismatchedParams;
7970   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7971   TypoCorrection Correction;
7972   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7973   unsigned DiagMsg =
7974     IsLocalFriend ? diag::err_no_matching_local_friend :
7975     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
7976     diag::err_member_decl_does_not_match;
7977   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7978                     IsLocalFriend ? Sema::LookupLocalFriendName
7979                                   : Sema::LookupOrdinaryName,
7980                     Sema::ForVisibleRedeclaration);
7981 
7982   NewFD->setInvalidDecl();
7983   if (IsLocalFriend)
7984     SemaRef.LookupName(Prev, S);
7985   else
7986     SemaRef.LookupQualifiedName(Prev, NewDC);
7987   assert(!Prev.isAmbiguous() &&
7988          "Cannot have an ambiguity in previous-declaration lookup");
7989   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7990   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
7991                                 MD ? MD->getParent() : nullptr);
7992   if (!Prev.empty()) {
7993     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7994          Func != FuncEnd; ++Func) {
7995       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7996       if (FD &&
7997           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7998         // Add 1 to the index so that 0 can mean the mismatch didn't
7999         // involve a parameter
8000         unsigned ParamNum =
8001             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8002         NearMatches.push_back(std::make_pair(FD, ParamNum));
8003       }
8004     }
8005   // If the qualified name lookup yielded nothing, try typo correction
8006   } else if ((Correction = SemaRef.CorrectTypo(
8007                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8008                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8009                   IsLocalFriend ? nullptr : NewDC))) {
8010     // Set up everything for the call to ActOnFunctionDeclarator
8011     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8012                               ExtraArgs.D.getIdentifierLoc());
8013     Previous.clear();
8014     Previous.setLookupName(Correction.getCorrection());
8015     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8016                                     CDeclEnd = Correction.end();
8017          CDecl != CDeclEnd; ++CDecl) {
8018       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8019       if (FD && !FD->hasBody() &&
8020           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8021         Previous.addDecl(FD);
8022       }
8023     }
8024     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8025 
8026     NamedDecl *Result;
8027     // Retry building the function declaration with the new previous
8028     // declarations, and with errors suppressed.
8029     {
8030       // Trap errors.
8031       Sema::SFINAETrap Trap(SemaRef);
8032 
8033       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8034       // pieces need to verify the typo-corrected C++ declaration and hopefully
8035       // eliminate the need for the parameter pack ExtraArgs.
8036       Result = SemaRef.ActOnFunctionDeclarator(
8037           ExtraArgs.S, ExtraArgs.D,
8038           Correction.getCorrectionDecl()->getDeclContext(),
8039           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8040           ExtraArgs.AddToScope);
8041 
8042       if (Trap.hasErrorOccurred())
8043         Result = nullptr;
8044     }
8045 
8046     if (Result) {
8047       // Determine which correction we picked.
8048       Decl *Canonical = Result->getCanonicalDecl();
8049       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8050            I != E; ++I)
8051         if ((*I)->getCanonicalDecl() == Canonical)
8052           Correction.setCorrectionDecl(*I);
8053 
8054       // Let Sema know about the correction.
8055       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8056       SemaRef.diagnoseTypo(
8057           Correction,
8058           SemaRef.PDiag(IsLocalFriend
8059                           ? diag::err_no_matching_local_friend_suggest
8060                           : diag::err_member_decl_does_not_match_suggest)
8061             << Name << NewDC << IsDefinition);
8062       return Result;
8063     }
8064 
8065     // Pretend the typo correction never occurred
8066     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8067                               ExtraArgs.D.getIdentifierLoc());
8068     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8069     Previous.clear();
8070     Previous.setLookupName(Name);
8071   }
8072 
8073   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8074       << Name << NewDC << IsDefinition << NewFD->getLocation();
8075 
8076   bool NewFDisConst = false;
8077   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8078     NewFDisConst = NewMD->isConst();
8079 
8080   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8081        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8082        NearMatch != NearMatchEnd; ++NearMatch) {
8083     FunctionDecl *FD = NearMatch->first;
8084     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8085     bool FDisConst = MD && MD->isConst();
8086     bool IsMember = MD || !IsLocalFriend;
8087 
8088     // FIXME: These notes are poorly worded for the local friend case.
8089     if (unsigned Idx = NearMatch->second) {
8090       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8091       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8092       if (Loc.isInvalid()) Loc = FD->getLocation();
8093       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8094                                  : diag::note_local_decl_close_param_match)
8095         << Idx << FDParam->getType()
8096         << NewFD->getParamDecl(Idx - 1)->getType();
8097     } else if (FDisConst != NewFDisConst) {
8098       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8099           << NewFDisConst << FD->getSourceRange().getEnd();
8100     } else
8101       SemaRef.Diag(FD->getLocation(),
8102                    IsMember ? diag::note_member_def_close_match
8103                             : diag::note_local_decl_close_match);
8104   }
8105   return nullptr;
8106 }
8107 
8108 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8109   switch (D.getDeclSpec().getStorageClassSpec()) {
8110   default: llvm_unreachable("Unknown storage class!");
8111   case DeclSpec::SCS_auto:
8112   case DeclSpec::SCS_register:
8113   case DeclSpec::SCS_mutable:
8114     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8115                  diag::err_typecheck_sclass_func);
8116     D.getMutableDeclSpec().ClearStorageClassSpecs();
8117     D.setInvalidType();
8118     break;
8119   case DeclSpec::SCS_unspecified: break;
8120   case DeclSpec::SCS_extern:
8121     if (D.getDeclSpec().isExternInLinkageSpec())
8122       return SC_None;
8123     return SC_Extern;
8124   case DeclSpec::SCS_static: {
8125     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8126       // C99 6.7.1p5:
8127       //   The declaration of an identifier for a function that has
8128       //   block scope shall have no explicit storage-class specifier
8129       //   other than extern
8130       // See also (C++ [dcl.stc]p4).
8131       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8132                    diag::err_static_block_func);
8133       break;
8134     } else
8135       return SC_Static;
8136   }
8137   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8138   }
8139 
8140   // No explicit storage class has already been returned
8141   return SC_None;
8142 }
8143 
8144 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8145                                            DeclContext *DC, QualType &R,
8146                                            TypeSourceInfo *TInfo,
8147                                            StorageClass SC,
8148                                            bool &IsVirtualOkay) {
8149   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8150   DeclarationName Name = NameInfo.getName();
8151 
8152   FunctionDecl *NewFD = nullptr;
8153   bool isInline = D.getDeclSpec().isInlineSpecified();
8154 
8155   if (!SemaRef.getLangOpts().CPlusPlus) {
8156     // Determine whether the function was written with a
8157     // prototype. This true when:
8158     //   - there is a prototype in the declarator, or
8159     //   - the type R of the function is some kind of typedef or other non-
8160     //     attributed reference to a type name (which eventually refers to a
8161     //     function type).
8162     bool HasPrototype =
8163       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8164       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8165 
8166     NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8167                                  R, TInfo, SC, isInline, HasPrototype,
8168                                  CSK_unspecified);
8169     if (D.isInvalidType())
8170       NewFD->setInvalidDecl();
8171 
8172     return NewFD;
8173   }
8174 
8175   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8176 
8177   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8178   if (ConstexprKind == CSK_constinit) {
8179     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8180                  diag::err_constexpr_wrong_decl_kind)
8181         << ConstexprKind;
8182     ConstexprKind = CSK_unspecified;
8183     D.getMutableDeclSpec().ClearConstexprSpec();
8184   }
8185 
8186   // Check that the return type is not an abstract class type.
8187   // For record types, this is done by the AbstractClassUsageDiagnoser once
8188   // the class has been completely parsed.
8189   if (!DC->isRecord() &&
8190       SemaRef.RequireNonAbstractType(
8191           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8192           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8193     D.setInvalidType();
8194 
8195   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8196     // This is a C++ constructor declaration.
8197     assert(DC->isRecord() &&
8198            "Constructors can only be declared in a member context");
8199 
8200     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8201     return CXXConstructorDecl::Create(
8202         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8203         TInfo, ExplicitSpecifier, isInline,
8204         /*isImplicitlyDeclared=*/false, ConstexprKind);
8205 
8206   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8207     // This is a C++ destructor declaration.
8208     if (DC->isRecord()) {
8209       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8210       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8211       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8212           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8213           isInline,
8214           /*isImplicitlyDeclared=*/false, ConstexprKind);
8215 
8216       // If the destructor needs an implicit exception specification, set it
8217       // now. FIXME: It'd be nice to be able to create the right type to start
8218       // with, but the type needs to reference the destructor declaration.
8219       if (SemaRef.getLangOpts().CPlusPlus11)
8220         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8221 
8222       IsVirtualOkay = true;
8223       return NewDD;
8224 
8225     } else {
8226       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8227       D.setInvalidType();
8228 
8229       // Create a FunctionDecl to satisfy the function definition parsing
8230       // code path.
8231       return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8232                                   D.getIdentifierLoc(), Name, R, TInfo, SC,
8233                                   isInline,
8234                                   /*hasPrototype=*/true, ConstexprKind);
8235     }
8236 
8237   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8238     if (!DC->isRecord()) {
8239       SemaRef.Diag(D.getIdentifierLoc(),
8240            diag::err_conv_function_not_member);
8241       return nullptr;
8242     }
8243 
8244     SemaRef.CheckConversionDeclarator(D, R, SC);
8245     if (D.isInvalidType())
8246       return nullptr;
8247 
8248     IsVirtualOkay = true;
8249     return CXXConversionDecl::Create(
8250         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8251         TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation());
8252 
8253   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8254     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8255 
8256     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8257                                          ExplicitSpecifier, NameInfo, R, TInfo,
8258                                          D.getEndLoc());
8259   } else if (DC->isRecord()) {
8260     // If the name of the function is the same as the name of the record,
8261     // then this must be an invalid constructor that has a return type.
8262     // (The parser checks for a return type and makes the declarator a
8263     // constructor if it has no return type).
8264     if (Name.getAsIdentifierInfo() &&
8265         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8266       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8267         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8268         << SourceRange(D.getIdentifierLoc());
8269       return nullptr;
8270     }
8271 
8272     // This is a C++ method declaration.
8273     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8274         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8275         TInfo, SC, isInline, ConstexprKind, SourceLocation());
8276     IsVirtualOkay = !Ret->isStatic();
8277     return Ret;
8278   } else {
8279     bool isFriend =
8280         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8281     if (!isFriend && SemaRef.CurContext->isRecord())
8282       return nullptr;
8283 
8284     // Determine whether the function was written with a
8285     // prototype. This true when:
8286     //   - we're in C++ (where every function has a prototype),
8287     return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8288                                 R, TInfo, SC, isInline, true /*HasPrototype*/,
8289                                 ConstexprKind);
8290   }
8291 }
8292 
8293 enum OpenCLParamType {
8294   ValidKernelParam,
8295   PtrPtrKernelParam,
8296   PtrKernelParam,
8297   InvalidAddrSpacePtrKernelParam,
8298   InvalidKernelParam,
8299   RecordKernelParam
8300 };
8301 
8302 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8303   // Size dependent types are just typedefs to normal integer types
8304   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8305   // integers other than by their names.
8306   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8307 
8308   // Remove typedefs one by one until we reach a typedef
8309   // for a size dependent type.
8310   QualType DesugaredTy = Ty;
8311   do {
8312     ArrayRef<StringRef> Names(SizeTypeNames);
8313     auto Match = llvm::find(Names, DesugaredTy.getAsString());
8314     if (Names.end() != Match)
8315       return true;
8316 
8317     Ty = DesugaredTy;
8318     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8319   } while (DesugaredTy != Ty);
8320 
8321   return false;
8322 }
8323 
8324 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8325   if (PT->isPointerType()) {
8326     QualType PointeeType = PT->getPointeeType();
8327     if (PointeeType->isPointerType())
8328       return PtrPtrKernelParam;
8329     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8330         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8331         PointeeType.getAddressSpace() == LangAS::Default)
8332       return InvalidAddrSpacePtrKernelParam;
8333     return PtrKernelParam;
8334   }
8335 
8336   // OpenCL v1.2 s6.9.k:
8337   // Arguments to kernel functions in a program cannot be declared with the
8338   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8339   // uintptr_t or a struct and/or union that contain fields declared to be one
8340   // of these built-in scalar types.
8341   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8342     return InvalidKernelParam;
8343 
8344   if (PT->isImageType())
8345     return PtrKernelParam;
8346 
8347   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8348     return InvalidKernelParam;
8349 
8350   // OpenCL extension spec v1.2 s9.5:
8351   // This extension adds support for half scalar and vector types as built-in
8352   // types that can be used for arithmetic operations, conversions etc.
8353   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8354     return InvalidKernelParam;
8355 
8356   if (PT->isRecordType())
8357     return RecordKernelParam;
8358 
8359   // Look into an array argument to check if it has a forbidden type.
8360   if (PT->isArrayType()) {
8361     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8362     // Call ourself to check an underlying type of an array. Since the
8363     // getPointeeOrArrayElementType returns an innermost type which is not an
8364     // array, this recursive call only happens once.
8365     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8366   }
8367 
8368   return ValidKernelParam;
8369 }
8370 
8371 static void checkIsValidOpenCLKernelParameter(
8372   Sema &S,
8373   Declarator &D,
8374   ParmVarDecl *Param,
8375   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8376   QualType PT = Param->getType();
8377 
8378   // Cache the valid types we encounter to avoid rechecking structs that are
8379   // used again
8380   if (ValidTypes.count(PT.getTypePtr()))
8381     return;
8382 
8383   switch (getOpenCLKernelParameterType(S, PT)) {
8384   case PtrPtrKernelParam:
8385     // OpenCL v1.2 s6.9.a:
8386     // A kernel function argument cannot be declared as a
8387     // pointer to a pointer type.
8388     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8389     D.setInvalidType();
8390     return;
8391 
8392   case InvalidAddrSpacePtrKernelParam:
8393     // OpenCL v1.0 s6.5:
8394     // __kernel function arguments declared to be a pointer of a type can point
8395     // to one of the following address spaces only : __global, __local or
8396     // __constant.
8397     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8398     D.setInvalidType();
8399     return;
8400 
8401     // OpenCL v1.2 s6.9.k:
8402     // Arguments to kernel functions in a program cannot be declared with the
8403     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8404     // uintptr_t or a struct and/or union that contain fields declared to be
8405     // one of these built-in scalar types.
8406 
8407   case InvalidKernelParam:
8408     // OpenCL v1.2 s6.8 n:
8409     // A kernel function argument cannot be declared
8410     // of event_t type.
8411     // Do not diagnose half type since it is diagnosed as invalid argument
8412     // type for any function elsewhere.
8413     if (!PT->isHalfType()) {
8414       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8415 
8416       // Explain what typedefs are involved.
8417       const TypedefType *Typedef = nullptr;
8418       while ((Typedef = PT->getAs<TypedefType>())) {
8419         SourceLocation Loc = Typedef->getDecl()->getLocation();
8420         // SourceLocation may be invalid for a built-in type.
8421         if (Loc.isValid())
8422           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8423         PT = Typedef->desugar();
8424       }
8425     }
8426 
8427     D.setInvalidType();
8428     return;
8429 
8430   case PtrKernelParam:
8431   case ValidKernelParam:
8432     ValidTypes.insert(PT.getTypePtr());
8433     return;
8434 
8435   case RecordKernelParam:
8436     break;
8437   }
8438 
8439   // Track nested structs we will inspect
8440   SmallVector<const Decl *, 4> VisitStack;
8441 
8442   // Track where we are in the nested structs. Items will migrate from
8443   // VisitStack to HistoryStack as we do the DFS for bad field.
8444   SmallVector<const FieldDecl *, 4> HistoryStack;
8445   HistoryStack.push_back(nullptr);
8446 
8447   // At this point we already handled everything except of a RecordType or
8448   // an ArrayType of a RecordType.
8449   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8450   const RecordType *RecTy =
8451       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8452   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8453 
8454   VisitStack.push_back(RecTy->getDecl());
8455   assert(VisitStack.back() && "First decl null?");
8456 
8457   do {
8458     const Decl *Next = VisitStack.pop_back_val();
8459     if (!Next) {
8460       assert(!HistoryStack.empty());
8461       // Found a marker, we have gone up a level
8462       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8463         ValidTypes.insert(Hist->getType().getTypePtr());
8464 
8465       continue;
8466     }
8467 
8468     // Adds everything except the original parameter declaration (which is not a
8469     // field itself) to the history stack.
8470     const RecordDecl *RD;
8471     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8472       HistoryStack.push_back(Field);
8473 
8474       QualType FieldTy = Field->getType();
8475       // Other field types (known to be valid or invalid) are handled while we
8476       // walk around RecordDecl::fields().
8477       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8478              "Unexpected type.");
8479       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8480 
8481       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8482     } else {
8483       RD = cast<RecordDecl>(Next);
8484     }
8485 
8486     // Add a null marker so we know when we've gone back up a level
8487     VisitStack.push_back(nullptr);
8488 
8489     for (const auto *FD : RD->fields()) {
8490       QualType QT = FD->getType();
8491 
8492       if (ValidTypes.count(QT.getTypePtr()))
8493         continue;
8494 
8495       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8496       if (ParamType == ValidKernelParam)
8497         continue;
8498 
8499       if (ParamType == RecordKernelParam) {
8500         VisitStack.push_back(FD);
8501         continue;
8502       }
8503 
8504       // OpenCL v1.2 s6.9.p:
8505       // Arguments to kernel functions that are declared to be a struct or union
8506       // do not allow OpenCL objects to be passed as elements of the struct or
8507       // union.
8508       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8509           ParamType == InvalidAddrSpacePtrKernelParam) {
8510         S.Diag(Param->getLocation(),
8511                diag::err_record_with_pointers_kernel_param)
8512           << PT->isUnionType()
8513           << PT;
8514       } else {
8515         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8516       }
8517 
8518       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8519           << OrigRecDecl->getDeclName();
8520 
8521       // We have an error, now let's go back up through history and show where
8522       // the offending field came from
8523       for (ArrayRef<const FieldDecl *>::const_iterator
8524                I = HistoryStack.begin() + 1,
8525                E = HistoryStack.end();
8526            I != E; ++I) {
8527         const FieldDecl *OuterField = *I;
8528         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8529           << OuterField->getType();
8530       }
8531 
8532       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8533         << QT->isPointerType()
8534         << QT;
8535       D.setInvalidType();
8536       return;
8537     }
8538   } while (!VisitStack.empty());
8539 }
8540 
8541 /// Find the DeclContext in which a tag is implicitly declared if we see an
8542 /// elaborated type specifier in the specified context, and lookup finds
8543 /// nothing.
8544 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8545   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8546     DC = DC->getParent();
8547   return DC;
8548 }
8549 
8550 /// Find the Scope in which a tag is implicitly declared if we see an
8551 /// elaborated type specifier in the specified context, and lookup finds
8552 /// nothing.
8553 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8554   while (S->isClassScope() ||
8555          (LangOpts.CPlusPlus &&
8556           S->isFunctionPrototypeScope()) ||
8557          ((S->getFlags() & Scope::DeclScope) == 0) ||
8558          (S->getEntity() && S->getEntity()->isTransparentContext()))
8559     S = S->getParent();
8560   return S;
8561 }
8562 
8563 NamedDecl*
8564 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8565                               TypeSourceInfo *TInfo, LookupResult &Previous,
8566                               MultiTemplateParamsArg TemplateParamLists,
8567                               bool &AddToScope) {
8568   QualType R = TInfo->getType();
8569 
8570   assert(R->isFunctionType());
8571 
8572   // TODO: consider using NameInfo for diagnostic.
8573   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8574   DeclarationName Name = NameInfo.getName();
8575   StorageClass SC = getFunctionStorageClass(*this, D);
8576 
8577   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8578     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8579          diag::err_invalid_thread)
8580       << DeclSpec::getSpecifierName(TSCS);
8581 
8582   if (D.isFirstDeclarationOfMember())
8583     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8584                            D.getIdentifierLoc());
8585 
8586   bool isFriend = false;
8587   FunctionTemplateDecl *FunctionTemplate = nullptr;
8588   bool isMemberSpecialization = false;
8589   bool isFunctionTemplateSpecialization = false;
8590 
8591   bool isDependentClassScopeExplicitSpecialization = false;
8592   bool HasExplicitTemplateArgs = false;
8593   TemplateArgumentListInfo TemplateArgs;
8594 
8595   bool isVirtualOkay = false;
8596 
8597   DeclContext *OriginalDC = DC;
8598   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8599 
8600   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8601                                               isVirtualOkay);
8602   if (!NewFD) return nullptr;
8603 
8604   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8605     NewFD->setTopLevelDeclInObjCContainer();
8606 
8607   // Set the lexical context. If this is a function-scope declaration, or has a
8608   // C++ scope specifier, or is the object of a friend declaration, the lexical
8609   // context will be different from the semantic context.
8610   NewFD->setLexicalDeclContext(CurContext);
8611 
8612   if (IsLocalExternDecl)
8613     NewFD->setLocalExternDecl();
8614 
8615   if (getLangOpts().CPlusPlus) {
8616     bool isInline = D.getDeclSpec().isInlineSpecified();
8617     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8618     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
8619     isFriend = D.getDeclSpec().isFriendSpecified();
8620     if (isFriend && !isInline && D.isFunctionDefinition()) {
8621       // C++ [class.friend]p5
8622       //   A function can be defined in a friend declaration of a
8623       //   class . . . . Such a function is implicitly inline.
8624       NewFD->setImplicitlyInline();
8625     }
8626 
8627     // If this is a method defined in an __interface, and is not a constructor
8628     // or an overloaded operator, then set the pure flag (isVirtual will already
8629     // return true).
8630     if (const CXXRecordDecl *Parent =
8631           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8632       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8633         NewFD->setPure(true);
8634 
8635       // C++ [class.union]p2
8636       //   A union can have member functions, but not virtual functions.
8637       if (isVirtual && Parent->isUnion())
8638         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8639     }
8640 
8641     SetNestedNameSpecifier(*this, NewFD, D);
8642     isMemberSpecialization = false;
8643     isFunctionTemplateSpecialization = false;
8644     if (D.isInvalidType())
8645       NewFD->setInvalidDecl();
8646 
8647     // Match up the template parameter lists with the scope specifier, then
8648     // determine whether we have a template or a template specialization.
8649     bool Invalid = false;
8650     if (TemplateParameterList *TemplateParams =
8651             MatchTemplateParametersToScopeSpecifier(
8652                 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8653                 D.getCXXScopeSpec(),
8654                 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8655                     ? D.getName().TemplateId
8656                     : nullptr,
8657                 TemplateParamLists, isFriend, isMemberSpecialization,
8658                 Invalid)) {
8659       if (TemplateParams->size() > 0) {
8660         // This is a function template
8661 
8662         // Check that we can declare a template here.
8663         if (CheckTemplateDeclScope(S, TemplateParams))
8664           NewFD->setInvalidDecl();
8665 
8666         // A destructor cannot be a template.
8667         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8668           Diag(NewFD->getLocation(), diag::err_destructor_template);
8669           NewFD->setInvalidDecl();
8670         }
8671 
8672         // If we're adding a template to a dependent context, we may need to
8673         // rebuilding some of the types used within the template parameter list,
8674         // now that we know what the current instantiation is.
8675         if (DC->isDependentContext()) {
8676           ContextRAII SavedContext(*this, DC);
8677           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8678             Invalid = true;
8679         }
8680 
8681         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8682                                                         NewFD->getLocation(),
8683                                                         Name, TemplateParams,
8684                                                         NewFD);
8685         FunctionTemplate->setLexicalDeclContext(CurContext);
8686         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8687 
8688         // For source fidelity, store the other template param lists.
8689         if (TemplateParamLists.size() > 1) {
8690           NewFD->setTemplateParameterListsInfo(Context,
8691                                                TemplateParamLists.drop_back(1));
8692         }
8693       } else {
8694         // This is a function template specialization.
8695         isFunctionTemplateSpecialization = true;
8696         // For source fidelity, store all the template param lists.
8697         if (TemplateParamLists.size() > 0)
8698           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8699 
8700         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8701         if (isFriend) {
8702           // We want to remove the "template<>", found here.
8703           SourceRange RemoveRange = TemplateParams->getSourceRange();
8704 
8705           // If we remove the template<> and the name is not a
8706           // template-id, we're actually silently creating a problem:
8707           // the friend declaration will refer to an untemplated decl,
8708           // and clearly the user wants a template specialization.  So
8709           // we need to insert '<>' after the name.
8710           SourceLocation InsertLoc;
8711           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8712             InsertLoc = D.getName().getSourceRange().getEnd();
8713             InsertLoc = getLocForEndOfToken(InsertLoc);
8714           }
8715 
8716           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8717             << Name << RemoveRange
8718             << FixItHint::CreateRemoval(RemoveRange)
8719             << FixItHint::CreateInsertion(InsertLoc, "<>");
8720         }
8721       }
8722     } else {
8723       // All template param lists were matched against the scope specifier:
8724       // this is NOT (an explicit specialization of) a template.
8725       if (TemplateParamLists.size() > 0)
8726         // For source fidelity, store all the template param lists.
8727         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8728     }
8729 
8730     if (Invalid) {
8731       NewFD->setInvalidDecl();
8732       if (FunctionTemplate)
8733         FunctionTemplate->setInvalidDecl();
8734     }
8735 
8736     // C++ [dcl.fct.spec]p5:
8737     //   The virtual specifier shall only be used in declarations of
8738     //   nonstatic class member functions that appear within a
8739     //   member-specification of a class declaration; see 10.3.
8740     //
8741     if (isVirtual && !NewFD->isInvalidDecl()) {
8742       if (!isVirtualOkay) {
8743         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8744              diag::err_virtual_non_function);
8745       } else if (!CurContext->isRecord()) {
8746         // 'virtual' was specified outside of the class.
8747         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8748              diag::err_virtual_out_of_class)
8749           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8750       } else if (NewFD->getDescribedFunctionTemplate()) {
8751         // C++ [temp.mem]p3:
8752         //  A member function template shall not be virtual.
8753         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8754              diag::err_virtual_member_function_template)
8755           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8756       } else {
8757         // Okay: Add virtual to the method.
8758         NewFD->setVirtualAsWritten(true);
8759       }
8760 
8761       if (getLangOpts().CPlusPlus14 &&
8762           NewFD->getReturnType()->isUndeducedType())
8763         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8764     }
8765 
8766     if (getLangOpts().CPlusPlus14 &&
8767         (NewFD->isDependentContext() ||
8768          (isFriend && CurContext->isDependentContext())) &&
8769         NewFD->getReturnType()->isUndeducedType()) {
8770       // If the function template is referenced directly (for instance, as a
8771       // member of the current instantiation), pretend it has a dependent type.
8772       // This is not really justified by the standard, but is the only sane
8773       // thing to do.
8774       // FIXME: For a friend function, we have not marked the function as being
8775       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8776       const FunctionProtoType *FPT =
8777           NewFD->getType()->castAs<FunctionProtoType>();
8778       QualType Result =
8779           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8780       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8781                                              FPT->getExtProtoInfo()));
8782     }
8783 
8784     // C++ [dcl.fct.spec]p3:
8785     //  The inline specifier shall not appear on a block scope function
8786     //  declaration.
8787     if (isInline && !NewFD->isInvalidDecl()) {
8788       if (CurContext->isFunctionOrMethod()) {
8789         // 'inline' is not allowed on block scope function declaration.
8790         Diag(D.getDeclSpec().getInlineSpecLoc(),
8791              diag::err_inline_declaration_block_scope) << Name
8792           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8793       }
8794     }
8795 
8796     // C++ [dcl.fct.spec]p6:
8797     //  The explicit specifier shall be used only in the declaration of a
8798     //  constructor or conversion function within its class definition;
8799     //  see 12.3.1 and 12.3.2.
8800     if (hasExplicit && !NewFD->isInvalidDecl() &&
8801         !isa<CXXDeductionGuideDecl>(NewFD)) {
8802       if (!CurContext->isRecord()) {
8803         // 'explicit' was specified outside of the class.
8804         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8805              diag::err_explicit_out_of_class)
8806             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
8807       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8808                  !isa<CXXConversionDecl>(NewFD)) {
8809         // 'explicit' was specified on a function that wasn't a constructor
8810         // or conversion function.
8811         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8812              diag::err_explicit_non_ctor_or_conv_function)
8813             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
8814       }
8815     }
8816 
8817     if (ConstexprSpecKind ConstexprKind =
8818             D.getDeclSpec().getConstexprSpecifier()) {
8819       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8820       // are implicitly inline.
8821       NewFD->setImplicitlyInline();
8822 
8823       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8824       // be either constructors or to return a literal type. Therefore,
8825       // destructors cannot be declared constexpr.
8826       if (isa<CXXDestructorDecl>(NewFD) && !getLangOpts().CPlusPlus2a) {
8827         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
8828             << ConstexprKind;
8829       }
8830     }
8831 
8832     // If __module_private__ was specified, mark the function accordingly.
8833     if (D.getDeclSpec().isModulePrivateSpecified()) {
8834       if (isFunctionTemplateSpecialization) {
8835         SourceLocation ModulePrivateLoc
8836           = D.getDeclSpec().getModulePrivateSpecLoc();
8837         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8838           << 0
8839           << FixItHint::CreateRemoval(ModulePrivateLoc);
8840       } else {
8841         NewFD->setModulePrivate();
8842         if (FunctionTemplate)
8843           FunctionTemplate->setModulePrivate();
8844       }
8845     }
8846 
8847     if (isFriend) {
8848       if (FunctionTemplate) {
8849         FunctionTemplate->setObjectOfFriendDecl();
8850         FunctionTemplate->setAccess(AS_public);
8851       }
8852       NewFD->setObjectOfFriendDecl();
8853       NewFD->setAccess(AS_public);
8854     }
8855 
8856     // If a function is defined as defaulted or deleted, mark it as such now.
8857     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8858     // definition kind to FDK_Definition.
8859     switch (D.getFunctionDefinitionKind()) {
8860       case FDK_Declaration:
8861       case FDK_Definition:
8862         break;
8863 
8864       case FDK_Defaulted:
8865         NewFD->setDefaulted();
8866         break;
8867 
8868       case FDK_Deleted:
8869         NewFD->setDeletedAsWritten();
8870         break;
8871     }
8872 
8873     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8874         D.isFunctionDefinition()) {
8875       // C++ [class.mfct]p2:
8876       //   A member function may be defined (8.4) in its class definition, in
8877       //   which case it is an inline member function (7.1.2)
8878       NewFD->setImplicitlyInline();
8879     }
8880 
8881     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8882         !CurContext->isRecord()) {
8883       // C++ [class.static]p1:
8884       //   A data or function member of a class may be declared static
8885       //   in a class definition, in which case it is a static member of
8886       //   the class.
8887 
8888       // Complain about the 'static' specifier if it's on an out-of-line
8889       // member function definition.
8890 
8891       // MSVC permits the use of a 'static' storage specifier on an out-of-line
8892       // member function template declaration and class member template
8893       // declaration (MSVC versions before 2015), warn about this.
8894       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8895            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
8896              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
8897            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
8898            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
8899         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8900     }
8901 
8902     // C++11 [except.spec]p15:
8903     //   A deallocation function with no exception-specification is treated
8904     //   as if it were specified with noexcept(true).
8905     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8906     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8907          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8908         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8909       NewFD->setType(Context.getFunctionType(
8910           FPT->getReturnType(), FPT->getParamTypes(),
8911           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8912   }
8913 
8914   // Filter out previous declarations that don't match the scope.
8915   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8916                        D.getCXXScopeSpec().isNotEmpty() ||
8917                        isMemberSpecialization ||
8918                        isFunctionTemplateSpecialization);
8919 
8920   // Handle GNU asm-label extension (encoded as an attribute).
8921   if (Expr *E = (Expr*) D.getAsmLabel()) {
8922     // The parser guarantees this is a string.
8923     StringLiteral *SE = cast<StringLiteral>(E);
8924     NewFD->addAttr(::new (Context)
8925                        AsmLabelAttr(Context, SE->getStrTokenLoc(0),
8926                                     SE->getString(), /*IsLiteralLabel=*/true));
8927   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8928     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8929       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8930     if (I != ExtnameUndeclaredIdentifiers.end()) {
8931       if (isDeclExternC(NewFD)) {
8932         NewFD->addAttr(I->second);
8933         ExtnameUndeclaredIdentifiers.erase(I);
8934       } else
8935         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8936             << /*Variable*/0 << NewFD;
8937     }
8938   }
8939 
8940   // Copy the parameter declarations from the declarator D to the function
8941   // declaration NewFD, if they are available.  First scavenge them into Params.
8942   SmallVector<ParmVarDecl*, 16> Params;
8943   unsigned FTIIdx;
8944   if (D.isFunctionDeclarator(FTIIdx)) {
8945     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8946 
8947     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8948     // function that takes no arguments, not a function that takes a
8949     // single void argument.
8950     // We let through "const void" here because Sema::GetTypeForDeclarator
8951     // already checks for that case.
8952     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8953       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8954         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8955         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8956         Param->setDeclContext(NewFD);
8957         Params.push_back(Param);
8958 
8959         if (Param->isInvalidDecl())
8960           NewFD->setInvalidDecl();
8961       }
8962     }
8963 
8964     if (!getLangOpts().CPlusPlus) {
8965       // In C, find all the tag declarations from the prototype and move them
8966       // into the function DeclContext. Remove them from the surrounding tag
8967       // injection context of the function, which is typically but not always
8968       // the TU.
8969       DeclContext *PrototypeTagContext =
8970           getTagInjectionContext(NewFD->getLexicalDeclContext());
8971       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8972         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8973 
8974         // We don't want to reparent enumerators. Look at their parent enum
8975         // instead.
8976         if (!TD) {
8977           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8978             TD = cast<EnumDecl>(ECD->getDeclContext());
8979         }
8980         if (!TD)
8981           continue;
8982         DeclContext *TagDC = TD->getLexicalDeclContext();
8983         if (!TagDC->containsDecl(TD))
8984           continue;
8985         TagDC->removeDecl(TD);
8986         TD->setDeclContext(NewFD);
8987         NewFD->addDecl(TD);
8988 
8989         // Preserve the lexical DeclContext if it is not the surrounding tag
8990         // injection context of the FD. In this example, the semantic context of
8991         // E will be f and the lexical context will be S, while both the
8992         // semantic and lexical contexts of S will be f:
8993         //   void f(struct S { enum E { a } f; } s);
8994         if (TagDC != PrototypeTagContext)
8995           TD->setLexicalDeclContext(TagDC);
8996       }
8997     }
8998   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8999     // When we're declaring a function with a typedef, typeof, etc as in the
9000     // following example, we'll need to synthesize (unnamed)
9001     // parameters for use in the declaration.
9002     //
9003     // @code
9004     // typedef void fn(int);
9005     // fn f;
9006     // @endcode
9007 
9008     // Synthesize a parameter for each argument type.
9009     for (const auto &AI : FT->param_types()) {
9010       ParmVarDecl *Param =
9011           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9012       Param->setScopeInfo(0, Params.size());
9013       Params.push_back(Param);
9014     }
9015   } else {
9016     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9017            "Should not need args for typedef of non-prototype fn");
9018   }
9019 
9020   // Finally, we know we have the right number of parameters, install them.
9021   NewFD->setParams(Params);
9022 
9023   if (D.getDeclSpec().isNoreturnSpecified())
9024     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9025                                            D.getDeclSpec().getNoreturnSpecLoc(),
9026                                            AttributeCommonInfo::AS_Keyword));
9027 
9028   // Functions returning a variably modified type violate C99 6.7.5.2p2
9029   // because all functions have linkage.
9030   if (!NewFD->isInvalidDecl() &&
9031       NewFD->getReturnType()->isVariablyModifiedType()) {
9032     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9033     NewFD->setInvalidDecl();
9034   }
9035 
9036   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9037   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9038       !NewFD->hasAttr<SectionAttr>())
9039     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9040         Context, PragmaClangTextSection.SectionName,
9041         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9042 
9043   // Apply an implicit SectionAttr if #pragma code_seg is active.
9044   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9045       !NewFD->hasAttr<SectionAttr>()) {
9046     NewFD->addAttr(SectionAttr::CreateImplicit(
9047         Context, CodeSegStack.CurrentValue->getString(),
9048         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9049         SectionAttr::Declspec_allocate));
9050     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9051                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9052                          ASTContext::PSF_Read,
9053                      NewFD))
9054       NewFD->dropAttr<SectionAttr>();
9055   }
9056 
9057   // Apply an implicit CodeSegAttr from class declspec or
9058   // apply an implicit SectionAttr from #pragma code_seg if active.
9059   if (!NewFD->hasAttr<CodeSegAttr>()) {
9060     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9061                                                                  D.isFunctionDefinition())) {
9062       NewFD->addAttr(SAttr);
9063     }
9064   }
9065 
9066   // Handle attributes.
9067   ProcessDeclAttributes(S, NewFD, D);
9068 
9069   if (getLangOpts().OpenCL) {
9070     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9071     // type declaration will generate a compilation error.
9072     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9073     if (AddressSpace != LangAS::Default) {
9074       Diag(NewFD->getLocation(),
9075            diag::err_opencl_return_value_with_address_space);
9076       NewFD->setInvalidDecl();
9077     }
9078   }
9079 
9080   if (!getLangOpts().CPlusPlus) {
9081     // Perform semantic checking on the function declaration.
9082     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9083       CheckMain(NewFD, D.getDeclSpec());
9084 
9085     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9086       CheckMSVCRTEntryPoint(NewFD);
9087 
9088     if (!NewFD->isInvalidDecl())
9089       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9090                                                   isMemberSpecialization));
9091     else if (!Previous.empty())
9092       // Recover gracefully from an invalid redeclaration.
9093       D.setRedeclaration(true);
9094     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9095             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9096            "previous declaration set still overloaded");
9097 
9098     // Diagnose no-prototype function declarations with calling conventions that
9099     // don't support variadic calls. Only do this in C and do it after merging
9100     // possibly prototyped redeclarations.
9101     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9102     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9103       CallingConv CC = FT->getExtInfo().getCC();
9104       if (!supportsVariadicCall(CC)) {
9105         // Windows system headers sometimes accidentally use stdcall without
9106         // (void) parameters, so we relax this to a warning.
9107         int DiagID =
9108             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9109         Diag(NewFD->getLocation(), DiagID)
9110             << FunctionType::getNameForCallConv(CC);
9111       }
9112     }
9113 
9114    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9115        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9116      checkNonTrivialCUnion(NewFD->getReturnType(),
9117                            NewFD->getReturnTypeSourceRange().getBegin(),
9118                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9119   } else {
9120     // C++11 [replacement.functions]p3:
9121     //  The program's definitions shall not be specified as inline.
9122     //
9123     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9124     //
9125     // Suppress the diagnostic if the function is __attribute__((used)), since
9126     // that forces an external definition to be emitted.
9127     if (D.getDeclSpec().isInlineSpecified() &&
9128         NewFD->isReplaceableGlobalAllocationFunction() &&
9129         !NewFD->hasAttr<UsedAttr>())
9130       Diag(D.getDeclSpec().getInlineSpecLoc(),
9131            diag::ext_operator_new_delete_declared_inline)
9132         << NewFD->getDeclName();
9133 
9134     // If the declarator is a template-id, translate the parser's template
9135     // argument list into our AST format.
9136     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9137       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9138       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9139       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9140       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9141                                          TemplateId->NumArgs);
9142       translateTemplateArguments(TemplateArgsPtr,
9143                                  TemplateArgs);
9144 
9145       HasExplicitTemplateArgs = true;
9146 
9147       if (NewFD->isInvalidDecl()) {
9148         HasExplicitTemplateArgs = false;
9149       } else if (FunctionTemplate) {
9150         // Function template with explicit template arguments.
9151         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9152           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9153 
9154         HasExplicitTemplateArgs = false;
9155       } else {
9156         assert((isFunctionTemplateSpecialization ||
9157                 D.getDeclSpec().isFriendSpecified()) &&
9158                "should have a 'template<>' for this decl");
9159         // "friend void foo<>(int);" is an implicit specialization decl.
9160         isFunctionTemplateSpecialization = true;
9161       }
9162     } else if (isFriend && isFunctionTemplateSpecialization) {
9163       // This combination is only possible in a recovery case;  the user
9164       // wrote something like:
9165       //   template <> friend void foo(int);
9166       // which we're recovering from as if the user had written:
9167       //   friend void foo<>(int);
9168       // Go ahead and fake up a template id.
9169       HasExplicitTemplateArgs = true;
9170       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9171       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9172     }
9173 
9174     // We do not add HD attributes to specializations here because
9175     // they may have different constexpr-ness compared to their
9176     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9177     // may end up with different effective targets. Instead, a
9178     // specialization inherits its target attributes from its template
9179     // in the CheckFunctionTemplateSpecialization() call below.
9180     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9181       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9182 
9183     // If it's a friend (and only if it's a friend), it's possible
9184     // that either the specialized function type or the specialized
9185     // template is dependent, and therefore matching will fail.  In
9186     // this case, don't check the specialization yet.
9187     bool InstantiationDependent = false;
9188     if (isFunctionTemplateSpecialization && isFriend &&
9189         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9190          TemplateSpecializationType::anyDependentTemplateArguments(
9191             TemplateArgs,
9192             InstantiationDependent))) {
9193       assert(HasExplicitTemplateArgs &&
9194              "friend function specialization without template args");
9195       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9196                                                        Previous))
9197         NewFD->setInvalidDecl();
9198     } else if (isFunctionTemplateSpecialization) {
9199       if (CurContext->isDependentContext() && CurContext->isRecord()
9200           && !isFriend) {
9201         isDependentClassScopeExplicitSpecialization = true;
9202       } else if (!NewFD->isInvalidDecl() &&
9203                  CheckFunctionTemplateSpecialization(
9204                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9205                      Previous))
9206         NewFD->setInvalidDecl();
9207 
9208       // C++ [dcl.stc]p1:
9209       //   A storage-class-specifier shall not be specified in an explicit
9210       //   specialization (14.7.3)
9211       FunctionTemplateSpecializationInfo *Info =
9212           NewFD->getTemplateSpecializationInfo();
9213       if (Info && SC != SC_None) {
9214         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9215           Diag(NewFD->getLocation(),
9216                diag::err_explicit_specialization_inconsistent_storage_class)
9217             << SC
9218             << FixItHint::CreateRemoval(
9219                                       D.getDeclSpec().getStorageClassSpecLoc());
9220 
9221         else
9222           Diag(NewFD->getLocation(),
9223                diag::ext_explicit_specialization_storage_class)
9224             << FixItHint::CreateRemoval(
9225                                       D.getDeclSpec().getStorageClassSpecLoc());
9226       }
9227     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9228       if (CheckMemberSpecialization(NewFD, Previous))
9229           NewFD->setInvalidDecl();
9230     }
9231 
9232     // Perform semantic checking on the function declaration.
9233     if (!isDependentClassScopeExplicitSpecialization) {
9234       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9235         CheckMain(NewFD, D.getDeclSpec());
9236 
9237       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9238         CheckMSVCRTEntryPoint(NewFD);
9239 
9240       if (!NewFD->isInvalidDecl())
9241         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9242                                                     isMemberSpecialization));
9243       else if (!Previous.empty())
9244         // Recover gracefully from an invalid redeclaration.
9245         D.setRedeclaration(true);
9246     }
9247 
9248     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9249             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9250            "previous declaration set still overloaded");
9251 
9252     NamedDecl *PrincipalDecl = (FunctionTemplate
9253                                 ? cast<NamedDecl>(FunctionTemplate)
9254                                 : NewFD);
9255 
9256     if (isFriend && NewFD->getPreviousDecl()) {
9257       AccessSpecifier Access = AS_public;
9258       if (!NewFD->isInvalidDecl())
9259         Access = NewFD->getPreviousDecl()->getAccess();
9260 
9261       NewFD->setAccess(Access);
9262       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9263     }
9264 
9265     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9266         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9267       PrincipalDecl->setNonMemberOperator();
9268 
9269     // If we have a function template, check the template parameter
9270     // list. This will check and merge default template arguments.
9271     if (FunctionTemplate) {
9272       FunctionTemplateDecl *PrevTemplate =
9273                                      FunctionTemplate->getPreviousDecl();
9274       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9275                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9276                                     : nullptr,
9277                             D.getDeclSpec().isFriendSpecified()
9278                               ? (D.isFunctionDefinition()
9279                                    ? TPC_FriendFunctionTemplateDefinition
9280                                    : TPC_FriendFunctionTemplate)
9281                               : (D.getCXXScopeSpec().isSet() &&
9282                                  DC && DC->isRecord() &&
9283                                  DC->isDependentContext())
9284                                   ? TPC_ClassTemplateMember
9285                                   : TPC_FunctionTemplate);
9286     }
9287 
9288     if (NewFD->isInvalidDecl()) {
9289       // Ignore all the rest of this.
9290     } else if (!D.isRedeclaration()) {
9291       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9292                                        AddToScope };
9293       // Fake up an access specifier if it's supposed to be a class member.
9294       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9295         NewFD->setAccess(AS_public);
9296 
9297       // Qualified decls generally require a previous declaration.
9298       if (D.getCXXScopeSpec().isSet()) {
9299         // ...with the major exception of templated-scope or
9300         // dependent-scope friend declarations.
9301 
9302         // TODO: we currently also suppress this check in dependent
9303         // contexts because (1) the parameter depth will be off when
9304         // matching friend templates and (2) we might actually be
9305         // selecting a friend based on a dependent factor.  But there
9306         // are situations where these conditions don't apply and we
9307         // can actually do this check immediately.
9308         //
9309         // Unless the scope is dependent, it's always an error if qualified
9310         // redeclaration lookup found nothing at all. Diagnose that now;
9311         // nothing will diagnose that error later.
9312         if (isFriend &&
9313             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9314              (!Previous.empty() && CurContext->isDependentContext()))) {
9315           // ignore these
9316         } else {
9317           // The user tried to provide an out-of-line definition for a
9318           // function that is a member of a class or namespace, but there
9319           // was no such member function declared (C++ [class.mfct]p2,
9320           // C++ [namespace.memdef]p2). For example:
9321           //
9322           // class X {
9323           //   void f() const;
9324           // };
9325           //
9326           // void X::f() { } // ill-formed
9327           //
9328           // Complain about this problem, and attempt to suggest close
9329           // matches (e.g., those that differ only in cv-qualifiers and
9330           // whether the parameter types are references).
9331 
9332           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9333                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9334             AddToScope = ExtraArgs.AddToScope;
9335             return Result;
9336           }
9337         }
9338 
9339         // Unqualified local friend declarations are required to resolve
9340         // to something.
9341       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9342         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9343                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9344           AddToScope = ExtraArgs.AddToScope;
9345           return Result;
9346         }
9347       }
9348     } else if (!D.isFunctionDefinition() &&
9349                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9350                !isFriend && !isFunctionTemplateSpecialization &&
9351                !isMemberSpecialization) {
9352       // An out-of-line member function declaration must also be a
9353       // definition (C++ [class.mfct]p2).
9354       // Note that this is not the case for explicit specializations of
9355       // function templates or member functions of class templates, per
9356       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9357       // extension for compatibility with old SWIG code which likes to
9358       // generate them.
9359       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9360         << D.getCXXScopeSpec().getRange();
9361     }
9362   }
9363 
9364   ProcessPragmaWeak(S, NewFD);
9365   checkAttributesAfterMerging(*this, *NewFD);
9366 
9367   AddKnownFunctionAttributes(NewFD);
9368 
9369   if (NewFD->hasAttr<OverloadableAttr>() &&
9370       !NewFD->getType()->getAs<FunctionProtoType>()) {
9371     Diag(NewFD->getLocation(),
9372          diag::err_attribute_overloadable_no_prototype)
9373       << NewFD;
9374 
9375     // Turn this into a variadic function with no parameters.
9376     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9377     FunctionProtoType::ExtProtoInfo EPI(
9378         Context.getDefaultCallingConvention(true, false));
9379     EPI.Variadic = true;
9380     EPI.ExtInfo = FT->getExtInfo();
9381 
9382     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9383     NewFD->setType(R);
9384   }
9385 
9386   // If there's a #pragma GCC visibility in scope, and this isn't a class
9387   // member, set the visibility of this function.
9388   if (!DC->isRecord() && NewFD->isExternallyVisible())
9389     AddPushedVisibilityAttribute(NewFD);
9390 
9391   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9392   // marking the function.
9393   AddCFAuditedAttribute(NewFD);
9394 
9395   // If this is a function definition, check if we have to apply optnone due to
9396   // a pragma.
9397   if(D.isFunctionDefinition())
9398     AddRangeBasedOptnone(NewFD);
9399 
9400   // If this is the first declaration of an extern C variable, update
9401   // the map of such variables.
9402   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9403       isIncompleteDeclExternC(*this, NewFD))
9404     RegisterLocallyScopedExternCDecl(NewFD, S);
9405 
9406   // Set this FunctionDecl's range up to the right paren.
9407   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9408 
9409   if (D.isRedeclaration() && !Previous.empty()) {
9410     NamedDecl *Prev = Previous.getRepresentativeDecl();
9411     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9412                                    isMemberSpecialization ||
9413                                        isFunctionTemplateSpecialization,
9414                                    D.isFunctionDefinition());
9415   }
9416 
9417   if (getLangOpts().CUDA) {
9418     IdentifierInfo *II = NewFD->getIdentifier();
9419     if (II && II->isStr(getCudaConfigureFuncName()) &&
9420         !NewFD->isInvalidDecl() &&
9421         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9422       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9423         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9424             << getCudaConfigureFuncName();
9425       Context.setcudaConfigureCallDecl(NewFD);
9426     }
9427 
9428     // Variadic functions, other than a *declaration* of printf, are not allowed
9429     // in device-side CUDA code, unless someone passed
9430     // -fcuda-allow-variadic-functions.
9431     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9432         (NewFD->hasAttr<CUDADeviceAttr>() ||
9433          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9434         !(II && II->isStr("printf") && NewFD->isExternC() &&
9435           !D.isFunctionDefinition())) {
9436       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9437     }
9438   }
9439 
9440   MarkUnusedFileScopedDecl(NewFD);
9441 
9442 
9443 
9444   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9445     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9446     if ((getLangOpts().OpenCLVersion >= 120)
9447         && (SC == SC_Static)) {
9448       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9449       D.setInvalidType();
9450     }
9451 
9452     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9453     if (!NewFD->getReturnType()->isVoidType()) {
9454       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9455       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9456           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9457                                 : FixItHint());
9458       D.setInvalidType();
9459     }
9460 
9461     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9462     for (auto Param : NewFD->parameters())
9463       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9464 
9465     if (getLangOpts().OpenCLCPlusPlus) {
9466       if (DC->isRecord()) {
9467         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9468         D.setInvalidType();
9469       }
9470       if (FunctionTemplate) {
9471         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9472         D.setInvalidType();
9473       }
9474     }
9475   }
9476 
9477   if (getLangOpts().CPlusPlus) {
9478     if (FunctionTemplate) {
9479       if (NewFD->isInvalidDecl())
9480         FunctionTemplate->setInvalidDecl();
9481       return FunctionTemplate;
9482     }
9483 
9484     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9485       CompleteMemberSpecialization(NewFD, Previous);
9486   }
9487 
9488   for (const ParmVarDecl *Param : NewFD->parameters()) {
9489     QualType PT = Param->getType();
9490 
9491     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9492     // types.
9493     if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
9494       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9495         QualType ElemTy = PipeTy->getElementType();
9496           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9497             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9498             D.setInvalidType();
9499           }
9500       }
9501     }
9502   }
9503 
9504   // Here we have an function template explicit specialization at class scope.
9505   // The actual specialization will be postponed to template instatiation
9506   // time via the ClassScopeFunctionSpecializationDecl node.
9507   if (isDependentClassScopeExplicitSpecialization) {
9508     ClassScopeFunctionSpecializationDecl *NewSpec =
9509                          ClassScopeFunctionSpecializationDecl::Create(
9510                                 Context, CurContext, NewFD->getLocation(),
9511                                 cast<CXXMethodDecl>(NewFD),
9512                                 HasExplicitTemplateArgs, TemplateArgs);
9513     CurContext->addDecl(NewSpec);
9514     AddToScope = false;
9515   }
9516 
9517   // Diagnose availability attributes. Availability cannot be used on functions
9518   // that are run during load/unload.
9519   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9520     if (NewFD->hasAttr<ConstructorAttr>()) {
9521       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9522           << 1;
9523       NewFD->dropAttr<AvailabilityAttr>();
9524     }
9525     if (NewFD->hasAttr<DestructorAttr>()) {
9526       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9527           << 2;
9528       NewFD->dropAttr<AvailabilityAttr>();
9529     }
9530   }
9531 
9532   return NewFD;
9533 }
9534 
9535 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
9536 /// when __declspec(code_seg) "is applied to a class, all member functions of
9537 /// the class and nested classes -- this includes compiler-generated special
9538 /// member functions -- are put in the specified segment."
9539 /// The actual behavior is a little more complicated. The Microsoft compiler
9540 /// won't check outer classes if there is an active value from #pragma code_seg.
9541 /// The CodeSeg is always applied from the direct parent but only from outer
9542 /// classes when the #pragma code_seg stack is empty. See:
9543 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9544 /// available since MS has removed the page.
9545 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9546   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9547   if (!Method)
9548     return nullptr;
9549   const CXXRecordDecl *Parent = Method->getParent();
9550   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9551     Attr *NewAttr = SAttr->clone(S.getASTContext());
9552     NewAttr->setImplicit(true);
9553     return NewAttr;
9554   }
9555 
9556   // The Microsoft compiler won't check outer classes for the CodeSeg
9557   // when the #pragma code_seg stack is active.
9558   if (S.CodeSegStack.CurrentValue)
9559    return nullptr;
9560 
9561   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9562     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9563       Attr *NewAttr = SAttr->clone(S.getASTContext());
9564       NewAttr->setImplicit(true);
9565       return NewAttr;
9566     }
9567   }
9568   return nullptr;
9569 }
9570 
9571 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9572 /// containing class. Otherwise it will return implicit SectionAttr if the
9573 /// function is a definition and there is an active value on CodeSegStack
9574 /// (from the current #pragma code-seg value).
9575 ///
9576 /// \param FD Function being declared.
9577 /// \param IsDefinition Whether it is a definition or just a declarartion.
9578 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
9579 ///          nullptr if no attribute should be added.
9580 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9581                                                        bool IsDefinition) {
9582   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9583     return A;
9584   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9585       CodeSegStack.CurrentValue)
9586     return SectionAttr::CreateImplicit(
9587         getASTContext(), CodeSegStack.CurrentValue->getString(),
9588         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9589         SectionAttr::Declspec_allocate);
9590   return nullptr;
9591 }
9592 
9593 /// Determines if we can perform a correct type check for \p D as a
9594 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
9595 /// best-effort check.
9596 ///
9597 /// \param NewD The new declaration.
9598 /// \param OldD The old declaration.
9599 /// \param NewT The portion of the type of the new declaration to check.
9600 /// \param OldT The portion of the type of the old declaration to check.
9601 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
9602                                           QualType NewT, QualType OldT) {
9603   if (!NewD->getLexicalDeclContext()->isDependentContext())
9604     return true;
9605 
9606   // For dependently-typed local extern declarations and friends, we can't
9607   // perform a correct type check in general until instantiation:
9608   //
9609   //   int f();
9610   //   template<typename T> void g() { T f(); }
9611   //
9612   // (valid if g() is only instantiated with T = int).
9613   if (NewT->isDependentType() &&
9614       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
9615     return false;
9616 
9617   // Similarly, if the previous declaration was a dependent local extern
9618   // declaration, we don't really know its type yet.
9619   if (OldT->isDependentType() && OldD->isLocalExternDecl())
9620     return false;
9621 
9622   return true;
9623 }
9624 
9625 /// Checks if the new declaration declared in dependent context must be
9626 /// put in the same redeclaration chain as the specified declaration.
9627 ///
9628 /// \param D Declaration that is checked.
9629 /// \param PrevDecl Previous declaration found with proper lookup method for the
9630 ///                 same declaration name.
9631 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9632 ///          belongs to.
9633 ///
9634 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9635   if (!D->getLexicalDeclContext()->isDependentContext())
9636     return true;
9637 
9638   // Don't chain dependent friend function definitions until instantiation, to
9639   // permit cases like
9640   //
9641   //   void func();
9642   //   template<typename T> class C1 { friend void func() {} };
9643   //   template<typename T> class C2 { friend void func() {} };
9644   //
9645   // ... which is valid if only one of C1 and C2 is ever instantiated.
9646   //
9647   // FIXME: This need only apply to function definitions. For now, we proxy
9648   // this by checking for a file-scope function. We do not want this to apply
9649   // to friend declarations nominating member functions, because that gets in
9650   // the way of access checks.
9651   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
9652     return false;
9653 
9654   auto *VD = dyn_cast<ValueDecl>(D);
9655   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
9656   return !VD || !PrevVD ||
9657          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
9658                                         PrevVD->getType());
9659 }
9660 
9661 /// Check the target attribute of the function for MultiVersion
9662 /// validity.
9663 ///
9664 /// Returns true if there was an error, false otherwise.
9665 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9666   const auto *TA = FD->getAttr<TargetAttr>();
9667   assert(TA && "MultiVersion Candidate requires a target attribute");
9668   TargetAttr::ParsedTargetAttr ParseInfo = TA->parse();
9669   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9670   enum ErrType { Feature = 0, Architecture = 1 };
9671 
9672   if (!ParseInfo.Architecture.empty() &&
9673       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
9674     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9675         << Architecture << ParseInfo.Architecture;
9676     return true;
9677   }
9678 
9679   for (const auto &Feat : ParseInfo.Features) {
9680     auto BareFeat = StringRef{Feat}.substr(1);
9681     if (Feat[0] == '-') {
9682       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9683           << Feature << ("no-" + BareFeat).str();
9684       return true;
9685     }
9686 
9687     if (!TargetInfo.validateCpuSupports(BareFeat) ||
9688         !TargetInfo.isValidFeatureName(BareFeat)) {
9689       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9690           << Feature << BareFeat;
9691       return true;
9692     }
9693   }
9694   return false;
9695 }
9696 
9697 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD,
9698                                          MultiVersionKind MVType) {
9699   for (const Attr *A : FD->attrs()) {
9700     switch (A->getKind()) {
9701     case attr::CPUDispatch:
9702     case attr::CPUSpecific:
9703       if (MVType != MultiVersionKind::CPUDispatch &&
9704           MVType != MultiVersionKind::CPUSpecific)
9705         return true;
9706       break;
9707     case attr::Target:
9708       if (MVType != MultiVersionKind::Target)
9709         return true;
9710       break;
9711     default:
9712       return true;
9713     }
9714   }
9715   return false;
9716 }
9717 
9718 bool Sema::areMultiversionVariantFunctionsCompatible(
9719     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
9720     const PartialDiagnostic &NoProtoDiagID,
9721     const PartialDiagnosticAt &NoteCausedDiagIDAt,
9722     const PartialDiagnosticAt &NoSupportDiagIDAt,
9723     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
9724     bool ConstexprSupported, bool CLinkageMayDiffer) {
9725   enum DoesntSupport {
9726     FuncTemplates = 0,
9727     VirtFuncs = 1,
9728     DeducedReturn = 2,
9729     Constructors = 3,
9730     Destructors = 4,
9731     DeletedFuncs = 5,
9732     DefaultedFuncs = 6,
9733     ConstexprFuncs = 7,
9734     ConstevalFuncs = 8,
9735   };
9736   enum Different {
9737     CallingConv = 0,
9738     ReturnType = 1,
9739     ConstexprSpec = 2,
9740     InlineSpec = 3,
9741     StorageClass = 4,
9742     Linkage = 5,
9743   };
9744 
9745   if (OldFD && !OldFD->getType()->getAs<FunctionProtoType>()) {
9746     Diag(OldFD->getLocation(), NoProtoDiagID);
9747     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
9748     return true;
9749   }
9750 
9751   if (!NewFD->getType()->getAs<FunctionProtoType>())
9752     return Diag(NewFD->getLocation(), NoProtoDiagID);
9753 
9754   if (!TemplatesSupported &&
9755       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9756     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9757            << FuncTemplates;
9758 
9759   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
9760     if (NewCXXFD->isVirtual())
9761       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9762              << VirtFuncs;
9763 
9764     if (isa<CXXConstructorDecl>(NewCXXFD))
9765       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9766              << Constructors;
9767 
9768     if (isa<CXXDestructorDecl>(NewCXXFD))
9769       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9770              << Destructors;
9771   }
9772 
9773   if (NewFD->isDeleted())
9774     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9775            << DeletedFuncs;
9776 
9777   if (NewFD->isDefaulted())
9778     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9779            << DefaultedFuncs;
9780 
9781   if (!ConstexprSupported && NewFD->isConstexpr())
9782     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9783            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
9784 
9785   QualType NewQType = Context.getCanonicalType(NewFD->getType());
9786   const auto *NewType = cast<FunctionType>(NewQType);
9787   QualType NewReturnType = NewType->getReturnType();
9788 
9789   if (NewReturnType->isUndeducedType())
9790     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9791            << DeducedReturn;
9792 
9793   // Ensure the return type is identical.
9794   if (OldFD) {
9795     QualType OldQType = Context.getCanonicalType(OldFD->getType());
9796     const auto *OldType = cast<FunctionType>(OldQType);
9797     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
9798     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
9799 
9800     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
9801       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
9802 
9803     QualType OldReturnType = OldType->getReturnType();
9804 
9805     if (OldReturnType != NewReturnType)
9806       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
9807 
9808     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
9809       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
9810 
9811     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
9812       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
9813 
9814     if (OldFD->getStorageClass() != NewFD->getStorageClass())
9815       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass;
9816 
9817     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
9818       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
9819 
9820     if (CheckEquivalentExceptionSpec(
9821             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
9822             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
9823       return true;
9824   }
9825   return false;
9826 }
9827 
9828 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
9829                                              const FunctionDecl *NewFD,
9830                                              bool CausesMV,
9831                                              MultiVersionKind MVType) {
9832   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9833     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9834     if (OldFD)
9835       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9836     return true;
9837   }
9838 
9839   bool IsCPUSpecificCPUDispatchMVType =
9840       MVType == MultiVersionKind::CPUDispatch ||
9841       MVType == MultiVersionKind::CPUSpecific;
9842 
9843   // For now, disallow all other attributes.  These should be opt-in, but
9844   // an analysis of all of them is a future FIXME.
9845   if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) {
9846     S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
9847         << IsCPUSpecificCPUDispatchMVType;
9848     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9849     return true;
9850   }
9851 
9852   if (HasNonMultiVersionAttributes(NewFD, MVType))
9853     return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
9854            << IsCPUSpecificCPUDispatchMVType;
9855 
9856   // Only allow transition to MultiVersion if it hasn't been used.
9857   if (OldFD && CausesMV && OldFD->isUsed(false))
9858     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
9859 
9860   return S.areMultiversionVariantFunctionsCompatible(
9861       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
9862       PartialDiagnosticAt(NewFD->getLocation(),
9863                           S.PDiag(diag::note_multiversioning_caused_here)),
9864       PartialDiagnosticAt(NewFD->getLocation(),
9865                           S.PDiag(diag::err_multiversion_doesnt_support)
9866                               << IsCPUSpecificCPUDispatchMVType),
9867       PartialDiagnosticAt(NewFD->getLocation(),
9868                           S.PDiag(diag::err_multiversion_diff)),
9869       /*TemplatesSupported=*/false,
9870       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
9871       /*CLinkageMayDiffer=*/false);
9872 }
9873 
9874 /// Check the validity of a multiversion function declaration that is the
9875 /// first of its kind. Also sets the multiversion'ness' of the function itself.
9876 ///
9877 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9878 ///
9879 /// Returns true if there was an error, false otherwise.
9880 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
9881                                            MultiVersionKind MVType,
9882                                            const TargetAttr *TA) {
9883   assert(MVType != MultiVersionKind::None &&
9884          "Function lacks multiversion attribute");
9885 
9886   // Target only causes MV if it is default, otherwise this is a normal
9887   // function.
9888   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
9889     return false;
9890 
9891   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
9892     FD->setInvalidDecl();
9893     return true;
9894   }
9895 
9896   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
9897     FD->setInvalidDecl();
9898     return true;
9899   }
9900 
9901   FD->setIsMultiVersion();
9902   return false;
9903 }
9904 
9905 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
9906   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
9907     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
9908       return true;
9909   }
9910 
9911   return false;
9912 }
9913 
9914 static bool CheckTargetCausesMultiVersioning(
9915     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
9916     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
9917     LookupResult &Previous) {
9918   const auto *OldTA = OldFD->getAttr<TargetAttr>();
9919   TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse();
9920   // Sort order doesn't matter, it just needs to be consistent.
9921   llvm::sort(NewParsed.Features);
9922 
9923   // If the old decl is NOT MultiVersioned yet, and we don't cause that
9924   // to change, this is a simple redeclaration.
9925   if (!NewTA->isDefaultVersion() &&
9926       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
9927     return false;
9928 
9929   // Otherwise, this decl causes MultiVersioning.
9930   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9931     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9932     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9933     NewFD->setInvalidDecl();
9934     return true;
9935   }
9936 
9937   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
9938                                        MultiVersionKind::Target)) {
9939     NewFD->setInvalidDecl();
9940     return true;
9941   }
9942 
9943   if (CheckMultiVersionValue(S, NewFD)) {
9944     NewFD->setInvalidDecl();
9945     return true;
9946   }
9947 
9948   // If this is 'default', permit the forward declaration.
9949   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
9950     Redeclaration = true;
9951     OldDecl = OldFD;
9952     OldFD->setIsMultiVersion();
9953     NewFD->setIsMultiVersion();
9954     return false;
9955   }
9956 
9957   if (CheckMultiVersionValue(S, OldFD)) {
9958     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9959     NewFD->setInvalidDecl();
9960     return true;
9961   }
9962 
9963   TargetAttr::ParsedTargetAttr OldParsed =
9964       OldTA->parse(std::less<std::string>());
9965 
9966   if (OldParsed == NewParsed) {
9967     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9968     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9969     NewFD->setInvalidDecl();
9970     return true;
9971   }
9972 
9973   for (const auto *FD : OldFD->redecls()) {
9974     const auto *CurTA = FD->getAttr<TargetAttr>();
9975     // We allow forward declarations before ANY multiversioning attributes, but
9976     // nothing after the fact.
9977     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
9978         (!CurTA || CurTA->isInherited())) {
9979       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
9980           << 0;
9981       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9982       NewFD->setInvalidDecl();
9983       return true;
9984     }
9985   }
9986 
9987   OldFD->setIsMultiVersion();
9988   NewFD->setIsMultiVersion();
9989   Redeclaration = false;
9990   MergeTypeWithPrevious = false;
9991   OldDecl = nullptr;
9992   Previous.clear();
9993   return false;
9994 }
9995 
9996 /// Check the validity of a new function declaration being added to an existing
9997 /// multiversioned declaration collection.
9998 static bool CheckMultiVersionAdditionalDecl(
9999     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10000     MultiVersionKind NewMVType, const TargetAttr *NewTA,
10001     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10002     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10003     LookupResult &Previous) {
10004 
10005   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10006   // Disallow mixing of multiversioning types.
10007   if ((OldMVType == MultiVersionKind::Target &&
10008        NewMVType != MultiVersionKind::Target) ||
10009       (NewMVType == MultiVersionKind::Target &&
10010        OldMVType != MultiVersionKind::Target)) {
10011     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10012     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10013     NewFD->setInvalidDecl();
10014     return true;
10015   }
10016 
10017   TargetAttr::ParsedTargetAttr NewParsed;
10018   if (NewTA) {
10019     NewParsed = NewTA->parse();
10020     llvm::sort(NewParsed.Features);
10021   }
10022 
10023   bool UseMemberUsingDeclRules =
10024       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10025 
10026   // Next, check ALL non-overloads to see if this is a redeclaration of a
10027   // previous member of the MultiVersion set.
10028   for (NamedDecl *ND : Previous) {
10029     FunctionDecl *CurFD = ND->getAsFunction();
10030     if (!CurFD)
10031       continue;
10032     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10033       continue;
10034 
10035     if (NewMVType == MultiVersionKind::Target) {
10036       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10037       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10038         NewFD->setIsMultiVersion();
10039         Redeclaration = true;
10040         OldDecl = ND;
10041         return false;
10042       }
10043 
10044       TargetAttr::ParsedTargetAttr CurParsed =
10045           CurTA->parse(std::less<std::string>());
10046       if (CurParsed == NewParsed) {
10047         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10048         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10049         NewFD->setInvalidDecl();
10050         return true;
10051       }
10052     } else {
10053       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10054       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10055       // Handle CPUDispatch/CPUSpecific versions.
10056       // Only 1 CPUDispatch function is allowed, this will make it go through
10057       // the redeclaration errors.
10058       if (NewMVType == MultiVersionKind::CPUDispatch &&
10059           CurFD->hasAttr<CPUDispatchAttr>()) {
10060         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10061             std::equal(
10062                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10063                 NewCPUDisp->cpus_begin(),
10064                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10065                   return Cur->getName() == New->getName();
10066                 })) {
10067           NewFD->setIsMultiVersion();
10068           Redeclaration = true;
10069           OldDecl = ND;
10070           return false;
10071         }
10072 
10073         // If the declarations don't match, this is an error condition.
10074         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10075         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10076         NewFD->setInvalidDecl();
10077         return true;
10078       }
10079       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10080 
10081         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10082             std::equal(
10083                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10084                 NewCPUSpec->cpus_begin(),
10085                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10086                   return Cur->getName() == New->getName();
10087                 })) {
10088           NewFD->setIsMultiVersion();
10089           Redeclaration = true;
10090           OldDecl = ND;
10091           return false;
10092         }
10093 
10094         // Only 1 version of CPUSpecific is allowed for each CPU.
10095         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10096           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10097             if (CurII == NewII) {
10098               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10099                   << NewII;
10100               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10101               NewFD->setInvalidDecl();
10102               return true;
10103             }
10104           }
10105         }
10106       }
10107       // If the two decls aren't the same MVType, there is no possible error
10108       // condition.
10109     }
10110   }
10111 
10112   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10113   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10114   // handled in the attribute adding step.
10115   if (NewMVType == MultiVersionKind::Target &&
10116       CheckMultiVersionValue(S, NewFD)) {
10117     NewFD->setInvalidDecl();
10118     return true;
10119   }
10120 
10121   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10122                                        !OldFD->isMultiVersion(), NewMVType)) {
10123     NewFD->setInvalidDecl();
10124     return true;
10125   }
10126 
10127   // Permit forward declarations in the case where these two are compatible.
10128   if (!OldFD->isMultiVersion()) {
10129     OldFD->setIsMultiVersion();
10130     NewFD->setIsMultiVersion();
10131     Redeclaration = true;
10132     OldDecl = OldFD;
10133     return false;
10134   }
10135 
10136   NewFD->setIsMultiVersion();
10137   Redeclaration = false;
10138   MergeTypeWithPrevious = false;
10139   OldDecl = nullptr;
10140   Previous.clear();
10141   return false;
10142 }
10143 
10144 
10145 /// Check the validity of a mulitversion function declaration.
10146 /// Also sets the multiversion'ness' of the function itself.
10147 ///
10148 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10149 ///
10150 /// Returns true if there was an error, false otherwise.
10151 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10152                                       bool &Redeclaration, NamedDecl *&OldDecl,
10153                                       bool &MergeTypeWithPrevious,
10154                                       LookupResult &Previous) {
10155   const auto *NewTA = NewFD->getAttr<TargetAttr>();
10156   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10157   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10158 
10159   // Mixing Multiversioning types is prohibited.
10160   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
10161       (NewCPUDisp && NewCPUSpec)) {
10162     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10163     NewFD->setInvalidDecl();
10164     return true;
10165   }
10166 
10167   MultiVersionKind  MVType = NewFD->getMultiVersionKind();
10168 
10169   // Main isn't allowed to become a multiversion function, however it IS
10170   // permitted to have 'main' be marked with the 'target' optimization hint.
10171   if (NewFD->isMain()) {
10172     if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10173         MVType == MultiVersionKind::CPUDispatch ||
10174         MVType == MultiVersionKind::CPUSpecific) {
10175       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10176       NewFD->setInvalidDecl();
10177       return true;
10178     }
10179     return false;
10180   }
10181 
10182   if (!OldDecl || !OldDecl->getAsFunction() ||
10183       OldDecl->getDeclContext()->getRedeclContext() !=
10184           NewFD->getDeclContext()->getRedeclContext()) {
10185     // If there's no previous declaration, AND this isn't attempting to cause
10186     // multiversioning, this isn't an error condition.
10187     if (MVType == MultiVersionKind::None)
10188       return false;
10189     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10190   }
10191 
10192   FunctionDecl *OldFD = OldDecl->getAsFunction();
10193 
10194   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10195     return false;
10196 
10197   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10198     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10199         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10200     NewFD->setInvalidDecl();
10201     return true;
10202   }
10203 
10204   // Handle the target potentially causes multiversioning case.
10205   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10206     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10207                                             Redeclaration, OldDecl,
10208                                             MergeTypeWithPrevious, Previous);
10209 
10210   // At this point, we have a multiversion function decl (in OldFD) AND an
10211   // appropriate attribute in the current function decl.  Resolve that these are
10212   // still compatible with previous declarations.
10213   return CheckMultiVersionAdditionalDecl(
10214       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10215       OldDecl, MergeTypeWithPrevious, Previous);
10216 }
10217 
10218 /// Perform semantic checking of a new function declaration.
10219 ///
10220 /// Performs semantic analysis of the new function declaration
10221 /// NewFD. This routine performs all semantic checking that does not
10222 /// require the actual declarator involved in the declaration, and is
10223 /// used both for the declaration of functions as they are parsed
10224 /// (called via ActOnDeclarator) and for the declaration of functions
10225 /// that have been instantiated via C++ template instantiation (called
10226 /// via InstantiateDecl).
10227 ///
10228 /// \param IsMemberSpecialization whether this new function declaration is
10229 /// a member specialization (that replaces any definition provided by the
10230 /// previous declaration).
10231 ///
10232 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10233 ///
10234 /// \returns true if the function declaration is a redeclaration.
10235 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10236                                     LookupResult &Previous,
10237                                     bool IsMemberSpecialization) {
10238   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10239          "Variably modified return types are not handled here");
10240 
10241   // Determine whether the type of this function should be merged with
10242   // a previous visible declaration. This never happens for functions in C++,
10243   // and always happens in C if the previous declaration was visible.
10244   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10245                                !Previous.isShadowed();
10246 
10247   bool Redeclaration = false;
10248   NamedDecl *OldDecl = nullptr;
10249   bool MayNeedOverloadableChecks = false;
10250 
10251   // Merge or overload the declaration with an existing declaration of
10252   // the same name, if appropriate.
10253   if (!Previous.empty()) {
10254     // Determine whether NewFD is an overload of PrevDecl or
10255     // a declaration that requires merging. If it's an overload,
10256     // there's no more work to do here; we'll just add the new
10257     // function to the scope.
10258     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10259       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10260       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10261         Redeclaration = true;
10262         OldDecl = Candidate;
10263       }
10264     } else {
10265       MayNeedOverloadableChecks = true;
10266       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10267                             /*NewIsUsingDecl*/ false)) {
10268       case Ovl_Match:
10269         Redeclaration = true;
10270         break;
10271 
10272       case Ovl_NonFunction:
10273         Redeclaration = true;
10274         break;
10275 
10276       case Ovl_Overload:
10277         Redeclaration = false;
10278         break;
10279       }
10280     }
10281   }
10282 
10283   // Check for a previous extern "C" declaration with this name.
10284   if (!Redeclaration &&
10285       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10286     if (!Previous.empty()) {
10287       // This is an extern "C" declaration with the same name as a previous
10288       // declaration, and thus redeclares that entity...
10289       Redeclaration = true;
10290       OldDecl = Previous.getFoundDecl();
10291       MergeTypeWithPrevious = false;
10292 
10293       // ... except in the presence of __attribute__((overloadable)).
10294       if (OldDecl->hasAttr<OverloadableAttr>() ||
10295           NewFD->hasAttr<OverloadableAttr>()) {
10296         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10297           MayNeedOverloadableChecks = true;
10298           Redeclaration = false;
10299           OldDecl = nullptr;
10300         }
10301       }
10302     }
10303   }
10304 
10305   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10306                                 MergeTypeWithPrevious, Previous))
10307     return Redeclaration;
10308 
10309   // C++11 [dcl.constexpr]p8:
10310   //   A constexpr specifier for a non-static member function that is not
10311   //   a constructor declares that member function to be const.
10312   //
10313   // This needs to be delayed until we know whether this is an out-of-line
10314   // definition of a static member function.
10315   //
10316   // This rule is not present in C++1y, so we produce a backwards
10317   // compatibility warning whenever it happens in C++11.
10318   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10319   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10320       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10321       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10322     CXXMethodDecl *OldMD = nullptr;
10323     if (OldDecl)
10324       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10325     if (!OldMD || !OldMD->isStatic()) {
10326       const FunctionProtoType *FPT =
10327         MD->getType()->castAs<FunctionProtoType>();
10328       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10329       EPI.TypeQuals.addConst();
10330       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10331                                           FPT->getParamTypes(), EPI));
10332 
10333       // Warn that we did this, if we're not performing template instantiation.
10334       // In that case, we'll have warned already when the template was defined.
10335       if (!inTemplateInstantiation()) {
10336         SourceLocation AddConstLoc;
10337         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10338                 .IgnoreParens().getAs<FunctionTypeLoc>())
10339           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10340 
10341         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10342           << FixItHint::CreateInsertion(AddConstLoc, " const");
10343       }
10344     }
10345   }
10346 
10347   if (Redeclaration) {
10348     // NewFD and OldDecl represent declarations that need to be
10349     // merged.
10350     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10351       NewFD->setInvalidDecl();
10352       return Redeclaration;
10353     }
10354 
10355     Previous.clear();
10356     Previous.addDecl(OldDecl);
10357 
10358     if (FunctionTemplateDecl *OldTemplateDecl =
10359             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10360       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10361       FunctionTemplateDecl *NewTemplateDecl
10362         = NewFD->getDescribedFunctionTemplate();
10363       assert(NewTemplateDecl && "Template/non-template mismatch");
10364 
10365       // The call to MergeFunctionDecl above may have created some state in
10366       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10367       // can add it as a redeclaration.
10368       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10369 
10370       NewFD->setPreviousDeclaration(OldFD);
10371       adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10372       if (NewFD->isCXXClassMember()) {
10373         NewFD->setAccess(OldTemplateDecl->getAccess());
10374         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10375       }
10376 
10377       // If this is an explicit specialization of a member that is a function
10378       // template, mark it as a member specialization.
10379       if (IsMemberSpecialization &&
10380           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10381         NewTemplateDecl->setMemberSpecialization();
10382         assert(OldTemplateDecl->isMemberSpecialization());
10383         // Explicit specializations of a member template do not inherit deleted
10384         // status from the parent member template that they are specializing.
10385         if (OldFD->isDeleted()) {
10386           // FIXME: This assert will not hold in the presence of modules.
10387           assert(OldFD->getCanonicalDecl() == OldFD);
10388           // FIXME: We need an update record for this AST mutation.
10389           OldFD->setDeletedAsWritten(false);
10390         }
10391       }
10392 
10393     } else {
10394       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10395         auto *OldFD = cast<FunctionDecl>(OldDecl);
10396         // This needs to happen first so that 'inline' propagates.
10397         NewFD->setPreviousDeclaration(OldFD);
10398         adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10399         if (NewFD->isCXXClassMember())
10400           NewFD->setAccess(OldFD->getAccess());
10401       }
10402     }
10403   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10404              !NewFD->getAttr<OverloadableAttr>()) {
10405     assert((Previous.empty() ||
10406             llvm::any_of(Previous,
10407                          [](const NamedDecl *ND) {
10408                            return ND->hasAttr<OverloadableAttr>();
10409                          })) &&
10410            "Non-redecls shouldn't happen without overloadable present");
10411 
10412     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10413       const auto *FD = dyn_cast<FunctionDecl>(ND);
10414       return FD && !FD->hasAttr<OverloadableAttr>();
10415     });
10416 
10417     if (OtherUnmarkedIter != Previous.end()) {
10418       Diag(NewFD->getLocation(),
10419            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10420       Diag((*OtherUnmarkedIter)->getLocation(),
10421            diag::note_attribute_overloadable_prev_overload)
10422           << false;
10423 
10424       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10425     }
10426   }
10427 
10428   // Semantic checking for this function declaration (in isolation).
10429 
10430   if (getLangOpts().CPlusPlus) {
10431     // C++-specific checks.
10432     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10433       CheckConstructor(Constructor);
10434     } else if (CXXDestructorDecl *Destructor =
10435                 dyn_cast<CXXDestructorDecl>(NewFD)) {
10436       CXXRecordDecl *Record = Destructor->getParent();
10437       QualType ClassType = Context.getTypeDeclType(Record);
10438 
10439       // FIXME: Shouldn't we be able to perform this check even when the class
10440       // type is dependent? Both gcc and edg can handle that.
10441       if (!ClassType->isDependentType()) {
10442         DeclarationName Name
10443           = Context.DeclarationNames.getCXXDestructorName(
10444                                         Context.getCanonicalType(ClassType));
10445         if (NewFD->getDeclName() != Name) {
10446           Diag(NewFD->getLocation(), diag::err_destructor_name);
10447           NewFD->setInvalidDecl();
10448           return Redeclaration;
10449         }
10450       }
10451     } else if (CXXConversionDecl *Conversion
10452                = dyn_cast<CXXConversionDecl>(NewFD)) {
10453       ActOnConversionDeclarator(Conversion);
10454     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10455       if (auto *TD = Guide->getDescribedFunctionTemplate())
10456         CheckDeductionGuideTemplate(TD);
10457 
10458       // A deduction guide is not on the list of entities that can be
10459       // explicitly specialized.
10460       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10461         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10462             << /*explicit specialization*/ 1;
10463     }
10464 
10465     // Find any virtual functions that this function overrides.
10466     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10467       if (!Method->isFunctionTemplateSpecialization() &&
10468           !Method->getDescribedFunctionTemplate() &&
10469           Method->isCanonicalDecl()) {
10470         if (AddOverriddenMethods(Method->getParent(), Method)) {
10471           // If the function was marked as "static", we have a problem.
10472           if (NewFD->getStorageClass() == SC_Static) {
10473             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
10474           }
10475         }
10476       }
10477 
10478       if (Method->isStatic())
10479         checkThisInStaticMemberFunctionType(Method);
10480     }
10481 
10482     // Extra checking for C++ overloaded operators (C++ [over.oper]).
10483     if (NewFD->isOverloadedOperator() &&
10484         CheckOverloadedOperatorDeclaration(NewFD)) {
10485       NewFD->setInvalidDecl();
10486       return Redeclaration;
10487     }
10488 
10489     // Extra checking for C++0x literal operators (C++0x [over.literal]).
10490     if (NewFD->getLiteralIdentifier() &&
10491         CheckLiteralOperatorDeclaration(NewFD)) {
10492       NewFD->setInvalidDecl();
10493       return Redeclaration;
10494     }
10495 
10496     // In C++, check default arguments now that we have merged decls. Unless
10497     // the lexical context is the class, because in this case this is done
10498     // during delayed parsing anyway.
10499     if (!CurContext->isRecord())
10500       CheckCXXDefaultArguments(NewFD);
10501 
10502     // If this function declares a builtin function, check the type of this
10503     // declaration against the expected type for the builtin.
10504     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10505       ASTContext::GetBuiltinTypeError Error;
10506       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
10507       QualType T = Context.GetBuiltinType(BuiltinID, Error);
10508       // If the type of the builtin differs only in its exception
10509       // specification, that's OK.
10510       // FIXME: If the types do differ in this way, it would be better to
10511       // retain the 'noexcept' form of the type.
10512       if (!T.isNull() &&
10513           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10514                                                             NewFD->getType()))
10515         // The type of this function differs from the type of the builtin,
10516         // so forget about the builtin entirely.
10517         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10518     }
10519 
10520     // If this function is declared as being extern "C", then check to see if
10521     // the function returns a UDT (class, struct, or union type) that is not C
10522     // compatible, and if it does, warn the user.
10523     // But, issue any diagnostic on the first declaration only.
10524     if (Previous.empty() && NewFD->isExternC()) {
10525       QualType R = NewFD->getReturnType();
10526       if (R->isIncompleteType() && !R->isVoidType())
10527         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10528             << NewFD << R;
10529       else if (!R.isPODType(Context) && !R->isVoidType() &&
10530                !R->isObjCObjectPointerType())
10531         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10532     }
10533 
10534     // C++1z [dcl.fct]p6:
10535     //   [...] whether the function has a non-throwing exception-specification
10536     //   [is] part of the function type
10537     //
10538     // This results in an ABI break between C++14 and C++17 for functions whose
10539     // declared type includes an exception-specification in a parameter or
10540     // return type. (Exception specifications on the function itself are OK in
10541     // most cases, and exception specifications are not permitted in most other
10542     // contexts where they could make it into a mangling.)
10543     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10544       auto HasNoexcept = [&](QualType T) -> bool {
10545         // Strip off declarator chunks that could be between us and a function
10546         // type. We don't need to look far, exception specifications are very
10547         // restricted prior to C++17.
10548         if (auto *RT = T->getAs<ReferenceType>())
10549           T = RT->getPointeeType();
10550         else if (T->isAnyPointerType())
10551           T = T->getPointeeType();
10552         else if (auto *MPT = T->getAs<MemberPointerType>())
10553           T = MPT->getPointeeType();
10554         if (auto *FPT = T->getAs<FunctionProtoType>())
10555           if (FPT->isNothrow())
10556             return true;
10557         return false;
10558       };
10559 
10560       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10561       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10562       for (QualType T : FPT->param_types())
10563         AnyNoexcept |= HasNoexcept(T);
10564       if (AnyNoexcept)
10565         Diag(NewFD->getLocation(),
10566              diag::warn_cxx17_compat_exception_spec_in_signature)
10567             << NewFD;
10568     }
10569 
10570     if (!Redeclaration && LangOpts.CUDA)
10571       checkCUDATargetOverload(NewFD, Previous);
10572   }
10573   return Redeclaration;
10574 }
10575 
10576 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10577   // C++11 [basic.start.main]p3:
10578   //   A program that [...] declares main to be inline, static or
10579   //   constexpr is ill-formed.
10580   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
10581   //   appear in a declaration of main.
10582   // static main is not an error under C99, but we should warn about it.
10583   // We accept _Noreturn main as an extension.
10584   if (FD->getStorageClass() == SC_Static)
10585     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10586          ? diag::err_static_main : diag::warn_static_main)
10587       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10588   if (FD->isInlineSpecified())
10589     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10590       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10591   if (DS.isNoreturnSpecified()) {
10592     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10593     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10594     Diag(NoreturnLoc, diag::ext_noreturn_main);
10595     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10596       << FixItHint::CreateRemoval(NoreturnRange);
10597   }
10598   if (FD->isConstexpr()) {
10599     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10600         << FD->isConsteval()
10601         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10602     FD->setConstexprKind(CSK_unspecified);
10603   }
10604 
10605   if (getLangOpts().OpenCL) {
10606     Diag(FD->getLocation(), diag::err_opencl_no_main)
10607         << FD->hasAttr<OpenCLKernelAttr>();
10608     FD->setInvalidDecl();
10609     return;
10610   }
10611 
10612   QualType T = FD->getType();
10613   assert(T->isFunctionType() && "function decl is not of function type");
10614   const FunctionType* FT = T->castAs<FunctionType>();
10615 
10616   // Set default calling convention for main()
10617   if (FT->getCallConv() != CC_C) {
10618     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10619     FD->setType(QualType(FT, 0));
10620     T = Context.getCanonicalType(FD->getType());
10621   }
10622 
10623   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10624     // In C with GNU extensions we allow main() to have non-integer return
10625     // type, but we should warn about the extension, and we disable the
10626     // implicit-return-zero rule.
10627 
10628     // GCC in C mode accepts qualified 'int'.
10629     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
10630       FD->setHasImplicitReturnZero(true);
10631     else {
10632       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
10633       SourceRange RTRange = FD->getReturnTypeSourceRange();
10634       if (RTRange.isValid())
10635         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
10636             << FixItHint::CreateReplacement(RTRange, "int");
10637     }
10638   } else {
10639     // In C and C++, main magically returns 0 if you fall off the end;
10640     // set the flag which tells us that.
10641     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
10642 
10643     // All the standards say that main() should return 'int'.
10644     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
10645       FD->setHasImplicitReturnZero(true);
10646     else {
10647       // Otherwise, this is just a flat-out error.
10648       SourceRange RTRange = FD->getReturnTypeSourceRange();
10649       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
10650           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
10651                                 : FixItHint());
10652       FD->setInvalidDecl(true);
10653     }
10654   }
10655 
10656   // Treat protoless main() as nullary.
10657   if (isa<FunctionNoProtoType>(FT)) return;
10658 
10659   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
10660   unsigned nparams = FTP->getNumParams();
10661   assert(FD->getNumParams() == nparams);
10662 
10663   bool HasExtraParameters = (nparams > 3);
10664 
10665   if (FTP->isVariadic()) {
10666     Diag(FD->getLocation(), diag::ext_variadic_main);
10667     // FIXME: if we had information about the location of the ellipsis, we
10668     // could add a FixIt hint to remove it as a parameter.
10669   }
10670 
10671   // Darwin passes an undocumented fourth argument of type char**.  If
10672   // other platforms start sprouting these, the logic below will start
10673   // getting shifty.
10674   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
10675     HasExtraParameters = false;
10676 
10677   if (HasExtraParameters) {
10678     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
10679     FD->setInvalidDecl(true);
10680     nparams = 3;
10681   }
10682 
10683   // FIXME: a lot of the following diagnostics would be improved
10684   // if we had some location information about types.
10685 
10686   QualType CharPP =
10687     Context.getPointerType(Context.getPointerType(Context.CharTy));
10688   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
10689 
10690   for (unsigned i = 0; i < nparams; ++i) {
10691     QualType AT = FTP->getParamType(i);
10692 
10693     bool mismatch = true;
10694 
10695     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
10696       mismatch = false;
10697     else if (Expected[i] == CharPP) {
10698       // As an extension, the following forms are okay:
10699       //   char const **
10700       //   char const * const *
10701       //   char * const *
10702 
10703       QualifierCollector qs;
10704       const PointerType* PT;
10705       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
10706           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
10707           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
10708                               Context.CharTy)) {
10709         qs.removeConst();
10710         mismatch = !qs.empty();
10711       }
10712     }
10713 
10714     if (mismatch) {
10715       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
10716       // TODO: suggest replacing given type with expected type
10717       FD->setInvalidDecl(true);
10718     }
10719   }
10720 
10721   if (nparams == 1 && !FD->isInvalidDecl()) {
10722     Diag(FD->getLocation(), diag::warn_main_one_arg);
10723   }
10724 
10725   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10726     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10727     FD->setInvalidDecl();
10728   }
10729 }
10730 
10731 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
10732   QualType T = FD->getType();
10733   assert(T->isFunctionType() && "function decl is not of function type");
10734   const FunctionType *FT = T->castAs<FunctionType>();
10735 
10736   // Set an implicit return of 'zero' if the function can return some integral,
10737   // enumeration, pointer or nullptr type.
10738   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
10739       FT->getReturnType()->isAnyPointerType() ||
10740       FT->getReturnType()->isNullPtrType())
10741     // DllMain is exempt because a return value of zero means it failed.
10742     if (FD->getName() != "DllMain")
10743       FD->setHasImplicitReturnZero(true);
10744 
10745   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10746     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10747     FD->setInvalidDecl();
10748   }
10749 }
10750 
10751 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
10752   // FIXME: Need strict checking.  In C89, we need to check for
10753   // any assignment, increment, decrement, function-calls, or
10754   // commas outside of a sizeof.  In C99, it's the same list,
10755   // except that the aforementioned are allowed in unevaluated
10756   // expressions.  Everything else falls under the
10757   // "may accept other forms of constant expressions" exception.
10758   // (We never end up here for C++, so the constant expression
10759   // rules there don't matter.)
10760   const Expr *Culprit;
10761   if (Init->isConstantInitializer(Context, false, &Culprit))
10762     return false;
10763   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
10764     << Culprit->getSourceRange();
10765   return true;
10766 }
10767 
10768 namespace {
10769   // Visits an initialization expression to see if OrigDecl is evaluated in
10770   // its own initialization and throws a warning if it does.
10771   class SelfReferenceChecker
10772       : public EvaluatedExprVisitor<SelfReferenceChecker> {
10773     Sema &S;
10774     Decl *OrigDecl;
10775     bool isRecordType;
10776     bool isPODType;
10777     bool isReferenceType;
10778 
10779     bool isInitList;
10780     llvm::SmallVector<unsigned, 4> InitFieldIndex;
10781 
10782   public:
10783     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
10784 
10785     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
10786                                                     S(S), OrigDecl(OrigDecl) {
10787       isPODType = false;
10788       isRecordType = false;
10789       isReferenceType = false;
10790       isInitList = false;
10791       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
10792         isPODType = VD->getType().isPODType(S.Context);
10793         isRecordType = VD->getType()->isRecordType();
10794         isReferenceType = VD->getType()->isReferenceType();
10795       }
10796     }
10797 
10798     // For most expressions, just call the visitor.  For initializer lists,
10799     // track the index of the field being initialized since fields are
10800     // initialized in order allowing use of previously initialized fields.
10801     void CheckExpr(Expr *E) {
10802       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
10803       if (!InitList) {
10804         Visit(E);
10805         return;
10806       }
10807 
10808       // Track and increment the index here.
10809       isInitList = true;
10810       InitFieldIndex.push_back(0);
10811       for (auto Child : InitList->children()) {
10812         CheckExpr(cast<Expr>(Child));
10813         ++InitFieldIndex.back();
10814       }
10815       InitFieldIndex.pop_back();
10816     }
10817 
10818     // Returns true if MemberExpr is checked and no further checking is needed.
10819     // Returns false if additional checking is required.
10820     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
10821       llvm::SmallVector<FieldDecl*, 4> Fields;
10822       Expr *Base = E;
10823       bool ReferenceField = false;
10824 
10825       // Get the field members used.
10826       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10827         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
10828         if (!FD)
10829           return false;
10830         Fields.push_back(FD);
10831         if (FD->getType()->isReferenceType())
10832           ReferenceField = true;
10833         Base = ME->getBase()->IgnoreParenImpCasts();
10834       }
10835 
10836       // Keep checking only if the base Decl is the same.
10837       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
10838       if (!DRE || DRE->getDecl() != OrigDecl)
10839         return false;
10840 
10841       // A reference field can be bound to an unininitialized field.
10842       if (CheckReference && !ReferenceField)
10843         return true;
10844 
10845       // Convert FieldDecls to their index number.
10846       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
10847       for (const FieldDecl *I : llvm::reverse(Fields))
10848         UsedFieldIndex.push_back(I->getFieldIndex());
10849 
10850       // See if a warning is needed by checking the first difference in index
10851       // numbers.  If field being used has index less than the field being
10852       // initialized, then the use is safe.
10853       for (auto UsedIter = UsedFieldIndex.begin(),
10854                 UsedEnd = UsedFieldIndex.end(),
10855                 OrigIter = InitFieldIndex.begin(),
10856                 OrigEnd = InitFieldIndex.end();
10857            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
10858         if (*UsedIter < *OrigIter)
10859           return true;
10860         if (*UsedIter > *OrigIter)
10861           break;
10862       }
10863 
10864       // TODO: Add a different warning which will print the field names.
10865       HandleDeclRefExpr(DRE);
10866       return true;
10867     }
10868 
10869     // For most expressions, the cast is directly above the DeclRefExpr.
10870     // For conditional operators, the cast can be outside the conditional
10871     // operator if both expressions are DeclRefExpr's.
10872     void HandleValue(Expr *E) {
10873       E = E->IgnoreParens();
10874       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
10875         HandleDeclRefExpr(DRE);
10876         return;
10877       }
10878 
10879       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
10880         Visit(CO->getCond());
10881         HandleValue(CO->getTrueExpr());
10882         HandleValue(CO->getFalseExpr());
10883         return;
10884       }
10885 
10886       if (BinaryConditionalOperator *BCO =
10887               dyn_cast<BinaryConditionalOperator>(E)) {
10888         Visit(BCO->getCond());
10889         HandleValue(BCO->getFalseExpr());
10890         return;
10891       }
10892 
10893       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
10894         HandleValue(OVE->getSourceExpr());
10895         return;
10896       }
10897 
10898       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10899         if (BO->getOpcode() == BO_Comma) {
10900           Visit(BO->getLHS());
10901           HandleValue(BO->getRHS());
10902           return;
10903         }
10904       }
10905 
10906       if (isa<MemberExpr>(E)) {
10907         if (isInitList) {
10908           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
10909                                       false /*CheckReference*/))
10910             return;
10911         }
10912 
10913         Expr *Base = E->IgnoreParenImpCasts();
10914         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10915           // Check for static member variables and don't warn on them.
10916           if (!isa<FieldDecl>(ME->getMemberDecl()))
10917             return;
10918           Base = ME->getBase()->IgnoreParenImpCasts();
10919         }
10920         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
10921           HandleDeclRefExpr(DRE);
10922         return;
10923       }
10924 
10925       Visit(E);
10926     }
10927 
10928     // Reference types not handled in HandleValue are handled here since all
10929     // uses of references are bad, not just r-value uses.
10930     void VisitDeclRefExpr(DeclRefExpr *E) {
10931       if (isReferenceType)
10932         HandleDeclRefExpr(E);
10933     }
10934 
10935     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
10936       if (E->getCastKind() == CK_LValueToRValue) {
10937         HandleValue(E->getSubExpr());
10938         return;
10939       }
10940 
10941       Inherited::VisitImplicitCastExpr(E);
10942     }
10943 
10944     void VisitMemberExpr(MemberExpr *E) {
10945       if (isInitList) {
10946         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
10947           return;
10948       }
10949 
10950       // Don't warn on arrays since they can be treated as pointers.
10951       if (E->getType()->canDecayToPointerType()) return;
10952 
10953       // Warn when a non-static method call is followed by non-static member
10954       // field accesses, which is followed by a DeclRefExpr.
10955       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
10956       bool Warn = (MD && !MD->isStatic());
10957       Expr *Base = E->getBase()->IgnoreParenImpCasts();
10958       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10959         if (!isa<FieldDecl>(ME->getMemberDecl()))
10960           Warn = false;
10961         Base = ME->getBase()->IgnoreParenImpCasts();
10962       }
10963 
10964       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
10965         if (Warn)
10966           HandleDeclRefExpr(DRE);
10967         return;
10968       }
10969 
10970       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
10971       // Visit that expression.
10972       Visit(Base);
10973     }
10974 
10975     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
10976       Expr *Callee = E->getCallee();
10977 
10978       if (isa<UnresolvedLookupExpr>(Callee))
10979         return Inherited::VisitCXXOperatorCallExpr(E);
10980 
10981       Visit(Callee);
10982       for (auto Arg: E->arguments())
10983         HandleValue(Arg->IgnoreParenImpCasts());
10984     }
10985 
10986     void VisitUnaryOperator(UnaryOperator *E) {
10987       // For POD record types, addresses of its own members are well-defined.
10988       if (E->getOpcode() == UO_AddrOf && isRecordType &&
10989           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
10990         if (!isPODType)
10991           HandleValue(E->getSubExpr());
10992         return;
10993       }
10994 
10995       if (E->isIncrementDecrementOp()) {
10996         HandleValue(E->getSubExpr());
10997         return;
10998       }
10999 
11000       Inherited::VisitUnaryOperator(E);
11001     }
11002 
11003     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11004 
11005     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11006       if (E->getConstructor()->isCopyConstructor()) {
11007         Expr *ArgExpr = E->getArg(0);
11008         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11009           if (ILE->getNumInits() == 1)
11010             ArgExpr = ILE->getInit(0);
11011         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11012           if (ICE->getCastKind() == CK_NoOp)
11013             ArgExpr = ICE->getSubExpr();
11014         HandleValue(ArgExpr);
11015         return;
11016       }
11017       Inherited::VisitCXXConstructExpr(E);
11018     }
11019 
11020     void VisitCallExpr(CallExpr *E) {
11021       // Treat std::move as a use.
11022       if (E->isCallToStdMove()) {
11023         HandleValue(E->getArg(0));
11024         return;
11025       }
11026 
11027       Inherited::VisitCallExpr(E);
11028     }
11029 
11030     void VisitBinaryOperator(BinaryOperator *E) {
11031       if (E->isCompoundAssignmentOp()) {
11032         HandleValue(E->getLHS());
11033         Visit(E->getRHS());
11034         return;
11035       }
11036 
11037       Inherited::VisitBinaryOperator(E);
11038     }
11039 
11040     // A custom visitor for BinaryConditionalOperator is needed because the
11041     // regular visitor would check the condition and true expression separately
11042     // but both point to the same place giving duplicate diagnostics.
11043     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11044       Visit(E->getCond());
11045       Visit(E->getFalseExpr());
11046     }
11047 
11048     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11049       Decl* ReferenceDecl = DRE->getDecl();
11050       if (OrigDecl != ReferenceDecl) return;
11051       unsigned diag;
11052       if (isReferenceType) {
11053         diag = diag::warn_uninit_self_reference_in_reference_init;
11054       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11055         diag = diag::warn_static_self_reference_in_init;
11056       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11057                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11058                  DRE->getDecl()->getType()->isRecordType()) {
11059         diag = diag::warn_uninit_self_reference_in_init;
11060       } else {
11061         // Local variables will be handled by the CFG analysis.
11062         return;
11063       }
11064 
11065       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11066                             S.PDiag(diag)
11067                                 << DRE->getDecl() << OrigDecl->getLocation()
11068                                 << DRE->getSourceRange());
11069     }
11070   };
11071 
11072   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11073   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11074                                  bool DirectInit) {
11075     // Parameters arguments are occassionially constructed with itself,
11076     // for instance, in recursive functions.  Skip them.
11077     if (isa<ParmVarDecl>(OrigDecl))
11078       return;
11079 
11080     E = E->IgnoreParens();
11081 
11082     // Skip checking T a = a where T is not a record or reference type.
11083     // Doing so is a way to silence uninitialized warnings.
11084     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11085       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11086         if (ICE->getCastKind() == CK_LValueToRValue)
11087           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11088             if (DRE->getDecl() == OrigDecl)
11089               return;
11090 
11091     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11092   }
11093 } // end anonymous namespace
11094 
11095 namespace {
11096   // Simple wrapper to add the name of a variable or (if no variable is
11097   // available) a DeclarationName into a diagnostic.
11098   struct VarDeclOrName {
11099     VarDecl *VDecl;
11100     DeclarationName Name;
11101 
11102     friend const Sema::SemaDiagnosticBuilder &
11103     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11104       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11105     }
11106   };
11107 } // end anonymous namespace
11108 
11109 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11110                                             DeclarationName Name, QualType Type,
11111                                             TypeSourceInfo *TSI,
11112                                             SourceRange Range, bool DirectInit,
11113                                             Expr *Init) {
11114   bool IsInitCapture = !VDecl;
11115   assert((!VDecl || !VDecl->isInitCapture()) &&
11116          "init captures are expected to be deduced prior to initialization");
11117 
11118   VarDeclOrName VN{VDecl, Name};
11119 
11120   DeducedType *Deduced = Type->getContainedDeducedType();
11121   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11122 
11123   // C++11 [dcl.spec.auto]p3
11124   if (!Init) {
11125     assert(VDecl && "no init for init capture deduction?");
11126 
11127     // Except for class argument deduction, and then for an initializing
11128     // declaration only, i.e. no static at class scope or extern.
11129     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11130         VDecl->hasExternalStorage() ||
11131         VDecl->isStaticDataMember()) {
11132       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11133         << VDecl->getDeclName() << Type;
11134       return QualType();
11135     }
11136   }
11137 
11138   ArrayRef<Expr*> DeduceInits;
11139   if (Init)
11140     DeduceInits = Init;
11141 
11142   if (DirectInit) {
11143     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11144       DeduceInits = PL->exprs();
11145   }
11146 
11147   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11148     assert(VDecl && "non-auto type for init capture deduction?");
11149     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11150     InitializationKind Kind = InitializationKind::CreateForInit(
11151         VDecl->getLocation(), DirectInit, Init);
11152     // FIXME: Initialization should not be taking a mutable list of inits.
11153     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11154     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11155                                                        InitsCopy);
11156   }
11157 
11158   if (DirectInit) {
11159     if (auto *IL = dyn_cast<InitListExpr>(Init))
11160       DeduceInits = IL->inits();
11161   }
11162 
11163   // Deduction only works if we have exactly one source expression.
11164   if (DeduceInits.empty()) {
11165     // It isn't possible to write this directly, but it is possible to
11166     // end up in this situation with "auto x(some_pack...);"
11167     Diag(Init->getBeginLoc(), IsInitCapture
11168                                   ? diag::err_init_capture_no_expression
11169                                   : diag::err_auto_var_init_no_expression)
11170         << VN << Type << Range;
11171     return QualType();
11172   }
11173 
11174   if (DeduceInits.size() > 1) {
11175     Diag(DeduceInits[1]->getBeginLoc(),
11176          IsInitCapture ? diag::err_init_capture_multiple_expressions
11177                        : diag::err_auto_var_init_multiple_expressions)
11178         << VN << Type << Range;
11179     return QualType();
11180   }
11181 
11182   Expr *DeduceInit = DeduceInits[0];
11183   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11184     Diag(Init->getBeginLoc(), IsInitCapture
11185                                   ? diag::err_init_capture_paren_braces
11186                                   : diag::err_auto_var_init_paren_braces)
11187         << isa<InitListExpr>(Init) << VN << Type << Range;
11188     return QualType();
11189   }
11190 
11191   // Expressions default to 'id' when we're in a debugger.
11192   bool DefaultedAnyToId = false;
11193   if (getLangOpts().DebuggerCastResultToId &&
11194       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11195     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11196     if (Result.isInvalid()) {
11197       return QualType();
11198     }
11199     Init = Result.get();
11200     DefaultedAnyToId = true;
11201   }
11202 
11203   // C++ [dcl.decomp]p1:
11204   //   If the assignment-expression [...] has array type A and no ref-qualifier
11205   //   is present, e has type cv A
11206   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11207       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11208       DeduceInit->getType()->isConstantArrayType())
11209     return Context.getQualifiedType(DeduceInit->getType(),
11210                                     Type.getQualifiers());
11211 
11212   QualType DeducedType;
11213   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11214     if (!IsInitCapture)
11215       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11216     else if (isa<InitListExpr>(Init))
11217       Diag(Range.getBegin(),
11218            diag::err_init_capture_deduction_failure_from_init_list)
11219           << VN
11220           << (DeduceInit->getType().isNull() ? TSI->getType()
11221                                              : DeduceInit->getType())
11222           << DeduceInit->getSourceRange();
11223     else
11224       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11225           << VN << TSI->getType()
11226           << (DeduceInit->getType().isNull() ? TSI->getType()
11227                                              : DeduceInit->getType())
11228           << DeduceInit->getSourceRange();
11229   }
11230 
11231   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11232   // 'id' instead of a specific object type prevents most of our usual
11233   // checks.
11234   // We only want to warn outside of template instantiations, though:
11235   // inside a template, the 'id' could have come from a parameter.
11236   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11237       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11238     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11239     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11240   }
11241 
11242   return DeducedType;
11243 }
11244 
11245 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11246                                          Expr *Init) {
11247   QualType DeducedType = deduceVarTypeFromInitializer(
11248       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11249       VDecl->getSourceRange(), DirectInit, Init);
11250   if (DeducedType.isNull()) {
11251     VDecl->setInvalidDecl();
11252     return true;
11253   }
11254 
11255   VDecl->setType(DeducedType);
11256   assert(VDecl->isLinkageValid());
11257 
11258   // In ARC, infer lifetime.
11259   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11260     VDecl->setInvalidDecl();
11261 
11262   // If this is a redeclaration, check that the type we just deduced matches
11263   // the previously declared type.
11264   if (VarDecl *Old = VDecl->getPreviousDecl()) {
11265     // We never need to merge the type, because we cannot form an incomplete
11266     // array of auto, nor deduce such a type.
11267     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11268   }
11269 
11270   // Check the deduced type is valid for a variable declaration.
11271   CheckVariableDeclarationType(VDecl);
11272   return VDecl->isInvalidDecl();
11273 }
11274 
11275 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11276                                               SourceLocation Loc) {
11277   if (auto *CE = dyn_cast<ConstantExpr>(Init))
11278     Init = CE->getSubExpr();
11279 
11280   QualType InitType = Init->getType();
11281   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11282           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
11283          "shouldn't be called if type doesn't have a non-trivial C struct");
11284   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11285     for (auto I : ILE->inits()) {
11286       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11287           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11288         continue;
11289       SourceLocation SL = I->getExprLoc();
11290       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11291     }
11292     return;
11293   }
11294 
11295   if (isa<ImplicitValueInitExpr>(Init)) {
11296     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11297       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11298                             NTCUK_Init);
11299   } else {
11300     // Assume all other explicit initializers involving copying some existing
11301     // object.
11302     // TODO: ignore any explicit initializers where we can guarantee
11303     // copy-elision.
11304     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11305       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11306   }
11307 }
11308 
11309 namespace {
11310 
11311 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11312   // Ignore unavailable fields. A field can be marked as unavailable explicitly
11313   // in the source code or implicitly by the compiler if it is in a union
11314   // defined in a system header and has non-trivial ObjC ownership
11315   // qualifications. We don't want those fields to participate in determining
11316   // whether the containing union is non-trivial.
11317   return FD->hasAttr<UnavailableAttr>();
11318 }
11319 
11320 struct DiagNonTrivalCUnionDefaultInitializeVisitor
11321     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11322                                     void> {
11323   using Super =
11324       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11325                                     void>;
11326 
11327   DiagNonTrivalCUnionDefaultInitializeVisitor(
11328       QualType OrigTy, SourceLocation OrigLoc,
11329       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11330       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11331 
11332   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11333                      const FieldDecl *FD, bool InNonTrivialUnion) {
11334     if (const auto *AT = S.Context.getAsArrayType(QT))
11335       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11336                                      InNonTrivialUnion);
11337     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11338   }
11339 
11340   void visitARCStrong(QualType QT, const FieldDecl *FD,
11341                       bool InNonTrivialUnion) {
11342     if (InNonTrivialUnion)
11343       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11344           << 1 << 0 << QT << FD->getName();
11345   }
11346 
11347   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11348     if (InNonTrivialUnion)
11349       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11350           << 1 << 0 << QT << FD->getName();
11351   }
11352 
11353   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11354     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11355     if (RD->isUnion()) {
11356       if (OrigLoc.isValid()) {
11357         bool IsUnion = false;
11358         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11359           IsUnion = OrigRD->isUnion();
11360         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11361             << 0 << OrigTy << IsUnion << UseContext;
11362         // Reset OrigLoc so that this diagnostic is emitted only once.
11363         OrigLoc = SourceLocation();
11364       }
11365       InNonTrivialUnion = true;
11366     }
11367 
11368     if (InNonTrivialUnion)
11369       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11370           << 0 << 0 << QT.getUnqualifiedType() << "";
11371 
11372     for (const FieldDecl *FD : RD->fields())
11373       if (!shouldIgnoreForRecordTriviality(FD))
11374         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11375   }
11376 
11377   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11378 
11379   // The non-trivial C union type or the struct/union type that contains a
11380   // non-trivial C union.
11381   QualType OrigTy;
11382   SourceLocation OrigLoc;
11383   Sema::NonTrivialCUnionContext UseContext;
11384   Sema &S;
11385 };
11386 
11387 struct DiagNonTrivalCUnionDestructedTypeVisitor
11388     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
11389   using Super =
11390       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
11391 
11392   DiagNonTrivalCUnionDestructedTypeVisitor(
11393       QualType OrigTy, SourceLocation OrigLoc,
11394       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11395       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11396 
11397   void visitWithKind(QualType::DestructionKind DK, QualType QT,
11398                      const FieldDecl *FD, bool InNonTrivialUnion) {
11399     if (const auto *AT = S.Context.getAsArrayType(QT))
11400       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11401                                      InNonTrivialUnion);
11402     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
11403   }
11404 
11405   void visitARCStrong(QualType QT, const FieldDecl *FD,
11406                       bool InNonTrivialUnion) {
11407     if (InNonTrivialUnion)
11408       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11409           << 1 << 1 << QT << FD->getName();
11410   }
11411 
11412   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11413     if (InNonTrivialUnion)
11414       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11415           << 1 << 1 << QT << FD->getName();
11416   }
11417 
11418   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11419     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11420     if (RD->isUnion()) {
11421       if (OrigLoc.isValid()) {
11422         bool IsUnion = false;
11423         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11424           IsUnion = OrigRD->isUnion();
11425         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11426             << 1 << OrigTy << IsUnion << UseContext;
11427         // Reset OrigLoc so that this diagnostic is emitted only once.
11428         OrigLoc = SourceLocation();
11429       }
11430       InNonTrivialUnion = true;
11431     }
11432 
11433     if (InNonTrivialUnion)
11434       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11435           << 0 << 1 << QT.getUnqualifiedType() << "";
11436 
11437     for (const FieldDecl *FD : RD->fields())
11438       if (!shouldIgnoreForRecordTriviality(FD))
11439         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11440   }
11441 
11442   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11443   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
11444                           bool InNonTrivialUnion) {}
11445 
11446   // The non-trivial C union type or the struct/union type that contains a
11447   // non-trivial C union.
11448   QualType OrigTy;
11449   SourceLocation OrigLoc;
11450   Sema::NonTrivialCUnionContext UseContext;
11451   Sema &S;
11452 };
11453 
11454 struct DiagNonTrivalCUnionCopyVisitor
11455     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
11456   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
11457 
11458   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
11459                                  Sema::NonTrivialCUnionContext UseContext,
11460                                  Sema &S)
11461       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11462 
11463   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
11464                      const FieldDecl *FD, bool InNonTrivialUnion) {
11465     if (const auto *AT = S.Context.getAsArrayType(QT))
11466       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11467                                      InNonTrivialUnion);
11468     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
11469   }
11470 
11471   void visitARCStrong(QualType QT, const FieldDecl *FD,
11472                       bool InNonTrivialUnion) {
11473     if (InNonTrivialUnion)
11474       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11475           << 1 << 2 << QT << FD->getName();
11476   }
11477 
11478   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11479     if (InNonTrivialUnion)
11480       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11481           << 1 << 2 << QT << FD->getName();
11482   }
11483 
11484   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11485     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11486     if (RD->isUnion()) {
11487       if (OrigLoc.isValid()) {
11488         bool IsUnion = false;
11489         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11490           IsUnion = OrigRD->isUnion();
11491         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11492             << 2 << OrigTy << IsUnion << UseContext;
11493         // Reset OrigLoc so that this diagnostic is emitted only once.
11494         OrigLoc = SourceLocation();
11495       }
11496       InNonTrivialUnion = true;
11497     }
11498 
11499     if (InNonTrivialUnion)
11500       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11501           << 0 << 2 << QT.getUnqualifiedType() << "";
11502 
11503     for (const FieldDecl *FD : RD->fields())
11504       if (!shouldIgnoreForRecordTriviality(FD))
11505         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11506   }
11507 
11508   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
11509                 const FieldDecl *FD, bool InNonTrivialUnion) {}
11510   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11511   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
11512                             bool InNonTrivialUnion) {}
11513 
11514   // The non-trivial C union type or the struct/union type that contains a
11515   // non-trivial C union.
11516   QualType OrigTy;
11517   SourceLocation OrigLoc;
11518   Sema::NonTrivialCUnionContext UseContext;
11519   Sema &S;
11520 };
11521 
11522 } // namespace
11523 
11524 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
11525                                  NonTrivialCUnionContext UseContext,
11526                                  unsigned NonTrivialKind) {
11527   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11528           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
11529           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
11530          "shouldn't be called if type doesn't have a non-trivial C union");
11531 
11532   if ((NonTrivialKind & NTCUK_Init) &&
11533       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11534     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
11535         .visit(QT, nullptr, false);
11536   if ((NonTrivialKind & NTCUK_Destruct) &&
11537       QT.hasNonTrivialToPrimitiveDestructCUnion())
11538     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
11539         .visit(QT, nullptr, false);
11540   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
11541     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
11542         .visit(QT, nullptr, false);
11543 }
11544 
11545 /// AddInitializerToDecl - Adds the initializer Init to the
11546 /// declaration dcl. If DirectInit is true, this is C++ direct
11547 /// initialization rather than copy initialization.
11548 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
11549   // If there is no declaration, there was an error parsing it.  Just ignore
11550   // the initializer.
11551   if (!RealDecl || RealDecl->isInvalidDecl()) {
11552     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
11553     return;
11554   }
11555 
11556   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
11557     // Pure-specifiers are handled in ActOnPureSpecifier.
11558     Diag(Method->getLocation(), diag::err_member_function_initialization)
11559       << Method->getDeclName() << Init->getSourceRange();
11560     Method->setInvalidDecl();
11561     return;
11562   }
11563 
11564   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
11565   if (!VDecl) {
11566     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
11567     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
11568     RealDecl->setInvalidDecl();
11569     return;
11570   }
11571 
11572   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
11573   if (VDecl->getType()->isUndeducedType()) {
11574     // Attempt typo correction early so that the type of the init expression can
11575     // be deduced based on the chosen correction if the original init contains a
11576     // TypoExpr.
11577     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
11578     if (!Res.isUsable()) {
11579       RealDecl->setInvalidDecl();
11580       return;
11581     }
11582     Init = Res.get();
11583 
11584     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
11585       return;
11586   }
11587 
11588   // dllimport cannot be used on variable definitions.
11589   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
11590     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
11591     VDecl->setInvalidDecl();
11592     return;
11593   }
11594 
11595   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
11596     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
11597     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
11598     VDecl->setInvalidDecl();
11599     return;
11600   }
11601 
11602   if (!VDecl->getType()->isDependentType()) {
11603     // A definition must end up with a complete type, which means it must be
11604     // complete with the restriction that an array type might be completed by
11605     // the initializer; note that later code assumes this restriction.
11606     QualType BaseDeclType = VDecl->getType();
11607     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
11608       BaseDeclType = Array->getElementType();
11609     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
11610                             diag::err_typecheck_decl_incomplete_type)) {
11611       RealDecl->setInvalidDecl();
11612       return;
11613     }
11614 
11615     // The variable can not have an abstract class type.
11616     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
11617                                diag::err_abstract_type_in_decl,
11618                                AbstractVariableType))
11619       VDecl->setInvalidDecl();
11620   }
11621 
11622   // If adding the initializer will turn this declaration into a definition,
11623   // and we already have a definition for this variable, diagnose or otherwise
11624   // handle the situation.
11625   VarDecl *Def;
11626   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
11627       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
11628       !VDecl->isThisDeclarationADemotedDefinition() &&
11629       checkVarDeclRedefinition(Def, VDecl))
11630     return;
11631 
11632   if (getLangOpts().CPlusPlus) {
11633     // C++ [class.static.data]p4
11634     //   If a static data member is of const integral or const
11635     //   enumeration type, its declaration in the class definition can
11636     //   specify a constant-initializer which shall be an integral
11637     //   constant expression (5.19). In that case, the member can appear
11638     //   in integral constant expressions. The member shall still be
11639     //   defined in a namespace scope if it is used in the program and the
11640     //   namespace scope definition shall not contain an initializer.
11641     //
11642     // We already performed a redefinition check above, but for static
11643     // data members we also need to check whether there was an in-class
11644     // declaration with an initializer.
11645     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
11646       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
11647           << VDecl->getDeclName();
11648       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
11649            diag::note_previous_initializer)
11650           << 0;
11651       return;
11652     }
11653 
11654     if (VDecl->hasLocalStorage())
11655       setFunctionHasBranchProtectedScope();
11656 
11657     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
11658       VDecl->setInvalidDecl();
11659       return;
11660     }
11661   }
11662 
11663   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
11664   // a kernel function cannot be initialized."
11665   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
11666     Diag(VDecl->getLocation(), diag::err_local_cant_init);
11667     VDecl->setInvalidDecl();
11668     return;
11669   }
11670 
11671   // Get the decls type and save a reference for later, since
11672   // CheckInitializerTypes may change it.
11673   QualType DclT = VDecl->getType(), SavT = DclT;
11674 
11675   // Expressions default to 'id' when we're in a debugger
11676   // and we are assigning it to a variable of Objective-C pointer type.
11677   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
11678       Init->getType() == Context.UnknownAnyTy) {
11679     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11680     if (Result.isInvalid()) {
11681       VDecl->setInvalidDecl();
11682       return;
11683     }
11684     Init = Result.get();
11685   }
11686 
11687   // Perform the initialization.
11688   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
11689   if (!VDecl->isInvalidDecl()) {
11690     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11691     InitializationKind Kind = InitializationKind::CreateForInit(
11692         VDecl->getLocation(), DirectInit, Init);
11693 
11694     MultiExprArg Args = Init;
11695     if (CXXDirectInit)
11696       Args = MultiExprArg(CXXDirectInit->getExprs(),
11697                           CXXDirectInit->getNumExprs());
11698 
11699     // Try to correct any TypoExprs in the initialization arguments.
11700     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
11701       ExprResult Res = CorrectDelayedTyposInExpr(
11702           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
11703             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
11704             return Init.Failed() ? ExprError() : E;
11705           });
11706       if (Res.isInvalid()) {
11707         VDecl->setInvalidDecl();
11708       } else if (Res.get() != Args[Idx]) {
11709         Args[Idx] = Res.get();
11710       }
11711     }
11712     if (VDecl->isInvalidDecl())
11713       return;
11714 
11715     InitializationSequence InitSeq(*this, Entity, Kind, Args,
11716                                    /*TopLevelOfInitList=*/false,
11717                                    /*TreatUnavailableAsInvalid=*/false);
11718     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
11719     if (Result.isInvalid()) {
11720       VDecl->setInvalidDecl();
11721       return;
11722     }
11723 
11724     Init = Result.getAs<Expr>();
11725   }
11726 
11727   // Check for self-references within variable initializers.
11728   // Variables declared within a function/method body (except for references)
11729   // are handled by a dataflow analysis.
11730   // This is undefined behavior in C++, but valid in C.
11731   if (getLangOpts().CPlusPlus) {
11732     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
11733         VDecl->getType()->isReferenceType()) {
11734       CheckSelfReference(*this, RealDecl, Init, DirectInit);
11735     }
11736   }
11737 
11738   // If the type changed, it means we had an incomplete type that was
11739   // completed by the initializer. For example:
11740   //   int ary[] = { 1, 3, 5 };
11741   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
11742   if (!VDecl->isInvalidDecl() && (DclT != SavT))
11743     VDecl->setType(DclT);
11744 
11745   if (!VDecl->isInvalidDecl()) {
11746     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
11747 
11748     if (VDecl->hasAttr<BlocksAttr>())
11749       checkRetainCycles(VDecl, Init);
11750 
11751     // It is safe to assign a weak reference into a strong variable.
11752     // Although this code can still have problems:
11753     //   id x = self.weakProp;
11754     //   id y = self.weakProp;
11755     // we do not warn to warn spuriously when 'x' and 'y' are on separate
11756     // paths through the function. This should be revisited if
11757     // -Wrepeated-use-of-weak is made flow-sensitive.
11758     if (FunctionScopeInfo *FSI = getCurFunction())
11759       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
11760            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
11761           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11762                            Init->getBeginLoc()))
11763         FSI->markSafeWeakUse(Init);
11764   }
11765 
11766   // The initialization is usually a full-expression.
11767   //
11768   // FIXME: If this is a braced initialization of an aggregate, it is not
11769   // an expression, and each individual field initializer is a separate
11770   // full-expression. For instance, in:
11771   //
11772   //   struct Temp { ~Temp(); };
11773   //   struct S { S(Temp); };
11774   //   struct T { S a, b; } t = { Temp(), Temp() }
11775   //
11776   // we should destroy the first Temp before constructing the second.
11777   ExprResult Result =
11778       ActOnFinishFullExpr(Init, VDecl->getLocation(),
11779                           /*DiscardedValue*/ false, VDecl->isConstexpr());
11780   if (Result.isInvalid()) {
11781     VDecl->setInvalidDecl();
11782     return;
11783   }
11784   Init = Result.get();
11785 
11786   // Attach the initializer to the decl.
11787   VDecl->setInit(Init);
11788 
11789   if (VDecl->isLocalVarDecl()) {
11790     // Don't check the initializer if the declaration is malformed.
11791     if (VDecl->isInvalidDecl()) {
11792       // do nothing
11793 
11794     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
11795     // This is true even in C++ for OpenCL.
11796     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
11797       CheckForConstantInitializer(Init, DclT);
11798 
11799     // Otherwise, C++ does not restrict the initializer.
11800     } else if (getLangOpts().CPlusPlus) {
11801       // do nothing
11802 
11803     // C99 6.7.8p4: All the expressions in an initializer for an object that has
11804     // static storage duration shall be constant expressions or string literals.
11805     } else if (VDecl->getStorageClass() == SC_Static) {
11806       CheckForConstantInitializer(Init, DclT);
11807 
11808     // C89 is stricter than C99 for aggregate initializers.
11809     // C89 6.5.7p3: All the expressions [...] in an initializer list
11810     // for an object that has aggregate or union type shall be
11811     // constant expressions.
11812     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
11813                isa<InitListExpr>(Init)) {
11814       const Expr *Culprit;
11815       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
11816         Diag(Culprit->getExprLoc(),
11817              diag::ext_aggregate_init_not_constant)
11818           << Culprit->getSourceRange();
11819       }
11820     }
11821 
11822     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
11823       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
11824         if (VDecl->hasLocalStorage())
11825           BE->getBlockDecl()->setCanAvoidCopyToHeap();
11826   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
11827              VDecl->getLexicalDeclContext()->isRecord()) {
11828     // This is an in-class initialization for a static data member, e.g.,
11829     //
11830     // struct S {
11831     //   static const int value = 17;
11832     // };
11833 
11834     // C++ [class.mem]p4:
11835     //   A member-declarator can contain a constant-initializer only
11836     //   if it declares a static member (9.4) of const integral or
11837     //   const enumeration type, see 9.4.2.
11838     //
11839     // C++11 [class.static.data]p3:
11840     //   If a non-volatile non-inline const static data member is of integral
11841     //   or enumeration type, its declaration in the class definition can
11842     //   specify a brace-or-equal-initializer in which every initializer-clause
11843     //   that is an assignment-expression is a constant expression. A static
11844     //   data member of literal type can be declared in the class definition
11845     //   with the constexpr specifier; if so, its declaration shall specify a
11846     //   brace-or-equal-initializer in which every initializer-clause that is
11847     //   an assignment-expression is a constant expression.
11848 
11849     // Do nothing on dependent types.
11850     if (DclT->isDependentType()) {
11851 
11852     // Allow any 'static constexpr' members, whether or not they are of literal
11853     // type. We separately check that every constexpr variable is of literal
11854     // type.
11855     } else if (VDecl->isConstexpr()) {
11856 
11857     // Require constness.
11858     } else if (!DclT.isConstQualified()) {
11859       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
11860         << Init->getSourceRange();
11861       VDecl->setInvalidDecl();
11862 
11863     // We allow integer constant expressions in all cases.
11864     } else if (DclT->isIntegralOrEnumerationType()) {
11865       // Check whether the expression is a constant expression.
11866       SourceLocation Loc;
11867       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
11868         // In C++11, a non-constexpr const static data member with an
11869         // in-class initializer cannot be volatile.
11870         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
11871       else if (Init->isValueDependent())
11872         ; // Nothing to check.
11873       else if (Init->isIntegerConstantExpr(Context, &Loc))
11874         ; // Ok, it's an ICE!
11875       else if (Init->getType()->isScopedEnumeralType() &&
11876                Init->isCXX11ConstantExpr(Context))
11877         ; // Ok, it is a scoped-enum constant expression.
11878       else if (Init->isEvaluatable(Context)) {
11879         // If we can constant fold the initializer through heroics, accept it,
11880         // but report this as a use of an extension for -pedantic.
11881         Diag(Loc, diag::ext_in_class_initializer_non_constant)
11882           << Init->getSourceRange();
11883       } else {
11884         // Otherwise, this is some crazy unknown case.  Report the issue at the
11885         // location provided by the isIntegerConstantExpr failed check.
11886         Diag(Loc, diag::err_in_class_initializer_non_constant)
11887           << Init->getSourceRange();
11888         VDecl->setInvalidDecl();
11889       }
11890 
11891     // We allow foldable floating-point constants as an extension.
11892     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
11893       // In C++98, this is a GNU extension. In C++11, it is not, but we support
11894       // it anyway and provide a fixit to add the 'constexpr'.
11895       if (getLangOpts().CPlusPlus11) {
11896         Diag(VDecl->getLocation(),
11897              diag::ext_in_class_initializer_float_type_cxx11)
11898             << DclT << Init->getSourceRange();
11899         Diag(VDecl->getBeginLoc(),
11900              diag::note_in_class_initializer_float_type_cxx11)
11901             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11902       } else {
11903         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
11904           << DclT << Init->getSourceRange();
11905 
11906         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
11907           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
11908             << Init->getSourceRange();
11909           VDecl->setInvalidDecl();
11910         }
11911       }
11912 
11913     // Suggest adding 'constexpr' in C++11 for literal types.
11914     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
11915       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
11916           << DclT << Init->getSourceRange()
11917           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11918       VDecl->setConstexpr(true);
11919 
11920     } else {
11921       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
11922         << DclT << Init->getSourceRange();
11923       VDecl->setInvalidDecl();
11924     }
11925   } else if (VDecl->isFileVarDecl()) {
11926     // In C, extern is typically used to avoid tentative definitions when
11927     // declaring variables in headers, but adding an intializer makes it a
11928     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
11929     // In C++, extern is often used to give implictly static const variables
11930     // external linkage, so don't warn in that case. If selectany is present,
11931     // this might be header code intended for C and C++ inclusion, so apply the
11932     // C++ rules.
11933     if (VDecl->getStorageClass() == SC_Extern &&
11934         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
11935          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
11936         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
11937         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
11938       Diag(VDecl->getLocation(), diag::warn_extern_init);
11939 
11940     // In Microsoft C++ mode, a const variable defined in namespace scope has
11941     // external linkage by default if the variable is declared with
11942     // __declspec(dllexport).
11943     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
11944         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
11945         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
11946       VDecl->setStorageClass(SC_Extern);
11947 
11948     // C99 6.7.8p4. All file scoped initializers need to be constant.
11949     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
11950       CheckForConstantInitializer(Init, DclT);
11951   }
11952 
11953   QualType InitType = Init->getType();
11954   if (!InitType.isNull() &&
11955       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11956        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
11957     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
11958 
11959   // We will represent direct-initialization similarly to copy-initialization:
11960   //    int x(1);  -as-> int x = 1;
11961   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
11962   //
11963   // Clients that want to distinguish between the two forms, can check for
11964   // direct initializer using VarDecl::getInitStyle().
11965   // A major benefit is that clients that don't particularly care about which
11966   // exactly form was it (like the CodeGen) can handle both cases without
11967   // special case code.
11968 
11969   // C++ 8.5p11:
11970   // The form of initialization (using parentheses or '=') is generally
11971   // insignificant, but does matter when the entity being initialized has a
11972   // class type.
11973   if (CXXDirectInit) {
11974     assert(DirectInit && "Call-style initializer must be direct init.");
11975     VDecl->setInitStyle(VarDecl::CallInit);
11976   } else if (DirectInit) {
11977     // This must be list-initialization. No other way is direct-initialization.
11978     VDecl->setInitStyle(VarDecl::ListInit);
11979   }
11980 
11981   CheckCompleteVariableDeclaration(VDecl);
11982 }
11983 
11984 /// ActOnInitializerError - Given that there was an error parsing an
11985 /// initializer for the given declaration, try to return to some form
11986 /// of sanity.
11987 void Sema::ActOnInitializerError(Decl *D) {
11988   // Our main concern here is re-establishing invariants like "a
11989   // variable's type is either dependent or complete".
11990   if (!D || D->isInvalidDecl()) return;
11991 
11992   VarDecl *VD = dyn_cast<VarDecl>(D);
11993   if (!VD) return;
11994 
11995   // Bindings are not usable if we can't make sense of the initializer.
11996   if (auto *DD = dyn_cast<DecompositionDecl>(D))
11997     for (auto *BD : DD->bindings())
11998       BD->setInvalidDecl();
11999 
12000   // Auto types are meaningless if we can't make sense of the initializer.
12001   if (ParsingInitForAutoVars.count(D)) {
12002     D->setInvalidDecl();
12003     return;
12004   }
12005 
12006   QualType Ty = VD->getType();
12007   if (Ty->isDependentType()) return;
12008 
12009   // Require a complete type.
12010   if (RequireCompleteType(VD->getLocation(),
12011                           Context.getBaseElementType(Ty),
12012                           diag::err_typecheck_decl_incomplete_type)) {
12013     VD->setInvalidDecl();
12014     return;
12015   }
12016 
12017   // Require a non-abstract type.
12018   if (RequireNonAbstractType(VD->getLocation(), Ty,
12019                              diag::err_abstract_type_in_decl,
12020                              AbstractVariableType)) {
12021     VD->setInvalidDecl();
12022     return;
12023   }
12024 
12025   // Don't bother complaining about constructors or destructors,
12026   // though.
12027 }
12028 
12029 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12030   // If there is no declaration, there was an error parsing it. Just ignore it.
12031   if (!RealDecl)
12032     return;
12033 
12034   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12035     QualType Type = Var->getType();
12036 
12037     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12038     if (isa<DecompositionDecl>(RealDecl)) {
12039       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12040       Var->setInvalidDecl();
12041       return;
12042     }
12043 
12044     if (Type->isUndeducedType() &&
12045         DeduceVariableDeclarationType(Var, false, nullptr))
12046       return;
12047 
12048     // C++11 [class.static.data]p3: A static data member can be declared with
12049     // the constexpr specifier; if so, its declaration shall specify
12050     // a brace-or-equal-initializer.
12051     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12052     // the definition of a variable [...] or the declaration of a static data
12053     // member.
12054     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12055         !Var->isThisDeclarationADemotedDefinition()) {
12056       if (Var->isStaticDataMember()) {
12057         // C++1z removes the relevant rule; the in-class declaration is always
12058         // a definition there.
12059         if (!getLangOpts().CPlusPlus17 &&
12060             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12061           Diag(Var->getLocation(),
12062                diag::err_constexpr_static_mem_var_requires_init)
12063             << Var->getDeclName();
12064           Var->setInvalidDecl();
12065           return;
12066         }
12067       } else {
12068         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12069         Var->setInvalidDecl();
12070         return;
12071       }
12072     }
12073 
12074     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12075     // be initialized.
12076     if (!Var->isInvalidDecl() &&
12077         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12078         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12079       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12080       Var->setInvalidDecl();
12081       return;
12082     }
12083 
12084     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12085     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12086         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12087       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12088                             NTCUC_DefaultInitializedObject, NTCUK_Init);
12089 
12090 
12091     switch (DefKind) {
12092     case VarDecl::Definition:
12093       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12094         break;
12095 
12096       // We have an out-of-line definition of a static data member
12097       // that has an in-class initializer, so we type-check this like
12098       // a declaration.
12099       //
12100       LLVM_FALLTHROUGH;
12101 
12102     case VarDecl::DeclarationOnly:
12103       // It's only a declaration.
12104 
12105       // Block scope. C99 6.7p7: If an identifier for an object is
12106       // declared with no linkage (C99 6.2.2p6), the type for the
12107       // object shall be complete.
12108       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12109           !Var->hasLinkage() && !Var->isInvalidDecl() &&
12110           RequireCompleteType(Var->getLocation(), Type,
12111                               diag::err_typecheck_decl_incomplete_type))
12112         Var->setInvalidDecl();
12113 
12114       // Make sure that the type is not abstract.
12115       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12116           RequireNonAbstractType(Var->getLocation(), Type,
12117                                  diag::err_abstract_type_in_decl,
12118                                  AbstractVariableType))
12119         Var->setInvalidDecl();
12120       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12121           Var->getStorageClass() == SC_PrivateExtern) {
12122         Diag(Var->getLocation(), diag::warn_private_extern);
12123         Diag(Var->getLocation(), diag::note_private_extern);
12124       }
12125 
12126       return;
12127 
12128     case VarDecl::TentativeDefinition:
12129       // File scope. C99 6.9.2p2: A declaration of an identifier for an
12130       // object that has file scope without an initializer, and without a
12131       // storage-class specifier or with the storage-class specifier "static",
12132       // constitutes a tentative definition. Note: A tentative definition with
12133       // external linkage is valid (C99 6.2.2p5).
12134       if (!Var->isInvalidDecl()) {
12135         if (const IncompleteArrayType *ArrayT
12136                                     = Context.getAsIncompleteArrayType(Type)) {
12137           if (RequireCompleteType(Var->getLocation(),
12138                                   ArrayT->getElementType(),
12139                                   diag::err_illegal_decl_array_incomplete_type))
12140             Var->setInvalidDecl();
12141         } else if (Var->getStorageClass() == SC_Static) {
12142           // C99 6.9.2p3: If the declaration of an identifier for an object is
12143           // a tentative definition and has internal linkage (C99 6.2.2p3), the
12144           // declared type shall not be an incomplete type.
12145           // NOTE: code such as the following
12146           //     static struct s;
12147           //     struct s { int a; };
12148           // is accepted by gcc. Hence here we issue a warning instead of
12149           // an error and we do not invalidate the static declaration.
12150           // NOTE: to avoid multiple warnings, only check the first declaration.
12151           if (Var->isFirstDecl())
12152             RequireCompleteType(Var->getLocation(), Type,
12153                                 diag::ext_typecheck_decl_incomplete_type);
12154         }
12155       }
12156 
12157       // Record the tentative definition; we're done.
12158       if (!Var->isInvalidDecl())
12159         TentativeDefinitions.push_back(Var);
12160       return;
12161     }
12162 
12163     // Provide a specific diagnostic for uninitialized variable
12164     // definitions with incomplete array type.
12165     if (Type->isIncompleteArrayType()) {
12166       Diag(Var->getLocation(),
12167            diag::err_typecheck_incomplete_array_needs_initializer);
12168       Var->setInvalidDecl();
12169       return;
12170     }
12171 
12172     // Provide a specific diagnostic for uninitialized variable
12173     // definitions with reference type.
12174     if (Type->isReferenceType()) {
12175       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12176         << Var->getDeclName()
12177         << SourceRange(Var->getLocation(), Var->getLocation());
12178       Var->setInvalidDecl();
12179       return;
12180     }
12181 
12182     // Do not attempt to type-check the default initializer for a
12183     // variable with dependent type.
12184     if (Type->isDependentType())
12185       return;
12186 
12187     if (Var->isInvalidDecl())
12188       return;
12189 
12190     if (!Var->hasAttr<AliasAttr>()) {
12191       if (RequireCompleteType(Var->getLocation(),
12192                               Context.getBaseElementType(Type),
12193                               diag::err_typecheck_decl_incomplete_type)) {
12194         Var->setInvalidDecl();
12195         return;
12196       }
12197     } else {
12198       return;
12199     }
12200 
12201     // The variable can not have an abstract class type.
12202     if (RequireNonAbstractType(Var->getLocation(), Type,
12203                                diag::err_abstract_type_in_decl,
12204                                AbstractVariableType)) {
12205       Var->setInvalidDecl();
12206       return;
12207     }
12208 
12209     // Check for jumps past the implicit initializer.  C++0x
12210     // clarifies that this applies to a "variable with automatic
12211     // storage duration", not a "local variable".
12212     // C++11 [stmt.dcl]p3
12213     //   A program that jumps from a point where a variable with automatic
12214     //   storage duration is not in scope to a point where it is in scope is
12215     //   ill-formed unless the variable has scalar type, class type with a
12216     //   trivial default constructor and a trivial destructor, a cv-qualified
12217     //   version of one of these types, or an array of one of the preceding
12218     //   types and is declared without an initializer.
12219     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12220       if (const RecordType *Record
12221             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12222         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12223         // Mark the function (if we're in one) for further checking even if the
12224         // looser rules of C++11 do not require such checks, so that we can
12225         // diagnose incompatibilities with C++98.
12226         if (!CXXRecord->isPOD())
12227           setFunctionHasBranchProtectedScope();
12228       }
12229     }
12230     // In OpenCL, we can't initialize objects in the __local address space,
12231     // even implicitly, so don't synthesize an implicit initializer.
12232     if (getLangOpts().OpenCL &&
12233         Var->getType().getAddressSpace() == LangAS::opencl_local)
12234       return;
12235     // C++03 [dcl.init]p9:
12236     //   If no initializer is specified for an object, and the
12237     //   object is of (possibly cv-qualified) non-POD class type (or
12238     //   array thereof), the object shall be default-initialized; if
12239     //   the object is of const-qualified type, the underlying class
12240     //   type shall have a user-declared default
12241     //   constructor. Otherwise, if no initializer is specified for
12242     //   a non- static object, the object and its subobjects, if
12243     //   any, have an indeterminate initial value); if the object
12244     //   or any of its subobjects are of const-qualified type, the
12245     //   program is ill-formed.
12246     // C++0x [dcl.init]p11:
12247     //   If no initializer is specified for an object, the object is
12248     //   default-initialized; [...].
12249     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12250     InitializationKind Kind
12251       = InitializationKind::CreateDefault(Var->getLocation());
12252 
12253     InitializationSequence InitSeq(*this, Entity, Kind, None);
12254     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12255     if (Init.isInvalid())
12256       Var->setInvalidDecl();
12257     else if (Init.get()) {
12258       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12259       // This is important for template substitution.
12260       Var->setInitStyle(VarDecl::CallInit);
12261     }
12262 
12263     CheckCompleteVariableDeclaration(Var);
12264   }
12265 }
12266 
12267 void Sema::ActOnCXXForRangeDecl(Decl *D) {
12268   // If there is no declaration, there was an error parsing it. Ignore it.
12269   if (!D)
12270     return;
12271 
12272   VarDecl *VD = dyn_cast<VarDecl>(D);
12273   if (!VD) {
12274     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12275     D->setInvalidDecl();
12276     return;
12277   }
12278 
12279   VD->setCXXForRangeDecl(true);
12280 
12281   // for-range-declaration cannot be given a storage class specifier.
12282   int Error = -1;
12283   switch (VD->getStorageClass()) {
12284   case SC_None:
12285     break;
12286   case SC_Extern:
12287     Error = 0;
12288     break;
12289   case SC_Static:
12290     Error = 1;
12291     break;
12292   case SC_PrivateExtern:
12293     Error = 2;
12294     break;
12295   case SC_Auto:
12296     Error = 3;
12297     break;
12298   case SC_Register:
12299     Error = 4;
12300     break;
12301   }
12302   if (Error != -1) {
12303     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12304       << VD->getDeclName() << Error;
12305     D->setInvalidDecl();
12306   }
12307 }
12308 
12309 StmtResult
12310 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
12311                                  IdentifierInfo *Ident,
12312                                  ParsedAttributes &Attrs,
12313                                  SourceLocation AttrEnd) {
12314   // C++1y [stmt.iter]p1:
12315   //   A range-based for statement of the form
12316   //      for ( for-range-identifier : for-range-initializer ) statement
12317   //   is equivalent to
12318   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
12319   DeclSpec DS(Attrs.getPool().getFactory());
12320 
12321   const char *PrevSpec;
12322   unsigned DiagID;
12323   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
12324                      getPrintingPolicy());
12325 
12326   Declarator D(DS, DeclaratorContext::ForContext);
12327   D.SetIdentifier(Ident, IdentLoc);
12328   D.takeAttributes(Attrs, AttrEnd);
12329 
12330   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
12331                 IdentLoc);
12332   Decl *Var = ActOnDeclarator(S, D);
12333   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
12334   FinalizeDeclaration(Var);
12335   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
12336                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
12337 }
12338 
12339 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
12340   if (var->isInvalidDecl()) return;
12341 
12342   if (getLangOpts().OpenCL) {
12343     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
12344     // initialiser
12345     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
12346         !var->hasInit()) {
12347       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
12348           << 1 /*Init*/;
12349       var->setInvalidDecl();
12350       return;
12351     }
12352   }
12353 
12354   // In Objective-C, don't allow jumps past the implicit initialization of a
12355   // local retaining variable.
12356   if (getLangOpts().ObjC &&
12357       var->hasLocalStorage()) {
12358     switch (var->getType().getObjCLifetime()) {
12359     case Qualifiers::OCL_None:
12360     case Qualifiers::OCL_ExplicitNone:
12361     case Qualifiers::OCL_Autoreleasing:
12362       break;
12363 
12364     case Qualifiers::OCL_Weak:
12365     case Qualifiers::OCL_Strong:
12366       setFunctionHasBranchProtectedScope();
12367       break;
12368     }
12369   }
12370 
12371   if (var->hasLocalStorage() &&
12372       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
12373     setFunctionHasBranchProtectedScope();
12374 
12375   // Warn about externally-visible variables being defined without a
12376   // prior declaration.  We only want to do this for global
12377   // declarations, but we also specifically need to avoid doing it for
12378   // class members because the linkage of an anonymous class can
12379   // change if it's later given a typedef name.
12380   if (var->isThisDeclarationADefinition() &&
12381       var->getDeclContext()->getRedeclContext()->isFileContext() &&
12382       var->isExternallyVisible() && var->hasLinkage() &&
12383       !var->isInline() && !var->getDescribedVarTemplate() &&
12384       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
12385       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
12386                                   var->getLocation())) {
12387     // Find a previous declaration that's not a definition.
12388     VarDecl *prev = var->getPreviousDecl();
12389     while (prev && prev->isThisDeclarationADefinition())
12390       prev = prev->getPreviousDecl();
12391 
12392     if (!prev) {
12393       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
12394       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
12395           << /* variable */ 0;
12396     }
12397   }
12398 
12399   // Cache the result of checking for constant initialization.
12400   Optional<bool> CacheHasConstInit;
12401   const Expr *CacheCulprit = nullptr;
12402   auto checkConstInit = [&]() mutable {
12403     if (!CacheHasConstInit)
12404       CacheHasConstInit = var->getInit()->isConstantInitializer(
12405             Context, var->getType()->isReferenceType(), &CacheCulprit);
12406     return *CacheHasConstInit;
12407   };
12408 
12409   if (var->getTLSKind() == VarDecl::TLS_Static) {
12410     if (var->getType().isDestructedType()) {
12411       // GNU C++98 edits for __thread, [basic.start.term]p3:
12412       //   The type of an object with thread storage duration shall not
12413       //   have a non-trivial destructor.
12414       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
12415       if (getLangOpts().CPlusPlus11)
12416         Diag(var->getLocation(), diag::note_use_thread_local);
12417     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
12418       if (!checkConstInit()) {
12419         // GNU C++98 edits for __thread, [basic.start.init]p4:
12420         //   An object of thread storage duration shall not require dynamic
12421         //   initialization.
12422         // FIXME: Need strict checking here.
12423         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
12424           << CacheCulprit->getSourceRange();
12425         if (getLangOpts().CPlusPlus11)
12426           Diag(var->getLocation(), diag::note_use_thread_local);
12427       }
12428     }
12429   }
12430 
12431   // Apply section attributes and pragmas to global variables.
12432   bool GlobalStorage = var->hasGlobalStorage();
12433   if (GlobalStorage && var->isThisDeclarationADefinition() &&
12434       !inTemplateInstantiation()) {
12435     PragmaStack<StringLiteral *> *Stack = nullptr;
12436     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
12437     if (var->getType().isConstQualified())
12438       Stack = &ConstSegStack;
12439     else if (!var->getInit()) {
12440       Stack = &BSSSegStack;
12441       SectionFlags |= ASTContext::PSF_Write;
12442     } else {
12443       Stack = &DataSegStack;
12444       SectionFlags |= ASTContext::PSF_Write;
12445     }
12446     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>())
12447       var->addAttr(SectionAttr::CreateImplicit(
12448           Context, Stack->CurrentValue->getString(),
12449           Stack->CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
12450           SectionAttr::Declspec_allocate));
12451     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
12452       if (UnifySection(SA->getName(), SectionFlags, var))
12453         var->dropAttr<SectionAttr>();
12454 
12455     // Apply the init_seg attribute if this has an initializer.  If the
12456     // initializer turns out to not be dynamic, we'll end up ignoring this
12457     // attribute.
12458     if (CurInitSeg && var->getInit())
12459       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
12460                                                CurInitSegLoc,
12461                                                AttributeCommonInfo::AS_Pragma));
12462   }
12463 
12464   // All the following checks are C++ only.
12465   if (!getLangOpts().CPlusPlus) {
12466       // If this variable must be emitted, add it as an initializer for the
12467       // current module.
12468      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12469        Context.addModuleInitializer(ModuleScopes.back().Module, var);
12470      return;
12471   }
12472 
12473   if (auto *DD = dyn_cast<DecompositionDecl>(var))
12474     CheckCompleteDecompositionDeclaration(DD);
12475 
12476   QualType type = var->getType();
12477   if (type->isDependentType()) return;
12478 
12479   if (var->hasAttr<BlocksAttr>())
12480     getCurFunction()->addByrefBlockVar(var);
12481 
12482   Expr *Init = var->getInit();
12483   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
12484   QualType baseType = Context.getBaseElementType(type);
12485 
12486   if (Init && !Init->isValueDependent()) {
12487     if (var->isConstexpr()) {
12488       SmallVector<PartialDiagnosticAt, 8> Notes;
12489       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
12490         SourceLocation DiagLoc = var->getLocation();
12491         // If the note doesn't add any useful information other than a source
12492         // location, fold it into the primary diagnostic.
12493         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12494               diag::note_invalid_subexpr_in_const_expr) {
12495           DiagLoc = Notes[0].first;
12496           Notes.clear();
12497         }
12498         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
12499           << var << Init->getSourceRange();
12500         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
12501           Diag(Notes[I].first, Notes[I].second);
12502       }
12503     } else if (var->mightBeUsableInConstantExpressions(Context)) {
12504       // Check whether the initializer of a const variable of integral or
12505       // enumeration type is an ICE now, since we can't tell whether it was
12506       // initialized by a constant expression if we check later.
12507       var->checkInitIsICE();
12508     }
12509 
12510     // Don't emit further diagnostics about constexpr globals since they
12511     // were just diagnosed.
12512     if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) {
12513       // FIXME: Need strict checking in C++03 here.
12514       bool DiagErr = getLangOpts().CPlusPlus11
12515           ? !var->checkInitIsICE() : !checkConstInit();
12516       if (DiagErr) {
12517         auto *Attr = var->getAttr<ConstInitAttr>();
12518         Diag(var->getLocation(), diag::err_require_constant_init_failed)
12519           << Init->getSourceRange();
12520         Diag(Attr->getLocation(),
12521              diag::note_declared_required_constant_init_here)
12522             << Attr->getRange() << Attr->isConstinit();
12523         if (getLangOpts().CPlusPlus11) {
12524           APValue Value;
12525           SmallVector<PartialDiagnosticAt, 8> Notes;
12526           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
12527           for (auto &it : Notes)
12528             Diag(it.first, it.second);
12529         } else {
12530           Diag(CacheCulprit->getExprLoc(),
12531                diag::note_invalid_subexpr_in_const_expr)
12532               << CacheCulprit->getSourceRange();
12533         }
12534       }
12535     }
12536     else if (!var->isConstexpr() && IsGlobal &&
12537              !getDiagnostics().isIgnored(diag::warn_global_constructor,
12538                                     var->getLocation())) {
12539       // Warn about globals which don't have a constant initializer.  Don't
12540       // warn about globals with a non-trivial destructor because we already
12541       // warned about them.
12542       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
12543       if (!(RD && !RD->hasTrivialDestructor())) {
12544         if (!checkConstInit())
12545           Diag(var->getLocation(), diag::warn_global_constructor)
12546             << Init->getSourceRange();
12547       }
12548     }
12549   }
12550 
12551   // Require the destructor.
12552   if (const RecordType *recordType = baseType->getAs<RecordType>())
12553     FinalizeVarWithDestructor(var, recordType);
12554 
12555   // If this variable must be emitted, add it as an initializer for the current
12556   // module.
12557   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12558     Context.addModuleInitializer(ModuleScopes.back().Module, var);
12559 }
12560 
12561 /// Determines if a variable's alignment is dependent.
12562 static bool hasDependentAlignment(VarDecl *VD) {
12563   if (VD->getType()->isDependentType())
12564     return true;
12565   for (auto *I : VD->specific_attrs<AlignedAttr>())
12566     if (I->isAlignmentDependent())
12567       return true;
12568   return false;
12569 }
12570 
12571 /// Check if VD needs to be dllexport/dllimport due to being in a
12572 /// dllexport/import function.
12573 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
12574   assert(VD->isStaticLocal());
12575 
12576   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12577 
12578   // Find outermost function when VD is in lambda function.
12579   while (FD && !getDLLAttr(FD) &&
12580          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
12581          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
12582     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
12583   }
12584 
12585   if (!FD)
12586     return;
12587 
12588   // Static locals inherit dll attributes from their function.
12589   if (Attr *A = getDLLAttr(FD)) {
12590     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
12591     NewAttr->setInherited(true);
12592     VD->addAttr(NewAttr);
12593   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
12594     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
12595     NewAttr->setInherited(true);
12596     VD->addAttr(NewAttr);
12597 
12598     // Export this function to enforce exporting this static variable even
12599     // if it is not used in this compilation unit.
12600     if (!FD->hasAttr<DLLExportAttr>())
12601       FD->addAttr(NewAttr);
12602 
12603   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
12604     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
12605     NewAttr->setInherited(true);
12606     VD->addAttr(NewAttr);
12607   }
12608 }
12609 
12610 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
12611 /// any semantic actions necessary after any initializer has been attached.
12612 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
12613   // Note that we are no longer parsing the initializer for this declaration.
12614   ParsingInitForAutoVars.erase(ThisDecl);
12615 
12616   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
12617   if (!VD)
12618     return;
12619 
12620   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
12621   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
12622       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
12623     if (PragmaClangBSSSection.Valid)
12624       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
12625           Context, PragmaClangBSSSection.SectionName,
12626           PragmaClangBSSSection.PragmaLocation,
12627           AttributeCommonInfo::AS_Pragma));
12628     if (PragmaClangDataSection.Valid)
12629       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
12630           Context, PragmaClangDataSection.SectionName,
12631           PragmaClangDataSection.PragmaLocation,
12632           AttributeCommonInfo::AS_Pragma));
12633     if (PragmaClangRodataSection.Valid)
12634       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
12635           Context, PragmaClangRodataSection.SectionName,
12636           PragmaClangRodataSection.PragmaLocation,
12637           AttributeCommonInfo::AS_Pragma));
12638     if (PragmaClangRelroSection.Valid)
12639       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
12640           Context, PragmaClangRelroSection.SectionName,
12641           PragmaClangRelroSection.PragmaLocation,
12642           AttributeCommonInfo::AS_Pragma));
12643   }
12644 
12645   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
12646     for (auto *BD : DD->bindings()) {
12647       FinalizeDeclaration(BD);
12648     }
12649   }
12650 
12651   checkAttributesAfterMerging(*this, *VD);
12652 
12653   // Perform TLS alignment check here after attributes attached to the variable
12654   // which may affect the alignment have been processed. Only perform the check
12655   // if the target has a maximum TLS alignment (zero means no constraints).
12656   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
12657     // Protect the check so that it's not performed on dependent types and
12658     // dependent alignments (we can't determine the alignment in that case).
12659     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
12660         !VD->isInvalidDecl()) {
12661       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
12662       if (Context.getDeclAlign(VD) > MaxAlignChars) {
12663         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
12664           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
12665           << (unsigned)MaxAlignChars.getQuantity();
12666       }
12667     }
12668   }
12669 
12670   if (VD->isStaticLocal()) {
12671     CheckStaticLocalForDllExport(VD);
12672 
12673     if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
12674       // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
12675       // function, only __shared__ variables or variables without any device
12676       // memory qualifiers may be declared with static storage class.
12677       // Note: It is unclear how a function-scope non-const static variable
12678       // without device memory qualifier is implemented, therefore only static
12679       // const variable without device memory qualifier is allowed.
12680       [&]() {
12681         if (!getLangOpts().CUDA)
12682           return;
12683         if (VD->hasAttr<CUDASharedAttr>())
12684           return;
12685         if (VD->getType().isConstQualified() &&
12686             !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
12687           return;
12688         if (CUDADiagIfDeviceCode(VD->getLocation(),
12689                                  diag::err_device_static_local_var)
12690             << CurrentCUDATarget())
12691           VD->setInvalidDecl();
12692       }();
12693     }
12694   }
12695 
12696   // Perform check for initializers of device-side global variables.
12697   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
12698   // 7.5). We must also apply the same checks to all __shared__
12699   // variables whether they are local or not. CUDA also allows
12700   // constant initializers for __constant__ and __device__ variables.
12701   if (getLangOpts().CUDA)
12702     checkAllowedCUDAInitializer(VD);
12703 
12704   // Grab the dllimport or dllexport attribute off of the VarDecl.
12705   const InheritableAttr *DLLAttr = getDLLAttr(VD);
12706 
12707   // Imported static data members cannot be defined out-of-line.
12708   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
12709     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
12710         VD->isThisDeclarationADefinition()) {
12711       // We allow definitions of dllimport class template static data members
12712       // with a warning.
12713       CXXRecordDecl *Context =
12714         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
12715       bool IsClassTemplateMember =
12716           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
12717           Context->getDescribedClassTemplate();
12718 
12719       Diag(VD->getLocation(),
12720            IsClassTemplateMember
12721                ? diag::warn_attribute_dllimport_static_field_definition
12722                : diag::err_attribute_dllimport_static_field_definition);
12723       Diag(IA->getLocation(), diag::note_attribute);
12724       if (!IsClassTemplateMember)
12725         VD->setInvalidDecl();
12726     }
12727   }
12728 
12729   // dllimport/dllexport variables cannot be thread local, their TLS index
12730   // isn't exported with the variable.
12731   if (DLLAttr && VD->getTLSKind()) {
12732     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12733     if (F && getDLLAttr(F)) {
12734       assert(VD->isStaticLocal());
12735       // But if this is a static local in a dlimport/dllexport function, the
12736       // function will never be inlined, which means the var would never be
12737       // imported, so having it marked import/export is safe.
12738     } else {
12739       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
12740                                                                     << DLLAttr;
12741       VD->setInvalidDecl();
12742     }
12743   }
12744 
12745   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
12746     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
12747       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
12748       VD->dropAttr<UsedAttr>();
12749     }
12750   }
12751 
12752   const DeclContext *DC = VD->getDeclContext();
12753   // If there's a #pragma GCC visibility in scope, and this isn't a class
12754   // member, set the visibility of this variable.
12755   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
12756     AddPushedVisibilityAttribute(VD);
12757 
12758   // FIXME: Warn on unused var template partial specializations.
12759   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
12760     MarkUnusedFileScopedDecl(VD);
12761 
12762   // Now we have parsed the initializer and can update the table of magic
12763   // tag values.
12764   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
12765       !VD->getType()->isIntegralOrEnumerationType())
12766     return;
12767 
12768   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
12769     const Expr *MagicValueExpr = VD->getInit();
12770     if (!MagicValueExpr) {
12771       continue;
12772     }
12773     llvm::APSInt MagicValueInt;
12774     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
12775       Diag(I->getRange().getBegin(),
12776            diag::err_type_tag_for_datatype_not_ice)
12777         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12778       continue;
12779     }
12780     if (MagicValueInt.getActiveBits() > 64) {
12781       Diag(I->getRange().getBegin(),
12782            diag::err_type_tag_for_datatype_too_large)
12783         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12784       continue;
12785     }
12786     uint64_t MagicValue = MagicValueInt.getZExtValue();
12787     RegisterTypeTagForDatatype(I->getArgumentKind(),
12788                                MagicValue,
12789                                I->getMatchingCType(),
12790                                I->getLayoutCompatible(),
12791                                I->getMustBeNull());
12792   }
12793 }
12794 
12795 static bool hasDeducedAuto(DeclaratorDecl *DD) {
12796   auto *VD = dyn_cast<VarDecl>(DD);
12797   return VD && !VD->getType()->hasAutoForTrailingReturnType();
12798 }
12799 
12800 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
12801                                                    ArrayRef<Decl *> Group) {
12802   SmallVector<Decl*, 8> Decls;
12803 
12804   if (DS.isTypeSpecOwned())
12805     Decls.push_back(DS.getRepAsDecl());
12806 
12807   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
12808   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
12809   bool DiagnosedMultipleDecomps = false;
12810   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
12811   bool DiagnosedNonDeducedAuto = false;
12812 
12813   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12814     if (Decl *D = Group[i]) {
12815       // For declarators, there are some additional syntactic-ish checks we need
12816       // to perform.
12817       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
12818         if (!FirstDeclaratorInGroup)
12819           FirstDeclaratorInGroup = DD;
12820         if (!FirstDecompDeclaratorInGroup)
12821           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
12822         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
12823             !hasDeducedAuto(DD))
12824           FirstNonDeducedAutoInGroup = DD;
12825 
12826         if (FirstDeclaratorInGroup != DD) {
12827           // A decomposition declaration cannot be combined with any other
12828           // declaration in the same group.
12829           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
12830             Diag(FirstDecompDeclaratorInGroup->getLocation(),
12831                  diag::err_decomp_decl_not_alone)
12832                 << FirstDeclaratorInGroup->getSourceRange()
12833                 << DD->getSourceRange();
12834             DiagnosedMultipleDecomps = true;
12835           }
12836 
12837           // A declarator that uses 'auto' in any way other than to declare a
12838           // variable with a deduced type cannot be combined with any other
12839           // declarator in the same group.
12840           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
12841             Diag(FirstNonDeducedAutoInGroup->getLocation(),
12842                  diag::err_auto_non_deduced_not_alone)
12843                 << FirstNonDeducedAutoInGroup->getType()
12844                        ->hasAutoForTrailingReturnType()
12845                 << FirstDeclaratorInGroup->getSourceRange()
12846                 << DD->getSourceRange();
12847             DiagnosedNonDeducedAuto = true;
12848           }
12849         }
12850       }
12851 
12852       Decls.push_back(D);
12853     }
12854   }
12855 
12856   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
12857     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
12858       handleTagNumbering(Tag, S);
12859       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
12860           getLangOpts().CPlusPlus)
12861         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
12862     }
12863   }
12864 
12865   return BuildDeclaratorGroup(Decls);
12866 }
12867 
12868 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
12869 /// group, performing any necessary semantic checking.
12870 Sema::DeclGroupPtrTy
12871 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
12872   // C++14 [dcl.spec.auto]p7: (DR1347)
12873   //   If the type that replaces the placeholder type is not the same in each
12874   //   deduction, the program is ill-formed.
12875   if (Group.size() > 1) {
12876     QualType Deduced;
12877     VarDecl *DeducedDecl = nullptr;
12878     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12879       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
12880       if (!D || D->isInvalidDecl())
12881         break;
12882       DeducedType *DT = D->getType()->getContainedDeducedType();
12883       if (!DT || DT->getDeducedType().isNull())
12884         continue;
12885       if (Deduced.isNull()) {
12886         Deduced = DT->getDeducedType();
12887         DeducedDecl = D;
12888       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
12889         auto *AT = dyn_cast<AutoType>(DT);
12890         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
12891              diag::err_auto_different_deductions)
12892           << (AT ? (unsigned)AT->getKeyword() : 3)
12893           << Deduced << DeducedDecl->getDeclName()
12894           << DT->getDeducedType() << D->getDeclName()
12895           << DeducedDecl->getInit()->getSourceRange()
12896           << D->getInit()->getSourceRange();
12897         D->setInvalidDecl();
12898         break;
12899       }
12900     }
12901   }
12902 
12903   ActOnDocumentableDecls(Group);
12904 
12905   return DeclGroupPtrTy::make(
12906       DeclGroupRef::Create(Context, Group.data(), Group.size()));
12907 }
12908 
12909 void Sema::ActOnDocumentableDecl(Decl *D) {
12910   ActOnDocumentableDecls(D);
12911 }
12912 
12913 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
12914   // Don't parse the comment if Doxygen diagnostics are ignored.
12915   if (Group.empty() || !Group[0])
12916     return;
12917 
12918   if (Diags.isIgnored(diag::warn_doc_param_not_found,
12919                       Group[0]->getLocation()) &&
12920       Diags.isIgnored(diag::warn_unknown_comment_command_name,
12921                       Group[0]->getLocation()))
12922     return;
12923 
12924   if (Group.size() >= 2) {
12925     // This is a decl group.  Normally it will contain only declarations
12926     // produced from declarator list.  But in case we have any definitions or
12927     // additional declaration references:
12928     //   'typedef struct S {} S;'
12929     //   'typedef struct S *S;'
12930     //   'struct S *pS;'
12931     // FinalizeDeclaratorGroup adds these as separate declarations.
12932     Decl *MaybeTagDecl = Group[0];
12933     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
12934       Group = Group.slice(1);
12935     }
12936   }
12937 
12938   // FIMXE: We assume every Decl in the group is in the same file.
12939   // This is false when preprocessor constructs the group from decls in
12940   // different files (e. g. macros or #include).
12941   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
12942 }
12943 
12944 /// Common checks for a parameter-declaration that should apply to both function
12945 /// parameters and non-type template parameters.
12946 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
12947   // Check that there are no default arguments inside the type of this
12948   // parameter.
12949   if (getLangOpts().CPlusPlus)
12950     CheckExtraCXXDefaultArguments(D);
12951 
12952   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
12953   if (D.getCXXScopeSpec().isSet()) {
12954     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
12955       << D.getCXXScopeSpec().getRange();
12956   }
12957 
12958   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
12959   // simple identifier except [...irrelevant cases...].
12960   switch (D.getName().getKind()) {
12961   case UnqualifiedIdKind::IK_Identifier:
12962     break;
12963 
12964   case UnqualifiedIdKind::IK_OperatorFunctionId:
12965   case UnqualifiedIdKind::IK_ConversionFunctionId:
12966   case UnqualifiedIdKind::IK_LiteralOperatorId:
12967   case UnqualifiedIdKind::IK_ConstructorName:
12968   case UnqualifiedIdKind::IK_DestructorName:
12969   case UnqualifiedIdKind::IK_ImplicitSelfParam:
12970   case UnqualifiedIdKind::IK_DeductionGuideName:
12971     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
12972       << GetNameForDeclarator(D).getName();
12973     break;
12974 
12975   case UnqualifiedIdKind::IK_TemplateId:
12976   case UnqualifiedIdKind::IK_ConstructorTemplateId:
12977     // GetNameForDeclarator would not produce a useful name in this case.
12978     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
12979     break;
12980   }
12981 }
12982 
12983 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
12984 /// to introduce parameters into function prototype scope.
12985 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
12986   const DeclSpec &DS = D.getDeclSpec();
12987 
12988   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
12989 
12990   // C++03 [dcl.stc]p2 also permits 'auto'.
12991   StorageClass SC = SC_None;
12992   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
12993     SC = SC_Register;
12994     // In C++11, the 'register' storage class specifier is deprecated.
12995     // In C++17, it is not allowed, but we tolerate it as an extension.
12996     if (getLangOpts().CPlusPlus11) {
12997       Diag(DS.getStorageClassSpecLoc(),
12998            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
12999                                      : diag::warn_deprecated_register)
13000         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13001     }
13002   } else if (getLangOpts().CPlusPlus &&
13003              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13004     SC = SC_Auto;
13005   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13006     Diag(DS.getStorageClassSpecLoc(),
13007          diag::err_invalid_storage_class_in_func_decl);
13008     D.getMutableDeclSpec().ClearStorageClassSpecs();
13009   }
13010 
13011   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13012     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13013       << DeclSpec::getSpecifierName(TSCS);
13014   if (DS.isInlineSpecified())
13015     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13016         << getLangOpts().CPlusPlus17;
13017   if (DS.hasConstexprSpecifier())
13018     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13019         << 0 << D.getDeclSpec().getConstexprSpecifier();
13020 
13021   DiagnoseFunctionSpecifiers(DS);
13022 
13023   CheckFunctionOrTemplateParamDeclarator(S, D);
13024 
13025   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13026   QualType parmDeclType = TInfo->getType();
13027 
13028   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13029   IdentifierInfo *II = D.getIdentifier();
13030   if (II) {
13031     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13032                    ForVisibleRedeclaration);
13033     LookupName(R, S);
13034     if (R.isSingleResult()) {
13035       NamedDecl *PrevDecl = R.getFoundDecl();
13036       if (PrevDecl->isTemplateParameter()) {
13037         // Maybe we will complain about the shadowed template parameter.
13038         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13039         // Just pretend that we didn't see the previous declaration.
13040         PrevDecl = nullptr;
13041       } else if (S->isDeclScope(PrevDecl)) {
13042         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13043         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13044 
13045         // Recover by removing the name
13046         II = nullptr;
13047         D.SetIdentifier(nullptr, D.getIdentifierLoc());
13048         D.setInvalidType(true);
13049       }
13050     }
13051   }
13052 
13053   // Temporarily put parameter variables in the translation unit, not
13054   // the enclosing context.  This prevents them from accidentally
13055   // looking like class members in C++.
13056   ParmVarDecl *New =
13057       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13058                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13059 
13060   if (D.isInvalidType())
13061     New->setInvalidDecl();
13062 
13063   assert(S->isFunctionPrototypeScope());
13064   assert(S->getFunctionPrototypeDepth() >= 1);
13065   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13066                     S->getNextFunctionPrototypeIndex());
13067 
13068   // Add the parameter declaration into this scope.
13069   S->AddDecl(New);
13070   if (II)
13071     IdResolver.AddDecl(New);
13072 
13073   ProcessDeclAttributes(S, New, D);
13074 
13075   if (D.getDeclSpec().isModulePrivateSpecified())
13076     Diag(New->getLocation(), diag::err_module_private_local)
13077       << 1 << New->getDeclName()
13078       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13079       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13080 
13081   if (New->hasAttr<BlocksAttr>()) {
13082     Diag(New->getLocation(), diag::err_block_on_nonlocal);
13083   }
13084   return New;
13085 }
13086 
13087 /// Synthesizes a variable for a parameter arising from a
13088 /// typedef.
13089 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13090                                               SourceLocation Loc,
13091                                               QualType T) {
13092   /* FIXME: setting StartLoc == Loc.
13093      Would it be worth to modify callers so as to provide proper source
13094      location for the unnamed parameters, embedding the parameter's type? */
13095   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13096                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
13097                                            SC_None, nullptr);
13098   Param->setImplicit();
13099   return Param;
13100 }
13101 
13102 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13103   // Don't diagnose unused-parameter errors in template instantiations; we
13104   // will already have done so in the template itself.
13105   if (inTemplateInstantiation())
13106     return;
13107 
13108   for (const ParmVarDecl *Parameter : Parameters) {
13109     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13110         !Parameter->hasAttr<UnusedAttr>()) {
13111       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13112         << Parameter->getDeclName();
13113     }
13114   }
13115 }
13116 
13117 void Sema::DiagnoseSizeOfParametersAndReturnValue(
13118     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13119   if (LangOpts.NumLargeByValueCopy == 0) // No check.
13120     return;
13121 
13122   // Warn if the return value is pass-by-value and larger than the specified
13123   // threshold.
13124   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13125     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13126     if (Size > LangOpts.NumLargeByValueCopy)
13127       Diag(D->getLocation(), diag::warn_return_value_size)
13128           << D->getDeclName() << Size;
13129   }
13130 
13131   // Warn if any parameter is pass-by-value and larger than the specified
13132   // threshold.
13133   for (const ParmVarDecl *Parameter : Parameters) {
13134     QualType T = Parameter->getType();
13135     if (T->isDependentType() || !T.isPODType(Context))
13136       continue;
13137     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13138     if (Size > LangOpts.NumLargeByValueCopy)
13139       Diag(Parameter->getLocation(), diag::warn_parameter_size)
13140           << Parameter->getDeclName() << Size;
13141   }
13142 }
13143 
13144 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13145                                   SourceLocation NameLoc, IdentifierInfo *Name,
13146                                   QualType T, TypeSourceInfo *TSInfo,
13147                                   StorageClass SC) {
13148   // In ARC, infer a lifetime qualifier for appropriate parameter types.
13149   if (getLangOpts().ObjCAutoRefCount &&
13150       T.getObjCLifetime() == Qualifiers::OCL_None &&
13151       T->isObjCLifetimeType()) {
13152 
13153     Qualifiers::ObjCLifetime lifetime;
13154 
13155     // Special cases for arrays:
13156     //   - if it's const, use __unsafe_unretained
13157     //   - otherwise, it's an error
13158     if (T->isArrayType()) {
13159       if (!T.isConstQualified()) {
13160         if (DelayedDiagnostics.shouldDelayDiagnostics())
13161           DelayedDiagnostics.add(
13162               sema::DelayedDiagnostic::makeForbiddenType(
13163               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13164         else
13165           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13166               << TSInfo->getTypeLoc().getSourceRange();
13167       }
13168       lifetime = Qualifiers::OCL_ExplicitNone;
13169     } else {
13170       lifetime = T->getObjCARCImplicitLifetime();
13171     }
13172     T = Context.getLifetimeQualifiedType(T, lifetime);
13173   }
13174 
13175   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13176                                          Context.getAdjustedParameterType(T),
13177                                          TSInfo, SC, nullptr);
13178 
13179   // Make a note if we created a new pack in the scope of a lambda, so that
13180   // we know that references to that pack must also be expanded within the
13181   // lambda scope.
13182   if (New->isParameterPack())
13183     if (auto *LSI = getEnclosingLambda())
13184       LSI->LocalPacks.push_back(New);
13185 
13186   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13187       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13188     checkNonTrivialCUnion(New->getType(), New->getLocation(),
13189                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13190 
13191   // Parameters can not be abstract class types.
13192   // For record types, this is done by the AbstractClassUsageDiagnoser once
13193   // the class has been completely parsed.
13194   if (!CurContext->isRecord() &&
13195       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13196                              AbstractParamType))
13197     New->setInvalidDecl();
13198 
13199   // Parameter declarators cannot be interface types. All ObjC objects are
13200   // passed by reference.
13201   if (T->isObjCObjectType()) {
13202     SourceLocation TypeEndLoc =
13203         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13204     Diag(NameLoc,
13205          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13206       << FixItHint::CreateInsertion(TypeEndLoc, "*");
13207     T = Context.getObjCObjectPointerType(T);
13208     New->setType(T);
13209   }
13210 
13211   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13212   // duration shall not be qualified by an address-space qualifier."
13213   // Since all parameters have automatic store duration, they can not have
13214   // an address space.
13215   if (T.getAddressSpace() != LangAS::Default &&
13216       // OpenCL allows function arguments declared to be an array of a type
13217       // to be qualified with an address space.
13218       !(getLangOpts().OpenCL &&
13219         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13220     Diag(NameLoc, diag::err_arg_with_address_space);
13221     New->setInvalidDecl();
13222   }
13223 
13224   return New;
13225 }
13226 
13227 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
13228                                            SourceLocation LocAfterDecls) {
13229   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
13230 
13231   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
13232   // for a K&R function.
13233   if (!FTI.hasPrototype) {
13234     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
13235       --i;
13236       if (FTI.Params[i].Param == nullptr) {
13237         SmallString<256> Code;
13238         llvm::raw_svector_ostream(Code)
13239             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
13240         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
13241             << FTI.Params[i].Ident
13242             << FixItHint::CreateInsertion(LocAfterDecls, Code);
13243 
13244         // Implicitly declare the argument as type 'int' for lack of a better
13245         // type.
13246         AttributeFactory attrs;
13247         DeclSpec DS(attrs);
13248         const char* PrevSpec; // unused
13249         unsigned DiagID; // unused
13250         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
13251                            DiagID, Context.getPrintingPolicy());
13252         // Use the identifier location for the type source range.
13253         DS.SetRangeStart(FTI.Params[i].IdentLoc);
13254         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
13255         Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
13256         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
13257         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
13258       }
13259     }
13260   }
13261 }
13262 
13263 Decl *
13264 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
13265                               MultiTemplateParamsArg TemplateParameterLists,
13266                               SkipBodyInfo *SkipBody) {
13267   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
13268   assert(D.isFunctionDeclarator() && "Not a function declarator!");
13269   Scope *ParentScope = FnBodyScope->getParent();
13270 
13271   D.setFunctionDefinitionKind(FDK_Definition);
13272   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
13273   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
13274 }
13275 
13276 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
13277   Consumer.HandleInlineFunctionDefinition(D);
13278 }
13279 
13280 static bool
13281 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
13282                                 const FunctionDecl *&PossiblePrototype) {
13283   // Don't warn about invalid declarations.
13284   if (FD->isInvalidDecl())
13285     return false;
13286 
13287   // Or declarations that aren't global.
13288   if (!FD->isGlobal())
13289     return false;
13290 
13291   // Don't warn about C++ member functions.
13292   if (isa<CXXMethodDecl>(FD))
13293     return false;
13294 
13295   // Don't warn about 'main'.
13296   if (FD->isMain())
13297     return false;
13298 
13299   // Don't warn about inline functions.
13300   if (FD->isInlined())
13301     return false;
13302 
13303   // Don't warn about function templates.
13304   if (FD->getDescribedFunctionTemplate())
13305     return false;
13306 
13307   // Don't warn about function template specializations.
13308   if (FD->isFunctionTemplateSpecialization())
13309     return false;
13310 
13311   // Don't warn for OpenCL kernels.
13312   if (FD->hasAttr<OpenCLKernelAttr>())
13313     return false;
13314 
13315   // Don't warn on explicitly deleted functions.
13316   if (FD->isDeleted())
13317     return false;
13318 
13319   for (const FunctionDecl *Prev = FD->getPreviousDecl();
13320        Prev; Prev = Prev->getPreviousDecl()) {
13321     // Ignore any declarations that occur in function or method
13322     // scope, because they aren't visible from the header.
13323     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
13324       continue;
13325 
13326     PossiblePrototype = Prev;
13327     return Prev->getType()->isFunctionNoProtoType();
13328   }
13329 
13330   return true;
13331 }
13332 
13333 void
13334 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
13335                                    const FunctionDecl *EffectiveDefinition,
13336                                    SkipBodyInfo *SkipBody) {
13337   const FunctionDecl *Definition = EffectiveDefinition;
13338   if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
13339     // If this is a friend function defined in a class template, it does not
13340     // have a body until it is used, nevertheless it is a definition, see
13341     // [temp.inst]p2:
13342     //
13343     // ... for the purpose of determining whether an instantiated redeclaration
13344     // is valid according to [basic.def.odr] and [class.mem], a declaration that
13345     // corresponds to a definition in the template is considered to be a
13346     // definition.
13347     //
13348     // The following code must produce redefinition error:
13349     //
13350     //     template<typename T> struct C20 { friend void func_20() {} };
13351     //     C20<int> c20i;
13352     //     void func_20() {}
13353     //
13354     for (auto I : FD->redecls()) {
13355       if (I != FD && !I->isInvalidDecl() &&
13356           I->getFriendObjectKind() != Decl::FOK_None) {
13357         if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
13358           if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
13359             // A merged copy of the same function, instantiated as a member of
13360             // the same class, is OK.
13361             if (declaresSameEntity(OrigFD, Original) &&
13362                 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
13363                                    cast<Decl>(FD->getLexicalDeclContext())))
13364               continue;
13365           }
13366 
13367           if (Original->isThisDeclarationADefinition()) {
13368             Definition = I;
13369             break;
13370           }
13371         }
13372       }
13373     }
13374   }
13375 
13376   if (!Definition)
13377     // Similar to friend functions a friend function template may be a
13378     // definition and do not have a body if it is instantiated in a class
13379     // template.
13380     if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
13381       for (auto I : FTD->redecls()) {
13382         auto D = cast<FunctionTemplateDecl>(I);
13383         if (D != FTD) {
13384           assert(!D->isThisDeclarationADefinition() &&
13385                  "More than one definition in redeclaration chain");
13386           if (D->getFriendObjectKind() != Decl::FOK_None)
13387             if (FunctionTemplateDecl *FT =
13388                                        D->getInstantiatedFromMemberTemplate()) {
13389               if (FT->isThisDeclarationADefinition()) {
13390                 Definition = D->getTemplatedDecl();
13391                 break;
13392               }
13393             }
13394         }
13395       }
13396     }
13397 
13398   if (!Definition)
13399     return;
13400 
13401   if (canRedefineFunction(Definition, getLangOpts()))
13402     return;
13403 
13404   // Don't emit an error when this is redefinition of a typo-corrected
13405   // definition.
13406   if (TypoCorrectedFunctionDefinitions.count(Definition))
13407     return;
13408 
13409   // If we don't have a visible definition of the function, and it's inline or
13410   // a template, skip the new definition.
13411   if (SkipBody && !hasVisibleDefinition(Definition) &&
13412       (Definition->getFormalLinkage() == InternalLinkage ||
13413        Definition->isInlined() ||
13414        Definition->getDescribedFunctionTemplate() ||
13415        Definition->getNumTemplateParameterLists())) {
13416     SkipBody->ShouldSkip = true;
13417     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
13418     if (auto *TD = Definition->getDescribedFunctionTemplate())
13419       makeMergedDefinitionVisible(TD);
13420     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
13421     return;
13422   }
13423 
13424   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
13425       Definition->getStorageClass() == SC_Extern)
13426     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
13427         << FD->getDeclName() << getLangOpts().CPlusPlus;
13428   else
13429     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
13430 
13431   Diag(Definition->getLocation(), diag::note_previous_definition);
13432   FD->setInvalidDecl();
13433 }
13434 
13435 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
13436                                    Sema &S) {
13437   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
13438 
13439   LambdaScopeInfo *LSI = S.PushLambdaScope();
13440   LSI->CallOperator = CallOperator;
13441   LSI->Lambda = LambdaClass;
13442   LSI->ReturnType = CallOperator->getReturnType();
13443   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
13444 
13445   if (LCD == LCD_None)
13446     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
13447   else if (LCD == LCD_ByCopy)
13448     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
13449   else if (LCD == LCD_ByRef)
13450     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
13451   DeclarationNameInfo DNI = CallOperator->getNameInfo();
13452 
13453   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
13454   LSI->Mutable = !CallOperator->isConst();
13455 
13456   // Add the captures to the LSI so they can be noted as already
13457   // captured within tryCaptureVar.
13458   auto I = LambdaClass->field_begin();
13459   for (const auto &C : LambdaClass->captures()) {
13460     if (C.capturesVariable()) {
13461       VarDecl *VD = C.getCapturedVar();
13462       if (VD->isInitCapture())
13463         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
13464       QualType CaptureType = VD->getType();
13465       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
13466       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
13467           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
13468           /*EllipsisLoc*/C.isPackExpansion()
13469                          ? C.getEllipsisLoc() : SourceLocation(),
13470           CaptureType, /*Invalid*/false);
13471 
13472     } else if (C.capturesThis()) {
13473       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
13474                           C.getCaptureKind() == LCK_StarThis);
13475     } else {
13476       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
13477                              I->getType());
13478     }
13479     ++I;
13480   }
13481 }
13482 
13483 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
13484                                     SkipBodyInfo *SkipBody) {
13485   if (!D) {
13486     // Parsing the function declaration failed in some way. Push on a fake scope
13487     // anyway so we can try to parse the function body.
13488     PushFunctionScope();
13489     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13490     return D;
13491   }
13492 
13493   FunctionDecl *FD = nullptr;
13494 
13495   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
13496     FD = FunTmpl->getTemplatedDecl();
13497   else
13498     FD = cast<FunctionDecl>(D);
13499 
13500   // Do not push if it is a lambda because one is already pushed when building
13501   // the lambda in ActOnStartOfLambdaDefinition().
13502   if (!isLambdaCallOperator(FD))
13503     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13504 
13505   // Check for defining attributes before the check for redefinition.
13506   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
13507     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
13508     FD->dropAttr<AliasAttr>();
13509     FD->setInvalidDecl();
13510   }
13511   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
13512     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
13513     FD->dropAttr<IFuncAttr>();
13514     FD->setInvalidDecl();
13515   }
13516 
13517   // See if this is a redefinition. If 'will have body' is already set, then
13518   // these checks were already performed when it was set.
13519   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
13520     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
13521 
13522     // If we're skipping the body, we're done. Don't enter the scope.
13523     if (SkipBody && SkipBody->ShouldSkip)
13524       return D;
13525   }
13526 
13527   // Mark this function as "will have a body eventually".  This lets users to
13528   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
13529   // this function.
13530   FD->setWillHaveBody();
13531 
13532   // If we are instantiating a generic lambda call operator, push
13533   // a LambdaScopeInfo onto the function stack.  But use the information
13534   // that's already been calculated (ActOnLambdaExpr) to prime the current
13535   // LambdaScopeInfo.
13536   // When the template operator is being specialized, the LambdaScopeInfo,
13537   // has to be properly restored so that tryCaptureVariable doesn't try
13538   // and capture any new variables. In addition when calculating potential
13539   // captures during transformation of nested lambdas, it is necessary to
13540   // have the LSI properly restored.
13541   if (isGenericLambdaCallOperatorSpecialization(FD)) {
13542     assert(inTemplateInstantiation() &&
13543            "There should be an active template instantiation on the stack "
13544            "when instantiating a generic lambda!");
13545     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
13546   } else {
13547     // Enter a new function scope
13548     PushFunctionScope();
13549   }
13550 
13551   // Builtin functions cannot be defined.
13552   if (unsigned BuiltinID = FD->getBuiltinID()) {
13553     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
13554         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
13555       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
13556       FD->setInvalidDecl();
13557     }
13558   }
13559 
13560   // The return type of a function definition must be complete
13561   // (C99 6.9.1p3, C++ [dcl.fct]p6).
13562   QualType ResultType = FD->getReturnType();
13563   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
13564       !FD->isInvalidDecl() &&
13565       RequireCompleteType(FD->getLocation(), ResultType,
13566                           diag::err_func_def_incomplete_result))
13567     FD->setInvalidDecl();
13568 
13569   if (FnBodyScope)
13570     PushDeclContext(FnBodyScope, FD);
13571 
13572   // Check the validity of our function parameters
13573   CheckParmsForFunctionDef(FD->parameters(),
13574                            /*CheckParameterNames=*/true);
13575 
13576   // Add non-parameter declarations already in the function to the current
13577   // scope.
13578   if (FnBodyScope) {
13579     for (Decl *NPD : FD->decls()) {
13580       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
13581       if (!NonParmDecl)
13582         continue;
13583       assert(!isa<ParmVarDecl>(NonParmDecl) &&
13584              "parameters should not be in newly created FD yet");
13585 
13586       // If the decl has a name, make it accessible in the current scope.
13587       if (NonParmDecl->getDeclName())
13588         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
13589 
13590       // Similarly, dive into enums and fish their constants out, making them
13591       // accessible in this scope.
13592       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
13593         for (auto *EI : ED->enumerators())
13594           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
13595       }
13596     }
13597   }
13598 
13599   // Introduce our parameters into the function scope
13600   for (auto Param : FD->parameters()) {
13601     Param->setOwningFunction(FD);
13602 
13603     // If this has an identifier, add it to the scope stack.
13604     if (Param->getIdentifier() && FnBodyScope) {
13605       CheckShadow(FnBodyScope, Param);
13606 
13607       PushOnScopeChains(Param, FnBodyScope);
13608     }
13609   }
13610 
13611   // Ensure that the function's exception specification is instantiated.
13612   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
13613     ResolveExceptionSpec(D->getLocation(), FPT);
13614 
13615   // dllimport cannot be applied to non-inline function definitions.
13616   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
13617       !FD->isTemplateInstantiation()) {
13618     assert(!FD->hasAttr<DLLExportAttr>());
13619     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
13620     FD->setInvalidDecl();
13621     return D;
13622   }
13623   // We want to attach documentation to original Decl (which might be
13624   // a function template).
13625   ActOnDocumentableDecl(D);
13626   if (getCurLexicalContext()->isObjCContainer() &&
13627       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
13628       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
13629     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
13630 
13631   return D;
13632 }
13633 
13634 /// Given the set of return statements within a function body,
13635 /// compute the variables that are subject to the named return value
13636 /// optimization.
13637 ///
13638 /// Each of the variables that is subject to the named return value
13639 /// optimization will be marked as NRVO variables in the AST, and any
13640 /// return statement that has a marked NRVO variable as its NRVO candidate can
13641 /// use the named return value optimization.
13642 ///
13643 /// This function applies a very simplistic algorithm for NRVO: if every return
13644 /// statement in the scope of a variable has the same NRVO candidate, that
13645 /// candidate is an NRVO variable.
13646 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
13647   ReturnStmt **Returns = Scope->Returns.data();
13648 
13649   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
13650     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
13651       if (!NRVOCandidate->isNRVOVariable())
13652         Returns[I]->setNRVOCandidate(nullptr);
13653     }
13654   }
13655 }
13656 
13657 bool Sema::canDelayFunctionBody(const Declarator &D) {
13658   // We can't delay parsing the body of a constexpr function template (yet).
13659   if (D.getDeclSpec().hasConstexprSpecifier())
13660     return false;
13661 
13662   // We can't delay parsing the body of a function template with a deduced
13663   // return type (yet).
13664   if (D.getDeclSpec().hasAutoTypeSpec()) {
13665     // If the placeholder introduces a non-deduced trailing return type,
13666     // we can still delay parsing it.
13667     if (D.getNumTypeObjects()) {
13668       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
13669       if (Outer.Kind == DeclaratorChunk::Function &&
13670           Outer.Fun.hasTrailingReturnType()) {
13671         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
13672         return Ty.isNull() || !Ty->isUndeducedType();
13673       }
13674     }
13675     return false;
13676   }
13677 
13678   return true;
13679 }
13680 
13681 bool Sema::canSkipFunctionBody(Decl *D) {
13682   // We cannot skip the body of a function (or function template) which is
13683   // constexpr, since we may need to evaluate its body in order to parse the
13684   // rest of the file.
13685   // We cannot skip the body of a function with an undeduced return type,
13686   // because any callers of that function need to know the type.
13687   if (const FunctionDecl *FD = D->getAsFunction()) {
13688     if (FD->isConstexpr())
13689       return false;
13690     // We can't simply call Type::isUndeducedType here, because inside template
13691     // auto can be deduced to a dependent type, which is not considered
13692     // "undeduced".
13693     if (FD->getReturnType()->getContainedDeducedType())
13694       return false;
13695   }
13696   return Consumer.shouldSkipFunctionBody(D);
13697 }
13698 
13699 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
13700   if (!Decl)
13701     return nullptr;
13702   if (FunctionDecl *FD = Decl->getAsFunction())
13703     FD->setHasSkippedBody();
13704   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
13705     MD->setHasSkippedBody();
13706   return Decl;
13707 }
13708 
13709 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
13710   return ActOnFinishFunctionBody(D, BodyArg, false);
13711 }
13712 
13713 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
13714 /// body.
13715 class ExitFunctionBodyRAII {
13716 public:
13717   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
13718   ~ExitFunctionBodyRAII() {
13719     if (!IsLambda)
13720       S.PopExpressionEvaluationContext();
13721   }
13722 
13723 private:
13724   Sema &S;
13725   bool IsLambda = false;
13726 };
13727 
13728 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
13729   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
13730 
13731   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
13732     if (EscapeInfo.count(BD))
13733       return EscapeInfo[BD];
13734 
13735     bool R = false;
13736     const BlockDecl *CurBD = BD;
13737 
13738     do {
13739       R = !CurBD->doesNotEscape();
13740       if (R)
13741         break;
13742       CurBD = CurBD->getParent()->getInnermostBlockDecl();
13743     } while (CurBD);
13744 
13745     return EscapeInfo[BD] = R;
13746   };
13747 
13748   // If the location where 'self' is implicitly retained is inside a escaping
13749   // block, emit a diagnostic.
13750   for (const std::pair<SourceLocation, const BlockDecl *> &P :
13751        S.ImplicitlyRetainedSelfLocs)
13752     if (IsOrNestedInEscapingBlock(P.second))
13753       S.Diag(P.first, diag::warn_implicitly_retains_self)
13754           << FixItHint::CreateInsertion(P.first, "self->");
13755 }
13756 
13757 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
13758                                     bool IsInstantiation) {
13759   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
13760 
13761   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13762   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
13763 
13764   if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
13765     CheckCompletedCoroutineBody(FD, Body);
13766 
13767   // Do not call PopExpressionEvaluationContext() if it is a lambda because one
13768   // is already popped when finishing the lambda in BuildLambdaExpr(). This is
13769   // meant to pop the context added in ActOnStartOfFunctionDef().
13770   ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
13771 
13772   if (FD) {
13773     FD->setBody(Body);
13774     FD->setWillHaveBody(false);
13775 
13776     if (getLangOpts().CPlusPlus14) {
13777       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
13778           FD->getReturnType()->isUndeducedType()) {
13779         // If the function has a deduced result type but contains no 'return'
13780         // statements, the result type as written must be exactly 'auto', and
13781         // the deduced result type is 'void'.
13782         if (!FD->getReturnType()->getAs<AutoType>()) {
13783           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
13784               << FD->getReturnType();
13785           FD->setInvalidDecl();
13786         } else {
13787           // Substitute 'void' for the 'auto' in the type.
13788           TypeLoc ResultType = getReturnTypeLoc(FD);
13789           Context.adjustDeducedFunctionResultType(
13790               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
13791         }
13792       }
13793     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
13794       // In C++11, we don't use 'auto' deduction rules for lambda call
13795       // operators because we don't support return type deduction.
13796       auto *LSI = getCurLambda();
13797       if (LSI->HasImplicitReturnType) {
13798         deduceClosureReturnType(*LSI);
13799 
13800         // C++11 [expr.prim.lambda]p4:
13801         //   [...] if there are no return statements in the compound-statement
13802         //   [the deduced type is] the type void
13803         QualType RetType =
13804             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
13805 
13806         // Update the return type to the deduced type.
13807         const FunctionProtoType *Proto =
13808             FD->getType()->getAs<FunctionProtoType>();
13809         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
13810                                             Proto->getExtProtoInfo()));
13811       }
13812     }
13813 
13814     // If the function implicitly returns zero (like 'main') or is naked,
13815     // don't complain about missing return statements.
13816     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
13817       WP.disableCheckFallThrough();
13818 
13819     // MSVC permits the use of pure specifier (=0) on function definition,
13820     // defined at class scope, warn about this non-standard construct.
13821     if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
13822       Diag(FD->getLocation(), diag::ext_pure_function_definition);
13823 
13824     if (!FD->isInvalidDecl()) {
13825       // Don't diagnose unused parameters of defaulted or deleted functions.
13826       if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
13827         DiagnoseUnusedParameters(FD->parameters());
13828       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
13829                                              FD->getReturnType(), FD);
13830 
13831       // If this is a structor, we need a vtable.
13832       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
13833         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
13834       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
13835         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
13836 
13837       // Try to apply the named return value optimization. We have to check
13838       // if we can do this here because lambdas keep return statements around
13839       // to deduce an implicit return type.
13840       if (FD->getReturnType()->isRecordType() &&
13841           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
13842         computeNRVO(Body, getCurFunction());
13843     }
13844 
13845     // GNU warning -Wmissing-prototypes:
13846     //   Warn if a global function is defined without a previous
13847     //   prototype declaration. This warning is issued even if the
13848     //   definition itself provides a prototype. The aim is to detect
13849     //   global functions that fail to be declared in header files.
13850     const FunctionDecl *PossiblePrototype = nullptr;
13851     if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
13852       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
13853 
13854       if (PossiblePrototype) {
13855         // We found a declaration that is not a prototype,
13856         // but that could be a zero-parameter prototype
13857         if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
13858           TypeLoc TL = TI->getTypeLoc();
13859           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
13860             Diag(PossiblePrototype->getLocation(),
13861                  diag::note_declaration_not_a_prototype)
13862                 << (FD->getNumParams() != 0)
13863                 << (FD->getNumParams() == 0
13864                         ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
13865                         : FixItHint{});
13866         }
13867       } else {
13868         Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13869             << /* function */ 1
13870             << (FD->getStorageClass() == SC_None
13871                     ? FixItHint::CreateInsertion(FD->getTypeSpecStartLoc(),
13872                                                  "static ")
13873                     : FixItHint{});
13874       }
13875 
13876       // GNU warning -Wstrict-prototypes
13877       //   Warn if K&R function is defined without a previous declaration.
13878       //   This warning is issued only if the definition itself does not provide
13879       //   a prototype. Only K&R definitions do not provide a prototype.
13880       //   An empty list in a function declarator that is part of a definition
13881       //   of that function specifies that the function has no parameters
13882       //   (C99 6.7.5.3p14)
13883       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
13884           !LangOpts.CPlusPlus) {
13885         TypeSourceInfo *TI = FD->getTypeSourceInfo();
13886         TypeLoc TL = TI->getTypeLoc();
13887         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
13888         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
13889       }
13890     }
13891 
13892     // Warn on CPUDispatch with an actual body.
13893     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
13894       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
13895         if (!CmpndBody->body_empty())
13896           Diag(CmpndBody->body_front()->getBeginLoc(),
13897                diag::warn_dispatch_body_ignored);
13898 
13899     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13900       const CXXMethodDecl *KeyFunction;
13901       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
13902           MD->isVirtual() &&
13903           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
13904           MD == KeyFunction->getCanonicalDecl()) {
13905         // Update the key-function state if necessary for this ABI.
13906         if (FD->isInlined() &&
13907             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13908           Context.setNonKeyFunction(MD);
13909 
13910           // If the newly-chosen key function is already defined, then we
13911           // need to mark the vtable as used retroactively.
13912           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
13913           const FunctionDecl *Definition;
13914           if (KeyFunction && KeyFunction->isDefined(Definition))
13915             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
13916         } else {
13917           // We just defined they key function; mark the vtable as used.
13918           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
13919         }
13920       }
13921     }
13922 
13923     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
13924            "Function parsing confused");
13925   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
13926     assert(MD == getCurMethodDecl() && "Method parsing confused");
13927     MD->setBody(Body);
13928     if (!MD->isInvalidDecl()) {
13929       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
13930                                              MD->getReturnType(), MD);
13931 
13932       if (Body)
13933         computeNRVO(Body, getCurFunction());
13934     }
13935     if (getCurFunction()->ObjCShouldCallSuper) {
13936       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
13937           << MD->getSelector().getAsString();
13938       getCurFunction()->ObjCShouldCallSuper = false;
13939     }
13940     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
13941       const ObjCMethodDecl *InitMethod = nullptr;
13942       bool isDesignated =
13943           MD->isDesignatedInitializerForTheInterface(&InitMethod);
13944       assert(isDesignated && InitMethod);
13945       (void)isDesignated;
13946 
13947       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
13948         auto IFace = MD->getClassInterface();
13949         if (!IFace)
13950           return false;
13951         auto SuperD = IFace->getSuperClass();
13952         if (!SuperD)
13953           return false;
13954         return SuperD->getIdentifier() ==
13955             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
13956       };
13957       // Don't issue this warning for unavailable inits or direct subclasses
13958       // of NSObject.
13959       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
13960         Diag(MD->getLocation(),
13961              diag::warn_objc_designated_init_missing_super_call);
13962         Diag(InitMethod->getLocation(),
13963              diag::note_objc_designated_init_marked_here);
13964       }
13965       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
13966     }
13967     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
13968       // Don't issue this warning for unavaialable inits.
13969       if (!MD->isUnavailable())
13970         Diag(MD->getLocation(),
13971              diag::warn_objc_secondary_init_missing_init_call);
13972       getCurFunction()->ObjCWarnForNoInitDelegation = false;
13973     }
13974 
13975     diagnoseImplicitlyRetainedSelf(*this);
13976   } else {
13977     // Parsing the function declaration failed in some way. Pop the fake scope
13978     // we pushed on.
13979     PopFunctionScopeInfo(ActivePolicy, dcl);
13980     return nullptr;
13981   }
13982 
13983   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13984     DiagnoseUnguardedAvailabilityViolations(dcl);
13985 
13986   assert(!getCurFunction()->ObjCShouldCallSuper &&
13987          "This should only be set for ObjC methods, which should have been "
13988          "handled in the block above.");
13989 
13990   // Verify and clean out per-function state.
13991   if (Body && (!FD || !FD->isDefaulted())) {
13992     // C++ constructors that have function-try-blocks can't have return
13993     // statements in the handlers of that block. (C++ [except.handle]p14)
13994     // Verify this.
13995     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
13996       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
13997 
13998     // Verify that gotos and switch cases don't jump into scopes illegally.
13999     if (getCurFunction()->NeedsScopeChecking() &&
14000         !PP.isCodeCompletionEnabled())
14001       DiagnoseInvalidJumps(Body);
14002 
14003     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14004       if (!Destructor->getParent()->isDependentType())
14005         CheckDestructor(Destructor);
14006 
14007       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14008                                              Destructor->getParent());
14009     }
14010 
14011     // If any errors have occurred, clear out any temporaries that may have
14012     // been leftover. This ensures that these temporaries won't be picked up for
14013     // deletion in some later function.
14014     if (getDiagnostics().hasErrorOccurred() ||
14015         getDiagnostics().getSuppressAllDiagnostics()) {
14016       DiscardCleanupsInEvaluationContext();
14017     }
14018     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
14019         !isa<FunctionTemplateDecl>(dcl)) {
14020       // Since the body is valid, issue any analysis-based warnings that are
14021       // enabled.
14022       ActivePolicy = &WP;
14023     }
14024 
14025     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14026         !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14027       FD->setInvalidDecl();
14028 
14029     if (FD && FD->hasAttr<NakedAttr>()) {
14030       for (const Stmt *S : Body->children()) {
14031         // Allow local register variables without initializer as they don't
14032         // require prologue.
14033         bool RegisterVariables = false;
14034         if (auto *DS = dyn_cast<DeclStmt>(S)) {
14035           for (const auto *Decl : DS->decls()) {
14036             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14037               RegisterVariables =
14038                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14039               if (!RegisterVariables)
14040                 break;
14041             }
14042           }
14043         }
14044         if (RegisterVariables)
14045           continue;
14046         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14047           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14048           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14049           FD->setInvalidDecl();
14050           break;
14051         }
14052       }
14053     }
14054 
14055     assert(ExprCleanupObjects.size() ==
14056                ExprEvalContexts.back().NumCleanupObjects &&
14057            "Leftover temporaries in function");
14058     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
14059     assert(MaybeODRUseExprs.empty() &&
14060            "Leftover expressions for odr-use checking");
14061   }
14062 
14063   if (!IsInstantiation)
14064     PopDeclContext();
14065 
14066   PopFunctionScopeInfo(ActivePolicy, dcl);
14067   // If any errors have occurred, clear out any temporaries that may have
14068   // been leftover. This ensures that these temporaries won't be picked up for
14069   // deletion in some later function.
14070   if (getDiagnostics().hasErrorOccurred()) {
14071     DiscardCleanupsInEvaluationContext();
14072   }
14073 
14074   return dcl;
14075 }
14076 
14077 /// When we finish delayed parsing of an attribute, we must attach it to the
14078 /// relevant Decl.
14079 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14080                                        ParsedAttributes &Attrs) {
14081   // Always attach attributes to the underlying decl.
14082   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14083     D = TD->getTemplatedDecl();
14084   ProcessDeclAttributeList(S, D, Attrs);
14085 
14086   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14087     if (Method->isStatic())
14088       checkThisInStaticMemberFunctionAttributes(Method);
14089 }
14090 
14091 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14092 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
14093 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14094                                           IdentifierInfo &II, Scope *S) {
14095   // Find the scope in which the identifier is injected and the corresponding
14096   // DeclContext.
14097   // FIXME: C89 does not say what happens if there is no enclosing block scope.
14098   // In that case, we inject the declaration into the translation unit scope
14099   // instead.
14100   Scope *BlockScope = S;
14101   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14102     BlockScope = BlockScope->getParent();
14103 
14104   Scope *ContextScope = BlockScope;
14105   while (!ContextScope->getEntity())
14106     ContextScope = ContextScope->getParent();
14107   ContextRAII SavedContext(*this, ContextScope->getEntity());
14108 
14109   // Before we produce a declaration for an implicitly defined
14110   // function, see whether there was a locally-scoped declaration of
14111   // this name as a function or variable. If so, use that
14112   // (non-visible) declaration, and complain about it.
14113   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14114   if (ExternCPrev) {
14115     // We still need to inject the function into the enclosing block scope so
14116     // that later (non-call) uses can see it.
14117     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14118 
14119     // C89 footnote 38:
14120     //   If in fact it is not defined as having type "function returning int",
14121     //   the behavior is undefined.
14122     if (!isa<FunctionDecl>(ExternCPrev) ||
14123         !Context.typesAreCompatible(
14124             cast<FunctionDecl>(ExternCPrev)->getType(),
14125             Context.getFunctionNoProtoType(Context.IntTy))) {
14126       Diag(Loc, diag::ext_use_out_of_scope_declaration)
14127           << ExternCPrev << !getLangOpts().C99;
14128       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14129       return ExternCPrev;
14130     }
14131   }
14132 
14133   // Extension in C99.  Legal in C90, but warn about it.
14134   unsigned diag_id;
14135   if (II.getName().startswith("__builtin_"))
14136     diag_id = diag::warn_builtin_unknown;
14137   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14138   else if (getLangOpts().OpenCL)
14139     diag_id = diag::err_opencl_implicit_function_decl;
14140   else if (getLangOpts().C99)
14141     diag_id = diag::ext_implicit_function_decl;
14142   else
14143     diag_id = diag::warn_implicit_function_decl;
14144   Diag(Loc, diag_id) << &II;
14145 
14146   // If we found a prior declaration of this function, don't bother building
14147   // another one. We've already pushed that one into scope, so there's nothing
14148   // more to do.
14149   if (ExternCPrev)
14150     return ExternCPrev;
14151 
14152   // Because typo correction is expensive, only do it if the implicit
14153   // function declaration is going to be treated as an error.
14154   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
14155     TypoCorrection Corrected;
14156     DeclFilterCCC<FunctionDecl> CCC{};
14157     if (S && (Corrected =
14158                   CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
14159                               S, nullptr, CCC, CTK_NonError)))
14160       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
14161                    /*ErrorRecovery*/false);
14162   }
14163 
14164   // Set a Declarator for the implicit definition: int foo();
14165   const char *Dummy;
14166   AttributeFactory attrFactory;
14167   DeclSpec DS(attrFactory);
14168   unsigned DiagID;
14169   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
14170                                   Context.getPrintingPolicy());
14171   (void)Error; // Silence warning.
14172   assert(!Error && "Error setting up implicit decl!");
14173   SourceLocation NoLoc;
14174   Declarator D(DS, DeclaratorContext::BlockContext);
14175   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
14176                                              /*IsAmbiguous=*/false,
14177                                              /*LParenLoc=*/NoLoc,
14178                                              /*Params=*/nullptr,
14179                                              /*NumParams=*/0,
14180                                              /*EllipsisLoc=*/NoLoc,
14181                                              /*RParenLoc=*/NoLoc,
14182                                              /*RefQualifierIsLvalueRef=*/true,
14183                                              /*RefQualifierLoc=*/NoLoc,
14184                                              /*MutableLoc=*/NoLoc, EST_None,
14185                                              /*ESpecRange=*/SourceRange(),
14186                                              /*Exceptions=*/nullptr,
14187                                              /*ExceptionRanges=*/nullptr,
14188                                              /*NumExceptions=*/0,
14189                                              /*NoexceptExpr=*/nullptr,
14190                                              /*ExceptionSpecTokens=*/nullptr,
14191                                              /*DeclsInPrototype=*/None, Loc,
14192                                              Loc, D),
14193                 std::move(DS.getAttributes()), SourceLocation());
14194   D.SetIdentifier(&II, Loc);
14195 
14196   // Insert this function into the enclosing block scope.
14197   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
14198   FD->setImplicit();
14199 
14200   AddKnownFunctionAttributes(FD);
14201 
14202   return FD;
14203 }
14204 
14205 /// Adds any function attributes that we know a priori based on
14206 /// the declaration of this function.
14207 ///
14208 /// These attributes can apply both to implicitly-declared builtins
14209 /// (like __builtin___printf_chk) or to library-declared functions
14210 /// like NSLog or printf.
14211 ///
14212 /// We need to check for duplicate attributes both here and where user-written
14213 /// attributes are applied to declarations.
14214 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
14215   if (FD->isInvalidDecl())
14216     return;
14217 
14218   // If this is a built-in function, map its builtin attributes to
14219   // actual attributes.
14220   if (unsigned BuiltinID = FD->getBuiltinID()) {
14221     // Handle printf-formatting attributes.
14222     unsigned FormatIdx;
14223     bool HasVAListArg;
14224     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
14225       if (!FD->hasAttr<FormatAttr>()) {
14226         const char *fmt = "printf";
14227         unsigned int NumParams = FD->getNumParams();
14228         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
14229             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
14230           fmt = "NSString";
14231         FD->addAttr(FormatAttr::CreateImplicit(Context,
14232                                                &Context.Idents.get(fmt),
14233                                                FormatIdx+1,
14234                                                HasVAListArg ? 0 : FormatIdx+2,
14235                                                FD->getLocation()));
14236       }
14237     }
14238     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
14239                                              HasVAListArg)) {
14240      if (!FD->hasAttr<FormatAttr>())
14241        FD->addAttr(FormatAttr::CreateImplicit(Context,
14242                                               &Context.Idents.get("scanf"),
14243                                               FormatIdx+1,
14244                                               HasVAListArg ? 0 : FormatIdx+2,
14245                                               FD->getLocation()));
14246     }
14247 
14248     // Handle automatically recognized callbacks.
14249     SmallVector<int, 4> Encoding;
14250     if (!FD->hasAttr<CallbackAttr>() &&
14251         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
14252       FD->addAttr(CallbackAttr::CreateImplicit(
14253           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
14254 
14255     // Mark const if we don't care about errno and that is the only thing
14256     // preventing the function from being const. This allows IRgen to use LLVM
14257     // intrinsics for such functions.
14258     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
14259         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
14260       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14261 
14262     // We make "fma" on some platforms const because we know it does not set
14263     // errno in those environments even though it could set errno based on the
14264     // C standard.
14265     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
14266     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
14267         !FD->hasAttr<ConstAttr>()) {
14268       switch (BuiltinID) {
14269       case Builtin::BI__builtin_fma:
14270       case Builtin::BI__builtin_fmaf:
14271       case Builtin::BI__builtin_fmal:
14272       case Builtin::BIfma:
14273       case Builtin::BIfmaf:
14274       case Builtin::BIfmal:
14275         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14276         break;
14277       default:
14278         break;
14279       }
14280     }
14281 
14282     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
14283         !FD->hasAttr<ReturnsTwiceAttr>())
14284       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
14285                                          FD->getLocation()));
14286     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
14287       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14288     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
14289       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
14290     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
14291       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14292     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
14293         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
14294       // Add the appropriate attribute, depending on the CUDA compilation mode
14295       // and which target the builtin belongs to. For example, during host
14296       // compilation, aux builtins are __device__, while the rest are __host__.
14297       if (getLangOpts().CUDAIsDevice !=
14298           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
14299         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
14300       else
14301         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
14302     }
14303   }
14304 
14305   // If C++ exceptions are enabled but we are told extern "C" functions cannot
14306   // throw, add an implicit nothrow attribute to any extern "C" function we come
14307   // across.
14308   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
14309       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
14310     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
14311     if (!FPT || FPT->getExceptionSpecType() == EST_None)
14312       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14313   }
14314 
14315   IdentifierInfo *Name = FD->getIdentifier();
14316   if (!Name)
14317     return;
14318   if ((!getLangOpts().CPlusPlus &&
14319        FD->getDeclContext()->isTranslationUnit()) ||
14320       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
14321        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
14322        LinkageSpecDecl::lang_c)) {
14323     // Okay: this could be a libc/libm/Objective-C function we know
14324     // about.
14325   } else
14326     return;
14327 
14328   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
14329     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
14330     // target-specific builtins, perhaps?
14331     if (!FD->hasAttr<FormatAttr>())
14332       FD->addAttr(FormatAttr::CreateImplicit(Context,
14333                                              &Context.Idents.get("printf"), 2,
14334                                              Name->isStr("vasprintf") ? 0 : 3,
14335                                              FD->getLocation()));
14336   }
14337 
14338   if (Name->isStr("__CFStringMakeConstantString")) {
14339     // We already have a __builtin___CFStringMakeConstantString,
14340     // but builds that use -fno-constant-cfstrings don't go through that.
14341     if (!FD->hasAttr<FormatArgAttr>())
14342       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
14343                                                 FD->getLocation()));
14344   }
14345 }
14346 
14347 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
14348                                     TypeSourceInfo *TInfo) {
14349   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
14350   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
14351 
14352   if (!TInfo) {
14353     assert(D.isInvalidType() && "no declarator info for valid type");
14354     TInfo = Context.getTrivialTypeSourceInfo(T);
14355   }
14356 
14357   // Scope manipulation handled by caller.
14358   TypedefDecl *NewTD =
14359       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
14360                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
14361 
14362   // Bail out immediately if we have an invalid declaration.
14363   if (D.isInvalidType()) {
14364     NewTD->setInvalidDecl();
14365     return NewTD;
14366   }
14367 
14368   if (D.getDeclSpec().isModulePrivateSpecified()) {
14369     if (CurContext->isFunctionOrMethod())
14370       Diag(NewTD->getLocation(), diag::err_module_private_local)
14371         << 2 << NewTD->getDeclName()
14372         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14373         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
14374     else
14375       NewTD->setModulePrivate();
14376   }
14377 
14378   // C++ [dcl.typedef]p8:
14379   //   If the typedef declaration defines an unnamed class (or
14380   //   enum), the first typedef-name declared by the declaration
14381   //   to be that class type (or enum type) is used to denote the
14382   //   class type (or enum type) for linkage purposes only.
14383   // We need to check whether the type was declared in the declaration.
14384   switch (D.getDeclSpec().getTypeSpecType()) {
14385   case TST_enum:
14386   case TST_struct:
14387   case TST_interface:
14388   case TST_union:
14389   case TST_class: {
14390     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
14391     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
14392     break;
14393   }
14394 
14395   default:
14396     break;
14397   }
14398 
14399   return NewTD;
14400 }
14401 
14402 /// Check that this is a valid underlying type for an enum declaration.
14403 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
14404   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
14405   QualType T = TI->getType();
14406 
14407   if (T->isDependentType())
14408     return false;
14409 
14410   if (const BuiltinType *BT = T->getAs<BuiltinType>())
14411     if (BT->isInteger())
14412       return false;
14413 
14414   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
14415   return true;
14416 }
14417 
14418 /// Check whether this is a valid redeclaration of a previous enumeration.
14419 /// \return true if the redeclaration was invalid.
14420 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
14421                                   QualType EnumUnderlyingTy, bool IsFixed,
14422                                   const EnumDecl *Prev) {
14423   if (IsScoped != Prev->isScoped()) {
14424     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
14425       << Prev->isScoped();
14426     Diag(Prev->getLocation(), diag::note_previous_declaration);
14427     return true;
14428   }
14429 
14430   if (IsFixed && Prev->isFixed()) {
14431     if (!EnumUnderlyingTy->isDependentType() &&
14432         !Prev->getIntegerType()->isDependentType() &&
14433         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
14434                                         Prev->getIntegerType())) {
14435       // TODO: Highlight the underlying type of the redeclaration.
14436       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
14437         << EnumUnderlyingTy << Prev->getIntegerType();
14438       Diag(Prev->getLocation(), diag::note_previous_declaration)
14439           << Prev->getIntegerTypeRange();
14440       return true;
14441     }
14442   } else if (IsFixed != Prev->isFixed()) {
14443     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
14444       << Prev->isFixed();
14445     Diag(Prev->getLocation(), diag::note_previous_declaration);
14446     return true;
14447   }
14448 
14449   return false;
14450 }
14451 
14452 /// Get diagnostic %select index for tag kind for
14453 /// redeclaration diagnostic message.
14454 /// WARNING: Indexes apply to particular diagnostics only!
14455 ///
14456 /// \returns diagnostic %select index.
14457 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
14458   switch (Tag) {
14459   case TTK_Struct: return 0;
14460   case TTK_Interface: return 1;
14461   case TTK_Class:  return 2;
14462   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
14463   }
14464 }
14465 
14466 /// Determine if tag kind is a class-key compatible with
14467 /// class for redeclaration (class, struct, or __interface).
14468 ///
14469 /// \returns true iff the tag kind is compatible.
14470 static bool isClassCompatTagKind(TagTypeKind Tag)
14471 {
14472   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
14473 }
14474 
14475 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
14476                                              TagTypeKind TTK) {
14477   if (isa<TypedefDecl>(PrevDecl))
14478     return NTK_Typedef;
14479   else if (isa<TypeAliasDecl>(PrevDecl))
14480     return NTK_TypeAlias;
14481   else if (isa<ClassTemplateDecl>(PrevDecl))
14482     return NTK_Template;
14483   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
14484     return NTK_TypeAliasTemplate;
14485   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
14486     return NTK_TemplateTemplateArgument;
14487   switch (TTK) {
14488   case TTK_Struct:
14489   case TTK_Interface:
14490   case TTK_Class:
14491     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
14492   case TTK_Union:
14493     return NTK_NonUnion;
14494   case TTK_Enum:
14495     return NTK_NonEnum;
14496   }
14497   llvm_unreachable("invalid TTK");
14498 }
14499 
14500 /// Determine whether a tag with a given kind is acceptable
14501 /// as a redeclaration of the given tag declaration.
14502 ///
14503 /// \returns true if the new tag kind is acceptable, false otherwise.
14504 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
14505                                         TagTypeKind NewTag, bool isDefinition,
14506                                         SourceLocation NewTagLoc,
14507                                         const IdentifierInfo *Name) {
14508   // C++ [dcl.type.elab]p3:
14509   //   The class-key or enum keyword present in the
14510   //   elaborated-type-specifier shall agree in kind with the
14511   //   declaration to which the name in the elaborated-type-specifier
14512   //   refers. This rule also applies to the form of
14513   //   elaborated-type-specifier that declares a class-name or
14514   //   friend class since it can be construed as referring to the
14515   //   definition of the class. Thus, in any
14516   //   elaborated-type-specifier, the enum keyword shall be used to
14517   //   refer to an enumeration (7.2), the union class-key shall be
14518   //   used to refer to a union (clause 9), and either the class or
14519   //   struct class-key shall be used to refer to a class (clause 9)
14520   //   declared using the class or struct class-key.
14521   TagTypeKind OldTag = Previous->getTagKind();
14522   if (OldTag != NewTag &&
14523       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
14524     return false;
14525 
14526   // Tags are compatible, but we might still want to warn on mismatched tags.
14527   // Non-class tags can't be mismatched at this point.
14528   if (!isClassCompatTagKind(NewTag))
14529     return true;
14530 
14531   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
14532   // by our warning analysis. We don't want to warn about mismatches with (eg)
14533   // declarations in system headers that are designed to be specialized, but if
14534   // a user asks us to warn, we should warn if their code contains mismatched
14535   // declarations.
14536   auto IsIgnoredLoc = [&](SourceLocation Loc) {
14537     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
14538                                       Loc);
14539   };
14540   if (IsIgnoredLoc(NewTagLoc))
14541     return true;
14542 
14543   auto IsIgnored = [&](const TagDecl *Tag) {
14544     return IsIgnoredLoc(Tag->getLocation());
14545   };
14546   while (IsIgnored(Previous)) {
14547     Previous = Previous->getPreviousDecl();
14548     if (!Previous)
14549       return true;
14550     OldTag = Previous->getTagKind();
14551   }
14552 
14553   bool isTemplate = false;
14554   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
14555     isTemplate = Record->getDescribedClassTemplate();
14556 
14557   if (inTemplateInstantiation()) {
14558     if (OldTag != NewTag) {
14559       // In a template instantiation, do not offer fix-its for tag mismatches
14560       // since they usually mess up the template instead of fixing the problem.
14561       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14562         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14563         << getRedeclDiagFromTagKind(OldTag);
14564       // FIXME: Note previous location?
14565     }
14566     return true;
14567   }
14568 
14569   if (isDefinition) {
14570     // On definitions, check all previous tags and issue a fix-it for each
14571     // one that doesn't match the current tag.
14572     if (Previous->getDefinition()) {
14573       // Don't suggest fix-its for redefinitions.
14574       return true;
14575     }
14576 
14577     bool previousMismatch = false;
14578     for (const TagDecl *I : Previous->redecls()) {
14579       if (I->getTagKind() != NewTag) {
14580         // Ignore previous declarations for which the warning was disabled.
14581         if (IsIgnored(I))
14582           continue;
14583 
14584         if (!previousMismatch) {
14585           previousMismatch = true;
14586           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
14587             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14588             << getRedeclDiagFromTagKind(I->getTagKind());
14589         }
14590         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
14591           << getRedeclDiagFromTagKind(NewTag)
14592           << FixItHint::CreateReplacement(I->getInnerLocStart(),
14593                TypeWithKeyword::getTagTypeKindName(NewTag));
14594       }
14595     }
14596     return true;
14597   }
14598 
14599   // Identify the prevailing tag kind: this is the kind of the definition (if
14600   // there is a non-ignored definition), or otherwise the kind of the prior
14601   // (non-ignored) declaration.
14602   const TagDecl *PrevDef = Previous->getDefinition();
14603   if (PrevDef && IsIgnored(PrevDef))
14604     PrevDef = nullptr;
14605   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
14606   if (Redecl->getTagKind() != NewTag) {
14607     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14608       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14609       << getRedeclDiagFromTagKind(OldTag);
14610     Diag(Redecl->getLocation(), diag::note_previous_use);
14611 
14612     // If there is a previous definition, suggest a fix-it.
14613     if (PrevDef) {
14614       Diag(NewTagLoc, diag::note_struct_class_suggestion)
14615         << getRedeclDiagFromTagKind(Redecl->getTagKind())
14616         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
14617              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
14618     }
14619   }
14620 
14621   return true;
14622 }
14623 
14624 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
14625 /// from an outer enclosing namespace or file scope inside a friend declaration.
14626 /// This should provide the commented out code in the following snippet:
14627 ///   namespace N {
14628 ///     struct X;
14629 ///     namespace M {
14630 ///       struct Y { friend struct /*N::*/ X; };
14631 ///     }
14632 ///   }
14633 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
14634                                          SourceLocation NameLoc) {
14635   // While the decl is in a namespace, do repeated lookup of that name and see
14636   // if we get the same namespace back.  If we do not, continue until
14637   // translation unit scope, at which point we have a fully qualified NNS.
14638   SmallVector<IdentifierInfo *, 4> Namespaces;
14639   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14640   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
14641     // This tag should be declared in a namespace, which can only be enclosed by
14642     // other namespaces.  Bail if there's an anonymous namespace in the chain.
14643     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
14644     if (!Namespace || Namespace->isAnonymousNamespace())
14645       return FixItHint();
14646     IdentifierInfo *II = Namespace->getIdentifier();
14647     Namespaces.push_back(II);
14648     NamedDecl *Lookup = SemaRef.LookupSingleName(
14649         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
14650     if (Lookup == Namespace)
14651       break;
14652   }
14653 
14654   // Once we have all the namespaces, reverse them to go outermost first, and
14655   // build an NNS.
14656   SmallString<64> Insertion;
14657   llvm::raw_svector_ostream OS(Insertion);
14658   if (DC->isTranslationUnit())
14659     OS << "::";
14660   std::reverse(Namespaces.begin(), Namespaces.end());
14661   for (auto *II : Namespaces)
14662     OS << II->getName() << "::";
14663   return FixItHint::CreateInsertion(NameLoc, Insertion);
14664 }
14665 
14666 /// Determine whether a tag originally declared in context \p OldDC can
14667 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
14668 /// found a declaration in \p OldDC as a previous decl, perhaps through a
14669 /// using-declaration).
14670 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
14671                                          DeclContext *NewDC) {
14672   OldDC = OldDC->getRedeclContext();
14673   NewDC = NewDC->getRedeclContext();
14674 
14675   if (OldDC->Equals(NewDC))
14676     return true;
14677 
14678   // In MSVC mode, we allow a redeclaration if the contexts are related (either
14679   // encloses the other).
14680   if (S.getLangOpts().MSVCCompat &&
14681       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
14682     return true;
14683 
14684   return false;
14685 }
14686 
14687 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
14688 /// former case, Name will be non-null.  In the later case, Name will be null.
14689 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
14690 /// reference/declaration/definition of a tag.
14691 ///
14692 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
14693 /// trailing-type-specifier) other than one in an alias-declaration.
14694 ///
14695 /// \param SkipBody If non-null, will be set to indicate if the caller should
14696 /// skip the definition of this tag and treat it as if it were a declaration.
14697 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
14698                      SourceLocation KWLoc, CXXScopeSpec &SS,
14699                      IdentifierInfo *Name, SourceLocation NameLoc,
14700                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
14701                      SourceLocation ModulePrivateLoc,
14702                      MultiTemplateParamsArg TemplateParameterLists,
14703                      bool &OwnedDecl, bool &IsDependent,
14704                      SourceLocation ScopedEnumKWLoc,
14705                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
14706                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
14707                      SkipBodyInfo *SkipBody) {
14708   // If this is not a definition, it must have a name.
14709   IdentifierInfo *OrigName = Name;
14710   assert((Name != nullptr || TUK == TUK_Definition) &&
14711          "Nameless record must be a definition!");
14712   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
14713 
14714   OwnedDecl = false;
14715   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14716   bool ScopedEnum = ScopedEnumKWLoc.isValid();
14717 
14718   // FIXME: Check member specializations more carefully.
14719   bool isMemberSpecialization = false;
14720   bool Invalid = false;
14721 
14722   // We only need to do this matching if we have template parameters
14723   // or a scope specifier, which also conveniently avoids this work
14724   // for non-C++ cases.
14725   if (TemplateParameterLists.size() > 0 ||
14726       (SS.isNotEmpty() && TUK != TUK_Reference)) {
14727     if (TemplateParameterList *TemplateParams =
14728             MatchTemplateParametersToScopeSpecifier(
14729                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
14730                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
14731       if (Kind == TTK_Enum) {
14732         Diag(KWLoc, diag::err_enum_template);
14733         return nullptr;
14734       }
14735 
14736       if (TemplateParams->size() > 0) {
14737         // This is a declaration or definition of a class template (which may
14738         // be a member of another template).
14739 
14740         if (Invalid)
14741           return nullptr;
14742 
14743         OwnedDecl = false;
14744         DeclResult Result = CheckClassTemplate(
14745             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
14746             AS, ModulePrivateLoc,
14747             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
14748             TemplateParameterLists.data(), SkipBody);
14749         return Result.get();
14750       } else {
14751         // The "template<>" header is extraneous.
14752         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14753           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14754         isMemberSpecialization = true;
14755       }
14756     }
14757   }
14758 
14759   // Figure out the underlying type if this a enum declaration. We need to do
14760   // this early, because it's needed to detect if this is an incompatible
14761   // redeclaration.
14762   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
14763   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
14764 
14765   if (Kind == TTK_Enum) {
14766     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
14767       // No underlying type explicitly specified, or we failed to parse the
14768       // type, default to int.
14769       EnumUnderlying = Context.IntTy.getTypePtr();
14770     } else if (UnderlyingType.get()) {
14771       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
14772       // integral type; any cv-qualification is ignored.
14773       TypeSourceInfo *TI = nullptr;
14774       GetTypeFromParser(UnderlyingType.get(), &TI);
14775       EnumUnderlying = TI;
14776 
14777       if (CheckEnumUnderlyingType(TI))
14778         // Recover by falling back to int.
14779         EnumUnderlying = Context.IntTy.getTypePtr();
14780 
14781       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
14782                                           UPPC_FixedUnderlyingType))
14783         EnumUnderlying = Context.IntTy.getTypePtr();
14784 
14785     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
14786       // For MSVC ABI compatibility, unfixed enums must use an underlying type
14787       // of 'int'. However, if this is an unfixed forward declaration, don't set
14788       // the underlying type unless the user enables -fms-compatibility. This
14789       // makes unfixed forward declared enums incomplete and is more conforming.
14790       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
14791         EnumUnderlying = Context.IntTy.getTypePtr();
14792     }
14793   }
14794 
14795   DeclContext *SearchDC = CurContext;
14796   DeclContext *DC = CurContext;
14797   bool isStdBadAlloc = false;
14798   bool isStdAlignValT = false;
14799 
14800   RedeclarationKind Redecl = forRedeclarationInCurContext();
14801   if (TUK == TUK_Friend || TUK == TUK_Reference)
14802     Redecl = NotForRedeclaration;
14803 
14804   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
14805   /// implemented asks for structural equivalence checking, the returned decl
14806   /// here is passed back to the parser, allowing the tag body to be parsed.
14807   auto createTagFromNewDecl = [&]() -> TagDecl * {
14808     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
14809     // If there is an identifier, use the location of the identifier as the
14810     // location of the decl, otherwise use the location of the struct/union
14811     // keyword.
14812     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14813     TagDecl *New = nullptr;
14814 
14815     if (Kind == TTK_Enum) {
14816       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
14817                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
14818       // If this is an undefined enum, bail.
14819       if (TUK != TUK_Definition && !Invalid)
14820         return nullptr;
14821       if (EnumUnderlying) {
14822         EnumDecl *ED = cast<EnumDecl>(New);
14823         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
14824           ED->setIntegerTypeSourceInfo(TI);
14825         else
14826           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
14827         ED->setPromotionType(ED->getIntegerType());
14828       }
14829     } else { // struct/union
14830       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14831                                nullptr);
14832     }
14833 
14834     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14835       // Add alignment attributes if necessary; these attributes are checked
14836       // when the ASTContext lays out the structure.
14837       //
14838       // It is important for implementing the correct semantics that this
14839       // happen here (in ActOnTag). The #pragma pack stack is
14840       // maintained as a result of parser callbacks which can occur at
14841       // many points during the parsing of a struct declaration (because
14842       // the #pragma tokens are effectively skipped over during the
14843       // parsing of the struct).
14844       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
14845         AddAlignmentAttributesForRecord(RD);
14846         AddMsStructLayoutForRecord(RD);
14847       }
14848     }
14849     New->setLexicalDeclContext(CurContext);
14850     return New;
14851   };
14852 
14853   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
14854   if (Name && SS.isNotEmpty()) {
14855     // We have a nested-name tag ('struct foo::bar').
14856 
14857     // Check for invalid 'foo::'.
14858     if (SS.isInvalid()) {
14859       Name = nullptr;
14860       goto CreateNewDecl;
14861     }
14862 
14863     // If this is a friend or a reference to a class in a dependent
14864     // context, don't try to make a decl for it.
14865     if (TUK == TUK_Friend || TUK == TUK_Reference) {
14866       DC = computeDeclContext(SS, false);
14867       if (!DC) {
14868         IsDependent = true;
14869         return nullptr;
14870       }
14871     } else {
14872       DC = computeDeclContext(SS, true);
14873       if (!DC) {
14874         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
14875           << SS.getRange();
14876         return nullptr;
14877       }
14878     }
14879 
14880     if (RequireCompleteDeclContext(SS, DC))
14881       return nullptr;
14882 
14883     SearchDC = DC;
14884     // Look-up name inside 'foo::'.
14885     LookupQualifiedName(Previous, DC);
14886 
14887     if (Previous.isAmbiguous())
14888       return nullptr;
14889 
14890     if (Previous.empty()) {
14891       // Name lookup did not find anything. However, if the
14892       // nested-name-specifier refers to the current instantiation,
14893       // and that current instantiation has any dependent base
14894       // classes, we might find something at instantiation time: treat
14895       // this as a dependent elaborated-type-specifier.
14896       // But this only makes any sense for reference-like lookups.
14897       if (Previous.wasNotFoundInCurrentInstantiation() &&
14898           (TUK == TUK_Reference || TUK == TUK_Friend)) {
14899         IsDependent = true;
14900         return nullptr;
14901       }
14902 
14903       // A tag 'foo::bar' must already exist.
14904       Diag(NameLoc, diag::err_not_tag_in_scope)
14905         << Kind << Name << DC << SS.getRange();
14906       Name = nullptr;
14907       Invalid = true;
14908       goto CreateNewDecl;
14909     }
14910   } else if (Name) {
14911     // C++14 [class.mem]p14:
14912     //   If T is the name of a class, then each of the following shall have a
14913     //   name different from T:
14914     //    -- every member of class T that is itself a type
14915     if (TUK != TUK_Reference && TUK != TUK_Friend &&
14916         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
14917       return nullptr;
14918 
14919     // If this is a named struct, check to see if there was a previous forward
14920     // declaration or definition.
14921     // FIXME: We're looking into outer scopes here, even when we
14922     // shouldn't be. Doing so can result in ambiguities that we
14923     // shouldn't be diagnosing.
14924     LookupName(Previous, S);
14925 
14926     // When declaring or defining a tag, ignore ambiguities introduced
14927     // by types using'ed into this scope.
14928     if (Previous.isAmbiguous() &&
14929         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
14930       LookupResult::Filter F = Previous.makeFilter();
14931       while (F.hasNext()) {
14932         NamedDecl *ND = F.next();
14933         if (!ND->getDeclContext()->getRedeclContext()->Equals(
14934                 SearchDC->getRedeclContext()))
14935           F.erase();
14936       }
14937       F.done();
14938     }
14939 
14940     // C++11 [namespace.memdef]p3:
14941     //   If the name in a friend declaration is neither qualified nor
14942     //   a template-id and the declaration is a function or an
14943     //   elaborated-type-specifier, the lookup to determine whether
14944     //   the entity has been previously declared shall not consider
14945     //   any scopes outside the innermost enclosing namespace.
14946     //
14947     // MSVC doesn't implement the above rule for types, so a friend tag
14948     // declaration may be a redeclaration of a type declared in an enclosing
14949     // scope.  They do implement this rule for friend functions.
14950     //
14951     // Does it matter that this should be by scope instead of by
14952     // semantic context?
14953     if (!Previous.empty() && TUK == TUK_Friend) {
14954       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
14955       LookupResult::Filter F = Previous.makeFilter();
14956       bool FriendSawTagOutsideEnclosingNamespace = false;
14957       while (F.hasNext()) {
14958         NamedDecl *ND = F.next();
14959         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14960         if (DC->isFileContext() &&
14961             !EnclosingNS->Encloses(ND->getDeclContext())) {
14962           if (getLangOpts().MSVCCompat)
14963             FriendSawTagOutsideEnclosingNamespace = true;
14964           else
14965             F.erase();
14966         }
14967       }
14968       F.done();
14969 
14970       // Diagnose this MSVC extension in the easy case where lookup would have
14971       // unambiguously found something outside the enclosing namespace.
14972       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
14973         NamedDecl *ND = Previous.getFoundDecl();
14974         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
14975             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
14976       }
14977     }
14978 
14979     // Note:  there used to be some attempt at recovery here.
14980     if (Previous.isAmbiguous())
14981       return nullptr;
14982 
14983     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
14984       // FIXME: This makes sure that we ignore the contexts associated
14985       // with C structs, unions, and enums when looking for a matching
14986       // tag declaration or definition. See the similar lookup tweak
14987       // in Sema::LookupName; is there a better way to deal with this?
14988       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
14989         SearchDC = SearchDC->getParent();
14990     }
14991   }
14992 
14993   if (Previous.isSingleResult() &&
14994       Previous.getFoundDecl()->isTemplateParameter()) {
14995     // Maybe we will complain about the shadowed template parameter.
14996     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
14997     // Just pretend that we didn't see the previous declaration.
14998     Previous.clear();
14999   }
15000 
15001   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
15002       DC->Equals(getStdNamespace())) {
15003     if (Name->isStr("bad_alloc")) {
15004       // This is a declaration of or a reference to "std::bad_alloc".
15005       isStdBadAlloc = true;
15006 
15007       // If std::bad_alloc has been implicitly declared (but made invisible to
15008       // name lookup), fill in this implicit declaration as the previous
15009       // declaration, so that the declarations get chained appropriately.
15010       if (Previous.empty() && StdBadAlloc)
15011         Previous.addDecl(getStdBadAlloc());
15012     } else if (Name->isStr("align_val_t")) {
15013       isStdAlignValT = true;
15014       if (Previous.empty() && StdAlignValT)
15015         Previous.addDecl(getStdAlignValT());
15016     }
15017   }
15018 
15019   // If we didn't find a previous declaration, and this is a reference
15020   // (or friend reference), move to the correct scope.  In C++, we
15021   // also need to do a redeclaration lookup there, just in case
15022   // there's a shadow friend decl.
15023   if (Name && Previous.empty() &&
15024       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
15025     if (Invalid) goto CreateNewDecl;
15026     assert(SS.isEmpty());
15027 
15028     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
15029       // C++ [basic.scope.pdecl]p5:
15030       //   -- for an elaborated-type-specifier of the form
15031       //
15032       //          class-key identifier
15033       //
15034       //      if the elaborated-type-specifier is used in the
15035       //      decl-specifier-seq or parameter-declaration-clause of a
15036       //      function defined in namespace scope, the identifier is
15037       //      declared as a class-name in the namespace that contains
15038       //      the declaration; otherwise, except as a friend
15039       //      declaration, the identifier is declared in the smallest
15040       //      non-class, non-function-prototype scope that contains the
15041       //      declaration.
15042       //
15043       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
15044       // C structs and unions.
15045       //
15046       // It is an error in C++ to declare (rather than define) an enum
15047       // type, including via an elaborated type specifier.  We'll
15048       // diagnose that later; for now, declare the enum in the same
15049       // scope as we would have picked for any other tag type.
15050       //
15051       // GNU C also supports this behavior as part of its incomplete
15052       // enum types extension, while GNU C++ does not.
15053       //
15054       // Find the context where we'll be declaring the tag.
15055       // FIXME: We would like to maintain the current DeclContext as the
15056       // lexical context,
15057       SearchDC = getTagInjectionContext(SearchDC);
15058 
15059       // Find the scope where we'll be declaring the tag.
15060       S = getTagInjectionScope(S, getLangOpts());
15061     } else {
15062       assert(TUK == TUK_Friend);
15063       // C++ [namespace.memdef]p3:
15064       //   If a friend declaration in a non-local class first declares a
15065       //   class or function, the friend class or function is a member of
15066       //   the innermost enclosing namespace.
15067       SearchDC = SearchDC->getEnclosingNamespaceContext();
15068     }
15069 
15070     // In C++, we need to do a redeclaration lookup to properly
15071     // diagnose some problems.
15072     // FIXME: redeclaration lookup is also used (with and without C++) to find a
15073     // hidden declaration so that we don't get ambiguity errors when using a
15074     // type declared by an elaborated-type-specifier.  In C that is not correct
15075     // and we should instead merge compatible types found by lookup.
15076     if (getLangOpts().CPlusPlus) {
15077       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15078       LookupQualifiedName(Previous, SearchDC);
15079     } else {
15080       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15081       LookupName(Previous, S);
15082     }
15083   }
15084 
15085   // If we have a known previous declaration to use, then use it.
15086   if (Previous.empty() && SkipBody && SkipBody->Previous)
15087     Previous.addDecl(SkipBody->Previous);
15088 
15089   if (!Previous.empty()) {
15090     NamedDecl *PrevDecl = Previous.getFoundDecl();
15091     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
15092 
15093     // It's okay to have a tag decl in the same scope as a typedef
15094     // which hides a tag decl in the same scope.  Finding this
15095     // insanity with a redeclaration lookup can only actually happen
15096     // in C++.
15097     //
15098     // This is also okay for elaborated-type-specifiers, which is
15099     // technically forbidden by the current standard but which is
15100     // okay according to the likely resolution of an open issue;
15101     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
15102     if (getLangOpts().CPlusPlus) {
15103       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15104         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
15105           TagDecl *Tag = TT->getDecl();
15106           if (Tag->getDeclName() == Name &&
15107               Tag->getDeclContext()->getRedeclContext()
15108                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
15109             PrevDecl = Tag;
15110             Previous.clear();
15111             Previous.addDecl(Tag);
15112             Previous.resolveKind();
15113           }
15114         }
15115       }
15116     }
15117 
15118     // If this is a redeclaration of a using shadow declaration, it must
15119     // declare a tag in the same context. In MSVC mode, we allow a
15120     // redefinition if either context is within the other.
15121     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
15122       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
15123       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
15124           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
15125           !(OldTag && isAcceptableTagRedeclContext(
15126                           *this, OldTag->getDeclContext(), SearchDC))) {
15127         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
15128         Diag(Shadow->getTargetDecl()->getLocation(),
15129              diag::note_using_decl_target);
15130         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
15131             << 0;
15132         // Recover by ignoring the old declaration.
15133         Previous.clear();
15134         goto CreateNewDecl;
15135       }
15136     }
15137 
15138     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
15139       // If this is a use of a previous tag, or if the tag is already declared
15140       // in the same scope (so that the definition/declaration completes or
15141       // rementions the tag), reuse the decl.
15142       if (TUK == TUK_Reference || TUK == TUK_Friend ||
15143           isDeclInScope(DirectPrevDecl, SearchDC, S,
15144                         SS.isNotEmpty() || isMemberSpecialization)) {
15145         // Make sure that this wasn't declared as an enum and now used as a
15146         // struct or something similar.
15147         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
15148                                           TUK == TUK_Definition, KWLoc,
15149                                           Name)) {
15150           bool SafeToContinue
15151             = (PrevTagDecl->getTagKind() != TTK_Enum &&
15152                Kind != TTK_Enum);
15153           if (SafeToContinue)
15154             Diag(KWLoc, diag::err_use_with_wrong_tag)
15155               << Name
15156               << FixItHint::CreateReplacement(SourceRange(KWLoc),
15157                                               PrevTagDecl->getKindName());
15158           else
15159             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
15160           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
15161 
15162           if (SafeToContinue)
15163             Kind = PrevTagDecl->getTagKind();
15164           else {
15165             // Recover by making this an anonymous redefinition.
15166             Name = nullptr;
15167             Previous.clear();
15168             Invalid = true;
15169           }
15170         }
15171 
15172         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
15173           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
15174 
15175           // If this is an elaborated-type-specifier for a scoped enumeration,
15176           // the 'class' keyword is not necessary and not permitted.
15177           if (TUK == TUK_Reference || TUK == TUK_Friend) {
15178             if (ScopedEnum)
15179               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
15180                 << PrevEnum->isScoped()
15181                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
15182             return PrevTagDecl;
15183           }
15184 
15185           QualType EnumUnderlyingTy;
15186           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15187             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
15188           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
15189             EnumUnderlyingTy = QualType(T, 0);
15190 
15191           // All conflicts with previous declarations are recovered by
15192           // returning the previous declaration, unless this is a definition,
15193           // in which case we want the caller to bail out.
15194           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
15195                                      ScopedEnum, EnumUnderlyingTy,
15196                                      IsFixed, PrevEnum))
15197             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
15198         }
15199 
15200         // C++11 [class.mem]p1:
15201         //   A member shall not be declared twice in the member-specification,
15202         //   except that a nested class or member class template can be declared
15203         //   and then later defined.
15204         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
15205             S->isDeclScope(PrevDecl)) {
15206           Diag(NameLoc, diag::ext_member_redeclared);
15207           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
15208         }
15209 
15210         if (!Invalid) {
15211           // If this is a use, just return the declaration we found, unless
15212           // we have attributes.
15213           if (TUK == TUK_Reference || TUK == TUK_Friend) {
15214             if (!Attrs.empty()) {
15215               // FIXME: Diagnose these attributes. For now, we create a new
15216               // declaration to hold them.
15217             } else if (TUK == TUK_Reference &&
15218                        (PrevTagDecl->getFriendObjectKind() ==
15219                             Decl::FOK_Undeclared ||
15220                         PrevDecl->getOwningModule() != getCurrentModule()) &&
15221                        SS.isEmpty()) {
15222               // This declaration is a reference to an existing entity, but
15223               // has different visibility from that entity: it either makes
15224               // a friend visible or it makes a type visible in a new module.
15225               // In either case, create a new declaration. We only do this if
15226               // the declaration would have meant the same thing if no prior
15227               // declaration were found, that is, if it was found in the same
15228               // scope where we would have injected a declaration.
15229               if (!getTagInjectionContext(CurContext)->getRedeclContext()
15230                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
15231                 return PrevTagDecl;
15232               // This is in the injected scope, create a new declaration in
15233               // that scope.
15234               S = getTagInjectionScope(S, getLangOpts());
15235             } else {
15236               return PrevTagDecl;
15237             }
15238           }
15239 
15240           // Diagnose attempts to redefine a tag.
15241           if (TUK == TUK_Definition) {
15242             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
15243               // If we're defining a specialization and the previous definition
15244               // is from an implicit instantiation, don't emit an error
15245               // here; we'll catch this in the general case below.
15246               bool IsExplicitSpecializationAfterInstantiation = false;
15247               if (isMemberSpecialization) {
15248                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
15249                   IsExplicitSpecializationAfterInstantiation =
15250                     RD->getTemplateSpecializationKind() !=
15251                     TSK_ExplicitSpecialization;
15252                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
15253                   IsExplicitSpecializationAfterInstantiation =
15254                     ED->getTemplateSpecializationKind() !=
15255                     TSK_ExplicitSpecialization;
15256               }
15257 
15258               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
15259               // not keep more that one definition around (merge them). However,
15260               // ensure the decl passes the structural compatibility check in
15261               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
15262               NamedDecl *Hidden = nullptr;
15263               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
15264                 // There is a definition of this tag, but it is not visible. We
15265                 // explicitly make use of C++'s one definition rule here, and
15266                 // assume that this definition is identical to the hidden one
15267                 // we already have. Make the existing definition visible and
15268                 // use it in place of this one.
15269                 if (!getLangOpts().CPlusPlus) {
15270                   // Postpone making the old definition visible until after we
15271                   // complete parsing the new one and do the structural
15272                   // comparison.
15273                   SkipBody->CheckSameAsPrevious = true;
15274                   SkipBody->New = createTagFromNewDecl();
15275                   SkipBody->Previous = Def;
15276                   return Def;
15277                 } else {
15278                   SkipBody->ShouldSkip = true;
15279                   SkipBody->Previous = Def;
15280                   makeMergedDefinitionVisible(Hidden);
15281                   // Carry on and handle it like a normal definition. We'll
15282                   // skip starting the definitiion later.
15283                 }
15284               } else if (!IsExplicitSpecializationAfterInstantiation) {
15285                 // A redeclaration in function prototype scope in C isn't
15286                 // visible elsewhere, so merely issue a warning.
15287                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
15288                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
15289                 else
15290                   Diag(NameLoc, diag::err_redefinition) << Name;
15291                 notePreviousDefinition(Def,
15292                                        NameLoc.isValid() ? NameLoc : KWLoc);
15293                 // If this is a redefinition, recover by making this
15294                 // struct be anonymous, which will make any later
15295                 // references get the previous definition.
15296                 Name = nullptr;
15297                 Previous.clear();
15298                 Invalid = true;
15299               }
15300             } else {
15301               // If the type is currently being defined, complain
15302               // about a nested redefinition.
15303               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
15304               if (TD->isBeingDefined()) {
15305                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
15306                 Diag(PrevTagDecl->getLocation(),
15307                      diag::note_previous_definition);
15308                 Name = nullptr;
15309                 Previous.clear();
15310                 Invalid = true;
15311               }
15312             }
15313 
15314             // Okay, this is definition of a previously declared or referenced
15315             // tag. We're going to create a new Decl for it.
15316           }
15317 
15318           // Okay, we're going to make a redeclaration.  If this is some kind
15319           // of reference, make sure we build the redeclaration in the same DC
15320           // as the original, and ignore the current access specifier.
15321           if (TUK == TUK_Friend || TUK == TUK_Reference) {
15322             SearchDC = PrevTagDecl->getDeclContext();
15323             AS = AS_none;
15324           }
15325         }
15326         // If we get here we have (another) forward declaration or we
15327         // have a definition.  Just create a new decl.
15328 
15329       } else {
15330         // If we get here, this is a definition of a new tag type in a nested
15331         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
15332         // new decl/type.  We set PrevDecl to NULL so that the entities
15333         // have distinct types.
15334         Previous.clear();
15335       }
15336       // If we get here, we're going to create a new Decl. If PrevDecl
15337       // is non-NULL, it's a definition of the tag declared by
15338       // PrevDecl. If it's NULL, we have a new definition.
15339 
15340     // Otherwise, PrevDecl is not a tag, but was found with tag
15341     // lookup.  This is only actually possible in C++, where a few
15342     // things like templates still live in the tag namespace.
15343     } else {
15344       // Use a better diagnostic if an elaborated-type-specifier
15345       // found the wrong kind of type on the first
15346       // (non-redeclaration) lookup.
15347       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
15348           !Previous.isForRedeclaration()) {
15349         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15350         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
15351                                                        << Kind;
15352         Diag(PrevDecl->getLocation(), diag::note_declared_at);
15353         Invalid = true;
15354 
15355       // Otherwise, only diagnose if the declaration is in scope.
15356       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
15357                                 SS.isNotEmpty() || isMemberSpecialization)) {
15358         // do nothing
15359 
15360       // Diagnose implicit declarations introduced by elaborated types.
15361       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
15362         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15363         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
15364         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15365         Invalid = true;
15366 
15367       // Otherwise it's a declaration.  Call out a particularly common
15368       // case here.
15369       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15370         unsigned Kind = 0;
15371         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
15372         Diag(NameLoc, diag::err_tag_definition_of_typedef)
15373           << Name << Kind << TND->getUnderlyingType();
15374         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15375         Invalid = true;
15376 
15377       // Otherwise, diagnose.
15378       } else {
15379         // The tag name clashes with something else in the target scope,
15380         // issue an error and recover by making this tag be anonymous.
15381         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
15382         notePreviousDefinition(PrevDecl, NameLoc);
15383         Name = nullptr;
15384         Invalid = true;
15385       }
15386 
15387       // The existing declaration isn't relevant to us; we're in a
15388       // new scope, so clear out the previous declaration.
15389       Previous.clear();
15390     }
15391   }
15392 
15393 CreateNewDecl:
15394 
15395   TagDecl *PrevDecl = nullptr;
15396   if (Previous.isSingleResult())
15397     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
15398 
15399   // If there is an identifier, use the location of the identifier as the
15400   // location of the decl, otherwise use the location of the struct/union
15401   // keyword.
15402   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15403 
15404   // Otherwise, create a new declaration. If there is a previous
15405   // declaration of the same entity, the two will be linked via
15406   // PrevDecl.
15407   TagDecl *New;
15408 
15409   if (Kind == TTK_Enum) {
15410     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15411     // enum X { A, B, C } D;    D should chain to X.
15412     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
15413                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
15414                            ScopedEnumUsesClassTag, IsFixed);
15415 
15416     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
15417       StdAlignValT = cast<EnumDecl>(New);
15418 
15419     // If this is an undefined enum, warn.
15420     if (TUK != TUK_Definition && !Invalid) {
15421       TagDecl *Def;
15422       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
15423         // C++0x: 7.2p2: opaque-enum-declaration.
15424         // Conflicts are diagnosed above. Do nothing.
15425       }
15426       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
15427         Diag(Loc, diag::ext_forward_ref_enum_def)
15428           << New;
15429         Diag(Def->getLocation(), diag::note_previous_definition);
15430       } else {
15431         unsigned DiagID = diag::ext_forward_ref_enum;
15432         if (getLangOpts().MSVCCompat)
15433           DiagID = diag::ext_ms_forward_ref_enum;
15434         else if (getLangOpts().CPlusPlus)
15435           DiagID = diag::err_forward_ref_enum;
15436         Diag(Loc, DiagID);
15437       }
15438     }
15439 
15440     if (EnumUnderlying) {
15441       EnumDecl *ED = cast<EnumDecl>(New);
15442       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15443         ED->setIntegerTypeSourceInfo(TI);
15444       else
15445         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
15446       ED->setPromotionType(ED->getIntegerType());
15447       assert(ED->isComplete() && "enum with type should be complete");
15448     }
15449   } else {
15450     // struct/union/class
15451 
15452     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15453     // struct X { int A; } D;    D should chain to X.
15454     if (getLangOpts().CPlusPlus) {
15455       // FIXME: Look for a way to use RecordDecl for simple structs.
15456       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15457                                   cast_or_null<CXXRecordDecl>(PrevDecl));
15458 
15459       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
15460         StdBadAlloc = cast<CXXRecordDecl>(New);
15461     } else
15462       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15463                                cast_or_null<RecordDecl>(PrevDecl));
15464   }
15465 
15466   // C++11 [dcl.type]p3:
15467   //   A type-specifier-seq shall not define a class or enumeration [...].
15468   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
15469       TUK == TUK_Definition) {
15470     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
15471       << Context.getTagDeclType(New);
15472     Invalid = true;
15473   }
15474 
15475   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
15476       DC->getDeclKind() == Decl::Enum) {
15477     Diag(New->getLocation(), diag::err_type_defined_in_enum)
15478       << Context.getTagDeclType(New);
15479     Invalid = true;
15480   }
15481 
15482   // Maybe add qualifier info.
15483   if (SS.isNotEmpty()) {
15484     if (SS.isSet()) {
15485       // If this is either a declaration or a definition, check the
15486       // nested-name-specifier against the current context.
15487       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
15488           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
15489                                        isMemberSpecialization))
15490         Invalid = true;
15491 
15492       New->setQualifierInfo(SS.getWithLocInContext(Context));
15493       if (TemplateParameterLists.size() > 0) {
15494         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
15495       }
15496     }
15497     else
15498       Invalid = true;
15499   }
15500 
15501   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15502     // Add alignment attributes if necessary; these attributes are checked when
15503     // the ASTContext lays out the structure.
15504     //
15505     // It is important for implementing the correct semantics that this
15506     // happen here (in ActOnTag). The #pragma pack stack is
15507     // maintained as a result of parser callbacks which can occur at
15508     // many points during the parsing of a struct declaration (because
15509     // the #pragma tokens are effectively skipped over during the
15510     // parsing of the struct).
15511     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15512       AddAlignmentAttributesForRecord(RD);
15513       AddMsStructLayoutForRecord(RD);
15514     }
15515   }
15516 
15517   if (ModulePrivateLoc.isValid()) {
15518     if (isMemberSpecialization)
15519       Diag(New->getLocation(), diag::err_module_private_specialization)
15520         << 2
15521         << FixItHint::CreateRemoval(ModulePrivateLoc);
15522     // __module_private__ does not apply to local classes. However, we only
15523     // diagnose this as an error when the declaration specifiers are
15524     // freestanding. Here, we just ignore the __module_private__.
15525     else if (!SearchDC->isFunctionOrMethod())
15526       New->setModulePrivate();
15527   }
15528 
15529   // If this is a specialization of a member class (of a class template),
15530   // check the specialization.
15531   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
15532     Invalid = true;
15533 
15534   // If we're declaring or defining a tag in function prototype scope in C,
15535   // note that this type can only be used within the function and add it to
15536   // the list of decls to inject into the function definition scope.
15537   if ((Name || Kind == TTK_Enum) &&
15538       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
15539     if (getLangOpts().CPlusPlus) {
15540       // C++ [dcl.fct]p6:
15541       //   Types shall not be defined in return or parameter types.
15542       if (TUK == TUK_Definition && !IsTypeSpecifier) {
15543         Diag(Loc, diag::err_type_defined_in_param_type)
15544             << Name;
15545         Invalid = true;
15546       }
15547     } else if (!PrevDecl) {
15548       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
15549     }
15550   }
15551 
15552   if (Invalid)
15553     New->setInvalidDecl();
15554 
15555   // Set the lexical context. If the tag has a C++ scope specifier, the
15556   // lexical context will be different from the semantic context.
15557   New->setLexicalDeclContext(CurContext);
15558 
15559   // Mark this as a friend decl if applicable.
15560   // In Microsoft mode, a friend declaration also acts as a forward
15561   // declaration so we always pass true to setObjectOfFriendDecl to make
15562   // the tag name visible.
15563   if (TUK == TUK_Friend)
15564     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
15565 
15566   // Set the access specifier.
15567   if (!Invalid && SearchDC->isRecord())
15568     SetMemberAccessSpecifier(New, PrevDecl, AS);
15569 
15570   if (PrevDecl)
15571     CheckRedeclarationModuleOwnership(New, PrevDecl);
15572 
15573   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
15574     New->startDefinition();
15575 
15576   ProcessDeclAttributeList(S, New, Attrs);
15577   AddPragmaAttributes(S, New);
15578 
15579   // If this has an identifier, add it to the scope stack.
15580   if (TUK == TUK_Friend) {
15581     // We might be replacing an existing declaration in the lookup tables;
15582     // if so, borrow its access specifier.
15583     if (PrevDecl)
15584       New->setAccess(PrevDecl->getAccess());
15585 
15586     DeclContext *DC = New->getDeclContext()->getRedeclContext();
15587     DC->makeDeclVisibleInContext(New);
15588     if (Name) // can be null along some error paths
15589       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
15590         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
15591   } else if (Name) {
15592     S = getNonFieldDeclScope(S);
15593     PushOnScopeChains(New, S, true);
15594   } else {
15595     CurContext->addDecl(New);
15596   }
15597 
15598   // If this is the C FILE type, notify the AST context.
15599   if (IdentifierInfo *II = New->getIdentifier())
15600     if (!New->isInvalidDecl() &&
15601         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
15602         II->isStr("FILE"))
15603       Context.setFILEDecl(New);
15604 
15605   if (PrevDecl)
15606     mergeDeclAttributes(New, PrevDecl);
15607 
15608   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
15609     inferGslOwnerPointerAttribute(CXXRD);
15610 
15611   // If there's a #pragma GCC visibility in scope, set the visibility of this
15612   // record.
15613   AddPushedVisibilityAttribute(New);
15614 
15615   if (isMemberSpecialization && !New->isInvalidDecl())
15616     CompleteMemberSpecialization(New, Previous);
15617 
15618   OwnedDecl = true;
15619   // In C++, don't return an invalid declaration. We can't recover well from
15620   // the cases where we make the type anonymous.
15621   if (Invalid && getLangOpts().CPlusPlus) {
15622     if (New->isBeingDefined())
15623       if (auto RD = dyn_cast<RecordDecl>(New))
15624         RD->completeDefinition();
15625     return nullptr;
15626   } else if (SkipBody && SkipBody->ShouldSkip) {
15627     return SkipBody->Previous;
15628   } else {
15629     return New;
15630   }
15631 }
15632 
15633 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
15634   AdjustDeclIfTemplate(TagD);
15635   TagDecl *Tag = cast<TagDecl>(TagD);
15636 
15637   // Enter the tag context.
15638   PushDeclContext(S, Tag);
15639 
15640   ActOnDocumentableDecl(TagD);
15641 
15642   // If there's a #pragma GCC visibility in scope, set the visibility of this
15643   // record.
15644   AddPushedVisibilityAttribute(Tag);
15645 }
15646 
15647 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
15648                                     SkipBodyInfo &SkipBody) {
15649   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
15650     return false;
15651 
15652   // Make the previous decl visible.
15653   makeMergedDefinitionVisible(SkipBody.Previous);
15654   return true;
15655 }
15656 
15657 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
15658   assert(isa<ObjCContainerDecl>(IDecl) &&
15659          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
15660   DeclContext *OCD = cast<DeclContext>(IDecl);
15661   assert(getContainingDC(OCD) == CurContext &&
15662       "The next DeclContext should be lexically contained in the current one.");
15663   CurContext = OCD;
15664   return IDecl;
15665 }
15666 
15667 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
15668                                            SourceLocation FinalLoc,
15669                                            bool IsFinalSpelledSealed,
15670                                            SourceLocation LBraceLoc) {
15671   AdjustDeclIfTemplate(TagD);
15672   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
15673 
15674   FieldCollector->StartClass();
15675 
15676   if (!Record->getIdentifier())
15677     return;
15678 
15679   if (FinalLoc.isValid())
15680     Record->addAttr(FinalAttr::Create(
15681         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
15682         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
15683 
15684   // C++ [class]p2:
15685   //   [...] The class-name is also inserted into the scope of the
15686   //   class itself; this is known as the injected-class-name. For
15687   //   purposes of access checking, the injected-class-name is treated
15688   //   as if it were a public member name.
15689   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
15690       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
15691       Record->getLocation(), Record->getIdentifier(),
15692       /*PrevDecl=*/nullptr,
15693       /*DelayTypeCreation=*/true);
15694   Context.getTypeDeclType(InjectedClassName, Record);
15695   InjectedClassName->setImplicit();
15696   InjectedClassName->setAccess(AS_public);
15697   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
15698       InjectedClassName->setDescribedClassTemplate(Template);
15699   PushOnScopeChains(InjectedClassName, S);
15700   assert(InjectedClassName->isInjectedClassName() &&
15701          "Broken injected-class-name");
15702 }
15703 
15704 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
15705                                     SourceRange BraceRange) {
15706   AdjustDeclIfTemplate(TagD);
15707   TagDecl *Tag = cast<TagDecl>(TagD);
15708   Tag->setBraceRange(BraceRange);
15709 
15710   // Make sure we "complete" the definition even it is invalid.
15711   if (Tag->isBeingDefined()) {
15712     assert(Tag->isInvalidDecl() && "We should already have completed it");
15713     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15714       RD->completeDefinition();
15715   }
15716 
15717   if (isa<CXXRecordDecl>(Tag)) {
15718     FieldCollector->FinishClass();
15719   }
15720 
15721   // Exit this scope of this tag's definition.
15722   PopDeclContext();
15723 
15724   if (getCurLexicalContext()->isObjCContainer() &&
15725       Tag->getDeclContext()->isFileContext())
15726     Tag->setTopLevelDeclInObjCContainer();
15727 
15728   // Notify the consumer that we've defined a tag.
15729   if (!Tag->isInvalidDecl())
15730     Consumer.HandleTagDeclDefinition(Tag);
15731 }
15732 
15733 void Sema::ActOnObjCContainerFinishDefinition() {
15734   // Exit this scope of this interface definition.
15735   PopDeclContext();
15736 }
15737 
15738 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
15739   assert(DC == CurContext && "Mismatch of container contexts");
15740   OriginalLexicalContext = DC;
15741   ActOnObjCContainerFinishDefinition();
15742 }
15743 
15744 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
15745   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
15746   OriginalLexicalContext = nullptr;
15747 }
15748 
15749 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
15750   AdjustDeclIfTemplate(TagD);
15751   TagDecl *Tag = cast<TagDecl>(TagD);
15752   Tag->setInvalidDecl();
15753 
15754   // Make sure we "complete" the definition even it is invalid.
15755   if (Tag->isBeingDefined()) {
15756     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15757       RD->completeDefinition();
15758   }
15759 
15760   // We're undoing ActOnTagStartDefinition here, not
15761   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
15762   // the FieldCollector.
15763 
15764   PopDeclContext();
15765 }
15766 
15767 // Note that FieldName may be null for anonymous bitfields.
15768 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
15769                                 IdentifierInfo *FieldName,
15770                                 QualType FieldTy, bool IsMsStruct,
15771                                 Expr *BitWidth, bool *ZeroWidth) {
15772   // Default to true; that shouldn't confuse checks for emptiness
15773   if (ZeroWidth)
15774     *ZeroWidth = true;
15775 
15776   // C99 6.7.2.1p4 - verify the field type.
15777   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
15778   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
15779     // Handle incomplete types with specific error.
15780     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
15781       return ExprError();
15782     if (FieldName)
15783       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
15784         << FieldName << FieldTy << BitWidth->getSourceRange();
15785     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
15786       << FieldTy << BitWidth->getSourceRange();
15787   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
15788                                              UPPC_BitFieldWidth))
15789     return ExprError();
15790 
15791   // If the bit-width is type- or value-dependent, don't try to check
15792   // it now.
15793   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
15794     return BitWidth;
15795 
15796   llvm::APSInt Value;
15797   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
15798   if (ICE.isInvalid())
15799     return ICE;
15800   BitWidth = ICE.get();
15801 
15802   if (Value != 0 && ZeroWidth)
15803     *ZeroWidth = false;
15804 
15805   // Zero-width bitfield is ok for anonymous field.
15806   if (Value == 0 && FieldName)
15807     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
15808 
15809   if (Value.isSigned() && Value.isNegative()) {
15810     if (FieldName)
15811       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
15812                << FieldName << Value.toString(10);
15813     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
15814       << Value.toString(10);
15815   }
15816 
15817   if (!FieldTy->isDependentType()) {
15818     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
15819     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
15820     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
15821 
15822     // Over-wide bitfields are an error in C or when using the MSVC bitfield
15823     // ABI.
15824     bool CStdConstraintViolation =
15825         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
15826     bool MSBitfieldViolation =
15827         Value.ugt(TypeStorageSize) &&
15828         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
15829     if (CStdConstraintViolation || MSBitfieldViolation) {
15830       unsigned DiagWidth =
15831           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
15832       if (FieldName)
15833         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
15834                << FieldName << (unsigned)Value.getZExtValue()
15835                << !CStdConstraintViolation << DiagWidth;
15836 
15837       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
15838              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
15839              << DiagWidth;
15840     }
15841 
15842     // Warn on types where the user might conceivably expect to get all
15843     // specified bits as value bits: that's all integral types other than
15844     // 'bool'.
15845     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
15846       if (FieldName)
15847         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
15848             << FieldName << (unsigned)Value.getZExtValue()
15849             << (unsigned)TypeWidth;
15850       else
15851         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
15852             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
15853     }
15854   }
15855 
15856   return BitWidth;
15857 }
15858 
15859 /// ActOnField - Each field of a C struct/union is passed into this in order
15860 /// to create a FieldDecl object for it.
15861 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
15862                        Declarator &D, Expr *BitfieldWidth) {
15863   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
15864                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
15865                                /*InitStyle=*/ICIS_NoInit, AS_public);
15866   return Res;
15867 }
15868 
15869 /// HandleField - Analyze a field of a C struct or a C++ data member.
15870 ///
15871 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
15872                              SourceLocation DeclStart,
15873                              Declarator &D, Expr *BitWidth,
15874                              InClassInitStyle InitStyle,
15875                              AccessSpecifier AS) {
15876   if (D.isDecompositionDeclarator()) {
15877     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
15878     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
15879       << Decomp.getSourceRange();
15880     return nullptr;
15881   }
15882 
15883   IdentifierInfo *II = D.getIdentifier();
15884   SourceLocation Loc = DeclStart;
15885   if (II) Loc = D.getIdentifierLoc();
15886 
15887   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15888   QualType T = TInfo->getType();
15889   if (getLangOpts().CPlusPlus) {
15890     CheckExtraCXXDefaultArguments(D);
15891 
15892     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15893                                         UPPC_DataMemberType)) {
15894       D.setInvalidType();
15895       T = Context.IntTy;
15896       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15897     }
15898   }
15899 
15900   DiagnoseFunctionSpecifiers(D.getDeclSpec());
15901 
15902   if (D.getDeclSpec().isInlineSpecified())
15903     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15904         << getLangOpts().CPlusPlus17;
15905   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15906     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15907          diag::err_invalid_thread)
15908       << DeclSpec::getSpecifierName(TSCS);
15909 
15910   // Check to see if this name was declared as a member previously
15911   NamedDecl *PrevDecl = nullptr;
15912   LookupResult Previous(*this, II, Loc, LookupMemberName,
15913                         ForVisibleRedeclaration);
15914   LookupName(Previous, S);
15915   switch (Previous.getResultKind()) {
15916     case LookupResult::Found:
15917     case LookupResult::FoundUnresolvedValue:
15918       PrevDecl = Previous.getAsSingle<NamedDecl>();
15919       break;
15920 
15921     case LookupResult::FoundOverloaded:
15922       PrevDecl = Previous.getRepresentativeDecl();
15923       break;
15924 
15925     case LookupResult::NotFound:
15926     case LookupResult::NotFoundInCurrentInstantiation:
15927     case LookupResult::Ambiguous:
15928       break;
15929   }
15930   Previous.suppressDiagnostics();
15931 
15932   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15933     // Maybe we will complain about the shadowed template parameter.
15934     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15935     // Just pretend that we didn't see the previous declaration.
15936     PrevDecl = nullptr;
15937   }
15938 
15939   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15940     PrevDecl = nullptr;
15941 
15942   bool Mutable
15943     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
15944   SourceLocation TSSL = D.getBeginLoc();
15945   FieldDecl *NewFD
15946     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
15947                      TSSL, AS, PrevDecl, &D);
15948 
15949   if (NewFD->isInvalidDecl())
15950     Record->setInvalidDecl();
15951 
15952   if (D.getDeclSpec().isModulePrivateSpecified())
15953     NewFD->setModulePrivate();
15954 
15955   if (NewFD->isInvalidDecl() && PrevDecl) {
15956     // Don't introduce NewFD into scope; there's already something
15957     // with the same name in the same scope.
15958   } else if (II) {
15959     PushOnScopeChains(NewFD, S);
15960   } else
15961     Record->addDecl(NewFD);
15962 
15963   return NewFD;
15964 }
15965 
15966 /// Build a new FieldDecl and check its well-formedness.
15967 ///
15968 /// This routine builds a new FieldDecl given the fields name, type,
15969 /// record, etc. \p PrevDecl should refer to any previous declaration
15970 /// with the same name and in the same scope as the field to be
15971 /// created.
15972 ///
15973 /// \returns a new FieldDecl.
15974 ///
15975 /// \todo The Declarator argument is a hack. It will be removed once
15976 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
15977                                 TypeSourceInfo *TInfo,
15978                                 RecordDecl *Record, SourceLocation Loc,
15979                                 bool Mutable, Expr *BitWidth,
15980                                 InClassInitStyle InitStyle,
15981                                 SourceLocation TSSL,
15982                                 AccessSpecifier AS, NamedDecl *PrevDecl,
15983                                 Declarator *D) {
15984   IdentifierInfo *II = Name.getAsIdentifierInfo();
15985   bool InvalidDecl = false;
15986   if (D) InvalidDecl = D->isInvalidType();
15987 
15988   // If we receive a broken type, recover by assuming 'int' and
15989   // marking this declaration as invalid.
15990   if (T.isNull()) {
15991     InvalidDecl = true;
15992     T = Context.IntTy;
15993   }
15994 
15995   QualType EltTy = Context.getBaseElementType(T);
15996   if (!EltTy->isDependentType()) {
15997     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
15998       // Fields of incomplete type force their record to be invalid.
15999       Record->setInvalidDecl();
16000       InvalidDecl = true;
16001     } else {
16002       NamedDecl *Def;
16003       EltTy->isIncompleteType(&Def);
16004       if (Def && Def->isInvalidDecl()) {
16005         Record->setInvalidDecl();
16006         InvalidDecl = true;
16007       }
16008     }
16009   }
16010 
16011   // TR 18037 does not allow fields to be declared with address space
16012   if (T.getQualifiers().hasAddressSpace() || T->isDependentAddressSpaceType() ||
16013       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
16014     Diag(Loc, diag::err_field_with_address_space);
16015     Record->setInvalidDecl();
16016     InvalidDecl = true;
16017   }
16018 
16019   if (LangOpts.OpenCL) {
16020     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
16021     // used as structure or union field: image, sampler, event or block types.
16022     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
16023         T->isBlockPointerType()) {
16024       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
16025       Record->setInvalidDecl();
16026       InvalidDecl = true;
16027     }
16028     // OpenCL v1.2 s6.9.c: bitfields are not supported.
16029     if (BitWidth) {
16030       Diag(Loc, diag::err_opencl_bitfields);
16031       InvalidDecl = true;
16032     }
16033   }
16034 
16035   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
16036   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
16037       T.hasQualifiers()) {
16038     InvalidDecl = true;
16039     Diag(Loc, diag::err_anon_bitfield_qualifiers);
16040   }
16041 
16042   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16043   // than a variably modified type.
16044   if (!InvalidDecl && T->isVariablyModifiedType()) {
16045     bool SizeIsNegative;
16046     llvm::APSInt Oversized;
16047 
16048     TypeSourceInfo *FixedTInfo =
16049       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
16050                                                     SizeIsNegative,
16051                                                     Oversized);
16052     if (FixedTInfo) {
16053       Diag(Loc, diag::warn_illegal_constant_array_size);
16054       TInfo = FixedTInfo;
16055       T = FixedTInfo->getType();
16056     } else {
16057       if (SizeIsNegative)
16058         Diag(Loc, diag::err_typecheck_negative_array_size);
16059       else if (Oversized.getBoolValue())
16060         Diag(Loc, diag::err_array_too_large)
16061           << Oversized.toString(10);
16062       else
16063         Diag(Loc, diag::err_typecheck_field_variable_size);
16064       InvalidDecl = true;
16065     }
16066   }
16067 
16068   // Fields can not have abstract class types
16069   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
16070                                              diag::err_abstract_type_in_decl,
16071                                              AbstractFieldType))
16072     InvalidDecl = true;
16073 
16074   bool ZeroWidth = false;
16075   if (InvalidDecl)
16076     BitWidth = nullptr;
16077   // If this is declared as a bit-field, check the bit-field.
16078   if (BitWidth) {
16079     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
16080                               &ZeroWidth).get();
16081     if (!BitWidth) {
16082       InvalidDecl = true;
16083       BitWidth = nullptr;
16084       ZeroWidth = false;
16085     }
16086   }
16087 
16088   // Check that 'mutable' is consistent with the type of the declaration.
16089   if (!InvalidDecl && Mutable) {
16090     unsigned DiagID = 0;
16091     if (T->isReferenceType())
16092       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
16093                                         : diag::err_mutable_reference;
16094     else if (T.isConstQualified())
16095       DiagID = diag::err_mutable_const;
16096 
16097     if (DiagID) {
16098       SourceLocation ErrLoc = Loc;
16099       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
16100         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
16101       Diag(ErrLoc, DiagID);
16102       if (DiagID != diag::ext_mutable_reference) {
16103         Mutable = false;
16104         InvalidDecl = true;
16105       }
16106     }
16107   }
16108 
16109   // C++11 [class.union]p8 (DR1460):
16110   //   At most one variant member of a union may have a
16111   //   brace-or-equal-initializer.
16112   if (InitStyle != ICIS_NoInit)
16113     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
16114 
16115   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
16116                                        BitWidth, Mutable, InitStyle);
16117   if (InvalidDecl)
16118     NewFD->setInvalidDecl();
16119 
16120   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
16121     Diag(Loc, diag::err_duplicate_member) << II;
16122     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16123     NewFD->setInvalidDecl();
16124   }
16125 
16126   if (!InvalidDecl && getLangOpts().CPlusPlus) {
16127     if (Record->isUnion()) {
16128       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16129         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
16130         if (RDecl->getDefinition()) {
16131           // C++ [class.union]p1: An object of a class with a non-trivial
16132           // constructor, a non-trivial copy constructor, a non-trivial
16133           // destructor, or a non-trivial copy assignment operator
16134           // cannot be a member of a union, nor can an array of such
16135           // objects.
16136           if (CheckNontrivialField(NewFD))
16137             NewFD->setInvalidDecl();
16138         }
16139       }
16140 
16141       // C++ [class.union]p1: If a union contains a member of reference type,
16142       // the program is ill-formed, except when compiling with MSVC extensions
16143       // enabled.
16144       if (EltTy->isReferenceType()) {
16145         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
16146                                     diag::ext_union_member_of_reference_type :
16147                                     diag::err_union_member_of_reference_type)
16148           << NewFD->getDeclName() << EltTy;
16149         if (!getLangOpts().MicrosoftExt)
16150           NewFD->setInvalidDecl();
16151       }
16152     }
16153   }
16154 
16155   // FIXME: We need to pass in the attributes given an AST
16156   // representation, not a parser representation.
16157   if (D) {
16158     // FIXME: The current scope is almost... but not entirely... correct here.
16159     ProcessDeclAttributes(getCurScope(), NewFD, *D);
16160 
16161     if (NewFD->hasAttrs())
16162       CheckAlignasUnderalignment(NewFD);
16163   }
16164 
16165   // In auto-retain/release, infer strong retension for fields of
16166   // retainable type.
16167   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
16168     NewFD->setInvalidDecl();
16169 
16170   if (T.isObjCGCWeak())
16171     Diag(Loc, diag::warn_attribute_weak_on_field);
16172 
16173   NewFD->setAccess(AS);
16174   return NewFD;
16175 }
16176 
16177 bool Sema::CheckNontrivialField(FieldDecl *FD) {
16178   assert(FD);
16179   assert(getLangOpts().CPlusPlus && "valid check only for C++");
16180 
16181   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
16182     return false;
16183 
16184   QualType EltTy = Context.getBaseElementType(FD->getType());
16185   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16186     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
16187     if (RDecl->getDefinition()) {
16188       // We check for copy constructors before constructors
16189       // because otherwise we'll never get complaints about
16190       // copy constructors.
16191 
16192       CXXSpecialMember member = CXXInvalid;
16193       // We're required to check for any non-trivial constructors. Since the
16194       // implicit default constructor is suppressed if there are any
16195       // user-declared constructors, we just need to check that there is a
16196       // trivial default constructor and a trivial copy constructor. (We don't
16197       // worry about move constructors here, since this is a C++98 check.)
16198       if (RDecl->hasNonTrivialCopyConstructor())
16199         member = CXXCopyConstructor;
16200       else if (!RDecl->hasTrivialDefaultConstructor())
16201         member = CXXDefaultConstructor;
16202       else if (RDecl->hasNonTrivialCopyAssignment())
16203         member = CXXCopyAssignment;
16204       else if (RDecl->hasNonTrivialDestructor())
16205         member = CXXDestructor;
16206 
16207       if (member != CXXInvalid) {
16208         if (!getLangOpts().CPlusPlus11 &&
16209             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
16210           // Objective-C++ ARC: it is an error to have a non-trivial field of
16211           // a union. However, system headers in Objective-C programs
16212           // occasionally have Objective-C lifetime objects within unions,
16213           // and rather than cause the program to fail, we make those
16214           // members unavailable.
16215           SourceLocation Loc = FD->getLocation();
16216           if (getSourceManager().isInSystemHeader(Loc)) {
16217             if (!FD->hasAttr<UnavailableAttr>())
16218               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
16219                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
16220             return false;
16221           }
16222         }
16223 
16224         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
16225                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
16226                diag::err_illegal_union_or_anon_struct_member)
16227           << FD->getParent()->isUnion() << FD->getDeclName() << member;
16228         DiagnoseNontrivial(RDecl, member);
16229         return !getLangOpts().CPlusPlus11;
16230       }
16231     }
16232   }
16233 
16234   return false;
16235 }
16236 
16237 /// TranslateIvarVisibility - Translate visibility from a token ID to an
16238 ///  AST enum value.
16239 static ObjCIvarDecl::AccessControl
16240 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
16241   switch (ivarVisibility) {
16242   default: llvm_unreachable("Unknown visitibility kind");
16243   case tok::objc_private: return ObjCIvarDecl::Private;
16244   case tok::objc_public: return ObjCIvarDecl::Public;
16245   case tok::objc_protected: return ObjCIvarDecl::Protected;
16246   case tok::objc_package: return ObjCIvarDecl::Package;
16247   }
16248 }
16249 
16250 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
16251 /// in order to create an IvarDecl object for it.
16252 Decl *Sema::ActOnIvar(Scope *S,
16253                                 SourceLocation DeclStart,
16254                                 Declarator &D, Expr *BitfieldWidth,
16255                                 tok::ObjCKeywordKind Visibility) {
16256 
16257   IdentifierInfo *II = D.getIdentifier();
16258   Expr *BitWidth = (Expr*)BitfieldWidth;
16259   SourceLocation Loc = DeclStart;
16260   if (II) Loc = D.getIdentifierLoc();
16261 
16262   // FIXME: Unnamed fields can be handled in various different ways, for
16263   // example, unnamed unions inject all members into the struct namespace!
16264 
16265   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16266   QualType T = TInfo->getType();
16267 
16268   if (BitWidth) {
16269     // 6.7.2.1p3, 6.7.2.1p4
16270     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
16271     if (!BitWidth)
16272       D.setInvalidType();
16273   } else {
16274     // Not a bitfield.
16275 
16276     // validate II.
16277 
16278   }
16279   if (T->isReferenceType()) {
16280     Diag(Loc, diag::err_ivar_reference_type);
16281     D.setInvalidType();
16282   }
16283   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16284   // than a variably modified type.
16285   else if (T->isVariablyModifiedType()) {
16286     Diag(Loc, diag::err_typecheck_ivar_variable_size);
16287     D.setInvalidType();
16288   }
16289 
16290   // Get the visibility (access control) for this ivar.
16291   ObjCIvarDecl::AccessControl ac =
16292     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
16293                                         : ObjCIvarDecl::None;
16294   // Must set ivar's DeclContext to its enclosing interface.
16295   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
16296   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
16297     return nullptr;
16298   ObjCContainerDecl *EnclosingContext;
16299   if (ObjCImplementationDecl *IMPDecl =
16300       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16301     if (LangOpts.ObjCRuntime.isFragile()) {
16302     // Case of ivar declared in an implementation. Context is that of its class.
16303       EnclosingContext = IMPDecl->getClassInterface();
16304       assert(EnclosingContext && "Implementation has no class interface!");
16305     }
16306     else
16307       EnclosingContext = EnclosingDecl;
16308   } else {
16309     if (ObjCCategoryDecl *CDecl =
16310         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16311       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
16312         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
16313         return nullptr;
16314       }
16315     }
16316     EnclosingContext = EnclosingDecl;
16317   }
16318 
16319   // Construct the decl.
16320   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
16321                                              DeclStart, Loc, II, T,
16322                                              TInfo, ac, (Expr *)BitfieldWidth);
16323 
16324   if (II) {
16325     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
16326                                            ForVisibleRedeclaration);
16327     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
16328         && !isa<TagDecl>(PrevDecl)) {
16329       Diag(Loc, diag::err_duplicate_member) << II;
16330       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16331       NewID->setInvalidDecl();
16332     }
16333   }
16334 
16335   // Process attributes attached to the ivar.
16336   ProcessDeclAttributes(S, NewID, D);
16337 
16338   if (D.isInvalidType())
16339     NewID->setInvalidDecl();
16340 
16341   // In ARC, infer 'retaining' for ivars of retainable type.
16342   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
16343     NewID->setInvalidDecl();
16344 
16345   if (D.getDeclSpec().isModulePrivateSpecified())
16346     NewID->setModulePrivate();
16347 
16348   if (II) {
16349     // FIXME: When interfaces are DeclContexts, we'll need to add
16350     // these to the interface.
16351     S->AddDecl(NewID);
16352     IdResolver.AddDecl(NewID);
16353   }
16354 
16355   if (LangOpts.ObjCRuntime.isNonFragile() &&
16356       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
16357     Diag(Loc, diag::warn_ivars_in_interface);
16358 
16359   return NewID;
16360 }
16361 
16362 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
16363 /// class and class extensions. For every class \@interface and class
16364 /// extension \@interface, if the last ivar is a bitfield of any type,
16365 /// then add an implicit `char :0` ivar to the end of that interface.
16366 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
16367                              SmallVectorImpl<Decl *> &AllIvarDecls) {
16368   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
16369     return;
16370 
16371   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
16372   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
16373 
16374   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
16375     return;
16376   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
16377   if (!ID) {
16378     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
16379       if (!CD->IsClassExtension())
16380         return;
16381     }
16382     // No need to add this to end of @implementation.
16383     else
16384       return;
16385   }
16386   // All conditions are met. Add a new bitfield to the tail end of ivars.
16387   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
16388   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
16389 
16390   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
16391                               DeclLoc, DeclLoc, nullptr,
16392                               Context.CharTy,
16393                               Context.getTrivialTypeSourceInfo(Context.CharTy,
16394                                                                DeclLoc),
16395                               ObjCIvarDecl::Private, BW,
16396                               true);
16397   AllIvarDecls.push_back(Ivar);
16398 }
16399 
16400 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
16401                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
16402                        SourceLocation RBrac,
16403                        const ParsedAttributesView &Attrs) {
16404   assert(EnclosingDecl && "missing record or interface decl");
16405 
16406   // If this is an Objective-C @implementation or category and we have
16407   // new fields here we should reset the layout of the interface since
16408   // it will now change.
16409   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
16410     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
16411     switch (DC->getKind()) {
16412     default: break;
16413     case Decl::ObjCCategory:
16414       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
16415       break;
16416     case Decl::ObjCImplementation:
16417       Context.
16418         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
16419       break;
16420     }
16421   }
16422 
16423   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
16424   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
16425 
16426   // Start counting up the number of named members; make sure to include
16427   // members of anonymous structs and unions in the total.
16428   unsigned NumNamedMembers = 0;
16429   if (Record) {
16430     for (const auto *I : Record->decls()) {
16431       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
16432         if (IFD->getDeclName())
16433           ++NumNamedMembers;
16434     }
16435   }
16436 
16437   // Verify that all the fields are okay.
16438   SmallVector<FieldDecl*, 32> RecFields;
16439 
16440   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
16441        i != end; ++i) {
16442     FieldDecl *FD = cast<FieldDecl>(*i);
16443 
16444     // Get the type for the field.
16445     const Type *FDTy = FD->getType().getTypePtr();
16446 
16447     if (!FD->isAnonymousStructOrUnion()) {
16448       // Remember all fields written by the user.
16449       RecFields.push_back(FD);
16450     }
16451 
16452     // If the field is already invalid for some reason, don't emit more
16453     // diagnostics about it.
16454     if (FD->isInvalidDecl()) {
16455       EnclosingDecl->setInvalidDecl();
16456       continue;
16457     }
16458 
16459     // C99 6.7.2.1p2:
16460     //   A structure or union shall not contain a member with
16461     //   incomplete or function type (hence, a structure shall not
16462     //   contain an instance of itself, but may contain a pointer to
16463     //   an instance of itself), except that the last member of a
16464     //   structure with more than one named member may have incomplete
16465     //   array type; such a structure (and any union containing,
16466     //   possibly recursively, a member that is such a structure)
16467     //   shall not be a member of a structure or an element of an
16468     //   array.
16469     bool IsLastField = (i + 1 == Fields.end());
16470     if (FDTy->isFunctionType()) {
16471       // Field declared as a function.
16472       Diag(FD->getLocation(), diag::err_field_declared_as_function)
16473         << FD->getDeclName();
16474       FD->setInvalidDecl();
16475       EnclosingDecl->setInvalidDecl();
16476       continue;
16477     } else if (FDTy->isIncompleteArrayType() &&
16478                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
16479       if (Record) {
16480         // Flexible array member.
16481         // Microsoft and g++ is more permissive regarding flexible array.
16482         // It will accept flexible array in union and also
16483         // as the sole element of a struct/class.
16484         unsigned DiagID = 0;
16485         if (!Record->isUnion() && !IsLastField) {
16486           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
16487             << FD->getDeclName() << FD->getType() << Record->getTagKind();
16488           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
16489           FD->setInvalidDecl();
16490           EnclosingDecl->setInvalidDecl();
16491           continue;
16492         } else if (Record->isUnion())
16493           DiagID = getLangOpts().MicrosoftExt
16494                        ? diag::ext_flexible_array_union_ms
16495                        : getLangOpts().CPlusPlus
16496                              ? diag::ext_flexible_array_union_gnu
16497                              : diag::err_flexible_array_union;
16498         else if (NumNamedMembers < 1)
16499           DiagID = getLangOpts().MicrosoftExt
16500                        ? diag::ext_flexible_array_empty_aggregate_ms
16501                        : getLangOpts().CPlusPlus
16502                              ? diag::ext_flexible_array_empty_aggregate_gnu
16503                              : diag::err_flexible_array_empty_aggregate;
16504 
16505         if (DiagID)
16506           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
16507                                           << Record->getTagKind();
16508         // While the layout of types that contain virtual bases is not specified
16509         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
16510         // virtual bases after the derived members.  This would make a flexible
16511         // array member declared at the end of an object not adjacent to the end
16512         // of the type.
16513         if (CXXRecord && CXXRecord->getNumVBases() != 0)
16514           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
16515               << FD->getDeclName() << Record->getTagKind();
16516         if (!getLangOpts().C99)
16517           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
16518             << FD->getDeclName() << Record->getTagKind();
16519 
16520         // If the element type has a non-trivial destructor, we would not
16521         // implicitly destroy the elements, so disallow it for now.
16522         //
16523         // FIXME: GCC allows this. We should probably either implicitly delete
16524         // the destructor of the containing class, or just allow this.
16525         QualType BaseElem = Context.getBaseElementType(FD->getType());
16526         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
16527           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
16528             << FD->getDeclName() << FD->getType();
16529           FD->setInvalidDecl();
16530           EnclosingDecl->setInvalidDecl();
16531           continue;
16532         }
16533         // Okay, we have a legal flexible array member at the end of the struct.
16534         Record->setHasFlexibleArrayMember(true);
16535       } else {
16536         // In ObjCContainerDecl ivars with incomplete array type are accepted,
16537         // unless they are followed by another ivar. That check is done
16538         // elsewhere, after synthesized ivars are known.
16539       }
16540     } else if (!FDTy->isDependentType() &&
16541                RequireCompleteType(FD->getLocation(), FD->getType(),
16542                                    diag::err_field_incomplete)) {
16543       // Incomplete type
16544       FD->setInvalidDecl();
16545       EnclosingDecl->setInvalidDecl();
16546       continue;
16547     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
16548       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
16549         // A type which contains a flexible array member is considered to be a
16550         // flexible array member.
16551         Record->setHasFlexibleArrayMember(true);
16552         if (!Record->isUnion()) {
16553           // If this is a struct/class and this is not the last element, reject
16554           // it.  Note that GCC supports variable sized arrays in the middle of
16555           // structures.
16556           if (!IsLastField)
16557             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
16558               << FD->getDeclName() << FD->getType();
16559           else {
16560             // We support flexible arrays at the end of structs in
16561             // other structs as an extension.
16562             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
16563               << FD->getDeclName();
16564           }
16565         }
16566       }
16567       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
16568           RequireNonAbstractType(FD->getLocation(), FD->getType(),
16569                                  diag::err_abstract_type_in_decl,
16570                                  AbstractIvarType)) {
16571         // Ivars can not have abstract class types
16572         FD->setInvalidDecl();
16573       }
16574       if (Record && FDTTy->getDecl()->hasObjectMember())
16575         Record->setHasObjectMember(true);
16576       if (Record && FDTTy->getDecl()->hasVolatileMember())
16577         Record->setHasVolatileMember(true);
16578     } else if (FDTy->isObjCObjectType()) {
16579       /// A field cannot be an Objective-c object
16580       Diag(FD->getLocation(), diag::err_statically_allocated_object)
16581         << FixItHint::CreateInsertion(FD->getLocation(), "*");
16582       QualType T = Context.getObjCObjectPointerType(FD->getType());
16583       FD->setType(T);
16584     } else if (Record && Record->isUnion() &&
16585                FD->getType().hasNonTrivialObjCLifetime() &&
16586                getSourceManager().isInSystemHeader(FD->getLocation()) &&
16587                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
16588                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
16589                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
16590       // For backward compatibility, fields of C unions declared in system
16591       // headers that have non-trivial ObjC ownership qualifications are marked
16592       // as unavailable unless the qualifier is explicit and __strong. This can
16593       // break ABI compatibility between programs compiled with ARC and MRR, but
16594       // is a better option than rejecting programs using those unions under
16595       // ARC.
16596       FD->addAttr(UnavailableAttr::CreateImplicit(
16597           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
16598           FD->getLocation()));
16599     } else if (getLangOpts().ObjC &&
16600                getLangOpts().getGC() != LangOptions::NonGC &&
16601                Record && !Record->hasObjectMember()) {
16602       if (FD->getType()->isObjCObjectPointerType() ||
16603           FD->getType().isObjCGCStrong())
16604         Record->setHasObjectMember(true);
16605       else if (Context.getAsArrayType(FD->getType())) {
16606         QualType BaseType = Context.getBaseElementType(FD->getType());
16607         if (BaseType->isRecordType() &&
16608             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
16609           Record->setHasObjectMember(true);
16610         else if (BaseType->isObjCObjectPointerType() ||
16611                  BaseType.isObjCGCStrong())
16612                Record->setHasObjectMember(true);
16613       }
16614     }
16615 
16616     if (Record && !getLangOpts().CPlusPlus &&
16617         !shouldIgnoreForRecordTriviality(FD)) {
16618       QualType FT = FD->getType();
16619       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
16620         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
16621         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
16622             Record->isUnion())
16623           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
16624       }
16625       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
16626       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
16627         Record->setNonTrivialToPrimitiveCopy(true);
16628         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
16629           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
16630       }
16631       if (FT.isDestructedType()) {
16632         Record->setNonTrivialToPrimitiveDestroy(true);
16633         Record->setParamDestroyedInCallee(true);
16634         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
16635           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
16636       }
16637 
16638       if (const auto *RT = FT->getAs<RecordType>()) {
16639         if (RT->getDecl()->getArgPassingRestrictions() ==
16640             RecordDecl::APK_CanNeverPassInRegs)
16641           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16642       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
16643         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16644     }
16645 
16646     if (Record && FD->getType().isVolatileQualified())
16647       Record->setHasVolatileMember(true);
16648     // Keep track of the number of named members.
16649     if (FD->getIdentifier())
16650       ++NumNamedMembers;
16651   }
16652 
16653   // Okay, we successfully defined 'Record'.
16654   if (Record) {
16655     bool Completed = false;
16656     if (CXXRecord) {
16657       if (!CXXRecord->isInvalidDecl()) {
16658         // Set access bits correctly on the directly-declared conversions.
16659         for (CXXRecordDecl::conversion_iterator
16660                I = CXXRecord->conversion_begin(),
16661                E = CXXRecord->conversion_end(); I != E; ++I)
16662           I.setAccess((*I)->getAccess());
16663       }
16664 
16665       if (!CXXRecord->isDependentType()) {
16666         // Add any implicitly-declared members to this class.
16667         AddImplicitlyDeclaredMembersToClass(CXXRecord);
16668 
16669         if (!CXXRecord->isInvalidDecl()) {
16670           // If we have virtual base classes, we may end up finding multiple
16671           // final overriders for a given virtual function. Check for this
16672           // problem now.
16673           if (CXXRecord->getNumVBases()) {
16674             CXXFinalOverriderMap FinalOverriders;
16675             CXXRecord->getFinalOverriders(FinalOverriders);
16676 
16677             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
16678                                              MEnd = FinalOverriders.end();
16679                  M != MEnd; ++M) {
16680               for (OverridingMethods::iterator SO = M->second.begin(),
16681                                             SOEnd = M->second.end();
16682                    SO != SOEnd; ++SO) {
16683                 assert(SO->second.size() > 0 &&
16684                        "Virtual function without overriding functions?");
16685                 if (SO->second.size() == 1)
16686                   continue;
16687 
16688                 // C++ [class.virtual]p2:
16689                 //   In a derived class, if a virtual member function of a base
16690                 //   class subobject has more than one final overrider the
16691                 //   program is ill-formed.
16692                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
16693                   << (const NamedDecl *)M->first << Record;
16694                 Diag(M->first->getLocation(),
16695                      diag::note_overridden_virtual_function);
16696                 for (OverridingMethods::overriding_iterator
16697                           OM = SO->second.begin(),
16698                        OMEnd = SO->second.end();
16699                      OM != OMEnd; ++OM)
16700                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
16701                     << (const NamedDecl *)M->first << OM->Method->getParent();
16702 
16703                 Record->setInvalidDecl();
16704               }
16705             }
16706             CXXRecord->completeDefinition(&FinalOverriders);
16707             Completed = true;
16708           }
16709         }
16710       }
16711     }
16712 
16713     if (!Completed)
16714       Record->completeDefinition();
16715 
16716     // Handle attributes before checking the layout.
16717     ProcessDeclAttributeList(S, Record, Attrs);
16718 
16719     // We may have deferred checking for a deleted destructor. Check now.
16720     if (CXXRecord) {
16721       auto *Dtor = CXXRecord->getDestructor();
16722       if (Dtor && Dtor->isImplicit() &&
16723           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
16724         CXXRecord->setImplicitDestructorIsDeleted();
16725         SetDeclDeleted(Dtor, CXXRecord->getLocation());
16726       }
16727     }
16728 
16729     if (Record->hasAttrs()) {
16730       CheckAlignasUnderalignment(Record);
16731 
16732       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
16733         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
16734                                            IA->getRange(), IA->getBestCase(),
16735                                            IA->getSemanticSpelling());
16736     }
16737 
16738     // Check if the structure/union declaration is a type that can have zero
16739     // size in C. For C this is a language extension, for C++ it may cause
16740     // compatibility problems.
16741     bool CheckForZeroSize;
16742     if (!getLangOpts().CPlusPlus) {
16743       CheckForZeroSize = true;
16744     } else {
16745       // For C++ filter out types that cannot be referenced in C code.
16746       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
16747       CheckForZeroSize =
16748           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
16749           !CXXRecord->isDependentType() &&
16750           CXXRecord->isCLike();
16751     }
16752     if (CheckForZeroSize) {
16753       bool ZeroSize = true;
16754       bool IsEmpty = true;
16755       unsigned NonBitFields = 0;
16756       for (RecordDecl::field_iterator I = Record->field_begin(),
16757                                       E = Record->field_end();
16758            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
16759         IsEmpty = false;
16760         if (I->isUnnamedBitfield()) {
16761           if (!I->isZeroLengthBitField(Context))
16762             ZeroSize = false;
16763         } else {
16764           ++NonBitFields;
16765           QualType FieldType = I->getType();
16766           if (FieldType->isIncompleteType() ||
16767               !Context.getTypeSizeInChars(FieldType).isZero())
16768             ZeroSize = false;
16769         }
16770       }
16771 
16772       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
16773       // allowed in C++, but warn if its declaration is inside
16774       // extern "C" block.
16775       if (ZeroSize) {
16776         Diag(RecLoc, getLangOpts().CPlusPlus ?
16777                          diag::warn_zero_size_struct_union_in_extern_c :
16778                          diag::warn_zero_size_struct_union_compat)
16779           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
16780       }
16781 
16782       // Structs without named members are extension in C (C99 6.7.2.1p7),
16783       // but are accepted by GCC.
16784       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
16785         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
16786                                diag::ext_no_named_members_in_struct_union)
16787           << Record->isUnion();
16788       }
16789     }
16790   } else {
16791     ObjCIvarDecl **ClsFields =
16792       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
16793     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
16794       ID->setEndOfDefinitionLoc(RBrac);
16795       // Add ivar's to class's DeclContext.
16796       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16797         ClsFields[i]->setLexicalDeclContext(ID);
16798         ID->addDecl(ClsFields[i]);
16799       }
16800       // Must enforce the rule that ivars in the base classes may not be
16801       // duplicates.
16802       if (ID->getSuperClass())
16803         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
16804     } else if (ObjCImplementationDecl *IMPDecl =
16805                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16806       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
16807       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
16808         // Ivar declared in @implementation never belongs to the implementation.
16809         // Only it is in implementation's lexical context.
16810         ClsFields[I]->setLexicalDeclContext(IMPDecl);
16811       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
16812       IMPDecl->setIvarLBraceLoc(LBrac);
16813       IMPDecl->setIvarRBraceLoc(RBrac);
16814     } else if (ObjCCategoryDecl *CDecl =
16815                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16816       // case of ivars in class extension; all other cases have been
16817       // reported as errors elsewhere.
16818       // FIXME. Class extension does not have a LocEnd field.
16819       // CDecl->setLocEnd(RBrac);
16820       // Add ivar's to class extension's DeclContext.
16821       // Diagnose redeclaration of private ivars.
16822       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
16823       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16824         if (IDecl) {
16825           if (const ObjCIvarDecl *ClsIvar =
16826               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
16827             Diag(ClsFields[i]->getLocation(),
16828                  diag::err_duplicate_ivar_declaration);
16829             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
16830             continue;
16831           }
16832           for (const auto *Ext : IDecl->known_extensions()) {
16833             if (const ObjCIvarDecl *ClsExtIvar
16834                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
16835               Diag(ClsFields[i]->getLocation(),
16836                    diag::err_duplicate_ivar_declaration);
16837               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
16838               continue;
16839             }
16840           }
16841         }
16842         ClsFields[i]->setLexicalDeclContext(CDecl);
16843         CDecl->addDecl(ClsFields[i]);
16844       }
16845       CDecl->setIvarLBraceLoc(LBrac);
16846       CDecl->setIvarRBraceLoc(RBrac);
16847     }
16848   }
16849 }
16850 
16851 /// Determine whether the given integral value is representable within
16852 /// the given type T.
16853 static bool isRepresentableIntegerValue(ASTContext &Context,
16854                                         llvm::APSInt &Value,
16855                                         QualType T) {
16856   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
16857          "Integral type required!");
16858   unsigned BitWidth = Context.getIntWidth(T);
16859 
16860   if (Value.isUnsigned() || Value.isNonNegative()) {
16861     if (T->isSignedIntegerOrEnumerationType())
16862       --BitWidth;
16863     return Value.getActiveBits() <= BitWidth;
16864   }
16865   return Value.getMinSignedBits() <= BitWidth;
16866 }
16867 
16868 // Given an integral type, return the next larger integral type
16869 // (or a NULL type of no such type exists).
16870 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
16871   // FIXME: Int128/UInt128 support, which also needs to be introduced into
16872   // enum checking below.
16873   assert((T->isIntegralType(Context) ||
16874          T->isEnumeralType()) && "Integral type required!");
16875   const unsigned NumTypes = 4;
16876   QualType SignedIntegralTypes[NumTypes] = {
16877     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
16878   };
16879   QualType UnsignedIntegralTypes[NumTypes] = {
16880     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
16881     Context.UnsignedLongLongTy
16882   };
16883 
16884   unsigned BitWidth = Context.getTypeSize(T);
16885   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
16886                                                         : UnsignedIntegralTypes;
16887   for (unsigned I = 0; I != NumTypes; ++I)
16888     if (Context.getTypeSize(Types[I]) > BitWidth)
16889       return Types[I];
16890 
16891   return QualType();
16892 }
16893 
16894 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
16895                                           EnumConstantDecl *LastEnumConst,
16896                                           SourceLocation IdLoc,
16897                                           IdentifierInfo *Id,
16898                                           Expr *Val) {
16899   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16900   llvm::APSInt EnumVal(IntWidth);
16901   QualType EltTy;
16902 
16903   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
16904     Val = nullptr;
16905 
16906   if (Val)
16907     Val = DefaultLvalueConversion(Val).get();
16908 
16909   if (Val) {
16910     if (Enum->isDependentType() || Val->isTypeDependent())
16911       EltTy = Context.DependentTy;
16912     else {
16913       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
16914         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
16915         // constant-expression in the enumerator-definition shall be a converted
16916         // constant expression of the underlying type.
16917         EltTy = Enum->getIntegerType();
16918         ExprResult Converted =
16919           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
16920                                            CCEK_Enumerator);
16921         if (Converted.isInvalid())
16922           Val = nullptr;
16923         else
16924           Val = Converted.get();
16925       } else if (!Val->isValueDependent() &&
16926                  !(Val = VerifyIntegerConstantExpression(Val,
16927                                                          &EnumVal).get())) {
16928         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
16929       } else {
16930         if (Enum->isComplete()) {
16931           EltTy = Enum->getIntegerType();
16932 
16933           // In Obj-C and Microsoft mode, require the enumeration value to be
16934           // representable in the underlying type of the enumeration. In C++11,
16935           // we perform a non-narrowing conversion as part of converted constant
16936           // expression checking.
16937           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
16938             if (Context.getTargetInfo()
16939                     .getTriple()
16940                     .isWindowsMSVCEnvironment()) {
16941               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
16942             } else {
16943               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
16944             }
16945           }
16946 
16947           // Cast to the underlying type.
16948           Val = ImpCastExprToType(Val, EltTy,
16949                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
16950                                                          : CK_IntegralCast)
16951                     .get();
16952         } else if (getLangOpts().CPlusPlus) {
16953           // C++11 [dcl.enum]p5:
16954           //   If the underlying type is not fixed, the type of each enumerator
16955           //   is the type of its initializing value:
16956           //     - If an initializer is specified for an enumerator, the
16957           //       initializing value has the same type as the expression.
16958           EltTy = Val->getType();
16959         } else {
16960           // C99 6.7.2.2p2:
16961           //   The expression that defines the value of an enumeration constant
16962           //   shall be an integer constant expression that has a value
16963           //   representable as an int.
16964 
16965           // Complain if the value is not representable in an int.
16966           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
16967             Diag(IdLoc, diag::ext_enum_value_not_int)
16968               << EnumVal.toString(10) << Val->getSourceRange()
16969               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
16970           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
16971             // Force the type of the expression to 'int'.
16972             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
16973           }
16974           EltTy = Val->getType();
16975         }
16976       }
16977     }
16978   }
16979 
16980   if (!Val) {
16981     if (Enum->isDependentType())
16982       EltTy = Context.DependentTy;
16983     else if (!LastEnumConst) {
16984       // C++0x [dcl.enum]p5:
16985       //   If the underlying type is not fixed, the type of each enumerator
16986       //   is the type of its initializing value:
16987       //     - If no initializer is specified for the first enumerator, the
16988       //       initializing value has an unspecified integral type.
16989       //
16990       // GCC uses 'int' for its unspecified integral type, as does
16991       // C99 6.7.2.2p3.
16992       if (Enum->isFixed()) {
16993         EltTy = Enum->getIntegerType();
16994       }
16995       else {
16996         EltTy = Context.IntTy;
16997       }
16998     } else {
16999       // Assign the last value + 1.
17000       EnumVal = LastEnumConst->getInitVal();
17001       ++EnumVal;
17002       EltTy = LastEnumConst->getType();
17003 
17004       // Check for overflow on increment.
17005       if (EnumVal < LastEnumConst->getInitVal()) {
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         //
17010         //     - Otherwise the type of the initializing value is the same as
17011         //       the type of the initializing value of the preceding enumerator
17012         //       unless the incremented value is not representable in that type,
17013         //       in which case the type is an unspecified integral type
17014         //       sufficient to contain the incremented value. If no such type
17015         //       exists, the program is ill-formed.
17016         QualType T = getNextLargerIntegralType(Context, EltTy);
17017         if (T.isNull() || Enum->isFixed()) {
17018           // There is no integral type larger enough to represent this
17019           // value. Complain, then allow the value to wrap around.
17020           EnumVal = LastEnumConst->getInitVal();
17021           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
17022           ++EnumVal;
17023           if (Enum->isFixed())
17024             // When the underlying type is fixed, this is ill-formed.
17025             Diag(IdLoc, diag::err_enumerator_wrapped)
17026               << EnumVal.toString(10)
17027               << EltTy;
17028           else
17029             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
17030               << EnumVal.toString(10);
17031         } else {
17032           EltTy = T;
17033         }
17034 
17035         // Retrieve the last enumerator's value, extent that type to the
17036         // type that is supposed to be large enough to represent the incremented
17037         // value, then increment.
17038         EnumVal = LastEnumConst->getInitVal();
17039         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17040         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
17041         ++EnumVal;
17042 
17043         // If we're not in C++, diagnose the overflow of enumerator values,
17044         // which in C99 means that the enumerator value is not representable in
17045         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
17046         // permits enumerator values that are representable in some larger
17047         // integral type.
17048         if (!getLangOpts().CPlusPlus && !T.isNull())
17049           Diag(IdLoc, diag::warn_enum_value_overflow);
17050       } else if (!getLangOpts().CPlusPlus &&
17051                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17052         // Enforce C99 6.7.2.2p2 even when we compute the next value.
17053         Diag(IdLoc, diag::ext_enum_value_not_int)
17054           << EnumVal.toString(10) << 1;
17055       }
17056     }
17057   }
17058 
17059   if (!EltTy->isDependentType()) {
17060     // Make the enumerator value match the signedness and size of the
17061     // enumerator's type.
17062     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
17063     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17064   }
17065 
17066   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
17067                                   Val, EnumVal);
17068 }
17069 
17070 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
17071                                                 SourceLocation IILoc) {
17072   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
17073       !getLangOpts().CPlusPlus)
17074     return SkipBodyInfo();
17075 
17076   // We have an anonymous enum definition. Look up the first enumerator to
17077   // determine if we should merge the definition with an existing one and
17078   // skip the body.
17079   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
17080                                          forRedeclarationInCurContext());
17081   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
17082   if (!PrevECD)
17083     return SkipBodyInfo();
17084 
17085   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
17086   NamedDecl *Hidden;
17087   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
17088     SkipBodyInfo Skip;
17089     Skip.Previous = Hidden;
17090     return Skip;
17091   }
17092 
17093   return SkipBodyInfo();
17094 }
17095 
17096 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
17097                               SourceLocation IdLoc, IdentifierInfo *Id,
17098                               const ParsedAttributesView &Attrs,
17099                               SourceLocation EqualLoc, Expr *Val) {
17100   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
17101   EnumConstantDecl *LastEnumConst =
17102     cast_or_null<EnumConstantDecl>(lastEnumConst);
17103 
17104   // The scope passed in may not be a decl scope.  Zip up the scope tree until
17105   // we find one that is.
17106   S = getNonFieldDeclScope(S);
17107 
17108   // Verify that there isn't already something declared with this name in this
17109   // scope.
17110   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
17111   LookupName(R, S);
17112   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
17113 
17114   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17115     // Maybe we will complain about the shadowed template parameter.
17116     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
17117     // Just pretend that we didn't see the previous declaration.
17118     PrevDecl = nullptr;
17119   }
17120 
17121   // C++ [class.mem]p15:
17122   // If T is the name of a class, then each of the following shall have a name
17123   // different from T:
17124   // - every enumerator of every member of class T that is an unscoped
17125   // enumerated type
17126   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
17127     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
17128                             DeclarationNameInfo(Id, IdLoc));
17129 
17130   EnumConstantDecl *New =
17131     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
17132   if (!New)
17133     return nullptr;
17134 
17135   if (PrevDecl) {
17136     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
17137       // Check for other kinds of shadowing not already handled.
17138       CheckShadow(New, PrevDecl, R);
17139     }
17140 
17141     // When in C++, we may get a TagDecl with the same name; in this case the
17142     // enum constant will 'hide' the tag.
17143     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
17144            "Received TagDecl when not in C++!");
17145     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
17146       if (isa<EnumConstantDecl>(PrevDecl))
17147         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
17148       else
17149         Diag(IdLoc, diag::err_redefinition) << Id;
17150       notePreviousDefinition(PrevDecl, IdLoc);
17151       return nullptr;
17152     }
17153   }
17154 
17155   // Process attributes.
17156   ProcessDeclAttributeList(S, New, Attrs);
17157   AddPragmaAttributes(S, New);
17158 
17159   // Register this decl in the current scope stack.
17160   New->setAccess(TheEnumDecl->getAccess());
17161   PushOnScopeChains(New, S);
17162 
17163   ActOnDocumentableDecl(New);
17164 
17165   return New;
17166 }
17167 
17168 // Returns true when the enum initial expression does not trigger the
17169 // duplicate enum warning.  A few common cases are exempted as follows:
17170 // Element2 = Element1
17171 // Element2 = Element1 + 1
17172 // Element2 = Element1 - 1
17173 // Where Element2 and Element1 are from the same enum.
17174 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
17175   Expr *InitExpr = ECD->getInitExpr();
17176   if (!InitExpr)
17177     return true;
17178   InitExpr = InitExpr->IgnoreImpCasts();
17179 
17180   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
17181     if (!BO->isAdditiveOp())
17182       return true;
17183     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
17184     if (!IL)
17185       return true;
17186     if (IL->getValue() != 1)
17187       return true;
17188 
17189     InitExpr = BO->getLHS();
17190   }
17191 
17192   // This checks if the elements are from the same enum.
17193   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
17194   if (!DRE)
17195     return true;
17196 
17197   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
17198   if (!EnumConstant)
17199     return true;
17200 
17201   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
17202       Enum)
17203     return true;
17204 
17205   return false;
17206 }
17207 
17208 // Emits a warning when an element is implicitly set a value that
17209 // a previous element has already been set to.
17210 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
17211                                         EnumDecl *Enum, QualType EnumType) {
17212   // Avoid anonymous enums
17213   if (!Enum->getIdentifier())
17214     return;
17215 
17216   // Only check for small enums.
17217   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
17218     return;
17219 
17220   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
17221     return;
17222 
17223   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
17224   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
17225 
17226   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
17227   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
17228 
17229   // Use int64_t as a key to avoid needing special handling for DenseMap keys.
17230   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
17231     llvm::APSInt Val = D->getInitVal();
17232     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
17233   };
17234 
17235   DuplicatesVector DupVector;
17236   ValueToVectorMap EnumMap;
17237 
17238   // Populate the EnumMap with all values represented by enum constants without
17239   // an initializer.
17240   for (auto *Element : Elements) {
17241     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
17242 
17243     // Null EnumConstantDecl means a previous diagnostic has been emitted for
17244     // this constant.  Skip this enum since it may be ill-formed.
17245     if (!ECD) {
17246       return;
17247     }
17248 
17249     // Constants with initalizers are handled in the next loop.
17250     if (ECD->getInitExpr())
17251       continue;
17252 
17253     // Duplicate values are handled in the next loop.
17254     EnumMap.insert({EnumConstantToKey(ECD), ECD});
17255   }
17256 
17257   if (EnumMap.size() == 0)
17258     return;
17259 
17260   // Create vectors for any values that has duplicates.
17261   for (auto *Element : Elements) {
17262     // The last loop returned if any constant was null.
17263     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
17264     if (!ValidDuplicateEnum(ECD, Enum))
17265       continue;
17266 
17267     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
17268     if (Iter == EnumMap.end())
17269       continue;
17270 
17271     DeclOrVector& Entry = Iter->second;
17272     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
17273       // Ensure constants are different.
17274       if (D == ECD)
17275         continue;
17276 
17277       // Create new vector and push values onto it.
17278       auto Vec = std::make_unique<ECDVector>();
17279       Vec->push_back(D);
17280       Vec->push_back(ECD);
17281 
17282       // Update entry to point to the duplicates vector.
17283       Entry = Vec.get();
17284 
17285       // Store the vector somewhere we can consult later for quick emission of
17286       // diagnostics.
17287       DupVector.emplace_back(std::move(Vec));
17288       continue;
17289     }
17290 
17291     ECDVector *Vec = Entry.get<ECDVector*>();
17292     // Make sure constants are not added more than once.
17293     if (*Vec->begin() == ECD)
17294       continue;
17295 
17296     Vec->push_back(ECD);
17297   }
17298 
17299   // Emit diagnostics.
17300   for (const auto &Vec : DupVector) {
17301     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
17302 
17303     // Emit warning for one enum constant.
17304     auto *FirstECD = Vec->front();
17305     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
17306       << FirstECD << FirstECD->getInitVal().toString(10)
17307       << FirstECD->getSourceRange();
17308 
17309     // Emit one note for each of the remaining enum constants with
17310     // the same value.
17311     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
17312       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
17313         << ECD << ECD->getInitVal().toString(10)
17314         << ECD->getSourceRange();
17315   }
17316 }
17317 
17318 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
17319                              bool AllowMask) const {
17320   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
17321   assert(ED->isCompleteDefinition() && "expected enum definition");
17322 
17323   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
17324   llvm::APInt &FlagBits = R.first->second;
17325 
17326   if (R.second) {
17327     for (auto *E : ED->enumerators()) {
17328       const auto &EVal = E->getInitVal();
17329       // Only single-bit enumerators introduce new flag values.
17330       if (EVal.isPowerOf2())
17331         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
17332     }
17333   }
17334 
17335   // A value is in a flag enum if either its bits are a subset of the enum's
17336   // flag bits (the first condition) or we are allowing masks and the same is
17337   // true of its complement (the second condition). When masks are allowed, we
17338   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
17339   //
17340   // While it's true that any value could be used as a mask, the assumption is
17341   // that a mask will have all of the insignificant bits set. Anything else is
17342   // likely a logic error.
17343   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
17344   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
17345 }
17346 
17347 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
17348                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
17349                          const ParsedAttributesView &Attrs) {
17350   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
17351   QualType EnumType = Context.getTypeDeclType(Enum);
17352 
17353   ProcessDeclAttributeList(S, Enum, Attrs);
17354 
17355   if (Enum->isDependentType()) {
17356     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17357       EnumConstantDecl *ECD =
17358         cast_or_null<EnumConstantDecl>(Elements[i]);
17359       if (!ECD) continue;
17360 
17361       ECD->setType(EnumType);
17362     }
17363 
17364     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
17365     return;
17366   }
17367 
17368   // TODO: If the result value doesn't fit in an int, it must be a long or long
17369   // long value.  ISO C does not support this, but GCC does as an extension,
17370   // emit a warning.
17371   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17372   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
17373   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
17374 
17375   // Verify that all the values are okay, compute the size of the values, and
17376   // reverse the list.
17377   unsigned NumNegativeBits = 0;
17378   unsigned NumPositiveBits = 0;
17379 
17380   // Keep track of whether all elements have type int.
17381   bool AllElementsInt = true;
17382 
17383   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17384     EnumConstantDecl *ECD =
17385       cast_or_null<EnumConstantDecl>(Elements[i]);
17386     if (!ECD) continue;  // Already issued a diagnostic.
17387 
17388     const llvm::APSInt &InitVal = ECD->getInitVal();
17389 
17390     // Keep track of the size of positive and negative values.
17391     if (InitVal.isUnsigned() || InitVal.isNonNegative())
17392       NumPositiveBits = std::max(NumPositiveBits,
17393                                  (unsigned)InitVal.getActiveBits());
17394     else
17395       NumNegativeBits = std::max(NumNegativeBits,
17396                                  (unsigned)InitVal.getMinSignedBits());
17397 
17398     // Keep track of whether every enum element has type int (very common).
17399     if (AllElementsInt)
17400       AllElementsInt = ECD->getType() == Context.IntTy;
17401   }
17402 
17403   // Figure out the type that should be used for this enum.
17404   QualType BestType;
17405   unsigned BestWidth;
17406 
17407   // C++0x N3000 [conv.prom]p3:
17408   //   An rvalue of an unscoped enumeration type whose underlying
17409   //   type is not fixed can be converted to an rvalue of the first
17410   //   of the following types that can represent all the values of
17411   //   the enumeration: int, unsigned int, long int, unsigned long
17412   //   int, long long int, or unsigned long long int.
17413   // C99 6.4.4.3p2:
17414   //   An identifier declared as an enumeration constant has type int.
17415   // The C99 rule is modified by a gcc extension
17416   QualType BestPromotionType;
17417 
17418   bool Packed = Enum->hasAttr<PackedAttr>();
17419   // -fshort-enums is the equivalent to specifying the packed attribute on all
17420   // enum definitions.
17421   if (LangOpts.ShortEnums)
17422     Packed = true;
17423 
17424   // If the enum already has a type because it is fixed or dictated by the
17425   // target, promote that type instead of analyzing the enumerators.
17426   if (Enum->isComplete()) {
17427     BestType = Enum->getIntegerType();
17428     if (BestType->isPromotableIntegerType())
17429       BestPromotionType = Context.getPromotedIntegerType(BestType);
17430     else
17431       BestPromotionType = BestType;
17432 
17433     BestWidth = Context.getIntWidth(BestType);
17434   }
17435   else if (NumNegativeBits) {
17436     // If there is a negative value, figure out the smallest integer type (of
17437     // int/long/longlong) that fits.
17438     // If it's packed, check also if it fits a char or a short.
17439     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
17440       BestType = Context.SignedCharTy;
17441       BestWidth = CharWidth;
17442     } else if (Packed && NumNegativeBits <= ShortWidth &&
17443                NumPositiveBits < ShortWidth) {
17444       BestType = Context.ShortTy;
17445       BestWidth = ShortWidth;
17446     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
17447       BestType = Context.IntTy;
17448       BestWidth = IntWidth;
17449     } else {
17450       BestWidth = Context.getTargetInfo().getLongWidth();
17451 
17452       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
17453         BestType = Context.LongTy;
17454       } else {
17455         BestWidth = Context.getTargetInfo().getLongLongWidth();
17456 
17457         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
17458           Diag(Enum->getLocation(), diag::ext_enum_too_large);
17459         BestType = Context.LongLongTy;
17460       }
17461     }
17462     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
17463   } else {
17464     // If there is no negative value, figure out the smallest type that fits
17465     // all of the enumerator values.
17466     // If it's packed, check also if it fits a char or a short.
17467     if (Packed && NumPositiveBits <= CharWidth) {
17468       BestType = Context.UnsignedCharTy;
17469       BestPromotionType = Context.IntTy;
17470       BestWidth = CharWidth;
17471     } else if (Packed && NumPositiveBits <= ShortWidth) {
17472       BestType = Context.UnsignedShortTy;
17473       BestPromotionType = Context.IntTy;
17474       BestWidth = ShortWidth;
17475     } else if (NumPositiveBits <= IntWidth) {
17476       BestType = Context.UnsignedIntTy;
17477       BestWidth = IntWidth;
17478       BestPromotionType
17479         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17480                            ? Context.UnsignedIntTy : Context.IntTy;
17481     } else if (NumPositiveBits <=
17482                (BestWidth = Context.getTargetInfo().getLongWidth())) {
17483       BestType = Context.UnsignedLongTy;
17484       BestPromotionType
17485         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17486                            ? Context.UnsignedLongTy : Context.LongTy;
17487     } else {
17488       BestWidth = Context.getTargetInfo().getLongLongWidth();
17489       assert(NumPositiveBits <= BestWidth &&
17490              "How could an initializer get larger than ULL?");
17491       BestType = Context.UnsignedLongLongTy;
17492       BestPromotionType
17493         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17494                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
17495     }
17496   }
17497 
17498   // Loop over all of the enumerator constants, changing their types to match
17499   // the type of the enum if needed.
17500   for (auto *D : Elements) {
17501     auto *ECD = cast_or_null<EnumConstantDecl>(D);
17502     if (!ECD) continue;  // Already issued a diagnostic.
17503 
17504     // Standard C says the enumerators have int type, but we allow, as an
17505     // extension, the enumerators to be larger than int size.  If each
17506     // enumerator value fits in an int, type it as an int, otherwise type it the
17507     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
17508     // that X has type 'int', not 'unsigned'.
17509 
17510     // Determine whether the value fits into an int.
17511     llvm::APSInt InitVal = ECD->getInitVal();
17512 
17513     // If it fits into an integer type, force it.  Otherwise force it to match
17514     // the enum decl type.
17515     QualType NewTy;
17516     unsigned NewWidth;
17517     bool NewSign;
17518     if (!getLangOpts().CPlusPlus &&
17519         !Enum->isFixed() &&
17520         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
17521       NewTy = Context.IntTy;
17522       NewWidth = IntWidth;
17523       NewSign = true;
17524     } else if (ECD->getType() == BestType) {
17525       // Already the right type!
17526       if (getLangOpts().CPlusPlus)
17527         // C++ [dcl.enum]p4: Following the closing brace of an
17528         // enum-specifier, each enumerator has the type of its
17529         // enumeration.
17530         ECD->setType(EnumType);
17531       continue;
17532     } else {
17533       NewTy = BestType;
17534       NewWidth = BestWidth;
17535       NewSign = BestType->isSignedIntegerOrEnumerationType();
17536     }
17537 
17538     // Adjust the APSInt value.
17539     InitVal = InitVal.extOrTrunc(NewWidth);
17540     InitVal.setIsSigned(NewSign);
17541     ECD->setInitVal(InitVal);
17542 
17543     // Adjust the Expr initializer and type.
17544     if (ECD->getInitExpr() &&
17545         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
17546       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
17547                                                 CK_IntegralCast,
17548                                                 ECD->getInitExpr(),
17549                                                 /*base paths*/ nullptr,
17550                                                 VK_RValue));
17551     if (getLangOpts().CPlusPlus)
17552       // C++ [dcl.enum]p4: Following the closing brace of an
17553       // enum-specifier, each enumerator has the type of its
17554       // enumeration.
17555       ECD->setType(EnumType);
17556     else
17557       ECD->setType(NewTy);
17558   }
17559 
17560   Enum->completeDefinition(BestType, BestPromotionType,
17561                            NumPositiveBits, NumNegativeBits);
17562 
17563   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
17564 
17565   if (Enum->isClosedFlag()) {
17566     for (Decl *D : Elements) {
17567       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
17568       if (!ECD) continue;  // Already issued a diagnostic.
17569 
17570       llvm::APSInt InitVal = ECD->getInitVal();
17571       if (InitVal != 0 && !InitVal.isPowerOf2() &&
17572           !IsValueInFlagEnum(Enum, InitVal, true))
17573         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
17574           << ECD << Enum;
17575     }
17576   }
17577 
17578   // Now that the enum type is defined, ensure it's not been underaligned.
17579   if (Enum->hasAttrs())
17580     CheckAlignasUnderalignment(Enum);
17581 }
17582 
17583 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
17584                                   SourceLocation StartLoc,
17585                                   SourceLocation EndLoc) {
17586   StringLiteral *AsmString = cast<StringLiteral>(expr);
17587 
17588   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
17589                                                    AsmString, StartLoc,
17590                                                    EndLoc);
17591   CurContext->addDecl(New);
17592   return New;
17593 }
17594 
17595 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
17596                                       IdentifierInfo* AliasName,
17597                                       SourceLocation PragmaLoc,
17598                                       SourceLocation NameLoc,
17599                                       SourceLocation AliasNameLoc) {
17600   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
17601                                          LookupOrdinaryName);
17602   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
17603                            AttributeCommonInfo::AS_Pragma);
17604   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
17605       Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
17606 
17607   // If a declaration that:
17608   // 1) declares a function or a variable
17609   // 2) has external linkage
17610   // already exists, add a label attribute to it.
17611   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17612     if (isDeclExternC(PrevDecl))
17613       PrevDecl->addAttr(Attr);
17614     else
17615       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
17616           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
17617   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
17618   } else
17619     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
17620 }
17621 
17622 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
17623                              SourceLocation PragmaLoc,
17624                              SourceLocation NameLoc) {
17625   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
17626 
17627   if (PrevDecl) {
17628     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
17629   } else {
17630     (void)WeakUndeclaredIdentifiers.insert(
17631       std::pair<IdentifierInfo*,WeakInfo>
17632         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
17633   }
17634 }
17635 
17636 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
17637                                 IdentifierInfo* AliasName,
17638                                 SourceLocation PragmaLoc,
17639                                 SourceLocation NameLoc,
17640                                 SourceLocation AliasNameLoc) {
17641   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
17642                                     LookupOrdinaryName);
17643   WeakInfo W = WeakInfo(Name, NameLoc);
17644 
17645   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17646     if (!PrevDecl->hasAttr<AliasAttr>())
17647       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
17648         DeclApplyPragmaWeak(TUScope, ND, W);
17649   } else {
17650     (void)WeakUndeclaredIdentifiers.insert(
17651       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
17652   }
17653 }
17654 
17655 Decl *Sema::getObjCDeclContext() const {
17656   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
17657 }
17658 
17659 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD) {
17660   // Templates are emitted when they're instantiated.
17661   if (FD->isDependentContext())
17662     return FunctionEmissionStatus::TemplateDiscarded;
17663 
17664   FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown;
17665   if (LangOpts.OpenMPIsDevice) {
17666     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
17667         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
17668     if (DevTy.hasValue()) {
17669       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
17670         OMPES = FunctionEmissionStatus::OMPDiscarded;
17671       else if (DeviceKnownEmittedFns.count(FD) > 0)
17672         OMPES = FunctionEmissionStatus::Emitted;
17673     }
17674   } else if (LangOpts.OpenMP) {
17675     // In OpenMP 4.5 all the functions are host functions.
17676     if (LangOpts.OpenMP <= 45) {
17677       OMPES = FunctionEmissionStatus::Emitted;
17678     } else {
17679       Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
17680           OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
17681       // In OpenMP 5.0 or above, DevTy may be changed later by
17682       // #pragma omp declare target to(*) device_type(*). Therefore DevTy
17683       // having no value does not imply host. The emission status will be
17684       // checked again at the end of compilation unit.
17685       if (DevTy.hasValue()) {
17686         if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
17687           OMPES = FunctionEmissionStatus::OMPDiscarded;
17688         } else if (DeviceKnownEmittedFns.count(FD) > 0) {
17689           OMPES = FunctionEmissionStatus::Emitted;
17690         }
17691       }
17692     }
17693   }
17694   if (OMPES == FunctionEmissionStatus::OMPDiscarded ||
17695       (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA))
17696     return OMPES;
17697 
17698   if (LangOpts.CUDA) {
17699     // When compiling for device, host functions are never emitted.  Similarly,
17700     // when compiling for host, device and global functions are never emitted.
17701     // (Technically, we do emit a host-side stub for global functions, but this
17702     // doesn't count for our purposes here.)
17703     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
17704     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
17705       return FunctionEmissionStatus::CUDADiscarded;
17706     if (!LangOpts.CUDAIsDevice &&
17707         (T == Sema::CFT_Device || T == Sema::CFT_Global))
17708       return FunctionEmissionStatus::CUDADiscarded;
17709 
17710     // Check whether this function is externally visible -- if so, it's
17711     // known-emitted.
17712     //
17713     // We have to check the GVA linkage of the function's *definition* -- if we
17714     // only have a declaration, we don't know whether or not the function will
17715     // be emitted, because (say) the definition could include "inline".
17716     FunctionDecl *Def = FD->getDefinition();
17717 
17718     if (Def &&
17719         !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def))
17720         && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted))
17721       return FunctionEmissionStatus::Emitted;
17722   }
17723 
17724   // Otherwise, the function is known-emitted if it's in our set of
17725   // known-emitted functions.
17726   return (DeviceKnownEmittedFns.count(FD) > 0)
17727              ? FunctionEmissionStatus::Emitted
17728              : FunctionEmissionStatus::Unknown;
17729 }
17730 
17731 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
17732   // Host-side references to a __global__ function refer to the stub, so the
17733   // function itself is never emitted and therefore should not be marked.
17734   // If we have host fn calls kernel fn calls host+device, the HD function
17735   // does not get instantiated on the host. We model this by omitting at the
17736   // call to the kernel from the callgraph. This ensures that, when compiling
17737   // for host, only HD functions actually called from the host get marked as
17738   // known-emitted.
17739   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
17740          IdentifyCUDATarget(Callee) == CFT_Global;
17741 }
17742