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   if (SS.isInvalid())
871     return NameClassification::Error();
872 
873   // For unqualified lookup in a class template in MSVC mode, look into
874   // dependent base classes where the primary class template is known.
875   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
876     if (ParsedType TypeInBase =
877             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
878       return TypeInBase;
879   }
880 
881   // Perform lookup for Objective-C instance variables (including automatically
882   // synthesized instance variables), if we're in an Objective-C method.
883   // FIXME: This lookup really, really needs to be folded in to the normal
884   // unqualified lookup mechanism.
885   if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
886     DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
887     if (Ivar.isInvalid())
888       return NameClassification::Error();
889     if (Ivar.isUsable())
890       return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
891 
892     // We defer builtin creation until after ivar lookup inside ObjC methods.
893     if (Result.empty())
894       LookupBuiltin(Result);
895   }
896 
897   bool SecondTry = false;
898   bool IsFilteredTemplateName = false;
899 
900 Corrected:
901   switch (Result.getResultKind()) {
902   case LookupResult::NotFound:
903     // If an unqualified-id is followed by a '(', then we have a function
904     // call.
905     if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
906       // In C++, this is an ADL-only call.
907       // FIXME: Reference?
908       if (getLangOpts().CPlusPlus)
909         return NameClassification::UndeclaredNonType();
910 
911       // C90 6.3.2.2:
912       //   If the expression that precedes the parenthesized argument list in a
913       //   function call consists solely of an identifier, and if no
914       //   declaration is visible for this identifier, the identifier is
915       //   implicitly declared exactly as if, in the innermost block containing
916       //   the function call, the declaration
917       //
918       //     extern int identifier ();
919       //
920       //   appeared.
921       //
922       // We also allow this in C99 as an extension.
923       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
924         return NameClassification::NonType(D);
925     }
926 
927     if (getLangOpts().CPlusPlus2a && SS.isEmpty() && NextToken.is(tok::less)) {
928       // In C++20 onwards, this could be an ADL-only call to a function
929       // template, and we're required to assume that this is a template name.
930       //
931       // FIXME: Find a way to still do typo correction in this case.
932       TemplateName Template =
933           Context.getAssumedTemplateName(NameInfo.getName());
934       return NameClassification::UndeclaredTemplate(Template);
935     }
936 
937     // In C, we first see whether there is a tag type by the same name, in
938     // which case it's likely that the user just forgot to write "enum",
939     // "struct", or "union".
940     if (!getLangOpts().CPlusPlus && !SecondTry &&
941         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
942       break;
943     }
944 
945     // Perform typo correction to determine if there is another name that is
946     // close to this name.
947     if (!SecondTry && CCC) {
948       SecondTry = true;
949       if (TypoCorrection Corrected =
950               CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
951                           &SS, *CCC, CTK_ErrorRecovery)) {
952         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
953         unsigned QualifiedDiag = diag::err_no_member_suggest;
954 
955         NamedDecl *FirstDecl = Corrected.getFoundDecl();
956         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
957         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
958             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
959           UnqualifiedDiag = diag::err_no_template_suggest;
960           QualifiedDiag = diag::err_no_member_template_suggest;
961         } else if (UnderlyingFirstDecl &&
962                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
963                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
964                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
965           UnqualifiedDiag = diag::err_unknown_typename_suggest;
966           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
967         }
968 
969         if (SS.isEmpty()) {
970           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
971         } else {// FIXME: is this even reachable? Test it.
972           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
973           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
974                                   Name->getName().equals(CorrectedStr);
975           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
976                                     << Name << computeDeclContext(SS, false)
977                                     << DroppedSpecifier << SS.getRange());
978         }
979 
980         // Update the name, so that the caller has the new name.
981         Name = Corrected.getCorrectionAsIdentifierInfo();
982 
983         // Typo correction corrected to a keyword.
984         if (Corrected.isKeyword())
985           return Name;
986 
987         // Also update the LookupResult...
988         // FIXME: This should probably go away at some point
989         Result.clear();
990         Result.setLookupName(Corrected.getCorrection());
991         if (FirstDecl)
992           Result.addDecl(FirstDecl);
993 
994         // If we found an Objective-C instance variable, let
995         // LookupInObjCMethod build the appropriate expression to
996         // reference the ivar.
997         // FIXME: This is a gross hack.
998         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
999           DeclResult R =
1000               LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1001           if (R.isInvalid())
1002             return NameClassification::Error();
1003           if (R.isUsable())
1004             return NameClassification::NonType(Ivar);
1005         }
1006 
1007         goto Corrected;
1008       }
1009     }
1010 
1011     // We failed to correct; just fall through and let the parser deal with it.
1012     Result.suppressDiagnostics();
1013     return NameClassification::Unknown();
1014 
1015   case LookupResult::NotFoundInCurrentInstantiation: {
1016     // We performed name lookup into the current instantiation, and there were
1017     // dependent bases, so we treat this result the same way as any other
1018     // dependent nested-name-specifier.
1019 
1020     // C++ [temp.res]p2:
1021     //   A name used in a template declaration or definition and that is
1022     //   dependent on a template-parameter is assumed not to name a type
1023     //   unless the applicable name lookup finds a type name or the name is
1024     //   qualified by the keyword typename.
1025     //
1026     // FIXME: If the next token is '<', we might want to ask the parser to
1027     // perform some heroics to see if we actually have a
1028     // template-argument-list, which would indicate a missing 'template'
1029     // keyword here.
1030     return NameClassification::DependentNonType();
1031   }
1032 
1033   case LookupResult::Found:
1034   case LookupResult::FoundOverloaded:
1035   case LookupResult::FoundUnresolvedValue:
1036     break;
1037 
1038   case LookupResult::Ambiguous:
1039     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1040         hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1041                                       /*AllowDependent=*/false)) {
1042       // C++ [temp.local]p3:
1043       //   A lookup that finds an injected-class-name (10.2) can result in an
1044       //   ambiguity in certain cases (for example, if it is found in more than
1045       //   one base class). If all of the injected-class-names that are found
1046       //   refer to specializations of the same class template, and if the name
1047       //   is followed by a template-argument-list, the reference refers to the
1048       //   class template itself and not a specialization thereof, and is not
1049       //   ambiguous.
1050       //
1051       // This filtering can make an ambiguous result into an unambiguous one,
1052       // so try again after filtering out template names.
1053       FilterAcceptableTemplateNames(Result);
1054       if (!Result.isAmbiguous()) {
1055         IsFilteredTemplateName = true;
1056         break;
1057       }
1058     }
1059 
1060     // Diagnose the ambiguity and return an error.
1061     return NameClassification::Error();
1062   }
1063 
1064   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1065       (IsFilteredTemplateName ||
1066        hasAnyAcceptableTemplateNames(
1067            Result, /*AllowFunctionTemplates=*/true,
1068            /*AllowDependent=*/false,
1069            /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1070                getLangOpts().CPlusPlus2a))) {
1071     // C++ [temp.names]p3:
1072     //   After name lookup (3.4) finds that a name is a template-name or that
1073     //   an operator-function-id or a literal- operator-id refers to a set of
1074     //   overloaded functions any member of which is a function template if
1075     //   this is followed by a <, the < is always taken as the delimiter of a
1076     //   template-argument-list and never as the less-than operator.
1077     // C++2a [temp.names]p2:
1078     //   A name is also considered to refer to a template if it is an
1079     //   unqualified-id followed by a < and name lookup finds either one
1080     //   or more functions or finds nothing.
1081     if (!IsFilteredTemplateName)
1082       FilterAcceptableTemplateNames(Result);
1083 
1084     bool IsFunctionTemplate;
1085     bool IsVarTemplate;
1086     TemplateName Template;
1087     if (Result.end() - Result.begin() > 1) {
1088       IsFunctionTemplate = true;
1089       Template = Context.getOverloadedTemplateName(Result.begin(),
1090                                                    Result.end());
1091     } else if (!Result.empty()) {
1092       auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1093           *Result.begin(), /*AllowFunctionTemplates=*/true,
1094           /*AllowDependent=*/false));
1095       IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1096       IsVarTemplate = isa<VarTemplateDecl>(TD);
1097 
1098       if (SS.isNotEmpty())
1099         Template =
1100             Context.getQualifiedTemplateName(SS.getScopeRep(),
1101                                              /*TemplateKeyword=*/false, TD);
1102       else
1103         Template = TemplateName(TD);
1104     } else {
1105       // All results were non-template functions. This is a function template
1106       // name.
1107       IsFunctionTemplate = true;
1108       Template = Context.getAssumedTemplateName(NameInfo.getName());
1109     }
1110 
1111     if (IsFunctionTemplate) {
1112       // Function templates always go through overload resolution, at which
1113       // point we'll perform the various checks (e.g., accessibility) we need
1114       // to based on which function we selected.
1115       Result.suppressDiagnostics();
1116 
1117       return NameClassification::FunctionTemplate(Template);
1118     }
1119 
1120     return IsVarTemplate ? NameClassification::VarTemplate(Template)
1121                          : NameClassification::TypeTemplate(Template);
1122   }
1123 
1124   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1125   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1126     DiagnoseUseOfDecl(Type, NameLoc);
1127     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1128     QualType T = Context.getTypeDeclType(Type);
1129     if (SS.isNotEmpty())
1130       return buildNestedType(*this, SS, T, NameLoc);
1131     return ParsedType::make(T);
1132   }
1133 
1134   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1135   if (!Class) {
1136     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1137     if (ObjCCompatibleAliasDecl *Alias =
1138             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1139       Class = Alias->getClassInterface();
1140   }
1141 
1142   if (Class) {
1143     DiagnoseUseOfDecl(Class, NameLoc);
1144 
1145     if (NextToken.is(tok::period)) {
1146       // Interface. <something> is parsed as a property reference expression.
1147       // Just return "unknown" as a fall-through for now.
1148       Result.suppressDiagnostics();
1149       return NameClassification::Unknown();
1150     }
1151 
1152     QualType T = Context.getObjCInterfaceType(Class);
1153     return ParsedType::make(T);
1154   }
1155 
1156   if (isa<ConceptDecl>(FirstDecl))
1157     return NameClassification::Concept(
1158         TemplateName(cast<TemplateDecl>(FirstDecl)));
1159 
1160   // We can have a type template here if we're classifying a template argument.
1161   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1162       !isa<VarTemplateDecl>(FirstDecl))
1163     return NameClassification::TypeTemplate(
1164         TemplateName(cast<TemplateDecl>(FirstDecl)));
1165 
1166   // Check for a tag type hidden by a non-type decl in a few cases where it
1167   // seems likely a type is wanted instead of the non-type that was found.
1168   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1169   if ((NextToken.is(tok::identifier) ||
1170        (NextIsOp &&
1171         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1172       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1173     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1174     DiagnoseUseOfDecl(Type, NameLoc);
1175     QualType T = Context.getTypeDeclType(Type);
1176     if (SS.isNotEmpty())
1177       return buildNestedType(*this, SS, T, NameLoc);
1178     return ParsedType::make(T);
1179   }
1180 
1181   // FIXME: This is context-dependent. We need to defer building the member
1182   // expression until the classification is consumed.
1183   if (FirstDecl->isCXXClassMember())
1184     return NameClassification::ContextIndependentExpr(
1185         BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, nullptr,
1186                                         S));
1187 
1188   // If we already know which single declaration is referenced, just annotate
1189   // that declaration directly.
1190   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1191   if (Result.isSingleResult() && !ADL)
1192     return NameClassification::NonType(Result.getRepresentativeDecl());
1193 
1194   // Build an UnresolvedLookupExpr. Note that this doesn't depend on the
1195   // context in which we performed classification, so it's safe to do now.
1196   return NameClassification::ContextIndependentExpr(
1197       BuildDeclarationNameExpr(SS, Result, ADL));
1198 }
1199 
1200 ExprResult
1201 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1202                                              SourceLocation NameLoc) {
1203   assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1204   CXXScopeSpec SS;
1205   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1206   return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1207 }
1208 
1209 ExprResult
1210 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1211                                             IdentifierInfo *Name,
1212                                             SourceLocation NameLoc,
1213                                             bool IsAddressOfOperand) {
1214   DeclarationNameInfo NameInfo(Name, NameLoc);
1215   return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1216                                     NameInfo, IsAddressOfOperand,
1217                                     /*TemplateArgs=*/nullptr);
1218 }
1219 
1220 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1221                                               NamedDecl *Found,
1222                                               SourceLocation NameLoc,
1223                                               const Token &NextToken) {
1224   if (getCurMethodDecl() && SS.isEmpty())
1225     if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1226       return BuildIvarRefExpr(S, NameLoc, Ivar);
1227 
1228   // Reconstruct the lookup result.
1229   LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1230   Result.addDecl(Found);
1231   Result.resolveKind();
1232 
1233   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1234   return BuildDeclarationNameExpr(SS, Result, ADL);
1235 }
1236 
1237 Sema::TemplateNameKindForDiagnostics
1238 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1239   auto *TD = Name.getAsTemplateDecl();
1240   if (!TD)
1241     return TemplateNameKindForDiagnostics::DependentTemplate;
1242   if (isa<ClassTemplateDecl>(TD))
1243     return TemplateNameKindForDiagnostics::ClassTemplate;
1244   if (isa<FunctionTemplateDecl>(TD))
1245     return TemplateNameKindForDiagnostics::FunctionTemplate;
1246   if (isa<VarTemplateDecl>(TD))
1247     return TemplateNameKindForDiagnostics::VarTemplate;
1248   if (isa<TypeAliasTemplateDecl>(TD))
1249     return TemplateNameKindForDiagnostics::AliasTemplate;
1250   if (isa<TemplateTemplateParmDecl>(TD))
1251     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1252   if (isa<ConceptDecl>(TD))
1253     return TemplateNameKindForDiagnostics::Concept;
1254   return TemplateNameKindForDiagnostics::DependentTemplate;
1255 }
1256 
1257 // Determines the context to return to after temporarily entering a
1258 // context.  This depends in an unnecessarily complicated way on the
1259 // exact ordering of callbacks from the parser.
1260 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1261 
1262   // Functions defined inline within classes aren't parsed until we've
1263   // finished parsing the top-level class, so the top-level class is
1264   // the context we'll need to return to.
1265   // A Lambda call operator whose parent is a class must not be treated
1266   // as an inline member function.  A Lambda can be used legally
1267   // either as an in-class member initializer or a default argument.  These
1268   // are parsed once the class has been marked complete and so the containing
1269   // context would be the nested class (when the lambda is defined in one);
1270   // If the class is not complete, then the lambda is being used in an
1271   // ill-formed fashion (such as to specify the width of a bit-field, or
1272   // in an array-bound) - in which case we still want to return the
1273   // lexically containing DC (which could be a nested class).
1274   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1275     DC = DC->getLexicalParent();
1276 
1277     // A function not defined within a class will always return to its
1278     // lexical context.
1279     if (!isa<CXXRecordDecl>(DC))
1280       return DC;
1281 
1282     // A C++ inline method/friend is parsed *after* the topmost class
1283     // it was declared in is fully parsed ("complete");  the topmost
1284     // class is the context we need to return to.
1285     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1286       DC = RD;
1287 
1288     // Return the declaration context of the topmost class the inline method is
1289     // declared in.
1290     return DC;
1291   }
1292 
1293   return DC->getLexicalParent();
1294 }
1295 
1296 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1297   assert(getContainingDC(DC) == CurContext &&
1298       "The next DeclContext should be lexically contained in the current one.");
1299   CurContext = DC;
1300   S->setEntity(DC);
1301 }
1302 
1303 void Sema::PopDeclContext() {
1304   assert(CurContext && "DeclContext imbalance!");
1305 
1306   CurContext = getContainingDC(CurContext);
1307   assert(CurContext && "Popped translation unit!");
1308 }
1309 
1310 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1311                                                                     Decl *D) {
1312   // Unlike PushDeclContext, the context to which we return is not necessarily
1313   // the containing DC of TD, because the new context will be some pre-existing
1314   // TagDecl definition instead of a fresh one.
1315   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1316   CurContext = cast<TagDecl>(D)->getDefinition();
1317   assert(CurContext && "skipping definition of undefined tag");
1318   // Start lookups from the parent of the current context; we don't want to look
1319   // into the pre-existing complete definition.
1320   S->setEntity(CurContext->getLookupParent());
1321   return Result;
1322 }
1323 
1324 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1325   CurContext = static_cast<decltype(CurContext)>(Context);
1326 }
1327 
1328 /// EnterDeclaratorContext - Used when we must lookup names in the context
1329 /// of a declarator's nested name specifier.
1330 ///
1331 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1332   // C++0x [basic.lookup.unqual]p13:
1333   //   A name used in the definition of a static data member of class
1334   //   X (after the qualified-id of the static member) is looked up as
1335   //   if the name was used in a member function of X.
1336   // C++0x [basic.lookup.unqual]p14:
1337   //   If a variable member of a namespace is defined outside of the
1338   //   scope of its namespace then any name used in the definition of
1339   //   the variable member (after the declarator-id) is looked up as
1340   //   if the definition of the variable member occurred in its
1341   //   namespace.
1342   // Both of these imply that we should push a scope whose context
1343   // is the semantic context of the declaration.  We can't use
1344   // PushDeclContext here because that context is not necessarily
1345   // lexically contained in the current context.  Fortunately,
1346   // the containing scope should have the appropriate information.
1347 
1348   assert(!S->getEntity() && "scope already has entity");
1349 
1350 #ifndef NDEBUG
1351   Scope *Ancestor = S->getParent();
1352   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1353   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1354 #endif
1355 
1356   CurContext = DC;
1357   S->setEntity(DC);
1358 }
1359 
1360 void Sema::ExitDeclaratorContext(Scope *S) {
1361   assert(S->getEntity() == CurContext && "Context imbalance!");
1362 
1363   // Switch back to the lexical context.  The safety of this is
1364   // enforced by an assert in EnterDeclaratorContext.
1365   Scope *Ancestor = S->getParent();
1366   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1367   CurContext = Ancestor->getEntity();
1368 
1369   // We don't need to do anything with the scope, which is going to
1370   // disappear.
1371 }
1372 
1373 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1374   // We assume that the caller has already called
1375   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1376   FunctionDecl *FD = D->getAsFunction();
1377   if (!FD)
1378     return;
1379 
1380   // Same implementation as PushDeclContext, but enters the context
1381   // from the lexical parent, rather than the top-level class.
1382   assert(CurContext == FD->getLexicalParent() &&
1383     "The next DeclContext should be lexically contained in the current one.");
1384   CurContext = FD;
1385   S->setEntity(CurContext);
1386 
1387   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1388     ParmVarDecl *Param = FD->getParamDecl(P);
1389     // If the parameter has an identifier, then add it to the scope
1390     if (Param->getIdentifier()) {
1391       S->AddDecl(Param);
1392       IdResolver.AddDecl(Param);
1393     }
1394   }
1395 }
1396 
1397 void Sema::ActOnExitFunctionContext() {
1398   // Same implementation as PopDeclContext, but returns to the lexical parent,
1399   // rather than the top-level class.
1400   assert(CurContext && "DeclContext imbalance!");
1401   CurContext = CurContext->getLexicalParent();
1402   assert(CurContext && "Popped translation unit!");
1403 }
1404 
1405 /// Determine whether we allow overloading of the function
1406 /// PrevDecl with another declaration.
1407 ///
1408 /// This routine determines whether overloading is possible, not
1409 /// whether some new function is actually an overload. It will return
1410 /// true in C++ (where we can always provide overloads) or, as an
1411 /// extension, in C when the previous function is already an
1412 /// overloaded function declaration or has the "overloadable"
1413 /// attribute.
1414 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1415                                        ASTContext &Context,
1416                                        const FunctionDecl *New) {
1417   if (Context.getLangOpts().CPlusPlus)
1418     return true;
1419 
1420   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1421     return true;
1422 
1423   return Previous.getResultKind() == LookupResult::Found &&
1424          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1425           New->hasAttr<OverloadableAttr>());
1426 }
1427 
1428 /// Add this decl to the scope shadowed decl chains.
1429 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1430   // Move up the scope chain until we find the nearest enclosing
1431   // non-transparent context. The declaration will be introduced into this
1432   // scope.
1433   while (S->getEntity() && S->getEntity()->isTransparentContext())
1434     S = S->getParent();
1435 
1436   // Add scoped declarations into their context, so that they can be
1437   // found later. Declarations without a context won't be inserted
1438   // into any context.
1439   if (AddToContext)
1440     CurContext->addDecl(D);
1441 
1442   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1443   // are function-local declarations.
1444   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1445       !D->getDeclContext()->getRedeclContext()->Equals(
1446         D->getLexicalDeclContext()->getRedeclContext()) &&
1447       !D->getLexicalDeclContext()->isFunctionOrMethod())
1448     return;
1449 
1450   // Template instantiations should also not be pushed into scope.
1451   if (isa<FunctionDecl>(D) &&
1452       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1453     return;
1454 
1455   // If this replaces anything in the current scope,
1456   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1457                                IEnd = IdResolver.end();
1458   for (; I != IEnd; ++I) {
1459     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1460       S->RemoveDecl(*I);
1461       IdResolver.RemoveDecl(*I);
1462 
1463       // Should only need to replace one decl.
1464       break;
1465     }
1466   }
1467 
1468   S->AddDecl(D);
1469 
1470   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1471     // Implicitly-generated labels may end up getting generated in an order that
1472     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1473     // the label at the appropriate place in the identifier chain.
1474     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1475       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1476       if (IDC == CurContext) {
1477         if (!S->isDeclScope(*I))
1478           continue;
1479       } else if (IDC->Encloses(CurContext))
1480         break;
1481     }
1482 
1483     IdResolver.InsertDeclAfter(I, D);
1484   } else {
1485     IdResolver.AddDecl(D);
1486   }
1487 }
1488 
1489 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1490                          bool AllowInlineNamespace) {
1491   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1492 }
1493 
1494 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1495   DeclContext *TargetDC = DC->getPrimaryContext();
1496   do {
1497     if (DeclContext *ScopeDC = S->getEntity())
1498       if (ScopeDC->getPrimaryContext() == TargetDC)
1499         return S;
1500   } while ((S = S->getParent()));
1501 
1502   return nullptr;
1503 }
1504 
1505 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1506                                             DeclContext*,
1507                                             ASTContext&);
1508 
1509 /// Filters out lookup results that don't fall within the given scope
1510 /// as determined by isDeclInScope.
1511 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1512                                 bool ConsiderLinkage,
1513                                 bool AllowInlineNamespace) {
1514   LookupResult::Filter F = R.makeFilter();
1515   while (F.hasNext()) {
1516     NamedDecl *D = F.next();
1517 
1518     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1519       continue;
1520 
1521     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1522       continue;
1523 
1524     F.erase();
1525   }
1526 
1527   F.done();
1528 }
1529 
1530 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1531 /// have compatible owning modules.
1532 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1533   // FIXME: The Modules TS is not clear about how friend declarations are
1534   // to be treated. It's not meaningful to have different owning modules for
1535   // linkage in redeclarations of the same entity, so for now allow the
1536   // redeclaration and change the owning modules to match.
1537   if (New->getFriendObjectKind() &&
1538       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1539     New->setLocalOwningModule(Old->getOwningModule());
1540     makeMergedDefinitionVisible(New);
1541     return false;
1542   }
1543 
1544   Module *NewM = New->getOwningModule();
1545   Module *OldM = Old->getOwningModule();
1546 
1547   if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1548     NewM = NewM->Parent;
1549   if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1550     OldM = OldM->Parent;
1551 
1552   if (NewM == OldM)
1553     return false;
1554 
1555   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1556   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1557   if (NewIsModuleInterface || OldIsModuleInterface) {
1558     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1559     //   if a declaration of D [...] appears in the purview of a module, all
1560     //   other such declarations shall appear in the purview of the same module
1561     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1562       << New
1563       << NewIsModuleInterface
1564       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1565       << OldIsModuleInterface
1566       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1567     Diag(Old->getLocation(), diag::note_previous_declaration);
1568     New->setInvalidDecl();
1569     return true;
1570   }
1571 
1572   return false;
1573 }
1574 
1575 static bool isUsingDecl(NamedDecl *D) {
1576   return isa<UsingShadowDecl>(D) ||
1577          isa<UnresolvedUsingTypenameDecl>(D) ||
1578          isa<UnresolvedUsingValueDecl>(D);
1579 }
1580 
1581 /// Removes using shadow declarations from the lookup results.
1582 static void RemoveUsingDecls(LookupResult &R) {
1583   LookupResult::Filter F = R.makeFilter();
1584   while (F.hasNext())
1585     if (isUsingDecl(F.next()))
1586       F.erase();
1587 
1588   F.done();
1589 }
1590 
1591 /// Check for this common pattern:
1592 /// @code
1593 /// class S {
1594 ///   S(const S&); // DO NOT IMPLEMENT
1595 ///   void operator=(const S&); // DO NOT IMPLEMENT
1596 /// };
1597 /// @endcode
1598 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1599   // FIXME: Should check for private access too but access is set after we get
1600   // the decl here.
1601   if (D->doesThisDeclarationHaveABody())
1602     return false;
1603 
1604   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1605     return CD->isCopyConstructor();
1606   return D->isCopyAssignmentOperator();
1607 }
1608 
1609 // We need this to handle
1610 //
1611 // typedef struct {
1612 //   void *foo() { return 0; }
1613 // } A;
1614 //
1615 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1616 // for example. If 'A', foo will have external linkage. If we have '*A',
1617 // foo will have no linkage. Since we can't know until we get to the end
1618 // of the typedef, this function finds out if D might have non-external linkage.
1619 // Callers should verify at the end of the TU if it D has external linkage or
1620 // not.
1621 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1622   const DeclContext *DC = D->getDeclContext();
1623   while (!DC->isTranslationUnit()) {
1624     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1625       if (!RD->hasNameForLinkage())
1626         return true;
1627     }
1628     DC = DC->getParent();
1629   }
1630 
1631   return !D->isExternallyVisible();
1632 }
1633 
1634 // FIXME: This needs to be refactored; some other isInMainFile users want
1635 // these semantics.
1636 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1637   if (S.TUKind != TU_Complete)
1638     return false;
1639   return S.SourceMgr.isInMainFile(Loc);
1640 }
1641 
1642 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1643   assert(D);
1644 
1645   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1646     return false;
1647 
1648   // Ignore all entities declared within templates, and out-of-line definitions
1649   // of members of class templates.
1650   if (D->getDeclContext()->isDependentContext() ||
1651       D->getLexicalDeclContext()->isDependentContext())
1652     return false;
1653 
1654   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1655     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1656       return false;
1657     // A non-out-of-line declaration of a member specialization was implicitly
1658     // instantiated; it's the out-of-line declaration that we're interested in.
1659     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1660         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1661       return false;
1662 
1663     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1664       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1665         return false;
1666     } else {
1667       // 'static inline' functions are defined in headers; don't warn.
1668       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1669         return false;
1670     }
1671 
1672     if (FD->doesThisDeclarationHaveABody() &&
1673         Context.DeclMustBeEmitted(FD))
1674       return false;
1675   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1676     // Constants and utility variables are defined in headers with internal
1677     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1678     // like "inline".)
1679     if (!isMainFileLoc(*this, VD->getLocation()))
1680       return false;
1681 
1682     if (Context.DeclMustBeEmitted(VD))
1683       return false;
1684 
1685     if (VD->isStaticDataMember() &&
1686         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1687       return false;
1688     if (VD->isStaticDataMember() &&
1689         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1690         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1691       return false;
1692 
1693     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1694       return false;
1695   } else {
1696     return false;
1697   }
1698 
1699   // Only warn for unused decls internal to the translation unit.
1700   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1701   // for inline functions defined in the main source file, for instance.
1702   return mightHaveNonExternalLinkage(D);
1703 }
1704 
1705 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1706   if (!D)
1707     return;
1708 
1709   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1710     const FunctionDecl *First = FD->getFirstDecl();
1711     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1712       return; // First should already be in the vector.
1713   }
1714 
1715   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1716     const VarDecl *First = VD->getFirstDecl();
1717     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1718       return; // First should already be in the vector.
1719   }
1720 
1721   if (ShouldWarnIfUnusedFileScopedDecl(D))
1722     UnusedFileScopedDecls.push_back(D);
1723 }
1724 
1725 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1726   if (D->isInvalidDecl())
1727     return false;
1728 
1729   bool Referenced = false;
1730   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1731     // For a decomposition declaration, warn if none of the bindings are
1732     // referenced, instead of if the variable itself is referenced (which
1733     // it is, by the bindings' expressions).
1734     for (auto *BD : DD->bindings()) {
1735       if (BD->isReferenced()) {
1736         Referenced = true;
1737         break;
1738       }
1739     }
1740   } else if (!D->getDeclName()) {
1741     return false;
1742   } else if (D->isReferenced() || D->isUsed()) {
1743     Referenced = true;
1744   }
1745 
1746   if (Referenced || D->hasAttr<UnusedAttr>() ||
1747       D->hasAttr<ObjCPreciseLifetimeAttr>())
1748     return false;
1749 
1750   if (isa<LabelDecl>(D))
1751     return true;
1752 
1753   // Except for labels, we only care about unused decls that are local to
1754   // functions.
1755   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1756   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1757     // For dependent types, the diagnostic is deferred.
1758     WithinFunction =
1759         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1760   if (!WithinFunction)
1761     return false;
1762 
1763   if (isa<TypedefNameDecl>(D))
1764     return true;
1765 
1766   // White-list anything that isn't a local variable.
1767   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1768     return false;
1769 
1770   // Types of valid local variables should be complete, so this should succeed.
1771   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1772 
1773     // White-list anything with an __attribute__((unused)) type.
1774     const auto *Ty = VD->getType().getTypePtr();
1775 
1776     // Only look at the outermost level of typedef.
1777     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1778       if (TT->getDecl()->hasAttr<UnusedAttr>())
1779         return false;
1780     }
1781 
1782     // If we failed to complete the type for some reason, or if the type is
1783     // dependent, don't diagnose the variable.
1784     if (Ty->isIncompleteType() || Ty->isDependentType())
1785       return false;
1786 
1787     // Look at the element type to ensure that the warning behaviour is
1788     // consistent for both scalars and arrays.
1789     Ty = Ty->getBaseElementTypeUnsafe();
1790 
1791     if (const TagType *TT = Ty->getAs<TagType>()) {
1792       const TagDecl *Tag = TT->getDecl();
1793       if (Tag->hasAttr<UnusedAttr>())
1794         return false;
1795 
1796       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1797         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1798           return false;
1799 
1800         if (const Expr *Init = VD->getInit()) {
1801           if (const ExprWithCleanups *Cleanups =
1802                   dyn_cast<ExprWithCleanups>(Init))
1803             Init = Cleanups->getSubExpr();
1804           const CXXConstructExpr *Construct =
1805             dyn_cast<CXXConstructExpr>(Init);
1806           if (Construct && !Construct->isElidable()) {
1807             CXXConstructorDecl *CD = Construct->getConstructor();
1808             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1809                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1810               return false;
1811           }
1812 
1813           // Suppress the warning if we don't know how this is constructed, and
1814           // it could possibly be non-trivial constructor.
1815           if (Init->isTypeDependent())
1816             for (const CXXConstructorDecl *Ctor : RD->ctors())
1817               if (!Ctor->isTrivial())
1818                 return false;
1819         }
1820       }
1821     }
1822 
1823     // TODO: __attribute__((unused)) templates?
1824   }
1825 
1826   return true;
1827 }
1828 
1829 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1830                                      FixItHint &Hint) {
1831   if (isa<LabelDecl>(D)) {
1832     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1833         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1834         true);
1835     if (AfterColon.isInvalid())
1836       return;
1837     Hint = FixItHint::CreateRemoval(
1838         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1839   }
1840 }
1841 
1842 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1843   if (D->getTypeForDecl()->isDependentType())
1844     return;
1845 
1846   for (auto *TmpD : D->decls()) {
1847     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1848       DiagnoseUnusedDecl(T);
1849     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1850       DiagnoseUnusedNestedTypedefs(R);
1851   }
1852 }
1853 
1854 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1855 /// unless they are marked attr(unused).
1856 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1857   if (!ShouldDiagnoseUnusedDecl(D))
1858     return;
1859 
1860   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1861     // typedefs can be referenced later on, so the diagnostics are emitted
1862     // at end-of-translation-unit.
1863     UnusedLocalTypedefNameCandidates.insert(TD);
1864     return;
1865   }
1866 
1867   FixItHint Hint;
1868   GenerateFixForUnusedDecl(D, Context, Hint);
1869 
1870   unsigned DiagID;
1871   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1872     DiagID = diag::warn_unused_exception_param;
1873   else if (isa<LabelDecl>(D))
1874     DiagID = diag::warn_unused_label;
1875   else
1876     DiagID = diag::warn_unused_variable;
1877 
1878   Diag(D->getLocation(), DiagID) << D << Hint;
1879 }
1880 
1881 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1882   // Verify that we have no forward references left.  If so, there was a goto
1883   // or address of a label taken, but no definition of it.  Label fwd
1884   // definitions are indicated with a null substmt which is also not a resolved
1885   // MS inline assembly label name.
1886   bool Diagnose = false;
1887   if (L->isMSAsmLabel())
1888     Diagnose = !L->isResolvedMSAsmLabel();
1889   else
1890     Diagnose = L->getStmt() == nullptr;
1891   if (Diagnose)
1892     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1893 }
1894 
1895 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1896   S->mergeNRVOIntoParent();
1897 
1898   if (S->decl_empty()) return;
1899   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1900          "Scope shouldn't contain decls!");
1901 
1902   for (auto *TmpD : S->decls()) {
1903     assert(TmpD && "This decl didn't get pushed??");
1904 
1905     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1906     NamedDecl *D = cast<NamedDecl>(TmpD);
1907 
1908     // Diagnose unused variables in this scope.
1909     if (!S->hasUnrecoverableErrorOccurred()) {
1910       DiagnoseUnusedDecl(D);
1911       if (const auto *RD = dyn_cast<RecordDecl>(D))
1912         DiagnoseUnusedNestedTypedefs(RD);
1913     }
1914 
1915     if (!D->getDeclName()) continue;
1916 
1917     // If this was a forward reference to a label, verify it was defined.
1918     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1919       CheckPoppedLabel(LD, *this);
1920 
1921     // Remove this name from our lexical scope, and warn on it if we haven't
1922     // already.
1923     IdResolver.RemoveDecl(D);
1924     auto ShadowI = ShadowingDecls.find(D);
1925     if (ShadowI != ShadowingDecls.end()) {
1926       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1927         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1928             << D << FD << FD->getParent();
1929         Diag(FD->getLocation(), diag::note_previous_declaration);
1930       }
1931       ShadowingDecls.erase(ShadowI);
1932     }
1933   }
1934 }
1935 
1936 /// Look for an Objective-C class in the translation unit.
1937 ///
1938 /// \param Id The name of the Objective-C class we're looking for. If
1939 /// typo-correction fixes this name, the Id will be updated
1940 /// to the fixed name.
1941 ///
1942 /// \param IdLoc The location of the name in the translation unit.
1943 ///
1944 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1945 /// if there is no class with the given name.
1946 ///
1947 /// \returns The declaration of the named Objective-C class, or NULL if the
1948 /// class could not be found.
1949 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1950                                               SourceLocation IdLoc,
1951                                               bool DoTypoCorrection) {
1952   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1953   // creation from this context.
1954   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1955 
1956   if (!IDecl && DoTypoCorrection) {
1957     // Perform typo correction at the given location, but only if we
1958     // find an Objective-C class name.
1959     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
1960     if (TypoCorrection C =
1961             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
1962                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
1963       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1964       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1965       Id = IDecl->getIdentifier();
1966     }
1967   }
1968   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1969   // This routine must always return a class definition, if any.
1970   if (Def && Def->getDefinition())
1971       Def = Def->getDefinition();
1972   return Def;
1973 }
1974 
1975 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1976 /// from S, where a non-field would be declared. This routine copes
1977 /// with the difference between C and C++ scoping rules in structs and
1978 /// unions. For example, the following code is well-formed in C but
1979 /// ill-formed in C++:
1980 /// @code
1981 /// struct S6 {
1982 ///   enum { BAR } e;
1983 /// };
1984 ///
1985 /// void test_S6() {
1986 ///   struct S6 a;
1987 ///   a.e = BAR;
1988 /// }
1989 /// @endcode
1990 /// For the declaration of BAR, this routine will return a different
1991 /// scope. The scope S will be the scope of the unnamed enumeration
1992 /// within S6. In C++, this routine will return the scope associated
1993 /// with S6, because the enumeration's scope is a transparent
1994 /// context but structures can contain non-field names. In C, this
1995 /// routine will return the translation unit scope, since the
1996 /// enumeration's scope is a transparent context and structures cannot
1997 /// contain non-field names.
1998 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1999   while (((S->getFlags() & Scope::DeclScope) == 0) ||
2000          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2001          (S->isClassScope() && !getLangOpts().CPlusPlus))
2002     S = S->getParent();
2003   return S;
2004 }
2005 
2006 /// Looks up the declaration of "struct objc_super" and
2007 /// saves it for later use in building builtin declaration of
2008 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
2009 /// pre-existing declaration exists no action takes place.
2010 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
2011                                         IdentifierInfo *II) {
2012   if (!II->isStr("objc_msgSendSuper"))
2013     return;
2014   ASTContext &Context = ThisSema.Context;
2015 
2016   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
2017                       SourceLocation(), Sema::LookupTagName);
2018   ThisSema.LookupName(Result, S);
2019   if (Result.getResultKind() == LookupResult::Found)
2020     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
2021       Context.setObjCSuperType(Context.getTagDeclType(TD));
2022 }
2023 
2024 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2025                                ASTContext::GetBuiltinTypeError Error) {
2026   switch (Error) {
2027   case ASTContext::GE_None:
2028     return "";
2029   case ASTContext::GE_Missing_type:
2030     return BuiltinInfo.getHeaderName(ID);
2031   case ASTContext::GE_Missing_stdio:
2032     return "stdio.h";
2033   case ASTContext::GE_Missing_setjmp:
2034     return "setjmp.h";
2035   case ASTContext::GE_Missing_ucontext:
2036     return "ucontext.h";
2037   }
2038   llvm_unreachable("unhandled error kind");
2039 }
2040 
2041 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2042 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2043 /// if we're creating this built-in in anticipation of redeclaring the
2044 /// built-in.
2045 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2046                                      Scope *S, bool ForRedeclaration,
2047                                      SourceLocation Loc) {
2048   LookupPredefedObjCSuperType(*this, S, II);
2049 
2050   ASTContext::GetBuiltinTypeError Error;
2051   QualType R = Context.GetBuiltinType(ID, Error);
2052   if (Error) {
2053     if (!ForRedeclaration)
2054       return nullptr;
2055 
2056     // If we have a builtin without an associated type we should not emit a
2057     // warning when we were not able to find a type for it.
2058     if (Error == ASTContext::GE_Missing_type)
2059       return nullptr;
2060 
2061     // If we could not find a type for setjmp it is because the jmp_buf type was
2062     // not defined prior to the setjmp declaration.
2063     if (Error == ASTContext::GE_Missing_setjmp) {
2064       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2065           << Context.BuiltinInfo.getName(ID);
2066       return nullptr;
2067     }
2068 
2069     // Generally, we emit a warning that the declaration requires the
2070     // appropriate header.
2071     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2072         << getHeaderName(Context.BuiltinInfo, ID, Error)
2073         << Context.BuiltinInfo.getName(ID);
2074     return nullptr;
2075   }
2076 
2077   if (!ForRedeclaration &&
2078       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2079        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2080     Diag(Loc, diag::ext_implicit_lib_function_decl)
2081         << Context.BuiltinInfo.getName(ID) << R;
2082     if (Context.BuiltinInfo.getHeaderName(ID) &&
2083         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
2084       Diag(Loc, diag::note_include_header_or_declare)
2085           << Context.BuiltinInfo.getHeaderName(ID)
2086           << Context.BuiltinInfo.getName(ID);
2087   }
2088 
2089   if (R.isNull())
2090     return nullptr;
2091 
2092   DeclContext *Parent = Context.getTranslationUnitDecl();
2093   if (getLangOpts().CPlusPlus) {
2094     LinkageSpecDecl *CLinkageDecl =
2095         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
2096                                 LinkageSpecDecl::lang_c, false);
2097     CLinkageDecl->setImplicit();
2098     Parent->addDecl(CLinkageDecl);
2099     Parent = CLinkageDecl;
2100   }
2101 
2102   FunctionDecl *New = FunctionDecl::Create(Context,
2103                                            Parent,
2104                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
2105                                            SC_Extern,
2106                                            false,
2107                                            R->isFunctionProtoType());
2108   New->setImplicit();
2109 
2110   // Create Decl objects for each parameter, adding them to the
2111   // FunctionDecl.
2112   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
2113     SmallVector<ParmVarDecl*, 16> Params;
2114     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2115       ParmVarDecl *parm =
2116           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2117                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2118                               SC_None, nullptr);
2119       parm->setScopeInfo(0, i);
2120       Params.push_back(parm);
2121     }
2122     New->setParams(Params);
2123   }
2124 
2125   AddKnownFunctionAttributes(New);
2126   RegisterLocallyScopedExternCDecl(New, S);
2127 
2128   // TUScope is the translation-unit scope to insert this function into.
2129   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2130   // relate Scopes to DeclContexts, and probably eliminate CurContext
2131   // entirely, but we're not there yet.
2132   DeclContext *SavedContext = CurContext;
2133   CurContext = Parent;
2134   PushOnScopeChains(New, TUScope);
2135   CurContext = SavedContext;
2136   return New;
2137 }
2138 
2139 /// Typedef declarations don't have linkage, but they still denote the same
2140 /// entity if their types are the same.
2141 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2142 /// isSameEntity.
2143 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2144                                                      TypedefNameDecl *Decl,
2145                                                      LookupResult &Previous) {
2146   // This is only interesting when modules are enabled.
2147   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2148     return;
2149 
2150   // Empty sets are uninteresting.
2151   if (Previous.empty())
2152     return;
2153 
2154   LookupResult::Filter Filter = Previous.makeFilter();
2155   while (Filter.hasNext()) {
2156     NamedDecl *Old = Filter.next();
2157 
2158     // Non-hidden declarations are never ignored.
2159     if (S.isVisible(Old))
2160       continue;
2161 
2162     // Declarations of the same entity are not ignored, even if they have
2163     // different linkages.
2164     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2165       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2166                                 Decl->getUnderlyingType()))
2167         continue;
2168 
2169       // If both declarations give a tag declaration a typedef name for linkage
2170       // purposes, then they declare the same entity.
2171       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2172           Decl->getAnonDeclWithTypedefName())
2173         continue;
2174     }
2175 
2176     Filter.erase();
2177   }
2178 
2179   Filter.done();
2180 }
2181 
2182 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2183   QualType OldType;
2184   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2185     OldType = OldTypedef->getUnderlyingType();
2186   else
2187     OldType = Context.getTypeDeclType(Old);
2188   QualType NewType = New->getUnderlyingType();
2189 
2190   if (NewType->isVariablyModifiedType()) {
2191     // Must not redefine a typedef with a variably-modified type.
2192     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2193     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2194       << Kind << NewType;
2195     if (Old->getLocation().isValid())
2196       notePreviousDefinition(Old, New->getLocation());
2197     New->setInvalidDecl();
2198     return true;
2199   }
2200 
2201   if (OldType != NewType &&
2202       !OldType->isDependentType() &&
2203       !NewType->isDependentType() &&
2204       !Context.hasSameType(OldType, NewType)) {
2205     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2206     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2207       << Kind << NewType << OldType;
2208     if (Old->getLocation().isValid())
2209       notePreviousDefinition(Old, New->getLocation());
2210     New->setInvalidDecl();
2211     return true;
2212   }
2213   return false;
2214 }
2215 
2216 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2217 /// same name and scope as a previous declaration 'Old'.  Figure out
2218 /// how to resolve this situation, merging decls or emitting
2219 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2220 ///
2221 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2222                                 LookupResult &OldDecls) {
2223   // If the new decl is known invalid already, don't bother doing any
2224   // merging checks.
2225   if (New->isInvalidDecl()) return;
2226 
2227   // Allow multiple definitions for ObjC built-in typedefs.
2228   // FIXME: Verify the underlying types are equivalent!
2229   if (getLangOpts().ObjC) {
2230     const IdentifierInfo *TypeID = New->getIdentifier();
2231     switch (TypeID->getLength()) {
2232     default: break;
2233     case 2:
2234       {
2235         if (!TypeID->isStr("id"))
2236           break;
2237         QualType T = New->getUnderlyingType();
2238         if (!T->isPointerType())
2239           break;
2240         if (!T->isVoidPointerType()) {
2241           QualType PT = T->castAs<PointerType>()->getPointeeType();
2242           if (!PT->isStructureType())
2243             break;
2244         }
2245         Context.setObjCIdRedefinitionType(T);
2246         // Install the built-in type for 'id', ignoring the current definition.
2247         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2248         return;
2249       }
2250     case 5:
2251       if (!TypeID->isStr("Class"))
2252         break;
2253       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2254       // Install the built-in type for 'Class', ignoring the current definition.
2255       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2256       return;
2257     case 3:
2258       if (!TypeID->isStr("SEL"))
2259         break;
2260       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2261       // Install the built-in type for 'SEL', ignoring the current definition.
2262       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2263       return;
2264     }
2265     // Fall through - the typedef name was not a builtin type.
2266   }
2267 
2268   // Verify the old decl was also a type.
2269   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2270   if (!Old) {
2271     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2272       << New->getDeclName();
2273 
2274     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2275     if (OldD->getLocation().isValid())
2276       notePreviousDefinition(OldD, New->getLocation());
2277 
2278     return New->setInvalidDecl();
2279   }
2280 
2281   // If the old declaration is invalid, just give up here.
2282   if (Old->isInvalidDecl())
2283     return New->setInvalidDecl();
2284 
2285   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2286     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2287     auto *NewTag = New->getAnonDeclWithTypedefName();
2288     NamedDecl *Hidden = nullptr;
2289     if (OldTag && NewTag &&
2290         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2291         !hasVisibleDefinition(OldTag, &Hidden)) {
2292       // There is a definition of this tag, but it is not visible. Use it
2293       // instead of our tag.
2294       New->setTypeForDecl(OldTD->getTypeForDecl());
2295       if (OldTD->isModed())
2296         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2297                                     OldTD->getUnderlyingType());
2298       else
2299         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2300 
2301       // Make the old tag definition visible.
2302       makeMergedDefinitionVisible(Hidden);
2303 
2304       // If this was an unscoped enumeration, yank all of its enumerators
2305       // out of the scope.
2306       if (isa<EnumDecl>(NewTag)) {
2307         Scope *EnumScope = getNonFieldDeclScope(S);
2308         for (auto *D : NewTag->decls()) {
2309           auto *ED = cast<EnumConstantDecl>(D);
2310           assert(EnumScope->isDeclScope(ED));
2311           EnumScope->RemoveDecl(ED);
2312           IdResolver.RemoveDecl(ED);
2313           ED->getLexicalDeclContext()->removeDecl(ED);
2314         }
2315       }
2316     }
2317   }
2318 
2319   // If the typedef types are not identical, reject them in all languages and
2320   // with any extensions enabled.
2321   if (isIncompatibleTypedef(Old, New))
2322     return;
2323 
2324   // The types match.  Link up the redeclaration chain and merge attributes if
2325   // the old declaration was a typedef.
2326   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2327     New->setPreviousDecl(Typedef);
2328     mergeDeclAttributes(New, Old);
2329   }
2330 
2331   if (getLangOpts().MicrosoftExt)
2332     return;
2333 
2334   if (getLangOpts().CPlusPlus) {
2335     // C++ [dcl.typedef]p2:
2336     //   In a given non-class scope, a typedef specifier can be used to
2337     //   redefine the name of any type declared in that scope to refer
2338     //   to the type to which it already refers.
2339     if (!isa<CXXRecordDecl>(CurContext))
2340       return;
2341 
2342     // C++0x [dcl.typedef]p4:
2343     //   In a given class scope, a typedef specifier can be used to redefine
2344     //   any class-name declared in that scope that is not also a typedef-name
2345     //   to refer to the type to which it already refers.
2346     //
2347     // This wording came in via DR424, which was a correction to the
2348     // wording in DR56, which accidentally banned code like:
2349     //
2350     //   struct S {
2351     //     typedef struct A { } A;
2352     //   };
2353     //
2354     // in the C++03 standard. We implement the C++0x semantics, which
2355     // allow the above but disallow
2356     //
2357     //   struct S {
2358     //     typedef int I;
2359     //     typedef int I;
2360     //   };
2361     //
2362     // since that was the intent of DR56.
2363     if (!isa<TypedefNameDecl>(Old))
2364       return;
2365 
2366     Diag(New->getLocation(), diag::err_redefinition)
2367       << New->getDeclName();
2368     notePreviousDefinition(Old, New->getLocation());
2369     return New->setInvalidDecl();
2370   }
2371 
2372   // Modules always permit redefinition of typedefs, as does C11.
2373   if (getLangOpts().Modules || getLangOpts().C11)
2374     return;
2375 
2376   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2377   // is normally mapped to an error, but can be controlled with
2378   // -Wtypedef-redefinition.  If either the original or the redefinition is
2379   // in a system header, don't emit this for compatibility with GCC.
2380   if (getDiagnostics().getSuppressSystemWarnings() &&
2381       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2382       (Old->isImplicit() ||
2383        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2384        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2385     return;
2386 
2387   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2388     << New->getDeclName();
2389   notePreviousDefinition(Old, New->getLocation());
2390 }
2391 
2392 /// DeclhasAttr - returns true if decl Declaration already has the target
2393 /// attribute.
2394 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2395   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2396   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2397   for (const auto *i : D->attrs())
2398     if (i->getKind() == A->getKind()) {
2399       if (Ann) {
2400         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2401           return true;
2402         continue;
2403       }
2404       // FIXME: Don't hardcode this check
2405       if (OA && isa<OwnershipAttr>(i))
2406         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2407       return true;
2408     }
2409 
2410   return false;
2411 }
2412 
2413 static bool isAttributeTargetADefinition(Decl *D) {
2414   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2415     return VD->isThisDeclarationADefinition();
2416   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2417     return TD->isCompleteDefinition() || TD->isBeingDefined();
2418   return true;
2419 }
2420 
2421 /// Merge alignment attributes from \p Old to \p New, taking into account the
2422 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2423 ///
2424 /// \return \c true if any attributes were added to \p New.
2425 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2426   // Look for alignas attributes on Old, and pick out whichever attribute
2427   // specifies the strictest alignment requirement.
2428   AlignedAttr *OldAlignasAttr = nullptr;
2429   AlignedAttr *OldStrictestAlignAttr = nullptr;
2430   unsigned OldAlign = 0;
2431   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2432     // FIXME: We have no way of representing inherited dependent alignments
2433     // in a case like:
2434     //   template<int A, int B> struct alignas(A) X;
2435     //   template<int A, int B> struct alignas(B) X {};
2436     // For now, we just ignore any alignas attributes which are not on the
2437     // definition in such a case.
2438     if (I->isAlignmentDependent())
2439       return false;
2440 
2441     if (I->isAlignas())
2442       OldAlignasAttr = I;
2443 
2444     unsigned Align = I->getAlignment(S.Context);
2445     if (Align > OldAlign) {
2446       OldAlign = Align;
2447       OldStrictestAlignAttr = I;
2448     }
2449   }
2450 
2451   // Look for alignas attributes on New.
2452   AlignedAttr *NewAlignasAttr = nullptr;
2453   unsigned NewAlign = 0;
2454   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2455     if (I->isAlignmentDependent())
2456       return false;
2457 
2458     if (I->isAlignas())
2459       NewAlignasAttr = I;
2460 
2461     unsigned Align = I->getAlignment(S.Context);
2462     if (Align > NewAlign)
2463       NewAlign = Align;
2464   }
2465 
2466   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2467     // Both declarations have 'alignas' attributes. We require them to match.
2468     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2469     // fall short. (If two declarations both have alignas, they must both match
2470     // every definition, and so must match each other if there is a definition.)
2471 
2472     // If either declaration only contains 'alignas(0)' specifiers, then it
2473     // specifies the natural alignment for the type.
2474     if (OldAlign == 0 || NewAlign == 0) {
2475       QualType Ty;
2476       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2477         Ty = VD->getType();
2478       else
2479         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2480 
2481       if (OldAlign == 0)
2482         OldAlign = S.Context.getTypeAlign(Ty);
2483       if (NewAlign == 0)
2484         NewAlign = S.Context.getTypeAlign(Ty);
2485     }
2486 
2487     if (OldAlign != NewAlign) {
2488       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2489         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2490         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2491       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2492     }
2493   }
2494 
2495   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2496     // C++11 [dcl.align]p6:
2497     //   if any declaration of an entity has an alignment-specifier,
2498     //   every defining declaration of that entity shall specify an
2499     //   equivalent alignment.
2500     // C11 6.7.5/7:
2501     //   If the definition of an object does not have an alignment
2502     //   specifier, any other declaration of that object shall also
2503     //   have no alignment specifier.
2504     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2505       << OldAlignasAttr;
2506     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2507       << OldAlignasAttr;
2508   }
2509 
2510   bool AnyAdded = false;
2511 
2512   // Ensure we have an attribute representing the strictest alignment.
2513   if (OldAlign > NewAlign) {
2514     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2515     Clone->setInherited(true);
2516     New->addAttr(Clone);
2517     AnyAdded = true;
2518   }
2519 
2520   // Ensure we have an alignas attribute if the old declaration had one.
2521   if (OldAlignasAttr && !NewAlignasAttr &&
2522       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2523     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2524     Clone->setInherited(true);
2525     New->addAttr(Clone);
2526     AnyAdded = true;
2527   }
2528 
2529   return AnyAdded;
2530 }
2531 
2532 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2533                                const InheritableAttr *Attr,
2534                                Sema::AvailabilityMergeKind AMK) {
2535   // This function copies an attribute Attr from a previous declaration to the
2536   // new declaration D if the new declaration doesn't itself have that attribute
2537   // yet or if that attribute allows duplicates.
2538   // If you're adding a new attribute that requires logic different from
2539   // "use explicit attribute on decl if present, else use attribute from
2540   // previous decl", for example if the attribute needs to be consistent
2541   // between redeclarations, you need to call a custom merge function here.
2542   InheritableAttr *NewAttr = nullptr;
2543   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2544     NewAttr = S.mergeAvailabilityAttr(
2545         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2546         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2547         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2548         AA->getPriority());
2549   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2550     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2551   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2552     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2553   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2554     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2555   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2556     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2557   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2558     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2559                                 FA->getFirstArg());
2560   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2561     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2562   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2563     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2564   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2565     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2566                                        IA->getInheritanceModel());
2567   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2568     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2569                                       &S.Context.Idents.get(AA->getSpelling()));
2570   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2571            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2572             isa<CUDAGlobalAttr>(Attr))) {
2573     // CUDA target attributes are part of function signature for
2574     // overloading purposes and must not be merged.
2575     return false;
2576   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2577     NewAttr = S.mergeMinSizeAttr(D, *MA);
2578   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2579     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2580   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2581     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2582   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2583     NewAttr = S.mergeCommonAttr(D, *CommonA);
2584   else if (isa<AlignedAttr>(Attr))
2585     // AlignedAttrs are handled separately, because we need to handle all
2586     // such attributes on a declaration at the same time.
2587     NewAttr = nullptr;
2588   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2589            (AMK == Sema::AMK_Override ||
2590             AMK == Sema::AMK_ProtocolImplementation))
2591     NewAttr = nullptr;
2592   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2593     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid());
2594   else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
2595     NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
2596   else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
2597     NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
2598   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2599     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2600 
2601   if (NewAttr) {
2602     NewAttr->setInherited(true);
2603     D->addAttr(NewAttr);
2604     if (isa<MSInheritanceAttr>(NewAttr))
2605       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2606     return true;
2607   }
2608 
2609   return false;
2610 }
2611 
2612 static const NamedDecl *getDefinition(const Decl *D) {
2613   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2614     return TD->getDefinition();
2615   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2616     const VarDecl *Def = VD->getDefinition();
2617     if (Def)
2618       return Def;
2619     return VD->getActingDefinition();
2620   }
2621   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2622     return FD->getDefinition();
2623   return nullptr;
2624 }
2625 
2626 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2627   for (const auto *Attribute : D->attrs())
2628     if (Attribute->getKind() == Kind)
2629       return true;
2630   return false;
2631 }
2632 
2633 /// checkNewAttributesAfterDef - If we already have a definition, check that
2634 /// there are no new attributes in this declaration.
2635 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2636   if (!New->hasAttrs())
2637     return;
2638 
2639   const NamedDecl *Def = getDefinition(Old);
2640   if (!Def || Def == New)
2641     return;
2642 
2643   AttrVec &NewAttributes = New->getAttrs();
2644   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2645     const Attr *NewAttribute = NewAttributes[I];
2646 
2647     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2648       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2649         Sema::SkipBodyInfo SkipBody;
2650         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2651 
2652         // If we're skipping this definition, drop the "alias" attribute.
2653         if (SkipBody.ShouldSkip) {
2654           NewAttributes.erase(NewAttributes.begin() + I);
2655           --E;
2656           continue;
2657         }
2658       } else {
2659         VarDecl *VD = cast<VarDecl>(New);
2660         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2661                                 VarDecl::TentativeDefinition
2662                             ? diag::err_alias_after_tentative
2663                             : diag::err_redefinition;
2664         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2665         if (Diag == diag::err_redefinition)
2666           S.notePreviousDefinition(Def, VD->getLocation());
2667         else
2668           S.Diag(Def->getLocation(), diag::note_previous_definition);
2669         VD->setInvalidDecl();
2670       }
2671       ++I;
2672       continue;
2673     }
2674 
2675     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2676       // Tentative definitions are only interesting for the alias check above.
2677       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2678         ++I;
2679         continue;
2680       }
2681     }
2682 
2683     if (hasAttribute(Def, NewAttribute->getKind())) {
2684       ++I;
2685       continue; // regular attr merging will take care of validating this.
2686     }
2687 
2688     if (isa<C11NoReturnAttr>(NewAttribute)) {
2689       // C's _Noreturn is allowed to be added to a function after it is defined.
2690       ++I;
2691       continue;
2692     } else if (isa<UuidAttr>(NewAttribute)) {
2693       // msvc will allow a subsequent definition to add an uuid to a class
2694       ++I;
2695       continue;
2696     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2697       if (AA->isAlignas()) {
2698         // C++11 [dcl.align]p6:
2699         //   if any declaration of an entity has an alignment-specifier,
2700         //   every defining declaration of that entity shall specify an
2701         //   equivalent alignment.
2702         // C11 6.7.5/7:
2703         //   If the definition of an object does not have an alignment
2704         //   specifier, any other declaration of that object shall also
2705         //   have no alignment specifier.
2706         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2707           << AA;
2708         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2709           << AA;
2710         NewAttributes.erase(NewAttributes.begin() + I);
2711         --E;
2712         continue;
2713       }
2714     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2715                cast<VarDecl>(New)->isInline() &&
2716                !cast<VarDecl>(New)->isInlineSpecified()) {
2717       // Don't warn about applying selectany to implicitly inline variables.
2718       // Older compilers and language modes would require the use of selectany
2719       // to make such variables inline, and it would have no effect if we
2720       // honored it.
2721       ++I;
2722       continue;
2723     }
2724 
2725     S.Diag(NewAttribute->getLocation(),
2726            diag::warn_attribute_precede_definition);
2727     S.Diag(Def->getLocation(), diag::note_previous_definition);
2728     NewAttributes.erase(NewAttributes.begin() + I);
2729     --E;
2730   }
2731 }
2732 
2733 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2734                                      const ConstInitAttr *CIAttr,
2735                                      bool AttrBeforeInit) {
2736   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2737 
2738   // Figure out a good way to write this specifier on the old declaration.
2739   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2740   // enough of the attribute list spelling information to extract that without
2741   // heroics.
2742   std::string SuitableSpelling;
2743   if (S.getLangOpts().CPlusPlus2a)
2744     SuitableSpelling = std::string(
2745         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2746   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2747     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2748         InsertLoc, {tok::l_square, tok::l_square,
2749                     S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2750                     S.PP.getIdentifierInfo("require_constant_initialization"),
2751                     tok::r_square, tok::r_square}));
2752   if (SuitableSpelling.empty())
2753     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2754         InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2755                     S.PP.getIdentifierInfo("require_constant_initialization"),
2756                     tok::r_paren, tok::r_paren}));
2757   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus2a)
2758     SuitableSpelling = "constinit";
2759   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2760     SuitableSpelling = "[[clang::require_constant_initialization]]";
2761   if (SuitableSpelling.empty())
2762     SuitableSpelling = "__attribute__((require_constant_initialization))";
2763   SuitableSpelling += " ";
2764 
2765   if (AttrBeforeInit) {
2766     // extern constinit int a;
2767     // int a = 0; // error (missing 'constinit'), accepted as extension
2768     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
2769     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2770         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2771     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2772   } else {
2773     // int a = 0;
2774     // constinit extern int a; // error (missing 'constinit')
2775     S.Diag(CIAttr->getLocation(),
2776            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2777                                  : diag::warn_require_const_init_added_too_late)
2778         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2779     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2780         << CIAttr->isConstinit()
2781         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2782   }
2783 }
2784 
2785 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2786 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2787                                AvailabilityMergeKind AMK) {
2788   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2789     UsedAttr *NewAttr = OldAttr->clone(Context);
2790     NewAttr->setInherited(true);
2791     New->addAttr(NewAttr);
2792   }
2793 
2794   if (!Old->hasAttrs() && !New->hasAttrs())
2795     return;
2796 
2797   // [dcl.constinit]p1:
2798   //   If the [constinit] specifier is applied to any declaration of a
2799   //   variable, it shall be applied to the initializing declaration.
2800   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2801   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2802   if (bool(OldConstInit) != bool(NewConstInit)) {
2803     const auto *OldVD = cast<VarDecl>(Old);
2804     auto *NewVD = cast<VarDecl>(New);
2805 
2806     // Find the initializing declaration. Note that we might not have linked
2807     // the new declaration into the redeclaration chain yet.
2808     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2809     if (!InitDecl &&
2810         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2811       InitDecl = NewVD;
2812 
2813     if (InitDecl == NewVD) {
2814       // This is the initializing declaration. If it would inherit 'constinit',
2815       // that's ill-formed. (Note that we do not apply this to the attribute
2816       // form).
2817       if (OldConstInit && OldConstInit->isConstinit())
2818         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2819                                  /*AttrBeforeInit=*/true);
2820     } else if (NewConstInit) {
2821       // This is the first time we've been told that this declaration should
2822       // have a constant initializer. If we already saw the initializing
2823       // declaration, this is too late.
2824       if (InitDecl && InitDecl != NewVD) {
2825         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2826                                  /*AttrBeforeInit=*/false);
2827         NewVD->dropAttr<ConstInitAttr>();
2828       }
2829     }
2830   }
2831 
2832   // Attributes declared post-definition are currently ignored.
2833   checkNewAttributesAfterDef(*this, New, Old);
2834 
2835   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2836     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2837       if (!OldA->isEquivalent(NewA)) {
2838         // This redeclaration changes __asm__ label.
2839         Diag(New->getLocation(), diag::err_different_asm_label);
2840         Diag(OldA->getLocation(), diag::note_previous_declaration);
2841       }
2842     } else if (Old->isUsed()) {
2843       // This redeclaration adds an __asm__ label to a declaration that has
2844       // already been ODR-used.
2845       Diag(New->getLocation(), diag::err_late_asm_label_name)
2846         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2847     }
2848   }
2849 
2850   // Re-declaration cannot add abi_tag's.
2851   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2852     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2853       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2854         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2855                       NewTag) == OldAbiTagAttr->tags_end()) {
2856           Diag(NewAbiTagAttr->getLocation(),
2857                diag::err_new_abi_tag_on_redeclaration)
2858               << NewTag;
2859           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2860         }
2861       }
2862     } else {
2863       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2864       Diag(Old->getLocation(), diag::note_previous_declaration);
2865     }
2866   }
2867 
2868   // This redeclaration adds a section attribute.
2869   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2870     if (auto *VD = dyn_cast<VarDecl>(New)) {
2871       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2872         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2873         Diag(Old->getLocation(), diag::note_previous_declaration);
2874       }
2875     }
2876   }
2877 
2878   // Redeclaration adds code-seg attribute.
2879   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2880   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2881       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2882     Diag(New->getLocation(), diag::warn_mismatched_section)
2883          << 0 /*codeseg*/;
2884     Diag(Old->getLocation(), diag::note_previous_declaration);
2885   }
2886 
2887   if (!Old->hasAttrs())
2888     return;
2889 
2890   bool foundAny = New->hasAttrs();
2891 
2892   // Ensure that any moving of objects within the allocated map is done before
2893   // we process them.
2894   if (!foundAny) New->setAttrs(AttrVec());
2895 
2896   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2897     // Ignore deprecated/unavailable/availability attributes if requested.
2898     AvailabilityMergeKind LocalAMK = AMK_None;
2899     if (isa<DeprecatedAttr>(I) ||
2900         isa<UnavailableAttr>(I) ||
2901         isa<AvailabilityAttr>(I)) {
2902       switch (AMK) {
2903       case AMK_None:
2904         continue;
2905 
2906       case AMK_Redeclaration:
2907       case AMK_Override:
2908       case AMK_ProtocolImplementation:
2909         LocalAMK = AMK;
2910         break;
2911       }
2912     }
2913 
2914     // Already handled.
2915     if (isa<UsedAttr>(I))
2916       continue;
2917 
2918     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2919       foundAny = true;
2920   }
2921 
2922   if (mergeAlignedAttrs(*this, New, Old))
2923     foundAny = true;
2924 
2925   if (!foundAny) New->dropAttrs();
2926 }
2927 
2928 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2929 /// to the new one.
2930 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2931                                      const ParmVarDecl *oldDecl,
2932                                      Sema &S) {
2933   // C++11 [dcl.attr.depend]p2:
2934   //   The first declaration of a function shall specify the
2935   //   carries_dependency attribute for its declarator-id if any declaration
2936   //   of the function specifies the carries_dependency attribute.
2937   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2938   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2939     S.Diag(CDA->getLocation(),
2940            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2941     // Find the first declaration of the parameter.
2942     // FIXME: Should we build redeclaration chains for function parameters?
2943     const FunctionDecl *FirstFD =
2944       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2945     const ParmVarDecl *FirstVD =
2946       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2947     S.Diag(FirstVD->getLocation(),
2948            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2949   }
2950 
2951   if (!oldDecl->hasAttrs())
2952     return;
2953 
2954   bool foundAny = newDecl->hasAttrs();
2955 
2956   // Ensure that any moving of objects within the allocated map is
2957   // done before we process them.
2958   if (!foundAny) newDecl->setAttrs(AttrVec());
2959 
2960   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2961     if (!DeclHasAttr(newDecl, I)) {
2962       InheritableAttr *newAttr =
2963         cast<InheritableParamAttr>(I->clone(S.Context));
2964       newAttr->setInherited(true);
2965       newDecl->addAttr(newAttr);
2966       foundAny = true;
2967     }
2968   }
2969 
2970   if (!foundAny) newDecl->dropAttrs();
2971 }
2972 
2973 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2974                                 const ParmVarDecl *OldParam,
2975                                 Sema &S) {
2976   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2977     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2978       if (*Oldnullability != *Newnullability) {
2979         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2980           << DiagNullabilityKind(
2981                *Newnullability,
2982                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2983                 != 0))
2984           << DiagNullabilityKind(
2985                *Oldnullability,
2986                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2987                 != 0));
2988         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2989       }
2990     } else {
2991       QualType NewT = NewParam->getType();
2992       NewT = S.Context.getAttributedType(
2993                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2994                          NewT, NewT);
2995       NewParam->setType(NewT);
2996     }
2997   }
2998 }
2999 
3000 namespace {
3001 
3002 /// Used in MergeFunctionDecl to keep track of function parameters in
3003 /// C.
3004 struct GNUCompatibleParamWarning {
3005   ParmVarDecl *OldParm;
3006   ParmVarDecl *NewParm;
3007   QualType PromotedType;
3008 };
3009 
3010 } // end anonymous namespace
3011 
3012 // Determine whether the previous declaration was a definition, implicit
3013 // declaration, or a declaration.
3014 template <typename T>
3015 static std::pair<diag::kind, SourceLocation>
3016 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3017   diag::kind PrevDiag;
3018   SourceLocation OldLocation = Old->getLocation();
3019   if (Old->isThisDeclarationADefinition())
3020     PrevDiag = diag::note_previous_definition;
3021   else if (Old->isImplicit()) {
3022     PrevDiag = diag::note_previous_implicit_declaration;
3023     if (OldLocation.isInvalid())
3024       OldLocation = New->getLocation();
3025   } else
3026     PrevDiag = diag::note_previous_declaration;
3027   return std::make_pair(PrevDiag, OldLocation);
3028 }
3029 
3030 /// canRedefineFunction - checks if a function can be redefined. Currently,
3031 /// only extern inline functions can be redefined, and even then only in
3032 /// GNU89 mode.
3033 static bool canRedefineFunction(const FunctionDecl *FD,
3034                                 const LangOptions& LangOpts) {
3035   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3036           !LangOpts.CPlusPlus &&
3037           FD->isInlineSpecified() &&
3038           FD->getStorageClass() == SC_Extern);
3039 }
3040 
3041 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3042   const AttributedType *AT = T->getAs<AttributedType>();
3043   while (AT && !AT->isCallingConv())
3044     AT = AT->getModifiedType()->getAs<AttributedType>();
3045   return AT;
3046 }
3047 
3048 template <typename T>
3049 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3050   const DeclContext *DC = Old->getDeclContext();
3051   if (DC->isRecord())
3052     return false;
3053 
3054   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3055   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3056     return true;
3057   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3058     return true;
3059   return false;
3060 }
3061 
3062 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3063 static bool isExternC(VarTemplateDecl *) { return false; }
3064 
3065 /// Check whether a redeclaration of an entity introduced by a
3066 /// using-declaration is valid, given that we know it's not an overload
3067 /// (nor a hidden tag declaration).
3068 template<typename ExpectedDecl>
3069 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3070                                    ExpectedDecl *New) {
3071   // C++11 [basic.scope.declarative]p4:
3072   //   Given a set of declarations in a single declarative region, each of
3073   //   which specifies the same unqualified name,
3074   //   -- they shall all refer to the same entity, or all refer to functions
3075   //      and function templates; or
3076   //   -- exactly one declaration shall declare a class name or enumeration
3077   //      name that is not a typedef name and the other declarations shall all
3078   //      refer to the same variable or enumerator, or all refer to functions
3079   //      and function templates; in this case the class name or enumeration
3080   //      name is hidden (3.3.10).
3081 
3082   // C++11 [namespace.udecl]p14:
3083   //   If a function declaration in namespace scope or block scope has the
3084   //   same name and the same parameter-type-list as a function introduced
3085   //   by a using-declaration, and the declarations do not declare the same
3086   //   function, the program is ill-formed.
3087 
3088   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3089   if (Old &&
3090       !Old->getDeclContext()->getRedeclContext()->Equals(
3091           New->getDeclContext()->getRedeclContext()) &&
3092       !(isExternC(Old) && isExternC(New)))
3093     Old = nullptr;
3094 
3095   if (!Old) {
3096     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3097     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3098     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
3099     return true;
3100   }
3101   return false;
3102 }
3103 
3104 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3105                                             const FunctionDecl *B) {
3106   assert(A->getNumParams() == B->getNumParams());
3107 
3108   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3109     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3110     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3111     if (AttrA == AttrB)
3112       return true;
3113     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3114            AttrA->isDynamic() == AttrB->isDynamic();
3115   };
3116 
3117   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3118 }
3119 
3120 /// If necessary, adjust the semantic declaration context for a qualified
3121 /// declaration to name the correct inline namespace within the qualifier.
3122 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3123                                                DeclaratorDecl *OldD) {
3124   // The only case where we need to update the DeclContext is when
3125   // redeclaration lookup for a qualified name finds a declaration
3126   // in an inline namespace within the context named by the qualifier:
3127   //
3128   //   inline namespace N { int f(); }
3129   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3130   //
3131   // For unqualified declarations, the semantic context *can* change
3132   // along the redeclaration chain (for local extern declarations,
3133   // extern "C" declarations, and friend declarations in particular).
3134   if (!NewD->getQualifier())
3135     return;
3136 
3137   // NewD is probably already in the right context.
3138   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3139   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3140   if (NamedDC->Equals(SemaDC))
3141     return;
3142 
3143   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3144           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3145          "unexpected context for redeclaration");
3146 
3147   auto *LexDC = NewD->getLexicalDeclContext();
3148   auto FixSemaDC = [=](NamedDecl *D) {
3149     if (!D)
3150       return;
3151     D->setDeclContext(SemaDC);
3152     D->setLexicalDeclContext(LexDC);
3153   };
3154 
3155   FixSemaDC(NewD);
3156   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3157     FixSemaDC(FD->getDescribedFunctionTemplate());
3158   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3159     FixSemaDC(VD->getDescribedVarTemplate());
3160 }
3161 
3162 /// MergeFunctionDecl - We just parsed a function 'New' from
3163 /// declarator D which has the same name and scope as a previous
3164 /// declaration 'Old'.  Figure out how to resolve this situation,
3165 /// merging decls or emitting diagnostics as appropriate.
3166 ///
3167 /// In C++, New and Old must be declarations that are not
3168 /// overloaded. Use IsOverload to determine whether New and Old are
3169 /// overloaded, and to select the Old declaration that New should be
3170 /// merged with.
3171 ///
3172 /// Returns true if there was an error, false otherwise.
3173 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3174                              Scope *S, bool MergeTypeWithOld) {
3175   // Verify the old decl was also a function.
3176   FunctionDecl *Old = OldD->getAsFunction();
3177   if (!Old) {
3178     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3179       if (New->getFriendObjectKind()) {
3180         Diag(New->getLocation(), diag::err_using_decl_friend);
3181         Diag(Shadow->getTargetDecl()->getLocation(),
3182              diag::note_using_decl_target);
3183         Diag(Shadow->getUsingDecl()->getLocation(),
3184              diag::note_using_decl) << 0;
3185         return true;
3186       }
3187 
3188       // Check whether the two declarations might declare the same function.
3189       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3190         return true;
3191       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3192     } else {
3193       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3194         << New->getDeclName();
3195       notePreviousDefinition(OldD, New->getLocation());
3196       return true;
3197     }
3198   }
3199 
3200   // If the old declaration is invalid, just give up here.
3201   if (Old->isInvalidDecl())
3202     return true;
3203 
3204   // Disallow redeclaration of some builtins.
3205   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3206     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3207     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3208         << Old << Old->getType();
3209     return true;
3210   }
3211 
3212   diag::kind PrevDiag;
3213   SourceLocation OldLocation;
3214   std::tie(PrevDiag, OldLocation) =
3215       getNoteDiagForInvalidRedeclaration(Old, New);
3216 
3217   // Don't complain about this if we're in GNU89 mode and the old function
3218   // is an extern inline function.
3219   // Don't complain about specializations. They are not supposed to have
3220   // storage classes.
3221   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3222       New->getStorageClass() == SC_Static &&
3223       Old->hasExternalFormalLinkage() &&
3224       !New->getTemplateSpecializationInfo() &&
3225       !canRedefineFunction(Old, getLangOpts())) {
3226     if (getLangOpts().MicrosoftExt) {
3227       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3228       Diag(OldLocation, PrevDiag);
3229     } else {
3230       Diag(New->getLocation(), diag::err_static_non_static) << New;
3231       Diag(OldLocation, PrevDiag);
3232       return true;
3233     }
3234   }
3235 
3236   if (New->hasAttr<InternalLinkageAttr>() &&
3237       !Old->hasAttr<InternalLinkageAttr>()) {
3238     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3239         << New->getDeclName();
3240     notePreviousDefinition(Old, New->getLocation());
3241     New->dropAttr<InternalLinkageAttr>();
3242   }
3243 
3244   if (CheckRedeclarationModuleOwnership(New, Old))
3245     return true;
3246 
3247   if (!getLangOpts().CPlusPlus) {
3248     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3249     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3250       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3251         << New << OldOvl;
3252 
3253       // Try our best to find a decl that actually has the overloadable
3254       // attribute for the note. In most cases (e.g. programs with only one
3255       // broken declaration/definition), this won't matter.
3256       //
3257       // FIXME: We could do this if we juggled some extra state in
3258       // OverloadableAttr, rather than just removing it.
3259       const Decl *DiagOld = Old;
3260       if (OldOvl) {
3261         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3262           const auto *A = D->getAttr<OverloadableAttr>();
3263           return A && !A->isImplicit();
3264         });
3265         // If we've implicitly added *all* of the overloadable attrs to this
3266         // chain, emitting a "previous redecl" note is pointless.
3267         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3268       }
3269 
3270       if (DiagOld)
3271         Diag(DiagOld->getLocation(),
3272              diag::note_attribute_overloadable_prev_overload)
3273           << OldOvl;
3274 
3275       if (OldOvl)
3276         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3277       else
3278         New->dropAttr<OverloadableAttr>();
3279     }
3280   }
3281 
3282   // If a function is first declared with a calling convention, but is later
3283   // declared or defined without one, all following decls assume the calling
3284   // convention of the first.
3285   //
3286   // It's OK if a function is first declared without a calling convention,
3287   // but is later declared or defined with the default calling convention.
3288   //
3289   // To test if either decl has an explicit calling convention, we look for
3290   // AttributedType sugar nodes on the type as written.  If they are missing or
3291   // were canonicalized away, we assume the calling convention was implicit.
3292   //
3293   // Note also that we DO NOT return at this point, because we still have
3294   // other tests to run.
3295   QualType OldQType = Context.getCanonicalType(Old->getType());
3296   QualType NewQType = Context.getCanonicalType(New->getType());
3297   const FunctionType *OldType = cast<FunctionType>(OldQType);
3298   const FunctionType *NewType = cast<FunctionType>(NewQType);
3299   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3300   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3301   bool RequiresAdjustment = false;
3302 
3303   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3304     FunctionDecl *First = Old->getFirstDecl();
3305     const FunctionType *FT =
3306         First->getType().getCanonicalType()->castAs<FunctionType>();
3307     FunctionType::ExtInfo FI = FT->getExtInfo();
3308     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3309     if (!NewCCExplicit) {
3310       // Inherit the CC from the previous declaration if it was specified
3311       // there but not here.
3312       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3313       RequiresAdjustment = true;
3314     } else if (New->getBuiltinID()) {
3315       // Calling Conventions on a Builtin aren't really useful and setting a
3316       // default calling convention and cdecl'ing some builtin redeclarations is
3317       // common, so warn and ignore the calling convention on the redeclaration.
3318       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3319           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3320           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3321       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3322       RequiresAdjustment = true;
3323     } else {
3324       // Calling conventions aren't compatible, so complain.
3325       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3326       Diag(New->getLocation(), diag::err_cconv_change)
3327         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3328         << !FirstCCExplicit
3329         << (!FirstCCExplicit ? "" :
3330             FunctionType::getNameForCallConv(FI.getCC()));
3331 
3332       // Put the note on the first decl, since it is the one that matters.
3333       Diag(First->getLocation(), diag::note_previous_declaration);
3334       return true;
3335     }
3336   }
3337 
3338   // FIXME: diagnose the other way around?
3339   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3340     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3341     RequiresAdjustment = true;
3342   }
3343 
3344   // Merge regparm attribute.
3345   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3346       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3347     if (NewTypeInfo.getHasRegParm()) {
3348       Diag(New->getLocation(), diag::err_regparm_mismatch)
3349         << NewType->getRegParmType()
3350         << OldType->getRegParmType();
3351       Diag(OldLocation, diag::note_previous_declaration);
3352       return true;
3353     }
3354 
3355     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3356     RequiresAdjustment = true;
3357   }
3358 
3359   // Merge ns_returns_retained attribute.
3360   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3361     if (NewTypeInfo.getProducesResult()) {
3362       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3363           << "'ns_returns_retained'";
3364       Diag(OldLocation, diag::note_previous_declaration);
3365       return true;
3366     }
3367 
3368     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3369     RequiresAdjustment = true;
3370   }
3371 
3372   if (OldTypeInfo.getNoCallerSavedRegs() !=
3373       NewTypeInfo.getNoCallerSavedRegs()) {
3374     if (NewTypeInfo.getNoCallerSavedRegs()) {
3375       AnyX86NoCallerSavedRegistersAttr *Attr =
3376         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3377       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3378       Diag(OldLocation, diag::note_previous_declaration);
3379       return true;
3380     }
3381 
3382     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3383     RequiresAdjustment = true;
3384   }
3385 
3386   if (RequiresAdjustment) {
3387     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3388     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3389     New->setType(QualType(AdjustedType, 0));
3390     NewQType = Context.getCanonicalType(New->getType());
3391   }
3392 
3393   // If this redeclaration makes the function inline, we may need to add it to
3394   // UndefinedButUsed.
3395   if (!Old->isInlined() && New->isInlined() &&
3396       !New->hasAttr<GNUInlineAttr>() &&
3397       !getLangOpts().GNUInline &&
3398       Old->isUsed(false) &&
3399       !Old->isDefined() && !New->isThisDeclarationADefinition())
3400     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3401                                            SourceLocation()));
3402 
3403   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3404   // about it.
3405   if (New->hasAttr<GNUInlineAttr>() &&
3406       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3407     UndefinedButUsed.erase(Old->getCanonicalDecl());
3408   }
3409 
3410   // If pass_object_size params don't match up perfectly, this isn't a valid
3411   // redeclaration.
3412   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3413       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3414     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3415         << New->getDeclName();
3416     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3417     return true;
3418   }
3419 
3420   if (getLangOpts().CPlusPlus) {
3421     // C++1z [over.load]p2
3422     //   Certain function declarations cannot be overloaded:
3423     //     -- Function declarations that differ only in the return type,
3424     //        the exception specification, or both cannot be overloaded.
3425 
3426     // Check the exception specifications match. This may recompute the type of
3427     // both Old and New if it resolved exception specifications, so grab the
3428     // types again after this. Because this updates the type, we do this before
3429     // any of the other checks below, which may update the "de facto" NewQType
3430     // but do not necessarily update the type of New.
3431     if (CheckEquivalentExceptionSpec(Old, New))
3432       return true;
3433     OldQType = Context.getCanonicalType(Old->getType());
3434     NewQType = Context.getCanonicalType(New->getType());
3435 
3436     // Go back to the type source info to compare the declared return types,
3437     // per C++1y [dcl.type.auto]p13:
3438     //   Redeclarations or specializations of a function or function template
3439     //   with a declared return type that uses a placeholder type shall also
3440     //   use that placeholder, not a deduced type.
3441     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3442     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3443     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3444         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3445                                        OldDeclaredReturnType)) {
3446       QualType ResQT;
3447       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3448           OldDeclaredReturnType->isObjCObjectPointerType())
3449         // FIXME: This does the wrong thing for a deduced return type.
3450         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3451       if (ResQT.isNull()) {
3452         if (New->isCXXClassMember() && New->isOutOfLine())
3453           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3454               << New << New->getReturnTypeSourceRange();
3455         else
3456           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3457               << New->getReturnTypeSourceRange();
3458         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3459                                     << Old->getReturnTypeSourceRange();
3460         return true;
3461       }
3462       else
3463         NewQType = ResQT;
3464     }
3465 
3466     QualType OldReturnType = OldType->getReturnType();
3467     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3468     if (OldReturnType != NewReturnType) {
3469       // If this function has a deduced return type and has already been
3470       // defined, copy the deduced value from the old declaration.
3471       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3472       if (OldAT && OldAT->isDeduced()) {
3473         New->setType(
3474             SubstAutoType(New->getType(),
3475                           OldAT->isDependentType() ? Context.DependentTy
3476                                                    : OldAT->getDeducedType()));
3477         NewQType = Context.getCanonicalType(
3478             SubstAutoType(NewQType,
3479                           OldAT->isDependentType() ? Context.DependentTy
3480                                                    : OldAT->getDeducedType()));
3481       }
3482     }
3483 
3484     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3485     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3486     if (OldMethod && NewMethod) {
3487       // Preserve triviality.
3488       NewMethod->setTrivial(OldMethod->isTrivial());
3489 
3490       // MSVC allows explicit template specialization at class scope:
3491       // 2 CXXMethodDecls referring to the same function will be injected.
3492       // We don't want a redeclaration error.
3493       bool IsClassScopeExplicitSpecialization =
3494                               OldMethod->isFunctionTemplateSpecialization() &&
3495                               NewMethod->isFunctionTemplateSpecialization();
3496       bool isFriend = NewMethod->getFriendObjectKind();
3497 
3498       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3499           !IsClassScopeExplicitSpecialization) {
3500         //    -- Member function declarations with the same name and the
3501         //       same parameter types cannot be overloaded if any of them
3502         //       is a static member function declaration.
3503         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3504           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3505           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3506           return true;
3507         }
3508 
3509         // C++ [class.mem]p1:
3510         //   [...] A member shall not be declared twice in the
3511         //   member-specification, except that a nested class or member
3512         //   class template can be declared and then later defined.
3513         if (!inTemplateInstantiation()) {
3514           unsigned NewDiag;
3515           if (isa<CXXConstructorDecl>(OldMethod))
3516             NewDiag = diag::err_constructor_redeclared;
3517           else if (isa<CXXDestructorDecl>(NewMethod))
3518             NewDiag = diag::err_destructor_redeclared;
3519           else if (isa<CXXConversionDecl>(NewMethod))
3520             NewDiag = diag::err_conv_function_redeclared;
3521           else
3522             NewDiag = diag::err_member_redeclared;
3523 
3524           Diag(New->getLocation(), NewDiag);
3525         } else {
3526           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3527             << New << New->getType();
3528         }
3529         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3530         return true;
3531 
3532       // Complain if this is an explicit declaration of a special
3533       // member that was initially declared implicitly.
3534       //
3535       // As an exception, it's okay to befriend such methods in order
3536       // to permit the implicit constructor/destructor/operator calls.
3537       } else if (OldMethod->isImplicit()) {
3538         if (isFriend) {
3539           NewMethod->setImplicit();
3540         } else {
3541           Diag(NewMethod->getLocation(),
3542                diag::err_definition_of_implicitly_declared_member)
3543             << New << getSpecialMember(OldMethod);
3544           return true;
3545         }
3546       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3547         Diag(NewMethod->getLocation(),
3548              diag::err_definition_of_explicitly_defaulted_member)
3549           << getSpecialMember(OldMethod);
3550         return true;
3551       }
3552     }
3553 
3554     // C++11 [dcl.attr.noreturn]p1:
3555     //   The first declaration of a function shall specify the noreturn
3556     //   attribute if any declaration of that function specifies the noreturn
3557     //   attribute.
3558     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3559     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3560       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3561       Diag(Old->getFirstDecl()->getLocation(),
3562            diag::note_noreturn_missing_first_decl);
3563     }
3564 
3565     // C++11 [dcl.attr.depend]p2:
3566     //   The first declaration of a function shall specify the
3567     //   carries_dependency attribute for its declarator-id if any declaration
3568     //   of the function specifies the carries_dependency attribute.
3569     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3570     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3571       Diag(CDA->getLocation(),
3572            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3573       Diag(Old->getFirstDecl()->getLocation(),
3574            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3575     }
3576 
3577     // (C++98 8.3.5p3):
3578     //   All declarations for a function shall agree exactly in both the
3579     //   return type and the parameter-type-list.
3580     // We also want to respect all the extended bits except noreturn.
3581 
3582     // noreturn should now match unless the old type info didn't have it.
3583     QualType OldQTypeForComparison = OldQType;
3584     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3585       auto *OldType = OldQType->castAs<FunctionProtoType>();
3586       const FunctionType *OldTypeForComparison
3587         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3588       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3589       assert(OldQTypeForComparison.isCanonical());
3590     }
3591 
3592     if (haveIncompatibleLanguageLinkages(Old, New)) {
3593       // As a special case, retain the language linkage from previous
3594       // declarations of a friend function as an extension.
3595       //
3596       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3597       // and is useful because there's otherwise no way to specify language
3598       // linkage within class scope.
3599       //
3600       // Check cautiously as the friend object kind isn't yet complete.
3601       if (New->getFriendObjectKind() != Decl::FOK_None) {
3602         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3603         Diag(OldLocation, PrevDiag);
3604       } else {
3605         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3606         Diag(OldLocation, PrevDiag);
3607         return true;
3608       }
3609     }
3610 
3611     // If the function types are compatible, merge the declarations. Ignore the
3612     // exception specifier because it was already checked above in
3613     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3614     // about incompatible types under -fms-compatibility.
3615     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3616                                                          NewQType))
3617       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3618 
3619     // If the types are imprecise (due to dependent constructs in friends or
3620     // local extern declarations), it's OK if they differ. We'll check again
3621     // during instantiation.
3622     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3623       return false;
3624 
3625     // Fall through for conflicting redeclarations and redefinitions.
3626   }
3627 
3628   // C: Function types need to be compatible, not identical. This handles
3629   // duplicate function decls like "void f(int); void f(enum X);" properly.
3630   if (!getLangOpts().CPlusPlus &&
3631       Context.typesAreCompatible(OldQType, NewQType)) {
3632     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3633     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3634     const FunctionProtoType *OldProto = nullptr;
3635     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3636         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3637       // The old declaration provided a function prototype, but the
3638       // new declaration does not. Merge in the prototype.
3639       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3640       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3641       NewQType =
3642           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3643                                   OldProto->getExtProtoInfo());
3644       New->setType(NewQType);
3645       New->setHasInheritedPrototype();
3646 
3647       // Synthesize parameters with the same types.
3648       SmallVector<ParmVarDecl*, 16> Params;
3649       for (const auto &ParamType : OldProto->param_types()) {
3650         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3651                                                  SourceLocation(), nullptr,
3652                                                  ParamType, /*TInfo=*/nullptr,
3653                                                  SC_None, nullptr);
3654         Param->setScopeInfo(0, Params.size());
3655         Param->setImplicit();
3656         Params.push_back(Param);
3657       }
3658 
3659       New->setParams(Params);
3660     }
3661 
3662     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3663   }
3664 
3665   // Check if the function types are compatible when pointer size address
3666   // spaces are ignored.
3667   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3668     return false;
3669 
3670   // GNU C permits a K&R definition to follow a prototype declaration
3671   // if the declared types of the parameters in the K&R definition
3672   // match the types in the prototype declaration, even when the
3673   // promoted types of the parameters from the K&R definition differ
3674   // from the types in the prototype. GCC then keeps the types from
3675   // the prototype.
3676   //
3677   // If a variadic prototype is followed by a non-variadic K&R definition,
3678   // the K&R definition becomes variadic.  This is sort of an edge case, but
3679   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3680   // C99 6.9.1p8.
3681   if (!getLangOpts().CPlusPlus &&
3682       Old->hasPrototype() && !New->hasPrototype() &&
3683       New->getType()->getAs<FunctionProtoType>() &&
3684       Old->getNumParams() == New->getNumParams()) {
3685     SmallVector<QualType, 16> ArgTypes;
3686     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3687     const FunctionProtoType *OldProto
3688       = Old->getType()->getAs<FunctionProtoType>();
3689     const FunctionProtoType *NewProto
3690       = New->getType()->getAs<FunctionProtoType>();
3691 
3692     // Determine whether this is the GNU C extension.
3693     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3694                                                NewProto->getReturnType());
3695     bool LooseCompatible = !MergedReturn.isNull();
3696     for (unsigned Idx = 0, End = Old->getNumParams();
3697          LooseCompatible && Idx != End; ++Idx) {
3698       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3699       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3700       if (Context.typesAreCompatible(OldParm->getType(),
3701                                      NewProto->getParamType(Idx))) {
3702         ArgTypes.push_back(NewParm->getType());
3703       } else if (Context.typesAreCompatible(OldParm->getType(),
3704                                             NewParm->getType(),
3705                                             /*CompareUnqualified=*/true)) {
3706         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3707                                            NewProto->getParamType(Idx) };
3708         Warnings.push_back(Warn);
3709         ArgTypes.push_back(NewParm->getType());
3710       } else
3711         LooseCompatible = false;
3712     }
3713 
3714     if (LooseCompatible) {
3715       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3716         Diag(Warnings[Warn].NewParm->getLocation(),
3717              diag::ext_param_promoted_not_compatible_with_prototype)
3718           << Warnings[Warn].PromotedType
3719           << Warnings[Warn].OldParm->getType();
3720         if (Warnings[Warn].OldParm->getLocation().isValid())
3721           Diag(Warnings[Warn].OldParm->getLocation(),
3722                diag::note_previous_declaration);
3723       }
3724 
3725       if (MergeTypeWithOld)
3726         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3727                                              OldProto->getExtProtoInfo()));
3728       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3729     }
3730 
3731     // Fall through to diagnose conflicting types.
3732   }
3733 
3734   // A function that has already been declared has been redeclared or
3735   // defined with a different type; show an appropriate diagnostic.
3736 
3737   // If the previous declaration was an implicitly-generated builtin
3738   // declaration, then at the very least we should use a specialized note.
3739   unsigned BuiltinID;
3740   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3741     // If it's actually a library-defined builtin function like 'malloc'
3742     // or 'printf', just warn about the incompatible redeclaration.
3743     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3744       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3745       Diag(OldLocation, diag::note_previous_builtin_declaration)
3746         << Old << Old->getType();
3747 
3748       // If this is a global redeclaration, just forget hereafter
3749       // about the "builtin-ness" of the function.
3750       //
3751       // Doing this for local extern declarations is problematic.  If
3752       // the builtin declaration remains visible, a second invalid
3753       // local declaration will produce a hard error; if it doesn't
3754       // remain visible, a single bogus local redeclaration (which is
3755       // actually only a warning) could break all the downstream code.
3756       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3757         New->getIdentifier()->revertBuiltin();
3758 
3759       return false;
3760     }
3761 
3762     PrevDiag = diag::note_previous_builtin_declaration;
3763   }
3764 
3765   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3766   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3767   return true;
3768 }
3769 
3770 /// Completes the merge of two function declarations that are
3771 /// known to be compatible.
3772 ///
3773 /// This routine handles the merging of attributes and other
3774 /// properties of function declarations from the old declaration to
3775 /// the new declaration, once we know that New is in fact a
3776 /// redeclaration of Old.
3777 ///
3778 /// \returns false
3779 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3780                                         Scope *S, bool MergeTypeWithOld) {
3781   // Merge the attributes
3782   mergeDeclAttributes(New, Old);
3783 
3784   // Merge "pure" flag.
3785   if (Old->isPure())
3786     New->setPure();
3787 
3788   // Merge "used" flag.
3789   if (Old->getMostRecentDecl()->isUsed(false))
3790     New->setIsUsed();
3791 
3792   // Merge attributes from the parameters.  These can mismatch with K&R
3793   // declarations.
3794   if (New->getNumParams() == Old->getNumParams())
3795       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3796         ParmVarDecl *NewParam = New->getParamDecl(i);
3797         ParmVarDecl *OldParam = Old->getParamDecl(i);
3798         mergeParamDeclAttributes(NewParam, OldParam, *this);
3799         mergeParamDeclTypes(NewParam, OldParam, *this);
3800       }
3801 
3802   if (getLangOpts().CPlusPlus)
3803     return MergeCXXFunctionDecl(New, Old, S);
3804 
3805   // Merge the function types so the we get the composite types for the return
3806   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3807   // was visible.
3808   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3809   if (!Merged.isNull() && MergeTypeWithOld)
3810     New->setType(Merged);
3811 
3812   return false;
3813 }
3814 
3815 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3816                                 ObjCMethodDecl *oldMethod) {
3817   // Merge the attributes, including deprecated/unavailable
3818   AvailabilityMergeKind MergeKind =
3819     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3820       ? AMK_ProtocolImplementation
3821       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3822                                                        : AMK_Override;
3823 
3824   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3825 
3826   // Merge attributes from the parameters.
3827   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3828                                        oe = oldMethod->param_end();
3829   for (ObjCMethodDecl::param_iterator
3830          ni = newMethod->param_begin(), ne = newMethod->param_end();
3831        ni != ne && oi != oe; ++ni, ++oi)
3832     mergeParamDeclAttributes(*ni, *oi, *this);
3833 
3834   CheckObjCMethodOverride(newMethod, oldMethod);
3835 }
3836 
3837 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3838   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3839 
3840   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3841          ? diag::err_redefinition_different_type
3842          : diag::err_redeclaration_different_type)
3843     << New->getDeclName() << New->getType() << Old->getType();
3844 
3845   diag::kind PrevDiag;
3846   SourceLocation OldLocation;
3847   std::tie(PrevDiag, OldLocation)
3848     = getNoteDiagForInvalidRedeclaration(Old, New);
3849   S.Diag(OldLocation, PrevDiag);
3850   New->setInvalidDecl();
3851 }
3852 
3853 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3854 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3855 /// emitting diagnostics as appropriate.
3856 ///
3857 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3858 /// to here in AddInitializerToDecl. We can't check them before the initializer
3859 /// is attached.
3860 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3861                              bool MergeTypeWithOld) {
3862   if (New->isInvalidDecl() || Old->isInvalidDecl())
3863     return;
3864 
3865   QualType MergedT;
3866   if (getLangOpts().CPlusPlus) {
3867     if (New->getType()->isUndeducedType()) {
3868       // We don't know what the new type is until the initializer is attached.
3869       return;
3870     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3871       // These could still be something that needs exception specs checked.
3872       return MergeVarDeclExceptionSpecs(New, Old);
3873     }
3874     // C++ [basic.link]p10:
3875     //   [...] the types specified by all declarations referring to a given
3876     //   object or function shall be identical, except that declarations for an
3877     //   array object can specify array types that differ by the presence or
3878     //   absence of a major array bound (8.3.4).
3879     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3880       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3881       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3882 
3883       // We are merging a variable declaration New into Old. If it has an array
3884       // bound, and that bound differs from Old's bound, we should diagnose the
3885       // mismatch.
3886       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3887         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3888              PrevVD = PrevVD->getPreviousDecl()) {
3889           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3890           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3891             continue;
3892 
3893           if (!Context.hasSameType(NewArray, PrevVDTy))
3894             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3895         }
3896       }
3897 
3898       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3899         if (Context.hasSameType(OldArray->getElementType(),
3900                                 NewArray->getElementType()))
3901           MergedT = New->getType();
3902       }
3903       // FIXME: Check visibility. New is hidden but has a complete type. If New
3904       // has no array bound, it should not inherit one from Old, if Old is not
3905       // visible.
3906       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3907         if (Context.hasSameType(OldArray->getElementType(),
3908                                 NewArray->getElementType()))
3909           MergedT = Old->getType();
3910       }
3911     }
3912     else if (New->getType()->isObjCObjectPointerType() &&
3913                Old->getType()->isObjCObjectPointerType()) {
3914       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3915                                               Old->getType());
3916     }
3917   } else {
3918     // C 6.2.7p2:
3919     //   All declarations that refer to the same object or function shall have
3920     //   compatible type.
3921     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3922   }
3923   if (MergedT.isNull()) {
3924     // It's OK if we couldn't merge types if either type is dependent, for a
3925     // block-scope variable. In other cases (static data members of class
3926     // templates, variable templates, ...), we require the types to be
3927     // equivalent.
3928     // FIXME: The C++ standard doesn't say anything about this.
3929     if ((New->getType()->isDependentType() ||
3930          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3931       // If the old type was dependent, we can't merge with it, so the new type
3932       // becomes dependent for now. We'll reproduce the original type when we
3933       // instantiate the TypeSourceInfo for the variable.
3934       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3935         New->setType(Context.DependentTy);
3936       return;
3937     }
3938     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3939   }
3940 
3941   // Don't actually update the type on the new declaration if the old
3942   // declaration was an extern declaration in a different scope.
3943   if (MergeTypeWithOld)
3944     New->setType(MergedT);
3945 }
3946 
3947 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3948                                   LookupResult &Previous) {
3949   // C11 6.2.7p4:
3950   //   For an identifier with internal or external linkage declared
3951   //   in a scope in which a prior declaration of that identifier is
3952   //   visible, if the prior declaration specifies internal or
3953   //   external linkage, the type of the identifier at the later
3954   //   declaration becomes the composite type.
3955   //
3956   // If the variable isn't visible, we do not merge with its type.
3957   if (Previous.isShadowed())
3958     return false;
3959 
3960   if (S.getLangOpts().CPlusPlus) {
3961     // C++11 [dcl.array]p3:
3962     //   If there is a preceding declaration of the entity in the same
3963     //   scope in which the bound was specified, an omitted array bound
3964     //   is taken to be the same as in that earlier declaration.
3965     return NewVD->isPreviousDeclInSameBlockScope() ||
3966            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3967             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3968   } else {
3969     // If the old declaration was function-local, don't merge with its
3970     // type unless we're in the same function.
3971     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3972            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3973   }
3974 }
3975 
3976 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3977 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3978 /// situation, merging decls or emitting diagnostics as appropriate.
3979 ///
3980 /// Tentative definition rules (C99 6.9.2p2) are checked by
3981 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3982 /// definitions here, since the initializer hasn't been attached.
3983 ///
3984 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3985   // If the new decl is already invalid, don't do any other checking.
3986   if (New->isInvalidDecl())
3987     return;
3988 
3989   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3990     return;
3991 
3992   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3993 
3994   // Verify the old decl was also a variable or variable template.
3995   VarDecl *Old = nullptr;
3996   VarTemplateDecl *OldTemplate = nullptr;
3997   if (Previous.isSingleResult()) {
3998     if (NewTemplate) {
3999       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4000       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4001 
4002       if (auto *Shadow =
4003               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4004         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4005           return New->setInvalidDecl();
4006     } else {
4007       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4008 
4009       if (auto *Shadow =
4010               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4011         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4012           return New->setInvalidDecl();
4013     }
4014   }
4015   if (!Old) {
4016     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4017         << New->getDeclName();
4018     notePreviousDefinition(Previous.getRepresentativeDecl(),
4019                            New->getLocation());
4020     return New->setInvalidDecl();
4021   }
4022 
4023   // Ensure the template parameters are compatible.
4024   if (NewTemplate &&
4025       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4026                                       OldTemplate->getTemplateParameters(),
4027                                       /*Complain=*/true, TPL_TemplateMatch))
4028     return New->setInvalidDecl();
4029 
4030   // C++ [class.mem]p1:
4031   //   A member shall not be declared twice in the member-specification [...]
4032   //
4033   // Here, we need only consider static data members.
4034   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4035     Diag(New->getLocation(), diag::err_duplicate_member)
4036       << New->getIdentifier();
4037     Diag(Old->getLocation(), diag::note_previous_declaration);
4038     New->setInvalidDecl();
4039   }
4040 
4041   mergeDeclAttributes(New, Old);
4042   // Warn if an already-declared variable is made a weak_import in a subsequent
4043   // declaration
4044   if (New->hasAttr<WeakImportAttr>() &&
4045       Old->getStorageClass() == SC_None &&
4046       !Old->hasAttr<WeakImportAttr>()) {
4047     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4048     notePreviousDefinition(Old, New->getLocation());
4049     // Remove weak_import attribute on new declaration.
4050     New->dropAttr<WeakImportAttr>();
4051   }
4052 
4053   if (New->hasAttr<InternalLinkageAttr>() &&
4054       !Old->hasAttr<InternalLinkageAttr>()) {
4055     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
4056         << New->getDeclName();
4057     notePreviousDefinition(Old, New->getLocation());
4058     New->dropAttr<InternalLinkageAttr>();
4059   }
4060 
4061   // Merge the types.
4062   VarDecl *MostRecent = Old->getMostRecentDecl();
4063   if (MostRecent != Old) {
4064     MergeVarDeclTypes(New, MostRecent,
4065                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4066     if (New->isInvalidDecl())
4067       return;
4068   }
4069 
4070   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4071   if (New->isInvalidDecl())
4072     return;
4073 
4074   diag::kind PrevDiag;
4075   SourceLocation OldLocation;
4076   std::tie(PrevDiag, OldLocation) =
4077       getNoteDiagForInvalidRedeclaration(Old, New);
4078 
4079   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4080   if (New->getStorageClass() == SC_Static &&
4081       !New->isStaticDataMember() &&
4082       Old->hasExternalFormalLinkage()) {
4083     if (getLangOpts().MicrosoftExt) {
4084       Diag(New->getLocation(), diag::ext_static_non_static)
4085           << New->getDeclName();
4086       Diag(OldLocation, PrevDiag);
4087     } else {
4088       Diag(New->getLocation(), diag::err_static_non_static)
4089           << New->getDeclName();
4090       Diag(OldLocation, PrevDiag);
4091       return New->setInvalidDecl();
4092     }
4093   }
4094   // C99 6.2.2p4:
4095   //   For an identifier declared with the storage-class specifier
4096   //   extern in a scope in which a prior declaration of that
4097   //   identifier is visible,23) if the prior declaration specifies
4098   //   internal or external linkage, the linkage of the identifier at
4099   //   the later declaration is the same as the linkage specified at
4100   //   the prior declaration. If no prior declaration is visible, or
4101   //   if the prior declaration specifies no linkage, then the
4102   //   identifier has external linkage.
4103   if (New->hasExternalStorage() && Old->hasLinkage())
4104     /* Okay */;
4105   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4106            !New->isStaticDataMember() &&
4107            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4108     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4109     Diag(OldLocation, PrevDiag);
4110     return New->setInvalidDecl();
4111   }
4112 
4113   // Check if extern is followed by non-extern and vice-versa.
4114   if (New->hasExternalStorage() &&
4115       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4116     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4117     Diag(OldLocation, PrevDiag);
4118     return New->setInvalidDecl();
4119   }
4120   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4121       !New->hasExternalStorage()) {
4122     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4123     Diag(OldLocation, PrevDiag);
4124     return New->setInvalidDecl();
4125   }
4126 
4127   if (CheckRedeclarationModuleOwnership(New, Old))
4128     return;
4129 
4130   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4131 
4132   // FIXME: The test for external storage here seems wrong? We still
4133   // need to check for mismatches.
4134   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4135       // Don't complain about out-of-line definitions of static members.
4136       !(Old->getLexicalDeclContext()->isRecord() &&
4137         !New->getLexicalDeclContext()->isRecord())) {
4138     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4139     Diag(OldLocation, PrevDiag);
4140     return New->setInvalidDecl();
4141   }
4142 
4143   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4144     if (VarDecl *Def = Old->getDefinition()) {
4145       // C++1z [dcl.fcn.spec]p4:
4146       //   If the definition of a variable appears in a translation unit before
4147       //   its first declaration as inline, the program is ill-formed.
4148       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4149       Diag(Def->getLocation(), diag::note_previous_definition);
4150     }
4151   }
4152 
4153   // If this redeclaration makes the variable inline, we may need to add it to
4154   // UndefinedButUsed.
4155   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4156       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4157     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4158                                            SourceLocation()));
4159 
4160   if (New->getTLSKind() != Old->getTLSKind()) {
4161     if (!Old->getTLSKind()) {
4162       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4163       Diag(OldLocation, PrevDiag);
4164     } else if (!New->getTLSKind()) {
4165       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4166       Diag(OldLocation, PrevDiag);
4167     } else {
4168       // Do not allow redeclaration to change the variable between requiring
4169       // static and dynamic initialization.
4170       // FIXME: GCC allows this, but uses the TLS keyword on the first
4171       // declaration to determine the kind. Do we need to be compatible here?
4172       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4173         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4174       Diag(OldLocation, PrevDiag);
4175     }
4176   }
4177 
4178   // C++ doesn't have tentative definitions, so go right ahead and check here.
4179   if (getLangOpts().CPlusPlus &&
4180       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4181     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4182         Old->getCanonicalDecl()->isConstexpr()) {
4183       // This definition won't be a definition any more once it's been merged.
4184       Diag(New->getLocation(),
4185            diag::warn_deprecated_redundant_constexpr_static_def);
4186     } else if (VarDecl *Def = Old->getDefinition()) {
4187       if (checkVarDeclRedefinition(Def, New))
4188         return;
4189     }
4190   }
4191 
4192   if (haveIncompatibleLanguageLinkages(Old, New)) {
4193     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4194     Diag(OldLocation, PrevDiag);
4195     New->setInvalidDecl();
4196     return;
4197   }
4198 
4199   // Merge "used" flag.
4200   if (Old->getMostRecentDecl()->isUsed(false))
4201     New->setIsUsed();
4202 
4203   // Keep a chain of previous declarations.
4204   New->setPreviousDecl(Old);
4205   if (NewTemplate)
4206     NewTemplate->setPreviousDecl(OldTemplate);
4207   adjustDeclContextForDeclaratorDecl(New, Old);
4208 
4209   // Inherit access appropriately.
4210   New->setAccess(Old->getAccess());
4211   if (NewTemplate)
4212     NewTemplate->setAccess(New->getAccess());
4213 
4214   if (Old->isInline())
4215     New->setImplicitlyInline();
4216 }
4217 
4218 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4219   SourceManager &SrcMgr = getSourceManager();
4220   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4221   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4222   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4223   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4224   auto &HSI = PP.getHeaderSearchInfo();
4225   StringRef HdrFilename =
4226       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4227 
4228   auto noteFromModuleOrInclude = [&](Module *Mod,
4229                                      SourceLocation IncLoc) -> bool {
4230     // Redefinition errors with modules are common with non modular mapped
4231     // headers, example: a non-modular header H in module A that also gets
4232     // included directly in a TU. Pointing twice to the same header/definition
4233     // is confusing, try to get better diagnostics when modules is on.
4234     if (IncLoc.isValid()) {
4235       if (Mod) {
4236         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4237             << HdrFilename.str() << Mod->getFullModuleName();
4238         if (!Mod->DefinitionLoc.isInvalid())
4239           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4240               << Mod->getFullModuleName();
4241       } else {
4242         Diag(IncLoc, diag::note_redefinition_include_same_file)
4243             << HdrFilename.str();
4244       }
4245       return true;
4246     }
4247 
4248     return false;
4249   };
4250 
4251   // Is it the same file and same offset? Provide more information on why
4252   // this leads to a redefinition error.
4253   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4254     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4255     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4256     bool EmittedDiag =
4257         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4258     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4259 
4260     // If the header has no guards, emit a note suggesting one.
4261     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4262       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4263 
4264     if (EmittedDiag)
4265       return;
4266   }
4267 
4268   // Redefinition coming from different files or couldn't do better above.
4269   if (Old->getLocation().isValid())
4270     Diag(Old->getLocation(), diag::note_previous_definition);
4271 }
4272 
4273 /// We've just determined that \p Old and \p New both appear to be definitions
4274 /// of the same variable. Either diagnose or fix the problem.
4275 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4276   if (!hasVisibleDefinition(Old) &&
4277       (New->getFormalLinkage() == InternalLinkage ||
4278        New->isInline() ||
4279        New->getDescribedVarTemplate() ||
4280        New->getNumTemplateParameterLists() ||
4281        New->getDeclContext()->isDependentContext())) {
4282     // The previous definition is hidden, and multiple definitions are
4283     // permitted (in separate TUs). Demote this to a declaration.
4284     New->demoteThisDefinitionToDeclaration();
4285 
4286     // Make the canonical definition visible.
4287     if (auto *OldTD = Old->getDescribedVarTemplate())
4288       makeMergedDefinitionVisible(OldTD);
4289     makeMergedDefinitionVisible(Old);
4290     return false;
4291   } else {
4292     Diag(New->getLocation(), diag::err_redefinition) << New;
4293     notePreviousDefinition(Old, New->getLocation());
4294     New->setInvalidDecl();
4295     return true;
4296   }
4297 }
4298 
4299 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4300 /// no declarator (e.g. "struct foo;") is parsed.
4301 Decl *
4302 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4303                                  RecordDecl *&AnonRecord) {
4304   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4305                                     AnonRecord);
4306 }
4307 
4308 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4309 // disambiguate entities defined in different scopes.
4310 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4311 // compatibility.
4312 // We will pick our mangling number depending on which version of MSVC is being
4313 // targeted.
4314 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4315   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4316              ? S->getMSCurManglingNumber()
4317              : S->getMSLastManglingNumber();
4318 }
4319 
4320 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4321   if (!Context.getLangOpts().CPlusPlus)
4322     return;
4323 
4324   if (isa<CXXRecordDecl>(Tag->getParent())) {
4325     // If this tag is the direct child of a class, number it if
4326     // it is anonymous.
4327     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4328       return;
4329     MangleNumberingContext &MCtx =
4330         Context.getManglingNumberContext(Tag->getParent());
4331     Context.setManglingNumber(
4332         Tag, MCtx.getManglingNumber(
4333                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4334     return;
4335   }
4336 
4337   // If this tag isn't a direct child of a class, number it if it is local.
4338   MangleNumberingContext *MCtx;
4339   Decl *ManglingContextDecl;
4340   std::tie(MCtx, ManglingContextDecl) =
4341       getCurrentMangleNumberContext(Tag->getDeclContext());
4342   if (MCtx) {
4343     Context.setManglingNumber(
4344         Tag, MCtx->getManglingNumber(
4345                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4346   }
4347 }
4348 
4349 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4350                                         TypedefNameDecl *NewTD) {
4351   if (TagFromDeclSpec->isInvalidDecl())
4352     return;
4353 
4354   // Do nothing if the tag already has a name for linkage purposes.
4355   if (TagFromDeclSpec->hasNameForLinkage())
4356     return;
4357 
4358   // A well-formed anonymous tag must always be a TUK_Definition.
4359   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4360 
4361   // The type must match the tag exactly;  no qualifiers allowed.
4362   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4363                            Context.getTagDeclType(TagFromDeclSpec))) {
4364     if (getLangOpts().CPlusPlus)
4365       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4366     return;
4367   }
4368 
4369   // If we've already computed linkage for the anonymous tag, then
4370   // adding a typedef name for the anonymous decl can change that
4371   // linkage, which might be a serious problem.  Diagnose this as
4372   // unsupported and ignore the typedef name.  TODO: we should
4373   // pursue this as a language defect and establish a formal rule
4374   // for how to handle it.
4375   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4376     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4377 
4378     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4379     tagLoc = getLocForEndOfToken(tagLoc);
4380 
4381     llvm::SmallString<40> textToInsert;
4382     textToInsert += ' ';
4383     textToInsert += NewTD->getIdentifier()->getName();
4384     Diag(tagLoc, diag::note_typedef_changes_linkage)
4385         << FixItHint::CreateInsertion(tagLoc, textToInsert);
4386     return;
4387   }
4388 
4389   // Otherwise, set this is the anon-decl typedef for the tag.
4390   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4391 }
4392 
4393 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4394   switch (T) {
4395   case DeclSpec::TST_class:
4396     return 0;
4397   case DeclSpec::TST_struct:
4398     return 1;
4399   case DeclSpec::TST_interface:
4400     return 2;
4401   case DeclSpec::TST_union:
4402     return 3;
4403   case DeclSpec::TST_enum:
4404     return 4;
4405   default:
4406     llvm_unreachable("unexpected type specifier");
4407   }
4408 }
4409 
4410 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4411 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4412 /// parameters to cope with template friend declarations.
4413 Decl *
4414 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4415                                  MultiTemplateParamsArg TemplateParams,
4416                                  bool IsExplicitInstantiation,
4417                                  RecordDecl *&AnonRecord) {
4418   Decl *TagD = nullptr;
4419   TagDecl *Tag = nullptr;
4420   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4421       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4422       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4423       DS.getTypeSpecType() == DeclSpec::TST_union ||
4424       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4425     TagD = DS.getRepAsDecl();
4426 
4427     if (!TagD) // We probably had an error
4428       return nullptr;
4429 
4430     // Note that the above type specs guarantee that the
4431     // type rep is a Decl, whereas in many of the others
4432     // it's a Type.
4433     if (isa<TagDecl>(TagD))
4434       Tag = cast<TagDecl>(TagD);
4435     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4436       Tag = CTD->getTemplatedDecl();
4437   }
4438 
4439   if (Tag) {
4440     handleTagNumbering(Tag, S);
4441     Tag->setFreeStanding();
4442     if (Tag->isInvalidDecl())
4443       return Tag;
4444   }
4445 
4446   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4447     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4448     // or incomplete types shall not be restrict-qualified."
4449     if (TypeQuals & DeclSpec::TQ_restrict)
4450       Diag(DS.getRestrictSpecLoc(),
4451            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4452            << DS.getSourceRange();
4453   }
4454 
4455   if (DS.isInlineSpecified())
4456     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4457         << getLangOpts().CPlusPlus17;
4458 
4459   if (DS.hasConstexprSpecifier()) {
4460     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4461     // and definitions of functions and variables.
4462     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4463     // the declaration of a function or function template
4464     if (Tag)
4465       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4466           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4467           << DS.getConstexprSpecifier();
4468     else
4469       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4470           << DS.getConstexprSpecifier();
4471     // Don't emit warnings after this error.
4472     return TagD;
4473   }
4474 
4475   DiagnoseFunctionSpecifiers(DS);
4476 
4477   if (DS.isFriendSpecified()) {
4478     // If we're dealing with a decl but not a TagDecl, assume that
4479     // whatever routines created it handled the friendship aspect.
4480     if (TagD && !Tag)
4481       return nullptr;
4482     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4483   }
4484 
4485   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4486   bool IsExplicitSpecialization =
4487     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4488   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4489       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4490       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4491     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4492     // nested-name-specifier unless it is an explicit instantiation
4493     // or an explicit specialization.
4494     //
4495     // FIXME: We allow class template partial specializations here too, per the
4496     // obvious intent of DR1819.
4497     //
4498     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4499     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4500         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4501     return nullptr;
4502   }
4503 
4504   // Track whether this decl-specifier declares anything.
4505   bool DeclaresAnything = true;
4506 
4507   // Handle anonymous struct definitions.
4508   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4509     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4510         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4511       if (getLangOpts().CPlusPlus ||
4512           Record->getDeclContext()->isRecord()) {
4513         // If CurContext is a DeclContext that can contain statements,
4514         // RecursiveASTVisitor won't visit the decls that
4515         // BuildAnonymousStructOrUnion() will put into CurContext.
4516         // Also store them here so that they can be part of the
4517         // DeclStmt that gets created in this case.
4518         // FIXME: Also return the IndirectFieldDecls created by
4519         // BuildAnonymousStructOr union, for the same reason?
4520         if (CurContext->isFunctionOrMethod())
4521           AnonRecord = Record;
4522         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4523                                            Context.getPrintingPolicy());
4524       }
4525 
4526       DeclaresAnything = false;
4527     }
4528   }
4529 
4530   // C11 6.7.2.1p2:
4531   //   A struct-declaration that does not declare an anonymous structure or
4532   //   anonymous union shall contain a struct-declarator-list.
4533   //
4534   // This rule also existed in C89 and C99; the grammar for struct-declaration
4535   // did not permit a struct-declaration without a struct-declarator-list.
4536   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4537       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4538     // Check for Microsoft C extension: anonymous struct/union member.
4539     // Handle 2 kinds of anonymous struct/union:
4540     //   struct STRUCT;
4541     //   union UNION;
4542     // and
4543     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4544     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4545     if ((Tag && Tag->getDeclName()) ||
4546         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4547       RecordDecl *Record = nullptr;
4548       if (Tag)
4549         Record = dyn_cast<RecordDecl>(Tag);
4550       else if (const RecordType *RT =
4551                    DS.getRepAsType().get()->getAsStructureType())
4552         Record = RT->getDecl();
4553       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4554         Record = UT->getDecl();
4555 
4556       if (Record && getLangOpts().MicrosoftExt) {
4557         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4558             << Record->isUnion() << DS.getSourceRange();
4559         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4560       }
4561 
4562       DeclaresAnything = false;
4563     }
4564   }
4565 
4566   // Skip all the checks below if we have a type error.
4567   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4568       (TagD && TagD->isInvalidDecl()))
4569     return TagD;
4570 
4571   if (getLangOpts().CPlusPlus &&
4572       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4573     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4574       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4575           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4576         DeclaresAnything = false;
4577 
4578   if (!DS.isMissingDeclaratorOk()) {
4579     // Customize diagnostic for a typedef missing a name.
4580     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4581       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4582           << DS.getSourceRange();
4583     else
4584       DeclaresAnything = false;
4585   }
4586 
4587   if (DS.isModulePrivateSpecified() &&
4588       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4589     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4590       << Tag->getTagKind()
4591       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4592 
4593   ActOnDocumentableDecl(TagD);
4594 
4595   // C 6.7/2:
4596   //   A declaration [...] shall declare at least a declarator [...], a tag,
4597   //   or the members of an enumeration.
4598   // C++ [dcl.dcl]p3:
4599   //   [If there are no declarators], and except for the declaration of an
4600   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4601   //   names into the program, or shall redeclare a name introduced by a
4602   //   previous declaration.
4603   if (!DeclaresAnything) {
4604     // In C, we allow this as a (popular) extension / bug. Don't bother
4605     // producing further diagnostics for redundant qualifiers after this.
4606     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4607     return TagD;
4608   }
4609 
4610   // C++ [dcl.stc]p1:
4611   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4612   //   init-declarator-list of the declaration shall not be empty.
4613   // C++ [dcl.fct.spec]p1:
4614   //   If a cv-qualifier appears in a decl-specifier-seq, the
4615   //   init-declarator-list of the declaration shall not be empty.
4616   //
4617   // Spurious qualifiers here appear to be valid in C.
4618   unsigned DiagID = diag::warn_standalone_specifier;
4619   if (getLangOpts().CPlusPlus)
4620     DiagID = diag::ext_standalone_specifier;
4621 
4622   // Note that a linkage-specification sets a storage class, but
4623   // 'extern "C" struct foo;' is actually valid and not theoretically
4624   // useless.
4625   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4626     if (SCS == DeclSpec::SCS_mutable)
4627       // Since mutable is not a viable storage class specifier in C, there is
4628       // no reason to treat it as an extension. Instead, diagnose as an error.
4629       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4630     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4631       Diag(DS.getStorageClassSpecLoc(), DiagID)
4632         << DeclSpec::getSpecifierName(SCS);
4633   }
4634 
4635   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4636     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4637       << DeclSpec::getSpecifierName(TSCS);
4638   if (DS.getTypeQualifiers()) {
4639     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4640       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4641     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4642       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4643     // Restrict is covered above.
4644     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4645       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4646     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4647       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4648   }
4649 
4650   // Warn about ignored type attributes, for example:
4651   // __attribute__((aligned)) struct A;
4652   // Attributes should be placed after tag to apply to type declaration.
4653   if (!DS.getAttributes().empty()) {
4654     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4655     if (TypeSpecType == DeclSpec::TST_class ||
4656         TypeSpecType == DeclSpec::TST_struct ||
4657         TypeSpecType == DeclSpec::TST_interface ||
4658         TypeSpecType == DeclSpec::TST_union ||
4659         TypeSpecType == DeclSpec::TST_enum) {
4660       for (const ParsedAttr &AL : DS.getAttributes())
4661         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4662             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4663     }
4664   }
4665 
4666   return TagD;
4667 }
4668 
4669 /// We are trying to inject an anonymous member into the given scope;
4670 /// check if there's an existing declaration that can't be overloaded.
4671 ///
4672 /// \return true if this is a forbidden redeclaration
4673 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4674                                          Scope *S,
4675                                          DeclContext *Owner,
4676                                          DeclarationName Name,
4677                                          SourceLocation NameLoc,
4678                                          bool IsUnion) {
4679   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4680                  Sema::ForVisibleRedeclaration);
4681   if (!SemaRef.LookupName(R, S)) return false;
4682 
4683   // Pick a representative declaration.
4684   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4685   assert(PrevDecl && "Expected a non-null Decl");
4686 
4687   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4688     return false;
4689 
4690   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4691     << IsUnion << Name;
4692   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4693 
4694   return true;
4695 }
4696 
4697 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4698 /// anonymous struct or union AnonRecord into the owning context Owner
4699 /// and scope S. This routine will be invoked just after we realize
4700 /// that an unnamed union or struct is actually an anonymous union or
4701 /// struct, e.g.,
4702 ///
4703 /// @code
4704 /// union {
4705 ///   int i;
4706 ///   float f;
4707 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4708 ///    // f into the surrounding scope.x
4709 /// @endcode
4710 ///
4711 /// This routine is recursive, injecting the names of nested anonymous
4712 /// structs/unions into the owning context and scope as well.
4713 static bool
4714 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4715                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4716                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4717   bool Invalid = false;
4718 
4719   // Look every FieldDecl and IndirectFieldDecl with a name.
4720   for (auto *D : AnonRecord->decls()) {
4721     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4722         cast<NamedDecl>(D)->getDeclName()) {
4723       ValueDecl *VD = cast<ValueDecl>(D);
4724       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4725                                        VD->getLocation(),
4726                                        AnonRecord->isUnion())) {
4727         // C++ [class.union]p2:
4728         //   The names of the members of an anonymous union shall be
4729         //   distinct from the names of any other entity in the
4730         //   scope in which the anonymous union is declared.
4731         Invalid = true;
4732       } else {
4733         // C++ [class.union]p2:
4734         //   For the purpose of name lookup, after the anonymous union
4735         //   definition, the members of the anonymous union are
4736         //   considered to have been defined in the scope in which the
4737         //   anonymous union is declared.
4738         unsigned OldChainingSize = Chaining.size();
4739         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4740           Chaining.append(IF->chain_begin(), IF->chain_end());
4741         else
4742           Chaining.push_back(VD);
4743 
4744         assert(Chaining.size() >= 2);
4745         NamedDecl **NamedChain =
4746           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4747         for (unsigned i = 0; i < Chaining.size(); i++)
4748           NamedChain[i] = Chaining[i];
4749 
4750         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4751             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4752             VD->getType(), {NamedChain, Chaining.size()});
4753 
4754         for (const auto *Attr : VD->attrs())
4755           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4756 
4757         IndirectField->setAccess(AS);
4758         IndirectField->setImplicit();
4759         SemaRef.PushOnScopeChains(IndirectField, S);
4760 
4761         // That includes picking up the appropriate access specifier.
4762         if (AS != AS_none) IndirectField->setAccess(AS);
4763 
4764         Chaining.resize(OldChainingSize);
4765       }
4766     }
4767   }
4768 
4769   return Invalid;
4770 }
4771 
4772 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4773 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4774 /// illegal input values are mapped to SC_None.
4775 static StorageClass
4776 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4777   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4778   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4779          "Parser allowed 'typedef' as storage class VarDecl.");
4780   switch (StorageClassSpec) {
4781   case DeclSpec::SCS_unspecified:    return SC_None;
4782   case DeclSpec::SCS_extern:
4783     if (DS.isExternInLinkageSpec())
4784       return SC_None;
4785     return SC_Extern;
4786   case DeclSpec::SCS_static:         return SC_Static;
4787   case DeclSpec::SCS_auto:           return SC_Auto;
4788   case DeclSpec::SCS_register:       return SC_Register;
4789   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4790     // Illegal SCSs map to None: error reporting is up to the caller.
4791   case DeclSpec::SCS_mutable:        // Fall through.
4792   case DeclSpec::SCS_typedef:        return SC_None;
4793   }
4794   llvm_unreachable("unknown storage class specifier");
4795 }
4796 
4797 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4798   assert(Record->hasInClassInitializer());
4799 
4800   for (const auto *I : Record->decls()) {
4801     const auto *FD = dyn_cast<FieldDecl>(I);
4802     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4803       FD = IFD->getAnonField();
4804     if (FD && FD->hasInClassInitializer())
4805       return FD->getLocation();
4806   }
4807 
4808   llvm_unreachable("couldn't find in-class initializer");
4809 }
4810 
4811 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4812                                       SourceLocation DefaultInitLoc) {
4813   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4814     return;
4815 
4816   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4817   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4818 }
4819 
4820 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4821                                       CXXRecordDecl *AnonUnion) {
4822   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4823     return;
4824 
4825   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4826 }
4827 
4828 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4829 /// anonymous structure or union. Anonymous unions are a C++ feature
4830 /// (C++ [class.union]) and a C11 feature; anonymous structures
4831 /// are a C11 feature and GNU C++ extension.
4832 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4833                                         AccessSpecifier AS,
4834                                         RecordDecl *Record,
4835                                         const PrintingPolicy &Policy) {
4836   DeclContext *Owner = Record->getDeclContext();
4837 
4838   // Diagnose whether this anonymous struct/union is an extension.
4839   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4840     Diag(Record->getLocation(), diag::ext_anonymous_union);
4841   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4842     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4843   else if (!Record->isUnion() && !getLangOpts().C11)
4844     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4845 
4846   // C and C++ require different kinds of checks for anonymous
4847   // structs/unions.
4848   bool Invalid = false;
4849   if (getLangOpts().CPlusPlus) {
4850     const char *PrevSpec = nullptr;
4851     if (Record->isUnion()) {
4852       // C++ [class.union]p6:
4853       // C++17 [class.union.anon]p2:
4854       //   Anonymous unions declared in a named namespace or in the
4855       //   global namespace shall be declared static.
4856       unsigned DiagID;
4857       DeclContext *OwnerScope = Owner->getRedeclContext();
4858       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4859           (OwnerScope->isTranslationUnit() ||
4860            (OwnerScope->isNamespace() &&
4861             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
4862         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4863           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4864 
4865         // Recover by adding 'static'.
4866         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4867                                PrevSpec, DiagID, Policy);
4868       }
4869       // C++ [class.union]p6:
4870       //   A storage class is not allowed in a declaration of an
4871       //   anonymous union in a class scope.
4872       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4873                isa<RecordDecl>(Owner)) {
4874         Diag(DS.getStorageClassSpecLoc(),
4875              diag::err_anonymous_union_with_storage_spec)
4876           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4877 
4878         // Recover by removing the storage specifier.
4879         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4880                                SourceLocation(),
4881                                PrevSpec, DiagID, Context.getPrintingPolicy());
4882       }
4883     }
4884 
4885     // Ignore const/volatile/restrict qualifiers.
4886     if (DS.getTypeQualifiers()) {
4887       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4888         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4889           << Record->isUnion() << "const"
4890           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4891       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4892         Diag(DS.getVolatileSpecLoc(),
4893              diag::ext_anonymous_struct_union_qualified)
4894           << Record->isUnion() << "volatile"
4895           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4896       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4897         Diag(DS.getRestrictSpecLoc(),
4898              diag::ext_anonymous_struct_union_qualified)
4899           << Record->isUnion() << "restrict"
4900           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4901       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4902         Diag(DS.getAtomicSpecLoc(),
4903              diag::ext_anonymous_struct_union_qualified)
4904           << Record->isUnion() << "_Atomic"
4905           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4906       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4907         Diag(DS.getUnalignedSpecLoc(),
4908              diag::ext_anonymous_struct_union_qualified)
4909           << Record->isUnion() << "__unaligned"
4910           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4911 
4912       DS.ClearTypeQualifiers();
4913     }
4914 
4915     // C++ [class.union]p2:
4916     //   The member-specification of an anonymous union shall only
4917     //   define non-static data members. [Note: nested types and
4918     //   functions cannot be declared within an anonymous union. ]
4919     for (auto *Mem : Record->decls()) {
4920       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4921         // C++ [class.union]p3:
4922         //   An anonymous union shall not have private or protected
4923         //   members (clause 11).
4924         assert(FD->getAccess() != AS_none);
4925         if (FD->getAccess() != AS_public) {
4926           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4927             << Record->isUnion() << (FD->getAccess() == AS_protected);
4928           Invalid = true;
4929         }
4930 
4931         // C++ [class.union]p1
4932         //   An object of a class with a non-trivial constructor, a non-trivial
4933         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4934         //   assignment operator cannot be a member of a union, nor can an
4935         //   array of such objects.
4936         if (CheckNontrivialField(FD))
4937           Invalid = true;
4938       } else if (Mem->isImplicit()) {
4939         // Any implicit members are fine.
4940       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4941         // This is a type that showed up in an
4942         // elaborated-type-specifier inside the anonymous struct or
4943         // union, but which actually declares a type outside of the
4944         // anonymous struct or union. It's okay.
4945       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4946         if (!MemRecord->isAnonymousStructOrUnion() &&
4947             MemRecord->getDeclName()) {
4948           // Visual C++ allows type definition in anonymous struct or union.
4949           if (getLangOpts().MicrosoftExt)
4950             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4951               << Record->isUnion();
4952           else {
4953             // This is a nested type declaration.
4954             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4955               << Record->isUnion();
4956             Invalid = true;
4957           }
4958         } else {
4959           // This is an anonymous type definition within another anonymous type.
4960           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4961           // not part of standard C++.
4962           Diag(MemRecord->getLocation(),
4963                diag::ext_anonymous_record_with_anonymous_type)
4964             << Record->isUnion();
4965         }
4966       } else if (isa<AccessSpecDecl>(Mem)) {
4967         // Any access specifier is fine.
4968       } else if (isa<StaticAssertDecl>(Mem)) {
4969         // In C++1z, static_assert declarations are also fine.
4970       } else {
4971         // We have something that isn't a non-static data
4972         // member. Complain about it.
4973         unsigned DK = diag::err_anonymous_record_bad_member;
4974         if (isa<TypeDecl>(Mem))
4975           DK = diag::err_anonymous_record_with_type;
4976         else if (isa<FunctionDecl>(Mem))
4977           DK = diag::err_anonymous_record_with_function;
4978         else if (isa<VarDecl>(Mem))
4979           DK = diag::err_anonymous_record_with_static;
4980 
4981         // Visual C++ allows type definition in anonymous struct or union.
4982         if (getLangOpts().MicrosoftExt &&
4983             DK == diag::err_anonymous_record_with_type)
4984           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4985             << Record->isUnion();
4986         else {
4987           Diag(Mem->getLocation(), DK) << Record->isUnion();
4988           Invalid = true;
4989         }
4990       }
4991     }
4992 
4993     // C++11 [class.union]p8 (DR1460):
4994     //   At most one variant member of a union may have a
4995     //   brace-or-equal-initializer.
4996     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4997         Owner->isRecord())
4998       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4999                                 cast<CXXRecordDecl>(Record));
5000   }
5001 
5002   if (!Record->isUnion() && !Owner->isRecord()) {
5003     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5004       << getLangOpts().CPlusPlus;
5005     Invalid = true;
5006   }
5007 
5008   // C++ [dcl.dcl]p3:
5009   //   [If there are no declarators], and except for the declaration of an
5010   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5011   //   names into the program
5012   // C++ [class.mem]p2:
5013   //   each such member-declaration shall either declare at least one member
5014   //   name of the class or declare at least one unnamed bit-field
5015   //
5016   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5017   if (getLangOpts().CPlusPlus && Record->field_empty())
5018     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5019 
5020   // Mock up a declarator.
5021   Declarator Dc(DS, DeclaratorContext::MemberContext);
5022   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5023   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5024 
5025   // Create a declaration for this anonymous struct/union.
5026   NamedDecl *Anon = nullptr;
5027   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5028     Anon = FieldDecl::Create(
5029         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5030         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5031         /*BitWidth=*/nullptr, /*Mutable=*/false,
5032         /*InitStyle=*/ICIS_NoInit);
5033     Anon->setAccess(AS);
5034     ProcessDeclAttributes(S, Anon, Dc);
5035 
5036     if (getLangOpts().CPlusPlus)
5037       FieldCollector->Add(cast<FieldDecl>(Anon));
5038   } else {
5039     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5040     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5041     if (SCSpec == DeclSpec::SCS_mutable) {
5042       // mutable can only appear on non-static class members, so it's always
5043       // an error here
5044       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5045       Invalid = true;
5046       SC = SC_None;
5047     }
5048 
5049     assert(DS.getAttributes().empty() && "No attribute expected");
5050     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5051                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5052                            Context.getTypeDeclType(Record), TInfo, SC);
5053 
5054     // Default-initialize the implicit variable. This initialization will be
5055     // trivial in almost all cases, except if a union member has an in-class
5056     // initializer:
5057     //   union { int n = 0; };
5058     ActOnUninitializedDecl(Anon);
5059   }
5060   Anon->setImplicit();
5061 
5062   // Mark this as an anonymous struct/union type.
5063   Record->setAnonymousStructOrUnion(true);
5064 
5065   // Add the anonymous struct/union object to the current
5066   // context. We'll be referencing this object when we refer to one of
5067   // its members.
5068   Owner->addDecl(Anon);
5069 
5070   // Inject the members of the anonymous struct/union into the owning
5071   // context and into the identifier resolver chain for name lookup
5072   // purposes.
5073   SmallVector<NamedDecl*, 2> Chain;
5074   Chain.push_back(Anon);
5075 
5076   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5077     Invalid = true;
5078 
5079   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5080     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5081       MangleNumberingContext *MCtx;
5082       Decl *ManglingContextDecl;
5083       std::tie(MCtx, ManglingContextDecl) =
5084           getCurrentMangleNumberContext(NewVD->getDeclContext());
5085       if (MCtx) {
5086         Context.setManglingNumber(
5087             NewVD, MCtx->getManglingNumber(
5088                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5089         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5090       }
5091     }
5092   }
5093 
5094   if (Invalid)
5095     Anon->setInvalidDecl();
5096 
5097   return Anon;
5098 }
5099 
5100 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5101 /// Microsoft C anonymous structure.
5102 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5103 /// Example:
5104 ///
5105 /// struct A { int a; };
5106 /// struct B { struct A; int b; };
5107 ///
5108 /// void foo() {
5109 ///   B var;
5110 ///   var.a = 3;
5111 /// }
5112 ///
5113 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5114                                            RecordDecl *Record) {
5115   assert(Record && "expected a record!");
5116 
5117   // Mock up a declarator.
5118   Declarator Dc(DS, DeclaratorContext::TypeNameContext);
5119   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5120   assert(TInfo && "couldn't build declarator info for anonymous struct");
5121 
5122   auto *ParentDecl = cast<RecordDecl>(CurContext);
5123   QualType RecTy = Context.getTypeDeclType(Record);
5124 
5125   // Create a declaration for this anonymous struct.
5126   NamedDecl *Anon =
5127       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5128                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5129                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5130                         /*InitStyle=*/ICIS_NoInit);
5131   Anon->setImplicit();
5132 
5133   // Add the anonymous struct object to the current context.
5134   CurContext->addDecl(Anon);
5135 
5136   // Inject the members of the anonymous struct into the current
5137   // context and into the identifier resolver chain for name lookup
5138   // purposes.
5139   SmallVector<NamedDecl*, 2> Chain;
5140   Chain.push_back(Anon);
5141 
5142   RecordDecl *RecordDef = Record->getDefinition();
5143   if (RequireCompleteType(Anon->getLocation(), RecTy,
5144                           diag::err_field_incomplete) ||
5145       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5146                                           AS_none, Chain)) {
5147     Anon->setInvalidDecl();
5148     ParentDecl->setInvalidDecl();
5149   }
5150 
5151   return Anon;
5152 }
5153 
5154 /// GetNameForDeclarator - Determine the full declaration name for the
5155 /// given Declarator.
5156 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5157   return GetNameFromUnqualifiedId(D.getName());
5158 }
5159 
5160 /// Retrieves the declaration name from a parsed unqualified-id.
5161 DeclarationNameInfo
5162 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5163   DeclarationNameInfo NameInfo;
5164   NameInfo.setLoc(Name.StartLocation);
5165 
5166   switch (Name.getKind()) {
5167 
5168   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5169   case UnqualifiedIdKind::IK_Identifier:
5170     NameInfo.setName(Name.Identifier);
5171     return NameInfo;
5172 
5173   case UnqualifiedIdKind::IK_DeductionGuideName: {
5174     // C++ [temp.deduct.guide]p3:
5175     //   The simple-template-id shall name a class template specialization.
5176     //   The template-name shall be the same identifier as the template-name
5177     //   of the simple-template-id.
5178     // These together intend to imply that the template-name shall name a
5179     // class template.
5180     // FIXME: template<typename T> struct X {};
5181     //        template<typename T> using Y = X<T>;
5182     //        Y(int) -> Y<int>;
5183     //   satisfies these rules but does not name a class template.
5184     TemplateName TN = Name.TemplateName.get().get();
5185     auto *Template = TN.getAsTemplateDecl();
5186     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5187       Diag(Name.StartLocation,
5188            diag::err_deduction_guide_name_not_class_template)
5189         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5190       if (Template)
5191         Diag(Template->getLocation(), diag::note_template_decl_here);
5192       return DeclarationNameInfo();
5193     }
5194 
5195     NameInfo.setName(
5196         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5197     return NameInfo;
5198   }
5199 
5200   case UnqualifiedIdKind::IK_OperatorFunctionId:
5201     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5202                                            Name.OperatorFunctionId.Operator));
5203     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
5204       = Name.OperatorFunctionId.SymbolLocations[0];
5205     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
5206       = Name.EndLocation.getRawEncoding();
5207     return NameInfo;
5208 
5209   case UnqualifiedIdKind::IK_LiteralOperatorId:
5210     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5211                                                            Name.Identifier));
5212     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5213     return NameInfo;
5214 
5215   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5216     TypeSourceInfo *TInfo;
5217     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5218     if (Ty.isNull())
5219       return DeclarationNameInfo();
5220     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5221                                                Context.getCanonicalType(Ty)));
5222     NameInfo.setNamedTypeInfo(TInfo);
5223     return NameInfo;
5224   }
5225 
5226   case UnqualifiedIdKind::IK_ConstructorName: {
5227     TypeSourceInfo *TInfo;
5228     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5229     if (Ty.isNull())
5230       return DeclarationNameInfo();
5231     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5232                                               Context.getCanonicalType(Ty)));
5233     NameInfo.setNamedTypeInfo(TInfo);
5234     return NameInfo;
5235   }
5236 
5237   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5238     // In well-formed code, we can only have a constructor
5239     // template-id that refers to the current context, so go there
5240     // to find the actual type being constructed.
5241     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5242     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5243       return DeclarationNameInfo();
5244 
5245     // Determine the type of the class being constructed.
5246     QualType CurClassType = Context.getTypeDeclType(CurClass);
5247 
5248     // FIXME: Check two things: that the template-id names the same type as
5249     // CurClassType, and that the template-id does not occur when the name
5250     // was qualified.
5251 
5252     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5253                                     Context.getCanonicalType(CurClassType)));
5254     // FIXME: should we retrieve TypeSourceInfo?
5255     NameInfo.setNamedTypeInfo(nullptr);
5256     return NameInfo;
5257   }
5258 
5259   case UnqualifiedIdKind::IK_DestructorName: {
5260     TypeSourceInfo *TInfo;
5261     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5262     if (Ty.isNull())
5263       return DeclarationNameInfo();
5264     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5265                                               Context.getCanonicalType(Ty)));
5266     NameInfo.setNamedTypeInfo(TInfo);
5267     return NameInfo;
5268   }
5269 
5270   case UnqualifiedIdKind::IK_TemplateId: {
5271     TemplateName TName = Name.TemplateId->Template.get();
5272     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5273     return Context.getNameForTemplate(TName, TNameLoc);
5274   }
5275 
5276   } // switch (Name.getKind())
5277 
5278   llvm_unreachable("Unknown name kind");
5279 }
5280 
5281 static QualType getCoreType(QualType Ty) {
5282   do {
5283     if (Ty->isPointerType() || Ty->isReferenceType())
5284       Ty = Ty->getPointeeType();
5285     else if (Ty->isArrayType())
5286       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5287     else
5288       return Ty.withoutLocalFastQualifiers();
5289   } while (true);
5290 }
5291 
5292 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5293 /// and Definition have "nearly" matching parameters. This heuristic is
5294 /// used to improve diagnostics in the case where an out-of-line function
5295 /// definition doesn't match any declaration within the class or namespace.
5296 /// Also sets Params to the list of indices to the parameters that differ
5297 /// between the declaration and the definition. If hasSimilarParameters
5298 /// returns true and Params is empty, then all of the parameters match.
5299 static bool hasSimilarParameters(ASTContext &Context,
5300                                      FunctionDecl *Declaration,
5301                                      FunctionDecl *Definition,
5302                                      SmallVectorImpl<unsigned> &Params) {
5303   Params.clear();
5304   if (Declaration->param_size() != Definition->param_size())
5305     return false;
5306   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5307     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5308     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5309 
5310     // The parameter types are identical
5311     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5312       continue;
5313 
5314     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5315     QualType DefParamBaseTy = getCoreType(DefParamTy);
5316     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5317     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5318 
5319     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5320         (DeclTyName && DeclTyName == DefTyName))
5321       Params.push_back(Idx);
5322     else  // The two parameters aren't even close
5323       return false;
5324   }
5325 
5326   return true;
5327 }
5328 
5329 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5330 /// declarator needs to be rebuilt in the current instantiation.
5331 /// Any bits of declarator which appear before the name are valid for
5332 /// consideration here.  That's specifically the type in the decl spec
5333 /// and the base type in any member-pointer chunks.
5334 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5335                                                     DeclarationName Name) {
5336   // The types we specifically need to rebuild are:
5337   //   - typenames, typeofs, and decltypes
5338   //   - types which will become injected class names
5339   // Of course, we also need to rebuild any type referencing such a
5340   // type.  It's safest to just say "dependent", but we call out a
5341   // few cases here.
5342 
5343   DeclSpec &DS = D.getMutableDeclSpec();
5344   switch (DS.getTypeSpecType()) {
5345   case DeclSpec::TST_typename:
5346   case DeclSpec::TST_typeofType:
5347   case DeclSpec::TST_underlyingType:
5348   case DeclSpec::TST_atomic: {
5349     // Grab the type from the parser.
5350     TypeSourceInfo *TSI = nullptr;
5351     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5352     if (T.isNull() || !T->isDependentType()) break;
5353 
5354     // Make sure there's a type source info.  This isn't really much
5355     // of a waste; most dependent types should have type source info
5356     // attached already.
5357     if (!TSI)
5358       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5359 
5360     // Rebuild the type in the current instantiation.
5361     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5362     if (!TSI) return true;
5363 
5364     // Store the new type back in the decl spec.
5365     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5366     DS.UpdateTypeRep(LocType);
5367     break;
5368   }
5369 
5370   case DeclSpec::TST_decltype:
5371   case DeclSpec::TST_typeofExpr: {
5372     Expr *E = DS.getRepAsExpr();
5373     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5374     if (Result.isInvalid()) return true;
5375     DS.UpdateExprRep(Result.get());
5376     break;
5377   }
5378 
5379   default:
5380     // Nothing to do for these decl specs.
5381     break;
5382   }
5383 
5384   // It doesn't matter what order we do this in.
5385   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5386     DeclaratorChunk &Chunk = D.getTypeObject(I);
5387 
5388     // The only type information in the declarator which can come
5389     // before the declaration name is the base type of a member
5390     // pointer.
5391     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5392       continue;
5393 
5394     // Rebuild the scope specifier in-place.
5395     CXXScopeSpec &SS = Chunk.Mem.Scope();
5396     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5397       return true;
5398   }
5399 
5400   return false;
5401 }
5402 
5403 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5404   D.setFunctionDefinitionKind(FDK_Declaration);
5405   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5406 
5407   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5408       Dcl && Dcl->getDeclContext()->isFileContext())
5409     Dcl->setTopLevelDeclInObjCContainer();
5410 
5411   if (getLangOpts().OpenCL)
5412     setCurrentOpenCLExtensionForDecl(Dcl);
5413 
5414   return Dcl;
5415 }
5416 
5417 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5418 ///   If T is the name of a class, then each of the following shall have a
5419 ///   name different from T:
5420 ///     - every static data member of class T;
5421 ///     - every member function of class T
5422 ///     - every member of class T that is itself a type;
5423 /// \returns true if the declaration name violates these rules.
5424 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5425                                    DeclarationNameInfo NameInfo) {
5426   DeclarationName Name = NameInfo.getName();
5427 
5428   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5429   while (Record && Record->isAnonymousStructOrUnion())
5430     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5431   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5432     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5433     return true;
5434   }
5435 
5436   return false;
5437 }
5438 
5439 /// Diagnose a declaration whose declarator-id has the given
5440 /// nested-name-specifier.
5441 ///
5442 /// \param SS The nested-name-specifier of the declarator-id.
5443 ///
5444 /// \param DC The declaration context to which the nested-name-specifier
5445 /// resolves.
5446 ///
5447 /// \param Name The name of the entity being declared.
5448 ///
5449 /// \param Loc The location of the name of the entity being declared.
5450 ///
5451 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5452 /// we're declaring an explicit / partial specialization / instantiation.
5453 ///
5454 /// \returns true if we cannot safely recover from this error, false otherwise.
5455 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5456                                         DeclarationName Name,
5457                                         SourceLocation Loc, bool IsTemplateId) {
5458   DeclContext *Cur = CurContext;
5459   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5460     Cur = Cur->getParent();
5461 
5462   // If the user provided a superfluous scope specifier that refers back to the
5463   // class in which the entity is already declared, diagnose and ignore it.
5464   //
5465   // class X {
5466   //   void X::f();
5467   // };
5468   //
5469   // Note, it was once ill-formed to give redundant qualification in all
5470   // contexts, but that rule was removed by DR482.
5471   if (Cur->Equals(DC)) {
5472     if (Cur->isRecord()) {
5473       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5474                                       : diag::err_member_extra_qualification)
5475         << Name << FixItHint::CreateRemoval(SS.getRange());
5476       SS.clear();
5477     } else {
5478       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5479     }
5480     return false;
5481   }
5482 
5483   // Check whether the qualifying scope encloses the scope of the original
5484   // declaration. For a template-id, we perform the checks in
5485   // CheckTemplateSpecializationScope.
5486   if (!Cur->Encloses(DC) && !IsTemplateId) {
5487     if (Cur->isRecord())
5488       Diag(Loc, diag::err_member_qualification)
5489         << Name << SS.getRange();
5490     else if (isa<TranslationUnitDecl>(DC))
5491       Diag(Loc, diag::err_invalid_declarator_global_scope)
5492         << Name << SS.getRange();
5493     else if (isa<FunctionDecl>(Cur))
5494       Diag(Loc, diag::err_invalid_declarator_in_function)
5495         << Name << SS.getRange();
5496     else if (isa<BlockDecl>(Cur))
5497       Diag(Loc, diag::err_invalid_declarator_in_block)
5498         << Name << SS.getRange();
5499     else
5500       Diag(Loc, diag::err_invalid_declarator_scope)
5501       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5502 
5503     return true;
5504   }
5505 
5506   if (Cur->isRecord()) {
5507     // Cannot qualify members within a class.
5508     Diag(Loc, diag::err_member_qualification)
5509       << Name << SS.getRange();
5510     SS.clear();
5511 
5512     // C++ constructors and destructors with incorrect scopes can break
5513     // our AST invariants by having the wrong underlying types. If
5514     // that's the case, then drop this declaration entirely.
5515     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5516          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5517         !Context.hasSameType(Name.getCXXNameType(),
5518                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5519       return true;
5520 
5521     return false;
5522   }
5523 
5524   // C++11 [dcl.meaning]p1:
5525   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5526   //   not begin with a decltype-specifer"
5527   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5528   while (SpecLoc.getPrefix())
5529     SpecLoc = SpecLoc.getPrefix();
5530   if (dyn_cast_or_null<DecltypeType>(
5531         SpecLoc.getNestedNameSpecifier()->getAsType()))
5532     Diag(Loc, diag::err_decltype_in_declarator)
5533       << SpecLoc.getTypeLoc().getSourceRange();
5534 
5535   return false;
5536 }
5537 
5538 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5539                                   MultiTemplateParamsArg TemplateParamLists) {
5540   // TODO: consider using NameInfo for diagnostic.
5541   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5542   DeclarationName Name = NameInfo.getName();
5543 
5544   // All of these full declarators require an identifier.  If it doesn't have
5545   // one, the ParsedFreeStandingDeclSpec action should be used.
5546   if (D.isDecompositionDeclarator()) {
5547     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5548   } else if (!Name) {
5549     if (!D.isInvalidType())  // Reject this if we think it is valid.
5550       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5551           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5552     return nullptr;
5553   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5554     return nullptr;
5555 
5556   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5557   // we find one that is.
5558   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5559          (S->getFlags() & Scope::TemplateParamScope) != 0)
5560     S = S->getParent();
5561 
5562   DeclContext *DC = CurContext;
5563   if (D.getCXXScopeSpec().isInvalid())
5564     D.setInvalidType();
5565   else if (D.getCXXScopeSpec().isSet()) {
5566     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5567                                         UPPC_DeclarationQualifier))
5568       return nullptr;
5569 
5570     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5571     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5572     if (!DC || isa<EnumDecl>(DC)) {
5573       // If we could not compute the declaration context, it's because the
5574       // declaration context is dependent but does not refer to a class,
5575       // class template, or class template partial specialization. Complain
5576       // and return early, to avoid the coming semantic disaster.
5577       Diag(D.getIdentifierLoc(),
5578            diag::err_template_qualified_declarator_no_match)
5579         << D.getCXXScopeSpec().getScopeRep()
5580         << D.getCXXScopeSpec().getRange();
5581       return nullptr;
5582     }
5583     bool IsDependentContext = DC->isDependentContext();
5584 
5585     if (!IsDependentContext &&
5586         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5587       return nullptr;
5588 
5589     // If a class is incomplete, do not parse entities inside it.
5590     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5591       Diag(D.getIdentifierLoc(),
5592            diag::err_member_def_undefined_record)
5593         << Name << DC << D.getCXXScopeSpec().getRange();
5594       return nullptr;
5595     }
5596     if (!D.getDeclSpec().isFriendSpecified()) {
5597       if (diagnoseQualifiedDeclaration(
5598               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5599               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5600         if (DC->isRecord())
5601           return nullptr;
5602 
5603         D.setInvalidType();
5604       }
5605     }
5606 
5607     // Check whether we need to rebuild the type of the given
5608     // declaration in the current instantiation.
5609     if (EnteringContext && IsDependentContext &&
5610         TemplateParamLists.size() != 0) {
5611       ContextRAII SavedContext(*this, DC);
5612       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5613         D.setInvalidType();
5614     }
5615   }
5616 
5617   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5618   QualType R = TInfo->getType();
5619 
5620   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5621                                       UPPC_DeclarationType))
5622     D.setInvalidType();
5623 
5624   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5625                         forRedeclarationInCurContext());
5626 
5627   // See if this is a redefinition of a variable in the same scope.
5628   if (!D.getCXXScopeSpec().isSet()) {
5629     bool IsLinkageLookup = false;
5630     bool CreateBuiltins = false;
5631 
5632     // If the declaration we're planning to build will be a function
5633     // or object with linkage, then look for another declaration with
5634     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5635     //
5636     // If the declaration we're planning to build will be declared with
5637     // external linkage in the translation unit, create any builtin with
5638     // the same name.
5639     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5640       /* Do nothing*/;
5641     else if (CurContext->isFunctionOrMethod() &&
5642              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5643               R->isFunctionType())) {
5644       IsLinkageLookup = true;
5645       CreateBuiltins =
5646           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5647     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5648                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5649       CreateBuiltins = true;
5650 
5651     if (IsLinkageLookup) {
5652       Previous.clear(LookupRedeclarationWithLinkage);
5653       Previous.setRedeclarationKind(ForExternalRedeclaration);
5654     }
5655 
5656     LookupName(Previous, S, CreateBuiltins);
5657   } else { // Something like "int foo::x;"
5658     LookupQualifiedName(Previous, DC);
5659 
5660     // C++ [dcl.meaning]p1:
5661     //   When the declarator-id is qualified, the declaration shall refer to a
5662     //  previously declared member of the class or namespace to which the
5663     //  qualifier refers (or, in the case of a namespace, of an element of the
5664     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5665     //  thereof; [...]
5666     //
5667     // Note that we already checked the context above, and that we do not have
5668     // enough information to make sure that Previous contains the declaration
5669     // we want to match. For example, given:
5670     //
5671     //   class X {
5672     //     void f();
5673     //     void f(float);
5674     //   };
5675     //
5676     //   void X::f(int) { } // ill-formed
5677     //
5678     // In this case, Previous will point to the overload set
5679     // containing the two f's declared in X, but neither of them
5680     // matches.
5681 
5682     // C++ [dcl.meaning]p1:
5683     //   [...] the member shall not merely have been introduced by a
5684     //   using-declaration in the scope of the class or namespace nominated by
5685     //   the nested-name-specifier of the declarator-id.
5686     RemoveUsingDecls(Previous);
5687   }
5688 
5689   if (Previous.isSingleResult() &&
5690       Previous.getFoundDecl()->isTemplateParameter()) {
5691     // Maybe we will complain about the shadowed template parameter.
5692     if (!D.isInvalidType())
5693       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5694                                       Previous.getFoundDecl());
5695 
5696     // Just pretend that we didn't see the previous declaration.
5697     Previous.clear();
5698   }
5699 
5700   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5701     // Forget that the previous declaration is the injected-class-name.
5702     Previous.clear();
5703 
5704   // In C++, the previous declaration we find might be a tag type
5705   // (class or enum). In this case, the new declaration will hide the
5706   // tag type. Note that this applies to functions, function templates, and
5707   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5708   if (Previous.isSingleTagDecl() &&
5709       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5710       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5711     Previous.clear();
5712 
5713   // Check that there are no default arguments other than in the parameters
5714   // of a function declaration (C++ only).
5715   if (getLangOpts().CPlusPlus)
5716     CheckExtraCXXDefaultArguments(D);
5717 
5718   NamedDecl *New;
5719 
5720   bool AddToScope = true;
5721   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5722     if (TemplateParamLists.size()) {
5723       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5724       return nullptr;
5725     }
5726 
5727     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5728   } else if (R->isFunctionType()) {
5729     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5730                                   TemplateParamLists,
5731                                   AddToScope);
5732   } else {
5733     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5734                                   AddToScope);
5735   }
5736 
5737   if (!New)
5738     return nullptr;
5739 
5740   // If this has an identifier and is not a function template specialization,
5741   // add it to the scope stack.
5742   if (New->getDeclName() && AddToScope)
5743     PushOnScopeChains(New, S);
5744 
5745   if (isInOpenMPDeclareTargetContext())
5746     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5747 
5748   return New;
5749 }
5750 
5751 /// Helper method to turn variable array types into constant array
5752 /// types in certain situations which would otherwise be errors (for
5753 /// GCC compatibility).
5754 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5755                                                     ASTContext &Context,
5756                                                     bool &SizeIsNegative,
5757                                                     llvm::APSInt &Oversized) {
5758   // This method tries to turn a variable array into a constant
5759   // array even when the size isn't an ICE.  This is necessary
5760   // for compatibility with code that depends on gcc's buggy
5761   // constant expression folding, like struct {char x[(int)(char*)2];}
5762   SizeIsNegative = false;
5763   Oversized = 0;
5764 
5765   if (T->isDependentType())
5766     return QualType();
5767 
5768   QualifierCollector Qs;
5769   const Type *Ty = Qs.strip(T);
5770 
5771   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5772     QualType Pointee = PTy->getPointeeType();
5773     QualType FixedType =
5774         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5775                                             Oversized);
5776     if (FixedType.isNull()) return FixedType;
5777     FixedType = Context.getPointerType(FixedType);
5778     return Qs.apply(Context, FixedType);
5779   }
5780   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5781     QualType Inner = PTy->getInnerType();
5782     QualType FixedType =
5783         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5784                                             Oversized);
5785     if (FixedType.isNull()) return FixedType;
5786     FixedType = Context.getParenType(FixedType);
5787     return Qs.apply(Context, FixedType);
5788   }
5789 
5790   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5791   if (!VLATy)
5792     return QualType();
5793   // FIXME: We should probably handle this case
5794   if (VLATy->getElementType()->isVariablyModifiedType())
5795     return QualType();
5796 
5797   Expr::EvalResult Result;
5798   if (!VLATy->getSizeExpr() ||
5799       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5800     return QualType();
5801 
5802   llvm::APSInt Res = Result.Val.getInt();
5803 
5804   // Check whether the array size is negative.
5805   if (Res.isSigned() && Res.isNegative()) {
5806     SizeIsNegative = true;
5807     return QualType();
5808   }
5809 
5810   // Check whether the array is too large to be addressed.
5811   unsigned ActiveSizeBits
5812     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5813                                               Res);
5814   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5815     Oversized = Res;
5816     return QualType();
5817   }
5818 
5819   return Context.getConstantArrayType(
5820       VLATy->getElementType(), Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
5821 }
5822 
5823 static void
5824 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5825   SrcTL = SrcTL.getUnqualifiedLoc();
5826   DstTL = DstTL.getUnqualifiedLoc();
5827   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5828     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5829     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5830                                       DstPTL.getPointeeLoc());
5831     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5832     return;
5833   }
5834   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5835     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5836     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5837                                       DstPTL.getInnerLoc());
5838     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5839     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5840     return;
5841   }
5842   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5843   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5844   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5845   TypeLoc DstElemTL = DstATL.getElementLoc();
5846   DstElemTL.initializeFullCopy(SrcElemTL);
5847   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5848   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5849   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5850 }
5851 
5852 /// Helper method to turn variable array types into constant array
5853 /// types in certain situations which would otherwise be errors (for
5854 /// GCC compatibility).
5855 static TypeSourceInfo*
5856 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5857                                               ASTContext &Context,
5858                                               bool &SizeIsNegative,
5859                                               llvm::APSInt &Oversized) {
5860   QualType FixedTy
5861     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5862                                           SizeIsNegative, Oversized);
5863   if (FixedTy.isNull())
5864     return nullptr;
5865   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5866   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5867                                     FixedTInfo->getTypeLoc());
5868   return FixedTInfo;
5869 }
5870 
5871 /// Register the given locally-scoped extern "C" declaration so
5872 /// that it can be found later for redeclarations. We include any extern "C"
5873 /// declaration that is not visible in the translation unit here, not just
5874 /// function-scope declarations.
5875 void
5876 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5877   if (!getLangOpts().CPlusPlus &&
5878       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5879     // Don't need to track declarations in the TU in C.
5880     return;
5881 
5882   // Note that we have a locally-scoped external with this name.
5883   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5884 }
5885 
5886 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5887   // FIXME: We can have multiple results via __attribute__((overloadable)).
5888   auto Result = Context.getExternCContextDecl()->lookup(Name);
5889   return Result.empty() ? nullptr : *Result.begin();
5890 }
5891 
5892 /// Diagnose function specifiers on a declaration of an identifier that
5893 /// does not identify a function.
5894 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5895   // FIXME: We should probably indicate the identifier in question to avoid
5896   // confusion for constructs like "virtual int a(), b;"
5897   if (DS.isVirtualSpecified())
5898     Diag(DS.getVirtualSpecLoc(),
5899          diag::err_virtual_non_function);
5900 
5901   if (DS.hasExplicitSpecifier())
5902     Diag(DS.getExplicitSpecLoc(),
5903          diag::err_explicit_non_function);
5904 
5905   if (DS.isNoreturnSpecified())
5906     Diag(DS.getNoreturnSpecLoc(),
5907          diag::err_noreturn_non_function);
5908 }
5909 
5910 NamedDecl*
5911 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5912                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5913   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5914   if (D.getCXXScopeSpec().isSet()) {
5915     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5916       << D.getCXXScopeSpec().getRange();
5917     D.setInvalidType();
5918     // Pretend we didn't see the scope specifier.
5919     DC = CurContext;
5920     Previous.clear();
5921   }
5922 
5923   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5924 
5925   if (D.getDeclSpec().isInlineSpecified())
5926     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5927         << getLangOpts().CPlusPlus17;
5928   if (D.getDeclSpec().hasConstexprSpecifier())
5929     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5930         << 1 << D.getDeclSpec().getConstexprSpecifier();
5931 
5932   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
5933     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
5934       Diag(D.getName().StartLocation,
5935            diag::err_deduction_guide_invalid_specifier)
5936           << "typedef";
5937     else
5938       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5939           << D.getName().getSourceRange();
5940     return nullptr;
5941   }
5942 
5943   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5944   if (!NewTD) return nullptr;
5945 
5946   // Handle attributes prior to checking for duplicates in MergeVarDecl
5947   ProcessDeclAttributes(S, NewTD, D);
5948 
5949   CheckTypedefForVariablyModifiedType(S, NewTD);
5950 
5951   bool Redeclaration = D.isRedeclaration();
5952   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5953   D.setRedeclaration(Redeclaration);
5954   return ND;
5955 }
5956 
5957 void
5958 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5959   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5960   // then it shall have block scope.
5961   // Note that variably modified types must be fixed before merging the decl so
5962   // that redeclarations will match.
5963   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5964   QualType T = TInfo->getType();
5965   if (T->isVariablyModifiedType()) {
5966     setFunctionHasBranchProtectedScope();
5967 
5968     if (S->getFnParent() == nullptr) {
5969       bool SizeIsNegative;
5970       llvm::APSInt Oversized;
5971       TypeSourceInfo *FixedTInfo =
5972         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5973                                                       SizeIsNegative,
5974                                                       Oversized);
5975       if (FixedTInfo) {
5976         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5977         NewTD->setTypeSourceInfo(FixedTInfo);
5978       } else {
5979         if (SizeIsNegative)
5980           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5981         else if (T->isVariableArrayType())
5982           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5983         else if (Oversized.getBoolValue())
5984           Diag(NewTD->getLocation(), diag::err_array_too_large)
5985             << Oversized.toString(10);
5986         else
5987           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5988         NewTD->setInvalidDecl();
5989       }
5990     }
5991   }
5992 }
5993 
5994 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5995 /// declares a typedef-name, either using the 'typedef' type specifier or via
5996 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5997 NamedDecl*
5998 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5999                            LookupResult &Previous, bool &Redeclaration) {
6000 
6001   // Find the shadowed declaration before filtering for scope.
6002   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6003 
6004   // Merge the decl with the existing one if appropriate. If the decl is
6005   // in an outer scope, it isn't the same thing.
6006   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6007                        /*AllowInlineNamespace*/false);
6008   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6009   if (!Previous.empty()) {
6010     Redeclaration = true;
6011     MergeTypedefNameDecl(S, NewTD, Previous);
6012   } else {
6013     inferGslPointerAttribute(NewTD);
6014   }
6015 
6016   if (ShadowedDecl && !Redeclaration)
6017     CheckShadow(NewTD, ShadowedDecl, Previous);
6018 
6019   // If this is the C FILE type, notify the AST context.
6020   if (IdentifierInfo *II = NewTD->getIdentifier())
6021     if (!NewTD->isInvalidDecl() &&
6022         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6023       if (II->isStr("FILE"))
6024         Context.setFILEDecl(NewTD);
6025       else if (II->isStr("jmp_buf"))
6026         Context.setjmp_bufDecl(NewTD);
6027       else if (II->isStr("sigjmp_buf"))
6028         Context.setsigjmp_bufDecl(NewTD);
6029       else if (II->isStr("ucontext_t"))
6030         Context.setucontext_tDecl(NewTD);
6031     }
6032 
6033   return NewTD;
6034 }
6035 
6036 /// Determines whether the given declaration is an out-of-scope
6037 /// previous declaration.
6038 ///
6039 /// This routine should be invoked when name lookup has found a
6040 /// previous declaration (PrevDecl) that is not in the scope where a
6041 /// new declaration by the same name is being introduced. If the new
6042 /// declaration occurs in a local scope, previous declarations with
6043 /// linkage may still be considered previous declarations (C99
6044 /// 6.2.2p4-5, C++ [basic.link]p6).
6045 ///
6046 /// \param PrevDecl the previous declaration found by name
6047 /// lookup
6048 ///
6049 /// \param DC the context in which the new declaration is being
6050 /// declared.
6051 ///
6052 /// \returns true if PrevDecl is an out-of-scope previous declaration
6053 /// for a new delcaration with the same name.
6054 static bool
6055 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6056                                 ASTContext &Context) {
6057   if (!PrevDecl)
6058     return false;
6059 
6060   if (!PrevDecl->hasLinkage())
6061     return false;
6062 
6063   if (Context.getLangOpts().CPlusPlus) {
6064     // C++ [basic.link]p6:
6065     //   If there is a visible declaration of an entity with linkage
6066     //   having the same name and type, ignoring entities declared
6067     //   outside the innermost enclosing namespace scope, the block
6068     //   scope declaration declares that same entity and receives the
6069     //   linkage of the previous declaration.
6070     DeclContext *OuterContext = DC->getRedeclContext();
6071     if (!OuterContext->isFunctionOrMethod())
6072       // This rule only applies to block-scope declarations.
6073       return false;
6074 
6075     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6076     if (PrevOuterContext->isRecord())
6077       // We found a member function: ignore it.
6078       return false;
6079 
6080     // Find the innermost enclosing namespace for the new and
6081     // previous declarations.
6082     OuterContext = OuterContext->getEnclosingNamespaceContext();
6083     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6084 
6085     // The previous declaration is in a different namespace, so it
6086     // isn't the same function.
6087     if (!OuterContext->Equals(PrevOuterContext))
6088       return false;
6089   }
6090 
6091   return true;
6092 }
6093 
6094 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6095   CXXScopeSpec &SS = D.getCXXScopeSpec();
6096   if (!SS.isSet()) return;
6097   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6098 }
6099 
6100 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6101   QualType type = decl->getType();
6102   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6103   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6104     // Various kinds of declaration aren't allowed to be __autoreleasing.
6105     unsigned kind = -1U;
6106     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6107       if (var->hasAttr<BlocksAttr>())
6108         kind = 0; // __block
6109       else if (!var->hasLocalStorage())
6110         kind = 1; // global
6111     } else if (isa<ObjCIvarDecl>(decl)) {
6112       kind = 3; // ivar
6113     } else if (isa<FieldDecl>(decl)) {
6114       kind = 2; // field
6115     }
6116 
6117     if (kind != -1U) {
6118       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6119         << kind;
6120     }
6121   } else if (lifetime == Qualifiers::OCL_None) {
6122     // Try to infer lifetime.
6123     if (!type->isObjCLifetimeType())
6124       return false;
6125 
6126     lifetime = type->getObjCARCImplicitLifetime();
6127     type = Context.getLifetimeQualifiedType(type, lifetime);
6128     decl->setType(type);
6129   }
6130 
6131   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6132     // Thread-local variables cannot have lifetime.
6133     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6134         var->getTLSKind()) {
6135       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6136         << var->getType();
6137       return true;
6138     }
6139   }
6140 
6141   return false;
6142 }
6143 
6144 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6145   if (Decl->getType().hasAddressSpace())
6146     return;
6147   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6148     QualType Type = Var->getType();
6149     if (Type->isSamplerT() || Type->isVoidType())
6150       return;
6151     LangAS ImplAS = LangAS::opencl_private;
6152     if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) &&
6153         Var->hasGlobalStorage())
6154       ImplAS = LangAS::opencl_global;
6155     // If the original type from a decayed type is an array type and that array
6156     // type has no address space yet, deduce it now.
6157     if (auto DT = dyn_cast<DecayedType>(Type)) {
6158       auto OrigTy = DT->getOriginalType();
6159       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6160         // Add the address space to the original array type and then propagate
6161         // that to the element type through `getAsArrayType`.
6162         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6163         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6164         // Re-generate the decayed type.
6165         Type = Context.getDecayedType(OrigTy);
6166       }
6167     }
6168     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6169     // Apply any qualifiers (including address space) from the array type to
6170     // the element type. This implements C99 6.7.3p8: "If the specification of
6171     // an array type includes any type qualifiers, the element type is so
6172     // qualified, not the array type."
6173     if (Type->isArrayType())
6174       Type = QualType(Context.getAsArrayType(Type), 0);
6175     Decl->setType(Type);
6176   }
6177 }
6178 
6179 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6180   // Ensure that an auto decl is deduced otherwise the checks below might cache
6181   // the wrong linkage.
6182   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6183 
6184   // 'weak' only applies to declarations with external linkage.
6185   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6186     if (!ND.isExternallyVisible()) {
6187       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6188       ND.dropAttr<WeakAttr>();
6189     }
6190   }
6191   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6192     if (ND.isExternallyVisible()) {
6193       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6194       ND.dropAttr<WeakRefAttr>();
6195       ND.dropAttr<AliasAttr>();
6196     }
6197   }
6198 
6199   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6200     if (VD->hasInit()) {
6201       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6202         assert(VD->isThisDeclarationADefinition() &&
6203                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6204         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6205         VD->dropAttr<AliasAttr>();
6206       }
6207     }
6208   }
6209 
6210   // 'selectany' only applies to externally visible variable declarations.
6211   // It does not apply to functions.
6212   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6213     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6214       S.Diag(Attr->getLocation(),
6215              diag::err_attribute_selectany_non_extern_data);
6216       ND.dropAttr<SelectAnyAttr>();
6217     }
6218   }
6219 
6220   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6221     auto *VD = dyn_cast<VarDecl>(&ND);
6222     bool IsAnonymousNS = false;
6223     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6224     if (VD) {
6225       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6226       while (NS && !IsAnonymousNS) {
6227         IsAnonymousNS = NS->isAnonymousNamespace();
6228         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6229       }
6230     }
6231     // dll attributes require external linkage. Static locals may have external
6232     // linkage but still cannot be explicitly imported or exported.
6233     // In Microsoft mode, a variable defined in anonymous namespace must have
6234     // external linkage in order to be exported.
6235     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6236     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6237         (!AnonNSInMicrosoftMode &&
6238          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6239       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6240         << &ND << Attr;
6241       ND.setInvalidDecl();
6242     }
6243   }
6244 
6245   // Virtual functions cannot be marked as 'notail'.
6246   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
6247     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
6248       if (MD->isVirtual()) {
6249         S.Diag(ND.getLocation(),
6250                diag::err_invalid_attribute_on_virtual_function)
6251             << Attr;
6252         ND.dropAttr<NotTailCalledAttr>();
6253       }
6254 
6255   // Check the attributes on the function type, if any.
6256   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6257     // Don't declare this variable in the second operand of the for-statement;
6258     // GCC miscompiles that by ending its lifetime before evaluating the
6259     // third operand. See gcc.gnu.org/PR86769.
6260     AttributedTypeLoc ATL;
6261     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6262          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6263          TL = ATL.getModifiedLoc()) {
6264       // The [[lifetimebound]] attribute can be applied to the implicit object
6265       // parameter of a non-static member function (other than a ctor or dtor)
6266       // by applying it to the function type.
6267       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6268         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6269         if (!MD || MD->isStatic()) {
6270           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6271               << !MD << A->getRange();
6272         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6273           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6274               << isa<CXXDestructorDecl>(MD) << A->getRange();
6275         }
6276       }
6277     }
6278   }
6279 }
6280 
6281 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6282                                            NamedDecl *NewDecl,
6283                                            bool IsSpecialization,
6284                                            bool IsDefinition) {
6285   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6286     return;
6287 
6288   bool IsTemplate = false;
6289   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6290     OldDecl = OldTD->getTemplatedDecl();
6291     IsTemplate = true;
6292     if (!IsSpecialization)
6293       IsDefinition = false;
6294   }
6295   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6296     NewDecl = NewTD->getTemplatedDecl();
6297     IsTemplate = true;
6298   }
6299 
6300   if (!OldDecl || !NewDecl)
6301     return;
6302 
6303   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6304   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6305   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6306   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6307 
6308   // dllimport and dllexport are inheritable attributes so we have to exclude
6309   // inherited attribute instances.
6310   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6311                     (NewExportAttr && !NewExportAttr->isInherited());
6312 
6313   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6314   // the only exception being explicit specializations.
6315   // Implicitly generated declarations are also excluded for now because there
6316   // is no other way to switch these to use dllimport or dllexport.
6317   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6318 
6319   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6320     // Allow with a warning for free functions and global variables.
6321     bool JustWarn = false;
6322     if (!OldDecl->isCXXClassMember()) {
6323       auto *VD = dyn_cast<VarDecl>(OldDecl);
6324       if (VD && !VD->getDescribedVarTemplate())
6325         JustWarn = true;
6326       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6327       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6328         JustWarn = true;
6329     }
6330 
6331     // We cannot change a declaration that's been used because IR has already
6332     // been emitted. Dllimported functions will still work though (modulo
6333     // address equality) as they can use the thunk.
6334     if (OldDecl->isUsed())
6335       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6336         JustWarn = false;
6337 
6338     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6339                                : diag::err_attribute_dll_redeclaration;
6340     S.Diag(NewDecl->getLocation(), DiagID)
6341         << NewDecl
6342         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6343     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6344     if (!JustWarn) {
6345       NewDecl->setInvalidDecl();
6346       return;
6347     }
6348   }
6349 
6350   // A redeclaration is not allowed to drop a dllimport attribute, the only
6351   // exceptions being inline function definitions (except for function
6352   // templates), local extern declarations, qualified friend declarations or
6353   // special MSVC extension: in the last case, the declaration is treated as if
6354   // it were marked dllexport.
6355   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6356   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6357   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6358     // Ignore static data because out-of-line definitions are diagnosed
6359     // separately.
6360     IsStaticDataMember = VD->isStaticDataMember();
6361     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6362                    VarDecl::DeclarationOnly;
6363   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6364     IsInline = FD->isInlined();
6365     IsQualifiedFriend = FD->getQualifier() &&
6366                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6367   }
6368 
6369   if (OldImportAttr && !HasNewAttr &&
6370       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6371       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6372     if (IsMicrosoft && IsDefinition) {
6373       S.Diag(NewDecl->getLocation(),
6374              diag::warn_redeclaration_without_import_attribute)
6375           << NewDecl;
6376       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6377       NewDecl->dropAttr<DLLImportAttr>();
6378       NewDecl->addAttr(
6379           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6380     } else {
6381       S.Diag(NewDecl->getLocation(),
6382              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6383           << NewDecl << OldImportAttr;
6384       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6385       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6386       OldDecl->dropAttr<DLLImportAttr>();
6387       NewDecl->dropAttr<DLLImportAttr>();
6388     }
6389   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6390     // In MinGW, seeing a function declared inline drops the dllimport
6391     // attribute.
6392     OldDecl->dropAttr<DLLImportAttr>();
6393     NewDecl->dropAttr<DLLImportAttr>();
6394     S.Diag(NewDecl->getLocation(),
6395            diag::warn_dllimport_dropped_from_inline_function)
6396         << NewDecl << OldImportAttr;
6397   }
6398 
6399   // A specialization of a class template member function is processed here
6400   // since it's a redeclaration. If the parent class is dllexport, the
6401   // specialization inherits that attribute. This doesn't happen automatically
6402   // since the parent class isn't instantiated until later.
6403   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6404     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6405         !NewImportAttr && !NewExportAttr) {
6406       if (const DLLExportAttr *ParentExportAttr =
6407               MD->getParent()->getAttr<DLLExportAttr>()) {
6408         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6409         NewAttr->setInherited(true);
6410         NewDecl->addAttr(NewAttr);
6411       }
6412     }
6413   }
6414 }
6415 
6416 /// Given that we are within the definition of the given function,
6417 /// will that definition behave like C99's 'inline', where the
6418 /// definition is discarded except for optimization purposes?
6419 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6420   // Try to avoid calling GetGVALinkageForFunction.
6421 
6422   // All cases of this require the 'inline' keyword.
6423   if (!FD->isInlined()) return false;
6424 
6425   // This is only possible in C++ with the gnu_inline attribute.
6426   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6427     return false;
6428 
6429   // Okay, go ahead and call the relatively-more-expensive function.
6430   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6431 }
6432 
6433 /// Determine whether a variable is extern "C" prior to attaching
6434 /// an initializer. We can't just call isExternC() here, because that
6435 /// will also compute and cache whether the declaration is externally
6436 /// visible, which might change when we attach the initializer.
6437 ///
6438 /// This can only be used if the declaration is known to not be a
6439 /// redeclaration of an internal linkage declaration.
6440 ///
6441 /// For instance:
6442 ///
6443 ///   auto x = []{};
6444 ///
6445 /// Attaching the initializer here makes this declaration not externally
6446 /// visible, because its type has internal linkage.
6447 ///
6448 /// FIXME: This is a hack.
6449 template<typename T>
6450 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6451   if (S.getLangOpts().CPlusPlus) {
6452     // In C++, the overloadable attribute negates the effects of extern "C".
6453     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6454       return false;
6455 
6456     // So do CUDA's host/device attributes.
6457     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6458                                  D->template hasAttr<CUDAHostAttr>()))
6459       return false;
6460   }
6461   return D->isExternC();
6462 }
6463 
6464 static bool shouldConsiderLinkage(const VarDecl *VD) {
6465   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6466   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6467       isa<OMPDeclareMapperDecl>(DC))
6468     return VD->hasExternalStorage();
6469   if (DC->isFileContext())
6470     return true;
6471   if (DC->isRecord())
6472     return false;
6473   if (isa<RequiresExprBodyDecl>(DC))
6474     return false;
6475   llvm_unreachable("Unexpected context");
6476 }
6477 
6478 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6479   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6480   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6481       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6482     return true;
6483   if (DC->isRecord())
6484     return false;
6485   llvm_unreachable("Unexpected context");
6486 }
6487 
6488 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6489                           ParsedAttr::Kind Kind) {
6490   // Check decl attributes on the DeclSpec.
6491   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6492     return true;
6493 
6494   // Walk the declarator structure, checking decl attributes that were in a type
6495   // position to the decl itself.
6496   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6497     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6498       return true;
6499   }
6500 
6501   // Finally, check attributes on the decl itself.
6502   return PD.getAttributes().hasAttribute(Kind);
6503 }
6504 
6505 /// Adjust the \c DeclContext for a function or variable that might be a
6506 /// function-local external declaration.
6507 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6508   if (!DC->isFunctionOrMethod())
6509     return false;
6510 
6511   // If this is a local extern function or variable declared within a function
6512   // template, don't add it into the enclosing namespace scope until it is
6513   // instantiated; it might have a dependent type right now.
6514   if (DC->isDependentContext())
6515     return true;
6516 
6517   // C++11 [basic.link]p7:
6518   //   When a block scope declaration of an entity with linkage is not found to
6519   //   refer to some other declaration, then that entity is a member of the
6520   //   innermost enclosing namespace.
6521   //
6522   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6523   // semantically-enclosing namespace, not a lexically-enclosing one.
6524   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6525     DC = DC->getParent();
6526   return true;
6527 }
6528 
6529 /// Returns true if given declaration has external C language linkage.
6530 static bool isDeclExternC(const Decl *D) {
6531   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6532     return FD->isExternC();
6533   if (const auto *VD = dyn_cast<VarDecl>(D))
6534     return VD->isExternC();
6535 
6536   llvm_unreachable("Unknown type of decl!");
6537 }
6538 /// Returns true if there hasn't been any invalid type diagnosed.
6539 static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D,
6540                                 DeclContext *DC, QualType R) {
6541   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6542   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6543   // argument.
6544   if (R->isImageType() || R->isPipeType()) {
6545     Se.Diag(D.getIdentifierLoc(),
6546             diag::err_opencl_type_can_only_be_used_as_function_parameter)
6547         << R;
6548     D.setInvalidType();
6549     return false;
6550   }
6551 
6552   // OpenCL v1.2 s6.9.r:
6553   // The event type cannot be used to declare a program scope variable.
6554   // OpenCL v2.0 s6.9.q:
6555   // The clk_event_t and reserve_id_t types cannot be declared in program
6556   // scope.
6557   if (NULL == S->getParent()) {
6558     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6559       Se.Diag(D.getIdentifierLoc(),
6560               diag::err_invalid_type_for_program_scope_var)
6561           << R;
6562       D.setInvalidType();
6563       return false;
6564     }
6565   }
6566 
6567   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6568   QualType NR = R;
6569   while (NR->isPointerType()) {
6570     if (NR->isFunctionPointerType()) {
6571       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6572       D.setInvalidType();
6573       return false;
6574     }
6575     NR = NR->getPointeeType();
6576   }
6577 
6578   if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6579     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6580     // half array type (unless the cl_khr_fp16 extension is enabled).
6581     if (Se.Context.getBaseElementType(R)->isHalfType()) {
6582       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6583       D.setInvalidType();
6584       return false;
6585     }
6586   }
6587 
6588   // OpenCL v1.2 s6.9.r:
6589   // The event type cannot be used with the __local, __constant and __global
6590   // address space qualifiers.
6591   if (R->isEventT()) {
6592     if (R.getAddressSpace() != LangAS::opencl_private) {
6593       Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6594       D.setInvalidType();
6595       return false;
6596     }
6597   }
6598 
6599   // C++ for OpenCL does not allow the thread_local storage qualifier.
6600   // OpenCL C does not support thread_local either, and
6601   // also reject all other thread storage class specifiers.
6602   DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6603   if (TSC != TSCS_unspecified) {
6604     bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus;
6605     Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6606             diag::err_opencl_unknown_type_specifier)
6607         << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString()
6608         << DeclSpec::getSpecifierName(TSC) << 1;
6609     D.setInvalidType();
6610     return false;
6611   }
6612 
6613   if (R->isSamplerT()) {
6614     // OpenCL v1.2 s6.9.b p4:
6615     // The sampler type cannot be used with the __local and __global address
6616     // space qualifiers.
6617     if (R.getAddressSpace() == LangAS::opencl_local ||
6618         R.getAddressSpace() == LangAS::opencl_global) {
6619       Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6620       D.setInvalidType();
6621     }
6622 
6623     // OpenCL v1.2 s6.12.14.1:
6624     // A global sampler must be declared with either the constant address
6625     // space qualifier or with the const qualifier.
6626     if (DC->isTranslationUnit() &&
6627         !(R.getAddressSpace() == LangAS::opencl_constant ||
6628           R.isConstQualified())) {
6629       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6630       D.setInvalidType();
6631     }
6632     if (D.isInvalidType())
6633       return false;
6634   }
6635   return true;
6636 }
6637 
6638 NamedDecl *Sema::ActOnVariableDeclarator(
6639     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6640     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6641     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6642   QualType R = TInfo->getType();
6643   DeclarationName Name = GetNameForDeclarator(D).getName();
6644 
6645   IdentifierInfo *II = Name.getAsIdentifierInfo();
6646 
6647   if (D.isDecompositionDeclarator()) {
6648     // Take the name of the first declarator as our name for diagnostic
6649     // purposes.
6650     auto &Decomp = D.getDecompositionDeclarator();
6651     if (!Decomp.bindings().empty()) {
6652       II = Decomp.bindings()[0].Name;
6653       Name = II;
6654     }
6655   } else if (!II) {
6656     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6657     return nullptr;
6658   }
6659 
6660 
6661   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6662   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6663 
6664   // dllimport globals without explicit storage class are treated as extern. We
6665   // have to change the storage class this early to get the right DeclContext.
6666   if (SC == SC_None && !DC->isRecord() &&
6667       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6668       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6669     SC = SC_Extern;
6670 
6671   DeclContext *OriginalDC = DC;
6672   bool IsLocalExternDecl = SC == SC_Extern &&
6673                            adjustContextForLocalExternDecl(DC);
6674 
6675   if (SCSpec == DeclSpec::SCS_mutable) {
6676     // mutable can only appear on non-static class members, so it's always
6677     // an error here
6678     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6679     D.setInvalidType();
6680     SC = SC_None;
6681   }
6682 
6683   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6684       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6685                               D.getDeclSpec().getStorageClassSpecLoc())) {
6686     // In C++11, the 'register' storage class specifier is deprecated.
6687     // Suppress the warning in system macros, it's used in macros in some
6688     // popular C system headers, such as in glibc's htonl() macro.
6689     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6690          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6691                                    : diag::warn_deprecated_register)
6692       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6693   }
6694 
6695   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6696 
6697   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6698     // C99 6.9p2: The storage-class specifiers auto and register shall not
6699     // appear in the declaration specifiers in an external declaration.
6700     // Global Register+Asm is a GNU extension we support.
6701     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6702       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6703       D.setInvalidType();
6704     }
6705   }
6706 
6707   bool IsMemberSpecialization = false;
6708   bool IsVariableTemplateSpecialization = false;
6709   bool IsPartialSpecialization = false;
6710   bool IsVariableTemplate = false;
6711   VarDecl *NewVD = nullptr;
6712   VarTemplateDecl *NewTemplate = nullptr;
6713   TemplateParameterList *TemplateParams = nullptr;
6714   if (!getLangOpts().CPlusPlus) {
6715     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6716                             II, R, TInfo, SC);
6717 
6718     if (R->getContainedDeducedType())
6719       ParsingInitForAutoVars.insert(NewVD);
6720 
6721     if (D.isInvalidType())
6722       NewVD->setInvalidDecl();
6723 
6724     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
6725         NewVD->hasLocalStorage())
6726       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
6727                             NTCUC_AutoVar, NTCUK_Destruct);
6728   } else {
6729     bool Invalid = false;
6730 
6731     if (DC->isRecord() && !CurContext->isRecord()) {
6732       // This is an out-of-line definition of a static data member.
6733       switch (SC) {
6734       case SC_None:
6735         break;
6736       case SC_Static:
6737         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6738              diag::err_static_out_of_line)
6739           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6740         break;
6741       case SC_Auto:
6742       case SC_Register:
6743       case SC_Extern:
6744         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6745         // to names of variables declared in a block or to function parameters.
6746         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6747         // of class members
6748 
6749         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6750              diag::err_storage_class_for_static_member)
6751           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6752         break;
6753       case SC_PrivateExtern:
6754         llvm_unreachable("C storage class in c++!");
6755       }
6756     }
6757 
6758     if (SC == SC_Static && CurContext->isRecord()) {
6759       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6760         if (RD->isLocalClass())
6761           Diag(D.getIdentifierLoc(),
6762                diag::err_static_data_member_not_allowed_in_local_class)
6763             << Name << RD->getDeclName();
6764 
6765         // C++98 [class.union]p1: If a union contains a static data member,
6766         // the program is ill-formed. C++11 drops this restriction.
6767         if (RD->isUnion())
6768           Diag(D.getIdentifierLoc(),
6769                getLangOpts().CPlusPlus11
6770                  ? diag::warn_cxx98_compat_static_data_member_in_union
6771                  : diag::ext_static_data_member_in_union) << Name;
6772         // We conservatively disallow static data members in anonymous structs.
6773         else if (!RD->getDeclName())
6774           Diag(D.getIdentifierLoc(),
6775                diag::err_static_data_member_not_allowed_in_anon_struct)
6776             << Name << RD->isUnion();
6777       }
6778     }
6779 
6780     // Match up the template parameter lists with the scope specifier, then
6781     // determine whether we have a template or a template specialization.
6782     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6783         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6784         D.getCXXScopeSpec(),
6785         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6786             ? D.getName().TemplateId
6787             : nullptr,
6788         TemplateParamLists,
6789         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6790 
6791     if (TemplateParams) {
6792       if (!TemplateParams->size() &&
6793           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6794         // There is an extraneous 'template<>' for this variable. Complain
6795         // about it, but allow the declaration of the variable.
6796         Diag(TemplateParams->getTemplateLoc(),
6797              diag::err_template_variable_noparams)
6798           << II
6799           << SourceRange(TemplateParams->getTemplateLoc(),
6800                          TemplateParams->getRAngleLoc());
6801         TemplateParams = nullptr;
6802       } else {
6803         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6804           // This is an explicit specialization or a partial specialization.
6805           // FIXME: Check that we can declare a specialization here.
6806           IsVariableTemplateSpecialization = true;
6807           IsPartialSpecialization = TemplateParams->size() > 0;
6808         } else { // if (TemplateParams->size() > 0)
6809           // This is a template declaration.
6810           IsVariableTemplate = true;
6811 
6812           // Check that we can declare a template here.
6813           if (CheckTemplateDeclScope(S, TemplateParams))
6814             return nullptr;
6815 
6816           // Only C++1y supports variable templates (N3651).
6817           Diag(D.getIdentifierLoc(),
6818                getLangOpts().CPlusPlus14
6819                    ? diag::warn_cxx11_compat_variable_template
6820                    : diag::ext_variable_template);
6821         }
6822       }
6823     } else {
6824       assert((Invalid ||
6825               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
6826              "should have a 'template<>' for this decl");
6827     }
6828 
6829     if (IsVariableTemplateSpecialization) {
6830       SourceLocation TemplateKWLoc =
6831           TemplateParamLists.size() > 0
6832               ? TemplateParamLists[0]->getTemplateLoc()
6833               : SourceLocation();
6834       DeclResult Res = ActOnVarTemplateSpecialization(
6835           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6836           IsPartialSpecialization);
6837       if (Res.isInvalid())
6838         return nullptr;
6839       NewVD = cast<VarDecl>(Res.get());
6840       AddToScope = false;
6841     } else if (D.isDecompositionDeclarator()) {
6842       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
6843                                         D.getIdentifierLoc(), R, TInfo, SC,
6844                                         Bindings);
6845     } else
6846       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
6847                               D.getIdentifierLoc(), II, R, TInfo, SC);
6848 
6849     // If this is supposed to be a variable template, create it as such.
6850     if (IsVariableTemplate) {
6851       NewTemplate =
6852           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6853                                   TemplateParams, NewVD);
6854       NewVD->setDescribedVarTemplate(NewTemplate);
6855     }
6856 
6857     // If this decl has an auto type in need of deduction, make a note of the
6858     // Decl so we can diagnose uses of it in its own initializer.
6859     if (R->getContainedDeducedType())
6860       ParsingInitForAutoVars.insert(NewVD);
6861 
6862     if (D.isInvalidType() || Invalid) {
6863       NewVD->setInvalidDecl();
6864       if (NewTemplate)
6865         NewTemplate->setInvalidDecl();
6866     }
6867 
6868     SetNestedNameSpecifier(*this, NewVD, D);
6869 
6870     // If we have any template parameter lists that don't directly belong to
6871     // the variable (matching the scope specifier), store them.
6872     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6873     if (TemplateParamLists.size() > VDTemplateParamLists)
6874       NewVD->setTemplateParameterListsInfo(
6875           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6876   }
6877 
6878   if (D.getDeclSpec().isInlineSpecified()) {
6879     if (!getLangOpts().CPlusPlus) {
6880       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6881           << 0;
6882     } else if (CurContext->isFunctionOrMethod()) {
6883       // 'inline' is not allowed on block scope variable declaration.
6884       Diag(D.getDeclSpec().getInlineSpecLoc(),
6885            diag::err_inline_declaration_block_scope) << Name
6886         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6887     } else {
6888       Diag(D.getDeclSpec().getInlineSpecLoc(),
6889            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
6890                                      : diag::ext_inline_variable);
6891       NewVD->setInlineSpecified();
6892     }
6893   }
6894 
6895   // Set the lexical context. If the declarator has a C++ scope specifier, the
6896   // lexical context will be different from the semantic context.
6897   NewVD->setLexicalDeclContext(CurContext);
6898   if (NewTemplate)
6899     NewTemplate->setLexicalDeclContext(CurContext);
6900 
6901   if (IsLocalExternDecl) {
6902     if (D.isDecompositionDeclarator())
6903       for (auto *B : Bindings)
6904         B->setLocalExternDecl();
6905     else
6906       NewVD->setLocalExternDecl();
6907   }
6908 
6909   bool EmitTLSUnsupportedError = false;
6910   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6911     // C++11 [dcl.stc]p4:
6912     //   When thread_local is applied to a variable of block scope the
6913     //   storage-class-specifier static is implied if it does not appear
6914     //   explicitly.
6915     // Core issue: 'static' is not implied if the variable is declared
6916     //   'extern'.
6917     if (NewVD->hasLocalStorage() &&
6918         (SCSpec != DeclSpec::SCS_unspecified ||
6919          TSCS != DeclSpec::TSCS_thread_local ||
6920          !DC->isFunctionOrMethod()))
6921       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6922            diag::err_thread_non_global)
6923         << DeclSpec::getSpecifierName(TSCS);
6924     else if (!Context.getTargetInfo().isTLSSupported()) {
6925       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6926         // Postpone error emission until we've collected attributes required to
6927         // figure out whether it's a host or device variable and whether the
6928         // error should be ignored.
6929         EmitTLSUnsupportedError = true;
6930         // We still need to mark the variable as TLS so it shows up in AST with
6931         // proper storage class for other tools to use even if we're not going
6932         // to emit any code for it.
6933         NewVD->setTSCSpec(TSCS);
6934       } else
6935         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6936              diag::err_thread_unsupported);
6937     } else
6938       NewVD->setTSCSpec(TSCS);
6939   }
6940 
6941   switch (D.getDeclSpec().getConstexprSpecifier()) {
6942   case CSK_unspecified:
6943     break;
6944 
6945   case CSK_consteval:
6946     Diag(D.getDeclSpec().getConstexprSpecLoc(),
6947         diag::err_constexpr_wrong_decl_kind)
6948       << D.getDeclSpec().getConstexprSpecifier();
6949     LLVM_FALLTHROUGH;
6950 
6951   case CSK_constexpr:
6952     NewVD->setConstexpr(true);
6953     // C++1z [dcl.spec.constexpr]p1:
6954     //   A static data member declared with the constexpr specifier is
6955     //   implicitly an inline variable.
6956     if (NewVD->isStaticDataMember() &&
6957         (getLangOpts().CPlusPlus17 ||
6958          Context.getTargetInfo().getCXXABI().isMicrosoft()))
6959       NewVD->setImplicitlyInline();
6960     break;
6961 
6962   case CSK_constinit:
6963     if (!NewVD->hasGlobalStorage())
6964       Diag(D.getDeclSpec().getConstexprSpecLoc(),
6965            diag::err_constinit_local_variable);
6966     else
6967       NewVD->addAttr(ConstInitAttr::Create(
6968           Context, D.getDeclSpec().getConstexprSpecLoc(),
6969           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
6970     break;
6971   }
6972 
6973   // C99 6.7.4p3
6974   //   An inline definition of a function with external linkage shall
6975   //   not contain a definition of a modifiable object with static or
6976   //   thread storage duration...
6977   // We only apply this when the function is required to be defined
6978   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6979   // that a local variable with thread storage duration still has to
6980   // be marked 'static'.  Also note that it's possible to get these
6981   // semantics in C++ using __attribute__((gnu_inline)).
6982   if (SC == SC_Static && S->getFnParent() != nullptr &&
6983       !NewVD->getType().isConstQualified()) {
6984     FunctionDecl *CurFD = getCurFunctionDecl();
6985     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6986       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6987            diag::warn_static_local_in_extern_inline);
6988       MaybeSuggestAddingStaticToDecl(CurFD);
6989     }
6990   }
6991 
6992   if (D.getDeclSpec().isModulePrivateSpecified()) {
6993     if (IsVariableTemplateSpecialization)
6994       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6995           << (IsPartialSpecialization ? 1 : 0)
6996           << FixItHint::CreateRemoval(
6997                  D.getDeclSpec().getModulePrivateSpecLoc());
6998     else if (IsMemberSpecialization)
6999       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7000         << 2
7001         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7002     else if (NewVD->hasLocalStorage())
7003       Diag(NewVD->getLocation(), diag::err_module_private_local)
7004         << 0 << NewVD->getDeclName()
7005         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7006         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7007     else {
7008       NewVD->setModulePrivate();
7009       if (NewTemplate)
7010         NewTemplate->setModulePrivate();
7011       for (auto *B : Bindings)
7012         B->setModulePrivate();
7013     }
7014   }
7015 
7016   if (getLangOpts().OpenCL) {
7017 
7018     deduceOpenCLAddressSpace(NewVD);
7019 
7020     diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType());
7021   }
7022 
7023   // Handle attributes prior to checking for duplicates in MergeVarDecl
7024   ProcessDeclAttributes(S, NewVD, D);
7025 
7026   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
7027     if (EmitTLSUnsupportedError &&
7028         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7029          (getLangOpts().OpenMPIsDevice &&
7030           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7031       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7032            diag::err_thread_unsupported);
7033     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7034     // storage [duration]."
7035     if (SC == SC_None && S->getFnParent() != nullptr &&
7036         (NewVD->hasAttr<CUDASharedAttr>() ||
7037          NewVD->hasAttr<CUDAConstantAttr>())) {
7038       NewVD->setStorageClass(SC_Static);
7039     }
7040   }
7041 
7042   // Ensure that dllimport globals without explicit storage class are treated as
7043   // extern. The storage class is set above using parsed attributes. Now we can
7044   // check the VarDecl itself.
7045   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7046          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7047          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7048 
7049   // In auto-retain/release, infer strong retension for variables of
7050   // retainable type.
7051   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7052     NewVD->setInvalidDecl();
7053 
7054   // Handle GNU asm-label extension (encoded as an attribute).
7055   if (Expr *E = (Expr*)D.getAsmLabel()) {
7056     // The parser guarantees this is a string.
7057     StringLiteral *SE = cast<StringLiteral>(E);
7058     StringRef Label = SE->getString();
7059     if (S->getFnParent() != nullptr) {
7060       switch (SC) {
7061       case SC_None:
7062       case SC_Auto:
7063         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7064         break;
7065       case SC_Register:
7066         // Local Named register
7067         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7068             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7069           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7070         break;
7071       case SC_Static:
7072       case SC_Extern:
7073       case SC_PrivateExtern:
7074         break;
7075       }
7076     } else if (SC == SC_Register) {
7077       // Global Named register
7078       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7079         const auto &TI = Context.getTargetInfo();
7080         bool HasSizeMismatch;
7081 
7082         if (!TI.isValidGCCRegisterName(Label))
7083           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7084         else if (!TI.validateGlobalRegisterVariable(Label,
7085                                                     Context.getTypeSize(R),
7086                                                     HasSizeMismatch))
7087           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7088         else if (HasSizeMismatch)
7089           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7090       }
7091 
7092       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7093         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7094         NewVD->setInvalidDecl(true);
7095       }
7096     }
7097 
7098     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7099                                         /*IsLiteralLabel=*/true,
7100                                         SE->getStrTokenLoc(0)));
7101   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7102     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7103       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7104     if (I != ExtnameUndeclaredIdentifiers.end()) {
7105       if (isDeclExternC(NewVD)) {
7106         NewVD->addAttr(I->second);
7107         ExtnameUndeclaredIdentifiers.erase(I);
7108       } else
7109         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7110             << /*Variable*/1 << NewVD;
7111     }
7112   }
7113 
7114   // Find the shadowed declaration before filtering for scope.
7115   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7116                                 ? getShadowedDeclaration(NewVD, Previous)
7117                                 : nullptr;
7118 
7119   // Don't consider existing declarations that are in a different
7120   // scope and are out-of-semantic-context declarations (if the new
7121   // declaration has linkage).
7122   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7123                        D.getCXXScopeSpec().isNotEmpty() ||
7124                        IsMemberSpecialization ||
7125                        IsVariableTemplateSpecialization);
7126 
7127   // Check whether the previous declaration is in the same block scope. This
7128   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7129   if (getLangOpts().CPlusPlus &&
7130       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7131     NewVD->setPreviousDeclInSameBlockScope(
7132         Previous.isSingleResult() && !Previous.isShadowed() &&
7133         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7134 
7135   if (!getLangOpts().CPlusPlus) {
7136     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7137   } else {
7138     // If this is an explicit specialization of a static data member, check it.
7139     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7140         CheckMemberSpecialization(NewVD, Previous))
7141       NewVD->setInvalidDecl();
7142 
7143     // Merge the decl with the existing one if appropriate.
7144     if (!Previous.empty()) {
7145       if (Previous.isSingleResult() &&
7146           isa<FieldDecl>(Previous.getFoundDecl()) &&
7147           D.getCXXScopeSpec().isSet()) {
7148         // The user tried to define a non-static data member
7149         // out-of-line (C++ [dcl.meaning]p1).
7150         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7151           << D.getCXXScopeSpec().getRange();
7152         Previous.clear();
7153         NewVD->setInvalidDecl();
7154       }
7155     } else if (D.getCXXScopeSpec().isSet()) {
7156       // No previous declaration in the qualifying scope.
7157       Diag(D.getIdentifierLoc(), diag::err_no_member)
7158         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7159         << D.getCXXScopeSpec().getRange();
7160       NewVD->setInvalidDecl();
7161     }
7162 
7163     if (!IsVariableTemplateSpecialization)
7164       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7165 
7166     if (NewTemplate) {
7167       VarTemplateDecl *PrevVarTemplate =
7168           NewVD->getPreviousDecl()
7169               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7170               : nullptr;
7171 
7172       // Check the template parameter list of this declaration, possibly
7173       // merging in the template parameter list from the previous variable
7174       // template declaration.
7175       if (CheckTemplateParameterList(
7176               TemplateParams,
7177               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7178                               : nullptr,
7179               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7180                DC->isDependentContext())
7181                   ? TPC_ClassTemplateMember
7182                   : TPC_VarTemplate))
7183         NewVD->setInvalidDecl();
7184 
7185       // If we are providing an explicit specialization of a static variable
7186       // template, make a note of that.
7187       if (PrevVarTemplate &&
7188           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7189         PrevVarTemplate->setMemberSpecialization();
7190     }
7191   }
7192 
7193   // Diagnose shadowed variables iff this isn't a redeclaration.
7194   if (ShadowedDecl && !D.isRedeclaration())
7195     CheckShadow(NewVD, ShadowedDecl, Previous);
7196 
7197   ProcessPragmaWeak(S, NewVD);
7198 
7199   // If this is the first declaration of an extern C variable, update
7200   // the map of such variables.
7201   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7202       isIncompleteDeclExternC(*this, NewVD))
7203     RegisterLocallyScopedExternCDecl(NewVD, S);
7204 
7205   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7206     MangleNumberingContext *MCtx;
7207     Decl *ManglingContextDecl;
7208     std::tie(MCtx, ManglingContextDecl) =
7209         getCurrentMangleNumberContext(NewVD->getDeclContext());
7210     if (MCtx) {
7211       Context.setManglingNumber(
7212           NewVD, MCtx->getManglingNumber(
7213                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7214       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7215     }
7216   }
7217 
7218   // Special handling of variable named 'main'.
7219   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7220       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7221       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7222 
7223     // C++ [basic.start.main]p3
7224     // A program that declares a variable main at global scope is ill-formed.
7225     if (getLangOpts().CPlusPlus)
7226       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7227 
7228     // In C, and external-linkage variable named main results in undefined
7229     // behavior.
7230     else if (NewVD->hasExternalFormalLinkage())
7231       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7232   }
7233 
7234   if (D.isRedeclaration() && !Previous.empty()) {
7235     NamedDecl *Prev = Previous.getRepresentativeDecl();
7236     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7237                                    D.isFunctionDefinition());
7238   }
7239 
7240   if (NewTemplate) {
7241     if (NewVD->isInvalidDecl())
7242       NewTemplate->setInvalidDecl();
7243     ActOnDocumentableDecl(NewTemplate);
7244     return NewTemplate;
7245   }
7246 
7247   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7248     CompleteMemberSpecialization(NewVD, Previous);
7249 
7250   return NewVD;
7251 }
7252 
7253 /// Enum describing the %select options in diag::warn_decl_shadow.
7254 enum ShadowedDeclKind {
7255   SDK_Local,
7256   SDK_Global,
7257   SDK_StaticMember,
7258   SDK_Field,
7259   SDK_Typedef,
7260   SDK_Using
7261 };
7262 
7263 /// Determine what kind of declaration we're shadowing.
7264 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7265                                                 const DeclContext *OldDC) {
7266   if (isa<TypeAliasDecl>(ShadowedDecl))
7267     return SDK_Using;
7268   else if (isa<TypedefDecl>(ShadowedDecl))
7269     return SDK_Typedef;
7270   else if (isa<RecordDecl>(OldDC))
7271     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7272 
7273   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7274 }
7275 
7276 /// Return the location of the capture if the given lambda captures the given
7277 /// variable \p VD, or an invalid source location otherwise.
7278 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7279                                          const VarDecl *VD) {
7280   for (const Capture &Capture : LSI->Captures) {
7281     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7282       return Capture.getLocation();
7283   }
7284   return SourceLocation();
7285 }
7286 
7287 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7288                                      const LookupResult &R) {
7289   // Only diagnose if we're shadowing an unambiguous field or variable.
7290   if (R.getResultKind() != LookupResult::Found)
7291     return false;
7292 
7293   // Return false if warning is ignored.
7294   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7295 }
7296 
7297 /// Return the declaration shadowed by the given variable \p D, or null
7298 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7299 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7300                                         const LookupResult &R) {
7301   if (!shouldWarnIfShadowedDecl(Diags, R))
7302     return nullptr;
7303 
7304   // Don't diagnose declarations at file scope.
7305   if (D->hasGlobalStorage())
7306     return nullptr;
7307 
7308   NamedDecl *ShadowedDecl = R.getFoundDecl();
7309   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
7310              ? ShadowedDecl
7311              : nullptr;
7312 }
7313 
7314 /// Return the declaration shadowed by the given typedef \p D, or null
7315 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7316 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7317                                         const LookupResult &R) {
7318   // Don't warn if typedef declaration is part of a class
7319   if (D->getDeclContext()->isRecord())
7320     return nullptr;
7321 
7322   if (!shouldWarnIfShadowedDecl(Diags, R))
7323     return nullptr;
7324 
7325   NamedDecl *ShadowedDecl = R.getFoundDecl();
7326   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7327 }
7328 
7329 /// Diagnose variable or built-in function shadowing.  Implements
7330 /// -Wshadow.
7331 ///
7332 /// This method is called whenever a VarDecl is added to a "useful"
7333 /// scope.
7334 ///
7335 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7336 /// \param R the lookup of the name
7337 ///
7338 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7339                        const LookupResult &R) {
7340   DeclContext *NewDC = D->getDeclContext();
7341 
7342   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7343     // Fields are not shadowed by variables in C++ static methods.
7344     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7345       if (MD->isStatic())
7346         return;
7347 
7348     // Fields shadowed by constructor parameters are a special case. Usually
7349     // the constructor initializes the field with the parameter.
7350     if (isa<CXXConstructorDecl>(NewDC))
7351       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7352         // Remember that this was shadowed so we can either warn about its
7353         // modification or its existence depending on warning settings.
7354         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7355         return;
7356       }
7357   }
7358 
7359   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7360     if (shadowedVar->isExternC()) {
7361       // For shadowing external vars, make sure that we point to the global
7362       // declaration, not a locally scoped extern declaration.
7363       for (auto I : shadowedVar->redecls())
7364         if (I->isFileVarDecl()) {
7365           ShadowedDecl = I;
7366           break;
7367         }
7368     }
7369 
7370   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7371 
7372   unsigned WarningDiag = diag::warn_decl_shadow;
7373   SourceLocation CaptureLoc;
7374   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7375       isa<CXXMethodDecl>(NewDC)) {
7376     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7377       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7378         if (RD->getLambdaCaptureDefault() == LCD_None) {
7379           // Try to avoid warnings for lambdas with an explicit capture list.
7380           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7381           // Warn only when the lambda captures the shadowed decl explicitly.
7382           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7383           if (CaptureLoc.isInvalid())
7384             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7385         } else {
7386           // Remember that this was shadowed so we can avoid the warning if the
7387           // shadowed decl isn't captured and the warning settings allow it.
7388           cast<LambdaScopeInfo>(getCurFunction())
7389               ->ShadowingDecls.push_back(
7390                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7391           return;
7392         }
7393       }
7394 
7395       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7396         // A variable can't shadow a local variable in an enclosing scope, if
7397         // they are separated by a non-capturing declaration context.
7398         for (DeclContext *ParentDC = NewDC;
7399              ParentDC && !ParentDC->Equals(OldDC);
7400              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7401           // Only block literals, captured statements, and lambda expressions
7402           // can capture; other scopes don't.
7403           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7404               !isLambdaCallOperator(ParentDC)) {
7405             return;
7406           }
7407         }
7408       }
7409     }
7410   }
7411 
7412   // Only warn about certain kinds of shadowing for class members.
7413   if (NewDC && NewDC->isRecord()) {
7414     // In particular, don't warn about shadowing non-class members.
7415     if (!OldDC->isRecord())
7416       return;
7417 
7418     // TODO: should we warn about static data members shadowing
7419     // static data members from base classes?
7420 
7421     // TODO: don't diagnose for inaccessible shadowed members.
7422     // This is hard to do perfectly because we might friend the
7423     // shadowing context, but that's just a false negative.
7424   }
7425 
7426 
7427   DeclarationName Name = R.getLookupName();
7428 
7429   // Emit warning and note.
7430   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7431     return;
7432   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7433   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7434   if (!CaptureLoc.isInvalid())
7435     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7436         << Name << /*explicitly*/ 1;
7437   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7438 }
7439 
7440 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7441 /// when these variables are captured by the lambda.
7442 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7443   for (const auto &Shadow : LSI->ShadowingDecls) {
7444     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7445     // Try to avoid the warning when the shadowed decl isn't captured.
7446     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7447     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7448     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7449                                        ? diag::warn_decl_shadow_uncaptured_local
7450                                        : diag::warn_decl_shadow)
7451         << Shadow.VD->getDeclName()
7452         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7453     if (!CaptureLoc.isInvalid())
7454       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7455           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7456     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7457   }
7458 }
7459 
7460 /// Check -Wshadow without the advantage of a previous lookup.
7461 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7462   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7463     return;
7464 
7465   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7466                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7467   LookupName(R, S);
7468   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7469     CheckShadow(D, ShadowedDecl, R);
7470 }
7471 
7472 /// Check if 'E', which is an expression that is about to be modified, refers
7473 /// to a constructor parameter that shadows a field.
7474 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7475   // Quickly ignore expressions that can't be shadowing ctor parameters.
7476   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7477     return;
7478   E = E->IgnoreParenImpCasts();
7479   auto *DRE = dyn_cast<DeclRefExpr>(E);
7480   if (!DRE)
7481     return;
7482   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7483   auto I = ShadowingDecls.find(D);
7484   if (I == ShadowingDecls.end())
7485     return;
7486   const NamedDecl *ShadowedDecl = I->second;
7487   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7488   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7489   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7490   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7491 
7492   // Avoid issuing multiple warnings about the same decl.
7493   ShadowingDecls.erase(I);
7494 }
7495 
7496 /// Check for conflict between this global or extern "C" declaration and
7497 /// previous global or extern "C" declarations. This is only used in C++.
7498 template<typename T>
7499 static bool checkGlobalOrExternCConflict(
7500     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7501   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7502   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7503 
7504   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7505     // The common case: this global doesn't conflict with any extern "C"
7506     // declaration.
7507     return false;
7508   }
7509 
7510   if (Prev) {
7511     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7512       // Both the old and new declarations have C language linkage. This is a
7513       // redeclaration.
7514       Previous.clear();
7515       Previous.addDecl(Prev);
7516       return true;
7517     }
7518 
7519     // This is a global, non-extern "C" declaration, and there is a previous
7520     // non-global extern "C" declaration. Diagnose if this is a variable
7521     // declaration.
7522     if (!isa<VarDecl>(ND))
7523       return false;
7524   } else {
7525     // The declaration is extern "C". Check for any declaration in the
7526     // translation unit which might conflict.
7527     if (IsGlobal) {
7528       // We have already performed the lookup into the translation unit.
7529       IsGlobal = false;
7530       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7531            I != E; ++I) {
7532         if (isa<VarDecl>(*I)) {
7533           Prev = *I;
7534           break;
7535         }
7536       }
7537     } else {
7538       DeclContext::lookup_result R =
7539           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7540       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7541            I != E; ++I) {
7542         if (isa<VarDecl>(*I)) {
7543           Prev = *I;
7544           break;
7545         }
7546         // FIXME: If we have any other entity with this name in global scope,
7547         // the declaration is ill-formed, but that is a defect: it breaks the
7548         // 'stat' hack, for instance. Only variables can have mangled name
7549         // clashes with extern "C" declarations, so only they deserve a
7550         // diagnostic.
7551       }
7552     }
7553 
7554     if (!Prev)
7555       return false;
7556   }
7557 
7558   // Use the first declaration's location to ensure we point at something which
7559   // is lexically inside an extern "C" linkage-spec.
7560   assert(Prev && "should have found a previous declaration to diagnose");
7561   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7562     Prev = FD->getFirstDecl();
7563   else
7564     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7565 
7566   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7567     << IsGlobal << ND;
7568   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7569     << IsGlobal;
7570   return false;
7571 }
7572 
7573 /// Apply special rules for handling extern "C" declarations. Returns \c true
7574 /// if we have found that this is a redeclaration of some prior entity.
7575 ///
7576 /// Per C++ [dcl.link]p6:
7577 ///   Two declarations [for a function or variable] with C language linkage
7578 ///   with the same name that appear in different scopes refer to the same
7579 ///   [entity]. An entity with C language linkage shall not be declared with
7580 ///   the same name as an entity in global scope.
7581 template<typename T>
7582 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7583                                                   LookupResult &Previous) {
7584   if (!S.getLangOpts().CPlusPlus) {
7585     // In C, when declaring a global variable, look for a corresponding 'extern'
7586     // variable declared in function scope. We don't need this in C++, because
7587     // we find local extern decls in the surrounding file-scope DeclContext.
7588     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7589       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7590         Previous.clear();
7591         Previous.addDecl(Prev);
7592         return true;
7593       }
7594     }
7595     return false;
7596   }
7597 
7598   // A declaration in the translation unit can conflict with an extern "C"
7599   // declaration.
7600   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7601     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7602 
7603   // An extern "C" declaration can conflict with a declaration in the
7604   // translation unit or can be a redeclaration of an extern "C" declaration
7605   // in another scope.
7606   if (isIncompleteDeclExternC(S,ND))
7607     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7608 
7609   // Neither global nor extern "C": nothing to do.
7610   return false;
7611 }
7612 
7613 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7614   // If the decl is already known invalid, don't check it.
7615   if (NewVD->isInvalidDecl())
7616     return;
7617 
7618   QualType T = NewVD->getType();
7619 
7620   // Defer checking an 'auto' type until its initializer is attached.
7621   if (T->isUndeducedType())
7622     return;
7623 
7624   if (NewVD->hasAttrs())
7625     CheckAlignasUnderalignment(NewVD);
7626 
7627   if (T->isObjCObjectType()) {
7628     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7629       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7630     T = Context.getObjCObjectPointerType(T);
7631     NewVD->setType(T);
7632   }
7633 
7634   // Emit an error if an address space was applied to decl with local storage.
7635   // This includes arrays of objects with address space qualifiers, but not
7636   // automatic variables that point to other address spaces.
7637   // ISO/IEC TR 18037 S5.1.2
7638   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7639       T.getAddressSpace() != LangAS::Default) {
7640     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7641     NewVD->setInvalidDecl();
7642     return;
7643   }
7644 
7645   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7646   // scope.
7647   if (getLangOpts().OpenCLVersion == 120 &&
7648       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7649       NewVD->isStaticLocal()) {
7650     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7651     NewVD->setInvalidDecl();
7652     return;
7653   }
7654 
7655   if (getLangOpts().OpenCL) {
7656     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7657     if (NewVD->hasAttr<BlocksAttr>()) {
7658       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7659       return;
7660     }
7661 
7662     if (T->isBlockPointerType()) {
7663       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7664       // can't use 'extern' storage class.
7665       if (!T.isConstQualified()) {
7666         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7667             << 0 /*const*/;
7668         NewVD->setInvalidDecl();
7669         return;
7670       }
7671       if (NewVD->hasExternalStorage()) {
7672         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7673         NewVD->setInvalidDecl();
7674         return;
7675       }
7676     }
7677     // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7678     // __constant address space.
7679     // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7680     // variables inside a function can also be declared in the global
7681     // address space.
7682     // C++ for OpenCL inherits rule from OpenCL C v2.0.
7683     // FIXME: Adding local AS in C++ for OpenCL might make sense.
7684     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7685         NewVD->hasExternalStorage()) {
7686       if (!T->isSamplerT() &&
7687           !(T.getAddressSpace() == LangAS::opencl_constant ||
7688             (T.getAddressSpace() == LangAS::opencl_global &&
7689              (getLangOpts().OpenCLVersion == 200 ||
7690               getLangOpts().OpenCLCPlusPlus)))) {
7691         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7692         if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7693           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7694               << Scope << "global or constant";
7695         else
7696           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7697               << Scope << "constant";
7698         NewVD->setInvalidDecl();
7699         return;
7700       }
7701     } else {
7702       if (T.getAddressSpace() == LangAS::opencl_global) {
7703         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7704             << 1 /*is any function*/ << "global";
7705         NewVD->setInvalidDecl();
7706         return;
7707       }
7708       if (T.getAddressSpace() == LangAS::opencl_constant ||
7709           T.getAddressSpace() == LangAS::opencl_local) {
7710         FunctionDecl *FD = getCurFunctionDecl();
7711         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7712         // in functions.
7713         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7714           if (T.getAddressSpace() == LangAS::opencl_constant)
7715             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7716                 << 0 /*non-kernel only*/ << "constant";
7717           else
7718             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7719                 << 0 /*non-kernel only*/ << "local";
7720           NewVD->setInvalidDecl();
7721           return;
7722         }
7723         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7724         // in the outermost scope of a kernel function.
7725         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7726           if (!getCurScope()->isFunctionScope()) {
7727             if (T.getAddressSpace() == LangAS::opencl_constant)
7728               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7729                   << "constant";
7730             else
7731               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7732                   << "local";
7733             NewVD->setInvalidDecl();
7734             return;
7735           }
7736         }
7737       } else if (T.getAddressSpace() != LangAS::opencl_private &&
7738                  // If we are parsing a template we didn't deduce an addr
7739                  // space yet.
7740                  T.getAddressSpace() != LangAS::Default) {
7741         // Do not allow other address spaces on automatic variable.
7742         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7743         NewVD->setInvalidDecl();
7744         return;
7745       }
7746     }
7747   }
7748 
7749   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7750       && !NewVD->hasAttr<BlocksAttr>()) {
7751     if (getLangOpts().getGC() != LangOptions::NonGC)
7752       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7753     else {
7754       assert(!getLangOpts().ObjCAutoRefCount);
7755       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7756     }
7757   }
7758 
7759   bool isVM = T->isVariablyModifiedType();
7760   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7761       NewVD->hasAttr<BlocksAttr>())
7762     setFunctionHasBranchProtectedScope();
7763 
7764   if ((isVM && NewVD->hasLinkage()) ||
7765       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7766     bool SizeIsNegative;
7767     llvm::APSInt Oversized;
7768     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7769         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7770     QualType FixedT;
7771     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
7772       FixedT = FixedTInfo->getType();
7773     else if (FixedTInfo) {
7774       // Type and type-as-written are canonically different. We need to fix up
7775       // both types separately.
7776       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7777                                                    Oversized);
7778     }
7779     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7780       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7781       // FIXME: This won't give the correct result for
7782       // int a[10][n];
7783       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7784 
7785       if (NewVD->isFileVarDecl())
7786         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7787         << SizeRange;
7788       else if (NewVD->isStaticLocal())
7789         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7790         << SizeRange;
7791       else
7792         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7793         << SizeRange;
7794       NewVD->setInvalidDecl();
7795       return;
7796     }
7797 
7798     if (!FixedTInfo) {
7799       if (NewVD->isFileVarDecl())
7800         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7801       else
7802         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7803       NewVD->setInvalidDecl();
7804       return;
7805     }
7806 
7807     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7808     NewVD->setType(FixedT);
7809     NewVD->setTypeSourceInfo(FixedTInfo);
7810   }
7811 
7812   if (T->isVoidType()) {
7813     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7814     //                    of objects and functions.
7815     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7816       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7817         << T;
7818       NewVD->setInvalidDecl();
7819       return;
7820     }
7821   }
7822 
7823   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7824     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7825     NewVD->setInvalidDecl();
7826     return;
7827   }
7828 
7829   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7830     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7831     NewVD->setInvalidDecl();
7832     return;
7833   }
7834 
7835   if (NewVD->isConstexpr() && !T->isDependentType() &&
7836       RequireLiteralType(NewVD->getLocation(), T,
7837                          diag::err_constexpr_var_non_literal)) {
7838     NewVD->setInvalidDecl();
7839     return;
7840   }
7841 }
7842 
7843 /// Perform semantic checking on a newly-created variable
7844 /// declaration.
7845 ///
7846 /// This routine performs all of the type-checking required for a
7847 /// variable declaration once it has been built. It is used both to
7848 /// check variables after they have been parsed and their declarators
7849 /// have been translated into a declaration, and to check variables
7850 /// that have been instantiated from a template.
7851 ///
7852 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7853 ///
7854 /// Returns true if the variable declaration is a redeclaration.
7855 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7856   CheckVariableDeclarationType(NewVD);
7857 
7858   // If the decl is already known invalid, don't check it.
7859   if (NewVD->isInvalidDecl())
7860     return false;
7861 
7862   // If we did not find anything by this name, look for a non-visible
7863   // extern "C" declaration with the same name.
7864   if (Previous.empty() &&
7865       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7866     Previous.setShadowed();
7867 
7868   if (!Previous.empty()) {
7869     MergeVarDecl(NewVD, Previous);
7870     return true;
7871   }
7872   return false;
7873 }
7874 
7875 namespace {
7876 struct FindOverriddenMethod {
7877   Sema *S;
7878   CXXMethodDecl *Method;
7879 
7880   /// Member lookup function that determines whether a given C++
7881   /// method overrides a method in a base class, to be used with
7882   /// CXXRecordDecl::lookupInBases().
7883   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7884     RecordDecl *BaseRecord =
7885         Specifier->getType()->castAs<RecordType>()->getDecl();
7886 
7887     DeclarationName Name = Method->getDeclName();
7888 
7889     // FIXME: Do we care about other names here too?
7890     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7891       // We really want to find the base class destructor here.
7892       QualType T = S->Context.getTypeDeclType(BaseRecord);
7893       CanQualType CT = S->Context.getCanonicalType(T);
7894 
7895       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7896     }
7897 
7898     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7899          Path.Decls = Path.Decls.slice(1)) {
7900       NamedDecl *D = Path.Decls.front();
7901       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7902         if (MD->isVirtual() &&
7903             !S->IsOverload(
7904                 Method, MD, /*UseMemberUsingDeclRules=*/false,
7905                 /*ConsiderCudaAttrs=*/true,
7906                 // C++2a [class.virtual]p2 does not consider requires clauses
7907                 // when overriding.
7908                 /*ConsiderRequiresClauses=*/false))
7909           return true;
7910       }
7911     }
7912 
7913     return false;
7914   }
7915 };
7916 
7917 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7918 } // end anonymous namespace
7919 
7920 /// Report an error regarding overriding, along with any relevant
7921 /// overridden methods.
7922 ///
7923 /// \param DiagID the primary error to report.
7924 /// \param MD the overriding method.
7925 /// \param OEK which overrides to include as notes.
7926 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7927                             OverrideErrorKind OEK = OEK_All) {
7928   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7929   for (const CXXMethodDecl *O : MD->overridden_methods()) {
7930     // This check (& the OEK parameter) could be replaced by a predicate, but
7931     // without lambdas that would be overkill. This is still nicer than writing
7932     // out the diag loop 3 times.
7933     if ((OEK == OEK_All) ||
7934         (OEK == OEK_NonDeleted && !O->isDeleted()) ||
7935         (OEK == OEK_Deleted && O->isDeleted()))
7936       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7937   }
7938 }
7939 
7940 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7941 /// and if so, check that it's a valid override and remember it.
7942 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7943   // Look for methods in base classes that this method might override.
7944   CXXBasePaths Paths;
7945   FindOverriddenMethod FOM;
7946   FOM.Method = MD;
7947   FOM.S = this;
7948   bool hasDeletedOverridenMethods = false;
7949   bool hasNonDeletedOverridenMethods = false;
7950   bool AddedAny = false;
7951   if (DC->lookupInBases(FOM, Paths)) {
7952     for (auto *I : Paths.found_decls()) {
7953       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7954         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7955         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7956             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7957             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7958             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7959           hasDeletedOverridenMethods |= OldMD->isDeleted();
7960           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7961           AddedAny = true;
7962         }
7963       }
7964     }
7965   }
7966 
7967   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7968     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7969   }
7970   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7971     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7972   }
7973 
7974   return AddedAny;
7975 }
7976 
7977 namespace {
7978   // Struct for holding all of the extra arguments needed by
7979   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7980   struct ActOnFDArgs {
7981     Scope *S;
7982     Declarator &D;
7983     MultiTemplateParamsArg TemplateParamLists;
7984     bool AddToScope;
7985   };
7986 } // end anonymous namespace
7987 
7988 namespace {
7989 
7990 // Callback to only accept typo corrections that have a non-zero edit distance.
7991 // Also only accept corrections that have the same parent decl.
7992 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
7993  public:
7994   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7995                             CXXRecordDecl *Parent)
7996       : Context(Context), OriginalFD(TypoFD),
7997         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7998 
7999   bool ValidateCandidate(const TypoCorrection &candidate) override {
8000     if (candidate.getEditDistance() == 0)
8001       return false;
8002 
8003     SmallVector<unsigned, 1> MismatchedParams;
8004     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8005                                           CDeclEnd = candidate.end();
8006          CDecl != CDeclEnd; ++CDecl) {
8007       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8008 
8009       if (FD && !FD->hasBody() &&
8010           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8011         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8012           CXXRecordDecl *Parent = MD->getParent();
8013           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8014             return true;
8015         } else if (!ExpectedParent) {
8016           return true;
8017         }
8018       }
8019     }
8020 
8021     return false;
8022   }
8023 
8024   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8025     return std::make_unique<DifferentNameValidatorCCC>(*this);
8026   }
8027 
8028  private:
8029   ASTContext &Context;
8030   FunctionDecl *OriginalFD;
8031   CXXRecordDecl *ExpectedParent;
8032 };
8033 
8034 } // end anonymous namespace
8035 
8036 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8037   TypoCorrectedFunctionDefinitions.insert(F);
8038 }
8039 
8040 /// Generate diagnostics for an invalid function redeclaration.
8041 ///
8042 /// This routine handles generating the diagnostic messages for an invalid
8043 /// function redeclaration, including finding possible similar declarations
8044 /// or performing typo correction if there are no previous declarations with
8045 /// the same name.
8046 ///
8047 /// Returns a NamedDecl iff typo correction was performed and substituting in
8048 /// the new declaration name does not cause new errors.
8049 static NamedDecl *DiagnoseInvalidRedeclaration(
8050     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8051     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8052   DeclarationName Name = NewFD->getDeclName();
8053   DeclContext *NewDC = NewFD->getDeclContext();
8054   SmallVector<unsigned, 1> MismatchedParams;
8055   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8056   TypoCorrection Correction;
8057   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8058   unsigned DiagMsg =
8059     IsLocalFriend ? diag::err_no_matching_local_friend :
8060     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8061     diag::err_member_decl_does_not_match;
8062   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8063                     IsLocalFriend ? Sema::LookupLocalFriendName
8064                                   : Sema::LookupOrdinaryName,
8065                     Sema::ForVisibleRedeclaration);
8066 
8067   NewFD->setInvalidDecl();
8068   if (IsLocalFriend)
8069     SemaRef.LookupName(Prev, S);
8070   else
8071     SemaRef.LookupQualifiedName(Prev, NewDC);
8072   assert(!Prev.isAmbiguous() &&
8073          "Cannot have an ambiguity in previous-declaration lookup");
8074   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8075   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8076                                 MD ? MD->getParent() : nullptr);
8077   if (!Prev.empty()) {
8078     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8079          Func != FuncEnd; ++Func) {
8080       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8081       if (FD &&
8082           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8083         // Add 1 to the index so that 0 can mean the mismatch didn't
8084         // involve a parameter
8085         unsigned ParamNum =
8086             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8087         NearMatches.push_back(std::make_pair(FD, ParamNum));
8088       }
8089     }
8090   // If the qualified name lookup yielded nothing, try typo correction
8091   } else if ((Correction = SemaRef.CorrectTypo(
8092                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8093                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8094                   IsLocalFriend ? nullptr : NewDC))) {
8095     // Set up everything for the call to ActOnFunctionDeclarator
8096     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8097                               ExtraArgs.D.getIdentifierLoc());
8098     Previous.clear();
8099     Previous.setLookupName(Correction.getCorrection());
8100     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8101                                     CDeclEnd = Correction.end();
8102          CDecl != CDeclEnd; ++CDecl) {
8103       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8104       if (FD && !FD->hasBody() &&
8105           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8106         Previous.addDecl(FD);
8107       }
8108     }
8109     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8110 
8111     NamedDecl *Result;
8112     // Retry building the function declaration with the new previous
8113     // declarations, and with errors suppressed.
8114     {
8115       // Trap errors.
8116       Sema::SFINAETrap Trap(SemaRef);
8117 
8118       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8119       // pieces need to verify the typo-corrected C++ declaration and hopefully
8120       // eliminate the need for the parameter pack ExtraArgs.
8121       Result = SemaRef.ActOnFunctionDeclarator(
8122           ExtraArgs.S, ExtraArgs.D,
8123           Correction.getCorrectionDecl()->getDeclContext(),
8124           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8125           ExtraArgs.AddToScope);
8126 
8127       if (Trap.hasErrorOccurred())
8128         Result = nullptr;
8129     }
8130 
8131     if (Result) {
8132       // Determine which correction we picked.
8133       Decl *Canonical = Result->getCanonicalDecl();
8134       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8135            I != E; ++I)
8136         if ((*I)->getCanonicalDecl() == Canonical)
8137           Correction.setCorrectionDecl(*I);
8138 
8139       // Let Sema know about the correction.
8140       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8141       SemaRef.diagnoseTypo(
8142           Correction,
8143           SemaRef.PDiag(IsLocalFriend
8144                           ? diag::err_no_matching_local_friend_suggest
8145                           : diag::err_member_decl_does_not_match_suggest)
8146             << Name << NewDC << IsDefinition);
8147       return Result;
8148     }
8149 
8150     // Pretend the typo correction never occurred
8151     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8152                               ExtraArgs.D.getIdentifierLoc());
8153     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8154     Previous.clear();
8155     Previous.setLookupName(Name);
8156   }
8157 
8158   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8159       << Name << NewDC << IsDefinition << NewFD->getLocation();
8160 
8161   bool NewFDisConst = false;
8162   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8163     NewFDisConst = NewMD->isConst();
8164 
8165   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8166        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8167        NearMatch != NearMatchEnd; ++NearMatch) {
8168     FunctionDecl *FD = NearMatch->first;
8169     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8170     bool FDisConst = MD && MD->isConst();
8171     bool IsMember = MD || !IsLocalFriend;
8172 
8173     // FIXME: These notes are poorly worded for the local friend case.
8174     if (unsigned Idx = NearMatch->second) {
8175       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8176       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8177       if (Loc.isInvalid()) Loc = FD->getLocation();
8178       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8179                                  : diag::note_local_decl_close_param_match)
8180         << Idx << FDParam->getType()
8181         << NewFD->getParamDecl(Idx - 1)->getType();
8182     } else if (FDisConst != NewFDisConst) {
8183       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8184           << NewFDisConst << FD->getSourceRange().getEnd();
8185     } else
8186       SemaRef.Diag(FD->getLocation(),
8187                    IsMember ? diag::note_member_def_close_match
8188                             : diag::note_local_decl_close_match);
8189   }
8190   return nullptr;
8191 }
8192 
8193 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8194   switch (D.getDeclSpec().getStorageClassSpec()) {
8195   default: llvm_unreachable("Unknown storage class!");
8196   case DeclSpec::SCS_auto:
8197   case DeclSpec::SCS_register:
8198   case DeclSpec::SCS_mutable:
8199     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8200                  diag::err_typecheck_sclass_func);
8201     D.getMutableDeclSpec().ClearStorageClassSpecs();
8202     D.setInvalidType();
8203     break;
8204   case DeclSpec::SCS_unspecified: break;
8205   case DeclSpec::SCS_extern:
8206     if (D.getDeclSpec().isExternInLinkageSpec())
8207       return SC_None;
8208     return SC_Extern;
8209   case DeclSpec::SCS_static: {
8210     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8211       // C99 6.7.1p5:
8212       //   The declaration of an identifier for a function that has
8213       //   block scope shall have no explicit storage-class specifier
8214       //   other than extern
8215       // See also (C++ [dcl.stc]p4).
8216       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8217                    diag::err_static_block_func);
8218       break;
8219     } else
8220       return SC_Static;
8221   }
8222   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8223   }
8224 
8225   // No explicit storage class has already been returned
8226   return SC_None;
8227 }
8228 
8229 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8230                                            DeclContext *DC, QualType &R,
8231                                            TypeSourceInfo *TInfo,
8232                                            StorageClass SC,
8233                                            bool &IsVirtualOkay) {
8234   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8235   DeclarationName Name = NameInfo.getName();
8236 
8237   FunctionDecl *NewFD = nullptr;
8238   bool isInline = D.getDeclSpec().isInlineSpecified();
8239 
8240   if (!SemaRef.getLangOpts().CPlusPlus) {
8241     // Determine whether the function was written with a
8242     // prototype. This true when:
8243     //   - there is a prototype in the declarator, or
8244     //   - the type R of the function is some kind of typedef or other non-
8245     //     attributed reference to a type name (which eventually refers to a
8246     //     function type).
8247     bool HasPrototype =
8248       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8249       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8250 
8251     NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8252                                  R, TInfo, SC, isInline, HasPrototype,
8253                                  CSK_unspecified,
8254                                  /*TrailingRequiresClause=*/nullptr);
8255     if (D.isInvalidType())
8256       NewFD->setInvalidDecl();
8257 
8258     return NewFD;
8259   }
8260 
8261   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8262 
8263   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8264   if (ConstexprKind == CSK_constinit) {
8265     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8266                  diag::err_constexpr_wrong_decl_kind)
8267         << ConstexprKind;
8268     ConstexprKind = CSK_unspecified;
8269     D.getMutableDeclSpec().ClearConstexprSpec();
8270   }
8271   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8272 
8273   // Check that the return type is not an abstract class type.
8274   // For record types, this is done by the AbstractClassUsageDiagnoser once
8275   // the class has been completely parsed.
8276   if (!DC->isRecord() &&
8277       SemaRef.RequireNonAbstractType(
8278           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8279           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8280     D.setInvalidType();
8281 
8282   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8283     // This is a C++ constructor declaration.
8284     assert(DC->isRecord() &&
8285            "Constructors can only be declared in a member context");
8286 
8287     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8288     return CXXConstructorDecl::Create(
8289         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8290         TInfo, ExplicitSpecifier, isInline,
8291         /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(),
8292         TrailingRequiresClause);
8293 
8294   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8295     // This is a C++ destructor declaration.
8296     if (DC->isRecord()) {
8297       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8298       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8299       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8300           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8301           isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8302           TrailingRequiresClause);
8303 
8304       // If the destructor needs an implicit exception specification, set it
8305       // now. FIXME: It'd be nice to be able to create the right type to start
8306       // with, but the type needs to reference the destructor declaration.
8307       if (SemaRef.getLangOpts().CPlusPlus11)
8308         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8309 
8310       IsVirtualOkay = true;
8311       return NewDD;
8312 
8313     } else {
8314       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8315       D.setInvalidType();
8316 
8317       // Create a FunctionDecl to satisfy the function definition parsing
8318       // code path.
8319       return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8320                                   D.getIdentifierLoc(), Name, R, TInfo, SC,
8321                                   isInline,
8322                                   /*hasPrototype=*/true, ConstexprKind,
8323                                   TrailingRequiresClause);
8324     }
8325 
8326   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8327     if (!DC->isRecord()) {
8328       SemaRef.Diag(D.getIdentifierLoc(),
8329            diag::err_conv_function_not_member);
8330       return nullptr;
8331     }
8332 
8333     SemaRef.CheckConversionDeclarator(D, R, SC);
8334     if (D.isInvalidType())
8335       return nullptr;
8336 
8337     IsVirtualOkay = true;
8338     return CXXConversionDecl::Create(
8339         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8340         TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(),
8341         TrailingRequiresClause);
8342 
8343   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8344     if (TrailingRequiresClause)
8345       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8346                    diag::err_trailing_requires_clause_on_deduction_guide)
8347           << TrailingRequiresClause->getSourceRange();
8348     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8349 
8350     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8351                                          ExplicitSpecifier, NameInfo, R, TInfo,
8352                                          D.getEndLoc());
8353   } else if (DC->isRecord()) {
8354     // If the name of the function is the same as the name of the record,
8355     // then this must be an invalid constructor that has a return type.
8356     // (The parser checks for a return type and makes the declarator a
8357     // constructor if it has no return type).
8358     if (Name.getAsIdentifierInfo() &&
8359         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8360       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8361         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8362         << SourceRange(D.getIdentifierLoc());
8363       return nullptr;
8364     }
8365 
8366     // This is a C++ method declaration.
8367     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8368         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8369         TInfo, SC, isInline, ConstexprKind, SourceLocation(),
8370         TrailingRequiresClause);
8371     IsVirtualOkay = !Ret->isStatic();
8372     return Ret;
8373   } else {
8374     bool isFriend =
8375         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8376     if (!isFriend && SemaRef.CurContext->isRecord())
8377       return nullptr;
8378 
8379     // Determine whether the function was written with a
8380     // prototype. This true when:
8381     //   - we're in C++ (where every function has a prototype),
8382     return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8383                                 R, TInfo, SC, isInline, true /*HasPrototype*/,
8384                                 ConstexprKind, TrailingRequiresClause);
8385   }
8386 }
8387 
8388 enum OpenCLParamType {
8389   ValidKernelParam,
8390   PtrPtrKernelParam,
8391   PtrKernelParam,
8392   InvalidAddrSpacePtrKernelParam,
8393   InvalidKernelParam,
8394   RecordKernelParam
8395 };
8396 
8397 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8398   // Size dependent types are just typedefs to normal integer types
8399   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8400   // integers other than by their names.
8401   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8402 
8403   // Remove typedefs one by one until we reach a typedef
8404   // for a size dependent type.
8405   QualType DesugaredTy = Ty;
8406   do {
8407     ArrayRef<StringRef> Names(SizeTypeNames);
8408     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8409     if (Names.end() != Match)
8410       return true;
8411 
8412     Ty = DesugaredTy;
8413     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8414   } while (DesugaredTy != Ty);
8415 
8416   return false;
8417 }
8418 
8419 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8420   if (PT->isPointerType()) {
8421     QualType PointeeType = PT->getPointeeType();
8422     if (PointeeType->isPointerType())
8423       return PtrPtrKernelParam;
8424     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8425         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8426         PointeeType.getAddressSpace() == LangAS::Default)
8427       return InvalidAddrSpacePtrKernelParam;
8428     return PtrKernelParam;
8429   }
8430 
8431   // OpenCL v1.2 s6.9.k:
8432   // Arguments to kernel functions in a program cannot be declared with the
8433   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8434   // uintptr_t or a struct and/or union that contain fields declared to be one
8435   // of these built-in scalar types.
8436   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8437     return InvalidKernelParam;
8438 
8439   if (PT->isImageType())
8440     return PtrKernelParam;
8441 
8442   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8443     return InvalidKernelParam;
8444 
8445   // OpenCL extension spec v1.2 s9.5:
8446   // This extension adds support for half scalar and vector types as built-in
8447   // types that can be used for arithmetic operations, conversions etc.
8448   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8449     return InvalidKernelParam;
8450 
8451   if (PT->isRecordType())
8452     return RecordKernelParam;
8453 
8454   // Look into an array argument to check if it has a forbidden type.
8455   if (PT->isArrayType()) {
8456     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8457     // Call ourself to check an underlying type of an array. Since the
8458     // getPointeeOrArrayElementType returns an innermost type which is not an
8459     // array, this recursive call only happens once.
8460     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8461   }
8462 
8463   return ValidKernelParam;
8464 }
8465 
8466 static void checkIsValidOpenCLKernelParameter(
8467   Sema &S,
8468   Declarator &D,
8469   ParmVarDecl *Param,
8470   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8471   QualType PT = Param->getType();
8472 
8473   // Cache the valid types we encounter to avoid rechecking structs that are
8474   // used again
8475   if (ValidTypes.count(PT.getTypePtr()))
8476     return;
8477 
8478   switch (getOpenCLKernelParameterType(S, PT)) {
8479   case PtrPtrKernelParam:
8480     // OpenCL v1.2 s6.9.a:
8481     // A kernel function argument cannot be declared as a
8482     // pointer to a pointer type.
8483     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8484     D.setInvalidType();
8485     return;
8486 
8487   case InvalidAddrSpacePtrKernelParam:
8488     // OpenCL v1.0 s6.5:
8489     // __kernel function arguments declared to be a pointer of a type can point
8490     // to one of the following address spaces only : __global, __local or
8491     // __constant.
8492     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8493     D.setInvalidType();
8494     return;
8495 
8496     // OpenCL v1.2 s6.9.k:
8497     // Arguments to kernel functions in a program cannot be declared with the
8498     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8499     // uintptr_t or a struct and/or union that contain fields declared to be
8500     // one of these built-in scalar types.
8501 
8502   case InvalidKernelParam:
8503     // OpenCL v1.2 s6.8 n:
8504     // A kernel function argument cannot be declared
8505     // of event_t type.
8506     // Do not diagnose half type since it is diagnosed as invalid argument
8507     // type for any function elsewhere.
8508     if (!PT->isHalfType()) {
8509       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8510 
8511       // Explain what typedefs are involved.
8512       const TypedefType *Typedef = nullptr;
8513       while ((Typedef = PT->getAs<TypedefType>())) {
8514         SourceLocation Loc = Typedef->getDecl()->getLocation();
8515         // SourceLocation may be invalid for a built-in type.
8516         if (Loc.isValid())
8517           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8518         PT = Typedef->desugar();
8519       }
8520     }
8521 
8522     D.setInvalidType();
8523     return;
8524 
8525   case PtrKernelParam:
8526   case ValidKernelParam:
8527     ValidTypes.insert(PT.getTypePtr());
8528     return;
8529 
8530   case RecordKernelParam:
8531     break;
8532   }
8533 
8534   // Track nested structs we will inspect
8535   SmallVector<const Decl *, 4> VisitStack;
8536 
8537   // Track where we are in the nested structs. Items will migrate from
8538   // VisitStack to HistoryStack as we do the DFS for bad field.
8539   SmallVector<const FieldDecl *, 4> HistoryStack;
8540   HistoryStack.push_back(nullptr);
8541 
8542   // At this point we already handled everything except of a RecordType or
8543   // an ArrayType of a RecordType.
8544   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8545   const RecordType *RecTy =
8546       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8547   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8548 
8549   VisitStack.push_back(RecTy->getDecl());
8550   assert(VisitStack.back() && "First decl null?");
8551 
8552   do {
8553     const Decl *Next = VisitStack.pop_back_val();
8554     if (!Next) {
8555       assert(!HistoryStack.empty());
8556       // Found a marker, we have gone up a level
8557       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8558         ValidTypes.insert(Hist->getType().getTypePtr());
8559 
8560       continue;
8561     }
8562 
8563     // Adds everything except the original parameter declaration (which is not a
8564     // field itself) to the history stack.
8565     const RecordDecl *RD;
8566     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8567       HistoryStack.push_back(Field);
8568 
8569       QualType FieldTy = Field->getType();
8570       // Other field types (known to be valid or invalid) are handled while we
8571       // walk around RecordDecl::fields().
8572       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8573              "Unexpected type.");
8574       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8575 
8576       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8577     } else {
8578       RD = cast<RecordDecl>(Next);
8579     }
8580 
8581     // Add a null marker so we know when we've gone back up a level
8582     VisitStack.push_back(nullptr);
8583 
8584     for (const auto *FD : RD->fields()) {
8585       QualType QT = FD->getType();
8586 
8587       if (ValidTypes.count(QT.getTypePtr()))
8588         continue;
8589 
8590       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8591       if (ParamType == ValidKernelParam)
8592         continue;
8593 
8594       if (ParamType == RecordKernelParam) {
8595         VisitStack.push_back(FD);
8596         continue;
8597       }
8598 
8599       // OpenCL v1.2 s6.9.p:
8600       // Arguments to kernel functions that are declared to be a struct or union
8601       // do not allow OpenCL objects to be passed as elements of the struct or
8602       // union.
8603       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8604           ParamType == InvalidAddrSpacePtrKernelParam) {
8605         S.Diag(Param->getLocation(),
8606                diag::err_record_with_pointers_kernel_param)
8607           << PT->isUnionType()
8608           << PT;
8609       } else {
8610         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8611       }
8612 
8613       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8614           << OrigRecDecl->getDeclName();
8615 
8616       // We have an error, now let's go back up through history and show where
8617       // the offending field came from
8618       for (ArrayRef<const FieldDecl *>::const_iterator
8619                I = HistoryStack.begin() + 1,
8620                E = HistoryStack.end();
8621            I != E; ++I) {
8622         const FieldDecl *OuterField = *I;
8623         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8624           << OuterField->getType();
8625       }
8626 
8627       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8628         << QT->isPointerType()
8629         << QT;
8630       D.setInvalidType();
8631       return;
8632     }
8633   } while (!VisitStack.empty());
8634 }
8635 
8636 /// Find the DeclContext in which a tag is implicitly declared if we see an
8637 /// elaborated type specifier in the specified context, and lookup finds
8638 /// nothing.
8639 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8640   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8641     DC = DC->getParent();
8642   return DC;
8643 }
8644 
8645 /// Find the Scope in which a tag is implicitly declared if we see an
8646 /// elaborated type specifier in the specified context, and lookup finds
8647 /// nothing.
8648 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8649   while (S->isClassScope() ||
8650          (LangOpts.CPlusPlus &&
8651           S->isFunctionPrototypeScope()) ||
8652          ((S->getFlags() & Scope::DeclScope) == 0) ||
8653          (S->getEntity() && S->getEntity()->isTransparentContext()))
8654     S = S->getParent();
8655   return S;
8656 }
8657 
8658 NamedDecl*
8659 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8660                               TypeSourceInfo *TInfo, LookupResult &Previous,
8661                               MultiTemplateParamsArg TemplateParamListsRef,
8662                               bool &AddToScope) {
8663   QualType R = TInfo->getType();
8664 
8665   assert(R->isFunctionType());
8666   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
8667   for (TemplateParameterList *TPL : TemplateParamListsRef)
8668     TemplateParamLists.push_back(TPL);
8669   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
8670     if (!TemplateParamLists.empty() &&
8671         Invented->getDepth() == TemplateParamLists.back()->getDepth())
8672       TemplateParamLists.back() = Invented;
8673     else
8674       TemplateParamLists.push_back(Invented);
8675   }
8676 
8677   // TODO: consider using NameInfo for diagnostic.
8678   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8679   DeclarationName Name = NameInfo.getName();
8680   StorageClass SC = getFunctionStorageClass(*this, D);
8681 
8682   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8683     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8684          diag::err_invalid_thread)
8685       << DeclSpec::getSpecifierName(TSCS);
8686 
8687   if (D.isFirstDeclarationOfMember())
8688     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8689                            D.getIdentifierLoc());
8690 
8691   bool isFriend = false;
8692   FunctionTemplateDecl *FunctionTemplate = nullptr;
8693   bool isMemberSpecialization = false;
8694   bool isFunctionTemplateSpecialization = false;
8695 
8696   bool isDependentClassScopeExplicitSpecialization = false;
8697   bool HasExplicitTemplateArgs = false;
8698   TemplateArgumentListInfo TemplateArgs;
8699 
8700   bool isVirtualOkay = false;
8701 
8702   DeclContext *OriginalDC = DC;
8703   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8704 
8705   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8706                                               isVirtualOkay);
8707   if (!NewFD) return nullptr;
8708 
8709   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8710     NewFD->setTopLevelDeclInObjCContainer();
8711 
8712   // Set the lexical context. If this is a function-scope declaration, or has a
8713   // C++ scope specifier, or is the object of a friend declaration, the lexical
8714   // context will be different from the semantic context.
8715   NewFD->setLexicalDeclContext(CurContext);
8716 
8717   if (IsLocalExternDecl)
8718     NewFD->setLocalExternDecl();
8719 
8720   if (getLangOpts().CPlusPlus) {
8721     bool isInline = D.getDeclSpec().isInlineSpecified();
8722     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8723     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
8724     isFriend = D.getDeclSpec().isFriendSpecified();
8725     if (isFriend && !isInline && D.isFunctionDefinition()) {
8726       // C++ [class.friend]p5
8727       //   A function can be defined in a friend declaration of a
8728       //   class . . . . Such a function is implicitly inline.
8729       NewFD->setImplicitlyInline();
8730     }
8731 
8732     // If this is a method defined in an __interface, and is not a constructor
8733     // or an overloaded operator, then set the pure flag (isVirtual will already
8734     // return true).
8735     if (const CXXRecordDecl *Parent =
8736           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8737       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8738         NewFD->setPure(true);
8739 
8740       // C++ [class.union]p2
8741       //   A union can have member functions, but not virtual functions.
8742       if (isVirtual && Parent->isUnion())
8743         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8744     }
8745 
8746     SetNestedNameSpecifier(*this, NewFD, D);
8747     isMemberSpecialization = false;
8748     isFunctionTemplateSpecialization = false;
8749     if (D.isInvalidType())
8750       NewFD->setInvalidDecl();
8751 
8752     // Match up the template parameter lists with the scope specifier, then
8753     // determine whether we have a template or a template specialization.
8754     bool Invalid = false;
8755     TemplateParameterList *TemplateParams =
8756         MatchTemplateParametersToScopeSpecifier(
8757             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8758             D.getCXXScopeSpec(),
8759             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8760                 ? D.getName().TemplateId
8761                 : nullptr,
8762             TemplateParamLists, isFriend, isMemberSpecialization,
8763             Invalid);
8764     if (TemplateParams) {
8765       if (TemplateParams->size() > 0) {
8766         // This is a function template
8767 
8768         // Check that we can declare a template here.
8769         if (CheckTemplateDeclScope(S, TemplateParams))
8770           NewFD->setInvalidDecl();
8771 
8772         // A destructor cannot be a template.
8773         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8774           Diag(NewFD->getLocation(), diag::err_destructor_template);
8775           NewFD->setInvalidDecl();
8776         }
8777 
8778         // If we're adding a template to a dependent context, we may need to
8779         // rebuilding some of the types used within the template parameter list,
8780         // now that we know what the current instantiation is.
8781         if (DC->isDependentContext()) {
8782           ContextRAII SavedContext(*this, DC);
8783           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8784             Invalid = true;
8785         }
8786 
8787         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8788                                                         NewFD->getLocation(),
8789                                                         Name, TemplateParams,
8790                                                         NewFD);
8791         FunctionTemplate->setLexicalDeclContext(CurContext);
8792         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8793 
8794         // For source fidelity, store the other template param lists.
8795         if (TemplateParamLists.size() > 1) {
8796           NewFD->setTemplateParameterListsInfo(Context,
8797               ArrayRef<TemplateParameterList *>(TemplateParamLists)
8798                   .drop_back(1));
8799         }
8800       } else {
8801         // This is a function template specialization.
8802         isFunctionTemplateSpecialization = true;
8803         // For source fidelity, store all the template param lists.
8804         if (TemplateParamLists.size() > 0)
8805           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8806 
8807         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8808         if (isFriend) {
8809           // We want to remove the "template<>", found here.
8810           SourceRange RemoveRange = TemplateParams->getSourceRange();
8811 
8812           // If we remove the template<> and the name is not a
8813           // template-id, we're actually silently creating a problem:
8814           // the friend declaration will refer to an untemplated decl,
8815           // and clearly the user wants a template specialization.  So
8816           // we need to insert '<>' after the name.
8817           SourceLocation InsertLoc;
8818           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8819             InsertLoc = D.getName().getSourceRange().getEnd();
8820             InsertLoc = getLocForEndOfToken(InsertLoc);
8821           }
8822 
8823           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8824             << Name << RemoveRange
8825             << FixItHint::CreateRemoval(RemoveRange)
8826             << FixItHint::CreateInsertion(InsertLoc, "<>");
8827         }
8828       }
8829     } else {
8830       // All template param lists were matched against the scope specifier:
8831       // this is NOT (an explicit specialization of) a template.
8832       if (TemplateParamLists.size() > 0)
8833         // For source fidelity, store all the template param lists.
8834         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8835     }
8836 
8837     if (Invalid) {
8838       NewFD->setInvalidDecl();
8839       if (FunctionTemplate)
8840         FunctionTemplate->setInvalidDecl();
8841     }
8842 
8843     // C++ [dcl.fct.spec]p5:
8844     //   The virtual specifier shall only be used in declarations of
8845     //   nonstatic class member functions that appear within a
8846     //   member-specification of a class declaration; see 10.3.
8847     //
8848     if (isVirtual && !NewFD->isInvalidDecl()) {
8849       if (!isVirtualOkay) {
8850         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8851              diag::err_virtual_non_function);
8852       } else if (!CurContext->isRecord()) {
8853         // 'virtual' was specified outside of the class.
8854         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8855              diag::err_virtual_out_of_class)
8856           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8857       } else if (NewFD->getDescribedFunctionTemplate()) {
8858         // C++ [temp.mem]p3:
8859         //  A member function template shall not be virtual.
8860         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8861              diag::err_virtual_member_function_template)
8862           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8863       } else {
8864         // Okay: Add virtual to the method.
8865         NewFD->setVirtualAsWritten(true);
8866       }
8867 
8868       if (getLangOpts().CPlusPlus14 &&
8869           NewFD->getReturnType()->isUndeducedType())
8870         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8871     }
8872 
8873     if (getLangOpts().CPlusPlus14 &&
8874         (NewFD->isDependentContext() ||
8875          (isFriend && CurContext->isDependentContext())) &&
8876         NewFD->getReturnType()->isUndeducedType()) {
8877       // If the function template is referenced directly (for instance, as a
8878       // member of the current instantiation), pretend it has a dependent type.
8879       // This is not really justified by the standard, but is the only sane
8880       // thing to do.
8881       // FIXME: For a friend function, we have not marked the function as being
8882       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8883       const FunctionProtoType *FPT =
8884           NewFD->getType()->castAs<FunctionProtoType>();
8885       QualType Result =
8886           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8887       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8888                                              FPT->getExtProtoInfo()));
8889     }
8890 
8891     // C++ [dcl.fct.spec]p3:
8892     //  The inline specifier shall not appear on a block scope function
8893     //  declaration.
8894     if (isInline && !NewFD->isInvalidDecl()) {
8895       if (CurContext->isFunctionOrMethod()) {
8896         // 'inline' is not allowed on block scope function declaration.
8897         Diag(D.getDeclSpec().getInlineSpecLoc(),
8898              diag::err_inline_declaration_block_scope) << Name
8899           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8900       }
8901     }
8902 
8903     // C++ [dcl.fct.spec]p6:
8904     //  The explicit specifier shall be used only in the declaration of a
8905     //  constructor or conversion function within its class definition;
8906     //  see 12.3.1 and 12.3.2.
8907     if (hasExplicit && !NewFD->isInvalidDecl() &&
8908         !isa<CXXDeductionGuideDecl>(NewFD)) {
8909       if (!CurContext->isRecord()) {
8910         // 'explicit' was specified outside of the class.
8911         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8912              diag::err_explicit_out_of_class)
8913             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
8914       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8915                  !isa<CXXConversionDecl>(NewFD)) {
8916         // 'explicit' was specified on a function that wasn't a constructor
8917         // or conversion function.
8918         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8919              diag::err_explicit_non_ctor_or_conv_function)
8920             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
8921       }
8922     }
8923 
8924     if (ConstexprSpecKind ConstexprKind =
8925             D.getDeclSpec().getConstexprSpecifier()) {
8926       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8927       // are implicitly inline.
8928       NewFD->setImplicitlyInline();
8929 
8930       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8931       // be either constructors or to return a literal type. Therefore,
8932       // destructors cannot be declared constexpr.
8933       if (isa<CXXDestructorDecl>(NewFD) &&
8934           (!getLangOpts().CPlusPlus2a || ConstexprKind == CSK_consteval)) {
8935         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
8936             << ConstexprKind;
8937         NewFD->setConstexprKind(getLangOpts().CPlusPlus2a ? CSK_unspecified : CSK_constexpr);
8938       }
8939       // C++20 [dcl.constexpr]p2: An allocation function, or a
8940       // deallocation function shall not be declared with the consteval
8941       // specifier.
8942       if (ConstexprKind == CSK_consteval &&
8943           (NewFD->getOverloadedOperator() == OO_New ||
8944            NewFD->getOverloadedOperator() == OO_Array_New ||
8945            NewFD->getOverloadedOperator() == OO_Delete ||
8946            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
8947         Diag(D.getDeclSpec().getConstexprSpecLoc(),
8948              diag::err_invalid_consteval_decl_kind)
8949             << NewFD;
8950         NewFD->setConstexprKind(CSK_constexpr);
8951       }
8952     }
8953 
8954     // If __module_private__ was specified, mark the function accordingly.
8955     if (D.getDeclSpec().isModulePrivateSpecified()) {
8956       if (isFunctionTemplateSpecialization) {
8957         SourceLocation ModulePrivateLoc
8958           = D.getDeclSpec().getModulePrivateSpecLoc();
8959         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8960           << 0
8961           << FixItHint::CreateRemoval(ModulePrivateLoc);
8962       } else {
8963         NewFD->setModulePrivate();
8964         if (FunctionTemplate)
8965           FunctionTemplate->setModulePrivate();
8966       }
8967     }
8968 
8969     if (isFriend) {
8970       if (FunctionTemplate) {
8971         FunctionTemplate->setObjectOfFriendDecl();
8972         FunctionTemplate->setAccess(AS_public);
8973       }
8974       NewFD->setObjectOfFriendDecl();
8975       NewFD->setAccess(AS_public);
8976     }
8977 
8978     // If a function is defined as defaulted or deleted, mark it as such now.
8979     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8980     // definition kind to FDK_Definition.
8981     switch (D.getFunctionDefinitionKind()) {
8982       case FDK_Declaration:
8983       case FDK_Definition:
8984         break;
8985 
8986       case FDK_Defaulted:
8987         NewFD->setDefaulted();
8988         break;
8989 
8990       case FDK_Deleted:
8991         NewFD->setDeletedAsWritten();
8992         break;
8993     }
8994 
8995     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8996         D.isFunctionDefinition()) {
8997       // C++ [class.mfct]p2:
8998       //   A member function may be defined (8.4) in its class definition, in
8999       //   which case it is an inline member function (7.1.2)
9000       NewFD->setImplicitlyInline();
9001     }
9002 
9003     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9004         !CurContext->isRecord()) {
9005       // C++ [class.static]p1:
9006       //   A data or function member of a class may be declared static
9007       //   in a class definition, in which case it is a static member of
9008       //   the class.
9009 
9010       // Complain about the 'static' specifier if it's on an out-of-line
9011       // member function definition.
9012 
9013       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9014       // member function template declaration and class member template
9015       // declaration (MSVC versions before 2015), warn about this.
9016       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9017            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9018              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9019            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9020            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9021         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9022     }
9023 
9024     // C++11 [except.spec]p15:
9025     //   A deallocation function with no exception-specification is treated
9026     //   as if it were specified with noexcept(true).
9027     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9028     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9029          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9030         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9031       NewFD->setType(Context.getFunctionType(
9032           FPT->getReturnType(), FPT->getParamTypes(),
9033           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9034   }
9035 
9036   // Filter out previous declarations that don't match the scope.
9037   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9038                        D.getCXXScopeSpec().isNotEmpty() ||
9039                        isMemberSpecialization ||
9040                        isFunctionTemplateSpecialization);
9041 
9042   // Handle GNU asm-label extension (encoded as an attribute).
9043   if (Expr *E = (Expr*) D.getAsmLabel()) {
9044     // The parser guarantees this is a string.
9045     StringLiteral *SE = cast<StringLiteral>(E);
9046     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9047                                         /*IsLiteralLabel=*/true,
9048                                         SE->getStrTokenLoc(0)));
9049   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9050     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9051       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9052     if (I != ExtnameUndeclaredIdentifiers.end()) {
9053       if (isDeclExternC(NewFD)) {
9054         NewFD->addAttr(I->second);
9055         ExtnameUndeclaredIdentifiers.erase(I);
9056       } else
9057         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9058             << /*Variable*/0 << NewFD;
9059     }
9060   }
9061 
9062   // Copy the parameter declarations from the declarator D to the function
9063   // declaration NewFD, if they are available.  First scavenge them into Params.
9064   SmallVector<ParmVarDecl*, 16> Params;
9065   unsigned FTIIdx;
9066   if (D.isFunctionDeclarator(FTIIdx)) {
9067     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9068 
9069     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9070     // function that takes no arguments, not a function that takes a
9071     // single void argument.
9072     // We let through "const void" here because Sema::GetTypeForDeclarator
9073     // already checks for that case.
9074     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9075       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9076         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9077         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9078         Param->setDeclContext(NewFD);
9079         Params.push_back(Param);
9080 
9081         if (Param->isInvalidDecl())
9082           NewFD->setInvalidDecl();
9083       }
9084     }
9085 
9086     if (!getLangOpts().CPlusPlus) {
9087       // In C, find all the tag declarations from the prototype and move them
9088       // into the function DeclContext. Remove them from the surrounding tag
9089       // injection context of the function, which is typically but not always
9090       // the TU.
9091       DeclContext *PrototypeTagContext =
9092           getTagInjectionContext(NewFD->getLexicalDeclContext());
9093       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9094         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9095 
9096         // We don't want to reparent enumerators. Look at their parent enum
9097         // instead.
9098         if (!TD) {
9099           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9100             TD = cast<EnumDecl>(ECD->getDeclContext());
9101         }
9102         if (!TD)
9103           continue;
9104         DeclContext *TagDC = TD->getLexicalDeclContext();
9105         if (!TagDC->containsDecl(TD))
9106           continue;
9107         TagDC->removeDecl(TD);
9108         TD->setDeclContext(NewFD);
9109         NewFD->addDecl(TD);
9110 
9111         // Preserve the lexical DeclContext if it is not the surrounding tag
9112         // injection context of the FD. In this example, the semantic context of
9113         // E will be f and the lexical context will be S, while both the
9114         // semantic and lexical contexts of S will be f:
9115         //   void f(struct S { enum E { a } f; } s);
9116         if (TagDC != PrototypeTagContext)
9117           TD->setLexicalDeclContext(TagDC);
9118       }
9119     }
9120   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9121     // When we're declaring a function with a typedef, typeof, etc as in the
9122     // following example, we'll need to synthesize (unnamed)
9123     // parameters for use in the declaration.
9124     //
9125     // @code
9126     // typedef void fn(int);
9127     // fn f;
9128     // @endcode
9129 
9130     // Synthesize a parameter for each argument type.
9131     for (const auto &AI : FT->param_types()) {
9132       ParmVarDecl *Param =
9133           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9134       Param->setScopeInfo(0, Params.size());
9135       Params.push_back(Param);
9136     }
9137   } else {
9138     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9139            "Should not need args for typedef of non-prototype fn");
9140   }
9141 
9142   // Finally, we know we have the right number of parameters, install them.
9143   NewFD->setParams(Params);
9144 
9145   if (D.getDeclSpec().isNoreturnSpecified())
9146     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9147                                            D.getDeclSpec().getNoreturnSpecLoc(),
9148                                            AttributeCommonInfo::AS_Keyword));
9149 
9150   // Functions returning a variably modified type violate C99 6.7.5.2p2
9151   // because all functions have linkage.
9152   if (!NewFD->isInvalidDecl() &&
9153       NewFD->getReturnType()->isVariablyModifiedType()) {
9154     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9155     NewFD->setInvalidDecl();
9156   }
9157 
9158   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9159   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9160       !NewFD->hasAttr<SectionAttr>())
9161     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9162         Context, PragmaClangTextSection.SectionName,
9163         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9164 
9165   // Apply an implicit SectionAttr if #pragma code_seg is active.
9166   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9167       !NewFD->hasAttr<SectionAttr>()) {
9168     NewFD->addAttr(SectionAttr::CreateImplicit(
9169         Context, CodeSegStack.CurrentValue->getString(),
9170         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9171         SectionAttr::Declspec_allocate));
9172     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9173                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9174                          ASTContext::PSF_Read,
9175                      NewFD))
9176       NewFD->dropAttr<SectionAttr>();
9177   }
9178 
9179   // Apply an implicit CodeSegAttr from class declspec or
9180   // apply an implicit SectionAttr from #pragma code_seg if active.
9181   if (!NewFD->hasAttr<CodeSegAttr>()) {
9182     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9183                                                                  D.isFunctionDefinition())) {
9184       NewFD->addAttr(SAttr);
9185     }
9186   }
9187 
9188   // Handle attributes.
9189   ProcessDeclAttributes(S, NewFD, D);
9190 
9191   if (getLangOpts().OpenCL) {
9192     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9193     // type declaration will generate a compilation error.
9194     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9195     if (AddressSpace != LangAS::Default) {
9196       Diag(NewFD->getLocation(),
9197            diag::err_opencl_return_value_with_address_space);
9198       NewFD->setInvalidDecl();
9199     }
9200   }
9201 
9202   if (!getLangOpts().CPlusPlus) {
9203     // Perform semantic checking on the function declaration.
9204     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9205       CheckMain(NewFD, D.getDeclSpec());
9206 
9207     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9208       CheckMSVCRTEntryPoint(NewFD);
9209 
9210     if (!NewFD->isInvalidDecl())
9211       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9212                                                   isMemberSpecialization));
9213     else if (!Previous.empty())
9214       // Recover gracefully from an invalid redeclaration.
9215       D.setRedeclaration(true);
9216     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9217             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9218            "previous declaration set still overloaded");
9219 
9220     // Diagnose no-prototype function declarations with calling conventions that
9221     // don't support variadic calls. Only do this in C and do it after merging
9222     // possibly prototyped redeclarations.
9223     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9224     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9225       CallingConv CC = FT->getExtInfo().getCC();
9226       if (!supportsVariadicCall(CC)) {
9227         // Windows system headers sometimes accidentally use stdcall without
9228         // (void) parameters, so we relax this to a warning.
9229         int DiagID =
9230             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9231         Diag(NewFD->getLocation(), DiagID)
9232             << FunctionType::getNameForCallConv(CC);
9233       }
9234     }
9235 
9236    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9237        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9238      checkNonTrivialCUnion(NewFD->getReturnType(),
9239                            NewFD->getReturnTypeSourceRange().getBegin(),
9240                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9241   } else {
9242     // C++11 [replacement.functions]p3:
9243     //  The program's definitions shall not be specified as inline.
9244     //
9245     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9246     //
9247     // Suppress the diagnostic if the function is __attribute__((used)), since
9248     // that forces an external definition to be emitted.
9249     if (D.getDeclSpec().isInlineSpecified() &&
9250         NewFD->isReplaceableGlobalAllocationFunction() &&
9251         !NewFD->hasAttr<UsedAttr>())
9252       Diag(D.getDeclSpec().getInlineSpecLoc(),
9253            diag::ext_operator_new_delete_declared_inline)
9254         << NewFD->getDeclName();
9255 
9256     // If the declarator is a template-id, translate the parser's template
9257     // argument list into our AST format.
9258     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9259       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9260       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9261       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9262       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9263                                          TemplateId->NumArgs);
9264       translateTemplateArguments(TemplateArgsPtr,
9265                                  TemplateArgs);
9266 
9267       HasExplicitTemplateArgs = true;
9268 
9269       if (NewFD->isInvalidDecl()) {
9270         HasExplicitTemplateArgs = false;
9271       } else if (FunctionTemplate) {
9272         // Function template with explicit template arguments.
9273         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9274           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9275 
9276         HasExplicitTemplateArgs = false;
9277       } else {
9278         assert((isFunctionTemplateSpecialization ||
9279                 D.getDeclSpec().isFriendSpecified()) &&
9280                "should have a 'template<>' for this decl");
9281         // "friend void foo<>(int);" is an implicit specialization decl.
9282         isFunctionTemplateSpecialization = true;
9283       }
9284     } else if (isFriend && isFunctionTemplateSpecialization) {
9285       // This combination is only possible in a recovery case;  the user
9286       // wrote something like:
9287       //   template <> friend void foo(int);
9288       // which we're recovering from as if the user had written:
9289       //   friend void foo<>(int);
9290       // Go ahead and fake up a template id.
9291       HasExplicitTemplateArgs = true;
9292       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9293       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9294     }
9295 
9296     // We do not add HD attributes to specializations here because
9297     // they may have different constexpr-ness compared to their
9298     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9299     // may end up with different effective targets. Instead, a
9300     // specialization inherits its target attributes from its template
9301     // in the CheckFunctionTemplateSpecialization() call below.
9302     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9303       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9304 
9305     // If it's a friend (and only if it's a friend), it's possible
9306     // that either the specialized function type or the specialized
9307     // template is dependent, and therefore matching will fail.  In
9308     // this case, don't check the specialization yet.
9309     bool InstantiationDependent = false;
9310     if (isFunctionTemplateSpecialization && isFriend &&
9311         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9312          TemplateSpecializationType::anyDependentTemplateArguments(
9313             TemplateArgs,
9314             InstantiationDependent))) {
9315       assert(HasExplicitTemplateArgs &&
9316              "friend function specialization without template args");
9317       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9318                                                        Previous))
9319         NewFD->setInvalidDecl();
9320     } else if (isFunctionTemplateSpecialization) {
9321       if (CurContext->isDependentContext() && CurContext->isRecord()
9322           && !isFriend) {
9323         isDependentClassScopeExplicitSpecialization = true;
9324       } else if (!NewFD->isInvalidDecl() &&
9325                  CheckFunctionTemplateSpecialization(
9326                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9327                      Previous))
9328         NewFD->setInvalidDecl();
9329 
9330       // C++ [dcl.stc]p1:
9331       //   A storage-class-specifier shall not be specified in an explicit
9332       //   specialization (14.7.3)
9333       FunctionTemplateSpecializationInfo *Info =
9334           NewFD->getTemplateSpecializationInfo();
9335       if (Info && SC != SC_None) {
9336         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9337           Diag(NewFD->getLocation(),
9338                diag::err_explicit_specialization_inconsistent_storage_class)
9339             << SC
9340             << FixItHint::CreateRemoval(
9341                                       D.getDeclSpec().getStorageClassSpecLoc());
9342 
9343         else
9344           Diag(NewFD->getLocation(),
9345                diag::ext_explicit_specialization_storage_class)
9346             << FixItHint::CreateRemoval(
9347                                       D.getDeclSpec().getStorageClassSpecLoc());
9348       }
9349     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9350       if (CheckMemberSpecialization(NewFD, Previous))
9351           NewFD->setInvalidDecl();
9352     }
9353 
9354     // Perform semantic checking on the function declaration.
9355     if (!isDependentClassScopeExplicitSpecialization) {
9356       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9357         CheckMain(NewFD, D.getDeclSpec());
9358 
9359       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9360         CheckMSVCRTEntryPoint(NewFD);
9361 
9362       if (!NewFD->isInvalidDecl())
9363         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9364                                                     isMemberSpecialization));
9365       else if (!Previous.empty())
9366         // Recover gracefully from an invalid redeclaration.
9367         D.setRedeclaration(true);
9368     }
9369 
9370     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9371             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9372            "previous declaration set still overloaded");
9373 
9374     NamedDecl *PrincipalDecl = (FunctionTemplate
9375                                 ? cast<NamedDecl>(FunctionTemplate)
9376                                 : NewFD);
9377 
9378     if (isFriend && NewFD->getPreviousDecl()) {
9379       AccessSpecifier Access = AS_public;
9380       if (!NewFD->isInvalidDecl())
9381         Access = NewFD->getPreviousDecl()->getAccess();
9382 
9383       NewFD->setAccess(Access);
9384       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9385     }
9386 
9387     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9388         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9389       PrincipalDecl->setNonMemberOperator();
9390 
9391     // If we have a function template, check the template parameter
9392     // list. This will check and merge default template arguments.
9393     if (FunctionTemplate) {
9394       FunctionTemplateDecl *PrevTemplate =
9395                                      FunctionTemplate->getPreviousDecl();
9396       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9397                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9398                                     : nullptr,
9399                             D.getDeclSpec().isFriendSpecified()
9400                               ? (D.isFunctionDefinition()
9401                                    ? TPC_FriendFunctionTemplateDefinition
9402                                    : TPC_FriendFunctionTemplate)
9403                               : (D.getCXXScopeSpec().isSet() &&
9404                                  DC && DC->isRecord() &&
9405                                  DC->isDependentContext())
9406                                   ? TPC_ClassTemplateMember
9407                                   : TPC_FunctionTemplate);
9408     }
9409 
9410     if (NewFD->isInvalidDecl()) {
9411       // Ignore all the rest of this.
9412     } else if (!D.isRedeclaration()) {
9413       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9414                                        AddToScope };
9415       // Fake up an access specifier if it's supposed to be a class member.
9416       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9417         NewFD->setAccess(AS_public);
9418 
9419       // Qualified decls generally require a previous declaration.
9420       if (D.getCXXScopeSpec().isSet()) {
9421         // ...with the major exception of templated-scope or
9422         // dependent-scope friend declarations.
9423 
9424         // TODO: we currently also suppress this check in dependent
9425         // contexts because (1) the parameter depth will be off when
9426         // matching friend templates and (2) we might actually be
9427         // selecting a friend based on a dependent factor.  But there
9428         // are situations where these conditions don't apply and we
9429         // can actually do this check immediately.
9430         //
9431         // Unless the scope is dependent, it's always an error if qualified
9432         // redeclaration lookup found nothing at all. Diagnose that now;
9433         // nothing will diagnose that error later.
9434         if (isFriend &&
9435             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9436              (!Previous.empty() && CurContext->isDependentContext()))) {
9437           // ignore these
9438         } else {
9439           // The user tried to provide an out-of-line definition for a
9440           // function that is a member of a class or namespace, but there
9441           // was no such member function declared (C++ [class.mfct]p2,
9442           // C++ [namespace.memdef]p2). For example:
9443           //
9444           // class X {
9445           //   void f() const;
9446           // };
9447           //
9448           // void X::f() { } // ill-formed
9449           //
9450           // Complain about this problem, and attempt to suggest close
9451           // matches (e.g., those that differ only in cv-qualifiers and
9452           // whether the parameter types are references).
9453 
9454           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9455                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9456             AddToScope = ExtraArgs.AddToScope;
9457             return Result;
9458           }
9459         }
9460 
9461         // Unqualified local friend declarations are required to resolve
9462         // to something.
9463       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9464         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9465                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9466           AddToScope = ExtraArgs.AddToScope;
9467           return Result;
9468         }
9469       }
9470     } else if (!D.isFunctionDefinition() &&
9471                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9472                !isFriend && !isFunctionTemplateSpecialization &&
9473                !isMemberSpecialization) {
9474       // An out-of-line member function declaration must also be a
9475       // definition (C++ [class.mfct]p2).
9476       // Note that this is not the case for explicit specializations of
9477       // function templates or member functions of class templates, per
9478       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9479       // extension for compatibility with old SWIG code which likes to
9480       // generate them.
9481       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9482         << D.getCXXScopeSpec().getRange();
9483     }
9484   }
9485 
9486   ProcessPragmaWeak(S, NewFD);
9487   checkAttributesAfterMerging(*this, *NewFD);
9488 
9489   AddKnownFunctionAttributes(NewFD);
9490 
9491   if (NewFD->hasAttr<OverloadableAttr>() &&
9492       !NewFD->getType()->getAs<FunctionProtoType>()) {
9493     Diag(NewFD->getLocation(),
9494          diag::err_attribute_overloadable_no_prototype)
9495       << NewFD;
9496 
9497     // Turn this into a variadic function with no parameters.
9498     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9499     FunctionProtoType::ExtProtoInfo EPI(
9500         Context.getDefaultCallingConvention(true, false));
9501     EPI.Variadic = true;
9502     EPI.ExtInfo = FT->getExtInfo();
9503 
9504     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9505     NewFD->setType(R);
9506   }
9507 
9508   // If there's a #pragma GCC visibility in scope, and this isn't a class
9509   // member, set the visibility of this function.
9510   if (!DC->isRecord() && NewFD->isExternallyVisible())
9511     AddPushedVisibilityAttribute(NewFD);
9512 
9513   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9514   // marking the function.
9515   AddCFAuditedAttribute(NewFD);
9516 
9517   // If this is a function definition, check if we have to apply optnone due to
9518   // a pragma.
9519   if(D.isFunctionDefinition())
9520     AddRangeBasedOptnone(NewFD);
9521 
9522   // If this is the first declaration of an extern C variable, update
9523   // the map of such variables.
9524   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9525       isIncompleteDeclExternC(*this, NewFD))
9526     RegisterLocallyScopedExternCDecl(NewFD, S);
9527 
9528   // Set this FunctionDecl's range up to the right paren.
9529   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9530 
9531   if (D.isRedeclaration() && !Previous.empty()) {
9532     NamedDecl *Prev = Previous.getRepresentativeDecl();
9533     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9534                                    isMemberSpecialization ||
9535                                        isFunctionTemplateSpecialization,
9536                                    D.isFunctionDefinition());
9537   }
9538 
9539   if (getLangOpts().CUDA) {
9540     IdentifierInfo *II = NewFD->getIdentifier();
9541     if (II && II->isStr(getCudaConfigureFuncName()) &&
9542         !NewFD->isInvalidDecl() &&
9543         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9544       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9545         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9546             << getCudaConfigureFuncName();
9547       Context.setcudaConfigureCallDecl(NewFD);
9548     }
9549 
9550     // Variadic functions, other than a *declaration* of printf, are not allowed
9551     // in device-side CUDA code, unless someone passed
9552     // -fcuda-allow-variadic-functions.
9553     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9554         (NewFD->hasAttr<CUDADeviceAttr>() ||
9555          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9556         !(II && II->isStr("printf") && NewFD->isExternC() &&
9557           !D.isFunctionDefinition())) {
9558       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9559     }
9560   }
9561 
9562   MarkUnusedFileScopedDecl(NewFD);
9563 
9564 
9565 
9566   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9567     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9568     if ((getLangOpts().OpenCLVersion >= 120)
9569         && (SC == SC_Static)) {
9570       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9571       D.setInvalidType();
9572     }
9573 
9574     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9575     if (!NewFD->getReturnType()->isVoidType()) {
9576       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9577       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9578           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9579                                 : FixItHint());
9580       D.setInvalidType();
9581     }
9582 
9583     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9584     for (auto Param : NewFD->parameters())
9585       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9586 
9587     if (getLangOpts().OpenCLCPlusPlus) {
9588       if (DC->isRecord()) {
9589         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9590         D.setInvalidType();
9591       }
9592       if (FunctionTemplate) {
9593         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9594         D.setInvalidType();
9595       }
9596     }
9597   }
9598 
9599   if (getLangOpts().CPlusPlus) {
9600     if (FunctionTemplate) {
9601       if (NewFD->isInvalidDecl())
9602         FunctionTemplate->setInvalidDecl();
9603       return FunctionTemplate;
9604     }
9605 
9606     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9607       CompleteMemberSpecialization(NewFD, Previous);
9608   }
9609 
9610   for (const ParmVarDecl *Param : NewFD->parameters()) {
9611     QualType PT = Param->getType();
9612 
9613     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9614     // types.
9615     if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
9616       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9617         QualType ElemTy = PipeTy->getElementType();
9618           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9619             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9620             D.setInvalidType();
9621           }
9622       }
9623     }
9624   }
9625 
9626   // Here we have an function template explicit specialization at class scope.
9627   // The actual specialization will be postponed to template instatiation
9628   // time via the ClassScopeFunctionSpecializationDecl node.
9629   if (isDependentClassScopeExplicitSpecialization) {
9630     ClassScopeFunctionSpecializationDecl *NewSpec =
9631                          ClassScopeFunctionSpecializationDecl::Create(
9632                                 Context, CurContext, NewFD->getLocation(),
9633                                 cast<CXXMethodDecl>(NewFD),
9634                                 HasExplicitTemplateArgs, TemplateArgs);
9635     CurContext->addDecl(NewSpec);
9636     AddToScope = false;
9637   }
9638 
9639   // Diagnose availability attributes. Availability cannot be used on functions
9640   // that are run during load/unload.
9641   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9642     if (NewFD->hasAttr<ConstructorAttr>()) {
9643       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9644           << 1;
9645       NewFD->dropAttr<AvailabilityAttr>();
9646     }
9647     if (NewFD->hasAttr<DestructorAttr>()) {
9648       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9649           << 2;
9650       NewFD->dropAttr<AvailabilityAttr>();
9651     }
9652   }
9653 
9654   // Diagnose no_builtin attribute on function declaration that are not a
9655   // definition.
9656   // FIXME: We should really be doing this in
9657   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
9658   // the FunctionDecl and at this point of the code
9659   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
9660   // because Sema::ActOnStartOfFunctionDef has not been called yet.
9661   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
9662     switch (D.getFunctionDefinitionKind()) {
9663     case FDK_Defaulted:
9664     case FDK_Deleted:
9665       Diag(NBA->getLocation(),
9666            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
9667           << NBA->getSpelling();
9668       break;
9669     case FDK_Declaration:
9670       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
9671           << NBA->getSpelling();
9672       break;
9673     case FDK_Definition:
9674       break;
9675     }
9676 
9677   return NewFD;
9678 }
9679 
9680 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
9681 /// when __declspec(code_seg) "is applied to a class, all member functions of
9682 /// the class and nested classes -- this includes compiler-generated special
9683 /// member functions -- are put in the specified segment."
9684 /// The actual behavior is a little more complicated. The Microsoft compiler
9685 /// won't check outer classes if there is an active value from #pragma code_seg.
9686 /// The CodeSeg is always applied from the direct parent but only from outer
9687 /// classes when the #pragma code_seg stack is empty. See:
9688 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9689 /// available since MS has removed the page.
9690 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9691   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9692   if (!Method)
9693     return nullptr;
9694   const CXXRecordDecl *Parent = Method->getParent();
9695   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9696     Attr *NewAttr = SAttr->clone(S.getASTContext());
9697     NewAttr->setImplicit(true);
9698     return NewAttr;
9699   }
9700 
9701   // The Microsoft compiler won't check outer classes for the CodeSeg
9702   // when the #pragma code_seg stack is active.
9703   if (S.CodeSegStack.CurrentValue)
9704    return nullptr;
9705 
9706   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9707     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9708       Attr *NewAttr = SAttr->clone(S.getASTContext());
9709       NewAttr->setImplicit(true);
9710       return NewAttr;
9711     }
9712   }
9713   return nullptr;
9714 }
9715 
9716 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9717 /// containing class. Otherwise it will return implicit SectionAttr if the
9718 /// function is a definition and there is an active value on CodeSegStack
9719 /// (from the current #pragma code-seg value).
9720 ///
9721 /// \param FD Function being declared.
9722 /// \param IsDefinition Whether it is a definition or just a declarartion.
9723 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
9724 ///          nullptr if no attribute should be added.
9725 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9726                                                        bool IsDefinition) {
9727   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9728     return A;
9729   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9730       CodeSegStack.CurrentValue)
9731     return SectionAttr::CreateImplicit(
9732         getASTContext(), CodeSegStack.CurrentValue->getString(),
9733         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9734         SectionAttr::Declspec_allocate);
9735   return nullptr;
9736 }
9737 
9738 /// Determines if we can perform a correct type check for \p D as a
9739 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
9740 /// best-effort check.
9741 ///
9742 /// \param NewD The new declaration.
9743 /// \param OldD The old declaration.
9744 /// \param NewT The portion of the type of the new declaration to check.
9745 /// \param OldT The portion of the type of the old declaration to check.
9746 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
9747                                           QualType NewT, QualType OldT) {
9748   if (!NewD->getLexicalDeclContext()->isDependentContext())
9749     return true;
9750 
9751   // For dependently-typed local extern declarations and friends, we can't
9752   // perform a correct type check in general until instantiation:
9753   //
9754   //   int f();
9755   //   template<typename T> void g() { T f(); }
9756   //
9757   // (valid if g() is only instantiated with T = int).
9758   if (NewT->isDependentType() &&
9759       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
9760     return false;
9761 
9762   // Similarly, if the previous declaration was a dependent local extern
9763   // declaration, we don't really know its type yet.
9764   if (OldT->isDependentType() && OldD->isLocalExternDecl())
9765     return false;
9766 
9767   return true;
9768 }
9769 
9770 /// Checks if the new declaration declared in dependent context must be
9771 /// put in the same redeclaration chain as the specified declaration.
9772 ///
9773 /// \param D Declaration that is checked.
9774 /// \param PrevDecl Previous declaration found with proper lookup method for the
9775 ///                 same declaration name.
9776 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9777 ///          belongs to.
9778 ///
9779 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9780   if (!D->getLexicalDeclContext()->isDependentContext())
9781     return true;
9782 
9783   // Don't chain dependent friend function definitions until instantiation, to
9784   // permit cases like
9785   //
9786   //   void func();
9787   //   template<typename T> class C1 { friend void func() {} };
9788   //   template<typename T> class C2 { friend void func() {} };
9789   //
9790   // ... which is valid if only one of C1 and C2 is ever instantiated.
9791   //
9792   // FIXME: This need only apply to function definitions. For now, we proxy
9793   // this by checking for a file-scope function. We do not want this to apply
9794   // to friend declarations nominating member functions, because that gets in
9795   // the way of access checks.
9796   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
9797     return false;
9798 
9799   auto *VD = dyn_cast<ValueDecl>(D);
9800   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
9801   return !VD || !PrevVD ||
9802          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
9803                                         PrevVD->getType());
9804 }
9805 
9806 /// Check the target attribute of the function for MultiVersion
9807 /// validity.
9808 ///
9809 /// Returns true if there was an error, false otherwise.
9810 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9811   const auto *TA = FD->getAttr<TargetAttr>();
9812   assert(TA && "MultiVersion Candidate requires a target attribute");
9813   ParsedTargetAttr ParseInfo = TA->parse();
9814   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9815   enum ErrType { Feature = 0, Architecture = 1 };
9816 
9817   if (!ParseInfo.Architecture.empty() &&
9818       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
9819     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9820         << Architecture << ParseInfo.Architecture;
9821     return true;
9822   }
9823 
9824   for (const auto &Feat : ParseInfo.Features) {
9825     auto BareFeat = StringRef{Feat}.substr(1);
9826     if (Feat[0] == '-') {
9827       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9828           << Feature << ("no-" + BareFeat).str();
9829       return true;
9830     }
9831 
9832     if (!TargetInfo.validateCpuSupports(BareFeat) ||
9833         !TargetInfo.isValidFeatureName(BareFeat)) {
9834       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9835           << Feature << BareFeat;
9836       return true;
9837     }
9838   }
9839   return false;
9840 }
9841 
9842 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD,
9843                                          MultiVersionKind MVType) {
9844   for (const Attr *A : FD->attrs()) {
9845     switch (A->getKind()) {
9846     case attr::CPUDispatch:
9847     case attr::CPUSpecific:
9848       if (MVType != MultiVersionKind::CPUDispatch &&
9849           MVType != MultiVersionKind::CPUSpecific)
9850         return true;
9851       break;
9852     case attr::Target:
9853       if (MVType != MultiVersionKind::Target)
9854         return true;
9855       break;
9856     default:
9857       return true;
9858     }
9859   }
9860   return false;
9861 }
9862 
9863 bool Sema::areMultiversionVariantFunctionsCompatible(
9864     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
9865     const PartialDiagnostic &NoProtoDiagID,
9866     const PartialDiagnosticAt &NoteCausedDiagIDAt,
9867     const PartialDiagnosticAt &NoSupportDiagIDAt,
9868     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
9869     bool ConstexprSupported, bool CLinkageMayDiffer) {
9870   enum DoesntSupport {
9871     FuncTemplates = 0,
9872     VirtFuncs = 1,
9873     DeducedReturn = 2,
9874     Constructors = 3,
9875     Destructors = 4,
9876     DeletedFuncs = 5,
9877     DefaultedFuncs = 6,
9878     ConstexprFuncs = 7,
9879     ConstevalFuncs = 8,
9880   };
9881   enum Different {
9882     CallingConv = 0,
9883     ReturnType = 1,
9884     ConstexprSpec = 2,
9885     InlineSpec = 3,
9886     StorageClass = 4,
9887     Linkage = 5,
9888   };
9889 
9890   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
9891       !OldFD->getType()->getAs<FunctionProtoType>()) {
9892     Diag(OldFD->getLocation(), NoProtoDiagID);
9893     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
9894     return true;
9895   }
9896 
9897   if (NoProtoDiagID.getDiagID() != 0 &&
9898       !NewFD->getType()->getAs<FunctionProtoType>())
9899     return Diag(NewFD->getLocation(), NoProtoDiagID);
9900 
9901   if (!TemplatesSupported &&
9902       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9903     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9904            << FuncTemplates;
9905 
9906   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
9907     if (NewCXXFD->isVirtual())
9908       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9909              << VirtFuncs;
9910 
9911     if (isa<CXXConstructorDecl>(NewCXXFD))
9912       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9913              << Constructors;
9914 
9915     if (isa<CXXDestructorDecl>(NewCXXFD))
9916       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9917              << Destructors;
9918   }
9919 
9920   if (NewFD->isDeleted())
9921     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9922            << DeletedFuncs;
9923 
9924   if (NewFD->isDefaulted())
9925     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9926            << DefaultedFuncs;
9927 
9928   if (!ConstexprSupported && NewFD->isConstexpr())
9929     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9930            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
9931 
9932   QualType NewQType = Context.getCanonicalType(NewFD->getType());
9933   const auto *NewType = cast<FunctionType>(NewQType);
9934   QualType NewReturnType = NewType->getReturnType();
9935 
9936   if (NewReturnType->isUndeducedType())
9937     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9938            << DeducedReturn;
9939 
9940   // Ensure the return type is identical.
9941   if (OldFD) {
9942     QualType OldQType = Context.getCanonicalType(OldFD->getType());
9943     const auto *OldType = cast<FunctionType>(OldQType);
9944     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
9945     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
9946 
9947     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
9948       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
9949 
9950     QualType OldReturnType = OldType->getReturnType();
9951 
9952     if (OldReturnType != NewReturnType)
9953       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
9954 
9955     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
9956       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
9957 
9958     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
9959       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
9960 
9961     if (OldFD->getStorageClass() != NewFD->getStorageClass())
9962       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass;
9963 
9964     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
9965       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
9966 
9967     if (CheckEquivalentExceptionSpec(
9968             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
9969             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
9970       return true;
9971   }
9972   return false;
9973 }
9974 
9975 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
9976                                              const FunctionDecl *NewFD,
9977                                              bool CausesMV,
9978                                              MultiVersionKind MVType) {
9979   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9980     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9981     if (OldFD)
9982       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9983     return true;
9984   }
9985 
9986   bool IsCPUSpecificCPUDispatchMVType =
9987       MVType == MultiVersionKind::CPUDispatch ||
9988       MVType == MultiVersionKind::CPUSpecific;
9989 
9990   // For now, disallow all other attributes.  These should be opt-in, but
9991   // an analysis of all of them is a future FIXME.
9992   if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) {
9993     S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
9994         << IsCPUSpecificCPUDispatchMVType;
9995     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9996     return true;
9997   }
9998 
9999   if (HasNonMultiVersionAttributes(NewFD, MVType))
10000     return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
10001            << IsCPUSpecificCPUDispatchMVType;
10002 
10003   // Only allow transition to MultiVersion if it hasn't been used.
10004   if (OldFD && CausesMV && OldFD->isUsed(false))
10005     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10006 
10007   return S.areMultiversionVariantFunctionsCompatible(
10008       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10009       PartialDiagnosticAt(NewFD->getLocation(),
10010                           S.PDiag(diag::note_multiversioning_caused_here)),
10011       PartialDiagnosticAt(NewFD->getLocation(),
10012                           S.PDiag(diag::err_multiversion_doesnt_support)
10013                               << IsCPUSpecificCPUDispatchMVType),
10014       PartialDiagnosticAt(NewFD->getLocation(),
10015                           S.PDiag(diag::err_multiversion_diff)),
10016       /*TemplatesSupported=*/false,
10017       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
10018       /*CLinkageMayDiffer=*/false);
10019 }
10020 
10021 /// Check the validity of a multiversion function declaration that is the
10022 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10023 ///
10024 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10025 ///
10026 /// Returns true if there was an error, false otherwise.
10027 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10028                                            MultiVersionKind MVType,
10029                                            const TargetAttr *TA) {
10030   assert(MVType != MultiVersionKind::None &&
10031          "Function lacks multiversion attribute");
10032 
10033   // Target only causes MV if it is default, otherwise this is a normal
10034   // function.
10035   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
10036     return false;
10037 
10038   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10039     FD->setInvalidDecl();
10040     return true;
10041   }
10042 
10043   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
10044     FD->setInvalidDecl();
10045     return true;
10046   }
10047 
10048   FD->setIsMultiVersion();
10049   return false;
10050 }
10051 
10052 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10053   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10054     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10055       return true;
10056   }
10057 
10058   return false;
10059 }
10060 
10061 static bool CheckTargetCausesMultiVersioning(
10062     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10063     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10064     LookupResult &Previous) {
10065   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10066   ParsedTargetAttr NewParsed = NewTA->parse();
10067   // Sort order doesn't matter, it just needs to be consistent.
10068   llvm::sort(NewParsed.Features);
10069 
10070   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10071   // to change, this is a simple redeclaration.
10072   if (!NewTA->isDefaultVersion() &&
10073       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10074     return false;
10075 
10076   // Otherwise, this decl causes MultiVersioning.
10077   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10078     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10079     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10080     NewFD->setInvalidDecl();
10081     return true;
10082   }
10083 
10084   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10085                                        MultiVersionKind::Target)) {
10086     NewFD->setInvalidDecl();
10087     return true;
10088   }
10089 
10090   if (CheckMultiVersionValue(S, NewFD)) {
10091     NewFD->setInvalidDecl();
10092     return true;
10093   }
10094 
10095   // If this is 'default', permit the forward declaration.
10096   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10097     Redeclaration = true;
10098     OldDecl = OldFD;
10099     OldFD->setIsMultiVersion();
10100     NewFD->setIsMultiVersion();
10101     return false;
10102   }
10103 
10104   if (CheckMultiVersionValue(S, OldFD)) {
10105     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10106     NewFD->setInvalidDecl();
10107     return true;
10108   }
10109 
10110   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10111 
10112   if (OldParsed == NewParsed) {
10113     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10114     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10115     NewFD->setInvalidDecl();
10116     return true;
10117   }
10118 
10119   for (const auto *FD : OldFD->redecls()) {
10120     const auto *CurTA = FD->getAttr<TargetAttr>();
10121     // We allow forward declarations before ANY multiversioning attributes, but
10122     // nothing after the fact.
10123     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10124         (!CurTA || CurTA->isInherited())) {
10125       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10126           << 0;
10127       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10128       NewFD->setInvalidDecl();
10129       return true;
10130     }
10131   }
10132 
10133   OldFD->setIsMultiVersion();
10134   NewFD->setIsMultiVersion();
10135   Redeclaration = false;
10136   MergeTypeWithPrevious = false;
10137   OldDecl = nullptr;
10138   Previous.clear();
10139   return false;
10140 }
10141 
10142 /// Check the validity of a new function declaration being added to an existing
10143 /// multiversioned declaration collection.
10144 static bool CheckMultiVersionAdditionalDecl(
10145     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10146     MultiVersionKind NewMVType, const TargetAttr *NewTA,
10147     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10148     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10149     LookupResult &Previous) {
10150 
10151   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10152   // Disallow mixing of multiversioning types.
10153   if ((OldMVType == MultiVersionKind::Target &&
10154        NewMVType != MultiVersionKind::Target) ||
10155       (NewMVType == MultiVersionKind::Target &&
10156        OldMVType != MultiVersionKind::Target)) {
10157     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10158     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10159     NewFD->setInvalidDecl();
10160     return true;
10161   }
10162 
10163   ParsedTargetAttr NewParsed;
10164   if (NewTA) {
10165     NewParsed = NewTA->parse();
10166     llvm::sort(NewParsed.Features);
10167   }
10168 
10169   bool UseMemberUsingDeclRules =
10170       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10171 
10172   // Next, check ALL non-overloads to see if this is a redeclaration of a
10173   // previous member of the MultiVersion set.
10174   for (NamedDecl *ND : Previous) {
10175     FunctionDecl *CurFD = ND->getAsFunction();
10176     if (!CurFD)
10177       continue;
10178     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10179       continue;
10180 
10181     if (NewMVType == MultiVersionKind::Target) {
10182       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10183       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10184         NewFD->setIsMultiVersion();
10185         Redeclaration = true;
10186         OldDecl = ND;
10187         return false;
10188       }
10189 
10190       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10191       if (CurParsed == NewParsed) {
10192         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10193         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10194         NewFD->setInvalidDecl();
10195         return true;
10196       }
10197     } else {
10198       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10199       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10200       // Handle CPUDispatch/CPUSpecific versions.
10201       // Only 1 CPUDispatch function is allowed, this will make it go through
10202       // the redeclaration errors.
10203       if (NewMVType == MultiVersionKind::CPUDispatch &&
10204           CurFD->hasAttr<CPUDispatchAttr>()) {
10205         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10206             std::equal(
10207                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10208                 NewCPUDisp->cpus_begin(),
10209                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10210                   return Cur->getName() == New->getName();
10211                 })) {
10212           NewFD->setIsMultiVersion();
10213           Redeclaration = true;
10214           OldDecl = ND;
10215           return false;
10216         }
10217 
10218         // If the declarations don't match, this is an error condition.
10219         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10220         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10221         NewFD->setInvalidDecl();
10222         return true;
10223       }
10224       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10225 
10226         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10227             std::equal(
10228                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10229                 NewCPUSpec->cpus_begin(),
10230                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10231                   return Cur->getName() == New->getName();
10232                 })) {
10233           NewFD->setIsMultiVersion();
10234           Redeclaration = true;
10235           OldDecl = ND;
10236           return false;
10237         }
10238 
10239         // Only 1 version of CPUSpecific is allowed for each CPU.
10240         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10241           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10242             if (CurII == NewII) {
10243               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10244                   << NewII;
10245               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10246               NewFD->setInvalidDecl();
10247               return true;
10248             }
10249           }
10250         }
10251       }
10252       // If the two decls aren't the same MVType, there is no possible error
10253       // condition.
10254     }
10255   }
10256 
10257   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10258   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10259   // handled in the attribute adding step.
10260   if (NewMVType == MultiVersionKind::Target &&
10261       CheckMultiVersionValue(S, NewFD)) {
10262     NewFD->setInvalidDecl();
10263     return true;
10264   }
10265 
10266   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10267                                        !OldFD->isMultiVersion(), NewMVType)) {
10268     NewFD->setInvalidDecl();
10269     return true;
10270   }
10271 
10272   // Permit forward declarations in the case where these two are compatible.
10273   if (!OldFD->isMultiVersion()) {
10274     OldFD->setIsMultiVersion();
10275     NewFD->setIsMultiVersion();
10276     Redeclaration = true;
10277     OldDecl = OldFD;
10278     return false;
10279   }
10280 
10281   NewFD->setIsMultiVersion();
10282   Redeclaration = false;
10283   MergeTypeWithPrevious = false;
10284   OldDecl = nullptr;
10285   Previous.clear();
10286   return false;
10287 }
10288 
10289 
10290 /// Check the validity of a mulitversion function declaration.
10291 /// Also sets the multiversion'ness' of the function itself.
10292 ///
10293 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10294 ///
10295 /// Returns true if there was an error, false otherwise.
10296 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10297                                       bool &Redeclaration, NamedDecl *&OldDecl,
10298                                       bool &MergeTypeWithPrevious,
10299                                       LookupResult &Previous) {
10300   const auto *NewTA = NewFD->getAttr<TargetAttr>();
10301   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10302   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10303 
10304   // Mixing Multiversioning types is prohibited.
10305   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
10306       (NewCPUDisp && NewCPUSpec)) {
10307     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10308     NewFD->setInvalidDecl();
10309     return true;
10310   }
10311 
10312   MultiVersionKind  MVType = NewFD->getMultiVersionKind();
10313 
10314   // Main isn't allowed to become a multiversion function, however it IS
10315   // permitted to have 'main' be marked with the 'target' optimization hint.
10316   if (NewFD->isMain()) {
10317     if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10318         MVType == MultiVersionKind::CPUDispatch ||
10319         MVType == MultiVersionKind::CPUSpecific) {
10320       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10321       NewFD->setInvalidDecl();
10322       return true;
10323     }
10324     return false;
10325   }
10326 
10327   if (!OldDecl || !OldDecl->getAsFunction() ||
10328       OldDecl->getDeclContext()->getRedeclContext() !=
10329           NewFD->getDeclContext()->getRedeclContext()) {
10330     // If there's no previous declaration, AND this isn't attempting to cause
10331     // multiversioning, this isn't an error condition.
10332     if (MVType == MultiVersionKind::None)
10333       return false;
10334     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10335   }
10336 
10337   FunctionDecl *OldFD = OldDecl->getAsFunction();
10338 
10339   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10340     return false;
10341 
10342   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10343     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10344         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10345     NewFD->setInvalidDecl();
10346     return true;
10347   }
10348 
10349   // Handle the target potentially causes multiversioning case.
10350   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10351     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10352                                             Redeclaration, OldDecl,
10353                                             MergeTypeWithPrevious, Previous);
10354 
10355   // At this point, we have a multiversion function decl (in OldFD) AND an
10356   // appropriate attribute in the current function decl.  Resolve that these are
10357   // still compatible with previous declarations.
10358   return CheckMultiVersionAdditionalDecl(
10359       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10360       OldDecl, MergeTypeWithPrevious, Previous);
10361 }
10362 
10363 /// Perform semantic checking of a new function declaration.
10364 ///
10365 /// Performs semantic analysis of the new function declaration
10366 /// NewFD. This routine performs all semantic checking that does not
10367 /// require the actual declarator involved in the declaration, and is
10368 /// used both for the declaration of functions as they are parsed
10369 /// (called via ActOnDeclarator) and for the declaration of functions
10370 /// that have been instantiated via C++ template instantiation (called
10371 /// via InstantiateDecl).
10372 ///
10373 /// \param IsMemberSpecialization whether this new function declaration is
10374 /// a member specialization (that replaces any definition provided by the
10375 /// previous declaration).
10376 ///
10377 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10378 ///
10379 /// \returns true if the function declaration is a redeclaration.
10380 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10381                                     LookupResult &Previous,
10382                                     bool IsMemberSpecialization) {
10383   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10384          "Variably modified return types are not handled here");
10385 
10386   // Determine whether the type of this function should be merged with
10387   // a previous visible declaration. This never happens for functions in C++,
10388   // and always happens in C if the previous declaration was visible.
10389   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10390                                !Previous.isShadowed();
10391 
10392   bool Redeclaration = false;
10393   NamedDecl *OldDecl = nullptr;
10394   bool MayNeedOverloadableChecks = false;
10395 
10396   // Merge or overload the declaration with an existing declaration of
10397   // the same name, if appropriate.
10398   if (!Previous.empty()) {
10399     // Determine whether NewFD is an overload of PrevDecl or
10400     // a declaration that requires merging. If it's an overload,
10401     // there's no more work to do here; we'll just add the new
10402     // function to the scope.
10403     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10404       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10405       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10406         Redeclaration = true;
10407         OldDecl = Candidate;
10408       }
10409     } else {
10410       MayNeedOverloadableChecks = true;
10411       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10412                             /*NewIsUsingDecl*/ false)) {
10413       case Ovl_Match:
10414         Redeclaration = true;
10415         break;
10416 
10417       case Ovl_NonFunction:
10418         Redeclaration = true;
10419         break;
10420 
10421       case Ovl_Overload:
10422         Redeclaration = false;
10423         break;
10424       }
10425     }
10426   }
10427 
10428   // Check for a previous extern "C" declaration with this name.
10429   if (!Redeclaration &&
10430       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10431     if (!Previous.empty()) {
10432       // This is an extern "C" declaration with the same name as a previous
10433       // declaration, and thus redeclares that entity...
10434       Redeclaration = true;
10435       OldDecl = Previous.getFoundDecl();
10436       MergeTypeWithPrevious = false;
10437 
10438       // ... except in the presence of __attribute__((overloadable)).
10439       if (OldDecl->hasAttr<OverloadableAttr>() ||
10440           NewFD->hasAttr<OverloadableAttr>()) {
10441         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10442           MayNeedOverloadableChecks = true;
10443           Redeclaration = false;
10444           OldDecl = nullptr;
10445         }
10446       }
10447     }
10448   }
10449 
10450   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10451                                 MergeTypeWithPrevious, Previous))
10452     return Redeclaration;
10453 
10454   // C++11 [dcl.constexpr]p8:
10455   //   A constexpr specifier for a non-static member function that is not
10456   //   a constructor declares that member function to be const.
10457   //
10458   // This needs to be delayed until we know whether this is an out-of-line
10459   // definition of a static member function.
10460   //
10461   // This rule is not present in C++1y, so we produce a backwards
10462   // compatibility warning whenever it happens in C++11.
10463   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10464   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10465       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10466       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10467     CXXMethodDecl *OldMD = nullptr;
10468     if (OldDecl)
10469       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10470     if (!OldMD || !OldMD->isStatic()) {
10471       const FunctionProtoType *FPT =
10472         MD->getType()->castAs<FunctionProtoType>();
10473       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10474       EPI.TypeQuals.addConst();
10475       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10476                                           FPT->getParamTypes(), EPI));
10477 
10478       // Warn that we did this, if we're not performing template instantiation.
10479       // In that case, we'll have warned already when the template was defined.
10480       if (!inTemplateInstantiation()) {
10481         SourceLocation AddConstLoc;
10482         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10483                 .IgnoreParens().getAs<FunctionTypeLoc>())
10484           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10485 
10486         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10487           << FixItHint::CreateInsertion(AddConstLoc, " const");
10488       }
10489     }
10490   }
10491 
10492   if (Redeclaration) {
10493     // NewFD and OldDecl represent declarations that need to be
10494     // merged.
10495     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10496       NewFD->setInvalidDecl();
10497       return Redeclaration;
10498     }
10499 
10500     Previous.clear();
10501     Previous.addDecl(OldDecl);
10502 
10503     if (FunctionTemplateDecl *OldTemplateDecl =
10504             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10505       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10506       FunctionTemplateDecl *NewTemplateDecl
10507         = NewFD->getDescribedFunctionTemplate();
10508       assert(NewTemplateDecl && "Template/non-template mismatch");
10509 
10510       // The call to MergeFunctionDecl above may have created some state in
10511       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10512       // can add it as a redeclaration.
10513       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10514 
10515       NewFD->setPreviousDeclaration(OldFD);
10516       adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10517       if (NewFD->isCXXClassMember()) {
10518         NewFD->setAccess(OldTemplateDecl->getAccess());
10519         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10520       }
10521 
10522       // If this is an explicit specialization of a member that is a function
10523       // template, mark it as a member specialization.
10524       if (IsMemberSpecialization &&
10525           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10526         NewTemplateDecl->setMemberSpecialization();
10527         assert(OldTemplateDecl->isMemberSpecialization());
10528         // Explicit specializations of a member template do not inherit deleted
10529         // status from the parent member template that they are specializing.
10530         if (OldFD->isDeleted()) {
10531           // FIXME: This assert will not hold in the presence of modules.
10532           assert(OldFD->getCanonicalDecl() == OldFD);
10533           // FIXME: We need an update record for this AST mutation.
10534           OldFD->setDeletedAsWritten(false);
10535         }
10536       }
10537 
10538     } else {
10539       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10540         auto *OldFD = cast<FunctionDecl>(OldDecl);
10541         // This needs to happen first so that 'inline' propagates.
10542         NewFD->setPreviousDeclaration(OldFD);
10543         adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10544         if (NewFD->isCXXClassMember())
10545           NewFD->setAccess(OldFD->getAccess());
10546       }
10547     }
10548   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10549              !NewFD->getAttr<OverloadableAttr>()) {
10550     assert((Previous.empty() ||
10551             llvm::any_of(Previous,
10552                          [](const NamedDecl *ND) {
10553                            return ND->hasAttr<OverloadableAttr>();
10554                          })) &&
10555            "Non-redecls shouldn't happen without overloadable present");
10556 
10557     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10558       const auto *FD = dyn_cast<FunctionDecl>(ND);
10559       return FD && !FD->hasAttr<OverloadableAttr>();
10560     });
10561 
10562     if (OtherUnmarkedIter != Previous.end()) {
10563       Diag(NewFD->getLocation(),
10564            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10565       Diag((*OtherUnmarkedIter)->getLocation(),
10566            diag::note_attribute_overloadable_prev_overload)
10567           << false;
10568 
10569       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10570     }
10571   }
10572 
10573   // Semantic checking for this function declaration (in isolation).
10574 
10575   if (getLangOpts().CPlusPlus) {
10576     // C++-specific checks.
10577     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10578       CheckConstructor(Constructor);
10579     } else if (CXXDestructorDecl *Destructor =
10580                 dyn_cast<CXXDestructorDecl>(NewFD)) {
10581       CXXRecordDecl *Record = Destructor->getParent();
10582       QualType ClassType = Context.getTypeDeclType(Record);
10583 
10584       // FIXME: Shouldn't we be able to perform this check even when the class
10585       // type is dependent? Both gcc and edg can handle that.
10586       if (!ClassType->isDependentType()) {
10587         DeclarationName Name
10588           = Context.DeclarationNames.getCXXDestructorName(
10589                                         Context.getCanonicalType(ClassType));
10590         if (NewFD->getDeclName() != Name) {
10591           Diag(NewFD->getLocation(), diag::err_destructor_name);
10592           NewFD->setInvalidDecl();
10593           return Redeclaration;
10594         }
10595       }
10596     } else if (CXXConversionDecl *Conversion
10597                = dyn_cast<CXXConversionDecl>(NewFD)) {
10598       ActOnConversionDeclarator(Conversion);
10599     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10600       if (auto *TD = Guide->getDescribedFunctionTemplate())
10601         CheckDeductionGuideTemplate(TD);
10602 
10603       // A deduction guide is not on the list of entities that can be
10604       // explicitly specialized.
10605       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10606         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10607             << /*explicit specialization*/ 1;
10608     }
10609 
10610     // Find any virtual functions that this function overrides.
10611     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10612       if (!Method->isFunctionTemplateSpecialization() &&
10613           !Method->getDescribedFunctionTemplate() &&
10614           Method->isCanonicalDecl()) {
10615         if (AddOverriddenMethods(Method->getParent(), Method)) {
10616           // If the function was marked as "static", we have a problem.
10617           if (NewFD->getStorageClass() == SC_Static) {
10618             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
10619           }
10620         }
10621       }
10622       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
10623         // C++2a [class.virtual]p6
10624         // A virtual method shall not have a requires-clause.
10625         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
10626              diag::err_constrained_virtual_method);
10627 
10628       if (Method->isStatic())
10629         checkThisInStaticMemberFunctionType(Method);
10630     }
10631 
10632     // Extra checking for C++ overloaded operators (C++ [over.oper]).
10633     if (NewFD->isOverloadedOperator() &&
10634         CheckOverloadedOperatorDeclaration(NewFD)) {
10635       NewFD->setInvalidDecl();
10636       return Redeclaration;
10637     }
10638 
10639     // Extra checking for C++0x literal operators (C++0x [over.literal]).
10640     if (NewFD->getLiteralIdentifier() &&
10641         CheckLiteralOperatorDeclaration(NewFD)) {
10642       NewFD->setInvalidDecl();
10643       return Redeclaration;
10644     }
10645 
10646     // In C++, check default arguments now that we have merged decls. Unless
10647     // the lexical context is the class, because in this case this is done
10648     // during delayed parsing anyway.
10649     if (!CurContext->isRecord())
10650       CheckCXXDefaultArguments(NewFD);
10651 
10652     // If this function declares a builtin function, check the type of this
10653     // declaration against the expected type for the builtin.
10654     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10655       ASTContext::GetBuiltinTypeError Error;
10656       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
10657       QualType T = Context.GetBuiltinType(BuiltinID, Error);
10658       // If the type of the builtin differs only in its exception
10659       // specification, that's OK.
10660       // FIXME: If the types do differ in this way, it would be better to
10661       // retain the 'noexcept' form of the type.
10662       if (!T.isNull() &&
10663           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10664                                                             NewFD->getType()))
10665         // The type of this function differs from the type of the builtin,
10666         // so forget about the builtin entirely.
10667         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10668     }
10669 
10670     // If this function is declared as being extern "C", then check to see if
10671     // the function returns a UDT (class, struct, or union type) that is not C
10672     // compatible, and if it does, warn the user.
10673     // But, issue any diagnostic on the first declaration only.
10674     if (Previous.empty() && NewFD->isExternC()) {
10675       QualType R = NewFD->getReturnType();
10676       if (R->isIncompleteType() && !R->isVoidType())
10677         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10678             << NewFD << R;
10679       else if (!R.isPODType(Context) && !R->isVoidType() &&
10680                !R->isObjCObjectPointerType())
10681         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10682     }
10683 
10684     // C++1z [dcl.fct]p6:
10685     //   [...] whether the function has a non-throwing exception-specification
10686     //   [is] part of the function type
10687     //
10688     // This results in an ABI break between C++14 and C++17 for functions whose
10689     // declared type includes an exception-specification in a parameter or
10690     // return type. (Exception specifications on the function itself are OK in
10691     // most cases, and exception specifications are not permitted in most other
10692     // contexts where they could make it into a mangling.)
10693     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10694       auto HasNoexcept = [&](QualType T) -> bool {
10695         // Strip off declarator chunks that could be between us and a function
10696         // type. We don't need to look far, exception specifications are very
10697         // restricted prior to C++17.
10698         if (auto *RT = T->getAs<ReferenceType>())
10699           T = RT->getPointeeType();
10700         else if (T->isAnyPointerType())
10701           T = T->getPointeeType();
10702         else if (auto *MPT = T->getAs<MemberPointerType>())
10703           T = MPT->getPointeeType();
10704         if (auto *FPT = T->getAs<FunctionProtoType>())
10705           if (FPT->isNothrow())
10706             return true;
10707         return false;
10708       };
10709 
10710       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10711       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10712       for (QualType T : FPT->param_types())
10713         AnyNoexcept |= HasNoexcept(T);
10714       if (AnyNoexcept)
10715         Diag(NewFD->getLocation(),
10716              diag::warn_cxx17_compat_exception_spec_in_signature)
10717             << NewFD;
10718     }
10719 
10720     if (!Redeclaration && LangOpts.CUDA)
10721       checkCUDATargetOverload(NewFD, Previous);
10722   }
10723   return Redeclaration;
10724 }
10725 
10726 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10727   // C++11 [basic.start.main]p3:
10728   //   A program that [...] declares main to be inline, static or
10729   //   constexpr is ill-formed.
10730   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
10731   //   appear in a declaration of main.
10732   // static main is not an error under C99, but we should warn about it.
10733   // We accept _Noreturn main as an extension.
10734   if (FD->getStorageClass() == SC_Static)
10735     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10736          ? diag::err_static_main : diag::warn_static_main)
10737       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10738   if (FD->isInlineSpecified())
10739     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10740       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10741   if (DS.isNoreturnSpecified()) {
10742     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10743     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10744     Diag(NoreturnLoc, diag::ext_noreturn_main);
10745     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10746       << FixItHint::CreateRemoval(NoreturnRange);
10747   }
10748   if (FD->isConstexpr()) {
10749     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10750         << FD->isConsteval()
10751         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10752     FD->setConstexprKind(CSK_unspecified);
10753   }
10754 
10755   if (getLangOpts().OpenCL) {
10756     Diag(FD->getLocation(), diag::err_opencl_no_main)
10757         << FD->hasAttr<OpenCLKernelAttr>();
10758     FD->setInvalidDecl();
10759     return;
10760   }
10761 
10762   QualType T = FD->getType();
10763   assert(T->isFunctionType() && "function decl is not of function type");
10764   const FunctionType* FT = T->castAs<FunctionType>();
10765 
10766   // Set default calling convention for main()
10767   if (FT->getCallConv() != CC_C) {
10768     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10769     FD->setType(QualType(FT, 0));
10770     T = Context.getCanonicalType(FD->getType());
10771   }
10772 
10773   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10774     // In C with GNU extensions we allow main() to have non-integer return
10775     // type, but we should warn about the extension, and we disable the
10776     // implicit-return-zero rule.
10777 
10778     // GCC in C mode accepts qualified 'int'.
10779     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
10780       FD->setHasImplicitReturnZero(true);
10781     else {
10782       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
10783       SourceRange RTRange = FD->getReturnTypeSourceRange();
10784       if (RTRange.isValid())
10785         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
10786             << FixItHint::CreateReplacement(RTRange, "int");
10787     }
10788   } else {
10789     // In C and C++, main magically returns 0 if you fall off the end;
10790     // set the flag which tells us that.
10791     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
10792 
10793     // All the standards say that main() should return 'int'.
10794     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
10795       FD->setHasImplicitReturnZero(true);
10796     else {
10797       // Otherwise, this is just a flat-out error.
10798       SourceRange RTRange = FD->getReturnTypeSourceRange();
10799       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
10800           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
10801                                 : FixItHint());
10802       FD->setInvalidDecl(true);
10803     }
10804   }
10805 
10806   // Treat protoless main() as nullary.
10807   if (isa<FunctionNoProtoType>(FT)) return;
10808 
10809   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
10810   unsigned nparams = FTP->getNumParams();
10811   assert(FD->getNumParams() == nparams);
10812 
10813   bool HasExtraParameters = (nparams > 3);
10814 
10815   if (FTP->isVariadic()) {
10816     Diag(FD->getLocation(), diag::ext_variadic_main);
10817     // FIXME: if we had information about the location of the ellipsis, we
10818     // could add a FixIt hint to remove it as a parameter.
10819   }
10820 
10821   // Darwin passes an undocumented fourth argument of type char**.  If
10822   // other platforms start sprouting these, the logic below will start
10823   // getting shifty.
10824   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
10825     HasExtraParameters = false;
10826 
10827   if (HasExtraParameters) {
10828     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
10829     FD->setInvalidDecl(true);
10830     nparams = 3;
10831   }
10832 
10833   // FIXME: a lot of the following diagnostics would be improved
10834   // if we had some location information about types.
10835 
10836   QualType CharPP =
10837     Context.getPointerType(Context.getPointerType(Context.CharTy));
10838   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
10839 
10840   for (unsigned i = 0; i < nparams; ++i) {
10841     QualType AT = FTP->getParamType(i);
10842 
10843     bool mismatch = true;
10844 
10845     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
10846       mismatch = false;
10847     else if (Expected[i] == CharPP) {
10848       // As an extension, the following forms are okay:
10849       //   char const **
10850       //   char const * const *
10851       //   char * const *
10852 
10853       QualifierCollector qs;
10854       const PointerType* PT;
10855       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
10856           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
10857           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
10858                               Context.CharTy)) {
10859         qs.removeConst();
10860         mismatch = !qs.empty();
10861       }
10862     }
10863 
10864     if (mismatch) {
10865       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
10866       // TODO: suggest replacing given type with expected type
10867       FD->setInvalidDecl(true);
10868     }
10869   }
10870 
10871   if (nparams == 1 && !FD->isInvalidDecl()) {
10872     Diag(FD->getLocation(), diag::warn_main_one_arg);
10873   }
10874 
10875   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10876     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10877     FD->setInvalidDecl();
10878   }
10879 }
10880 
10881 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
10882   QualType T = FD->getType();
10883   assert(T->isFunctionType() && "function decl is not of function type");
10884   const FunctionType *FT = T->castAs<FunctionType>();
10885 
10886   // Set an implicit return of 'zero' if the function can return some integral,
10887   // enumeration, pointer or nullptr type.
10888   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
10889       FT->getReturnType()->isAnyPointerType() ||
10890       FT->getReturnType()->isNullPtrType())
10891     // DllMain is exempt because a return value of zero means it failed.
10892     if (FD->getName() != "DllMain")
10893       FD->setHasImplicitReturnZero(true);
10894 
10895   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10896     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10897     FD->setInvalidDecl();
10898   }
10899 }
10900 
10901 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
10902   // FIXME: Need strict checking.  In C89, we need to check for
10903   // any assignment, increment, decrement, function-calls, or
10904   // commas outside of a sizeof.  In C99, it's the same list,
10905   // except that the aforementioned are allowed in unevaluated
10906   // expressions.  Everything else falls under the
10907   // "may accept other forms of constant expressions" exception.
10908   // (We never end up here for C++, so the constant expression
10909   // rules there don't matter.)
10910   const Expr *Culprit;
10911   if (Init->isConstantInitializer(Context, false, &Culprit))
10912     return false;
10913   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
10914     << Culprit->getSourceRange();
10915   return true;
10916 }
10917 
10918 namespace {
10919   // Visits an initialization expression to see if OrigDecl is evaluated in
10920   // its own initialization and throws a warning if it does.
10921   class SelfReferenceChecker
10922       : public EvaluatedExprVisitor<SelfReferenceChecker> {
10923     Sema &S;
10924     Decl *OrigDecl;
10925     bool isRecordType;
10926     bool isPODType;
10927     bool isReferenceType;
10928 
10929     bool isInitList;
10930     llvm::SmallVector<unsigned, 4> InitFieldIndex;
10931 
10932   public:
10933     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
10934 
10935     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
10936                                                     S(S), OrigDecl(OrigDecl) {
10937       isPODType = false;
10938       isRecordType = false;
10939       isReferenceType = false;
10940       isInitList = false;
10941       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
10942         isPODType = VD->getType().isPODType(S.Context);
10943         isRecordType = VD->getType()->isRecordType();
10944         isReferenceType = VD->getType()->isReferenceType();
10945       }
10946     }
10947 
10948     // For most expressions, just call the visitor.  For initializer lists,
10949     // track the index of the field being initialized since fields are
10950     // initialized in order allowing use of previously initialized fields.
10951     void CheckExpr(Expr *E) {
10952       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
10953       if (!InitList) {
10954         Visit(E);
10955         return;
10956       }
10957 
10958       // Track and increment the index here.
10959       isInitList = true;
10960       InitFieldIndex.push_back(0);
10961       for (auto Child : InitList->children()) {
10962         CheckExpr(cast<Expr>(Child));
10963         ++InitFieldIndex.back();
10964       }
10965       InitFieldIndex.pop_back();
10966     }
10967 
10968     // Returns true if MemberExpr is checked and no further checking is needed.
10969     // Returns false if additional checking is required.
10970     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
10971       llvm::SmallVector<FieldDecl*, 4> Fields;
10972       Expr *Base = E;
10973       bool ReferenceField = false;
10974 
10975       // Get the field members used.
10976       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10977         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
10978         if (!FD)
10979           return false;
10980         Fields.push_back(FD);
10981         if (FD->getType()->isReferenceType())
10982           ReferenceField = true;
10983         Base = ME->getBase()->IgnoreParenImpCasts();
10984       }
10985 
10986       // Keep checking only if the base Decl is the same.
10987       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
10988       if (!DRE || DRE->getDecl() != OrigDecl)
10989         return false;
10990 
10991       // A reference field can be bound to an unininitialized field.
10992       if (CheckReference && !ReferenceField)
10993         return true;
10994 
10995       // Convert FieldDecls to their index number.
10996       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
10997       for (const FieldDecl *I : llvm::reverse(Fields))
10998         UsedFieldIndex.push_back(I->getFieldIndex());
10999 
11000       // See if a warning is needed by checking the first difference in index
11001       // numbers.  If field being used has index less than the field being
11002       // initialized, then the use is safe.
11003       for (auto UsedIter = UsedFieldIndex.begin(),
11004                 UsedEnd = UsedFieldIndex.end(),
11005                 OrigIter = InitFieldIndex.begin(),
11006                 OrigEnd = InitFieldIndex.end();
11007            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11008         if (*UsedIter < *OrigIter)
11009           return true;
11010         if (*UsedIter > *OrigIter)
11011           break;
11012       }
11013 
11014       // TODO: Add a different warning which will print the field names.
11015       HandleDeclRefExpr(DRE);
11016       return true;
11017     }
11018 
11019     // For most expressions, the cast is directly above the DeclRefExpr.
11020     // For conditional operators, the cast can be outside the conditional
11021     // operator if both expressions are DeclRefExpr's.
11022     void HandleValue(Expr *E) {
11023       E = E->IgnoreParens();
11024       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11025         HandleDeclRefExpr(DRE);
11026         return;
11027       }
11028 
11029       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11030         Visit(CO->getCond());
11031         HandleValue(CO->getTrueExpr());
11032         HandleValue(CO->getFalseExpr());
11033         return;
11034       }
11035 
11036       if (BinaryConditionalOperator *BCO =
11037               dyn_cast<BinaryConditionalOperator>(E)) {
11038         Visit(BCO->getCond());
11039         HandleValue(BCO->getFalseExpr());
11040         return;
11041       }
11042 
11043       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11044         HandleValue(OVE->getSourceExpr());
11045         return;
11046       }
11047 
11048       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11049         if (BO->getOpcode() == BO_Comma) {
11050           Visit(BO->getLHS());
11051           HandleValue(BO->getRHS());
11052           return;
11053         }
11054       }
11055 
11056       if (isa<MemberExpr>(E)) {
11057         if (isInitList) {
11058           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11059                                       false /*CheckReference*/))
11060             return;
11061         }
11062 
11063         Expr *Base = E->IgnoreParenImpCasts();
11064         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11065           // Check for static member variables and don't warn on them.
11066           if (!isa<FieldDecl>(ME->getMemberDecl()))
11067             return;
11068           Base = ME->getBase()->IgnoreParenImpCasts();
11069         }
11070         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11071           HandleDeclRefExpr(DRE);
11072         return;
11073       }
11074 
11075       Visit(E);
11076     }
11077 
11078     // Reference types not handled in HandleValue are handled here since all
11079     // uses of references are bad, not just r-value uses.
11080     void VisitDeclRefExpr(DeclRefExpr *E) {
11081       if (isReferenceType)
11082         HandleDeclRefExpr(E);
11083     }
11084 
11085     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11086       if (E->getCastKind() == CK_LValueToRValue) {
11087         HandleValue(E->getSubExpr());
11088         return;
11089       }
11090 
11091       Inherited::VisitImplicitCastExpr(E);
11092     }
11093 
11094     void VisitMemberExpr(MemberExpr *E) {
11095       if (isInitList) {
11096         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11097           return;
11098       }
11099 
11100       // Don't warn on arrays since they can be treated as pointers.
11101       if (E->getType()->canDecayToPointerType()) return;
11102 
11103       // Warn when a non-static method call is followed by non-static member
11104       // field accesses, which is followed by a DeclRefExpr.
11105       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11106       bool Warn = (MD && !MD->isStatic());
11107       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11108       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11109         if (!isa<FieldDecl>(ME->getMemberDecl()))
11110           Warn = false;
11111         Base = ME->getBase()->IgnoreParenImpCasts();
11112       }
11113 
11114       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11115         if (Warn)
11116           HandleDeclRefExpr(DRE);
11117         return;
11118       }
11119 
11120       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11121       // Visit that expression.
11122       Visit(Base);
11123     }
11124 
11125     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11126       Expr *Callee = E->getCallee();
11127 
11128       if (isa<UnresolvedLookupExpr>(Callee))
11129         return Inherited::VisitCXXOperatorCallExpr(E);
11130 
11131       Visit(Callee);
11132       for (auto Arg: E->arguments())
11133         HandleValue(Arg->IgnoreParenImpCasts());
11134     }
11135 
11136     void VisitUnaryOperator(UnaryOperator *E) {
11137       // For POD record types, addresses of its own members are well-defined.
11138       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11139           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11140         if (!isPODType)
11141           HandleValue(E->getSubExpr());
11142         return;
11143       }
11144 
11145       if (E->isIncrementDecrementOp()) {
11146         HandleValue(E->getSubExpr());
11147         return;
11148       }
11149 
11150       Inherited::VisitUnaryOperator(E);
11151     }
11152 
11153     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11154 
11155     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11156       if (E->getConstructor()->isCopyConstructor()) {
11157         Expr *ArgExpr = E->getArg(0);
11158         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11159           if (ILE->getNumInits() == 1)
11160             ArgExpr = ILE->getInit(0);
11161         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11162           if (ICE->getCastKind() == CK_NoOp)
11163             ArgExpr = ICE->getSubExpr();
11164         HandleValue(ArgExpr);
11165         return;
11166       }
11167       Inherited::VisitCXXConstructExpr(E);
11168     }
11169 
11170     void VisitCallExpr(CallExpr *E) {
11171       // Treat std::move as a use.
11172       if (E->isCallToStdMove()) {
11173         HandleValue(E->getArg(0));
11174         return;
11175       }
11176 
11177       Inherited::VisitCallExpr(E);
11178     }
11179 
11180     void VisitBinaryOperator(BinaryOperator *E) {
11181       if (E->isCompoundAssignmentOp()) {
11182         HandleValue(E->getLHS());
11183         Visit(E->getRHS());
11184         return;
11185       }
11186 
11187       Inherited::VisitBinaryOperator(E);
11188     }
11189 
11190     // A custom visitor for BinaryConditionalOperator is needed because the
11191     // regular visitor would check the condition and true expression separately
11192     // but both point to the same place giving duplicate diagnostics.
11193     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11194       Visit(E->getCond());
11195       Visit(E->getFalseExpr());
11196     }
11197 
11198     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11199       Decl* ReferenceDecl = DRE->getDecl();
11200       if (OrigDecl != ReferenceDecl) return;
11201       unsigned diag;
11202       if (isReferenceType) {
11203         diag = diag::warn_uninit_self_reference_in_reference_init;
11204       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11205         diag = diag::warn_static_self_reference_in_init;
11206       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11207                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11208                  DRE->getDecl()->getType()->isRecordType()) {
11209         diag = diag::warn_uninit_self_reference_in_init;
11210       } else {
11211         // Local variables will be handled by the CFG analysis.
11212         return;
11213       }
11214 
11215       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11216                             S.PDiag(diag)
11217                                 << DRE->getDecl() << OrigDecl->getLocation()
11218                                 << DRE->getSourceRange());
11219     }
11220   };
11221 
11222   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11223   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11224                                  bool DirectInit) {
11225     // Parameters arguments are occassionially constructed with itself,
11226     // for instance, in recursive functions.  Skip them.
11227     if (isa<ParmVarDecl>(OrigDecl))
11228       return;
11229 
11230     E = E->IgnoreParens();
11231 
11232     // Skip checking T a = a where T is not a record or reference type.
11233     // Doing so is a way to silence uninitialized warnings.
11234     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11235       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11236         if (ICE->getCastKind() == CK_LValueToRValue)
11237           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11238             if (DRE->getDecl() == OrigDecl)
11239               return;
11240 
11241     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11242   }
11243 } // end anonymous namespace
11244 
11245 namespace {
11246   // Simple wrapper to add the name of a variable or (if no variable is
11247   // available) a DeclarationName into a diagnostic.
11248   struct VarDeclOrName {
11249     VarDecl *VDecl;
11250     DeclarationName Name;
11251 
11252     friend const Sema::SemaDiagnosticBuilder &
11253     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11254       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11255     }
11256   };
11257 } // end anonymous namespace
11258 
11259 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11260                                             DeclarationName Name, QualType Type,
11261                                             TypeSourceInfo *TSI,
11262                                             SourceRange Range, bool DirectInit,
11263                                             Expr *Init) {
11264   bool IsInitCapture = !VDecl;
11265   assert((!VDecl || !VDecl->isInitCapture()) &&
11266          "init captures are expected to be deduced prior to initialization");
11267 
11268   VarDeclOrName VN{VDecl, Name};
11269 
11270   DeducedType *Deduced = Type->getContainedDeducedType();
11271   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11272 
11273   // C++11 [dcl.spec.auto]p3
11274   if (!Init) {
11275     assert(VDecl && "no init for init capture deduction?");
11276 
11277     // Except for class argument deduction, and then for an initializing
11278     // declaration only, i.e. no static at class scope or extern.
11279     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11280         VDecl->hasExternalStorage() ||
11281         VDecl->isStaticDataMember()) {
11282       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11283         << VDecl->getDeclName() << Type;
11284       return QualType();
11285     }
11286   }
11287 
11288   ArrayRef<Expr*> DeduceInits;
11289   if (Init)
11290     DeduceInits = Init;
11291 
11292   if (DirectInit) {
11293     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11294       DeduceInits = PL->exprs();
11295   }
11296 
11297   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11298     assert(VDecl && "non-auto type for init capture deduction?");
11299     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11300     InitializationKind Kind = InitializationKind::CreateForInit(
11301         VDecl->getLocation(), DirectInit, Init);
11302     // FIXME: Initialization should not be taking a mutable list of inits.
11303     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11304     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11305                                                        InitsCopy);
11306   }
11307 
11308   if (DirectInit) {
11309     if (auto *IL = dyn_cast<InitListExpr>(Init))
11310       DeduceInits = IL->inits();
11311   }
11312 
11313   // Deduction only works if we have exactly one source expression.
11314   if (DeduceInits.empty()) {
11315     // It isn't possible to write this directly, but it is possible to
11316     // end up in this situation with "auto x(some_pack...);"
11317     Diag(Init->getBeginLoc(), IsInitCapture
11318                                   ? diag::err_init_capture_no_expression
11319                                   : diag::err_auto_var_init_no_expression)
11320         << VN << Type << Range;
11321     return QualType();
11322   }
11323 
11324   if (DeduceInits.size() > 1) {
11325     Diag(DeduceInits[1]->getBeginLoc(),
11326          IsInitCapture ? diag::err_init_capture_multiple_expressions
11327                        : diag::err_auto_var_init_multiple_expressions)
11328         << VN << Type << Range;
11329     return QualType();
11330   }
11331 
11332   Expr *DeduceInit = DeduceInits[0];
11333   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11334     Diag(Init->getBeginLoc(), IsInitCapture
11335                                   ? diag::err_init_capture_paren_braces
11336                                   : diag::err_auto_var_init_paren_braces)
11337         << isa<InitListExpr>(Init) << VN << Type << Range;
11338     return QualType();
11339   }
11340 
11341   // Expressions default to 'id' when we're in a debugger.
11342   bool DefaultedAnyToId = false;
11343   if (getLangOpts().DebuggerCastResultToId &&
11344       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11345     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11346     if (Result.isInvalid()) {
11347       return QualType();
11348     }
11349     Init = Result.get();
11350     DefaultedAnyToId = true;
11351   }
11352 
11353   // C++ [dcl.decomp]p1:
11354   //   If the assignment-expression [...] has array type A and no ref-qualifier
11355   //   is present, e has type cv A
11356   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11357       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11358       DeduceInit->getType()->isConstantArrayType())
11359     return Context.getQualifiedType(DeduceInit->getType(),
11360                                     Type.getQualifiers());
11361 
11362   QualType DeducedType;
11363   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11364     if (!IsInitCapture)
11365       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11366     else if (isa<InitListExpr>(Init))
11367       Diag(Range.getBegin(),
11368            diag::err_init_capture_deduction_failure_from_init_list)
11369           << VN
11370           << (DeduceInit->getType().isNull() ? TSI->getType()
11371                                              : DeduceInit->getType())
11372           << DeduceInit->getSourceRange();
11373     else
11374       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11375           << VN << TSI->getType()
11376           << (DeduceInit->getType().isNull() ? TSI->getType()
11377                                              : DeduceInit->getType())
11378           << DeduceInit->getSourceRange();
11379   }
11380 
11381   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11382   // 'id' instead of a specific object type prevents most of our usual
11383   // checks.
11384   // We only want to warn outside of template instantiations, though:
11385   // inside a template, the 'id' could have come from a parameter.
11386   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11387       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11388     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11389     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11390   }
11391 
11392   return DeducedType;
11393 }
11394 
11395 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11396                                          Expr *Init) {
11397   QualType DeducedType = deduceVarTypeFromInitializer(
11398       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11399       VDecl->getSourceRange(), DirectInit, Init);
11400   if (DeducedType.isNull()) {
11401     VDecl->setInvalidDecl();
11402     return true;
11403   }
11404 
11405   VDecl->setType(DeducedType);
11406   assert(VDecl->isLinkageValid());
11407 
11408   // In ARC, infer lifetime.
11409   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11410     VDecl->setInvalidDecl();
11411 
11412   if (getLangOpts().OpenCL)
11413     deduceOpenCLAddressSpace(VDecl);
11414 
11415   // If this is a redeclaration, check that the type we just deduced matches
11416   // the previously declared type.
11417   if (VarDecl *Old = VDecl->getPreviousDecl()) {
11418     // We never need to merge the type, because we cannot form an incomplete
11419     // array of auto, nor deduce such a type.
11420     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11421   }
11422 
11423   // Check the deduced type is valid for a variable declaration.
11424   CheckVariableDeclarationType(VDecl);
11425   return VDecl->isInvalidDecl();
11426 }
11427 
11428 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11429                                               SourceLocation Loc) {
11430   if (auto *CE = dyn_cast<ConstantExpr>(Init))
11431     Init = CE->getSubExpr();
11432 
11433   QualType InitType = Init->getType();
11434   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11435           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
11436          "shouldn't be called if type doesn't have a non-trivial C struct");
11437   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11438     for (auto I : ILE->inits()) {
11439       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11440           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11441         continue;
11442       SourceLocation SL = I->getExprLoc();
11443       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11444     }
11445     return;
11446   }
11447 
11448   if (isa<ImplicitValueInitExpr>(Init)) {
11449     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11450       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11451                             NTCUK_Init);
11452   } else {
11453     // Assume all other explicit initializers involving copying some existing
11454     // object.
11455     // TODO: ignore any explicit initializers where we can guarantee
11456     // copy-elision.
11457     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11458       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11459   }
11460 }
11461 
11462 namespace {
11463 
11464 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11465   // Ignore unavailable fields. A field can be marked as unavailable explicitly
11466   // in the source code or implicitly by the compiler if it is in a union
11467   // defined in a system header and has non-trivial ObjC ownership
11468   // qualifications. We don't want those fields to participate in determining
11469   // whether the containing union is non-trivial.
11470   return FD->hasAttr<UnavailableAttr>();
11471 }
11472 
11473 struct DiagNonTrivalCUnionDefaultInitializeVisitor
11474     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11475                                     void> {
11476   using Super =
11477       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11478                                     void>;
11479 
11480   DiagNonTrivalCUnionDefaultInitializeVisitor(
11481       QualType OrigTy, SourceLocation OrigLoc,
11482       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11483       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11484 
11485   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11486                      const FieldDecl *FD, bool InNonTrivialUnion) {
11487     if (const auto *AT = S.Context.getAsArrayType(QT))
11488       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11489                                      InNonTrivialUnion);
11490     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11491   }
11492 
11493   void visitARCStrong(QualType QT, const FieldDecl *FD,
11494                       bool InNonTrivialUnion) {
11495     if (InNonTrivialUnion)
11496       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11497           << 1 << 0 << QT << FD->getName();
11498   }
11499 
11500   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11501     if (InNonTrivialUnion)
11502       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11503           << 1 << 0 << QT << FD->getName();
11504   }
11505 
11506   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11507     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11508     if (RD->isUnion()) {
11509       if (OrigLoc.isValid()) {
11510         bool IsUnion = false;
11511         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11512           IsUnion = OrigRD->isUnion();
11513         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11514             << 0 << OrigTy << IsUnion << UseContext;
11515         // Reset OrigLoc so that this diagnostic is emitted only once.
11516         OrigLoc = SourceLocation();
11517       }
11518       InNonTrivialUnion = true;
11519     }
11520 
11521     if (InNonTrivialUnion)
11522       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11523           << 0 << 0 << QT.getUnqualifiedType() << "";
11524 
11525     for (const FieldDecl *FD : RD->fields())
11526       if (!shouldIgnoreForRecordTriviality(FD))
11527         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11528   }
11529 
11530   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11531 
11532   // The non-trivial C union type or the struct/union type that contains a
11533   // non-trivial C union.
11534   QualType OrigTy;
11535   SourceLocation OrigLoc;
11536   Sema::NonTrivialCUnionContext UseContext;
11537   Sema &S;
11538 };
11539 
11540 struct DiagNonTrivalCUnionDestructedTypeVisitor
11541     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
11542   using Super =
11543       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
11544 
11545   DiagNonTrivalCUnionDestructedTypeVisitor(
11546       QualType OrigTy, SourceLocation OrigLoc,
11547       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11548       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11549 
11550   void visitWithKind(QualType::DestructionKind DK, QualType QT,
11551                      const FieldDecl *FD, bool InNonTrivialUnion) {
11552     if (const auto *AT = S.Context.getAsArrayType(QT))
11553       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11554                                      InNonTrivialUnion);
11555     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
11556   }
11557 
11558   void visitARCStrong(QualType QT, const FieldDecl *FD,
11559                       bool InNonTrivialUnion) {
11560     if (InNonTrivialUnion)
11561       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11562           << 1 << 1 << QT << FD->getName();
11563   }
11564 
11565   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11566     if (InNonTrivialUnion)
11567       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11568           << 1 << 1 << QT << FD->getName();
11569   }
11570 
11571   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11572     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11573     if (RD->isUnion()) {
11574       if (OrigLoc.isValid()) {
11575         bool IsUnion = false;
11576         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11577           IsUnion = OrigRD->isUnion();
11578         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11579             << 1 << OrigTy << IsUnion << UseContext;
11580         // Reset OrigLoc so that this diagnostic is emitted only once.
11581         OrigLoc = SourceLocation();
11582       }
11583       InNonTrivialUnion = true;
11584     }
11585 
11586     if (InNonTrivialUnion)
11587       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11588           << 0 << 1 << QT.getUnqualifiedType() << "";
11589 
11590     for (const FieldDecl *FD : RD->fields())
11591       if (!shouldIgnoreForRecordTriviality(FD))
11592         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11593   }
11594 
11595   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11596   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
11597                           bool InNonTrivialUnion) {}
11598 
11599   // The non-trivial C union type or the struct/union type that contains a
11600   // non-trivial C union.
11601   QualType OrigTy;
11602   SourceLocation OrigLoc;
11603   Sema::NonTrivialCUnionContext UseContext;
11604   Sema &S;
11605 };
11606 
11607 struct DiagNonTrivalCUnionCopyVisitor
11608     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
11609   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
11610 
11611   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
11612                                  Sema::NonTrivialCUnionContext UseContext,
11613                                  Sema &S)
11614       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11615 
11616   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
11617                      const FieldDecl *FD, bool InNonTrivialUnion) {
11618     if (const auto *AT = S.Context.getAsArrayType(QT))
11619       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11620                                      InNonTrivialUnion);
11621     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
11622   }
11623 
11624   void visitARCStrong(QualType QT, const FieldDecl *FD,
11625                       bool InNonTrivialUnion) {
11626     if (InNonTrivialUnion)
11627       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11628           << 1 << 2 << QT << FD->getName();
11629   }
11630 
11631   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11632     if (InNonTrivialUnion)
11633       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11634           << 1 << 2 << QT << FD->getName();
11635   }
11636 
11637   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11638     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11639     if (RD->isUnion()) {
11640       if (OrigLoc.isValid()) {
11641         bool IsUnion = false;
11642         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11643           IsUnion = OrigRD->isUnion();
11644         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11645             << 2 << OrigTy << IsUnion << UseContext;
11646         // Reset OrigLoc so that this diagnostic is emitted only once.
11647         OrigLoc = SourceLocation();
11648       }
11649       InNonTrivialUnion = true;
11650     }
11651 
11652     if (InNonTrivialUnion)
11653       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11654           << 0 << 2 << QT.getUnqualifiedType() << "";
11655 
11656     for (const FieldDecl *FD : RD->fields())
11657       if (!shouldIgnoreForRecordTriviality(FD))
11658         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11659   }
11660 
11661   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
11662                 const FieldDecl *FD, bool InNonTrivialUnion) {}
11663   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11664   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
11665                             bool InNonTrivialUnion) {}
11666 
11667   // The non-trivial C union type or the struct/union type that contains a
11668   // non-trivial C union.
11669   QualType OrigTy;
11670   SourceLocation OrigLoc;
11671   Sema::NonTrivialCUnionContext UseContext;
11672   Sema &S;
11673 };
11674 
11675 } // namespace
11676 
11677 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
11678                                  NonTrivialCUnionContext UseContext,
11679                                  unsigned NonTrivialKind) {
11680   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11681           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
11682           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
11683          "shouldn't be called if type doesn't have a non-trivial C union");
11684 
11685   if ((NonTrivialKind & NTCUK_Init) &&
11686       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11687     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
11688         .visit(QT, nullptr, false);
11689   if ((NonTrivialKind & NTCUK_Destruct) &&
11690       QT.hasNonTrivialToPrimitiveDestructCUnion())
11691     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
11692         .visit(QT, nullptr, false);
11693   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
11694     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
11695         .visit(QT, nullptr, false);
11696 }
11697 
11698 /// AddInitializerToDecl - Adds the initializer Init to the
11699 /// declaration dcl. If DirectInit is true, this is C++ direct
11700 /// initialization rather than copy initialization.
11701 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
11702   // If there is no declaration, there was an error parsing it.  Just ignore
11703   // the initializer.
11704   if (!RealDecl || RealDecl->isInvalidDecl()) {
11705     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
11706     return;
11707   }
11708 
11709   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
11710     // Pure-specifiers are handled in ActOnPureSpecifier.
11711     Diag(Method->getLocation(), diag::err_member_function_initialization)
11712       << Method->getDeclName() << Init->getSourceRange();
11713     Method->setInvalidDecl();
11714     return;
11715   }
11716 
11717   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
11718   if (!VDecl) {
11719     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
11720     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
11721     RealDecl->setInvalidDecl();
11722     return;
11723   }
11724 
11725   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
11726   if (VDecl->getType()->isUndeducedType()) {
11727     // Attempt typo correction early so that the type of the init expression can
11728     // be deduced based on the chosen correction if the original init contains a
11729     // TypoExpr.
11730     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
11731     if (!Res.isUsable()) {
11732       RealDecl->setInvalidDecl();
11733       return;
11734     }
11735     Init = Res.get();
11736 
11737     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
11738       return;
11739   }
11740 
11741   // dllimport cannot be used on variable definitions.
11742   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
11743     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
11744     VDecl->setInvalidDecl();
11745     return;
11746   }
11747 
11748   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
11749     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
11750     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
11751     VDecl->setInvalidDecl();
11752     return;
11753   }
11754 
11755   if (!VDecl->getType()->isDependentType()) {
11756     // A definition must end up with a complete type, which means it must be
11757     // complete with the restriction that an array type might be completed by
11758     // the initializer; note that later code assumes this restriction.
11759     QualType BaseDeclType = VDecl->getType();
11760     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
11761       BaseDeclType = Array->getElementType();
11762     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
11763                             diag::err_typecheck_decl_incomplete_type)) {
11764       RealDecl->setInvalidDecl();
11765       return;
11766     }
11767 
11768     // The variable can not have an abstract class type.
11769     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
11770                                diag::err_abstract_type_in_decl,
11771                                AbstractVariableType))
11772       VDecl->setInvalidDecl();
11773   }
11774 
11775   // If adding the initializer will turn this declaration into a definition,
11776   // and we already have a definition for this variable, diagnose or otherwise
11777   // handle the situation.
11778   VarDecl *Def;
11779   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
11780       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
11781       !VDecl->isThisDeclarationADemotedDefinition() &&
11782       checkVarDeclRedefinition(Def, VDecl))
11783     return;
11784 
11785   if (getLangOpts().CPlusPlus) {
11786     // C++ [class.static.data]p4
11787     //   If a static data member is of const integral or const
11788     //   enumeration type, its declaration in the class definition can
11789     //   specify a constant-initializer which shall be an integral
11790     //   constant expression (5.19). In that case, the member can appear
11791     //   in integral constant expressions. The member shall still be
11792     //   defined in a namespace scope if it is used in the program and the
11793     //   namespace scope definition shall not contain an initializer.
11794     //
11795     // We already performed a redefinition check above, but for static
11796     // data members we also need to check whether there was an in-class
11797     // declaration with an initializer.
11798     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
11799       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
11800           << VDecl->getDeclName();
11801       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
11802            diag::note_previous_initializer)
11803           << 0;
11804       return;
11805     }
11806 
11807     if (VDecl->hasLocalStorage())
11808       setFunctionHasBranchProtectedScope();
11809 
11810     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
11811       VDecl->setInvalidDecl();
11812       return;
11813     }
11814   }
11815 
11816   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
11817   // a kernel function cannot be initialized."
11818   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
11819     Diag(VDecl->getLocation(), diag::err_local_cant_init);
11820     VDecl->setInvalidDecl();
11821     return;
11822   }
11823 
11824   // Get the decls type and save a reference for later, since
11825   // CheckInitializerTypes may change it.
11826   QualType DclT = VDecl->getType(), SavT = DclT;
11827 
11828   // Expressions default to 'id' when we're in a debugger
11829   // and we are assigning it to a variable of Objective-C pointer type.
11830   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
11831       Init->getType() == Context.UnknownAnyTy) {
11832     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11833     if (Result.isInvalid()) {
11834       VDecl->setInvalidDecl();
11835       return;
11836     }
11837     Init = Result.get();
11838   }
11839 
11840   // Perform the initialization.
11841   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
11842   if (!VDecl->isInvalidDecl()) {
11843     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11844     InitializationKind Kind = InitializationKind::CreateForInit(
11845         VDecl->getLocation(), DirectInit, Init);
11846 
11847     MultiExprArg Args = Init;
11848     if (CXXDirectInit)
11849       Args = MultiExprArg(CXXDirectInit->getExprs(),
11850                           CXXDirectInit->getNumExprs());
11851 
11852     // Try to correct any TypoExprs in the initialization arguments.
11853     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
11854       ExprResult Res = CorrectDelayedTyposInExpr(
11855           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
11856             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
11857             return Init.Failed() ? ExprError() : E;
11858           });
11859       if (Res.isInvalid()) {
11860         VDecl->setInvalidDecl();
11861       } else if (Res.get() != Args[Idx]) {
11862         Args[Idx] = Res.get();
11863       }
11864     }
11865     if (VDecl->isInvalidDecl())
11866       return;
11867 
11868     InitializationSequence InitSeq(*this, Entity, Kind, Args,
11869                                    /*TopLevelOfInitList=*/false,
11870                                    /*TreatUnavailableAsInvalid=*/false);
11871     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
11872     if (Result.isInvalid()) {
11873       VDecl->setInvalidDecl();
11874       return;
11875     }
11876 
11877     Init = Result.getAs<Expr>();
11878   }
11879 
11880   // Check for self-references within variable initializers.
11881   // Variables declared within a function/method body (except for references)
11882   // are handled by a dataflow analysis.
11883   // This is undefined behavior in C++, but valid in C.
11884   if (getLangOpts().CPlusPlus) {
11885     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
11886         VDecl->getType()->isReferenceType()) {
11887       CheckSelfReference(*this, RealDecl, Init, DirectInit);
11888     }
11889   }
11890 
11891   // If the type changed, it means we had an incomplete type that was
11892   // completed by the initializer. For example:
11893   //   int ary[] = { 1, 3, 5 };
11894   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
11895   if (!VDecl->isInvalidDecl() && (DclT != SavT))
11896     VDecl->setType(DclT);
11897 
11898   if (!VDecl->isInvalidDecl()) {
11899     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
11900 
11901     if (VDecl->hasAttr<BlocksAttr>())
11902       checkRetainCycles(VDecl, Init);
11903 
11904     // It is safe to assign a weak reference into a strong variable.
11905     // Although this code can still have problems:
11906     //   id x = self.weakProp;
11907     //   id y = self.weakProp;
11908     // we do not warn to warn spuriously when 'x' and 'y' are on separate
11909     // paths through the function. This should be revisited if
11910     // -Wrepeated-use-of-weak is made flow-sensitive.
11911     if (FunctionScopeInfo *FSI = getCurFunction())
11912       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
11913            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
11914           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11915                            Init->getBeginLoc()))
11916         FSI->markSafeWeakUse(Init);
11917   }
11918 
11919   // The initialization is usually a full-expression.
11920   //
11921   // FIXME: If this is a braced initialization of an aggregate, it is not
11922   // an expression, and each individual field initializer is a separate
11923   // full-expression. For instance, in:
11924   //
11925   //   struct Temp { ~Temp(); };
11926   //   struct S { S(Temp); };
11927   //   struct T { S a, b; } t = { Temp(), Temp() }
11928   //
11929   // we should destroy the first Temp before constructing the second.
11930   ExprResult Result =
11931       ActOnFinishFullExpr(Init, VDecl->getLocation(),
11932                           /*DiscardedValue*/ false, VDecl->isConstexpr());
11933   if (Result.isInvalid()) {
11934     VDecl->setInvalidDecl();
11935     return;
11936   }
11937   Init = Result.get();
11938 
11939   // Attach the initializer to the decl.
11940   VDecl->setInit(Init);
11941 
11942   if (VDecl->isLocalVarDecl()) {
11943     // Don't check the initializer if the declaration is malformed.
11944     if (VDecl->isInvalidDecl()) {
11945       // do nothing
11946 
11947     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
11948     // This is true even in C++ for OpenCL.
11949     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
11950       CheckForConstantInitializer(Init, DclT);
11951 
11952     // Otherwise, C++ does not restrict the initializer.
11953     } else if (getLangOpts().CPlusPlus) {
11954       // do nothing
11955 
11956     // C99 6.7.8p4: All the expressions in an initializer for an object that has
11957     // static storage duration shall be constant expressions or string literals.
11958     } else if (VDecl->getStorageClass() == SC_Static) {
11959       CheckForConstantInitializer(Init, DclT);
11960 
11961     // C89 is stricter than C99 for aggregate initializers.
11962     // C89 6.5.7p3: All the expressions [...] in an initializer list
11963     // for an object that has aggregate or union type shall be
11964     // constant expressions.
11965     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
11966                isa<InitListExpr>(Init)) {
11967       const Expr *Culprit;
11968       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
11969         Diag(Culprit->getExprLoc(),
11970              diag::ext_aggregate_init_not_constant)
11971           << Culprit->getSourceRange();
11972       }
11973     }
11974 
11975     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
11976       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
11977         if (VDecl->hasLocalStorage())
11978           BE->getBlockDecl()->setCanAvoidCopyToHeap();
11979   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
11980              VDecl->getLexicalDeclContext()->isRecord()) {
11981     // This is an in-class initialization for a static data member, e.g.,
11982     //
11983     // struct S {
11984     //   static const int value = 17;
11985     // };
11986 
11987     // C++ [class.mem]p4:
11988     //   A member-declarator can contain a constant-initializer only
11989     //   if it declares a static member (9.4) of const integral or
11990     //   const enumeration type, see 9.4.2.
11991     //
11992     // C++11 [class.static.data]p3:
11993     //   If a non-volatile non-inline const static data member is of integral
11994     //   or enumeration type, its declaration in the class definition can
11995     //   specify a brace-or-equal-initializer in which every initializer-clause
11996     //   that is an assignment-expression is a constant expression. A static
11997     //   data member of literal type can be declared in the class definition
11998     //   with the constexpr specifier; if so, its declaration shall specify a
11999     //   brace-or-equal-initializer in which every initializer-clause that is
12000     //   an assignment-expression is a constant expression.
12001 
12002     // Do nothing on dependent types.
12003     if (DclT->isDependentType()) {
12004 
12005     // Allow any 'static constexpr' members, whether or not they are of literal
12006     // type. We separately check that every constexpr variable is of literal
12007     // type.
12008     } else if (VDecl->isConstexpr()) {
12009 
12010     // Require constness.
12011     } else if (!DclT.isConstQualified()) {
12012       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12013         << Init->getSourceRange();
12014       VDecl->setInvalidDecl();
12015 
12016     // We allow integer constant expressions in all cases.
12017     } else if (DclT->isIntegralOrEnumerationType()) {
12018       // Check whether the expression is a constant expression.
12019       SourceLocation Loc;
12020       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12021         // In C++11, a non-constexpr const static data member with an
12022         // in-class initializer cannot be volatile.
12023         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12024       else if (Init->isValueDependent())
12025         ; // Nothing to check.
12026       else if (Init->isIntegerConstantExpr(Context, &Loc))
12027         ; // Ok, it's an ICE!
12028       else if (Init->getType()->isScopedEnumeralType() &&
12029                Init->isCXX11ConstantExpr(Context))
12030         ; // Ok, it is a scoped-enum constant expression.
12031       else if (Init->isEvaluatable(Context)) {
12032         // If we can constant fold the initializer through heroics, accept it,
12033         // but report this as a use of an extension for -pedantic.
12034         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12035           << Init->getSourceRange();
12036       } else {
12037         // Otherwise, this is some crazy unknown case.  Report the issue at the
12038         // location provided by the isIntegerConstantExpr failed check.
12039         Diag(Loc, diag::err_in_class_initializer_non_constant)
12040           << Init->getSourceRange();
12041         VDecl->setInvalidDecl();
12042       }
12043 
12044     // We allow foldable floating-point constants as an extension.
12045     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12046       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12047       // it anyway and provide a fixit to add the 'constexpr'.
12048       if (getLangOpts().CPlusPlus11) {
12049         Diag(VDecl->getLocation(),
12050              diag::ext_in_class_initializer_float_type_cxx11)
12051             << DclT << Init->getSourceRange();
12052         Diag(VDecl->getBeginLoc(),
12053              diag::note_in_class_initializer_float_type_cxx11)
12054             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12055       } else {
12056         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12057           << DclT << Init->getSourceRange();
12058 
12059         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12060           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12061             << Init->getSourceRange();
12062           VDecl->setInvalidDecl();
12063         }
12064       }
12065 
12066     // Suggest adding 'constexpr' in C++11 for literal types.
12067     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12068       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12069           << DclT << Init->getSourceRange()
12070           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12071       VDecl->setConstexpr(true);
12072 
12073     } else {
12074       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12075         << DclT << Init->getSourceRange();
12076       VDecl->setInvalidDecl();
12077     }
12078   } else if (VDecl->isFileVarDecl()) {
12079     // In C, extern is typically used to avoid tentative definitions when
12080     // declaring variables in headers, but adding an intializer makes it a
12081     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12082     // In C++, extern is often used to give implictly static const variables
12083     // external linkage, so don't warn in that case. If selectany is present,
12084     // this might be header code intended for C and C++ inclusion, so apply the
12085     // C++ rules.
12086     if (VDecl->getStorageClass() == SC_Extern &&
12087         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12088          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12089         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12090         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12091       Diag(VDecl->getLocation(), diag::warn_extern_init);
12092 
12093     // In Microsoft C++ mode, a const variable defined in namespace scope has
12094     // external linkage by default if the variable is declared with
12095     // __declspec(dllexport).
12096     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12097         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12098         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12099       VDecl->setStorageClass(SC_Extern);
12100 
12101     // C99 6.7.8p4. All file scoped initializers need to be constant.
12102     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12103       CheckForConstantInitializer(Init, DclT);
12104   }
12105 
12106   QualType InitType = Init->getType();
12107   if (!InitType.isNull() &&
12108       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12109        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12110     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12111 
12112   // We will represent direct-initialization similarly to copy-initialization:
12113   //    int x(1);  -as-> int x = 1;
12114   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12115   //
12116   // Clients that want to distinguish between the two forms, can check for
12117   // direct initializer using VarDecl::getInitStyle().
12118   // A major benefit is that clients that don't particularly care about which
12119   // exactly form was it (like the CodeGen) can handle both cases without
12120   // special case code.
12121 
12122   // C++ 8.5p11:
12123   // The form of initialization (using parentheses or '=') is generally
12124   // insignificant, but does matter when the entity being initialized has a
12125   // class type.
12126   if (CXXDirectInit) {
12127     assert(DirectInit && "Call-style initializer must be direct init.");
12128     VDecl->setInitStyle(VarDecl::CallInit);
12129   } else if (DirectInit) {
12130     // This must be list-initialization. No other way is direct-initialization.
12131     VDecl->setInitStyle(VarDecl::ListInit);
12132   }
12133 
12134   CheckCompleteVariableDeclaration(VDecl);
12135 }
12136 
12137 /// ActOnInitializerError - Given that there was an error parsing an
12138 /// initializer for the given declaration, try to return to some form
12139 /// of sanity.
12140 void Sema::ActOnInitializerError(Decl *D) {
12141   // Our main concern here is re-establishing invariants like "a
12142   // variable's type is either dependent or complete".
12143   if (!D || D->isInvalidDecl()) return;
12144 
12145   VarDecl *VD = dyn_cast<VarDecl>(D);
12146   if (!VD) return;
12147 
12148   // Bindings are not usable if we can't make sense of the initializer.
12149   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12150     for (auto *BD : DD->bindings())
12151       BD->setInvalidDecl();
12152 
12153   // Auto types are meaningless if we can't make sense of the initializer.
12154   if (ParsingInitForAutoVars.count(D)) {
12155     D->setInvalidDecl();
12156     return;
12157   }
12158 
12159   QualType Ty = VD->getType();
12160   if (Ty->isDependentType()) return;
12161 
12162   // Require a complete type.
12163   if (RequireCompleteType(VD->getLocation(),
12164                           Context.getBaseElementType(Ty),
12165                           diag::err_typecheck_decl_incomplete_type)) {
12166     VD->setInvalidDecl();
12167     return;
12168   }
12169 
12170   // Require a non-abstract type.
12171   if (RequireNonAbstractType(VD->getLocation(), Ty,
12172                              diag::err_abstract_type_in_decl,
12173                              AbstractVariableType)) {
12174     VD->setInvalidDecl();
12175     return;
12176   }
12177 
12178   // Don't bother complaining about constructors or destructors,
12179   // though.
12180 }
12181 
12182 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12183   // If there is no declaration, there was an error parsing it. Just ignore it.
12184   if (!RealDecl)
12185     return;
12186 
12187   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12188     QualType Type = Var->getType();
12189 
12190     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12191     if (isa<DecompositionDecl>(RealDecl)) {
12192       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12193       Var->setInvalidDecl();
12194       return;
12195     }
12196 
12197     if (Type->isUndeducedType() &&
12198         DeduceVariableDeclarationType(Var, false, nullptr))
12199       return;
12200 
12201     // C++11 [class.static.data]p3: A static data member can be declared with
12202     // the constexpr specifier; if so, its declaration shall specify
12203     // a brace-or-equal-initializer.
12204     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12205     // the definition of a variable [...] or the declaration of a static data
12206     // member.
12207     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12208         !Var->isThisDeclarationADemotedDefinition()) {
12209       if (Var->isStaticDataMember()) {
12210         // C++1z removes the relevant rule; the in-class declaration is always
12211         // a definition there.
12212         if (!getLangOpts().CPlusPlus17 &&
12213             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12214           Diag(Var->getLocation(),
12215                diag::err_constexpr_static_mem_var_requires_init)
12216             << Var->getDeclName();
12217           Var->setInvalidDecl();
12218           return;
12219         }
12220       } else {
12221         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12222         Var->setInvalidDecl();
12223         return;
12224       }
12225     }
12226 
12227     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12228     // be initialized.
12229     if (!Var->isInvalidDecl() &&
12230         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12231         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12232       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12233       Var->setInvalidDecl();
12234       return;
12235     }
12236 
12237     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12238     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12239         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12240       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12241                             NTCUC_DefaultInitializedObject, NTCUK_Init);
12242 
12243 
12244     switch (DefKind) {
12245     case VarDecl::Definition:
12246       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12247         break;
12248 
12249       // We have an out-of-line definition of a static data member
12250       // that has an in-class initializer, so we type-check this like
12251       // a declaration.
12252       //
12253       LLVM_FALLTHROUGH;
12254 
12255     case VarDecl::DeclarationOnly:
12256       // It's only a declaration.
12257 
12258       // Block scope. C99 6.7p7: If an identifier for an object is
12259       // declared with no linkage (C99 6.2.2p6), the type for the
12260       // object shall be complete.
12261       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12262           !Var->hasLinkage() && !Var->isInvalidDecl() &&
12263           RequireCompleteType(Var->getLocation(), Type,
12264                               diag::err_typecheck_decl_incomplete_type))
12265         Var->setInvalidDecl();
12266 
12267       // Make sure that the type is not abstract.
12268       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12269           RequireNonAbstractType(Var->getLocation(), Type,
12270                                  diag::err_abstract_type_in_decl,
12271                                  AbstractVariableType))
12272         Var->setInvalidDecl();
12273       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12274           Var->getStorageClass() == SC_PrivateExtern) {
12275         Diag(Var->getLocation(), diag::warn_private_extern);
12276         Diag(Var->getLocation(), diag::note_private_extern);
12277       }
12278 
12279       if (Context.getTargetInfo().allowDebugInfoForExternalVar() &&
12280           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12281         ExternalDeclarations.push_back(Var);
12282 
12283       return;
12284 
12285     case VarDecl::TentativeDefinition:
12286       // File scope. C99 6.9.2p2: A declaration of an identifier for an
12287       // object that has file scope without an initializer, and without a
12288       // storage-class specifier or with the storage-class specifier "static",
12289       // constitutes a tentative definition. Note: A tentative definition with
12290       // external linkage is valid (C99 6.2.2p5).
12291       if (!Var->isInvalidDecl()) {
12292         if (const IncompleteArrayType *ArrayT
12293                                     = Context.getAsIncompleteArrayType(Type)) {
12294           if (RequireCompleteType(Var->getLocation(),
12295                                   ArrayT->getElementType(),
12296                                   diag::err_illegal_decl_array_incomplete_type))
12297             Var->setInvalidDecl();
12298         } else if (Var->getStorageClass() == SC_Static) {
12299           // C99 6.9.2p3: If the declaration of an identifier for an object is
12300           // a tentative definition and has internal linkage (C99 6.2.2p3), the
12301           // declared type shall not be an incomplete type.
12302           // NOTE: code such as the following
12303           //     static struct s;
12304           //     struct s { int a; };
12305           // is accepted by gcc. Hence here we issue a warning instead of
12306           // an error and we do not invalidate the static declaration.
12307           // NOTE: to avoid multiple warnings, only check the first declaration.
12308           if (Var->isFirstDecl())
12309             RequireCompleteType(Var->getLocation(), Type,
12310                                 diag::ext_typecheck_decl_incomplete_type);
12311         }
12312       }
12313 
12314       // Record the tentative definition; we're done.
12315       if (!Var->isInvalidDecl())
12316         TentativeDefinitions.push_back(Var);
12317       return;
12318     }
12319 
12320     // Provide a specific diagnostic for uninitialized variable
12321     // definitions with incomplete array type.
12322     if (Type->isIncompleteArrayType()) {
12323       Diag(Var->getLocation(),
12324            diag::err_typecheck_incomplete_array_needs_initializer);
12325       Var->setInvalidDecl();
12326       return;
12327     }
12328 
12329     // Provide a specific diagnostic for uninitialized variable
12330     // definitions with reference type.
12331     if (Type->isReferenceType()) {
12332       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12333         << Var->getDeclName()
12334         << SourceRange(Var->getLocation(), Var->getLocation());
12335       Var->setInvalidDecl();
12336       return;
12337     }
12338 
12339     // Do not attempt to type-check the default initializer for a
12340     // variable with dependent type.
12341     if (Type->isDependentType())
12342       return;
12343 
12344     if (Var->isInvalidDecl())
12345       return;
12346 
12347     if (!Var->hasAttr<AliasAttr>()) {
12348       if (RequireCompleteType(Var->getLocation(),
12349                               Context.getBaseElementType(Type),
12350                               diag::err_typecheck_decl_incomplete_type)) {
12351         Var->setInvalidDecl();
12352         return;
12353       }
12354     } else {
12355       return;
12356     }
12357 
12358     // The variable can not have an abstract class type.
12359     if (RequireNonAbstractType(Var->getLocation(), Type,
12360                                diag::err_abstract_type_in_decl,
12361                                AbstractVariableType)) {
12362       Var->setInvalidDecl();
12363       return;
12364     }
12365 
12366     // Check for jumps past the implicit initializer.  C++0x
12367     // clarifies that this applies to a "variable with automatic
12368     // storage duration", not a "local variable".
12369     // C++11 [stmt.dcl]p3
12370     //   A program that jumps from a point where a variable with automatic
12371     //   storage duration is not in scope to a point where it is in scope is
12372     //   ill-formed unless the variable has scalar type, class type with a
12373     //   trivial default constructor and a trivial destructor, a cv-qualified
12374     //   version of one of these types, or an array of one of the preceding
12375     //   types and is declared without an initializer.
12376     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12377       if (const RecordType *Record
12378             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12379         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12380         // Mark the function (if we're in one) for further checking even if the
12381         // looser rules of C++11 do not require such checks, so that we can
12382         // diagnose incompatibilities with C++98.
12383         if (!CXXRecord->isPOD())
12384           setFunctionHasBranchProtectedScope();
12385       }
12386     }
12387     // In OpenCL, we can't initialize objects in the __local address space,
12388     // even implicitly, so don't synthesize an implicit initializer.
12389     if (getLangOpts().OpenCL &&
12390         Var->getType().getAddressSpace() == LangAS::opencl_local)
12391       return;
12392     // C++03 [dcl.init]p9:
12393     //   If no initializer is specified for an object, and the
12394     //   object is of (possibly cv-qualified) non-POD class type (or
12395     //   array thereof), the object shall be default-initialized; if
12396     //   the object is of const-qualified type, the underlying class
12397     //   type shall have a user-declared default
12398     //   constructor. Otherwise, if no initializer is specified for
12399     //   a non- static object, the object and its subobjects, if
12400     //   any, have an indeterminate initial value); if the object
12401     //   or any of its subobjects are of const-qualified type, the
12402     //   program is ill-formed.
12403     // C++0x [dcl.init]p11:
12404     //   If no initializer is specified for an object, the object is
12405     //   default-initialized; [...].
12406     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12407     InitializationKind Kind
12408       = InitializationKind::CreateDefault(Var->getLocation());
12409 
12410     InitializationSequence InitSeq(*this, Entity, Kind, None);
12411     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12412     if (Init.isInvalid())
12413       Var->setInvalidDecl();
12414     else if (Init.get()) {
12415       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12416       // This is important for template substitution.
12417       Var->setInitStyle(VarDecl::CallInit);
12418     }
12419 
12420     CheckCompleteVariableDeclaration(Var);
12421   }
12422 }
12423 
12424 void Sema::ActOnCXXForRangeDecl(Decl *D) {
12425   // If there is no declaration, there was an error parsing it. Ignore it.
12426   if (!D)
12427     return;
12428 
12429   VarDecl *VD = dyn_cast<VarDecl>(D);
12430   if (!VD) {
12431     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12432     D->setInvalidDecl();
12433     return;
12434   }
12435 
12436   VD->setCXXForRangeDecl(true);
12437 
12438   // for-range-declaration cannot be given a storage class specifier.
12439   int Error = -1;
12440   switch (VD->getStorageClass()) {
12441   case SC_None:
12442     break;
12443   case SC_Extern:
12444     Error = 0;
12445     break;
12446   case SC_Static:
12447     Error = 1;
12448     break;
12449   case SC_PrivateExtern:
12450     Error = 2;
12451     break;
12452   case SC_Auto:
12453     Error = 3;
12454     break;
12455   case SC_Register:
12456     Error = 4;
12457     break;
12458   }
12459   if (Error != -1) {
12460     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12461       << VD->getDeclName() << Error;
12462     D->setInvalidDecl();
12463   }
12464 }
12465 
12466 StmtResult
12467 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
12468                                  IdentifierInfo *Ident,
12469                                  ParsedAttributes &Attrs,
12470                                  SourceLocation AttrEnd) {
12471   // C++1y [stmt.iter]p1:
12472   //   A range-based for statement of the form
12473   //      for ( for-range-identifier : for-range-initializer ) statement
12474   //   is equivalent to
12475   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
12476   DeclSpec DS(Attrs.getPool().getFactory());
12477 
12478   const char *PrevSpec;
12479   unsigned DiagID;
12480   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
12481                      getPrintingPolicy());
12482 
12483   Declarator D(DS, DeclaratorContext::ForContext);
12484   D.SetIdentifier(Ident, IdentLoc);
12485   D.takeAttributes(Attrs, AttrEnd);
12486 
12487   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
12488                 IdentLoc);
12489   Decl *Var = ActOnDeclarator(S, D);
12490   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
12491   FinalizeDeclaration(Var);
12492   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
12493                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
12494 }
12495 
12496 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
12497   if (var->isInvalidDecl()) return;
12498 
12499   if (getLangOpts().OpenCL) {
12500     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
12501     // initialiser
12502     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
12503         !var->hasInit()) {
12504       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
12505           << 1 /*Init*/;
12506       var->setInvalidDecl();
12507       return;
12508     }
12509   }
12510 
12511   // In Objective-C, don't allow jumps past the implicit initialization of a
12512   // local retaining variable.
12513   if (getLangOpts().ObjC &&
12514       var->hasLocalStorage()) {
12515     switch (var->getType().getObjCLifetime()) {
12516     case Qualifiers::OCL_None:
12517     case Qualifiers::OCL_ExplicitNone:
12518     case Qualifiers::OCL_Autoreleasing:
12519       break;
12520 
12521     case Qualifiers::OCL_Weak:
12522     case Qualifiers::OCL_Strong:
12523       setFunctionHasBranchProtectedScope();
12524       break;
12525     }
12526   }
12527 
12528   if (var->hasLocalStorage() &&
12529       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
12530     setFunctionHasBranchProtectedScope();
12531 
12532   // Warn about externally-visible variables being defined without a
12533   // prior declaration.  We only want to do this for global
12534   // declarations, but we also specifically need to avoid doing it for
12535   // class members because the linkage of an anonymous class can
12536   // change if it's later given a typedef name.
12537   if (var->isThisDeclarationADefinition() &&
12538       var->getDeclContext()->getRedeclContext()->isFileContext() &&
12539       var->isExternallyVisible() && var->hasLinkage() &&
12540       !var->isInline() && !var->getDescribedVarTemplate() &&
12541       !isa<VarTemplatePartialSpecializationDecl>(var) &&
12542       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
12543       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
12544                                   var->getLocation())) {
12545     // Find a previous declaration that's not a definition.
12546     VarDecl *prev = var->getPreviousDecl();
12547     while (prev && prev->isThisDeclarationADefinition())
12548       prev = prev->getPreviousDecl();
12549 
12550     if (!prev) {
12551       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
12552       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
12553           << /* variable */ 0;
12554     }
12555   }
12556 
12557   // Cache the result of checking for constant initialization.
12558   Optional<bool> CacheHasConstInit;
12559   const Expr *CacheCulprit = nullptr;
12560   auto checkConstInit = [&]() mutable {
12561     if (!CacheHasConstInit)
12562       CacheHasConstInit = var->getInit()->isConstantInitializer(
12563             Context, var->getType()->isReferenceType(), &CacheCulprit);
12564     return *CacheHasConstInit;
12565   };
12566 
12567   if (var->getTLSKind() == VarDecl::TLS_Static) {
12568     if (var->getType().isDestructedType()) {
12569       // GNU C++98 edits for __thread, [basic.start.term]p3:
12570       //   The type of an object with thread storage duration shall not
12571       //   have a non-trivial destructor.
12572       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
12573       if (getLangOpts().CPlusPlus11)
12574         Diag(var->getLocation(), diag::note_use_thread_local);
12575     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
12576       if (!checkConstInit()) {
12577         // GNU C++98 edits for __thread, [basic.start.init]p4:
12578         //   An object of thread storage duration shall not require dynamic
12579         //   initialization.
12580         // FIXME: Need strict checking here.
12581         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
12582           << CacheCulprit->getSourceRange();
12583         if (getLangOpts().CPlusPlus11)
12584           Diag(var->getLocation(), diag::note_use_thread_local);
12585       }
12586     }
12587   }
12588 
12589   // Apply section attributes and pragmas to global variables.
12590   bool GlobalStorage = var->hasGlobalStorage();
12591   if (GlobalStorage && var->isThisDeclarationADefinition() &&
12592       !inTemplateInstantiation()) {
12593     PragmaStack<StringLiteral *> *Stack = nullptr;
12594     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
12595     if (var->getType().isConstQualified())
12596       Stack = &ConstSegStack;
12597     else if (!var->getInit()) {
12598       Stack = &BSSSegStack;
12599       SectionFlags |= ASTContext::PSF_Write;
12600     } else {
12601       Stack = &DataSegStack;
12602       SectionFlags |= ASTContext::PSF_Write;
12603     }
12604     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>())
12605       var->addAttr(SectionAttr::CreateImplicit(
12606           Context, Stack->CurrentValue->getString(),
12607           Stack->CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
12608           SectionAttr::Declspec_allocate));
12609     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
12610       if (UnifySection(SA->getName(), SectionFlags, var))
12611         var->dropAttr<SectionAttr>();
12612 
12613     // Apply the init_seg attribute if this has an initializer.  If the
12614     // initializer turns out to not be dynamic, we'll end up ignoring this
12615     // attribute.
12616     if (CurInitSeg && var->getInit())
12617       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
12618                                                CurInitSegLoc,
12619                                                AttributeCommonInfo::AS_Pragma));
12620   }
12621 
12622   // All the following checks are C++ only.
12623   if (!getLangOpts().CPlusPlus) {
12624       // If this variable must be emitted, add it as an initializer for the
12625       // current module.
12626      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12627        Context.addModuleInitializer(ModuleScopes.back().Module, var);
12628      return;
12629   }
12630 
12631   if (auto *DD = dyn_cast<DecompositionDecl>(var))
12632     CheckCompleteDecompositionDeclaration(DD);
12633 
12634   QualType type = var->getType();
12635   if (type->isDependentType()) return;
12636 
12637   if (var->hasAttr<BlocksAttr>())
12638     getCurFunction()->addByrefBlockVar(var);
12639 
12640   Expr *Init = var->getInit();
12641   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
12642   QualType baseType = Context.getBaseElementType(type);
12643 
12644   if (Init && !Init->isValueDependent()) {
12645     if (var->isConstexpr()) {
12646       SmallVector<PartialDiagnosticAt, 8> Notes;
12647       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
12648         SourceLocation DiagLoc = var->getLocation();
12649         // If the note doesn't add any useful information other than a source
12650         // location, fold it into the primary diagnostic.
12651         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12652               diag::note_invalid_subexpr_in_const_expr) {
12653           DiagLoc = Notes[0].first;
12654           Notes.clear();
12655         }
12656         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
12657           << var << Init->getSourceRange();
12658         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
12659           Diag(Notes[I].first, Notes[I].second);
12660       }
12661     } else if (var->mightBeUsableInConstantExpressions(Context)) {
12662       // Check whether the initializer of a const variable of integral or
12663       // enumeration type is an ICE now, since we can't tell whether it was
12664       // initialized by a constant expression if we check later.
12665       var->checkInitIsICE();
12666     }
12667 
12668     // Don't emit further diagnostics about constexpr globals since they
12669     // were just diagnosed.
12670     if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) {
12671       // FIXME: Need strict checking in C++03 here.
12672       bool DiagErr = getLangOpts().CPlusPlus11
12673           ? !var->checkInitIsICE() : !checkConstInit();
12674       if (DiagErr) {
12675         auto *Attr = var->getAttr<ConstInitAttr>();
12676         Diag(var->getLocation(), diag::err_require_constant_init_failed)
12677           << Init->getSourceRange();
12678         Diag(Attr->getLocation(),
12679              diag::note_declared_required_constant_init_here)
12680             << Attr->getRange() << Attr->isConstinit();
12681         if (getLangOpts().CPlusPlus11) {
12682           APValue Value;
12683           SmallVector<PartialDiagnosticAt, 8> Notes;
12684           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
12685           for (auto &it : Notes)
12686             Diag(it.first, it.second);
12687         } else {
12688           Diag(CacheCulprit->getExprLoc(),
12689                diag::note_invalid_subexpr_in_const_expr)
12690               << CacheCulprit->getSourceRange();
12691         }
12692       }
12693     }
12694     else if (!var->isConstexpr() && IsGlobal &&
12695              !getDiagnostics().isIgnored(diag::warn_global_constructor,
12696                                     var->getLocation())) {
12697       // Warn about globals which don't have a constant initializer.  Don't
12698       // warn about globals with a non-trivial destructor because we already
12699       // warned about them.
12700       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
12701       if (!(RD && !RD->hasTrivialDestructor())) {
12702         if (!checkConstInit())
12703           Diag(var->getLocation(), diag::warn_global_constructor)
12704             << Init->getSourceRange();
12705       }
12706     }
12707   }
12708 
12709   // Require the destructor.
12710   if (const RecordType *recordType = baseType->getAs<RecordType>())
12711     FinalizeVarWithDestructor(var, recordType);
12712 
12713   // If this variable must be emitted, add it as an initializer for the current
12714   // module.
12715   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12716     Context.addModuleInitializer(ModuleScopes.back().Module, var);
12717 }
12718 
12719 /// Determines if a variable's alignment is dependent.
12720 static bool hasDependentAlignment(VarDecl *VD) {
12721   if (VD->getType()->isDependentType())
12722     return true;
12723   for (auto *I : VD->specific_attrs<AlignedAttr>())
12724     if (I->isAlignmentDependent())
12725       return true;
12726   return false;
12727 }
12728 
12729 /// Check if VD needs to be dllexport/dllimport due to being in a
12730 /// dllexport/import function.
12731 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
12732   assert(VD->isStaticLocal());
12733 
12734   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12735 
12736   // Find outermost function when VD is in lambda function.
12737   while (FD && !getDLLAttr(FD) &&
12738          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
12739          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
12740     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
12741   }
12742 
12743   if (!FD)
12744     return;
12745 
12746   // Static locals inherit dll attributes from their function.
12747   if (Attr *A = getDLLAttr(FD)) {
12748     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
12749     NewAttr->setInherited(true);
12750     VD->addAttr(NewAttr);
12751   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
12752     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
12753     NewAttr->setInherited(true);
12754     VD->addAttr(NewAttr);
12755 
12756     // Export this function to enforce exporting this static variable even
12757     // if it is not used in this compilation unit.
12758     if (!FD->hasAttr<DLLExportAttr>())
12759       FD->addAttr(NewAttr);
12760 
12761   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
12762     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
12763     NewAttr->setInherited(true);
12764     VD->addAttr(NewAttr);
12765   }
12766 }
12767 
12768 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
12769 /// any semantic actions necessary after any initializer has been attached.
12770 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
12771   // Note that we are no longer parsing the initializer for this declaration.
12772   ParsingInitForAutoVars.erase(ThisDecl);
12773 
12774   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
12775   if (!VD)
12776     return;
12777 
12778   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
12779   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
12780       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
12781     if (PragmaClangBSSSection.Valid)
12782       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
12783           Context, PragmaClangBSSSection.SectionName,
12784           PragmaClangBSSSection.PragmaLocation,
12785           AttributeCommonInfo::AS_Pragma));
12786     if (PragmaClangDataSection.Valid)
12787       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
12788           Context, PragmaClangDataSection.SectionName,
12789           PragmaClangDataSection.PragmaLocation,
12790           AttributeCommonInfo::AS_Pragma));
12791     if (PragmaClangRodataSection.Valid)
12792       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
12793           Context, PragmaClangRodataSection.SectionName,
12794           PragmaClangRodataSection.PragmaLocation,
12795           AttributeCommonInfo::AS_Pragma));
12796     if (PragmaClangRelroSection.Valid)
12797       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
12798           Context, PragmaClangRelroSection.SectionName,
12799           PragmaClangRelroSection.PragmaLocation,
12800           AttributeCommonInfo::AS_Pragma));
12801   }
12802 
12803   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
12804     for (auto *BD : DD->bindings()) {
12805       FinalizeDeclaration(BD);
12806     }
12807   }
12808 
12809   checkAttributesAfterMerging(*this, *VD);
12810 
12811   // Perform TLS alignment check here after attributes attached to the variable
12812   // which may affect the alignment have been processed. Only perform the check
12813   // if the target has a maximum TLS alignment (zero means no constraints).
12814   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
12815     // Protect the check so that it's not performed on dependent types and
12816     // dependent alignments (we can't determine the alignment in that case).
12817     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
12818         !VD->isInvalidDecl()) {
12819       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
12820       if (Context.getDeclAlign(VD) > MaxAlignChars) {
12821         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
12822           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
12823           << (unsigned)MaxAlignChars.getQuantity();
12824       }
12825     }
12826   }
12827 
12828   if (VD->isStaticLocal()) {
12829     CheckStaticLocalForDllExport(VD);
12830 
12831     if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
12832       // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
12833       // function, only __shared__ variables or variables without any device
12834       // memory qualifiers may be declared with static storage class.
12835       // Note: It is unclear how a function-scope non-const static variable
12836       // without device memory qualifier is implemented, therefore only static
12837       // const variable without device memory qualifier is allowed.
12838       [&]() {
12839         if (!getLangOpts().CUDA)
12840           return;
12841         if (VD->hasAttr<CUDASharedAttr>())
12842           return;
12843         if (VD->getType().isConstQualified() &&
12844             !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
12845           return;
12846         if (CUDADiagIfDeviceCode(VD->getLocation(),
12847                                  diag::err_device_static_local_var)
12848             << CurrentCUDATarget())
12849           VD->setInvalidDecl();
12850       }();
12851     }
12852   }
12853 
12854   // Perform check for initializers of device-side global variables.
12855   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
12856   // 7.5). We must also apply the same checks to all __shared__
12857   // variables whether they are local or not. CUDA also allows
12858   // constant initializers for __constant__ and __device__ variables.
12859   if (getLangOpts().CUDA)
12860     checkAllowedCUDAInitializer(VD);
12861 
12862   // Grab the dllimport or dllexport attribute off of the VarDecl.
12863   const InheritableAttr *DLLAttr = getDLLAttr(VD);
12864 
12865   // Imported static data members cannot be defined out-of-line.
12866   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
12867     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
12868         VD->isThisDeclarationADefinition()) {
12869       // We allow definitions of dllimport class template static data members
12870       // with a warning.
12871       CXXRecordDecl *Context =
12872         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
12873       bool IsClassTemplateMember =
12874           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
12875           Context->getDescribedClassTemplate();
12876 
12877       Diag(VD->getLocation(),
12878            IsClassTemplateMember
12879                ? diag::warn_attribute_dllimport_static_field_definition
12880                : diag::err_attribute_dllimport_static_field_definition);
12881       Diag(IA->getLocation(), diag::note_attribute);
12882       if (!IsClassTemplateMember)
12883         VD->setInvalidDecl();
12884     }
12885   }
12886 
12887   // dllimport/dllexport variables cannot be thread local, their TLS index
12888   // isn't exported with the variable.
12889   if (DLLAttr && VD->getTLSKind()) {
12890     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12891     if (F && getDLLAttr(F)) {
12892       assert(VD->isStaticLocal());
12893       // But if this is a static local in a dlimport/dllexport function, the
12894       // function will never be inlined, which means the var would never be
12895       // imported, so having it marked import/export is safe.
12896     } else {
12897       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
12898                                                                     << DLLAttr;
12899       VD->setInvalidDecl();
12900     }
12901   }
12902 
12903   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
12904     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
12905       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
12906       VD->dropAttr<UsedAttr>();
12907     }
12908   }
12909 
12910   const DeclContext *DC = VD->getDeclContext();
12911   // If there's a #pragma GCC visibility in scope, and this isn't a class
12912   // member, set the visibility of this variable.
12913   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
12914     AddPushedVisibilityAttribute(VD);
12915 
12916   // FIXME: Warn on unused var template partial specializations.
12917   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
12918     MarkUnusedFileScopedDecl(VD);
12919 
12920   // Now we have parsed the initializer and can update the table of magic
12921   // tag values.
12922   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
12923       !VD->getType()->isIntegralOrEnumerationType())
12924     return;
12925 
12926   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
12927     const Expr *MagicValueExpr = VD->getInit();
12928     if (!MagicValueExpr) {
12929       continue;
12930     }
12931     llvm::APSInt MagicValueInt;
12932     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
12933       Diag(I->getRange().getBegin(),
12934            diag::err_type_tag_for_datatype_not_ice)
12935         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12936       continue;
12937     }
12938     if (MagicValueInt.getActiveBits() > 64) {
12939       Diag(I->getRange().getBegin(),
12940            diag::err_type_tag_for_datatype_too_large)
12941         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12942       continue;
12943     }
12944     uint64_t MagicValue = MagicValueInt.getZExtValue();
12945     RegisterTypeTagForDatatype(I->getArgumentKind(),
12946                                MagicValue,
12947                                I->getMatchingCType(),
12948                                I->getLayoutCompatible(),
12949                                I->getMustBeNull());
12950   }
12951 }
12952 
12953 static bool hasDeducedAuto(DeclaratorDecl *DD) {
12954   auto *VD = dyn_cast<VarDecl>(DD);
12955   return VD && !VD->getType()->hasAutoForTrailingReturnType();
12956 }
12957 
12958 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
12959                                                    ArrayRef<Decl *> Group) {
12960   SmallVector<Decl*, 8> Decls;
12961 
12962   if (DS.isTypeSpecOwned())
12963     Decls.push_back(DS.getRepAsDecl());
12964 
12965   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
12966   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
12967   bool DiagnosedMultipleDecomps = false;
12968   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
12969   bool DiagnosedNonDeducedAuto = false;
12970 
12971   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12972     if (Decl *D = Group[i]) {
12973       // For declarators, there are some additional syntactic-ish checks we need
12974       // to perform.
12975       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
12976         if (!FirstDeclaratorInGroup)
12977           FirstDeclaratorInGroup = DD;
12978         if (!FirstDecompDeclaratorInGroup)
12979           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
12980         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
12981             !hasDeducedAuto(DD))
12982           FirstNonDeducedAutoInGroup = DD;
12983 
12984         if (FirstDeclaratorInGroup != DD) {
12985           // A decomposition declaration cannot be combined with any other
12986           // declaration in the same group.
12987           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
12988             Diag(FirstDecompDeclaratorInGroup->getLocation(),
12989                  diag::err_decomp_decl_not_alone)
12990                 << FirstDeclaratorInGroup->getSourceRange()
12991                 << DD->getSourceRange();
12992             DiagnosedMultipleDecomps = true;
12993           }
12994 
12995           // A declarator that uses 'auto' in any way other than to declare a
12996           // variable with a deduced type cannot be combined with any other
12997           // declarator in the same group.
12998           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
12999             Diag(FirstNonDeducedAutoInGroup->getLocation(),
13000                  diag::err_auto_non_deduced_not_alone)
13001                 << FirstNonDeducedAutoInGroup->getType()
13002                        ->hasAutoForTrailingReturnType()
13003                 << FirstDeclaratorInGroup->getSourceRange()
13004                 << DD->getSourceRange();
13005             DiagnosedNonDeducedAuto = true;
13006           }
13007         }
13008       }
13009 
13010       Decls.push_back(D);
13011     }
13012   }
13013 
13014   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13015     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13016       handleTagNumbering(Tag, S);
13017       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13018           getLangOpts().CPlusPlus)
13019         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13020     }
13021   }
13022 
13023   return BuildDeclaratorGroup(Decls);
13024 }
13025 
13026 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
13027 /// group, performing any necessary semantic checking.
13028 Sema::DeclGroupPtrTy
13029 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13030   // C++14 [dcl.spec.auto]p7: (DR1347)
13031   //   If the type that replaces the placeholder type is not the same in each
13032   //   deduction, the program is ill-formed.
13033   if (Group.size() > 1) {
13034     QualType Deduced;
13035     VarDecl *DeducedDecl = nullptr;
13036     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13037       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13038       if (!D || D->isInvalidDecl())
13039         break;
13040       DeducedType *DT = D->getType()->getContainedDeducedType();
13041       if (!DT || DT->getDeducedType().isNull())
13042         continue;
13043       if (Deduced.isNull()) {
13044         Deduced = DT->getDeducedType();
13045         DeducedDecl = D;
13046       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13047         auto *AT = dyn_cast<AutoType>(DT);
13048         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13049              diag::err_auto_different_deductions)
13050           << (AT ? (unsigned)AT->getKeyword() : 3)
13051           << Deduced << DeducedDecl->getDeclName()
13052           << DT->getDeducedType() << D->getDeclName()
13053           << DeducedDecl->getInit()->getSourceRange()
13054           << D->getInit()->getSourceRange();
13055         D->setInvalidDecl();
13056         break;
13057       }
13058     }
13059   }
13060 
13061   ActOnDocumentableDecls(Group);
13062 
13063   return DeclGroupPtrTy::make(
13064       DeclGroupRef::Create(Context, Group.data(), Group.size()));
13065 }
13066 
13067 void Sema::ActOnDocumentableDecl(Decl *D) {
13068   ActOnDocumentableDecls(D);
13069 }
13070 
13071 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13072   // Don't parse the comment if Doxygen diagnostics are ignored.
13073   if (Group.empty() || !Group[0])
13074     return;
13075 
13076   if (Diags.isIgnored(diag::warn_doc_param_not_found,
13077                       Group[0]->getLocation()) &&
13078       Diags.isIgnored(diag::warn_unknown_comment_command_name,
13079                       Group[0]->getLocation()))
13080     return;
13081 
13082   if (Group.size() >= 2) {
13083     // This is a decl group.  Normally it will contain only declarations
13084     // produced from declarator list.  But in case we have any definitions or
13085     // additional declaration references:
13086     //   'typedef struct S {} S;'
13087     //   'typedef struct S *S;'
13088     //   'struct S *pS;'
13089     // FinalizeDeclaratorGroup adds these as separate declarations.
13090     Decl *MaybeTagDecl = Group[0];
13091     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13092       Group = Group.slice(1);
13093     }
13094   }
13095 
13096   // FIMXE: We assume every Decl in the group is in the same file.
13097   // This is false when preprocessor constructs the group from decls in
13098   // different files (e. g. macros or #include).
13099   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13100 }
13101 
13102 /// Common checks for a parameter-declaration that should apply to both function
13103 /// parameters and non-type template parameters.
13104 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13105   // Check that there are no default arguments inside the type of this
13106   // parameter.
13107   if (getLangOpts().CPlusPlus)
13108     CheckExtraCXXDefaultArguments(D);
13109 
13110   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13111   if (D.getCXXScopeSpec().isSet()) {
13112     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13113       << D.getCXXScopeSpec().getRange();
13114   }
13115 
13116   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13117   // simple identifier except [...irrelevant cases...].
13118   switch (D.getName().getKind()) {
13119   case UnqualifiedIdKind::IK_Identifier:
13120     break;
13121 
13122   case UnqualifiedIdKind::IK_OperatorFunctionId:
13123   case UnqualifiedIdKind::IK_ConversionFunctionId:
13124   case UnqualifiedIdKind::IK_LiteralOperatorId:
13125   case UnqualifiedIdKind::IK_ConstructorName:
13126   case UnqualifiedIdKind::IK_DestructorName:
13127   case UnqualifiedIdKind::IK_ImplicitSelfParam:
13128   case UnqualifiedIdKind::IK_DeductionGuideName:
13129     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13130       << GetNameForDeclarator(D).getName();
13131     break;
13132 
13133   case UnqualifiedIdKind::IK_TemplateId:
13134   case UnqualifiedIdKind::IK_ConstructorTemplateId:
13135     // GetNameForDeclarator would not produce a useful name in this case.
13136     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13137     break;
13138   }
13139 }
13140 
13141 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13142 /// to introduce parameters into function prototype scope.
13143 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13144   const DeclSpec &DS = D.getDeclSpec();
13145 
13146   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13147 
13148   // C++03 [dcl.stc]p2 also permits 'auto'.
13149   StorageClass SC = SC_None;
13150   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13151     SC = SC_Register;
13152     // In C++11, the 'register' storage class specifier is deprecated.
13153     // In C++17, it is not allowed, but we tolerate it as an extension.
13154     if (getLangOpts().CPlusPlus11) {
13155       Diag(DS.getStorageClassSpecLoc(),
13156            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13157                                      : diag::warn_deprecated_register)
13158         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13159     }
13160   } else if (getLangOpts().CPlusPlus &&
13161              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13162     SC = SC_Auto;
13163   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13164     Diag(DS.getStorageClassSpecLoc(),
13165          diag::err_invalid_storage_class_in_func_decl);
13166     D.getMutableDeclSpec().ClearStorageClassSpecs();
13167   }
13168 
13169   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13170     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13171       << DeclSpec::getSpecifierName(TSCS);
13172   if (DS.isInlineSpecified())
13173     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13174         << getLangOpts().CPlusPlus17;
13175   if (DS.hasConstexprSpecifier())
13176     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13177         << 0 << D.getDeclSpec().getConstexprSpecifier();
13178 
13179   DiagnoseFunctionSpecifiers(DS);
13180 
13181   CheckFunctionOrTemplateParamDeclarator(S, D);
13182 
13183   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13184   QualType parmDeclType = TInfo->getType();
13185 
13186   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13187   IdentifierInfo *II = D.getIdentifier();
13188   if (II) {
13189     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13190                    ForVisibleRedeclaration);
13191     LookupName(R, S);
13192     if (R.isSingleResult()) {
13193       NamedDecl *PrevDecl = R.getFoundDecl();
13194       if (PrevDecl->isTemplateParameter()) {
13195         // Maybe we will complain about the shadowed template parameter.
13196         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13197         // Just pretend that we didn't see the previous declaration.
13198         PrevDecl = nullptr;
13199       } else if (S->isDeclScope(PrevDecl)) {
13200         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13201         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13202 
13203         // Recover by removing the name
13204         II = nullptr;
13205         D.SetIdentifier(nullptr, D.getIdentifierLoc());
13206         D.setInvalidType(true);
13207       }
13208     }
13209   }
13210 
13211   // Temporarily put parameter variables in the translation unit, not
13212   // the enclosing context.  This prevents them from accidentally
13213   // looking like class members in C++.
13214   ParmVarDecl *New =
13215       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13216                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13217 
13218   if (D.isInvalidType())
13219     New->setInvalidDecl();
13220 
13221   assert(S->isFunctionPrototypeScope());
13222   assert(S->getFunctionPrototypeDepth() >= 1);
13223   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13224                     S->getNextFunctionPrototypeIndex());
13225 
13226   // Add the parameter declaration into this scope.
13227   S->AddDecl(New);
13228   if (II)
13229     IdResolver.AddDecl(New);
13230 
13231   ProcessDeclAttributes(S, New, D);
13232 
13233   if (D.getDeclSpec().isModulePrivateSpecified())
13234     Diag(New->getLocation(), diag::err_module_private_local)
13235       << 1 << New->getDeclName()
13236       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13237       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13238 
13239   if (New->hasAttr<BlocksAttr>()) {
13240     Diag(New->getLocation(), diag::err_block_on_nonlocal);
13241   }
13242 
13243   if (getLangOpts().OpenCL)
13244     deduceOpenCLAddressSpace(New);
13245 
13246   return New;
13247 }
13248 
13249 /// Synthesizes a variable for a parameter arising from a
13250 /// typedef.
13251 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13252                                               SourceLocation Loc,
13253                                               QualType T) {
13254   /* FIXME: setting StartLoc == Loc.
13255      Would it be worth to modify callers so as to provide proper source
13256      location for the unnamed parameters, embedding the parameter's type? */
13257   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13258                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
13259                                            SC_None, nullptr);
13260   Param->setImplicit();
13261   return Param;
13262 }
13263 
13264 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13265   // Don't diagnose unused-parameter errors in template instantiations; we
13266   // will already have done so in the template itself.
13267   if (inTemplateInstantiation())
13268     return;
13269 
13270   for (const ParmVarDecl *Parameter : Parameters) {
13271     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13272         !Parameter->hasAttr<UnusedAttr>()) {
13273       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13274         << Parameter->getDeclName();
13275     }
13276   }
13277 }
13278 
13279 void Sema::DiagnoseSizeOfParametersAndReturnValue(
13280     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13281   if (LangOpts.NumLargeByValueCopy == 0) // No check.
13282     return;
13283 
13284   // Warn if the return value is pass-by-value and larger than the specified
13285   // threshold.
13286   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13287     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13288     if (Size > LangOpts.NumLargeByValueCopy)
13289       Diag(D->getLocation(), diag::warn_return_value_size)
13290           << D->getDeclName() << Size;
13291   }
13292 
13293   // Warn if any parameter is pass-by-value and larger than the specified
13294   // threshold.
13295   for (const ParmVarDecl *Parameter : Parameters) {
13296     QualType T = Parameter->getType();
13297     if (T->isDependentType() || !T.isPODType(Context))
13298       continue;
13299     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13300     if (Size > LangOpts.NumLargeByValueCopy)
13301       Diag(Parameter->getLocation(), diag::warn_parameter_size)
13302           << Parameter->getDeclName() << Size;
13303   }
13304 }
13305 
13306 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13307                                   SourceLocation NameLoc, IdentifierInfo *Name,
13308                                   QualType T, TypeSourceInfo *TSInfo,
13309                                   StorageClass SC) {
13310   // In ARC, infer a lifetime qualifier for appropriate parameter types.
13311   if (getLangOpts().ObjCAutoRefCount &&
13312       T.getObjCLifetime() == Qualifiers::OCL_None &&
13313       T->isObjCLifetimeType()) {
13314 
13315     Qualifiers::ObjCLifetime lifetime;
13316 
13317     // Special cases for arrays:
13318     //   - if it's const, use __unsafe_unretained
13319     //   - otherwise, it's an error
13320     if (T->isArrayType()) {
13321       if (!T.isConstQualified()) {
13322         if (DelayedDiagnostics.shouldDelayDiagnostics())
13323           DelayedDiagnostics.add(
13324               sema::DelayedDiagnostic::makeForbiddenType(
13325               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13326         else
13327           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13328               << TSInfo->getTypeLoc().getSourceRange();
13329       }
13330       lifetime = Qualifiers::OCL_ExplicitNone;
13331     } else {
13332       lifetime = T->getObjCARCImplicitLifetime();
13333     }
13334     T = Context.getLifetimeQualifiedType(T, lifetime);
13335   }
13336 
13337   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13338                                          Context.getAdjustedParameterType(T),
13339                                          TSInfo, SC, nullptr);
13340 
13341   // Make a note if we created a new pack in the scope of a lambda, so that
13342   // we know that references to that pack must also be expanded within the
13343   // lambda scope.
13344   if (New->isParameterPack())
13345     if (auto *LSI = getEnclosingLambda())
13346       LSI->LocalPacks.push_back(New);
13347 
13348   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13349       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13350     checkNonTrivialCUnion(New->getType(), New->getLocation(),
13351                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13352 
13353   // Parameters can not be abstract class types.
13354   // For record types, this is done by the AbstractClassUsageDiagnoser once
13355   // the class has been completely parsed.
13356   if (!CurContext->isRecord() &&
13357       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13358                              AbstractParamType))
13359     New->setInvalidDecl();
13360 
13361   // Parameter declarators cannot be interface types. All ObjC objects are
13362   // passed by reference.
13363   if (T->isObjCObjectType()) {
13364     SourceLocation TypeEndLoc =
13365         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13366     Diag(NameLoc,
13367          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13368       << FixItHint::CreateInsertion(TypeEndLoc, "*");
13369     T = Context.getObjCObjectPointerType(T);
13370     New->setType(T);
13371   }
13372 
13373   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13374   // duration shall not be qualified by an address-space qualifier."
13375   // Since all parameters have automatic store duration, they can not have
13376   // an address space.
13377   if (T.getAddressSpace() != LangAS::Default &&
13378       // OpenCL allows function arguments declared to be an array of a type
13379       // to be qualified with an address space.
13380       !(getLangOpts().OpenCL &&
13381         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13382     Diag(NameLoc, diag::err_arg_with_address_space);
13383     New->setInvalidDecl();
13384   }
13385 
13386   return New;
13387 }
13388 
13389 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
13390                                            SourceLocation LocAfterDecls) {
13391   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
13392 
13393   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
13394   // for a K&R function.
13395   if (!FTI.hasPrototype) {
13396     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
13397       --i;
13398       if (FTI.Params[i].Param == nullptr) {
13399         SmallString<256> Code;
13400         llvm::raw_svector_ostream(Code)
13401             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
13402         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
13403             << FTI.Params[i].Ident
13404             << FixItHint::CreateInsertion(LocAfterDecls, Code);
13405 
13406         // Implicitly declare the argument as type 'int' for lack of a better
13407         // type.
13408         AttributeFactory attrs;
13409         DeclSpec DS(attrs);
13410         const char* PrevSpec; // unused
13411         unsigned DiagID; // unused
13412         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
13413                            DiagID, Context.getPrintingPolicy());
13414         // Use the identifier location for the type source range.
13415         DS.SetRangeStart(FTI.Params[i].IdentLoc);
13416         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
13417         Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
13418         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
13419         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
13420       }
13421     }
13422   }
13423 }
13424 
13425 Decl *
13426 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
13427                               MultiTemplateParamsArg TemplateParameterLists,
13428                               SkipBodyInfo *SkipBody) {
13429   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
13430   assert(D.isFunctionDeclarator() && "Not a function declarator!");
13431   Scope *ParentScope = FnBodyScope->getParent();
13432 
13433   D.setFunctionDefinitionKind(FDK_Definition);
13434   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
13435   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
13436 }
13437 
13438 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
13439   Consumer.HandleInlineFunctionDefinition(D);
13440 }
13441 
13442 static bool
13443 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
13444                                 const FunctionDecl *&PossiblePrototype) {
13445   // Don't warn about invalid declarations.
13446   if (FD->isInvalidDecl())
13447     return false;
13448 
13449   // Or declarations that aren't global.
13450   if (!FD->isGlobal())
13451     return false;
13452 
13453   // Don't warn about C++ member functions.
13454   if (isa<CXXMethodDecl>(FD))
13455     return false;
13456 
13457   // Don't warn about 'main'.
13458   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
13459     if (IdentifierInfo *II = FD->getIdentifier())
13460       if (II->isStr("main"))
13461         return false;
13462 
13463   // Don't warn about inline functions.
13464   if (FD->isInlined())
13465     return false;
13466 
13467   // Don't warn about function templates.
13468   if (FD->getDescribedFunctionTemplate())
13469     return false;
13470 
13471   // Don't warn about function template specializations.
13472   if (FD->isFunctionTemplateSpecialization())
13473     return false;
13474 
13475   // Don't warn for OpenCL kernels.
13476   if (FD->hasAttr<OpenCLKernelAttr>())
13477     return false;
13478 
13479   // Don't warn on explicitly deleted functions.
13480   if (FD->isDeleted())
13481     return false;
13482 
13483   for (const FunctionDecl *Prev = FD->getPreviousDecl();
13484        Prev; Prev = Prev->getPreviousDecl()) {
13485     // Ignore any declarations that occur in function or method
13486     // scope, because they aren't visible from the header.
13487     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
13488       continue;
13489 
13490     PossiblePrototype = Prev;
13491     return Prev->getType()->isFunctionNoProtoType();
13492   }
13493 
13494   return true;
13495 }
13496 
13497 void
13498 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
13499                                    const FunctionDecl *EffectiveDefinition,
13500                                    SkipBodyInfo *SkipBody) {
13501   const FunctionDecl *Definition = EffectiveDefinition;
13502   if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
13503     // If this is a friend function defined in a class template, it does not
13504     // have a body until it is used, nevertheless it is a definition, see
13505     // [temp.inst]p2:
13506     //
13507     // ... for the purpose of determining whether an instantiated redeclaration
13508     // is valid according to [basic.def.odr] and [class.mem], a declaration that
13509     // corresponds to a definition in the template is considered to be a
13510     // definition.
13511     //
13512     // The following code must produce redefinition error:
13513     //
13514     //     template<typename T> struct C20 { friend void func_20() {} };
13515     //     C20<int> c20i;
13516     //     void func_20() {}
13517     //
13518     for (auto I : FD->redecls()) {
13519       if (I != FD && !I->isInvalidDecl() &&
13520           I->getFriendObjectKind() != Decl::FOK_None) {
13521         if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
13522           if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
13523             // A merged copy of the same function, instantiated as a member of
13524             // the same class, is OK.
13525             if (declaresSameEntity(OrigFD, Original) &&
13526                 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
13527                                    cast<Decl>(FD->getLexicalDeclContext())))
13528               continue;
13529           }
13530 
13531           if (Original->isThisDeclarationADefinition()) {
13532             Definition = I;
13533             break;
13534           }
13535         }
13536       }
13537     }
13538   }
13539 
13540   if (!Definition)
13541     // Similar to friend functions a friend function template may be a
13542     // definition and do not have a body if it is instantiated in a class
13543     // template.
13544     if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
13545       for (auto I : FTD->redecls()) {
13546         auto D = cast<FunctionTemplateDecl>(I);
13547         if (D != FTD) {
13548           assert(!D->isThisDeclarationADefinition() &&
13549                  "More than one definition in redeclaration chain");
13550           if (D->getFriendObjectKind() != Decl::FOK_None)
13551             if (FunctionTemplateDecl *FT =
13552                                        D->getInstantiatedFromMemberTemplate()) {
13553               if (FT->isThisDeclarationADefinition()) {
13554                 Definition = D->getTemplatedDecl();
13555                 break;
13556               }
13557             }
13558         }
13559       }
13560     }
13561 
13562   if (!Definition)
13563     return;
13564 
13565   if (canRedefineFunction(Definition, getLangOpts()))
13566     return;
13567 
13568   // Don't emit an error when this is redefinition of a typo-corrected
13569   // definition.
13570   if (TypoCorrectedFunctionDefinitions.count(Definition))
13571     return;
13572 
13573   // If we don't have a visible definition of the function, and it's inline or
13574   // a template, skip the new definition.
13575   if (SkipBody && !hasVisibleDefinition(Definition) &&
13576       (Definition->getFormalLinkage() == InternalLinkage ||
13577        Definition->isInlined() ||
13578        Definition->getDescribedFunctionTemplate() ||
13579        Definition->getNumTemplateParameterLists())) {
13580     SkipBody->ShouldSkip = true;
13581     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
13582     if (auto *TD = Definition->getDescribedFunctionTemplate())
13583       makeMergedDefinitionVisible(TD);
13584     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
13585     return;
13586   }
13587 
13588   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
13589       Definition->getStorageClass() == SC_Extern)
13590     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
13591         << FD->getDeclName() << getLangOpts().CPlusPlus;
13592   else
13593     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
13594 
13595   Diag(Definition->getLocation(), diag::note_previous_definition);
13596   FD->setInvalidDecl();
13597 }
13598 
13599 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
13600                                    Sema &S) {
13601   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
13602 
13603   LambdaScopeInfo *LSI = S.PushLambdaScope();
13604   LSI->CallOperator = CallOperator;
13605   LSI->Lambda = LambdaClass;
13606   LSI->ReturnType = CallOperator->getReturnType();
13607   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
13608 
13609   if (LCD == LCD_None)
13610     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
13611   else if (LCD == LCD_ByCopy)
13612     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
13613   else if (LCD == LCD_ByRef)
13614     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
13615   DeclarationNameInfo DNI = CallOperator->getNameInfo();
13616 
13617   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
13618   LSI->Mutable = !CallOperator->isConst();
13619 
13620   // Add the captures to the LSI so they can be noted as already
13621   // captured within tryCaptureVar.
13622   auto I = LambdaClass->field_begin();
13623   for (const auto &C : LambdaClass->captures()) {
13624     if (C.capturesVariable()) {
13625       VarDecl *VD = C.getCapturedVar();
13626       if (VD->isInitCapture())
13627         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
13628       QualType CaptureType = VD->getType();
13629       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
13630       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
13631           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
13632           /*EllipsisLoc*/C.isPackExpansion()
13633                          ? C.getEllipsisLoc() : SourceLocation(),
13634           CaptureType, /*Invalid*/false);
13635 
13636     } else if (C.capturesThis()) {
13637       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
13638                           C.getCaptureKind() == LCK_StarThis);
13639     } else {
13640       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
13641                              I->getType());
13642     }
13643     ++I;
13644   }
13645 }
13646 
13647 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
13648                                     SkipBodyInfo *SkipBody) {
13649   if (!D) {
13650     // Parsing the function declaration failed in some way. Push on a fake scope
13651     // anyway so we can try to parse the function body.
13652     PushFunctionScope();
13653     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13654     return D;
13655   }
13656 
13657   FunctionDecl *FD = nullptr;
13658 
13659   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
13660     FD = FunTmpl->getTemplatedDecl();
13661   else
13662     FD = cast<FunctionDecl>(D);
13663 
13664   // Do not push if it is a lambda because one is already pushed when building
13665   // the lambda in ActOnStartOfLambdaDefinition().
13666   if (!isLambdaCallOperator(FD))
13667     PushExpressionEvaluationContext(
13668         FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
13669                           : ExprEvalContexts.back().Context);
13670 
13671   // Check for defining attributes before the check for redefinition.
13672   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
13673     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
13674     FD->dropAttr<AliasAttr>();
13675     FD->setInvalidDecl();
13676   }
13677   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
13678     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
13679     FD->dropAttr<IFuncAttr>();
13680     FD->setInvalidDecl();
13681   }
13682 
13683   // See if this is a redefinition. If 'will have body' is already set, then
13684   // these checks were already performed when it was set.
13685   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
13686     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
13687 
13688     // If we're skipping the body, we're done. Don't enter the scope.
13689     if (SkipBody && SkipBody->ShouldSkip)
13690       return D;
13691   }
13692 
13693   // Mark this function as "will have a body eventually".  This lets users to
13694   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
13695   // this function.
13696   FD->setWillHaveBody();
13697 
13698   // If we are instantiating a generic lambda call operator, push
13699   // a LambdaScopeInfo onto the function stack.  But use the information
13700   // that's already been calculated (ActOnLambdaExpr) to prime the current
13701   // LambdaScopeInfo.
13702   // When the template operator is being specialized, the LambdaScopeInfo,
13703   // has to be properly restored so that tryCaptureVariable doesn't try
13704   // and capture any new variables. In addition when calculating potential
13705   // captures during transformation of nested lambdas, it is necessary to
13706   // have the LSI properly restored.
13707   if (isGenericLambdaCallOperatorSpecialization(FD)) {
13708     assert(inTemplateInstantiation() &&
13709            "There should be an active template instantiation on the stack "
13710            "when instantiating a generic lambda!");
13711     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
13712   } else {
13713     // Enter a new function scope
13714     PushFunctionScope();
13715   }
13716 
13717   // Builtin functions cannot be defined.
13718   if (unsigned BuiltinID = FD->getBuiltinID()) {
13719     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
13720         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
13721       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
13722       FD->setInvalidDecl();
13723     }
13724   }
13725 
13726   // The return type of a function definition must be complete
13727   // (C99 6.9.1p3, C++ [dcl.fct]p6).
13728   QualType ResultType = FD->getReturnType();
13729   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
13730       !FD->isInvalidDecl() &&
13731       RequireCompleteType(FD->getLocation(), ResultType,
13732                           diag::err_func_def_incomplete_result))
13733     FD->setInvalidDecl();
13734 
13735   if (FnBodyScope)
13736     PushDeclContext(FnBodyScope, FD);
13737 
13738   // Check the validity of our function parameters
13739   CheckParmsForFunctionDef(FD->parameters(),
13740                            /*CheckParameterNames=*/true);
13741 
13742   // Add non-parameter declarations already in the function to the current
13743   // scope.
13744   if (FnBodyScope) {
13745     for (Decl *NPD : FD->decls()) {
13746       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
13747       if (!NonParmDecl)
13748         continue;
13749       assert(!isa<ParmVarDecl>(NonParmDecl) &&
13750              "parameters should not be in newly created FD yet");
13751 
13752       // If the decl has a name, make it accessible in the current scope.
13753       if (NonParmDecl->getDeclName())
13754         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
13755 
13756       // Similarly, dive into enums and fish their constants out, making them
13757       // accessible in this scope.
13758       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
13759         for (auto *EI : ED->enumerators())
13760           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
13761       }
13762     }
13763   }
13764 
13765   // Introduce our parameters into the function scope
13766   for (auto Param : FD->parameters()) {
13767     Param->setOwningFunction(FD);
13768 
13769     // If this has an identifier, add it to the scope stack.
13770     if (Param->getIdentifier() && FnBodyScope) {
13771       CheckShadow(FnBodyScope, Param);
13772 
13773       PushOnScopeChains(Param, FnBodyScope);
13774     }
13775   }
13776 
13777   // Ensure that the function's exception specification is instantiated.
13778   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
13779     ResolveExceptionSpec(D->getLocation(), FPT);
13780 
13781   // dllimport cannot be applied to non-inline function definitions.
13782   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
13783       !FD->isTemplateInstantiation()) {
13784     assert(!FD->hasAttr<DLLExportAttr>());
13785     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
13786     FD->setInvalidDecl();
13787     return D;
13788   }
13789   // We want to attach documentation to original Decl (which might be
13790   // a function template).
13791   ActOnDocumentableDecl(D);
13792   if (getCurLexicalContext()->isObjCContainer() &&
13793       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
13794       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
13795     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
13796 
13797   return D;
13798 }
13799 
13800 /// Given the set of return statements within a function body,
13801 /// compute the variables that are subject to the named return value
13802 /// optimization.
13803 ///
13804 /// Each of the variables that is subject to the named return value
13805 /// optimization will be marked as NRVO variables in the AST, and any
13806 /// return statement that has a marked NRVO variable as its NRVO candidate can
13807 /// use the named return value optimization.
13808 ///
13809 /// This function applies a very simplistic algorithm for NRVO: if every return
13810 /// statement in the scope of a variable has the same NRVO candidate, that
13811 /// candidate is an NRVO variable.
13812 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
13813   ReturnStmt **Returns = Scope->Returns.data();
13814 
13815   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
13816     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
13817       if (!NRVOCandidate->isNRVOVariable())
13818         Returns[I]->setNRVOCandidate(nullptr);
13819     }
13820   }
13821 }
13822 
13823 bool Sema::canDelayFunctionBody(const Declarator &D) {
13824   // We can't delay parsing the body of a constexpr function template (yet).
13825   if (D.getDeclSpec().hasConstexprSpecifier())
13826     return false;
13827 
13828   // We can't delay parsing the body of a function template with a deduced
13829   // return type (yet).
13830   if (D.getDeclSpec().hasAutoTypeSpec()) {
13831     // If the placeholder introduces a non-deduced trailing return type,
13832     // we can still delay parsing it.
13833     if (D.getNumTypeObjects()) {
13834       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
13835       if (Outer.Kind == DeclaratorChunk::Function &&
13836           Outer.Fun.hasTrailingReturnType()) {
13837         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
13838         return Ty.isNull() || !Ty->isUndeducedType();
13839       }
13840     }
13841     return false;
13842   }
13843 
13844   return true;
13845 }
13846 
13847 bool Sema::canSkipFunctionBody(Decl *D) {
13848   // We cannot skip the body of a function (or function template) which is
13849   // constexpr, since we may need to evaluate its body in order to parse the
13850   // rest of the file.
13851   // We cannot skip the body of a function with an undeduced return type,
13852   // because any callers of that function need to know the type.
13853   if (const FunctionDecl *FD = D->getAsFunction()) {
13854     if (FD->isConstexpr())
13855       return false;
13856     // We can't simply call Type::isUndeducedType here, because inside template
13857     // auto can be deduced to a dependent type, which is not considered
13858     // "undeduced".
13859     if (FD->getReturnType()->getContainedDeducedType())
13860       return false;
13861   }
13862   return Consumer.shouldSkipFunctionBody(D);
13863 }
13864 
13865 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
13866   if (!Decl)
13867     return nullptr;
13868   if (FunctionDecl *FD = Decl->getAsFunction())
13869     FD->setHasSkippedBody();
13870   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
13871     MD->setHasSkippedBody();
13872   return Decl;
13873 }
13874 
13875 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
13876   return ActOnFinishFunctionBody(D, BodyArg, false);
13877 }
13878 
13879 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
13880 /// body.
13881 class ExitFunctionBodyRAII {
13882 public:
13883   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
13884   ~ExitFunctionBodyRAII() {
13885     if (!IsLambda)
13886       S.PopExpressionEvaluationContext();
13887   }
13888 
13889 private:
13890   Sema &S;
13891   bool IsLambda = false;
13892 };
13893 
13894 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
13895   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
13896 
13897   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
13898     if (EscapeInfo.count(BD))
13899       return EscapeInfo[BD];
13900 
13901     bool R = false;
13902     const BlockDecl *CurBD = BD;
13903 
13904     do {
13905       R = !CurBD->doesNotEscape();
13906       if (R)
13907         break;
13908       CurBD = CurBD->getParent()->getInnermostBlockDecl();
13909     } while (CurBD);
13910 
13911     return EscapeInfo[BD] = R;
13912   };
13913 
13914   // If the location where 'self' is implicitly retained is inside a escaping
13915   // block, emit a diagnostic.
13916   for (const std::pair<SourceLocation, const BlockDecl *> &P :
13917        S.ImplicitlyRetainedSelfLocs)
13918     if (IsOrNestedInEscapingBlock(P.second))
13919       S.Diag(P.first, diag::warn_implicitly_retains_self)
13920           << FixItHint::CreateInsertion(P.first, "self->");
13921 }
13922 
13923 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
13924                                     bool IsInstantiation) {
13925   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
13926 
13927   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13928   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
13929 
13930   if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
13931     CheckCompletedCoroutineBody(FD, Body);
13932 
13933   // Do not call PopExpressionEvaluationContext() if it is a lambda because one
13934   // is already popped when finishing the lambda in BuildLambdaExpr(). This is
13935   // meant to pop the context added in ActOnStartOfFunctionDef().
13936   ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
13937 
13938   if (FD) {
13939     FD->setBody(Body);
13940     FD->setWillHaveBody(false);
13941 
13942     if (getLangOpts().CPlusPlus14) {
13943       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
13944           FD->getReturnType()->isUndeducedType()) {
13945         // If the function has a deduced result type but contains no 'return'
13946         // statements, the result type as written must be exactly 'auto', and
13947         // the deduced result type is 'void'.
13948         if (!FD->getReturnType()->getAs<AutoType>()) {
13949           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
13950               << FD->getReturnType();
13951           FD->setInvalidDecl();
13952         } else {
13953           // Substitute 'void' for the 'auto' in the type.
13954           TypeLoc ResultType = getReturnTypeLoc(FD);
13955           Context.adjustDeducedFunctionResultType(
13956               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
13957         }
13958       }
13959     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
13960       // In C++11, we don't use 'auto' deduction rules for lambda call
13961       // operators because we don't support return type deduction.
13962       auto *LSI = getCurLambda();
13963       if (LSI->HasImplicitReturnType) {
13964         deduceClosureReturnType(*LSI);
13965 
13966         // C++11 [expr.prim.lambda]p4:
13967         //   [...] if there are no return statements in the compound-statement
13968         //   [the deduced type is] the type void
13969         QualType RetType =
13970             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
13971 
13972         // Update the return type to the deduced type.
13973         const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
13974         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
13975                                             Proto->getExtProtoInfo()));
13976       }
13977     }
13978 
13979     // If the function implicitly returns zero (like 'main') or is naked,
13980     // don't complain about missing return statements.
13981     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
13982       WP.disableCheckFallThrough();
13983 
13984     // MSVC permits the use of pure specifier (=0) on function definition,
13985     // defined at class scope, warn about this non-standard construct.
13986     if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
13987       Diag(FD->getLocation(), diag::ext_pure_function_definition);
13988 
13989     if (!FD->isInvalidDecl()) {
13990       // Don't diagnose unused parameters of defaulted or deleted functions.
13991       if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
13992         DiagnoseUnusedParameters(FD->parameters());
13993       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
13994                                              FD->getReturnType(), FD);
13995 
13996       // If this is a structor, we need a vtable.
13997       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
13998         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
13999       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
14000         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14001 
14002       // Try to apply the named return value optimization. We have to check
14003       // if we can do this here because lambdas keep return statements around
14004       // to deduce an implicit return type.
14005       if (FD->getReturnType()->isRecordType() &&
14006           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14007         computeNRVO(Body, getCurFunction());
14008     }
14009 
14010     // GNU warning -Wmissing-prototypes:
14011     //   Warn if a global function is defined without a previous
14012     //   prototype declaration. This warning is issued even if the
14013     //   definition itself provides a prototype. The aim is to detect
14014     //   global functions that fail to be declared in header files.
14015     const FunctionDecl *PossiblePrototype = nullptr;
14016     if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14017       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14018 
14019       if (PossiblePrototype) {
14020         // We found a declaration that is not a prototype,
14021         // but that could be a zero-parameter prototype
14022         if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14023           TypeLoc TL = TI->getTypeLoc();
14024           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14025             Diag(PossiblePrototype->getLocation(),
14026                  diag::note_declaration_not_a_prototype)
14027                 << (FD->getNumParams() != 0)
14028                 << (FD->getNumParams() == 0
14029                         ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
14030                         : FixItHint{});
14031         }
14032       } else {
14033         Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14034             << /* function */ 1
14035             << (FD->getStorageClass() == SC_None
14036                     ? FixItHint::CreateInsertion(FD->getTypeSpecStartLoc(),
14037                                                  "static ")
14038                     : FixItHint{});
14039       }
14040 
14041       // GNU warning -Wstrict-prototypes
14042       //   Warn if K&R function is defined without a previous declaration.
14043       //   This warning is issued only if the definition itself does not provide
14044       //   a prototype. Only K&R definitions do not provide a prototype.
14045       //   An empty list in a function declarator that is part of a definition
14046       //   of that function specifies that the function has no parameters
14047       //   (C99 6.7.5.3p14)
14048       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
14049           !LangOpts.CPlusPlus) {
14050         TypeSourceInfo *TI = FD->getTypeSourceInfo();
14051         TypeLoc TL = TI->getTypeLoc();
14052         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
14053         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14054       }
14055     }
14056 
14057     // Warn on CPUDispatch with an actual body.
14058     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14059       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14060         if (!CmpndBody->body_empty())
14061           Diag(CmpndBody->body_front()->getBeginLoc(),
14062                diag::warn_dispatch_body_ignored);
14063 
14064     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14065       const CXXMethodDecl *KeyFunction;
14066       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14067           MD->isVirtual() &&
14068           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14069           MD == KeyFunction->getCanonicalDecl()) {
14070         // Update the key-function state if necessary for this ABI.
14071         if (FD->isInlined() &&
14072             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14073           Context.setNonKeyFunction(MD);
14074 
14075           // If the newly-chosen key function is already defined, then we
14076           // need to mark the vtable as used retroactively.
14077           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14078           const FunctionDecl *Definition;
14079           if (KeyFunction && KeyFunction->isDefined(Definition))
14080             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14081         } else {
14082           // We just defined they key function; mark the vtable as used.
14083           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14084         }
14085       }
14086     }
14087 
14088     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
14089            "Function parsing confused");
14090   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14091     assert(MD == getCurMethodDecl() && "Method parsing confused");
14092     MD->setBody(Body);
14093     if (!MD->isInvalidDecl()) {
14094       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14095                                              MD->getReturnType(), MD);
14096 
14097       if (Body)
14098         computeNRVO(Body, getCurFunction());
14099     }
14100     if (getCurFunction()->ObjCShouldCallSuper) {
14101       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14102           << MD->getSelector().getAsString();
14103       getCurFunction()->ObjCShouldCallSuper = false;
14104     }
14105     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
14106       const ObjCMethodDecl *InitMethod = nullptr;
14107       bool isDesignated =
14108           MD->isDesignatedInitializerForTheInterface(&InitMethod);
14109       assert(isDesignated && InitMethod);
14110       (void)isDesignated;
14111 
14112       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14113         auto IFace = MD->getClassInterface();
14114         if (!IFace)
14115           return false;
14116         auto SuperD = IFace->getSuperClass();
14117         if (!SuperD)
14118           return false;
14119         return SuperD->getIdentifier() ==
14120             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14121       };
14122       // Don't issue this warning for unavailable inits or direct subclasses
14123       // of NSObject.
14124       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14125         Diag(MD->getLocation(),
14126              diag::warn_objc_designated_init_missing_super_call);
14127         Diag(InitMethod->getLocation(),
14128              diag::note_objc_designated_init_marked_here);
14129       }
14130       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
14131     }
14132     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
14133       // Don't issue this warning for unavaialable inits.
14134       if (!MD->isUnavailable())
14135         Diag(MD->getLocation(),
14136              diag::warn_objc_secondary_init_missing_init_call);
14137       getCurFunction()->ObjCWarnForNoInitDelegation = false;
14138     }
14139 
14140     diagnoseImplicitlyRetainedSelf(*this);
14141   } else {
14142     // Parsing the function declaration failed in some way. Pop the fake scope
14143     // we pushed on.
14144     PopFunctionScopeInfo(ActivePolicy, dcl);
14145     return nullptr;
14146   }
14147 
14148   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
14149     DiagnoseUnguardedAvailabilityViolations(dcl);
14150 
14151   assert(!getCurFunction()->ObjCShouldCallSuper &&
14152          "This should only be set for ObjC methods, which should have been "
14153          "handled in the block above.");
14154 
14155   // Verify and clean out per-function state.
14156   if (Body && (!FD || !FD->isDefaulted())) {
14157     // C++ constructors that have function-try-blocks can't have return
14158     // statements in the handlers of that block. (C++ [except.handle]p14)
14159     // Verify this.
14160     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14161       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14162 
14163     // Verify that gotos and switch cases don't jump into scopes illegally.
14164     if (getCurFunction()->NeedsScopeChecking() &&
14165         !PP.isCodeCompletionEnabled())
14166       DiagnoseInvalidJumps(Body);
14167 
14168     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14169       if (!Destructor->getParent()->isDependentType())
14170         CheckDestructor(Destructor);
14171 
14172       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14173                                              Destructor->getParent());
14174     }
14175 
14176     // If any errors have occurred, clear out any temporaries that may have
14177     // been leftover. This ensures that these temporaries won't be picked up for
14178     // deletion in some later function.
14179     if (getDiagnostics().hasErrorOccurred() ||
14180         getDiagnostics().getSuppressAllDiagnostics()) {
14181       DiscardCleanupsInEvaluationContext();
14182     }
14183     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
14184         !isa<FunctionTemplateDecl>(dcl)) {
14185       // Since the body is valid, issue any analysis-based warnings that are
14186       // enabled.
14187       ActivePolicy = &WP;
14188     }
14189 
14190     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14191         !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14192       FD->setInvalidDecl();
14193 
14194     if (FD && FD->hasAttr<NakedAttr>()) {
14195       for (const Stmt *S : Body->children()) {
14196         // Allow local register variables without initializer as they don't
14197         // require prologue.
14198         bool RegisterVariables = false;
14199         if (auto *DS = dyn_cast<DeclStmt>(S)) {
14200           for (const auto *Decl : DS->decls()) {
14201             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14202               RegisterVariables =
14203                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14204               if (!RegisterVariables)
14205                 break;
14206             }
14207           }
14208         }
14209         if (RegisterVariables)
14210           continue;
14211         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14212           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14213           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14214           FD->setInvalidDecl();
14215           break;
14216         }
14217       }
14218     }
14219 
14220     assert(ExprCleanupObjects.size() ==
14221                ExprEvalContexts.back().NumCleanupObjects &&
14222            "Leftover temporaries in function");
14223     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
14224     assert(MaybeODRUseExprs.empty() &&
14225            "Leftover expressions for odr-use checking");
14226   }
14227 
14228   if (!IsInstantiation)
14229     PopDeclContext();
14230 
14231   PopFunctionScopeInfo(ActivePolicy, dcl);
14232   // If any errors have occurred, clear out any temporaries that may have
14233   // been leftover. This ensures that these temporaries won't be picked up for
14234   // deletion in some later function.
14235   if (getDiagnostics().hasErrorOccurred()) {
14236     DiscardCleanupsInEvaluationContext();
14237   }
14238 
14239   return dcl;
14240 }
14241 
14242 /// When we finish delayed parsing of an attribute, we must attach it to the
14243 /// relevant Decl.
14244 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14245                                        ParsedAttributes &Attrs) {
14246   // Always attach attributes to the underlying decl.
14247   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14248     D = TD->getTemplatedDecl();
14249   ProcessDeclAttributeList(S, D, Attrs);
14250 
14251   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14252     if (Method->isStatic())
14253       checkThisInStaticMemberFunctionAttributes(Method);
14254 }
14255 
14256 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14257 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
14258 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14259                                           IdentifierInfo &II, Scope *S) {
14260   // Find the scope in which the identifier is injected and the corresponding
14261   // DeclContext.
14262   // FIXME: C89 does not say what happens if there is no enclosing block scope.
14263   // In that case, we inject the declaration into the translation unit scope
14264   // instead.
14265   Scope *BlockScope = S;
14266   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14267     BlockScope = BlockScope->getParent();
14268 
14269   Scope *ContextScope = BlockScope;
14270   while (!ContextScope->getEntity())
14271     ContextScope = ContextScope->getParent();
14272   ContextRAII SavedContext(*this, ContextScope->getEntity());
14273 
14274   // Before we produce a declaration for an implicitly defined
14275   // function, see whether there was a locally-scoped declaration of
14276   // this name as a function or variable. If so, use that
14277   // (non-visible) declaration, and complain about it.
14278   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14279   if (ExternCPrev) {
14280     // We still need to inject the function into the enclosing block scope so
14281     // that later (non-call) uses can see it.
14282     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14283 
14284     // C89 footnote 38:
14285     //   If in fact it is not defined as having type "function returning int",
14286     //   the behavior is undefined.
14287     if (!isa<FunctionDecl>(ExternCPrev) ||
14288         !Context.typesAreCompatible(
14289             cast<FunctionDecl>(ExternCPrev)->getType(),
14290             Context.getFunctionNoProtoType(Context.IntTy))) {
14291       Diag(Loc, diag::ext_use_out_of_scope_declaration)
14292           << ExternCPrev << !getLangOpts().C99;
14293       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14294       return ExternCPrev;
14295     }
14296   }
14297 
14298   // Extension in C99.  Legal in C90, but warn about it.
14299   unsigned diag_id;
14300   if (II.getName().startswith("__builtin_"))
14301     diag_id = diag::warn_builtin_unknown;
14302   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14303   else if (getLangOpts().OpenCL)
14304     diag_id = diag::err_opencl_implicit_function_decl;
14305   else if (getLangOpts().C99)
14306     diag_id = diag::ext_implicit_function_decl;
14307   else
14308     diag_id = diag::warn_implicit_function_decl;
14309   Diag(Loc, diag_id) << &II;
14310 
14311   // If we found a prior declaration of this function, don't bother building
14312   // another one. We've already pushed that one into scope, so there's nothing
14313   // more to do.
14314   if (ExternCPrev)
14315     return ExternCPrev;
14316 
14317   // Because typo correction is expensive, only do it if the implicit
14318   // function declaration is going to be treated as an error.
14319   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
14320     TypoCorrection Corrected;
14321     DeclFilterCCC<FunctionDecl> CCC{};
14322     if (S && (Corrected =
14323                   CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
14324                               S, nullptr, CCC, CTK_NonError)))
14325       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
14326                    /*ErrorRecovery*/false);
14327   }
14328 
14329   // Set a Declarator for the implicit definition: int foo();
14330   const char *Dummy;
14331   AttributeFactory attrFactory;
14332   DeclSpec DS(attrFactory);
14333   unsigned DiagID;
14334   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
14335                                   Context.getPrintingPolicy());
14336   (void)Error; // Silence warning.
14337   assert(!Error && "Error setting up implicit decl!");
14338   SourceLocation NoLoc;
14339   Declarator D(DS, DeclaratorContext::BlockContext);
14340   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
14341                                              /*IsAmbiguous=*/false,
14342                                              /*LParenLoc=*/NoLoc,
14343                                              /*Params=*/nullptr,
14344                                              /*NumParams=*/0,
14345                                              /*EllipsisLoc=*/NoLoc,
14346                                              /*RParenLoc=*/NoLoc,
14347                                              /*RefQualifierIsLvalueRef=*/true,
14348                                              /*RefQualifierLoc=*/NoLoc,
14349                                              /*MutableLoc=*/NoLoc, EST_None,
14350                                              /*ESpecRange=*/SourceRange(),
14351                                              /*Exceptions=*/nullptr,
14352                                              /*ExceptionRanges=*/nullptr,
14353                                              /*NumExceptions=*/0,
14354                                              /*NoexceptExpr=*/nullptr,
14355                                              /*ExceptionSpecTokens=*/nullptr,
14356                                              /*DeclsInPrototype=*/None, Loc,
14357                                              Loc, D),
14358                 std::move(DS.getAttributes()), SourceLocation());
14359   D.SetIdentifier(&II, Loc);
14360 
14361   // Insert this function into the enclosing block scope.
14362   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
14363   FD->setImplicit();
14364 
14365   AddKnownFunctionAttributes(FD);
14366 
14367   return FD;
14368 }
14369 
14370 /// Adds any function attributes that we know a priori based on
14371 /// the declaration of this function.
14372 ///
14373 /// These attributes can apply both to implicitly-declared builtins
14374 /// (like __builtin___printf_chk) or to library-declared functions
14375 /// like NSLog or printf.
14376 ///
14377 /// We need to check for duplicate attributes both here and where user-written
14378 /// attributes are applied to declarations.
14379 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
14380   if (FD->isInvalidDecl())
14381     return;
14382 
14383   // If this is a built-in function, map its builtin attributes to
14384   // actual attributes.
14385   if (unsigned BuiltinID = FD->getBuiltinID()) {
14386     // Handle printf-formatting attributes.
14387     unsigned FormatIdx;
14388     bool HasVAListArg;
14389     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
14390       if (!FD->hasAttr<FormatAttr>()) {
14391         const char *fmt = "printf";
14392         unsigned int NumParams = FD->getNumParams();
14393         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
14394             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
14395           fmt = "NSString";
14396         FD->addAttr(FormatAttr::CreateImplicit(Context,
14397                                                &Context.Idents.get(fmt),
14398                                                FormatIdx+1,
14399                                                HasVAListArg ? 0 : FormatIdx+2,
14400                                                FD->getLocation()));
14401       }
14402     }
14403     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
14404                                              HasVAListArg)) {
14405      if (!FD->hasAttr<FormatAttr>())
14406        FD->addAttr(FormatAttr::CreateImplicit(Context,
14407                                               &Context.Idents.get("scanf"),
14408                                               FormatIdx+1,
14409                                               HasVAListArg ? 0 : FormatIdx+2,
14410                                               FD->getLocation()));
14411     }
14412 
14413     // Handle automatically recognized callbacks.
14414     SmallVector<int, 4> Encoding;
14415     if (!FD->hasAttr<CallbackAttr>() &&
14416         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
14417       FD->addAttr(CallbackAttr::CreateImplicit(
14418           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
14419 
14420     // Mark const if we don't care about errno and that is the only thing
14421     // preventing the function from being const. This allows IRgen to use LLVM
14422     // intrinsics for such functions.
14423     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
14424         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
14425       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14426 
14427     // We make "fma" on some platforms const because we know it does not set
14428     // errno in those environments even though it could set errno based on the
14429     // C standard.
14430     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
14431     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
14432         !FD->hasAttr<ConstAttr>()) {
14433       switch (BuiltinID) {
14434       case Builtin::BI__builtin_fma:
14435       case Builtin::BI__builtin_fmaf:
14436       case Builtin::BI__builtin_fmal:
14437       case Builtin::BIfma:
14438       case Builtin::BIfmaf:
14439       case Builtin::BIfmal:
14440         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14441         break;
14442       default:
14443         break;
14444       }
14445     }
14446 
14447     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
14448         !FD->hasAttr<ReturnsTwiceAttr>())
14449       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
14450                                          FD->getLocation()));
14451     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
14452       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14453     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
14454       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
14455     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
14456       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14457     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
14458         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
14459       // Add the appropriate attribute, depending on the CUDA compilation mode
14460       // and which target the builtin belongs to. For example, during host
14461       // compilation, aux builtins are __device__, while the rest are __host__.
14462       if (getLangOpts().CUDAIsDevice !=
14463           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
14464         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
14465       else
14466         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
14467     }
14468   }
14469 
14470   // If C++ exceptions are enabled but we are told extern "C" functions cannot
14471   // throw, add an implicit nothrow attribute to any extern "C" function we come
14472   // across.
14473   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
14474       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
14475     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
14476     if (!FPT || FPT->getExceptionSpecType() == EST_None)
14477       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14478   }
14479 
14480   IdentifierInfo *Name = FD->getIdentifier();
14481   if (!Name)
14482     return;
14483   if ((!getLangOpts().CPlusPlus &&
14484        FD->getDeclContext()->isTranslationUnit()) ||
14485       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
14486        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
14487        LinkageSpecDecl::lang_c)) {
14488     // Okay: this could be a libc/libm/Objective-C function we know
14489     // about.
14490   } else
14491     return;
14492 
14493   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
14494     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
14495     // target-specific builtins, perhaps?
14496     if (!FD->hasAttr<FormatAttr>())
14497       FD->addAttr(FormatAttr::CreateImplicit(Context,
14498                                              &Context.Idents.get("printf"), 2,
14499                                              Name->isStr("vasprintf") ? 0 : 3,
14500                                              FD->getLocation()));
14501   }
14502 
14503   if (Name->isStr("__CFStringMakeConstantString")) {
14504     // We already have a __builtin___CFStringMakeConstantString,
14505     // but builds that use -fno-constant-cfstrings don't go through that.
14506     if (!FD->hasAttr<FormatArgAttr>())
14507       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
14508                                                 FD->getLocation()));
14509   }
14510 }
14511 
14512 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
14513                                     TypeSourceInfo *TInfo) {
14514   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
14515   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
14516 
14517   if (!TInfo) {
14518     assert(D.isInvalidType() && "no declarator info for valid type");
14519     TInfo = Context.getTrivialTypeSourceInfo(T);
14520   }
14521 
14522   // Scope manipulation handled by caller.
14523   TypedefDecl *NewTD =
14524       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
14525                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
14526 
14527   // Bail out immediately if we have an invalid declaration.
14528   if (D.isInvalidType()) {
14529     NewTD->setInvalidDecl();
14530     return NewTD;
14531   }
14532 
14533   if (D.getDeclSpec().isModulePrivateSpecified()) {
14534     if (CurContext->isFunctionOrMethod())
14535       Diag(NewTD->getLocation(), diag::err_module_private_local)
14536         << 2 << NewTD->getDeclName()
14537         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14538         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
14539     else
14540       NewTD->setModulePrivate();
14541   }
14542 
14543   // C++ [dcl.typedef]p8:
14544   //   If the typedef declaration defines an unnamed class (or
14545   //   enum), the first typedef-name declared by the declaration
14546   //   to be that class type (or enum type) is used to denote the
14547   //   class type (or enum type) for linkage purposes only.
14548   // We need to check whether the type was declared in the declaration.
14549   switch (D.getDeclSpec().getTypeSpecType()) {
14550   case TST_enum:
14551   case TST_struct:
14552   case TST_interface:
14553   case TST_union:
14554   case TST_class: {
14555     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
14556     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
14557     break;
14558   }
14559 
14560   default:
14561     break;
14562   }
14563 
14564   return NewTD;
14565 }
14566 
14567 /// Check that this is a valid underlying type for an enum declaration.
14568 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
14569   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
14570   QualType T = TI->getType();
14571 
14572   if (T->isDependentType())
14573     return false;
14574 
14575   if (const BuiltinType *BT = T->getAs<BuiltinType>())
14576     if (BT->isInteger())
14577       return false;
14578 
14579   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
14580   return true;
14581 }
14582 
14583 /// Check whether this is a valid redeclaration of a previous enumeration.
14584 /// \return true if the redeclaration was invalid.
14585 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
14586                                   QualType EnumUnderlyingTy, bool IsFixed,
14587                                   const EnumDecl *Prev) {
14588   if (IsScoped != Prev->isScoped()) {
14589     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
14590       << Prev->isScoped();
14591     Diag(Prev->getLocation(), diag::note_previous_declaration);
14592     return true;
14593   }
14594 
14595   if (IsFixed && Prev->isFixed()) {
14596     if (!EnumUnderlyingTy->isDependentType() &&
14597         !Prev->getIntegerType()->isDependentType() &&
14598         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
14599                                         Prev->getIntegerType())) {
14600       // TODO: Highlight the underlying type of the redeclaration.
14601       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
14602         << EnumUnderlyingTy << Prev->getIntegerType();
14603       Diag(Prev->getLocation(), diag::note_previous_declaration)
14604           << Prev->getIntegerTypeRange();
14605       return true;
14606     }
14607   } else if (IsFixed != Prev->isFixed()) {
14608     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
14609       << Prev->isFixed();
14610     Diag(Prev->getLocation(), diag::note_previous_declaration);
14611     return true;
14612   }
14613 
14614   return false;
14615 }
14616 
14617 /// Get diagnostic %select index for tag kind for
14618 /// redeclaration diagnostic message.
14619 /// WARNING: Indexes apply to particular diagnostics only!
14620 ///
14621 /// \returns diagnostic %select index.
14622 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
14623   switch (Tag) {
14624   case TTK_Struct: return 0;
14625   case TTK_Interface: return 1;
14626   case TTK_Class:  return 2;
14627   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
14628   }
14629 }
14630 
14631 /// Determine if tag kind is a class-key compatible with
14632 /// class for redeclaration (class, struct, or __interface).
14633 ///
14634 /// \returns true iff the tag kind is compatible.
14635 static bool isClassCompatTagKind(TagTypeKind Tag)
14636 {
14637   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
14638 }
14639 
14640 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
14641                                              TagTypeKind TTK) {
14642   if (isa<TypedefDecl>(PrevDecl))
14643     return NTK_Typedef;
14644   else if (isa<TypeAliasDecl>(PrevDecl))
14645     return NTK_TypeAlias;
14646   else if (isa<ClassTemplateDecl>(PrevDecl))
14647     return NTK_Template;
14648   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
14649     return NTK_TypeAliasTemplate;
14650   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
14651     return NTK_TemplateTemplateArgument;
14652   switch (TTK) {
14653   case TTK_Struct:
14654   case TTK_Interface:
14655   case TTK_Class:
14656     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
14657   case TTK_Union:
14658     return NTK_NonUnion;
14659   case TTK_Enum:
14660     return NTK_NonEnum;
14661   }
14662   llvm_unreachable("invalid TTK");
14663 }
14664 
14665 /// Determine whether a tag with a given kind is acceptable
14666 /// as a redeclaration of the given tag declaration.
14667 ///
14668 /// \returns true if the new tag kind is acceptable, false otherwise.
14669 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
14670                                         TagTypeKind NewTag, bool isDefinition,
14671                                         SourceLocation NewTagLoc,
14672                                         const IdentifierInfo *Name) {
14673   // C++ [dcl.type.elab]p3:
14674   //   The class-key or enum keyword present in the
14675   //   elaborated-type-specifier shall agree in kind with the
14676   //   declaration to which the name in the elaborated-type-specifier
14677   //   refers. This rule also applies to the form of
14678   //   elaborated-type-specifier that declares a class-name or
14679   //   friend class since it can be construed as referring to the
14680   //   definition of the class. Thus, in any
14681   //   elaborated-type-specifier, the enum keyword shall be used to
14682   //   refer to an enumeration (7.2), the union class-key shall be
14683   //   used to refer to a union (clause 9), and either the class or
14684   //   struct class-key shall be used to refer to a class (clause 9)
14685   //   declared using the class or struct class-key.
14686   TagTypeKind OldTag = Previous->getTagKind();
14687   if (OldTag != NewTag &&
14688       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
14689     return false;
14690 
14691   // Tags are compatible, but we might still want to warn on mismatched tags.
14692   // Non-class tags can't be mismatched at this point.
14693   if (!isClassCompatTagKind(NewTag))
14694     return true;
14695 
14696   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
14697   // by our warning analysis. We don't want to warn about mismatches with (eg)
14698   // declarations in system headers that are designed to be specialized, but if
14699   // a user asks us to warn, we should warn if their code contains mismatched
14700   // declarations.
14701   auto IsIgnoredLoc = [&](SourceLocation Loc) {
14702     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
14703                                       Loc);
14704   };
14705   if (IsIgnoredLoc(NewTagLoc))
14706     return true;
14707 
14708   auto IsIgnored = [&](const TagDecl *Tag) {
14709     return IsIgnoredLoc(Tag->getLocation());
14710   };
14711   while (IsIgnored(Previous)) {
14712     Previous = Previous->getPreviousDecl();
14713     if (!Previous)
14714       return true;
14715     OldTag = Previous->getTagKind();
14716   }
14717 
14718   bool isTemplate = false;
14719   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
14720     isTemplate = Record->getDescribedClassTemplate();
14721 
14722   if (inTemplateInstantiation()) {
14723     if (OldTag != NewTag) {
14724       // In a template instantiation, do not offer fix-its for tag mismatches
14725       // since they usually mess up the template instead of fixing the problem.
14726       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14727         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14728         << getRedeclDiagFromTagKind(OldTag);
14729       // FIXME: Note previous location?
14730     }
14731     return true;
14732   }
14733 
14734   if (isDefinition) {
14735     // On definitions, check all previous tags and issue a fix-it for each
14736     // one that doesn't match the current tag.
14737     if (Previous->getDefinition()) {
14738       // Don't suggest fix-its for redefinitions.
14739       return true;
14740     }
14741 
14742     bool previousMismatch = false;
14743     for (const TagDecl *I : Previous->redecls()) {
14744       if (I->getTagKind() != NewTag) {
14745         // Ignore previous declarations for which the warning was disabled.
14746         if (IsIgnored(I))
14747           continue;
14748 
14749         if (!previousMismatch) {
14750           previousMismatch = true;
14751           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
14752             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14753             << getRedeclDiagFromTagKind(I->getTagKind());
14754         }
14755         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
14756           << getRedeclDiagFromTagKind(NewTag)
14757           << FixItHint::CreateReplacement(I->getInnerLocStart(),
14758                TypeWithKeyword::getTagTypeKindName(NewTag));
14759       }
14760     }
14761     return true;
14762   }
14763 
14764   // Identify the prevailing tag kind: this is the kind of the definition (if
14765   // there is a non-ignored definition), or otherwise the kind of the prior
14766   // (non-ignored) declaration.
14767   const TagDecl *PrevDef = Previous->getDefinition();
14768   if (PrevDef && IsIgnored(PrevDef))
14769     PrevDef = nullptr;
14770   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
14771   if (Redecl->getTagKind() != NewTag) {
14772     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14773       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14774       << getRedeclDiagFromTagKind(OldTag);
14775     Diag(Redecl->getLocation(), diag::note_previous_use);
14776 
14777     // If there is a previous definition, suggest a fix-it.
14778     if (PrevDef) {
14779       Diag(NewTagLoc, diag::note_struct_class_suggestion)
14780         << getRedeclDiagFromTagKind(Redecl->getTagKind())
14781         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
14782              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
14783     }
14784   }
14785 
14786   return true;
14787 }
14788 
14789 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
14790 /// from an outer enclosing namespace or file scope inside a friend declaration.
14791 /// This should provide the commented out code in the following snippet:
14792 ///   namespace N {
14793 ///     struct X;
14794 ///     namespace M {
14795 ///       struct Y { friend struct /*N::*/ X; };
14796 ///     }
14797 ///   }
14798 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
14799                                          SourceLocation NameLoc) {
14800   // While the decl is in a namespace, do repeated lookup of that name and see
14801   // if we get the same namespace back.  If we do not, continue until
14802   // translation unit scope, at which point we have a fully qualified NNS.
14803   SmallVector<IdentifierInfo *, 4> Namespaces;
14804   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14805   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
14806     // This tag should be declared in a namespace, which can only be enclosed by
14807     // other namespaces.  Bail if there's an anonymous namespace in the chain.
14808     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
14809     if (!Namespace || Namespace->isAnonymousNamespace())
14810       return FixItHint();
14811     IdentifierInfo *II = Namespace->getIdentifier();
14812     Namespaces.push_back(II);
14813     NamedDecl *Lookup = SemaRef.LookupSingleName(
14814         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
14815     if (Lookup == Namespace)
14816       break;
14817   }
14818 
14819   // Once we have all the namespaces, reverse them to go outermost first, and
14820   // build an NNS.
14821   SmallString<64> Insertion;
14822   llvm::raw_svector_ostream OS(Insertion);
14823   if (DC->isTranslationUnit())
14824     OS << "::";
14825   std::reverse(Namespaces.begin(), Namespaces.end());
14826   for (auto *II : Namespaces)
14827     OS << II->getName() << "::";
14828   return FixItHint::CreateInsertion(NameLoc, Insertion);
14829 }
14830 
14831 /// Determine whether a tag originally declared in context \p OldDC can
14832 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
14833 /// found a declaration in \p OldDC as a previous decl, perhaps through a
14834 /// using-declaration).
14835 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
14836                                          DeclContext *NewDC) {
14837   OldDC = OldDC->getRedeclContext();
14838   NewDC = NewDC->getRedeclContext();
14839 
14840   if (OldDC->Equals(NewDC))
14841     return true;
14842 
14843   // In MSVC mode, we allow a redeclaration if the contexts are related (either
14844   // encloses the other).
14845   if (S.getLangOpts().MSVCCompat &&
14846       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
14847     return true;
14848 
14849   return false;
14850 }
14851 
14852 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
14853 /// former case, Name will be non-null.  In the later case, Name will be null.
14854 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
14855 /// reference/declaration/definition of a tag.
14856 ///
14857 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
14858 /// trailing-type-specifier) other than one in an alias-declaration.
14859 ///
14860 /// \param SkipBody If non-null, will be set to indicate if the caller should
14861 /// skip the definition of this tag and treat it as if it were a declaration.
14862 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
14863                      SourceLocation KWLoc, CXXScopeSpec &SS,
14864                      IdentifierInfo *Name, SourceLocation NameLoc,
14865                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
14866                      SourceLocation ModulePrivateLoc,
14867                      MultiTemplateParamsArg TemplateParameterLists,
14868                      bool &OwnedDecl, bool &IsDependent,
14869                      SourceLocation ScopedEnumKWLoc,
14870                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
14871                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
14872                      SkipBodyInfo *SkipBody) {
14873   // If this is not a definition, it must have a name.
14874   IdentifierInfo *OrigName = Name;
14875   assert((Name != nullptr || TUK == TUK_Definition) &&
14876          "Nameless record must be a definition!");
14877   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
14878 
14879   OwnedDecl = false;
14880   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14881   bool ScopedEnum = ScopedEnumKWLoc.isValid();
14882 
14883   // FIXME: Check member specializations more carefully.
14884   bool isMemberSpecialization = false;
14885   bool Invalid = false;
14886 
14887   // We only need to do this matching if we have template parameters
14888   // or a scope specifier, which also conveniently avoids this work
14889   // for non-C++ cases.
14890   if (TemplateParameterLists.size() > 0 ||
14891       (SS.isNotEmpty() && TUK != TUK_Reference)) {
14892     if (TemplateParameterList *TemplateParams =
14893             MatchTemplateParametersToScopeSpecifier(
14894                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
14895                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
14896       if (Kind == TTK_Enum) {
14897         Diag(KWLoc, diag::err_enum_template);
14898         return nullptr;
14899       }
14900 
14901       if (TemplateParams->size() > 0) {
14902         // This is a declaration or definition of a class template (which may
14903         // be a member of another template).
14904 
14905         if (Invalid)
14906           return nullptr;
14907 
14908         OwnedDecl = false;
14909         DeclResult Result = CheckClassTemplate(
14910             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
14911             AS, ModulePrivateLoc,
14912             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
14913             TemplateParameterLists.data(), SkipBody);
14914         return Result.get();
14915       } else {
14916         // The "template<>" header is extraneous.
14917         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14918           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14919         isMemberSpecialization = true;
14920       }
14921     }
14922   }
14923 
14924   // Figure out the underlying type if this a enum declaration. We need to do
14925   // this early, because it's needed to detect if this is an incompatible
14926   // redeclaration.
14927   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
14928   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
14929 
14930   if (Kind == TTK_Enum) {
14931     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
14932       // No underlying type explicitly specified, or we failed to parse the
14933       // type, default to int.
14934       EnumUnderlying = Context.IntTy.getTypePtr();
14935     } else if (UnderlyingType.get()) {
14936       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
14937       // integral type; any cv-qualification is ignored.
14938       TypeSourceInfo *TI = nullptr;
14939       GetTypeFromParser(UnderlyingType.get(), &TI);
14940       EnumUnderlying = TI;
14941 
14942       if (CheckEnumUnderlyingType(TI))
14943         // Recover by falling back to int.
14944         EnumUnderlying = Context.IntTy.getTypePtr();
14945 
14946       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
14947                                           UPPC_FixedUnderlyingType))
14948         EnumUnderlying = Context.IntTy.getTypePtr();
14949 
14950     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
14951       // For MSVC ABI compatibility, unfixed enums must use an underlying type
14952       // of 'int'. However, if this is an unfixed forward declaration, don't set
14953       // the underlying type unless the user enables -fms-compatibility. This
14954       // makes unfixed forward declared enums incomplete and is more conforming.
14955       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
14956         EnumUnderlying = Context.IntTy.getTypePtr();
14957     }
14958   }
14959 
14960   DeclContext *SearchDC = CurContext;
14961   DeclContext *DC = CurContext;
14962   bool isStdBadAlloc = false;
14963   bool isStdAlignValT = false;
14964 
14965   RedeclarationKind Redecl = forRedeclarationInCurContext();
14966   if (TUK == TUK_Friend || TUK == TUK_Reference)
14967     Redecl = NotForRedeclaration;
14968 
14969   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
14970   /// implemented asks for structural equivalence checking, the returned decl
14971   /// here is passed back to the parser, allowing the tag body to be parsed.
14972   auto createTagFromNewDecl = [&]() -> TagDecl * {
14973     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
14974     // If there is an identifier, use the location of the identifier as the
14975     // location of the decl, otherwise use the location of the struct/union
14976     // keyword.
14977     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14978     TagDecl *New = nullptr;
14979 
14980     if (Kind == TTK_Enum) {
14981       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
14982                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
14983       // If this is an undefined enum, bail.
14984       if (TUK != TUK_Definition && !Invalid)
14985         return nullptr;
14986       if (EnumUnderlying) {
14987         EnumDecl *ED = cast<EnumDecl>(New);
14988         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
14989           ED->setIntegerTypeSourceInfo(TI);
14990         else
14991           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
14992         ED->setPromotionType(ED->getIntegerType());
14993       }
14994     } else { // struct/union
14995       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14996                                nullptr);
14997     }
14998 
14999     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15000       // Add alignment attributes if necessary; these attributes are checked
15001       // when the ASTContext lays out the structure.
15002       //
15003       // It is important for implementing the correct semantics that this
15004       // happen here (in ActOnTag). The #pragma pack stack is
15005       // maintained as a result of parser callbacks which can occur at
15006       // many points during the parsing of a struct declaration (because
15007       // the #pragma tokens are effectively skipped over during the
15008       // parsing of the struct).
15009       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15010         AddAlignmentAttributesForRecord(RD);
15011         AddMsStructLayoutForRecord(RD);
15012       }
15013     }
15014     New->setLexicalDeclContext(CurContext);
15015     return New;
15016   };
15017 
15018   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
15019   if (Name && SS.isNotEmpty()) {
15020     // We have a nested-name tag ('struct foo::bar').
15021 
15022     // Check for invalid 'foo::'.
15023     if (SS.isInvalid()) {
15024       Name = nullptr;
15025       goto CreateNewDecl;
15026     }
15027 
15028     // If this is a friend or a reference to a class in a dependent
15029     // context, don't try to make a decl for it.
15030     if (TUK == TUK_Friend || TUK == TUK_Reference) {
15031       DC = computeDeclContext(SS, false);
15032       if (!DC) {
15033         IsDependent = true;
15034         return nullptr;
15035       }
15036     } else {
15037       DC = computeDeclContext(SS, true);
15038       if (!DC) {
15039         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
15040           << SS.getRange();
15041         return nullptr;
15042       }
15043     }
15044 
15045     if (RequireCompleteDeclContext(SS, DC))
15046       return nullptr;
15047 
15048     SearchDC = DC;
15049     // Look-up name inside 'foo::'.
15050     LookupQualifiedName(Previous, DC);
15051 
15052     if (Previous.isAmbiguous())
15053       return nullptr;
15054 
15055     if (Previous.empty()) {
15056       // Name lookup did not find anything. However, if the
15057       // nested-name-specifier refers to the current instantiation,
15058       // and that current instantiation has any dependent base
15059       // classes, we might find something at instantiation time: treat
15060       // this as a dependent elaborated-type-specifier.
15061       // But this only makes any sense for reference-like lookups.
15062       if (Previous.wasNotFoundInCurrentInstantiation() &&
15063           (TUK == TUK_Reference || TUK == TUK_Friend)) {
15064         IsDependent = true;
15065         return nullptr;
15066       }
15067 
15068       // A tag 'foo::bar' must already exist.
15069       Diag(NameLoc, diag::err_not_tag_in_scope)
15070         << Kind << Name << DC << SS.getRange();
15071       Name = nullptr;
15072       Invalid = true;
15073       goto CreateNewDecl;
15074     }
15075   } else if (Name) {
15076     // C++14 [class.mem]p14:
15077     //   If T is the name of a class, then each of the following shall have a
15078     //   name different from T:
15079     //    -- every member of class T that is itself a type
15080     if (TUK != TUK_Reference && TUK != TUK_Friend &&
15081         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15082       return nullptr;
15083 
15084     // If this is a named struct, check to see if there was a previous forward
15085     // declaration or definition.
15086     // FIXME: We're looking into outer scopes here, even when we
15087     // shouldn't be. Doing so can result in ambiguities that we
15088     // shouldn't be diagnosing.
15089     LookupName(Previous, S);
15090 
15091     // When declaring or defining a tag, ignore ambiguities introduced
15092     // by types using'ed into this scope.
15093     if (Previous.isAmbiguous() &&
15094         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
15095       LookupResult::Filter F = Previous.makeFilter();
15096       while (F.hasNext()) {
15097         NamedDecl *ND = F.next();
15098         if (!ND->getDeclContext()->getRedeclContext()->Equals(
15099                 SearchDC->getRedeclContext()))
15100           F.erase();
15101       }
15102       F.done();
15103     }
15104 
15105     // C++11 [namespace.memdef]p3:
15106     //   If the name in a friend declaration is neither qualified nor
15107     //   a template-id and the declaration is a function or an
15108     //   elaborated-type-specifier, the lookup to determine whether
15109     //   the entity has been previously declared shall not consider
15110     //   any scopes outside the innermost enclosing namespace.
15111     //
15112     // MSVC doesn't implement the above rule for types, so a friend tag
15113     // declaration may be a redeclaration of a type declared in an enclosing
15114     // scope.  They do implement this rule for friend functions.
15115     //
15116     // Does it matter that this should be by scope instead of by
15117     // semantic context?
15118     if (!Previous.empty() && TUK == TUK_Friend) {
15119       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
15120       LookupResult::Filter F = Previous.makeFilter();
15121       bool FriendSawTagOutsideEnclosingNamespace = false;
15122       while (F.hasNext()) {
15123         NamedDecl *ND = F.next();
15124         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15125         if (DC->isFileContext() &&
15126             !EnclosingNS->Encloses(ND->getDeclContext())) {
15127           if (getLangOpts().MSVCCompat)
15128             FriendSawTagOutsideEnclosingNamespace = true;
15129           else
15130             F.erase();
15131         }
15132       }
15133       F.done();
15134 
15135       // Diagnose this MSVC extension in the easy case where lookup would have
15136       // unambiguously found something outside the enclosing namespace.
15137       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
15138         NamedDecl *ND = Previous.getFoundDecl();
15139         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
15140             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
15141       }
15142     }
15143 
15144     // Note:  there used to be some attempt at recovery here.
15145     if (Previous.isAmbiguous())
15146       return nullptr;
15147 
15148     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
15149       // FIXME: This makes sure that we ignore the contexts associated
15150       // with C structs, unions, and enums when looking for a matching
15151       // tag declaration or definition. See the similar lookup tweak
15152       // in Sema::LookupName; is there a better way to deal with this?
15153       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
15154         SearchDC = SearchDC->getParent();
15155     }
15156   }
15157 
15158   if (Previous.isSingleResult() &&
15159       Previous.getFoundDecl()->isTemplateParameter()) {
15160     // Maybe we will complain about the shadowed template parameter.
15161     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
15162     // Just pretend that we didn't see the previous declaration.
15163     Previous.clear();
15164   }
15165 
15166   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
15167       DC->Equals(getStdNamespace())) {
15168     if (Name->isStr("bad_alloc")) {
15169       // This is a declaration of or a reference to "std::bad_alloc".
15170       isStdBadAlloc = true;
15171 
15172       // If std::bad_alloc has been implicitly declared (but made invisible to
15173       // name lookup), fill in this implicit declaration as the previous
15174       // declaration, so that the declarations get chained appropriately.
15175       if (Previous.empty() && StdBadAlloc)
15176         Previous.addDecl(getStdBadAlloc());
15177     } else if (Name->isStr("align_val_t")) {
15178       isStdAlignValT = true;
15179       if (Previous.empty() && StdAlignValT)
15180         Previous.addDecl(getStdAlignValT());
15181     }
15182   }
15183 
15184   // If we didn't find a previous declaration, and this is a reference
15185   // (or friend reference), move to the correct scope.  In C++, we
15186   // also need to do a redeclaration lookup there, just in case
15187   // there's a shadow friend decl.
15188   if (Name && Previous.empty() &&
15189       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
15190     if (Invalid) goto CreateNewDecl;
15191     assert(SS.isEmpty());
15192 
15193     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
15194       // C++ [basic.scope.pdecl]p5:
15195       //   -- for an elaborated-type-specifier of the form
15196       //
15197       //          class-key identifier
15198       //
15199       //      if the elaborated-type-specifier is used in the
15200       //      decl-specifier-seq or parameter-declaration-clause of a
15201       //      function defined in namespace scope, the identifier is
15202       //      declared as a class-name in the namespace that contains
15203       //      the declaration; otherwise, except as a friend
15204       //      declaration, the identifier is declared in the smallest
15205       //      non-class, non-function-prototype scope that contains the
15206       //      declaration.
15207       //
15208       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
15209       // C structs and unions.
15210       //
15211       // It is an error in C++ to declare (rather than define) an enum
15212       // type, including via an elaborated type specifier.  We'll
15213       // diagnose that later; for now, declare the enum in the same
15214       // scope as we would have picked for any other tag type.
15215       //
15216       // GNU C also supports this behavior as part of its incomplete
15217       // enum types extension, while GNU C++ does not.
15218       //
15219       // Find the context where we'll be declaring the tag.
15220       // FIXME: We would like to maintain the current DeclContext as the
15221       // lexical context,
15222       SearchDC = getTagInjectionContext(SearchDC);
15223 
15224       // Find the scope where we'll be declaring the tag.
15225       S = getTagInjectionScope(S, getLangOpts());
15226     } else {
15227       assert(TUK == TUK_Friend);
15228       // C++ [namespace.memdef]p3:
15229       //   If a friend declaration in a non-local class first declares a
15230       //   class or function, the friend class or function is a member of
15231       //   the innermost enclosing namespace.
15232       SearchDC = SearchDC->getEnclosingNamespaceContext();
15233     }
15234 
15235     // In C++, we need to do a redeclaration lookup to properly
15236     // diagnose some problems.
15237     // FIXME: redeclaration lookup is also used (with and without C++) to find a
15238     // hidden declaration so that we don't get ambiguity errors when using a
15239     // type declared by an elaborated-type-specifier.  In C that is not correct
15240     // and we should instead merge compatible types found by lookup.
15241     if (getLangOpts().CPlusPlus) {
15242       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15243       LookupQualifiedName(Previous, SearchDC);
15244     } else {
15245       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15246       LookupName(Previous, S);
15247     }
15248   }
15249 
15250   // If we have a known previous declaration to use, then use it.
15251   if (Previous.empty() && SkipBody && SkipBody->Previous)
15252     Previous.addDecl(SkipBody->Previous);
15253 
15254   if (!Previous.empty()) {
15255     NamedDecl *PrevDecl = Previous.getFoundDecl();
15256     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
15257 
15258     // It's okay to have a tag decl in the same scope as a typedef
15259     // which hides a tag decl in the same scope.  Finding this
15260     // insanity with a redeclaration lookup can only actually happen
15261     // in C++.
15262     //
15263     // This is also okay for elaborated-type-specifiers, which is
15264     // technically forbidden by the current standard but which is
15265     // okay according to the likely resolution of an open issue;
15266     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
15267     if (getLangOpts().CPlusPlus) {
15268       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15269         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
15270           TagDecl *Tag = TT->getDecl();
15271           if (Tag->getDeclName() == Name &&
15272               Tag->getDeclContext()->getRedeclContext()
15273                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
15274             PrevDecl = Tag;
15275             Previous.clear();
15276             Previous.addDecl(Tag);
15277             Previous.resolveKind();
15278           }
15279         }
15280       }
15281     }
15282 
15283     // If this is a redeclaration of a using shadow declaration, it must
15284     // declare a tag in the same context. In MSVC mode, we allow a
15285     // redefinition if either context is within the other.
15286     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
15287       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
15288       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
15289           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
15290           !(OldTag && isAcceptableTagRedeclContext(
15291                           *this, OldTag->getDeclContext(), SearchDC))) {
15292         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
15293         Diag(Shadow->getTargetDecl()->getLocation(),
15294              diag::note_using_decl_target);
15295         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
15296             << 0;
15297         // Recover by ignoring the old declaration.
15298         Previous.clear();
15299         goto CreateNewDecl;
15300       }
15301     }
15302 
15303     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
15304       // If this is a use of a previous tag, or if the tag is already declared
15305       // in the same scope (so that the definition/declaration completes or
15306       // rementions the tag), reuse the decl.
15307       if (TUK == TUK_Reference || TUK == TUK_Friend ||
15308           isDeclInScope(DirectPrevDecl, SearchDC, S,
15309                         SS.isNotEmpty() || isMemberSpecialization)) {
15310         // Make sure that this wasn't declared as an enum and now used as a
15311         // struct or something similar.
15312         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
15313                                           TUK == TUK_Definition, KWLoc,
15314                                           Name)) {
15315           bool SafeToContinue
15316             = (PrevTagDecl->getTagKind() != TTK_Enum &&
15317                Kind != TTK_Enum);
15318           if (SafeToContinue)
15319             Diag(KWLoc, diag::err_use_with_wrong_tag)
15320               << Name
15321               << FixItHint::CreateReplacement(SourceRange(KWLoc),
15322                                               PrevTagDecl->getKindName());
15323           else
15324             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
15325           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
15326 
15327           if (SafeToContinue)
15328             Kind = PrevTagDecl->getTagKind();
15329           else {
15330             // Recover by making this an anonymous redefinition.
15331             Name = nullptr;
15332             Previous.clear();
15333             Invalid = true;
15334           }
15335         }
15336 
15337         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
15338           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
15339 
15340           // If this is an elaborated-type-specifier for a scoped enumeration,
15341           // the 'class' keyword is not necessary and not permitted.
15342           if (TUK == TUK_Reference || TUK == TUK_Friend) {
15343             if (ScopedEnum)
15344               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
15345                 << PrevEnum->isScoped()
15346                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
15347             return PrevTagDecl;
15348           }
15349 
15350           QualType EnumUnderlyingTy;
15351           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15352             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
15353           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
15354             EnumUnderlyingTy = QualType(T, 0);
15355 
15356           // All conflicts with previous declarations are recovered by
15357           // returning the previous declaration, unless this is a definition,
15358           // in which case we want the caller to bail out.
15359           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
15360                                      ScopedEnum, EnumUnderlyingTy,
15361                                      IsFixed, PrevEnum))
15362             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
15363         }
15364 
15365         // C++11 [class.mem]p1:
15366         //   A member shall not be declared twice in the member-specification,
15367         //   except that a nested class or member class template can be declared
15368         //   and then later defined.
15369         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
15370             S->isDeclScope(PrevDecl)) {
15371           Diag(NameLoc, diag::ext_member_redeclared);
15372           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
15373         }
15374 
15375         if (!Invalid) {
15376           // If this is a use, just return the declaration we found, unless
15377           // we have attributes.
15378           if (TUK == TUK_Reference || TUK == TUK_Friend) {
15379             if (!Attrs.empty()) {
15380               // FIXME: Diagnose these attributes. For now, we create a new
15381               // declaration to hold them.
15382             } else if (TUK == TUK_Reference &&
15383                        (PrevTagDecl->getFriendObjectKind() ==
15384                             Decl::FOK_Undeclared ||
15385                         PrevDecl->getOwningModule() != getCurrentModule()) &&
15386                        SS.isEmpty()) {
15387               // This declaration is a reference to an existing entity, but
15388               // has different visibility from that entity: it either makes
15389               // a friend visible or it makes a type visible in a new module.
15390               // In either case, create a new declaration. We only do this if
15391               // the declaration would have meant the same thing if no prior
15392               // declaration were found, that is, if it was found in the same
15393               // scope where we would have injected a declaration.
15394               if (!getTagInjectionContext(CurContext)->getRedeclContext()
15395                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
15396                 return PrevTagDecl;
15397               // This is in the injected scope, create a new declaration in
15398               // that scope.
15399               S = getTagInjectionScope(S, getLangOpts());
15400             } else {
15401               return PrevTagDecl;
15402             }
15403           }
15404 
15405           // Diagnose attempts to redefine a tag.
15406           if (TUK == TUK_Definition) {
15407             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
15408               // If we're defining a specialization and the previous definition
15409               // is from an implicit instantiation, don't emit an error
15410               // here; we'll catch this in the general case below.
15411               bool IsExplicitSpecializationAfterInstantiation = false;
15412               if (isMemberSpecialization) {
15413                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
15414                   IsExplicitSpecializationAfterInstantiation =
15415                     RD->getTemplateSpecializationKind() !=
15416                     TSK_ExplicitSpecialization;
15417                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
15418                   IsExplicitSpecializationAfterInstantiation =
15419                     ED->getTemplateSpecializationKind() !=
15420                     TSK_ExplicitSpecialization;
15421               }
15422 
15423               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
15424               // not keep more that one definition around (merge them). However,
15425               // ensure the decl passes the structural compatibility check in
15426               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
15427               NamedDecl *Hidden = nullptr;
15428               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
15429                 // There is a definition of this tag, but it is not visible. We
15430                 // explicitly make use of C++'s one definition rule here, and
15431                 // assume that this definition is identical to the hidden one
15432                 // we already have. Make the existing definition visible and
15433                 // use it in place of this one.
15434                 if (!getLangOpts().CPlusPlus) {
15435                   // Postpone making the old definition visible until after we
15436                   // complete parsing the new one and do the structural
15437                   // comparison.
15438                   SkipBody->CheckSameAsPrevious = true;
15439                   SkipBody->New = createTagFromNewDecl();
15440                   SkipBody->Previous = Def;
15441                   return Def;
15442                 } else {
15443                   SkipBody->ShouldSkip = true;
15444                   SkipBody->Previous = Def;
15445                   makeMergedDefinitionVisible(Hidden);
15446                   // Carry on and handle it like a normal definition. We'll
15447                   // skip starting the definitiion later.
15448                 }
15449               } else if (!IsExplicitSpecializationAfterInstantiation) {
15450                 // A redeclaration in function prototype scope in C isn't
15451                 // visible elsewhere, so merely issue a warning.
15452                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
15453                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
15454                 else
15455                   Diag(NameLoc, diag::err_redefinition) << Name;
15456                 notePreviousDefinition(Def,
15457                                        NameLoc.isValid() ? NameLoc : KWLoc);
15458                 // If this is a redefinition, recover by making this
15459                 // struct be anonymous, which will make any later
15460                 // references get the previous definition.
15461                 Name = nullptr;
15462                 Previous.clear();
15463                 Invalid = true;
15464               }
15465             } else {
15466               // If the type is currently being defined, complain
15467               // about a nested redefinition.
15468               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
15469               if (TD->isBeingDefined()) {
15470                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
15471                 Diag(PrevTagDecl->getLocation(),
15472                      diag::note_previous_definition);
15473                 Name = nullptr;
15474                 Previous.clear();
15475                 Invalid = true;
15476               }
15477             }
15478 
15479             // Okay, this is definition of a previously declared or referenced
15480             // tag. We're going to create a new Decl for it.
15481           }
15482 
15483           // Okay, we're going to make a redeclaration.  If this is some kind
15484           // of reference, make sure we build the redeclaration in the same DC
15485           // as the original, and ignore the current access specifier.
15486           if (TUK == TUK_Friend || TUK == TUK_Reference) {
15487             SearchDC = PrevTagDecl->getDeclContext();
15488             AS = AS_none;
15489           }
15490         }
15491         // If we get here we have (another) forward declaration or we
15492         // have a definition.  Just create a new decl.
15493 
15494       } else {
15495         // If we get here, this is a definition of a new tag type in a nested
15496         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
15497         // new decl/type.  We set PrevDecl to NULL so that the entities
15498         // have distinct types.
15499         Previous.clear();
15500       }
15501       // If we get here, we're going to create a new Decl. If PrevDecl
15502       // is non-NULL, it's a definition of the tag declared by
15503       // PrevDecl. If it's NULL, we have a new definition.
15504 
15505     // Otherwise, PrevDecl is not a tag, but was found with tag
15506     // lookup.  This is only actually possible in C++, where a few
15507     // things like templates still live in the tag namespace.
15508     } else {
15509       // Use a better diagnostic if an elaborated-type-specifier
15510       // found the wrong kind of type on the first
15511       // (non-redeclaration) lookup.
15512       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
15513           !Previous.isForRedeclaration()) {
15514         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15515         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
15516                                                        << Kind;
15517         Diag(PrevDecl->getLocation(), diag::note_declared_at);
15518         Invalid = true;
15519 
15520       // Otherwise, only diagnose if the declaration is in scope.
15521       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
15522                                 SS.isNotEmpty() || isMemberSpecialization)) {
15523         // do nothing
15524 
15525       // Diagnose implicit declarations introduced by elaborated types.
15526       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
15527         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15528         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
15529         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15530         Invalid = true;
15531 
15532       // Otherwise it's a declaration.  Call out a particularly common
15533       // case here.
15534       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15535         unsigned Kind = 0;
15536         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
15537         Diag(NameLoc, diag::err_tag_definition_of_typedef)
15538           << Name << Kind << TND->getUnderlyingType();
15539         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15540         Invalid = true;
15541 
15542       // Otherwise, diagnose.
15543       } else {
15544         // The tag name clashes with something else in the target scope,
15545         // issue an error and recover by making this tag be anonymous.
15546         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
15547         notePreviousDefinition(PrevDecl, NameLoc);
15548         Name = nullptr;
15549         Invalid = true;
15550       }
15551 
15552       // The existing declaration isn't relevant to us; we're in a
15553       // new scope, so clear out the previous declaration.
15554       Previous.clear();
15555     }
15556   }
15557 
15558 CreateNewDecl:
15559 
15560   TagDecl *PrevDecl = nullptr;
15561   if (Previous.isSingleResult())
15562     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
15563 
15564   // If there is an identifier, use the location of the identifier as the
15565   // location of the decl, otherwise use the location of the struct/union
15566   // keyword.
15567   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15568 
15569   // Otherwise, create a new declaration. If there is a previous
15570   // declaration of the same entity, the two will be linked via
15571   // PrevDecl.
15572   TagDecl *New;
15573 
15574   if (Kind == TTK_Enum) {
15575     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15576     // enum X { A, B, C } D;    D should chain to X.
15577     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
15578                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
15579                            ScopedEnumUsesClassTag, IsFixed);
15580 
15581     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
15582       StdAlignValT = cast<EnumDecl>(New);
15583 
15584     // If this is an undefined enum, warn.
15585     if (TUK != TUK_Definition && !Invalid) {
15586       TagDecl *Def;
15587       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
15588         // C++0x: 7.2p2: opaque-enum-declaration.
15589         // Conflicts are diagnosed above. Do nothing.
15590       }
15591       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
15592         Diag(Loc, diag::ext_forward_ref_enum_def)
15593           << New;
15594         Diag(Def->getLocation(), diag::note_previous_definition);
15595       } else {
15596         unsigned DiagID = diag::ext_forward_ref_enum;
15597         if (getLangOpts().MSVCCompat)
15598           DiagID = diag::ext_ms_forward_ref_enum;
15599         else if (getLangOpts().CPlusPlus)
15600           DiagID = diag::err_forward_ref_enum;
15601         Diag(Loc, DiagID);
15602       }
15603     }
15604 
15605     if (EnumUnderlying) {
15606       EnumDecl *ED = cast<EnumDecl>(New);
15607       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15608         ED->setIntegerTypeSourceInfo(TI);
15609       else
15610         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
15611       ED->setPromotionType(ED->getIntegerType());
15612       assert(ED->isComplete() && "enum with type should be complete");
15613     }
15614   } else {
15615     // struct/union/class
15616 
15617     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15618     // struct X { int A; } D;    D should chain to X.
15619     if (getLangOpts().CPlusPlus) {
15620       // FIXME: Look for a way to use RecordDecl for simple structs.
15621       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15622                                   cast_or_null<CXXRecordDecl>(PrevDecl));
15623 
15624       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
15625         StdBadAlloc = cast<CXXRecordDecl>(New);
15626     } else
15627       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15628                                cast_or_null<RecordDecl>(PrevDecl));
15629   }
15630 
15631   // C++11 [dcl.type]p3:
15632   //   A type-specifier-seq shall not define a class or enumeration [...].
15633   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
15634       TUK == TUK_Definition) {
15635     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
15636       << Context.getTagDeclType(New);
15637     Invalid = true;
15638   }
15639 
15640   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
15641       DC->getDeclKind() == Decl::Enum) {
15642     Diag(New->getLocation(), diag::err_type_defined_in_enum)
15643       << Context.getTagDeclType(New);
15644     Invalid = true;
15645   }
15646 
15647   // Maybe add qualifier info.
15648   if (SS.isNotEmpty()) {
15649     if (SS.isSet()) {
15650       // If this is either a declaration or a definition, check the
15651       // nested-name-specifier against the current context.
15652       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
15653           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
15654                                        isMemberSpecialization))
15655         Invalid = true;
15656 
15657       New->setQualifierInfo(SS.getWithLocInContext(Context));
15658       if (TemplateParameterLists.size() > 0) {
15659         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
15660       }
15661     }
15662     else
15663       Invalid = true;
15664   }
15665 
15666   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15667     // Add alignment attributes if necessary; these attributes are checked when
15668     // the ASTContext lays out the structure.
15669     //
15670     // It is important for implementing the correct semantics that this
15671     // happen here (in ActOnTag). The #pragma pack stack is
15672     // maintained as a result of parser callbacks which can occur at
15673     // many points during the parsing of a struct declaration (because
15674     // the #pragma tokens are effectively skipped over during the
15675     // parsing of the struct).
15676     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15677       AddAlignmentAttributesForRecord(RD);
15678       AddMsStructLayoutForRecord(RD);
15679     }
15680   }
15681 
15682   if (ModulePrivateLoc.isValid()) {
15683     if (isMemberSpecialization)
15684       Diag(New->getLocation(), diag::err_module_private_specialization)
15685         << 2
15686         << FixItHint::CreateRemoval(ModulePrivateLoc);
15687     // __module_private__ does not apply to local classes. However, we only
15688     // diagnose this as an error when the declaration specifiers are
15689     // freestanding. Here, we just ignore the __module_private__.
15690     else if (!SearchDC->isFunctionOrMethod())
15691       New->setModulePrivate();
15692   }
15693 
15694   // If this is a specialization of a member class (of a class template),
15695   // check the specialization.
15696   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
15697     Invalid = true;
15698 
15699   // If we're declaring or defining a tag in function prototype scope in C,
15700   // note that this type can only be used within the function and add it to
15701   // the list of decls to inject into the function definition scope.
15702   if ((Name || Kind == TTK_Enum) &&
15703       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
15704     if (getLangOpts().CPlusPlus) {
15705       // C++ [dcl.fct]p6:
15706       //   Types shall not be defined in return or parameter types.
15707       if (TUK == TUK_Definition && !IsTypeSpecifier) {
15708         Diag(Loc, diag::err_type_defined_in_param_type)
15709             << Name;
15710         Invalid = true;
15711       }
15712     } else if (!PrevDecl) {
15713       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
15714     }
15715   }
15716 
15717   if (Invalid)
15718     New->setInvalidDecl();
15719 
15720   // Set the lexical context. If the tag has a C++ scope specifier, the
15721   // lexical context will be different from the semantic context.
15722   New->setLexicalDeclContext(CurContext);
15723 
15724   // Mark this as a friend decl if applicable.
15725   // In Microsoft mode, a friend declaration also acts as a forward
15726   // declaration so we always pass true to setObjectOfFriendDecl to make
15727   // the tag name visible.
15728   if (TUK == TUK_Friend)
15729     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
15730 
15731   // Set the access specifier.
15732   if (!Invalid && SearchDC->isRecord())
15733     SetMemberAccessSpecifier(New, PrevDecl, AS);
15734 
15735   if (PrevDecl)
15736     CheckRedeclarationModuleOwnership(New, PrevDecl);
15737 
15738   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
15739     New->startDefinition();
15740 
15741   ProcessDeclAttributeList(S, New, Attrs);
15742   AddPragmaAttributes(S, New);
15743 
15744   // If this has an identifier, add it to the scope stack.
15745   if (TUK == TUK_Friend) {
15746     // We might be replacing an existing declaration in the lookup tables;
15747     // if so, borrow its access specifier.
15748     if (PrevDecl)
15749       New->setAccess(PrevDecl->getAccess());
15750 
15751     DeclContext *DC = New->getDeclContext()->getRedeclContext();
15752     DC->makeDeclVisibleInContext(New);
15753     if (Name) // can be null along some error paths
15754       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
15755         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
15756   } else if (Name) {
15757     S = getNonFieldDeclScope(S);
15758     PushOnScopeChains(New, S, true);
15759   } else {
15760     CurContext->addDecl(New);
15761   }
15762 
15763   // If this is the C FILE type, notify the AST context.
15764   if (IdentifierInfo *II = New->getIdentifier())
15765     if (!New->isInvalidDecl() &&
15766         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
15767         II->isStr("FILE"))
15768       Context.setFILEDecl(New);
15769 
15770   if (PrevDecl)
15771     mergeDeclAttributes(New, PrevDecl);
15772 
15773   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
15774     inferGslOwnerPointerAttribute(CXXRD);
15775 
15776   // If there's a #pragma GCC visibility in scope, set the visibility of this
15777   // record.
15778   AddPushedVisibilityAttribute(New);
15779 
15780   if (isMemberSpecialization && !New->isInvalidDecl())
15781     CompleteMemberSpecialization(New, Previous);
15782 
15783   OwnedDecl = true;
15784   // In C++, don't return an invalid declaration. We can't recover well from
15785   // the cases where we make the type anonymous.
15786   if (Invalid && getLangOpts().CPlusPlus) {
15787     if (New->isBeingDefined())
15788       if (auto RD = dyn_cast<RecordDecl>(New))
15789         RD->completeDefinition();
15790     return nullptr;
15791   } else if (SkipBody && SkipBody->ShouldSkip) {
15792     return SkipBody->Previous;
15793   } else {
15794     return New;
15795   }
15796 }
15797 
15798 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
15799   AdjustDeclIfTemplate(TagD);
15800   TagDecl *Tag = cast<TagDecl>(TagD);
15801 
15802   // Enter the tag context.
15803   PushDeclContext(S, Tag);
15804 
15805   ActOnDocumentableDecl(TagD);
15806 
15807   // If there's a #pragma GCC visibility in scope, set the visibility of this
15808   // record.
15809   AddPushedVisibilityAttribute(Tag);
15810 }
15811 
15812 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
15813                                     SkipBodyInfo &SkipBody) {
15814   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
15815     return false;
15816 
15817   // Make the previous decl visible.
15818   makeMergedDefinitionVisible(SkipBody.Previous);
15819   return true;
15820 }
15821 
15822 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
15823   assert(isa<ObjCContainerDecl>(IDecl) &&
15824          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
15825   DeclContext *OCD = cast<DeclContext>(IDecl);
15826   assert(getContainingDC(OCD) == CurContext &&
15827       "The next DeclContext should be lexically contained in the current one.");
15828   CurContext = OCD;
15829   return IDecl;
15830 }
15831 
15832 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
15833                                            SourceLocation FinalLoc,
15834                                            bool IsFinalSpelledSealed,
15835                                            SourceLocation LBraceLoc) {
15836   AdjustDeclIfTemplate(TagD);
15837   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
15838 
15839   FieldCollector->StartClass();
15840 
15841   if (!Record->getIdentifier())
15842     return;
15843 
15844   if (FinalLoc.isValid())
15845     Record->addAttr(FinalAttr::Create(
15846         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
15847         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
15848 
15849   // C++ [class]p2:
15850   //   [...] The class-name is also inserted into the scope of the
15851   //   class itself; this is known as the injected-class-name. For
15852   //   purposes of access checking, the injected-class-name is treated
15853   //   as if it were a public member name.
15854   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
15855       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
15856       Record->getLocation(), Record->getIdentifier(),
15857       /*PrevDecl=*/nullptr,
15858       /*DelayTypeCreation=*/true);
15859   Context.getTypeDeclType(InjectedClassName, Record);
15860   InjectedClassName->setImplicit();
15861   InjectedClassName->setAccess(AS_public);
15862   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
15863       InjectedClassName->setDescribedClassTemplate(Template);
15864   PushOnScopeChains(InjectedClassName, S);
15865   assert(InjectedClassName->isInjectedClassName() &&
15866          "Broken injected-class-name");
15867 }
15868 
15869 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
15870                                     SourceRange BraceRange) {
15871   AdjustDeclIfTemplate(TagD);
15872   TagDecl *Tag = cast<TagDecl>(TagD);
15873   Tag->setBraceRange(BraceRange);
15874 
15875   // Make sure we "complete" the definition even it is invalid.
15876   if (Tag->isBeingDefined()) {
15877     assert(Tag->isInvalidDecl() && "We should already have completed it");
15878     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15879       RD->completeDefinition();
15880   }
15881 
15882   if (isa<CXXRecordDecl>(Tag)) {
15883     FieldCollector->FinishClass();
15884   }
15885 
15886   // Exit this scope of this tag's definition.
15887   PopDeclContext();
15888 
15889   if (getCurLexicalContext()->isObjCContainer() &&
15890       Tag->getDeclContext()->isFileContext())
15891     Tag->setTopLevelDeclInObjCContainer();
15892 
15893   // Notify the consumer that we've defined a tag.
15894   if (!Tag->isInvalidDecl())
15895     Consumer.HandleTagDeclDefinition(Tag);
15896 }
15897 
15898 void Sema::ActOnObjCContainerFinishDefinition() {
15899   // Exit this scope of this interface definition.
15900   PopDeclContext();
15901 }
15902 
15903 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
15904   assert(DC == CurContext && "Mismatch of container contexts");
15905   OriginalLexicalContext = DC;
15906   ActOnObjCContainerFinishDefinition();
15907 }
15908 
15909 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
15910   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
15911   OriginalLexicalContext = nullptr;
15912 }
15913 
15914 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
15915   AdjustDeclIfTemplate(TagD);
15916   TagDecl *Tag = cast<TagDecl>(TagD);
15917   Tag->setInvalidDecl();
15918 
15919   // Make sure we "complete" the definition even it is invalid.
15920   if (Tag->isBeingDefined()) {
15921     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15922       RD->completeDefinition();
15923   }
15924 
15925   // We're undoing ActOnTagStartDefinition here, not
15926   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
15927   // the FieldCollector.
15928 
15929   PopDeclContext();
15930 }
15931 
15932 // Note that FieldName may be null for anonymous bitfields.
15933 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
15934                                 IdentifierInfo *FieldName,
15935                                 QualType FieldTy, bool IsMsStruct,
15936                                 Expr *BitWidth, bool *ZeroWidth) {
15937   // Default to true; that shouldn't confuse checks for emptiness
15938   if (ZeroWidth)
15939     *ZeroWidth = true;
15940 
15941   // C99 6.7.2.1p4 - verify the field type.
15942   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
15943   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
15944     // Handle incomplete types with specific error.
15945     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
15946       return ExprError();
15947     if (FieldName)
15948       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
15949         << FieldName << FieldTy << BitWidth->getSourceRange();
15950     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
15951       << FieldTy << BitWidth->getSourceRange();
15952   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
15953                                              UPPC_BitFieldWidth))
15954     return ExprError();
15955 
15956   // If the bit-width is type- or value-dependent, don't try to check
15957   // it now.
15958   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
15959     return BitWidth;
15960 
15961   llvm::APSInt Value;
15962   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
15963   if (ICE.isInvalid())
15964     return ICE;
15965   BitWidth = ICE.get();
15966 
15967   if (Value != 0 && ZeroWidth)
15968     *ZeroWidth = false;
15969 
15970   // Zero-width bitfield is ok for anonymous field.
15971   if (Value == 0 && FieldName)
15972     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
15973 
15974   if (Value.isSigned() && Value.isNegative()) {
15975     if (FieldName)
15976       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
15977                << FieldName << Value.toString(10);
15978     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
15979       << Value.toString(10);
15980   }
15981 
15982   if (!FieldTy->isDependentType()) {
15983     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
15984     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
15985     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
15986 
15987     // Over-wide bitfields are an error in C or when using the MSVC bitfield
15988     // ABI.
15989     bool CStdConstraintViolation =
15990         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
15991     bool MSBitfieldViolation =
15992         Value.ugt(TypeStorageSize) &&
15993         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
15994     if (CStdConstraintViolation || MSBitfieldViolation) {
15995       unsigned DiagWidth =
15996           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
15997       if (FieldName)
15998         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
15999                << FieldName << (unsigned)Value.getZExtValue()
16000                << !CStdConstraintViolation << DiagWidth;
16001 
16002       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
16003              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
16004              << DiagWidth;
16005     }
16006 
16007     // Warn on types where the user might conceivably expect to get all
16008     // specified bits as value bits: that's all integral types other than
16009     // 'bool'.
16010     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
16011       if (FieldName)
16012         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
16013             << FieldName << (unsigned)Value.getZExtValue()
16014             << (unsigned)TypeWidth;
16015       else
16016         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
16017             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
16018     }
16019   }
16020 
16021   return BitWidth;
16022 }
16023 
16024 /// ActOnField - Each field of a C struct/union is passed into this in order
16025 /// to create a FieldDecl object for it.
16026 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
16027                        Declarator &D, Expr *BitfieldWidth) {
16028   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
16029                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
16030                                /*InitStyle=*/ICIS_NoInit, AS_public);
16031   return Res;
16032 }
16033 
16034 /// HandleField - Analyze a field of a C struct or a C++ data member.
16035 ///
16036 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
16037                              SourceLocation DeclStart,
16038                              Declarator &D, Expr *BitWidth,
16039                              InClassInitStyle InitStyle,
16040                              AccessSpecifier AS) {
16041   if (D.isDecompositionDeclarator()) {
16042     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
16043     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
16044       << Decomp.getSourceRange();
16045     return nullptr;
16046   }
16047 
16048   IdentifierInfo *II = D.getIdentifier();
16049   SourceLocation Loc = DeclStart;
16050   if (II) Loc = D.getIdentifierLoc();
16051 
16052   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16053   QualType T = TInfo->getType();
16054   if (getLangOpts().CPlusPlus) {
16055     CheckExtraCXXDefaultArguments(D);
16056 
16057     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16058                                         UPPC_DataMemberType)) {
16059       D.setInvalidType();
16060       T = Context.IntTy;
16061       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
16062     }
16063   }
16064 
16065   DiagnoseFunctionSpecifiers(D.getDeclSpec());
16066 
16067   if (D.getDeclSpec().isInlineSpecified())
16068     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
16069         << getLangOpts().CPlusPlus17;
16070   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
16071     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
16072          diag::err_invalid_thread)
16073       << DeclSpec::getSpecifierName(TSCS);
16074 
16075   // Check to see if this name was declared as a member previously
16076   NamedDecl *PrevDecl = nullptr;
16077   LookupResult Previous(*this, II, Loc, LookupMemberName,
16078                         ForVisibleRedeclaration);
16079   LookupName(Previous, S);
16080   switch (Previous.getResultKind()) {
16081     case LookupResult::Found:
16082     case LookupResult::FoundUnresolvedValue:
16083       PrevDecl = Previous.getAsSingle<NamedDecl>();
16084       break;
16085 
16086     case LookupResult::FoundOverloaded:
16087       PrevDecl = Previous.getRepresentativeDecl();
16088       break;
16089 
16090     case LookupResult::NotFound:
16091     case LookupResult::NotFoundInCurrentInstantiation:
16092     case LookupResult::Ambiguous:
16093       break;
16094   }
16095   Previous.suppressDiagnostics();
16096 
16097   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16098     // Maybe we will complain about the shadowed template parameter.
16099     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16100     // Just pretend that we didn't see the previous declaration.
16101     PrevDecl = nullptr;
16102   }
16103 
16104   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
16105     PrevDecl = nullptr;
16106 
16107   bool Mutable
16108     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
16109   SourceLocation TSSL = D.getBeginLoc();
16110   FieldDecl *NewFD
16111     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
16112                      TSSL, AS, PrevDecl, &D);
16113 
16114   if (NewFD->isInvalidDecl())
16115     Record->setInvalidDecl();
16116 
16117   if (D.getDeclSpec().isModulePrivateSpecified())
16118     NewFD->setModulePrivate();
16119 
16120   if (NewFD->isInvalidDecl() && PrevDecl) {
16121     // Don't introduce NewFD into scope; there's already something
16122     // with the same name in the same scope.
16123   } else if (II) {
16124     PushOnScopeChains(NewFD, S);
16125   } else
16126     Record->addDecl(NewFD);
16127 
16128   return NewFD;
16129 }
16130 
16131 /// Build a new FieldDecl and check its well-formedness.
16132 ///
16133 /// This routine builds a new FieldDecl given the fields name, type,
16134 /// record, etc. \p PrevDecl should refer to any previous declaration
16135 /// with the same name and in the same scope as the field to be
16136 /// created.
16137 ///
16138 /// \returns a new FieldDecl.
16139 ///
16140 /// \todo The Declarator argument is a hack. It will be removed once
16141 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
16142                                 TypeSourceInfo *TInfo,
16143                                 RecordDecl *Record, SourceLocation Loc,
16144                                 bool Mutable, Expr *BitWidth,
16145                                 InClassInitStyle InitStyle,
16146                                 SourceLocation TSSL,
16147                                 AccessSpecifier AS, NamedDecl *PrevDecl,
16148                                 Declarator *D) {
16149   IdentifierInfo *II = Name.getAsIdentifierInfo();
16150   bool InvalidDecl = false;
16151   if (D) InvalidDecl = D->isInvalidType();
16152 
16153   // If we receive a broken type, recover by assuming 'int' and
16154   // marking this declaration as invalid.
16155   if (T.isNull()) {
16156     InvalidDecl = true;
16157     T = Context.IntTy;
16158   }
16159 
16160   QualType EltTy = Context.getBaseElementType(T);
16161   if (!EltTy->isDependentType()) {
16162     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
16163       // Fields of incomplete type force their record to be invalid.
16164       Record->setInvalidDecl();
16165       InvalidDecl = true;
16166     } else {
16167       NamedDecl *Def;
16168       EltTy->isIncompleteType(&Def);
16169       if (Def && Def->isInvalidDecl()) {
16170         Record->setInvalidDecl();
16171         InvalidDecl = true;
16172       }
16173     }
16174   }
16175 
16176   // TR 18037 does not allow fields to be declared with address space
16177   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
16178       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
16179     Diag(Loc, diag::err_field_with_address_space);
16180     Record->setInvalidDecl();
16181     InvalidDecl = true;
16182   }
16183 
16184   if (LangOpts.OpenCL) {
16185     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
16186     // used as structure or union field: image, sampler, event or block types.
16187     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
16188         T->isBlockPointerType()) {
16189       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
16190       Record->setInvalidDecl();
16191       InvalidDecl = true;
16192     }
16193     // OpenCL v1.2 s6.9.c: bitfields are not supported.
16194     if (BitWidth) {
16195       Diag(Loc, diag::err_opencl_bitfields);
16196       InvalidDecl = true;
16197     }
16198   }
16199 
16200   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
16201   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
16202       T.hasQualifiers()) {
16203     InvalidDecl = true;
16204     Diag(Loc, diag::err_anon_bitfield_qualifiers);
16205   }
16206 
16207   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16208   // than a variably modified type.
16209   if (!InvalidDecl && T->isVariablyModifiedType()) {
16210     bool SizeIsNegative;
16211     llvm::APSInt Oversized;
16212 
16213     TypeSourceInfo *FixedTInfo =
16214       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
16215                                                     SizeIsNegative,
16216                                                     Oversized);
16217     if (FixedTInfo) {
16218       Diag(Loc, diag::warn_illegal_constant_array_size);
16219       TInfo = FixedTInfo;
16220       T = FixedTInfo->getType();
16221     } else {
16222       if (SizeIsNegative)
16223         Diag(Loc, diag::err_typecheck_negative_array_size);
16224       else if (Oversized.getBoolValue())
16225         Diag(Loc, diag::err_array_too_large)
16226           << Oversized.toString(10);
16227       else
16228         Diag(Loc, diag::err_typecheck_field_variable_size);
16229       InvalidDecl = true;
16230     }
16231   }
16232 
16233   // Fields can not have abstract class types
16234   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
16235                                              diag::err_abstract_type_in_decl,
16236                                              AbstractFieldType))
16237     InvalidDecl = true;
16238 
16239   bool ZeroWidth = false;
16240   if (InvalidDecl)
16241     BitWidth = nullptr;
16242   // If this is declared as a bit-field, check the bit-field.
16243   if (BitWidth) {
16244     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
16245                               &ZeroWidth).get();
16246     if (!BitWidth) {
16247       InvalidDecl = true;
16248       BitWidth = nullptr;
16249       ZeroWidth = false;
16250     }
16251   }
16252 
16253   // Check that 'mutable' is consistent with the type of the declaration.
16254   if (!InvalidDecl && Mutable) {
16255     unsigned DiagID = 0;
16256     if (T->isReferenceType())
16257       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
16258                                         : diag::err_mutable_reference;
16259     else if (T.isConstQualified())
16260       DiagID = diag::err_mutable_const;
16261 
16262     if (DiagID) {
16263       SourceLocation ErrLoc = Loc;
16264       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
16265         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
16266       Diag(ErrLoc, DiagID);
16267       if (DiagID != diag::ext_mutable_reference) {
16268         Mutable = false;
16269         InvalidDecl = true;
16270       }
16271     }
16272   }
16273 
16274   // C++11 [class.union]p8 (DR1460):
16275   //   At most one variant member of a union may have a
16276   //   brace-or-equal-initializer.
16277   if (InitStyle != ICIS_NoInit)
16278     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
16279 
16280   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
16281                                        BitWidth, Mutable, InitStyle);
16282   if (InvalidDecl)
16283     NewFD->setInvalidDecl();
16284 
16285   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
16286     Diag(Loc, diag::err_duplicate_member) << II;
16287     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16288     NewFD->setInvalidDecl();
16289   }
16290 
16291   if (!InvalidDecl && getLangOpts().CPlusPlus) {
16292     if (Record->isUnion()) {
16293       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16294         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
16295         if (RDecl->getDefinition()) {
16296           // C++ [class.union]p1: An object of a class with a non-trivial
16297           // constructor, a non-trivial copy constructor, a non-trivial
16298           // destructor, or a non-trivial copy assignment operator
16299           // cannot be a member of a union, nor can an array of such
16300           // objects.
16301           if (CheckNontrivialField(NewFD))
16302             NewFD->setInvalidDecl();
16303         }
16304       }
16305 
16306       // C++ [class.union]p1: If a union contains a member of reference type,
16307       // the program is ill-formed, except when compiling with MSVC extensions
16308       // enabled.
16309       if (EltTy->isReferenceType()) {
16310         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
16311                                     diag::ext_union_member_of_reference_type :
16312                                     diag::err_union_member_of_reference_type)
16313           << NewFD->getDeclName() << EltTy;
16314         if (!getLangOpts().MicrosoftExt)
16315           NewFD->setInvalidDecl();
16316       }
16317     }
16318   }
16319 
16320   // FIXME: We need to pass in the attributes given an AST
16321   // representation, not a parser representation.
16322   if (D) {
16323     // FIXME: The current scope is almost... but not entirely... correct here.
16324     ProcessDeclAttributes(getCurScope(), NewFD, *D);
16325 
16326     if (NewFD->hasAttrs())
16327       CheckAlignasUnderalignment(NewFD);
16328   }
16329 
16330   // In auto-retain/release, infer strong retension for fields of
16331   // retainable type.
16332   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
16333     NewFD->setInvalidDecl();
16334 
16335   if (T.isObjCGCWeak())
16336     Diag(Loc, diag::warn_attribute_weak_on_field);
16337 
16338   NewFD->setAccess(AS);
16339   return NewFD;
16340 }
16341 
16342 bool Sema::CheckNontrivialField(FieldDecl *FD) {
16343   assert(FD);
16344   assert(getLangOpts().CPlusPlus && "valid check only for C++");
16345 
16346   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
16347     return false;
16348 
16349   QualType EltTy = Context.getBaseElementType(FD->getType());
16350   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16351     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
16352     if (RDecl->getDefinition()) {
16353       // We check for copy constructors before constructors
16354       // because otherwise we'll never get complaints about
16355       // copy constructors.
16356 
16357       CXXSpecialMember member = CXXInvalid;
16358       // We're required to check for any non-trivial constructors. Since the
16359       // implicit default constructor is suppressed if there are any
16360       // user-declared constructors, we just need to check that there is a
16361       // trivial default constructor and a trivial copy constructor. (We don't
16362       // worry about move constructors here, since this is a C++98 check.)
16363       if (RDecl->hasNonTrivialCopyConstructor())
16364         member = CXXCopyConstructor;
16365       else if (!RDecl->hasTrivialDefaultConstructor())
16366         member = CXXDefaultConstructor;
16367       else if (RDecl->hasNonTrivialCopyAssignment())
16368         member = CXXCopyAssignment;
16369       else if (RDecl->hasNonTrivialDestructor())
16370         member = CXXDestructor;
16371 
16372       if (member != CXXInvalid) {
16373         if (!getLangOpts().CPlusPlus11 &&
16374             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
16375           // Objective-C++ ARC: it is an error to have a non-trivial field of
16376           // a union. However, system headers in Objective-C programs
16377           // occasionally have Objective-C lifetime objects within unions,
16378           // and rather than cause the program to fail, we make those
16379           // members unavailable.
16380           SourceLocation Loc = FD->getLocation();
16381           if (getSourceManager().isInSystemHeader(Loc)) {
16382             if (!FD->hasAttr<UnavailableAttr>())
16383               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
16384                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
16385             return false;
16386           }
16387         }
16388 
16389         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
16390                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
16391                diag::err_illegal_union_or_anon_struct_member)
16392           << FD->getParent()->isUnion() << FD->getDeclName() << member;
16393         DiagnoseNontrivial(RDecl, member);
16394         return !getLangOpts().CPlusPlus11;
16395       }
16396     }
16397   }
16398 
16399   return false;
16400 }
16401 
16402 /// TranslateIvarVisibility - Translate visibility from a token ID to an
16403 ///  AST enum value.
16404 static ObjCIvarDecl::AccessControl
16405 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
16406   switch (ivarVisibility) {
16407   default: llvm_unreachable("Unknown visitibility kind");
16408   case tok::objc_private: return ObjCIvarDecl::Private;
16409   case tok::objc_public: return ObjCIvarDecl::Public;
16410   case tok::objc_protected: return ObjCIvarDecl::Protected;
16411   case tok::objc_package: return ObjCIvarDecl::Package;
16412   }
16413 }
16414 
16415 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
16416 /// in order to create an IvarDecl object for it.
16417 Decl *Sema::ActOnIvar(Scope *S,
16418                                 SourceLocation DeclStart,
16419                                 Declarator &D, Expr *BitfieldWidth,
16420                                 tok::ObjCKeywordKind Visibility) {
16421 
16422   IdentifierInfo *II = D.getIdentifier();
16423   Expr *BitWidth = (Expr*)BitfieldWidth;
16424   SourceLocation Loc = DeclStart;
16425   if (II) Loc = D.getIdentifierLoc();
16426 
16427   // FIXME: Unnamed fields can be handled in various different ways, for
16428   // example, unnamed unions inject all members into the struct namespace!
16429 
16430   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16431   QualType T = TInfo->getType();
16432 
16433   if (BitWidth) {
16434     // 6.7.2.1p3, 6.7.2.1p4
16435     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
16436     if (!BitWidth)
16437       D.setInvalidType();
16438   } else {
16439     // Not a bitfield.
16440 
16441     // validate II.
16442 
16443   }
16444   if (T->isReferenceType()) {
16445     Diag(Loc, diag::err_ivar_reference_type);
16446     D.setInvalidType();
16447   }
16448   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16449   // than a variably modified type.
16450   else if (T->isVariablyModifiedType()) {
16451     Diag(Loc, diag::err_typecheck_ivar_variable_size);
16452     D.setInvalidType();
16453   }
16454 
16455   // Get the visibility (access control) for this ivar.
16456   ObjCIvarDecl::AccessControl ac =
16457     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
16458                                         : ObjCIvarDecl::None;
16459   // Must set ivar's DeclContext to its enclosing interface.
16460   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
16461   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
16462     return nullptr;
16463   ObjCContainerDecl *EnclosingContext;
16464   if (ObjCImplementationDecl *IMPDecl =
16465       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16466     if (LangOpts.ObjCRuntime.isFragile()) {
16467     // Case of ivar declared in an implementation. Context is that of its class.
16468       EnclosingContext = IMPDecl->getClassInterface();
16469       assert(EnclosingContext && "Implementation has no class interface!");
16470     }
16471     else
16472       EnclosingContext = EnclosingDecl;
16473   } else {
16474     if (ObjCCategoryDecl *CDecl =
16475         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16476       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
16477         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
16478         return nullptr;
16479       }
16480     }
16481     EnclosingContext = EnclosingDecl;
16482   }
16483 
16484   // Construct the decl.
16485   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
16486                                              DeclStart, Loc, II, T,
16487                                              TInfo, ac, (Expr *)BitfieldWidth);
16488 
16489   if (II) {
16490     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
16491                                            ForVisibleRedeclaration);
16492     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
16493         && !isa<TagDecl>(PrevDecl)) {
16494       Diag(Loc, diag::err_duplicate_member) << II;
16495       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16496       NewID->setInvalidDecl();
16497     }
16498   }
16499 
16500   // Process attributes attached to the ivar.
16501   ProcessDeclAttributes(S, NewID, D);
16502 
16503   if (D.isInvalidType())
16504     NewID->setInvalidDecl();
16505 
16506   // In ARC, infer 'retaining' for ivars of retainable type.
16507   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
16508     NewID->setInvalidDecl();
16509 
16510   if (D.getDeclSpec().isModulePrivateSpecified())
16511     NewID->setModulePrivate();
16512 
16513   if (II) {
16514     // FIXME: When interfaces are DeclContexts, we'll need to add
16515     // these to the interface.
16516     S->AddDecl(NewID);
16517     IdResolver.AddDecl(NewID);
16518   }
16519 
16520   if (LangOpts.ObjCRuntime.isNonFragile() &&
16521       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
16522     Diag(Loc, diag::warn_ivars_in_interface);
16523 
16524   return NewID;
16525 }
16526 
16527 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
16528 /// class and class extensions. For every class \@interface and class
16529 /// extension \@interface, if the last ivar is a bitfield of any type,
16530 /// then add an implicit `char :0` ivar to the end of that interface.
16531 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
16532                              SmallVectorImpl<Decl *> &AllIvarDecls) {
16533   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
16534     return;
16535 
16536   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
16537   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
16538 
16539   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
16540     return;
16541   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
16542   if (!ID) {
16543     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
16544       if (!CD->IsClassExtension())
16545         return;
16546     }
16547     // No need to add this to end of @implementation.
16548     else
16549       return;
16550   }
16551   // All conditions are met. Add a new bitfield to the tail end of ivars.
16552   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
16553   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
16554 
16555   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
16556                               DeclLoc, DeclLoc, nullptr,
16557                               Context.CharTy,
16558                               Context.getTrivialTypeSourceInfo(Context.CharTy,
16559                                                                DeclLoc),
16560                               ObjCIvarDecl::Private, BW,
16561                               true);
16562   AllIvarDecls.push_back(Ivar);
16563 }
16564 
16565 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
16566                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
16567                        SourceLocation RBrac,
16568                        const ParsedAttributesView &Attrs) {
16569   assert(EnclosingDecl && "missing record or interface decl");
16570 
16571   // If this is an Objective-C @implementation or category and we have
16572   // new fields here we should reset the layout of the interface since
16573   // it will now change.
16574   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
16575     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
16576     switch (DC->getKind()) {
16577     default: break;
16578     case Decl::ObjCCategory:
16579       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
16580       break;
16581     case Decl::ObjCImplementation:
16582       Context.
16583         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
16584       break;
16585     }
16586   }
16587 
16588   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
16589   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
16590 
16591   // Start counting up the number of named members; make sure to include
16592   // members of anonymous structs and unions in the total.
16593   unsigned NumNamedMembers = 0;
16594   if (Record) {
16595     for (const auto *I : Record->decls()) {
16596       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
16597         if (IFD->getDeclName())
16598           ++NumNamedMembers;
16599     }
16600   }
16601 
16602   // Verify that all the fields are okay.
16603   SmallVector<FieldDecl*, 32> RecFields;
16604 
16605   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
16606        i != end; ++i) {
16607     FieldDecl *FD = cast<FieldDecl>(*i);
16608 
16609     // Get the type for the field.
16610     const Type *FDTy = FD->getType().getTypePtr();
16611 
16612     if (!FD->isAnonymousStructOrUnion()) {
16613       // Remember all fields written by the user.
16614       RecFields.push_back(FD);
16615     }
16616 
16617     // If the field is already invalid for some reason, don't emit more
16618     // diagnostics about it.
16619     if (FD->isInvalidDecl()) {
16620       EnclosingDecl->setInvalidDecl();
16621       continue;
16622     }
16623 
16624     // C99 6.7.2.1p2:
16625     //   A structure or union shall not contain a member with
16626     //   incomplete or function type (hence, a structure shall not
16627     //   contain an instance of itself, but may contain a pointer to
16628     //   an instance of itself), except that the last member of a
16629     //   structure with more than one named member may have incomplete
16630     //   array type; such a structure (and any union containing,
16631     //   possibly recursively, a member that is such a structure)
16632     //   shall not be a member of a structure or an element of an
16633     //   array.
16634     bool IsLastField = (i + 1 == Fields.end());
16635     if (FDTy->isFunctionType()) {
16636       // Field declared as a function.
16637       Diag(FD->getLocation(), diag::err_field_declared_as_function)
16638         << FD->getDeclName();
16639       FD->setInvalidDecl();
16640       EnclosingDecl->setInvalidDecl();
16641       continue;
16642     } else if (FDTy->isIncompleteArrayType() &&
16643                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
16644       if (Record) {
16645         // Flexible array member.
16646         // Microsoft and g++ is more permissive regarding flexible array.
16647         // It will accept flexible array in union and also
16648         // as the sole element of a struct/class.
16649         unsigned DiagID = 0;
16650         if (!Record->isUnion() && !IsLastField) {
16651           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
16652             << FD->getDeclName() << FD->getType() << Record->getTagKind();
16653           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
16654           FD->setInvalidDecl();
16655           EnclosingDecl->setInvalidDecl();
16656           continue;
16657         } else if (Record->isUnion())
16658           DiagID = getLangOpts().MicrosoftExt
16659                        ? diag::ext_flexible_array_union_ms
16660                        : getLangOpts().CPlusPlus
16661                              ? diag::ext_flexible_array_union_gnu
16662                              : diag::err_flexible_array_union;
16663         else if (NumNamedMembers < 1)
16664           DiagID = getLangOpts().MicrosoftExt
16665                        ? diag::ext_flexible_array_empty_aggregate_ms
16666                        : getLangOpts().CPlusPlus
16667                              ? diag::ext_flexible_array_empty_aggregate_gnu
16668                              : diag::err_flexible_array_empty_aggregate;
16669 
16670         if (DiagID)
16671           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
16672                                           << Record->getTagKind();
16673         // While the layout of types that contain virtual bases is not specified
16674         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
16675         // virtual bases after the derived members.  This would make a flexible
16676         // array member declared at the end of an object not adjacent to the end
16677         // of the type.
16678         if (CXXRecord && CXXRecord->getNumVBases() != 0)
16679           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
16680               << FD->getDeclName() << Record->getTagKind();
16681         if (!getLangOpts().C99)
16682           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
16683             << FD->getDeclName() << Record->getTagKind();
16684 
16685         // If the element type has a non-trivial destructor, we would not
16686         // implicitly destroy the elements, so disallow it for now.
16687         //
16688         // FIXME: GCC allows this. We should probably either implicitly delete
16689         // the destructor of the containing class, or just allow this.
16690         QualType BaseElem = Context.getBaseElementType(FD->getType());
16691         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
16692           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
16693             << FD->getDeclName() << FD->getType();
16694           FD->setInvalidDecl();
16695           EnclosingDecl->setInvalidDecl();
16696           continue;
16697         }
16698         // Okay, we have a legal flexible array member at the end of the struct.
16699         Record->setHasFlexibleArrayMember(true);
16700       } else {
16701         // In ObjCContainerDecl ivars with incomplete array type are accepted,
16702         // unless they are followed by another ivar. That check is done
16703         // elsewhere, after synthesized ivars are known.
16704       }
16705     } else if (!FDTy->isDependentType() &&
16706                RequireCompleteType(FD->getLocation(), FD->getType(),
16707                                    diag::err_field_incomplete)) {
16708       // Incomplete type
16709       FD->setInvalidDecl();
16710       EnclosingDecl->setInvalidDecl();
16711       continue;
16712     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
16713       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
16714         // A type which contains a flexible array member is considered to be a
16715         // flexible array member.
16716         Record->setHasFlexibleArrayMember(true);
16717         if (!Record->isUnion()) {
16718           // If this is a struct/class and this is not the last element, reject
16719           // it.  Note that GCC supports variable sized arrays in the middle of
16720           // structures.
16721           if (!IsLastField)
16722             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
16723               << FD->getDeclName() << FD->getType();
16724           else {
16725             // We support flexible arrays at the end of structs in
16726             // other structs as an extension.
16727             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
16728               << FD->getDeclName();
16729           }
16730         }
16731       }
16732       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
16733           RequireNonAbstractType(FD->getLocation(), FD->getType(),
16734                                  diag::err_abstract_type_in_decl,
16735                                  AbstractIvarType)) {
16736         // Ivars can not have abstract class types
16737         FD->setInvalidDecl();
16738       }
16739       if (Record && FDTTy->getDecl()->hasObjectMember())
16740         Record->setHasObjectMember(true);
16741       if (Record && FDTTy->getDecl()->hasVolatileMember())
16742         Record->setHasVolatileMember(true);
16743     } else if (FDTy->isObjCObjectType()) {
16744       /// A field cannot be an Objective-c object
16745       Diag(FD->getLocation(), diag::err_statically_allocated_object)
16746         << FixItHint::CreateInsertion(FD->getLocation(), "*");
16747       QualType T = Context.getObjCObjectPointerType(FD->getType());
16748       FD->setType(T);
16749     } else if (Record && Record->isUnion() &&
16750                FD->getType().hasNonTrivialObjCLifetime() &&
16751                getSourceManager().isInSystemHeader(FD->getLocation()) &&
16752                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
16753                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
16754                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
16755       // For backward compatibility, fields of C unions declared in system
16756       // headers that have non-trivial ObjC ownership qualifications are marked
16757       // as unavailable unless the qualifier is explicit and __strong. This can
16758       // break ABI compatibility between programs compiled with ARC and MRR, but
16759       // is a better option than rejecting programs using those unions under
16760       // ARC.
16761       FD->addAttr(UnavailableAttr::CreateImplicit(
16762           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
16763           FD->getLocation()));
16764     } else if (getLangOpts().ObjC &&
16765                getLangOpts().getGC() != LangOptions::NonGC &&
16766                Record && !Record->hasObjectMember()) {
16767       if (FD->getType()->isObjCObjectPointerType() ||
16768           FD->getType().isObjCGCStrong())
16769         Record->setHasObjectMember(true);
16770       else if (Context.getAsArrayType(FD->getType())) {
16771         QualType BaseType = Context.getBaseElementType(FD->getType());
16772         if (BaseType->isRecordType() &&
16773             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
16774           Record->setHasObjectMember(true);
16775         else if (BaseType->isObjCObjectPointerType() ||
16776                  BaseType.isObjCGCStrong())
16777                Record->setHasObjectMember(true);
16778       }
16779     }
16780 
16781     if (Record && !getLangOpts().CPlusPlus &&
16782         !shouldIgnoreForRecordTriviality(FD)) {
16783       QualType FT = FD->getType();
16784       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
16785         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
16786         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
16787             Record->isUnion())
16788           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
16789       }
16790       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
16791       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
16792         Record->setNonTrivialToPrimitiveCopy(true);
16793         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
16794           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
16795       }
16796       if (FT.isDestructedType()) {
16797         Record->setNonTrivialToPrimitiveDestroy(true);
16798         Record->setParamDestroyedInCallee(true);
16799         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
16800           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
16801       }
16802 
16803       if (const auto *RT = FT->getAs<RecordType>()) {
16804         if (RT->getDecl()->getArgPassingRestrictions() ==
16805             RecordDecl::APK_CanNeverPassInRegs)
16806           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16807       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
16808         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16809     }
16810 
16811     if (Record && FD->getType().isVolatileQualified())
16812       Record->setHasVolatileMember(true);
16813     // Keep track of the number of named members.
16814     if (FD->getIdentifier())
16815       ++NumNamedMembers;
16816   }
16817 
16818   // Okay, we successfully defined 'Record'.
16819   if (Record) {
16820     bool Completed = false;
16821     if (CXXRecord) {
16822       if (!CXXRecord->isInvalidDecl()) {
16823         // Set access bits correctly on the directly-declared conversions.
16824         for (CXXRecordDecl::conversion_iterator
16825                I = CXXRecord->conversion_begin(),
16826                E = CXXRecord->conversion_end(); I != E; ++I)
16827           I.setAccess((*I)->getAccess());
16828       }
16829 
16830       if (!CXXRecord->isDependentType()) {
16831         // Add any implicitly-declared members to this class.
16832         AddImplicitlyDeclaredMembersToClass(CXXRecord);
16833 
16834         if (!CXXRecord->isInvalidDecl()) {
16835           // If we have virtual base classes, we may end up finding multiple
16836           // final overriders for a given virtual function. Check for this
16837           // problem now.
16838           if (CXXRecord->getNumVBases()) {
16839             CXXFinalOverriderMap FinalOverriders;
16840             CXXRecord->getFinalOverriders(FinalOverriders);
16841 
16842             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
16843                                              MEnd = FinalOverriders.end();
16844                  M != MEnd; ++M) {
16845               for (OverridingMethods::iterator SO = M->second.begin(),
16846                                             SOEnd = M->second.end();
16847                    SO != SOEnd; ++SO) {
16848                 assert(SO->second.size() > 0 &&
16849                        "Virtual function without overriding functions?");
16850                 if (SO->second.size() == 1)
16851                   continue;
16852 
16853                 // C++ [class.virtual]p2:
16854                 //   In a derived class, if a virtual member function of a base
16855                 //   class subobject has more than one final overrider the
16856                 //   program is ill-formed.
16857                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
16858                   << (const NamedDecl *)M->first << Record;
16859                 Diag(M->first->getLocation(),
16860                      diag::note_overridden_virtual_function);
16861                 for (OverridingMethods::overriding_iterator
16862                           OM = SO->second.begin(),
16863                        OMEnd = SO->second.end();
16864                      OM != OMEnd; ++OM)
16865                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
16866                     << (const NamedDecl *)M->first << OM->Method->getParent();
16867 
16868                 Record->setInvalidDecl();
16869               }
16870             }
16871             CXXRecord->completeDefinition(&FinalOverriders);
16872             Completed = true;
16873           }
16874         }
16875       }
16876     }
16877 
16878     if (!Completed)
16879       Record->completeDefinition();
16880 
16881     // Handle attributes before checking the layout.
16882     ProcessDeclAttributeList(S, Record, Attrs);
16883 
16884     // We may have deferred checking for a deleted destructor. Check now.
16885     if (CXXRecord) {
16886       auto *Dtor = CXXRecord->getDestructor();
16887       if (Dtor && Dtor->isImplicit() &&
16888           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
16889         CXXRecord->setImplicitDestructorIsDeleted();
16890         SetDeclDeleted(Dtor, CXXRecord->getLocation());
16891       }
16892     }
16893 
16894     if (Record->hasAttrs()) {
16895       CheckAlignasUnderalignment(Record);
16896 
16897       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
16898         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
16899                                            IA->getRange(), IA->getBestCase(),
16900                                            IA->getInheritanceModel());
16901     }
16902 
16903     // Check if the structure/union declaration is a type that can have zero
16904     // size in C. For C this is a language extension, for C++ it may cause
16905     // compatibility problems.
16906     bool CheckForZeroSize;
16907     if (!getLangOpts().CPlusPlus) {
16908       CheckForZeroSize = true;
16909     } else {
16910       // For C++ filter out types that cannot be referenced in C code.
16911       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
16912       CheckForZeroSize =
16913           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
16914           !CXXRecord->isDependentType() &&
16915           CXXRecord->isCLike();
16916     }
16917     if (CheckForZeroSize) {
16918       bool ZeroSize = true;
16919       bool IsEmpty = true;
16920       unsigned NonBitFields = 0;
16921       for (RecordDecl::field_iterator I = Record->field_begin(),
16922                                       E = Record->field_end();
16923            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
16924         IsEmpty = false;
16925         if (I->isUnnamedBitfield()) {
16926           if (!I->isZeroLengthBitField(Context))
16927             ZeroSize = false;
16928         } else {
16929           ++NonBitFields;
16930           QualType FieldType = I->getType();
16931           if (FieldType->isIncompleteType() ||
16932               !Context.getTypeSizeInChars(FieldType).isZero())
16933             ZeroSize = false;
16934         }
16935       }
16936 
16937       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
16938       // allowed in C++, but warn if its declaration is inside
16939       // extern "C" block.
16940       if (ZeroSize) {
16941         Diag(RecLoc, getLangOpts().CPlusPlus ?
16942                          diag::warn_zero_size_struct_union_in_extern_c :
16943                          diag::warn_zero_size_struct_union_compat)
16944           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
16945       }
16946 
16947       // Structs without named members are extension in C (C99 6.7.2.1p7),
16948       // but are accepted by GCC.
16949       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
16950         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
16951                                diag::ext_no_named_members_in_struct_union)
16952           << Record->isUnion();
16953       }
16954     }
16955   } else {
16956     ObjCIvarDecl **ClsFields =
16957       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
16958     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
16959       ID->setEndOfDefinitionLoc(RBrac);
16960       // Add ivar's to class's DeclContext.
16961       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16962         ClsFields[i]->setLexicalDeclContext(ID);
16963         ID->addDecl(ClsFields[i]);
16964       }
16965       // Must enforce the rule that ivars in the base classes may not be
16966       // duplicates.
16967       if (ID->getSuperClass())
16968         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
16969     } else if (ObjCImplementationDecl *IMPDecl =
16970                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16971       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
16972       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
16973         // Ivar declared in @implementation never belongs to the implementation.
16974         // Only it is in implementation's lexical context.
16975         ClsFields[I]->setLexicalDeclContext(IMPDecl);
16976       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
16977       IMPDecl->setIvarLBraceLoc(LBrac);
16978       IMPDecl->setIvarRBraceLoc(RBrac);
16979     } else if (ObjCCategoryDecl *CDecl =
16980                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16981       // case of ivars in class extension; all other cases have been
16982       // reported as errors elsewhere.
16983       // FIXME. Class extension does not have a LocEnd field.
16984       // CDecl->setLocEnd(RBrac);
16985       // Add ivar's to class extension's DeclContext.
16986       // Diagnose redeclaration of private ivars.
16987       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
16988       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16989         if (IDecl) {
16990           if (const ObjCIvarDecl *ClsIvar =
16991               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
16992             Diag(ClsFields[i]->getLocation(),
16993                  diag::err_duplicate_ivar_declaration);
16994             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
16995             continue;
16996           }
16997           for (const auto *Ext : IDecl->known_extensions()) {
16998             if (const ObjCIvarDecl *ClsExtIvar
16999                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
17000               Diag(ClsFields[i]->getLocation(),
17001                    diag::err_duplicate_ivar_declaration);
17002               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
17003               continue;
17004             }
17005           }
17006         }
17007         ClsFields[i]->setLexicalDeclContext(CDecl);
17008         CDecl->addDecl(ClsFields[i]);
17009       }
17010       CDecl->setIvarLBraceLoc(LBrac);
17011       CDecl->setIvarRBraceLoc(RBrac);
17012     }
17013   }
17014 }
17015 
17016 /// Determine whether the given integral value is representable within
17017 /// the given type T.
17018 static bool isRepresentableIntegerValue(ASTContext &Context,
17019                                         llvm::APSInt &Value,
17020                                         QualType T) {
17021   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
17022          "Integral type required!");
17023   unsigned BitWidth = Context.getIntWidth(T);
17024 
17025   if (Value.isUnsigned() || Value.isNonNegative()) {
17026     if (T->isSignedIntegerOrEnumerationType())
17027       --BitWidth;
17028     return Value.getActiveBits() <= BitWidth;
17029   }
17030   return Value.getMinSignedBits() <= BitWidth;
17031 }
17032 
17033 // Given an integral type, return the next larger integral type
17034 // (or a NULL type of no such type exists).
17035 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
17036   // FIXME: Int128/UInt128 support, which also needs to be introduced into
17037   // enum checking below.
17038   assert((T->isIntegralType(Context) ||
17039          T->isEnumeralType()) && "Integral type required!");
17040   const unsigned NumTypes = 4;
17041   QualType SignedIntegralTypes[NumTypes] = {
17042     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
17043   };
17044   QualType UnsignedIntegralTypes[NumTypes] = {
17045     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
17046     Context.UnsignedLongLongTy
17047   };
17048 
17049   unsigned BitWidth = Context.getTypeSize(T);
17050   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
17051                                                         : UnsignedIntegralTypes;
17052   for (unsigned I = 0; I != NumTypes; ++I)
17053     if (Context.getTypeSize(Types[I]) > BitWidth)
17054       return Types[I];
17055 
17056   return QualType();
17057 }
17058 
17059 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
17060                                           EnumConstantDecl *LastEnumConst,
17061                                           SourceLocation IdLoc,
17062                                           IdentifierInfo *Id,
17063                                           Expr *Val) {
17064   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17065   llvm::APSInt EnumVal(IntWidth);
17066   QualType EltTy;
17067 
17068   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
17069     Val = nullptr;
17070 
17071   if (Val)
17072     Val = DefaultLvalueConversion(Val).get();
17073 
17074   if (Val) {
17075     if (Enum->isDependentType() || Val->isTypeDependent())
17076       EltTy = Context.DependentTy;
17077     else {
17078       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
17079         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
17080         // constant-expression in the enumerator-definition shall be a converted
17081         // constant expression of the underlying type.
17082         EltTy = Enum->getIntegerType();
17083         ExprResult Converted =
17084           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
17085                                            CCEK_Enumerator);
17086         if (Converted.isInvalid())
17087           Val = nullptr;
17088         else
17089           Val = Converted.get();
17090       } else if (!Val->isValueDependent() &&
17091                  !(Val = VerifyIntegerConstantExpression(Val,
17092                                                          &EnumVal).get())) {
17093         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
17094       } else {
17095         if (Enum->isComplete()) {
17096           EltTy = Enum->getIntegerType();
17097 
17098           // In Obj-C and Microsoft mode, require the enumeration value to be
17099           // representable in the underlying type of the enumeration. In C++11,
17100           // we perform a non-narrowing conversion as part of converted constant
17101           // expression checking.
17102           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17103             if (Context.getTargetInfo()
17104                     .getTriple()
17105                     .isWindowsMSVCEnvironment()) {
17106               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
17107             } else {
17108               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
17109             }
17110           }
17111 
17112           // Cast to the underlying type.
17113           Val = ImpCastExprToType(Val, EltTy,
17114                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
17115                                                          : CK_IntegralCast)
17116                     .get();
17117         } else if (getLangOpts().CPlusPlus) {
17118           // C++11 [dcl.enum]p5:
17119           //   If the underlying type is not fixed, the type of each enumerator
17120           //   is the type of its initializing value:
17121           //     - If an initializer is specified for an enumerator, the
17122           //       initializing value has the same type as the expression.
17123           EltTy = Val->getType();
17124         } else {
17125           // C99 6.7.2.2p2:
17126           //   The expression that defines the value of an enumeration constant
17127           //   shall be an integer constant expression that has a value
17128           //   representable as an int.
17129 
17130           // Complain if the value is not representable in an int.
17131           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
17132             Diag(IdLoc, diag::ext_enum_value_not_int)
17133               << EnumVal.toString(10) << Val->getSourceRange()
17134               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
17135           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
17136             // Force the type of the expression to 'int'.
17137             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
17138           }
17139           EltTy = Val->getType();
17140         }
17141       }
17142     }
17143   }
17144 
17145   if (!Val) {
17146     if (Enum->isDependentType())
17147       EltTy = Context.DependentTy;
17148     else if (!LastEnumConst) {
17149       // C++0x [dcl.enum]p5:
17150       //   If the underlying type is not fixed, the type of each enumerator
17151       //   is the type of its initializing value:
17152       //     - If no initializer is specified for the first enumerator, the
17153       //       initializing value has an unspecified integral type.
17154       //
17155       // GCC uses 'int' for its unspecified integral type, as does
17156       // C99 6.7.2.2p3.
17157       if (Enum->isFixed()) {
17158         EltTy = Enum->getIntegerType();
17159       }
17160       else {
17161         EltTy = Context.IntTy;
17162       }
17163     } else {
17164       // Assign the last value + 1.
17165       EnumVal = LastEnumConst->getInitVal();
17166       ++EnumVal;
17167       EltTy = LastEnumConst->getType();
17168 
17169       // Check for overflow on increment.
17170       if (EnumVal < LastEnumConst->getInitVal()) {
17171         // C++0x [dcl.enum]p5:
17172         //   If the underlying type is not fixed, the type of each enumerator
17173         //   is the type of its initializing value:
17174         //
17175         //     - Otherwise the type of the initializing value is the same as
17176         //       the type of the initializing value of the preceding enumerator
17177         //       unless the incremented value is not representable in that type,
17178         //       in which case the type is an unspecified integral type
17179         //       sufficient to contain the incremented value. If no such type
17180         //       exists, the program is ill-formed.
17181         QualType T = getNextLargerIntegralType(Context, EltTy);
17182         if (T.isNull() || Enum->isFixed()) {
17183           // There is no integral type larger enough to represent this
17184           // value. Complain, then allow the value to wrap around.
17185           EnumVal = LastEnumConst->getInitVal();
17186           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
17187           ++EnumVal;
17188           if (Enum->isFixed())
17189             // When the underlying type is fixed, this is ill-formed.
17190             Diag(IdLoc, diag::err_enumerator_wrapped)
17191               << EnumVal.toString(10)
17192               << EltTy;
17193           else
17194             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
17195               << EnumVal.toString(10);
17196         } else {
17197           EltTy = T;
17198         }
17199 
17200         // Retrieve the last enumerator's value, extent that type to the
17201         // type that is supposed to be large enough to represent the incremented
17202         // value, then increment.
17203         EnumVal = LastEnumConst->getInitVal();
17204         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17205         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
17206         ++EnumVal;
17207 
17208         // If we're not in C++, diagnose the overflow of enumerator values,
17209         // which in C99 means that the enumerator value is not representable in
17210         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
17211         // permits enumerator values that are representable in some larger
17212         // integral type.
17213         if (!getLangOpts().CPlusPlus && !T.isNull())
17214           Diag(IdLoc, diag::warn_enum_value_overflow);
17215       } else if (!getLangOpts().CPlusPlus &&
17216                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17217         // Enforce C99 6.7.2.2p2 even when we compute the next value.
17218         Diag(IdLoc, diag::ext_enum_value_not_int)
17219           << EnumVal.toString(10) << 1;
17220       }
17221     }
17222   }
17223 
17224   if (!EltTy->isDependentType()) {
17225     // Make the enumerator value match the signedness and size of the
17226     // enumerator's type.
17227     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
17228     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17229   }
17230 
17231   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
17232                                   Val, EnumVal);
17233 }
17234 
17235 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
17236                                                 SourceLocation IILoc) {
17237   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
17238       !getLangOpts().CPlusPlus)
17239     return SkipBodyInfo();
17240 
17241   // We have an anonymous enum definition. Look up the first enumerator to
17242   // determine if we should merge the definition with an existing one and
17243   // skip the body.
17244   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
17245                                          forRedeclarationInCurContext());
17246   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
17247   if (!PrevECD)
17248     return SkipBodyInfo();
17249 
17250   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
17251   NamedDecl *Hidden;
17252   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
17253     SkipBodyInfo Skip;
17254     Skip.Previous = Hidden;
17255     return Skip;
17256   }
17257 
17258   return SkipBodyInfo();
17259 }
17260 
17261 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
17262                               SourceLocation IdLoc, IdentifierInfo *Id,
17263                               const ParsedAttributesView &Attrs,
17264                               SourceLocation EqualLoc, Expr *Val) {
17265   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
17266   EnumConstantDecl *LastEnumConst =
17267     cast_or_null<EnumConstantDecl>(lastEnumConst);
17268 
17269   // The scope passed in may not be a decl scope.  Zip up the scope tree until
17270   // we find one that is.
17271   S = getNonFieldDeclScope(S);
17272 
17273   // Verify that there isn't already something declared with this name in this
17274   // scope.
17275   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
17276   LookupName(R, S);
17277   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
17278 
17279   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17280     // Maybe we will complain about the shadowed template parameter.
17281     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
17282     // Just pretend that we didn't see the previous declaration.
17283     PrevDecl = nullptr;
17284   }
17285 
17286   // C++ [class.mem]p15:
17287   // If T is the name of a class, then each of the following shall have a name
17288   // different from T:
17289   // - every enumerator of every member of class T that is an unscoped
17290   // enumerated type
17291   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
17292     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
17293                             DeclarationNameInfo(Id, IdLoc));
17294 
17295   EnumConstantDecl *New =
17296     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
17297   if (!New)
17298     return nullptr;
17299 
17300   if (PrevDecl) {
17301     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
17302       // Check for other kinds of shadowing not already handled.
17303       CheckShadow(New, PrevDecl, R);
17304     }
17305 
17306     // When in C++, we may get a TagDecl with the same name; in this case the
17307     // enum constant will 'hide' the tag.
17308     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
17309            "Received TagDecl when not in C++!");
17310     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
17311       if (isa<EnumConstantDecl>(PrevDecl))
17312         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
17313       else
17314         Diag(IdLoc, diag::err_redefinition) << Id;
17315       notePreviousDefinition(PrevDecl, IdLoc);
17316       return nullptr;
17317     }
17318   }
17319 
17320   // Process attributes.
17321   ProcessDeclAttributeList(S, New, Attrs);
17322   AddPragmaAttributes(S, New);
17323 
17324   // Register this decl in the current scope stack.
17325   New->setAccess(TheEnumDecl->getAccess());
17326   PushOnScopeChains(New, S);
17327 
17328   ActOnDocumentableDecl(New);
17329 
17330   return New;
17331 }
17332 
17333 // Returns true when the enum initial expression does not trigger the
17334 // duplicate enum warning.  A few common cases are exempted as follows:
17335 // Element2 = Element1
17336 // Element2 = Element1 + 1
17337 // Element2 = Element1 - 1
17338 // Where Element2 and Element1 are from the same enum.
17339 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
17340   Expr *InitExpr = ECD->getInitExpr();
17341   if (!InitExpr)
17342     return true;
17343   InitExpr = InitExpr->IgnoreImpCasts();
17344 
17345   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
17346     if (!BO->isAdditiveOp())
17347       return true;
17348     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
17349     if (!IL)
17350       return true;
17351     if (IL->getValue() != 1)
17352       return true;
17353 
17354     InitExpr = BO->getLHS();
17355   }
17356 
17357   // This checks if the elements are from the same enum.
17358   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
17359   if (!DRE)
17360     return true;
17361 
17362   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
17363   if (!EnumConstant)
17364     return true;
17365 
17366   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
17367       Enum)
17368     return true;
17369 
17370   return false;
17371 }
17372 
17373 // Emits a warning when an element is implicitly set a value that
17374 // a previous element has already been set to.
17375 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
17376                                         EnumDecl *Enum, QualType EnumType) {
17377   // Avoid anonymous enums
17378   if (!Enum->getIdentifier())
17379     return;
17380 
17381   // Only check for small enums.
17382   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
17383     return;
17384 
17385   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
17386     return;
17387 
17388   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
17389   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
17390 
17391   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
17392   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
17393 
17394   // Use int64_t as a key to avoid needing special handling for DenseMap keys.
17395   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
17396     llvm::APSInt Val = D->getInitVal();
17397     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
17398   };
17399 
17400   DuplicatesVector DupVector;
17401   ValueToVectorMap EnumMap;
17402 
17403   // Populate the EnumMap with all values represented by enum constants without
17404   // an initializer.
17405   for (auto *Element : Elements) {
17406     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
17407 
17408     // Null EnumConstantDecl means a previous diagnostic has been emitted for
17409     // this constant.  Skip this enum since it may be ill-formed.
17410     if (!ECD) {
17411       return;
17412     }
17413 
17414     // Constants with initalizers are handled in the next loop.
17415     if (ECD->getInitExpr())
17416       continue;
17417 
17418     // Duplicate values are handled in the next loop.
17419     EnumMap.insert({EnumConstantToKey(ECD), ECD});
17420   }
17421 
17422   if (EnumMap.size() == 0)
17423     return;
17424 
17425   // Create vectors for any values that has duplicates.
17426   for (auto *Element : Elements) {
17427     // The last loop returned if any constant was null.
17428     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
17429     if (!ValidDuplicateEnum(ECD, Enum))
17430       continue;
17431 
17432     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
17433     if (Iter == EnumMap.end())
17434       continue;
17435 
17436     DeclOrVector& Entry = Iter->second;
17437     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
17438       // Ensure constants are different.
17439       if (D == ECD)
17440         continue;
17441 
17442       // Create new vector and push values onto it.
17443       auto Vec = std::make_unique<ECDVector>();
17444       Vec->push_back(D);
17445       Vec->push_back(ECD);
17446 
17447       // Update entry to point to the duplicates vector.
17448       Entry = Vec.get();
17449 
17450       // Store the vector somewhere we can consult later for quick emission of
17451       // diagnostics.
17452       DupVector.emplace_back(std::move(Vec));
17453       continue;
17454     }
17455 
17456     ECDVector *Vec = Entry.get<ECDVector*>();
17457     // Make sure constants are not added more than once.
17458     if (*Vec->begin() == ECD)
17459       continue;
17460 
17461     Vec->push_back(ECD);
17462   }
17463 
17464   // Emit diagnostics.
17465   for (const auto &Vec : DupVector) {
17466     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
17467 
17468     // Emit warning for one enum constant.
17469     auto *FirstECD = Vec->front();
17470     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
17471       << FirstECD << FirstECD->getInitVal().toString(10)
17472       << FirstECD->getSourceRange();
17473 
17474     // Emit one note for each of the remaining enum constants with
17475     // the same value.
17476     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
17477       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
17478         << ECD << ECD->getInitVal().toString(10)
17479         << ECD->getSourceRange();
17480   }
17481 }
17482 
17483 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
17484                              bool AllowMask) const {
17485   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
17486   assert(ED->isCompleteDefinition() && "expected enum definition");
17487 
17488   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
17489   llvm::APInt &FlagBits = R.first->second;
17490 
17491   if (R.second) {
17492     for (auto *E : ED->enumerators()) {
17493       const auto &EVal = E->getInitVal();
17494       // Only single-bit enumerators introduce new flag values.
17495       if (EVal.isPowerOf2())
17496         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
17497     }
17498   }
17499 
17500   // A value is in a flag enum if either its bits are a subset of the enum's
17501   // flag bits (the first condition) or we are allowing masks and the same is
17502   // true of its complement (the second condition). When masks are allowed, we
17503   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
17504   //
17505   // While it's true that any value could be used as a mask, the assumption is
17506   // that a mask will have all of the insignificant bits set. Anything else is
17507   // likely a logic error.
17508   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
17509   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
17510 }
17511 
17512 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
17513                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
17514                          const ParsedAttributesView &Attrs) {
17515   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
17516   QualType EnumType = Context.getTypeDeclType(Enum);
17517 
17518   ProcessDeclAttributeList(S, Enum, Attrs);
17519 
17520   if (Enum->isDependentType()) {
17521     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17522       EnumConstantDecl *ECD =
17523         cast_or_null<EnumConstantDecl>(Elements[i]);
17524       if (!ECD) continue;
17525 
17526       ECD->setType(EnumType);
17527     }
17528 
17529     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
17530     return;
17531   }
17532 
17533   // TODO: If the result value doesn't fit in an int, it must be a long or long
17534   // long value.  ISO C does not support this, but GCC does as an extension,
17535   // emit a warning.
17536   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17537   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
17538   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
17539 
17540   // Verify that all the values are okay, compute the size of the values, and
17541   // reverse the list.
17542   unsigned NumNegativeBits = 0;
17543   unsigned NumPositiveBits = 0;
17544 
17545   // Keep track of whether all elements have type int.
17546   bool AllElementsInt = true;
17547 
17548   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17549     EnumConstantDecl *ECD =
17550       cast_or_null<EnumConstantDecl>(Elements[i]);
17551     if (!ECD) continue;  // Already issued a diagnostic.
17552 
17553     const llvm::APSInt &InitVal = ECD->getInitVal();
17554 
17555     // Keep track of the size of positive and negative values.
17556     if (InitVal.isUnsigned() || InitVal.isNonNegative())
17557       NumPositiveBits = std::max(NumPositiveBits,
17558                                  (unsigned)InitVal.getActiveBits());
17559     else
17560       NumNegativeBits = std::max(NumNegativeBits,
17561                                  (unsigned)InitVal.getMinSignedBits());
17562 
17563     // Keep track of whether every enum element has type int (very common).
17564     if (AllElementsInt)
17565       AllElementsInt = ECD->getType() == Context.IntTy;
17566   }
17567 
17568   // Figure out the type that should be used for this enum.
17569   QualType BestType;
17570   unsigned BestWidth;
17571 
17572   // C++0x N3000 [conv.prom]p3:
17573   //   An rvalue of an unscoped enumeration type whose underlying
17574   //   type is not fixed can be converted to an rvalue of the first
17575   //   of the following types that can represent all the values of
17576   //   the enumeration: int, unsigned int, long int, unsigned long
17577   //   int, long long int, or unsigned long long int.
17578   // C99 6.4.4.3p2:
17579   //   An identifier declared as an enumeration constant has type int.
17580   // The C99 rule is modified by a gcc extension
17581   QualType BestPromotionType;
17582 
17583   bool Packed = Enum->hasAttr<PackedAttr>();
17584   // -fshort-enums is the equivalent to specifying the packed attribute on all
17585   // enum definitions.
17586   if (LangOpts.ShortEnums)
17587     Packed = true;
17588 
17589   // If the enum already has a type because it is fixed or dictated by the
17590   // target, promote that type instead of analyzing the enumerators.
17591   if (Enum->isComplete()) {
17592     BestType = Enum->getIntegerType();
17593     if (BestType->isPromotableIntegerType())
17594       BestPromotionType = Context.getPromotedIntegerType(BestType);
17595     else
17596       BestPromotionType = BestType;
17597 
17598     BestWidth = Context.getIntWidth(BestType);
17599   }
17600   else if (NumNegativeBits) {
17601     // If there is a negative value, figure out the smallest integer type (of
17602     // int/long/longlong) that fits.
17603     // If it's packed, check also if it fits a char or a short.
17604     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
17605       BestType = Context.SignedCharTy;
17606       BestWidth = CharWidth;
17607     } else if (Packed && NumNegativeBits <= ShortWidth &&
17608                NumPositiveBits < ShortWidth) {
17609       BestType = Context.ShortTy;
17610       BestWidth = ShortWidth;
17611     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
17612       BestType = Context.IntTy;
17613       BestWidth = IntWidth;
17614     } else {
17615       BestWidth = Context.getTargetInfo().getLongWidth();
17616 
17617       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
17618         BestType = Context.LongTy;
17619       } else {
17620         BestWidth = Context.getTargetInfo().getLongLongWidth();
17621 
17622         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
17623           Diag(Enum->getLocation(), diag::ext_enum_too_large);
17624         BestType = Context.LongLongTy;
17625       }
17626     }
17627     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
17628   } else {
17629     // If there is no negative value, figure out the smallest type that fits
17630     // all of the enumerator values.
17631     // If it's packed, check also if it fits a char or a short.
17632     if (Packed && NumPositiveBits <= CharWidth) {
17633       BestType = Context.UnsignedCharTy;
17634       BestPromotionType = Context.IntTy;
17635       BestWidth = CharWidth;
17636     } else if (Packed && NumPositiveBits <= ShortWidth) {
17637       BestType = Context.UnsignedShortTy;
17638       BestPromotionType = Context.IntTy;
17639       BestWidth = ShortWidth;
17640     } else if (NumPositiveBits <= IntWidth) {
17641       BestType = Context.UnsignedIntTy;
17642       BestWidth = IntWidth;
17643       BestPromotionType
17644         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17645                            ? Context.UnsignedIntTy : Context.IntTy;
17646     } else if (NumPositiveBits <=
17647                (BestWidth = Context.getTargetInfo().getLongWidth())) {
17648       BestType = Context.UnsignedLongTy;
17649       BestPromotionType
17650         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17651                            ? Context.UnsignedLongTy : Context.LongTy;
17652     } else {
17653       BestWidth = Context.getTargetInfo().getLongLongWidth();
17654       assert(NumPositiveBits <= BestWidth &&
17655              "How could an initializer get larger than ULL?");
17656       BestType = Context.UnsignedLongLongTy;
17657       BestPromotionType
17658         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17659                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
17660     }
17661   }
17662 
17663   // Loop over all of the enumerator constants, changing their types to match
17664   // the type of the enum if needed.
17665   for (auto *D : Elements) {
17666     auto *ECD = cast_or_null<EnumConstantDecl>(D);
17667     if (!ECD) continue;  // Already issued a diagnostic.
17668 
17669     // Standard C says the enumerators have int type, but we allow, as an
17670     // extension, the enumerators to be larger than int size.  If each
17671     // enumerator value fits in an int, type it as an int, otherwise type it the
17672     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
17673     // that X has type 'int', not 'unsigned'.
17674 
17675     // Determine whether the value fits into an int.
17676     llvm::APSInt InitVal = ECD->getInitVal();
17677 
17678     // If it fits into an integer type, force it.  Otherwise force it to match
17679     // the enum decl type.
17680     QualType NewTy;
17681     unsigned NewWidth;
17682     bool NewSign;
17683     if (!getLangOpts().CPlusPlus &&
17684         !Enum->isFixed() &&
17685         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
17686       NewTy = Context.IntTy;
17687       NewWidth = IntWidth;
17688       NewSign = true;
17689     } else if (ECD->getType() == BestType) {
17690       // Already the right type!
17691       if (getLangOpts().CPlusPlus)
17692         // C++ [dcl.enum]p4: Following the closing brace of an
17693         // enum-specifier, each enumerator has the type of its
17694         // enumeration.
17695         ECD->setType(EnumType);
17696       continue;
17697     } else {
17698       NewTy = BestType;
17699       NewWidth = BestWidth;
17700       NewSign = BestType->isSignedIntegerOrEnumerationType();
17701     }
17702 
17703     // Adjust the APSInt value.
17704     InitVal = InitVal.extOrTrunc(NewWidth);
17705     InitVal.setIsSigned(NewSign);
17706     ECD->setInitVal(InitVal);
17707 
17708     // Adjust the Expr initializer and type.
17709     if (ECD->getInitExpr() &&
17710         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
17711       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
17712                                                 CK_IntegralCast,
17713                                                 ECD->getInitExpr(),
17714                                                 /*base paths*/ nullptr,
17715                                                 VK_RValue));
17716     if (getLangOpts().CPlusPlus)
17717       // C++ [dcl.enum]p4: Following the closing brace of an
17718       // enum-specifier, each enumerator has the type of its
17719       // enumeration.
17720       ECD->setType(EnumType);
17721     else
17722       ECD->setType(NewTy);
17723   }
17724 
17725   Enum->completeDefinition(BestType, BestPromotionType,
17726                            NumPositiveBits, NumNegativeBits);
17727 
17728   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
17729 
17730   if (Enum->isClosedFlag()) {
17731     for (Decl *D : Elements) {
17732       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
17733       if (!ECD) continue;  // Already issued a diagnostic.
17734 
17735       llvm::APSInt InitVal = ECD->getInitVal();
17736       if (InitVal != 0 && !InitVal.isPowerOf2() &&
17737           !IsValueInFlagEnum(Enum, InitVal, true))
17738         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
17739           << ECD << Enum;
17740     }
17741   }
17742 
17743   // Now that the enum type is defined, ensure it's not been underaligned.
17744   if (Enum->hasAttrs())
17745     CheckAlignasUnderalignment(Enum);
17746 }
17747 
17748 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
17749                                   SourceLocation StartLoc,
17750                                   SourceLocation EndLoc) {
17751   StringLiteral *AsmString = cast<StringLiteral>(expr);
17752 
17753   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
17754                                                    AsmString, StartLoc,
17755                                                    EndLoc);
17756   CurContext->addDecl(New);
17757   return New;
17758 }
17759 
17760 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
17761                                       IdentifierInfo* AliasName,
17762                                       SourceLocation PragmaLoc,
17763                                       SourceLocation NameLoc,
17764                                       SourceLocation AliasNameLoc) {
17765   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
17766                                          LookupOrdinaryName);
17767   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
17768                            AttributeCommonInfo::AS_Pragma);
17769   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
17770       Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
17771 
17772   // If a declaration that:
17773   // 1) declares a function or a variable
17774   // 2) has external linkage
17775   // already exists, add a label attribute to it.
17776   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17777     if (isDeclExternC(PrevDecl))
17778       PrevDecl->addAttr(Attr);
17779     else
17780       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
17781           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
17782   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
17783   } else
17784     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
17785 }
17786 
17787 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
17788                              SourceLocation PragmaLoc,
17789                              SourceLocation NameLoc) {
17790   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
17791 
17792   if (PrevDecl) {
17793     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
17794   } else {
17795     (void)WeakUndeclaredIdentifiers.insert(
17796       std::pair<IdentifierInfo*,WeakInfo>
17797         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
17798   }
17799 }
17800 
17801 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
17802                                 IdentifierInfo* AliasName,
17803                                 SourceLocation PragmaLoc,
17804                                 SourceLocation NameLoc,
17805                                 SourceLocation AliasNameLoc) {
17806   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
17807                                     LookupOrdinaryName);
17808   WeakInfo W = WeakInfo(Name, NameLoc);
17809 
17810   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17811     if (!PrevDecl->hasAttr<AliasAttr>())
17812       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
17813         DeclApplyPragmaWeak(TUScope, ND, W);
17814   } else {
17815     (void)WeakUndeclaredIdentifiers.insert(
17816       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
17817   }
17818 }
17819 
17820 Decl *Sema::getObjCDeclContext() const {
17821   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
17822 }
17823 
17824 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD) {
17825   // Templates are emitted when they're instantiated.
17826   if (FD->isDependentContext())
17827     return FunctionEmissionStatus::TemplateDiscarded;
17828 
17829   FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown;
17830   if (LangOpts.OpenMPIsDevice) {
17831     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
17832         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
17833     if (DevTy.hasValue()) {
17834       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
17835         OMPES = FunctionEmissionStatus::OMPDiscarded;
17836       else if (DeviceKnownEmittedFns.count(FD) > 0)
17837         OMPES = FunctionEmissionStatus::Emitted;
17838     }
17839   } else if (LangOpts.OpenMP) {
17840     // In OpenMP 4.5 all the functions are host functions.
17841     if (LangOpts.OpenMP <= 45) {
17842       OMPES = FunctionEmissionStatus::Emitted;
17843     } else {
17844       Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
17845           OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
17846       // In OpenMP 5.0 or above, DevTy may be changed later by
17847       // #pragma omp declare target to(*) device_type(*). Therefore DevTy
17848       // having no value does not imply host. The emission status will be
17849       // checked again at the end of compilation unit.
17850       if (DevTy.hasValue()) {
17851         if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
17852           OMPES = FunctionEmissionStatus::OMPDiscarded;
17853         } else if (DeviceKnownEmittedFns.count(FD) > 0) {
17854           OMPES = FunctionEmissionStatus::Emitted;
17855         }
17856       }
17857     }
17858   }
17859   if (OMPES == FunctionEmissionStatus::OMPDiscarded ||
17860       (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA))
17861     return OMPES;
17862 
17863   if (LangOpts.CUDA) {
17864     // When compiling for device, host functions are never emitted.  Similarly,
17865     // when compiling for host, device and global functions are never emitted.
17866     // (Technically, we do emit a host-side stub for global functions, but this
17867     // doesn't count for our purposes here.)
17868     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
17869     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
17870       return FunctionEmissionStatus::CUDADiscarded;
17871     if (!LangOpts.CUDAIsDevice &&
17872         (T == Sema::CFT_Device || T == Sema::CFT_Global))
17873       return FunctionEmissionStatus::CUDADiscarded;
17874 
17875     // Check whether this function is externally visible -- if so, it's
17876     // known-emitted.
17877     //
17878     // We have to check the GVA linkage of the function's *definition* -- if we
17879     // only have a declaration, we don't know whether or not the function will
17880     // be emitted, because (say) the definition could include "inline".
17881     FunctionDecl *Def = FD->getDefinition();
17882 
17883     if (Def &&
17884         !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def))
17885         && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted))
17886       return FunctionEmissionStatus::Emitted;
17887   }
17888 
17889   // Otherwise, the function is known-emitted if it's in our set of
17890   // known-emitted functions.
17891   return (DeviceKnownEmittedFns.count(FD) > 0)
17892              ? FunctionEmissionStatus::Emitted
17893              : FunctionEmissionStatus::Unknown;
17894 }
17895 
17896 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
17897   // Host-side references to a __global__ function refer to the stub, so the
17898   // function itself is never emitted and therefore should not be marked.
17899   // If we have host fn calls kernel fn calls host+device, the HD function
17900   // does not get instantiated on the host. We model this by omitting at the
17901   // call to the kernel from the callgraph. This ensures that, when compiling
17902   // for host, only HD functions actually called from the host get marked as
17903   // known-emitted.
17904   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
17905          IdentifyCUDATarget(Callee) == CFT_Global;
17906 }
17907