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   // We can have a type template here if we're classifying a template argument.
1157   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1158       !isa<VarTemplateDecl>(FirstDecl))
1159     return NameClassification::TypeTemplate(
1160         TemplateName(cast<TemplateDecl>(FirstDecl)));
1161 
1162   // Check for a tag type hidden by a non-type decl in a few cases where it
1163   // seems likely a type is wanted instead of the non-type that was found.
1164   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1165   if ((NextToken.is(tok::identifier) ||
1166        (NextIsOp &&
1167         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1168       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1169     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1170     DiagnoseUseOfDecl(Type, NameLoc);
1171     QualType T = Context.getTypeDeclType(Type);
1172     if (SS.isNotEmpty())
1173       return buildNestedType(*this, SS, T, NameLoc);
1174     return ParsedType::make(T);
1175   }
1176 
1177   // FIXME: This is context-dependent. We need to defer building the member
1178   // expression until the classification is consumed.
1179   if (FirstDecl->isCXXClassMember())
1180     return NameClassification::ContextIndependentExpr(
1181         BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, nullptr,
1182                                         S));
1183 
1184   // If we already know which single declaration is referenced, just annotate
1185   // that declaration directly.
1186   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1187   if (Result.isSingleResult() && !ADL)
1188     return NameClassification::NonType(Result.getRepresentativeDecl());
1189 
1190   // Build an UnresolvedLookupExpr. Note that this doesn't depend on the
1191   // context in which we performed classification, so it's safe to do now.
1192   return NameClassification::ContextIndependentExpr(
1193       BuildDeclarationNameExpr(SS, Result, ADL));
1194 }
1195 
1196 ExprResult
1197 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1198                                              SourceLocation NameLoc) {
1199   assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1200   CXXScopeSpec SS;
1201   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1202   return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1203 }
1204 
1205 ExprResult
1206 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1207                                             IdentifierInfo *Name,
1208                                             SourceLocation NameLoc,
1209                                             bool IsAddressOfOperand) {
1210   DeclarationNameInfo NameInfo(Name, NameLoc);
1211   return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1212                                     NameInfo, IsAddressOfOperand,
1213                                     /*TemplateArgs=*/nullptr);
1214 }
1215 
1216 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1217                                               NamedDecl *Found,
1218                                               SourceLocation NameLoc,
1219                                               const Token &NextToken) {
1220   if (getCurMethodDecl() && SS.isEmpty())
1221     if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1222       return BuildIvarRefExpr(S, NameLoc, Ivar);
1223 
1224   // Reconstruct the lookup result.
1225   LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1226   Result.addDecl(Found);
1227   Result.resolveKind();
1228 
1229   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1230   return BuildDeclarationNameExpr(SS, Result, ADL);
1231 }
1232 
1233 Sema::TemplateNameKindForDiagnostics
1234 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1235   auto *TD = Name.getAsTemplateDecl();
1236   if (!TD)
1237     return TemplateNameKindForDiagnostics::DependentTemplate;
1238   if (isa<ClassTemplateDecl>(TD))
1239     return TemplateNameKindForDiagnostics::ClassTemplate;
1240   if (isa<FunctionTemplateDecl>(TD))
1241     return TemplateNameKindForDiagnostics::FunctionTemplate;
1242   if (isa<VarTemplateDecl>(TD))
1243     return TemplateNameKindForDiagnostics::VarTemplate;
1244   if (isa<TypeAliasTemplateDecl>(TD))
1245     return TemplateNameKindForDiagnostics::AliasTemplate;
1246   if (isa<TemplateTemplateParmDecl>(TD))
1247     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1248   if (isa<ConceptDecl>(TD))
1249     return TemplateNameKindForDiagnostics::Concept;
1250   return TemplateNameKindForDiagnostics::DependentTemplate;
1251 }
1252 
1253 // Determines the context to return to after temporarily entering a
1254 // context.  This depends in an unnecessarily complicated way on the
1255 // exact ordering of callbacks from the parser.
1256 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1257 
1258   // Functions defined inline within classes aren't parsed until we've
1259   // finished parsing the top-level class, so the top-level class is
1260   // the context we'll need to return to.
1261   // A Lambda call operator whose parent is a class must not be treated
1262   // as an inline member function.  A Lambda can be used legally
1263   // either as an in-class member initializer or a default argument.  These
1264   // are parsed once the class has been marked complete and so the containing
1265   // context would be the nested class (when the lambda is defined in one);
1266   // If the class is not complete, then the lambda is being used in an
1267   // ill-formed fashion (such as to specify the width of a bit-field, or
1268   // in an array-bound) - in which case we still want to return the
1269   // lexically containing DC (which could be a nested class).
1270   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1271     DC = DC->getLexicalParent();
1272 
1273     // A function not defined within a class will always return to its
1274     // lexical context.
1275     if (!isa<CXXRecordDecl>(DC))
1276       return DC;
1277 
1278     // A C++ inline method/friend is parsed *after* the topmost class
1279     // it was declared in is fully parsed ("complete");  the topmost
1280     // class is the context we need to return to.
1281     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1282       DC = RD;
1283 
1284     // Return the declaration context of the topmost class the inline method is
1285     // declared in.
1286     return DC;
1287   }
1288 
1289   return DC->getLexicalParent();
1290 }
1291 
1292 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1293   assert(getContainingDC(DC) == CurContext &&
1294       "The next DeclContext should be lexically contained in the current one.");
1295   CurContext = DC;
1296   S->setEntity(DC);
1297 }
1298 
1299 void Sema::PopDeclContext() {
1300   assert(CurContext && "DeclContext imbalance!");
1301 
1302   CurContext = getContainingDC(CurContext);
1303   assert(CurContext && "Popped translation unit!");
1304 }
1305 
1306 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1307                                                                     Decl *D) {
1308   // Unlike PushDeclContext, the context to which we return is not necessarily
1309   // the containing DC of TD, because the new context will be some pre-existing
1310   // TagDecl definition instead of a fresh one.
1311   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1312   CurContext = cast<TagDecl>(D)->getDefinition();
1313   assert(CurContext && "skipping definition of undefined tag");
1314   // Start lookups from the parent of the current context; we don't want to look
1315   // into the pre-existing complete definition.
1316   S->setEntity(CurContext->getLookupParent());
1317   return Result;
1318 }
1319 
1320 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1321   CurContext = static_cast<decltype(CurContext)>(Context);
1322 }
1323 
1324 /// EnterDeclaratorContext - Used when we must lookup names in the context
1325 /// of a declarator's nested name specifier.
1326 ///
1327 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1328   // C++0x [basic.lookup.unqual]p13:
1329   //   A name used in the definition of a static data member of class
1330   //   X (after the qualified-id of the static member) is looked up as
1331   //   if the name was used in a member function of X.
1332   // C++0x [basic.lookup.unqual]p14:
1333   //   If a variable member of a namespace is defined outside of the
1334   //   scope of its namespace then any name used in the definition of
1335   //   the variable member (after the declarator-id) is looked up as
1336   //   if the definition of the variable member occurred in its
1337   //   namespace.
1338   // Both of these imply that we should push a scope whose context
1339   // is the semantic context of the declaration.  We can't use
1340   // PushDeclContext here because that context is not necessarily
1341   // lexically contained in the current context.  Fortunately,
1342   // the containing scope should have the appropriate information.
1343 
1344   assert(!S->getEntity() && "scope already has entity");
1345 
1346 #ifndef NDEBUG
1347   Scope *Ancestor = S->getParent();
1348   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1349   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1350 #endif
1351 
1352   CurContext = DC;
1353   S->setEntity(DC);
1354 }
1355 
1356 void Sema::ExitDeclaratorContext(Scope *S) {
1357   assert(S->getEntity() == CurContext && "Context imbalance!");
1358 
1359   // Switch back to the lexical context.  The safety of this is
1360   // enforced by an assert in EnterDeclaratorContext.
1361   Scope *Ancestor = S->getParent();
1362   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1363   CurContext = Ancestor->getEntity();
1364 
1365   // We don't need to do anything with the scope, which is going to
1366   // disappear.
1367 }
1368 
1369 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1370   // We assume that the caller has already called
1371   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1372   FunctionDecl *FD = D->getAsFunction();
1373   if (!FD)
1374     return;
1375 
1376   // Same implementation as PushDeclContext, but enters the context
1377   // from the lexical parent, rather than the top-level class.
1378   assert(CurContext == FD->getLexicalParent() &&
1379     "The next DeclContext should be lexically contained in the current one.");
1380   CurContext = FD;
1381   S->setEntity(CurContext);
1382 
1383   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1384     ParmVarDecl *Param = FD->getParamDecl(P);
1385     // If the parameter has an identifier, then add it to the scope
1386     if (Param->getIdentifier()) {
1387       S->AddDecl(Param);
1388       IdResolver.AddDecl(Param);
1389     }
1390   }
1391 }
1392 
1393 void Sema::ActOnExitFunctionContext() {
1394   // Same implementation as PopDeclContext, but returns to the lexical parent,
1395   // rather than the top-level class.
1396   assert(CurContext && "DeclContext imbalance!");
1397   CurContext = CurContext->getLexicalParent();
1398   assert(CurContext && "Popped translation unit!");
1399 }
1400 
1401 /// Determine whether we allow overloading of the function
1402 /// PrevDecl with another declaration.
1403 ///
1404 /// This routine determines whether overloading is possible, not
1405 /// whether some new function is actually an overload. It will return
1406 /// true in C++ (where we can always provide overloads) or, as an
1407 /// extension, in C when the previous function is already an
1408 /// overloaded function declaration or has the "overloadable"
1409 /// attribute.
1410 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1411                                        ASTContext &Context,
1412                                        const FunctionDecl *New) {
1413   if (Context.getLangOpts().CPlusPlus)
1414     return true;
1415 
1416   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1417     return true;
1418 
1419   return Previous.getResultKind() == LookupResult::Found &&
1420          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1421           New->hasAttr<OverloadableAttr>());
1422 }
1423 
1424 /// Add this decl to the scope shadowed decl chains.
1425 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1426   // Move up the scope chain until we find the nearest enclosing
1427   // non-transparent context. The declaration will be introduced into this
1428   // scope.
1429   while (S->getEntity() && S->getEntity()->isTransparentContext())
1430     S = S->getParent();
1431 
1432   // Add scoped declarations into their context, so that they can be
1433   // found later. Declarations without a context won't be inserted
1434   // into any context.
1435   if (AddToContext)
1436     CurContext->addDecl(D);
1437 
1438   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1439   // are function-local declarations.
1440   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1441       !D->getDeclContext()->getRedeclContext()->Equals(
1442         D->getLexicalDeclContext()->getRedeclContext()) &&
1443       !D->getLexicalDeclContext()->isFunctionOrMethod())
1444     return;
1445 
1446   // Template instantiations should also not be pushed into scope.
1447   if (isa<FunctionDecl>(D) &&
1448       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1449     return;
1450 
1451   // If this replaces anything in the current scope,
1452   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1453                                IEnd = IdResolver.end();
1454   for (; I != IEnd; ++I) {
1455     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1456       S->RemoveDecl(*I);
1457       IdResolver.RemoveDecl(*I);
1458 
1459       // Should only need to replace one decl.
1460       break;
1461     }
1462   }
1463 
1464   S->AddDecl(D);
1465 
1466   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1467     // Implicitly-generated labels may end up getting generated in an order that
1468     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1469     // the label at the appropriate place in the identifier chain.
1470     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1471       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1472       if (IDC == CurContext) {
1473         if (!S->isDeclScope(*I))
1474           continue;
1475       } else if (IDC->Encloses(CurContext))
1476         break;
1477     }
1478 
1479     IdResolver.InsertDeclAfter(I, D);
1480   } else {
1481     IdResolver.AddDecl(D);
1482   }
1483 }
1484 
1485 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1486                          bool AllowInlineNamespace) {
1487   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1488 }
1489 
1490 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1491   DeclContext *TargetDC = DC->getPrimaryContext();
1492   do {
1493     if (DeclContext *ScopeDC = S->getEntity())
1494       if (ScopeDC->getPrimaryContext() == TargetDC)
1495         return S;
1496   } while ((S = S->getParent()));
1497 
1498   return nullptr;
1499 }
1500 
1501 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1502                                             DeclContext*,
1503                                             ASTContext&);
1504 
1505 /// Filters out lookup results that don't fall within the given scope
1506 /// as determined by isDeclInScope.
1507 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1508                                 bool ConsiderLinkage,
1509                                 bool AllowInlineNamespace) {
1510   LookupResult::Filter F = R.makeFilter();
1511   while (F.hasNext()) {
1512     NamedDecl *D = F.next();
1513 
1514     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1515       continue;
1516 
1517     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1518       continue;
1519 
1520     F.erase();
1521   }
1522 
1523   F.done();
1524 }
1525 
1526 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1527 /// have compatible owning modules.
1528 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1529   // FIXME: The Modules TS is not clear about how friend declarations are
1530   // to be treated. It's not meaningful to have different owning modules for
1531   // linkage in redeclarations of the same entity, so for now allow the
1532   // redeclaration and change the owning modules to match.
1533   if (New->getFriendObjectKind() &&
1534       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1535     New->setLocalOwningModule(Old->getOwningModule());
1536     makeMergedDefinitionVisible(New);
1537     return false;
1538   }
1539 
1540   Module *NewM = New->getOwningModule();
1541   Module *OldM = Old->getOwningModule();
1542 
1543   if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1544     NewM = NewM->Parent;
1545   if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1546     OldM = OldM->Parent;
1547 
1548   if (NewM == OldM)
1549     return false;
1550 
1551   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1552   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1553   if (NewIsModuleInterface || OldIsModuleInterface) {
1554     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1555     //   if a declaration of D [...] appears in the purview of a module, all
1556     //   other such declarations shall appear in the purview of the same module
1557     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1558       << New
1559       << NewIsModuleInterface
1560       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1561       << OldIsModuleInterface
1562       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1563     Diag(Old->getLocation(), diag::note_previous_declaration);
1564     New->setInvalidDecl();
1565     return true;
1566   }
1567 
1568   return false;
1569 }
1570 
1571 static bool isUsingDecl(NamedDecl *D) {
1572   return isa<UsingShadowDecl>(D) ||
1573          isa<UnresolvedUsingTypenameDecl>(D) ||
1574          isa<UnresolvedUsingValueDecl>(D);
1575 }
1576 
1577 /// Removes using shadow declarations from the lookup results.
1578 static void RemoveUsingDecls(LookupResult &R) {
1579   LookupResult::Filter F = R.makeFilter();
1580   while (F.hasNext())
1581     if (isUsingDecl(F.next()))
1582       F.erase();
1583 
1584   F.done();
1585 }
1586 
1587 /// Check for this common pattern:
1588 /// @code
1589 /// class S {
1590 ///   S(const S&); // DO NOT IMPLEMENT
1591 ///   void operator=(const S&); // DO NOT IMPLEMENT
1592 /// };
1593 /// @endcode
1594 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1595   // FIXME: Should check for private access too but access is set after we get
1596   // the decl here.
1597   if (D->doesThisDeclarationHaveABody())
1598     return false;
1599 
1600   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1601     return CD->isCopyConstructor();
1602   return D->isCopyAssignmentOperator();
1603 }
1604 
1605 // We need this to handle
1606 //
1607 // typedef struct {
1608 //   void *foo() { return 0; }
1609 // } A;
1610 //
1611 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1612 // for example. If 'A', foo will have external linkage. If we have '*A',
1613 // foo will have no linkage. Since we can't know until we get to the end
1614 // of the typedef, this function finds out if D might have non-external linkage.
1615 // Callers should verify at the end of the TU if it D has external linkage or
1616 // not.
1617 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1618   const DeclContext *DC = D->getDeclContext();
1619   while (!DC->isTranslationUnit()) {
1620     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1621       if (!RD->hasNameForLinkage())
1622         return true;
1623     }
1624     DC = DC->getParent();
1625   }
1626 
1627   return !D->isExternallyVisible();
1628 }
1629 
1630 // FIXME: This needs to be refactored; some other isInMainFile users want
1631 // these semantics.
1632 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1633   if (S.TUKind != TU_Complete)
1634     return false;
1635   return S.SourceMgr.isInMainFile(Loc);
1636 }
1637 
1638 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1639   assert(D);
1640 
1641   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1642     return false;
1643 
1644   // Ignore all entities declared within templates, and out-of-line definitions
1645   // of members of class templates.
1646   if (D->getDeclContext()->isDependentContext() ||
1647       D->getLexicalDeclContext()->isDependentContext())
1648     return false;
1649 
1650   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1651     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1652       return false;
1653     // A non-out-of-line declaration of a member specialization was implicitly
1654     // instantiated; it's the out-of-line declaration that we're interested in.
1655     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1656         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1657       return false;
1658 
1659     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1660       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1661         return false;
1662     } else {
1663       // 'static inline' functions are defined in headers; don't warn.
1664       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1665         return false;
1666     }
1667 
1668     if (FD->doesThisDeclarationHaveABody() &&
1669         Context.DeclMustBeEmitted(FD))
1670       return false;
1671   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1672     // Constants and utility variables are defined in headers with internal
1673     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1674     // like "inline".)
1675     if (!isMainFileLoc(*this, VD->getLocation()))
1676       return false;
1677 
1678     if (Context.DeclMustBeEmitted(VD))
1679       return false;
1680 
1681     if (VD->isStaticDataMember() &&
1682         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1683       return false;
1684     if (VD->isStaticDataMember() &&
1685         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1686         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1687       return false;
1688 
1689     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1690       return false;
1691   } else {
1692     return false;
1693   }
1694 
1695   // Only warn for unused decls internal to the translation unit.
1696   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1697   // for inline functions defined in the main source file, for instance.
1698   return mightHaveNonExternalLinkage(D);
1699 }
1700 
1701 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1702   if (!D)
1703     return;
1704 
1705   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1706     const FunctionDecl *First = FD->getFirstDecl();
1707     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1708       return; // First should already be in the vector.
1709   }
1710 
1711   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1712     const VarDecl *First = VD->getFirstDecl();
1713     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1714       return; // First should already be in the vector.
1715   }
1716 
1717   if (ShouldWarnIfUnusedFileScopedDecl(D))
1718     UnusedFileScopedDecls.push_back(D);
1719 }
1720 
1721 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1722   if (D->isInvalidDecl())
1723     return false;
1724 
1725   bool Referenced = false;
1726   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1727     // For a decomposition declaration, warn if none of the bindings are
1728     // referenced, instead of if the variable itself is referenced (which
1729     // it is, by the bindings' expressions).
1730     for (auto *BD : DD->bindings()) {
1731       if (BD->isReferenced()) {
1732         Referenced = true;
1733         break;
1734       }
1735     }
1736   } else if (!D->getDeclName()) {
1737     return false;
1738   } else if (D->isReferenced() || D->isUsed()) {
1739     Referenced = true;
1740   }
1741 
1742   if (Referenced || D->hasAttr<UnusedAttr>() ||
1743       D->hasAttr<ObjCPreciseLifetimeAttr>())
1744     return false;
1745 
1746   if (isa<LabelDecl>(D))
1747     return true;
1748 
1749   // Except for labels, we only care about unused decls that are local to
1750   // functions.
1751   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1752   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1753     // For dependent types, the diagnostic is deferred.
1754     WithinFunction =
1755         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1756   if (!WithinFunction)
1757     return false;
1758 
1759   if (isa<TypedefNameDecl>(D))
1760     return true;
1761 
1762   // White-list anything that isn't a local variable.
1763   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1764     return false;
1765 
1766   // Types of valid local variables should be complete, so this should succeed.
1767   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1768 
1769     // White-list anything with an __attribute__((unused)) type.
1770     const auto *Ty = VD->getType().getTypePtr();
1771 
1772     // Only look at the outermost level of typedef.
1773     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1774       if (TT->getDecl()->hasAttr<UnusedAttr>())
1775         return false;
1776     }
1777 
1778     // If we failed to complete the type for some reason, or if the type is
1779     // dependent, don't diagnose the variable.
1780     if (Ty->isIncompleteType() || Ty->isDependentType())
1781       return false;
1782 
1783     // Look at the element type to ensure that the warning behaviour is
1784     // consistent for both scalars and arrays.
1785     Ty = Ty->getBaseElementTypeUnsafe();
1786 
1787     if (const TagType *TT = Ty->getAs<TagType>()) {
1788       const TagDecl *Tag = TT->getDecl();
1789       if (Tag->hasAttr<UnusedAttr>())
1790         return false;
1791 
1792       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1793         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1794           return false;
1795 
1796         if (const Expr *Init = VD->getInit()) {
1797           if (const ExprWithCleanups *Cleanups =
1798                   dyn_cast<ExprWithCleanups>(Init))
1799             Init = Cleanups->getSubExpr();
1800           const CXXConstructExpr *Construct =
1801             dyn_cast<CXXConstructExpr>(Init);
1802           if (Construct && !Construct->isElidable()) {
1803             CXXConstructorDecl *CD = Construct->getConstructor();
1804             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1805                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1806               return false;
1807           }
1808 
1809           // Suppress the warning if we don't know how this is constructed, and
1810           // it could possibly be non-trivial constructor.
1811           if (Init->isTypeDependent())
1812             for (const CXXConstructorDecl *Ctor : RD->ctors())
1813               if (!Ctor->isTrivial())
1814                 return false;
1815         }
1816       }
1817     }
1818 
1819     // TODO: __attribute__((unused)) templates?
1820   }
1821 
1822   return true;
1823 }
1824 
1825 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1826                                      FixItHint &Hint) {
1827   if (isa<LabelDecl>(D)) {
1828     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1829         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1830         true);
1831     if (AfterColon.isInvalid())
1832       return;
1833     Hint = FixItHint::CreateRemoval(
1834         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1835   }
1836 }
1837 
1838 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1839   if (D->getTypeForDecl()->isDependentType())
1840     return;
1841 
1842   for (auto *TmpD : D->decls()) {
1843     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1844       DiagnoseUnusedDecl(T);
1845     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1846       DiagnoseUnusedNestedTypedefs(R);
1847   }
1848 }
1849 
1850 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1851 /// unless they are marked attr(unused).
1852 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1853   if (!ShouldDiagnoseUnusedDecl(D))
1854     return;
1855 
1856   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1857     // typedefs can be referenced later on, so the diagnostics are emitted
1858     // at end-of-translation-unit.
1859     UnusedLocalTypedefNameCandidates.insert(TD);
1860     return;
1861   }
1862 
1863   FixItHint Hint;
1864   GenerateFixForUnusedDecl(D, Context, Hint);
1865 
1866   unsigned DiagID;
1867   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1868     DiagID = diag::warn_unused_exception_param;
1869   else if (isa<LabelDecl>(D))
1870     DiagID = diag::warn_unused_label;
1871   else
1872     DiagID = diag::warn_unused_variable;
1873 
1874   Diag(D->getLocation(), DiagID) << D << Hint;
1875 }
1876 
1877 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1878   // Verify that we have no forward references left.  If so, there was a goto
1879   // or address of a label taken, but no definition of it.  Label fwd
1880   // definitions are indicated with a null substmt which is also not a resolved
1881   // MS inline assembly label name.
1882   bool Diagnose = false;
1883   if (L->isMSAsmLabel())
1884     Diagnose = !L->isResolvedMSAsmLabel();
1885   else
1886     Diagnose = L->getStmt() == nullptr;
1887   if (Diagnose)
1888     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1889 }
1890 
1891 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1892   S->mergeNRVOIntoParent();
1893 
1894   if (S->decl_empty()) return;
1895   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1896          "Scope shouldn't contain decls!");
1897 
1898   for (auto *TmpD : S->decls()) {
1899     assert(TmpD && "This decl didn't get pushed??");
1900 
1901     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1902     NamedDecl *D = cast<NamedDecl>(TmpD);
1903 
1904     // Diagnose unused variables in this scope.
1905     if (!S->hasUnrecoverableErrorOccurred()) {
1906       DiagnoseUnusedDecl(D);
1907       if (const auto *RD = dyn_cast<RecordDecl>(D))
1908         DiagnoseUnusedNestedTypedefs(RD);
1909     }
1910 
1911     if (!D->getDeclName()) continue;
1912 
1913     // If this was a forward reference to a label, verify it was defined.
1914     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1915       CheckPoppedLabel(LD, *this);
1916 
1917     // Remove this name from our lexical scope, and warn on it if we haven't
1918     // already.
1919     IdResolver.RemoveDecl(D);
1920     auto ShadowI = ShadowingDecls.find(D);
1921     if (ShadowI != ShadowingDecls.end()) {
1922       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1923         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1924             << D << FD << FD->getParent();
1925         Diag(FD->getLocation(), diag::note_previous_declaration);
1926       }
1927       ShadowingDecls.erase(ShadowI);
1928     }
1929   }
1930 }
1931 
1932 /// Look for an Objective-C class in the translation unit.
1933 ///
1934 /// \param Id The name of the Objective-C class we're looking for. If
1935 /// typo-correction fixes this name, the Id will be updated
1936 /// to the fixed name.
1937 ///
1938 /// \param IdLoc The location of the name in the translation unit.
1939 ///
1940 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1941 /// if there is no class with the given name.
1942 ///
1943 /// \returns The declaration of the named Objective-C class, or NULL if the
1944 /// class could not be found.
1945 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1946                                               SourceLocation IdLoc,
1947                                               bool DoTypoCorrection) {
1948   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1949   // creation from this context.
1950   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1951 
1952   if (!IDecl && DoTypoCorrection) {
1953     // Perform typo correction at the given location, but only if we
1954     // find an Objective-C class name.
1955     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
1956     if (TypoCorrection C =
1957             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
1958                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
1959       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1960       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1961       Id = IDecl->getIdentifier();
1962     }
1963   }
1964   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1965   // This routine must always return a class definition, if any.
1966   if (Def && Def->getDefinition())
1967       Def = Def->getDefinition();
1968   return Def;
1969 }
1970 
1971 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1972 /// from S, where a non-field would be declared. This routine copes
1973 /// with the difference between C and C++ scoping rules in structs and
1974 /// unions. For example, the following code is well-formed in C but
1975 /// ill-formed in C++:
1976 /// @code
1977 /// struct S6 {
1978 ///   enum { BAR } e;
1979 /// };
1980 ///
1981 /// void test_S6() {
1982 ///   struct S6 a;
1983 ///   a.e = BAR;
1984 /// }
1985 /// @endcode
1986 /// For the declaration of BAR, this routine will return a different
1987 /// scope. The scope S will be the scope of the unnamed enumeration
1988 /// within S6. In C++, this routine will return the scope associated
1989 /// with S6, because the enumeration's scope is a transparent
1990 /// context but structures can contain non-field names. In C, this
1991 /// routine will return the translation unit scope, since the
1992 /// enumeration's scope is a transparent context and structures cannot
1993 /// contain non-field names.
1994 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1995   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1996          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1997          (S->isClassScope() && !getLangOpts().CPlusPlus))
1998     S = S->getParent();
1999   return S;
2000 }
2001 
2002 /// Looks up the declaration of "struct objc_super" and
2003 /// saves it for later use in building builtin declaration of
2004 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
2005 /// pre-existing declaration exists no action takes place.
2006 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
2007                                         IdentifierInfo *II) {
2008   if (!II->isStr("objc_msgSendSuper"))
2009     return;
2010   ASTContext &Context = ThisSema.Context;
2011 
2012   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
2013                       SourceLocation(), Sema::LookupTagName);
2014   ThisSema.LookupName(Result, S);
2015   if (Result.getResultKind() == LookupResult::Found)
2016     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
2017       Context.setObjCSuperType(Context.getTagDeclType(TD));
2018 }
2019 
2020 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2021                                ASTContext::GetBuiltinTypeError Error) {
2022   switch (Error) {
2023   case ASTContext::GE_None:
2024     return "";
2025   case ASTContext::GE_Missing_type:
2026     return BuiltinInfo.getHeaderName(ID);
2027   case ASTContext::GE_Missing_stdio:
2028     return "stdio.h";
2029   case ASTContext::GE_Missing_setjmp:
2030     return "setjmp.h";
2031   case ASTContext::GE_Missing_ucontext:
2032     return "ucontext.h";
2033   }
2034   llvm_unreachable("unhandled error kind");
2035 }
2036 
2037 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2038 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2039 /// if we're creating this built-in in anticipation of redeclaring the
2040 /// built-in.
2041 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2042                                      Scope *S, bool ForRedeclaration,
2043                                      SourceLocation Loc) {
2044   LookupPredefedObjCSuperType(*this, S, II);
2045 
2046   ASTContext::GetBuiltinTypeError Error;
2047   QualType R = Context.GetBuiltinType(ID, Error);
2048   if (Error) {
2049     if (!ForRedeclaration)
2050       return nullptr;
2051 
2052     // If we have a builtin without an associated type we should not emit a
2053     // warning when we were not able to find a type for it.
2054     if (Error == ASTContext::GE_Missing_type)
2055       return nullptr;
2056 
2057     // If we could not find a type for setjmp it is because the jmp_buf type was
2058     // not defined prior to the setjmp declaration.
2059     if (Error == ASTContext::GE_Missing_setjmp) {
2060       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2061           << Context.BuiltinInfo.getName(ID);
2062       return nullptr;
2063     }
2064 
2065     // Generally, we emit a warning that the declaration requires the
2066     // appropriate header.
2067     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2068         << getHeaderName(Context.BuiltinInfo, ID, Error)
2069         << Context.BuiltinInfo.getName(ID);
2070     return nullptr;
2071   }
2072 
2073   if (!ForRedeclaration &&
2074       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2075        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2076     Diag(Loc, diag::ext_implicit_lib_function_decl)
2077         << Context.BuiltinInfo.getName(ID) << R;
2078     if (Context.BuiltinInfo.getHeaderName(ID) &&
2079         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
2080       Diag(Loc, diag::note_include_header_or_declare)
2081           << Context.BuiltinInfo.getHeaderName(ID)
2082           << Context.BuiltinInfo.getName(ID);
2083   }
2084 
2085   if (R.isNull())
2086     return nullptr;
2087 
2088   DeclContext *Parent = Context.getTranslationUnitDecl();
2089   if (getLangOpts().CPlusPlus) {
2090     LinkageSpecDecl *CLinkageDecl =
2091         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
2092                                 LinkageSpecDecl::lang_c, false);
2093     CLinkageDecl->setImplicit();
2094     Parent->addDecl(CLinkageDecl);
2095     Parent = CLinkageDecl;
2096   }
2097 
2098   FunctionDecl *New = FunctionDecl::Create(Context,
2099                                            Parent,
2100                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
2101                                            SC_Extern,
2102                                            false,
2103                                            R->isFunctionProtoType());
2104   New->setImplicit();
2105 
2106   // Create Decl objects for each parameter, adding them to the
2107   // FunctionDecl.
2108   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
2109     SmallVector<ParmVarDecl*, 16> Params;
2110     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2111       ParmVarDecl *parm =
2112           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2113                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2114                               SC_None, nullptr);
2115       parm->setScopeInfo(0, i);
2116       Params.push_back(parm);
2117     }
2118     New->setParams(Params);
2119   }
2120 
2121   AddKnownFunctionAttributes(New);
2122   RegisterLocallyScopedExternCDecl(New, S);
2123 
2124   // TUScope is the translation-unit scope to insert this function into.
2125   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2126   // relate Scopes to DeclContexts, and probably eliminate CurContext
2127   // entirely, but we're not there yet.
2128   DeclContext *SavedContext = CurContext;
2129   CurContext = Parent;
2130   PushOnScopeChains(New, TUScope);
2131   CurContext = SavedContext;
2132   return New;
2133 }
2134 
2135 /// Typedef declarations don't have linkage, but they still denote the same
2136 /// entity if their types are the same.
2137 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2138 /// isSameEntity.
2139 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2140                                                      TypedefNameDecl *Decl,
2141                                                      LookupResult &Previous) {
2142   // This is only interesting when modules are enabled.
2143   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2144     return;
2145 
2146   // Empty sets are uninteresting.
2147   if (Previous.empty())
2148     return;
2149 
2150   LookupResult::Filter Filter = Previous.makeFilter();
2151   while (Filter.hasNext()) {
2152     NamedDecl *Old = Filter.next();
2153 
2154     // Non-hidden declarations are never ignored.
2155     if (S.isVisible(Old))
2156       continue;
2157 
2158     // Declarations of the same entity are not ignored, even if they have
2159     // different linkages.
2160     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2161       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2162                                 Decl->getUnderlyingType()))
2163         continue;
2164 
2165       // If both declarations give a tag declaration a typedef name for linkage
2166       // purposes, then they declare the same entity.
2167       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2168           Decl->getAnonDeclWithTypedefName())
2169         continue;
2170     }
2171 
2172     Filter.erase();
2173   }
2174 
2175   Filter.done();
2176 }
2177 
2178 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2179   QualType OldType;
2180   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2181     OldType = OldTypedef->getUnderlyingType();
2182   else
2183     OldType = Context.getTypeDeclType(Old);
2184   QualType NewType = New->getUnderlyingType();
2185 
2186   if (NewType->isVariablyModifiedType()) {
2187     // Must not redefine a typedef with a variably-modified type.
2188     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2189     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2190       << Kind << NewType;
2191     if (Old->getLocation().isValid())
2192       notePreviousDefinition(Old, New->getLocation());
2193     New->setInvalidDecl();
2194     return true;
2195   }
2196 
2197   if (OldType != NewType &&
2198       !OldType->isDependentType() &&
2199       !NewType->isDependentType() &&
2200       !Context.hasSameType(OldType, NewType)) {
2201     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2202     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2203       << Kind << NewType << OldType;
2204     if (Old->getLocation().isValid())
2205       notePreviousDefinition(Old, New->getLocation());
2206     New->setInvalidDecl();
2207     return true;
2208   }
2209   return false;
2210 }
2211 
2212 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2213 /// same name and scope as a previous declaration 'Old'.  Figure out
2214 /// how to resolve this situation, merging decls or emitting
2215 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2216 ///
2217 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2218                                 LookupResult &OldDecls) {
2219   // If the new decl is known invalid already, don't bother doing any
2220   // merging checks.
2221   if (New->isInvalidDecl()) return;
2222 
2223   // Allow multiple definitions for ObjC built-in typedefs.
2224   // FIXME: Verify the underlying types are equivalent!
2225   if (getLangOpts().ObjC) {
2226     const IdentifierInfo *TypeID = New->getIdentifier();
2227     switch (TypeID->getLength()) {
2228     default: break;
2229     case 2:
2230       {
2231         if (!TypeID->isStr("id"))
2232           break;
2233         QualType T = New->getUnderlyingType();
2234         if (!T->isPointerType())
2235           break;
2236         if (!T->isVoidPointerType()) {
2237           QualType PT = T->castAs<PointerType>()->getPointeeType();
2238           if (!PT->isStructureType())
2239             break;
2240         }
2241         Context.setObjCIdRedefinitionType(T);
2242         // Install the built-in type for 'id', ignoring the current definition.
2243         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2244         return;
2245       }
2246     case 5:
2247       if (!TypeID->isStr("Class"))
2248         break;
2249       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2250       // Install the built-in type for 'Class', ignoring the current definition.
2251       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2252       return;
2253     case 3:
2254       if (!TypeID->isStr("SEL"))
2255         break;
2256       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2257       // Install the built-in type for 'SEL', ignoring the current definition.
2258       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2259       return;
2260     }
2261     // Fall through - the typedef name was not a builtin type.
2262   }
2263 
2264   // Verify the old decl was also a type.
2265   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2266   if (!Old) {
2267     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2268       << New->getDeclName();
2269 
2270     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2271     if (OldD->getLocation().isValid())
2272       notePreviousDefinition(OldD, New->getLocation());
2273 
2274     return New->setInvalidDecl();
2275   }
2276 
2277   // If the old declaration is invalid, just give up here.
2278   if (Old->isInvalidDecl())
2279     return New->setInvalidDecl();
2280 
2281   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2282     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2283     auto *NewTag = New->getAnonDeclWithTypedefName();
2284     NamedDecl *Hidden = nullptr;
2285     if (OldTag && NewTag &&
2286         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2287         !hasVisibleDefinition(OldTag, &Hidden)) {
2288       // There is a definition of this tag, but it is not visible. Use it
2289       // instead of our tag.
2290       New->setTypeForDecl(OldTD->getTypeForDecl());
2291       if (OldTD->isModed())
2292         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2293                                     OldTD->getUnderlyingType());
2294       else
2295         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2296 
2297       // Make the old tag definition visible.
2298       makeMergedDefinitionVisible(Hidden);
2299 
2300       // If this was an unscoped enumeration, yank all of its enumerators
2301       // out of the scope.
2302       if (isa<EnumDecl>(NewTag)) {
2303         Scope *EnumScope = getNonFieldDeclScope(S);
2304         for (auto *D : NewTag->decls()) {
2305           auto *ED = cast<EnumConstantDecl>(D);
2306           assert(EnumScope->isDeclScope(ED));
2307           EnumScope->RemoveDecl(ED);
2308           IdResolver.RemoveDecl(ED);
2309           ED->getLexicalDeclContext()->removeDecl(ED);
2310         }
2311       }
2312     }
2313   }
2314 
2315   // If the typedef types are not identical, reject them in all languages and
2316   // with any extensions enabled.
2317   if (isIncompatibleTypedef(Old, New))
2318     return;
2319 
2320   // The types match.  Link up the redeclaration chain and merge attributes if
2321   // the old declaration was a typedef.
2322   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2323     New->setPreviousDecl(Typedef);
2324     mergeDeclAttributes(New, Old);
2325   }
2326 
2327   if (getLangOpts().MicrosoftExt)
2328     return;
2329 
2330   if (getLangOpts().CPlusPlus) {
2331     // C++ [dcl.typedef]p2:
2332     //   In a given non-class scope, a typedef specifier can be used to
2333     //   redefine the name of any type declared in that scope to refer
2334     //   to the type to which it already refers.
2335     if (!isa<CXXRecordDecl>(CurContext))
2336       return;
2337 
2338     // C++0x [dcl.typedef]p4:
2339     //   In a given class scope, a typedef specifier can be used to redefine
2340     //   any class-name declared in that scope that is not also a typedef-name
2341     //   to refer to the type to which it already refers.
2342     //
2343     // This wording came in via DR424, which was a correction to the
2344     // wording in DR56, which accidentally banned code like:
2345     //
2346     //   struct S {
2347     //     typedef struct A { } A;
2348     //   };
2349     //
2350     // in the C++03 standard. We implement the C++0x semantics, which
2351     // allow the above but disallow
2352     //
2353     //   struct S {
2354     //     typedef int I;
2355     //     typedef int I;
2356     //   };
2357     //
2358     // since that was the intent of DR56.
2359     if (!isa<TypedefNameDecl>(Old))
2360       return;
2361 
2362     Diag(New->getLocation(), diag::err_redefinition)
2363       << New->getDeclName();
2364     notePreviousDefinition(Old, New->getLocation());
2365     return New->setInvalidDecl();
2366   }
2367 
2368   // Modules always permit redefinition of typedefs, as does C11.
2369   if (getLangOpts().Modules || getLangOpts().C11)
2370     return;
2371 
2372   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2373   // is normally mapped to an error, but can be controlled with
2374   // -Wtypedef-redefinition.  If either the original or the redefinition is
2375   // in a system header, don't emit this for compatibility with GCC.
2376   if (getDiagnostics().getSuppressSystemWarnings() &&
2377       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2378       (Old->isImplicit() ||
2379        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2380        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2381     return;
2382 
2383   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2384     << New->getDeclName();
2385   notePreviousDefinition(Old, New->getLocation());
2386 }
2387 
2388 /// DeclhasAttr - returns true if decl Declaration already has the target
2389 /// attribute.
2390 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2391   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2392   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2393   for (const auto *i : D->attrs())
2394     if (i->getKind() == A->getKind()) {
2395       if (Ann) {
2396         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2397           return true;
2398         continue;
2399       }
2400       // FIXME: Don't hardcode this check
2401       if (OA && isa<OwnershipAttr>(i))
2402         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2403       return true;
2404     }
2405 
2406   return false;
2407 }
2408 
2409 static bool isAttributeTargetADefinition(Decl *D) {
2410   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2411     return VD->isThisDeclarationADefinition();
2412   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2413     return TD->isCompleteDefinition() || TD->isBeingDefined();
2414   return true;
2415 }
2416 
2417 /// Merge alignment attributes from \p Old to \p New, taking into account the
2418 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2419 ///
2420 /// \return \c true if any attributes were added to \p New.
2421 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2422   // Look for alignas attributes on Old, and pick out whichever attribute
2423   // specifies the strictest alignment requirement.
2424   AlignedAttr *OldAlignasAttr = nullptr;
2425   AlignedAttr *OldStrictestAlignAttr = nullptr;
2426   unsigned OldAlign = 0;
2427   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2428     // FIXME: We have no way of representing inherited dependent alignments
2429     // in a case like:
2430     //   template<int A, int B> struct alignas(A) X;
2431     //   template<int A, int B> struct alignas(B) X {};
2432     // For now, we just ignore any alignas attributes which are not on the
2433     // definition in such a case.
2434     if (I->isAlignmentDependent())
2435       return false;
2436 
2437     if (I->isAlignas())
2438       OldAlignasAttr = I;
2439 
2440     unsigned Align = I->getAlignment(S.Context);
2441     if (Align > OldAlign) {
2442       OldAlign = Align;
2443       OldStrictestAlignAttr = I;
2444     }
2445   }
2446 
2447   // Look for alignas attributes on New.
2448   AlignedAttr *NewAlignasAttr = nullptr;
2449   unsigned NewAlign = 0;
2450   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2451     if (I->isAlignmentDependent())
2452       return false;
2453 
2454     if (I->isAlignas())
2455       NewAlignasAttr = I;
2456 
2457     unsigned Align = I->getAlignment(S.Context);
2458     if (Align > NewAlign)
2459       NewAlign = Align;
2460   }
2461 
2462   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2463     // Both declarations have 'alignas' attributes. We require them to match.
2464     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2465     // fall short. (If two declarations both have alignas, they must both match
2466     // every definition, and so must match each other if there is a definition.)
2467 
2468     // If either declaration only contains 'alignas(0)' specifiers, then it
2469     // specifies the natural alignment for the type.
2470     if (OldAlign == 0 || NewAlign == 0) {
2471       QualType Ty;
2472       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2473         Ty = VD->getType();
2474       else
2475         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2476 
2477       if (OldAlign == 0)
2478         OldAlign = S.Context.getTypeAlign(Ty);
2479       if (NewAlign == 0)
2480         NewAlign = S.Context.getTypeAlign(Ty);
2481     }
2482 
2483     if (OldAlign != NewAlign) {
2484       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2485         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2486         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2487       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2488     }
2489   }
2490 
2491   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2492     // C++11 [dcl.align]p6:
2493     //   if any declaration of an entity has an alignment-specifier,
2494     //   every defining declaration of that entity shall specify an
2495     //   equivalent alignment.
2496     // C11 6.7.5/7:
2497     //   If the definition of an object does not have an alignment
2498     //   specifier, any other declaration of that object shall also
2499     //   have no alignment specifier.
2500     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2501       << OldAlignasAttr;
2502     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2503       << OldAlignasAttr;
2504   }
2505 
2506   bool AnyAdded = false;
2507 
2508   // Ensure we have an attribute representing the strictest alignment.
2509   if (OldAlign > NewAlign) {
2510     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2511     Clone->setInherited(true);
2512     New->addAttr(Clone);
2513     AnyAdded = true;
2514   }
2515 
2516   // Ensure we have an alignas attribute if the old declaration had one.
2517   if (OldAlignasAttr && !NewAlignasAttr &&
2518       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2519     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2520     Clone->setInherited(true);
2521     New->addAttr(Clone);
2522     AnyAdded = true;
2523   }
2524 
2525   return AnyAdded;
2526 }
2527 
2528 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2529                                const InheritableAttr *Attr,
2530                                Sema::AvailabilityMergeKind AMK) {
2531   // This function copies an attribute Attr from a previous declaration to the
2532   // new declaration D if the new declaration doesn't itself have that attribute
2533   // yet or if that attribute allows duplicates.
2534   // If you're adding a new attribute that requires logic different from
2535   // "use explicit attribute on decl if present, else use attribute from
2536   // previous decl", for example if the attribute needs to be consistent
2537   // between redeclarations, you need to call a custom merge function here.
2538   InheritableAttr *NewAttr = nullptr;
2539   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2540     NewAttr = S.mergeAvailabilityAttr(
2541         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2542         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2543         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2544         AA->getPriority());
2545   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2546     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2547   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2548     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2549   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2550     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2551   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2552     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2553   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2554     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2555                                 FA->getFirstArg());
2556   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2557     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2558   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2559     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2560   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2561     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2562                                        IA->getInheritanceModel());
2563   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2564     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2565                                       &S.Context.Idents.get(AA->getSpelling()));
2566   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2567            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2568             isa<CUDAGlobalAttr>(Attr))) {
2569     // CUDA target attributes are part of function signature for
2570     // overloading purposes and must not be merged.
2571     return false;
2572   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2573     NewAttr = S.mergeMinSizeAttr(D, *MA);
2574   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2575     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2576   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2577     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2578   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2579     NewAttr = S.mergeCommonAttr(D, *CommonA);
2580   else if (isa<AlignedAttr>(Attr))
2581     // AlignedAttrs are handled separately, because we need to handle all
2582     // such attributes on a declaration at the same time.
2583     NewAttr = nullptr;
2584   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2585            (AMK == Sema::AMK_Override ||
2586             AMK == Sema::AMK_ProtocolImplementation))
2587     NewAttr = nullptr;
2588   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2589     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid());
2590   else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
2591     NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
2592   else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
2593     NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
2594   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2595     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2596 
2597   if (NewAttr) {
2598     NewAttr->setInherited(true);
2599     D->addAttr(NewAttr);
2600     if (isa<MSInheritanceAttr>(NewAttr))
2601       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2602     return true;
2603   }
2604 
2605   return false;
2606 }
2607 
2608 static const NamedDecl *getDefinition(const Decl *D) {
2609   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2610     return TD->getDefinition();
2611   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2612     const VarDecl *Def = VD->getDefinition();
2613     if (Def)
2614       return Def;
2615     return VD->getActingDefinition();
2616   }
2617   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2618     return FD->getDefinition();
2619   return nullptr;
2620 }
2621 
2622 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2623   for (const auto *Attribute : D->attrs())
2624     if (Attribute->getKind() == Kind)
2625       return true;
2626   return false;
2627 }
2628 
2629 /// checkNewAttributesAfterDef - If we already have a definition, check that
2630 /// there are no new attributes in this declaration.
2631 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2632   if (!New->hasAttrs())
2633     return;
2634 
2635   const NamedDecl *Def = getDefinition(Old);
2636   if (!Def || Def == New)
2637     return;
2638 
2639   AttrVec &NewAttributes = New->getAttrs();
2640   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2641     const Attr *NewAttribute = NewAttributes[I];
2642 
2643     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2644       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2645         Sema::SkipBodyInfo SkipBody;
2646         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2647 
2648         // If we're skipping this definition, drop the "alias" attribute.
2649         if (SkipBody.ShouldSkip) {
2650           NewAttributes.erase(NewAttributes.begin() + I);
2651           --E;
2652           continue;
2653         }
2654       } else {
2655         VarDecl *VD = cast<VarDecl>(New);
2656         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2657                                 VarDecl::TentativeDefinition
2658                             ? diag::err_alias_after_tentative
2659                             : diag::err_redefinition;
2660         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2661         if (Diag == diag::err_redefinition)
2662           S.notePreviousDefinition(Def, VD->getLocation());
2663         else
2664           S.Diag(Def->getLocation(), diag::note_previous_definition);
2665         VD->setInvalidDecl();
2666       }
2667       ++I;
2668       continue;
2669     }
2670 
2671     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2672       // Tentative definitions are only interesting for the alias check above.
2673       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2674         ++I;
2675         continue;
2676       }
2677     }
2678 
2679     if (hasAttribute(Def, NewAttribute->getKind())) {
2680       ++I;
2681       continue; // regular attr merging will take care of validating this.
2682     }
2683 
2684     if (isa<C11NoReturnAttr>(NewAttribute)) {
2685       // C's _Noreturn is allowed to be added to a function after it is defined.
2686       ++I;
2687       continue;
2688     } else if (isa<UuidAttr>(NewAttribute)) {
2689       // msvc will allow a subsequent definition to add an uuid to a class
2690       ++I;
2691       continue;
2692     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2693       if (AA->isAlignas()) {
2694         // C++11 [dcl.align]p6:
2695         //   if any declaration of an entity has an alignment-specifier,
2696         //   every defining declaration of that entity shall specify an
2697         //   equivalent alignment.
2698         // C11 6.7.5/7:
2699         //   If the definition of an object does not have an alignment
2700         //   specifier, any other declaration of that object shall also
2701         //   have no alignment specifier.
2702         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2703           << AA;
2704         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2705           << AA;
2706         NewAttributes.erase(NewAttributes.begin() + I);
2707         --E;
2708         continue;
2709       }
2710     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2711                cast<VarDecl>(New)->isInline() &&
2712                !cast<VarDecl>(New)->isInlineSpecified()) {
2713       // Don't warn about applying selectany to implicitly inline variables.
2714       // Older compilers and language modes would require the use of selectany
2715       // to make such variables inline, and it would have no effect if we
2716       // honored it.
2717       ++I;
2718       continue;
2719     }
2720 
2721     S.Diag(NewAttribute->getLocation(),
2722            diag::warn_attribute_precede_definition);
2723     S.Diag(Def->getLocation(), diag::note_previous_definition);
2724     NewAttributes.erase(NewAttributes.begin() + I);
2725     --E;
2726   }
2727 }
2728 
2729 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2730                                      const ConstInitAttr *CIAttr,
2731                                      bool AttrBeforeInit) {
2732   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2733 
2734   // Figure out a good way to write this specifier on the old declaration.
2735   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2736   // enough of the attribute list spelling information to extract that without
2737   // heroics.
2738   std::string SuitableSpelling;
2739   if (S.getLangOpts().CPlusPlus2a)
2740     SuitableSpelling =
2741         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit});
2742   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2743     SuitableSpelling = S.PP.getLastMacroWithSpelling(
2744         InsertLoc,
2745         {tok::l_square, tok::l_square, S.PP.getIdentifierInfo("clang"),
2746          tok::coloncolon,
2747          S.PP.getIdentifierInfo("require_constant_initialization"),
2748          tok::r_square, tok::r_square});
2749   if (SuitableSpelling.empty())
2750     SuitableSpelling = S.PP.getLastMacroWithSpelling(
2751         InsertLoc,
2752         {tok::kw___attribute, tok::l_paren, tok::r_paren,
2753          S.PP.getIdentifierInfo("require_constant_initialization"),
2754          tok::r_paren, tok::r_paren});
2755   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus2a)
2756     SuitableSpelling = "constinit";
2757   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2758     SuitableSpelling = "[[clang::require_constant_initialization]]";
2759   if (SuitableSpelling.empty())
2760     SuitableSpelling = "__attribute__((require_constant_initialization))";
2761   SuitableSpelling += " ";
2762 
2763   if (AttrBeforeInit) {
2764     // extern constinit int a;
2765     // int a = 0; // error (missing 'constinit'), accepted as extension
2766     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
2767     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2768         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2769     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2770   } else {
2771     // int a = 0;
2772     // constinit extern int a; // error (missing 'constinit')
2773     S.Diag(CIAttr->getLocation(),
2774            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2775                                  : diag::warn_require_const_init_added_too_late)
2776         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2777     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2778         << CIAttr->isConstinit()
2779         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2780   }
2781 }
2782 
2783 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2784 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2785                                AvailabilityMergeKind AMK) {
2786   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2787     UsedAttr *NewAttr = OldAttr->clone(Context);
2788     NewAttr->setInherited(true);
2789     New->addAttr(NewAttr);
2790   }
2791 
2792   if (!Old->hasAttrs() && !New->hasAttrs())
2793     return;
2794 
2795   // [dcl.constinit]p1:
2796   //   If the [constinit] specifier is applied to any declaration of a
2797   //   variable, it shall be applied to the initializing declaration.
2798   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2799   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2800   if (bool(OldConstInit) != bool(NewConstInit)) {
2801     const auto *OldVD = cast<VarDecl>(Old);
2802     auto *NewVD = cast<VarDecl>(New);
2803 
2804     // Find the initializing declaration. Note that we might not have linked
2805     // the new declaration into the redeclaration chain yet.
2806     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2807     if (!InitDecl &&
2808         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2809       InitDecl = NewVD;
2810 
2811     if (InitDecl == NewVD) {
2812       // This is the initializing declaration. If it would inherit 'constinit',
2813       // that's ill-formed. (Note that we do not apply this to the attribute
2814       // form).
2815       if (OldConstInit && OldConstInit->isConstinit())
2816         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2817                                  /*AttrBeforeInit=*/true);
2818     } else if (NewConstInit) {
2819       // This is the first time we've been told that this declaration should
2820       // have a constant initializer. If we already saw the initializing
2821       // declaration, this is too late.
2822       if (InitDecl && InitDecl != NewVD) {
2823         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2824                                  /*AttrBeforeInit=*/false);
2825         NewVD->dropAttr<ConstInitAttr>();
2826       }
2827     }
2828   }
2829 
2830   // Attributes declared post-definition are currently ignored.
2831   checkNewAttributesAfterDef(*this, New, Old);
2832 
2833   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2834     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2835       if (!OldA->isEquivalent(NewA)) {
2836         // This redeclaration changes __asm__ label.
2837         Diag(New->getLocation(), diag::err_different_asm_label);
2838         Diag(OldA->getLocation(), diag::note_previous_declaration);
2839       }
2840     } else if (Old->isUsed()) {
2841       // This redeclaration adds an __asm__ label to a declaration that has
2842       // already been ODR-used.
2843       Diag(New->getLocation(), diag::err_late_asm_label_name)
2844         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2845     }
2846   }
2847 
2848   // Re-declaration cannot add abi_tag's.
2849   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2850     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2851       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2852         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2853                       NewTag) == OldAbiTagAttr->tags_end()) {
2854           Diag(NewAbiTagAttr->getLocation(),
2855                diag::err_new_abi_tag_on_redeclaration)
2856               << NewTag;
2857           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2858         }
2859       }
2860     } else {
2861       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2862       Diag(Old->getLocation(), diag::note_previous_declaration);
2863     }
2864   }
2865 
2866   // This redeclaration adds a section attribute.
2867   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2868     if (auto *VD = dyn_cast<VarDecl>(New)) {
2869       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2870         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2871         Diag(Old->getLocation(), diag::note_previous_declaration);
2872       }
2873     }
2874   }
2875 
2876   // Redeclaration adds code-seg attribute.
2877   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2878   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2879       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2880     Diag(New->getLocation(), diag::warn_mismatched_section)
2881          << 0 /*codeseg*/;
2882     Diag(Old->getLocation(), diag::note_previous_declaration);
2883   }
2884 
2885   if (!Old->hasAttrs())
2886     return;
2887 
2888   bool foundAny = New->hasAttrs();
2889 
2890   // Ensure that any moving of objects within the allocated map is done before
2891   // we process them.
2892   if (!foundAny) New->setAttrs(AttrVec());
2893 
2894   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2895     // Ignore deprecated/unavailable/availability attributes if requested.
2896     AvailabilityMergeKind LocalAMK = AMK_None;
2897     if (isa<DeprecatedAttr>(I) ||
2898         isa<UnavailableAttr>(I) ||
2899         isa<AvailabilityAttr>(I)) {
2900       switch (AMK) {
2901       case AMK_None:
2902         continue;
2903 
2904       case AMK_Redeclaration:
2905       case AMK_Override:
2906       case AMK_ProtocolImplementation:
2907         LocalAMK = AMK;
2908         break;
2909       }
2910     }
2911 
2912     // Already handled.
2913     if (isa<UsedAttr>(I))
2914       continue;
2915 
2916     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2917       foundAny = true;
2918   }
2919 
2920   if (mergeAlignedAttrs(*this, New, Old))
2921     foundAny = true;
2922 
2923   if (!foundAny) New->dropAttrs();
2924 }
2925 
2926 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2927 /// to the new one.
2928 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2929                                      const ParmVarDecl *oldDecl,
2930                                      Sema &S) {
2931   // C++11 [dcl.attr.depend]p2:
2932   //   The first declaration of a function shall specify the
2933   //   carries_dependency attribute for its declarator-id if any declaration
2934   //   of the function specifies the carries_dependency attribute.
2935   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2936   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2937     S.Diag(CDA->getLocation(),
2938            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2939     // Find the first declaration of the parameter.
2940     // FIXME: Should we build redeclaration chains for function parameters?
2941     const FunctionDecl *FirstFD =
2942       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2943     const ParmVarDecl *FirstVD =
2944       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2945     S.Diag(FirstVD->getLocation(),
2946            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2947   }
2948 
2949   if (!oldDecl->hasAttrs())
2950     return;
2951 
2952   bool foundAny = newDecl->hasAttrs();
2953 
2954   // Ensure that any moving of objects within the allocated map is
2955   // done before we process them.
2956   if (!foundAny) newDecl->setAttrs(AttrVec());
2957 
2958   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2959     if (!DeclHasAttr(newDecl, I)) {
2960       InheritableAttr *newAttr =
2961         cast<InheritableParamAttr>(I->clone(S.Context));
2962       newAttr->setInherited(true);
2963       newDecl->addAttr(newAttr);
2964       foundAny = true;
2965     }
2966   }
2967 
2968   if (!foundAny) newDecl->dropAttrs();
2969 }
2970 
2971 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2972                                 const ParmVarDecl *OldParam,
2973                                 Sema &S) {
2974   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2975     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2976       if (*Oldnullability != *Newnullability) {
2977         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2978           << DiagNullabilityKind(
2979                *Newnullability,
2980                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2981                 != 0))
2982           << DiagNullabilityKind(
2983                *Oldnullability,
2984                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2985                 != 0));
2986         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2987       }
2988     } else {
2989       QualType NewT = NewParam->getType();
2990       NewT = S.Context.getAttributedType(
2991                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2992                          NewT, NewT);
2993       NewParam->setType(NewT);
2994     }
2995   }
2996 }
2997 
2998 namespace {
2999 
3000 /// Used in MergeFunctionDecl to keep track of function parameters in
3001 /// C.
3002 struct GNUCompatibleParamWarning {
3003   ParmVarDecl *OldParm;
3004   ParmVarDecl *NewParm;
3005   QualType PromotedType;
3006 };
3007 
3008 } // end anonymous namespace
3009 
3010 // Determine whether the previous declaration was a definition, implicit
3011 // declaration, or a declaration.
3012 template <typename T>
3013 static std::pair<diag::kind, SourceLocation>
3014 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3015   diag::kind PrevDiag;
3016   SourceLocation OldLocation = Old->getLocation();
3017   if (Old->isThisDeclarationADefinition())
3018     PrevDiag = diag::note_previous_definition;
3019   else if (Old->isImplicit()) {
3020     PrevDiag = diag::note_previous_implicit_declaration;
3021     if (OldLocation.isInvalid())
3022       OldLocation = New->getLocation();
3023   } else
3024     PrevDiag = diag::note_previous_declaration;
3025   return std::make_pair(PrevDiag, OldLocation);
3026 }
3027 
3028 /// canRedefineFunction - checks if a function can be redefined. Currently,
3029 /// only extern inline functions can be redefined, and even then only in
3030 /// GNU89 mode.
3031 static bool canRedefineFunction(const FunctionDecl *FD,
3032                                 const LangOptions& LangOpts) {
3033   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3034           !LangOpts.CPlusPlus &&
3035           FD->isInlineSpecified() &&
3036           FD->getStorageClass() == SC_Extern);
3037 }
3038 
3039 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3040   const AttributedType *AT = T->getAs<AttributedType>();
3041   while (AT && !AT->isCallingConv())
3042     AT = AT->getModifiedType()->getAs<AttributedType>();
3043   return AT;
3044 }
3045 
3046 template <typename T>
3047 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3048   const DeclContext *DC = Old->getDeclContext();
3049   if (DC->isRecord())
3050     return false;
3051 
3052   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3053   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3054     return true;
3055   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3056     return true;
3057   return false;
3058 }
3059 
3060 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3061 static bool isExternC(VarTemplateDecl *) { return false; }
3062 
3063 /// Check whether a redeclaration of an entity introduced by a
3064 /// using-declaration is valid, given that we know it's not an overload
3065 /// (nor a hidden tag declaration).
3066 template<typename ExpectedDecl>
3067 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3068                                    ExpectedDecl *New) {
3069   // C++11 [basic.scope.declarative]p4:
3070   //   Given a set of declarations in a single declarative region, each of
3071   //   which specifies the same unqualified name,
3072   //   -- they shall all refer to the same entity, or all refer to functions
3073   //      and function templates; or
3074   //   -- exactly one declaration shall declare a class name or enumeration
3075   //      name that is not a typedef name and the other declarations shall all
3076   //      refer to the same variable or enumerator, or all refer to functions
3077   //      and function templates; in this case the class name or enumeration
3078   //      name is hidden (3.3.10).
3079 
3080   // C++11 [namespace.udecl]p14:
3081   //   If a function declaration in namespace scope or block scope has the
3082   //   same name and the same parameter-type-list as a function introduced
3083   //   by a using-declaration, and the declarations do not declare the same
3084   //   function, the program is ill-formed.
3085 
3086   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3087   if (Old &&
3088       !Old->getDeclContext()->getRedeclContext()->Equals(
3089           New->getDeclContext()->getRedeclContext()) &&
3090       !(isExternC(Old) && isExternC(New)))
3091     Old = nullptr;
3092 
3093   if (!Old) {
3094     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3095     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3096     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
3097     return true;
3098   }
3099   return false;
3100 }
3101 
3102 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3103                                             const FunctionDecl *B) {
3104   assert(A->getNumParams() == B->getNumParams());
3105 
3106   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3107     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3108     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3109     if (AttrA == AttrB)
3110       return true;
3111     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3112            AttrA->isDynamic() == AttrB->isDynamic();
3113   };
3114 
3115   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3116 }
3117 
3118 /// If necessary, adjust the semantic declaration context for a qualified
3119 /// declaration to name the correct inline namespace within the qualifier.
3120 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3121                                                DeclaratorDecl *OldD) {
3122   // The only case where we need to update the DeclContext is when
3123   // redeclaration lookup for a qualified name finds a declaration
3124   // in an inline namespace within the context named by the qualifier:
3125   //
3126   //   inline namespace N { int f(); }
3127   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3128   //
3129   // For unqualified declarations, the semantic context *can* change
3130   // along the redeclaration chain (for local extern declarations,
3131   // extern "C" declarations, and friend declarations in particular).
3132   if (!NewD->getQualifier())
3133     return;
3134 
3135   // NewD is probably already in the right context.
3136   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3137   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3138   if (NamedDC->Equals(SemaDC))
3139     return;
3140 
3141   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3142           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3143          "unexpected context for redeclaration");
3144 
3145   auto *LexDC = NewD->getLexicalDeclContext();
3146   auto FixSemaDC = [=](NamedDecl *D) {
3147     if (!D)
3148       return;
3149     D->setDeclContext(SemaDC);
3150     D->setLexicalDeclContext(LexDC);
3151   };
3152 
3153   FixSemaDC(NewD);
3154   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3155     FixSemaDC(FD->getDescribedFunctionTemplate());
3156   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3157     FixSemaDC(VD->getDescribedVarTemplate());
3158 }
3159 
3160 /// MergeFunctionDecl - We just parsed a function 'New' from
3161 /// declarator D which has the same name and scope as a previous
3162 /// declaration 'Old'.  Figure out how to resolve this situation,
3163 /// merging decls or emitting diagnostics as appropriate.
3164 ///
3165 /// In C++, New and Old must be declarations that are not
3166 /// overloaded. Use IsOverload to determine whether New and Old are
3167 /// overloaded, and to select the Old declaration that New should be
3168 /// merged with.
3169 ///
3170 /// Returns true if there was an error, false otherwise.
3171 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3172                              Scope *S, bool MergeTypeWithOld) {
3173   // Verify the old decl was also a function.
3174   FunctionDecl *Old = OldD->getAsFunction();
3175   if (!Old) {
3176     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3177       if (New->getFriendObjectKind()) {
3178         Diag(New->getLocation(), diag::err_using_decl_friend);
3179         Diag(Shadow->getTargetDecl()->getLocation(),
3180              diag::note_using_decl_target);
3181         Diag(Shadow->getUsingDecl()->getLocation(),
3182              diag::note_using_decl) << 0;
3183         return true;
3184       }
3185 
3186       // Check whether the two declarations might declare the same function.
3187       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3188         return true;
3189       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3190     } else {
3191       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3192         << New->getDeclName();
3193       notePreviousDefinition(OldD, New->getLocation());
3194       return true;
3195     }
3196   }
3197 
3198   // If the old declaration is invalid, just give up here.
3199   if (Old->isInvalidDecl())
3200     return true;
3201 
3202   // Disallow redeclaration of some builtins.
3203   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3204     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3205     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3206         << Old << Old->getType();
3207     return true;
3208   }
3209 
3210   diag::kind PrevDiag;
3211   SourceLocation OldLocation;
3212   std::tie(PrevDiag, OldLocation) =
3213       getNoteDiagForInvalidRedeclaration(Old, New);
3214 
3215   // Don't complain about this if we're in GNU89 mode and the old function
3216   // is an extern inline function.
3217   // Don't complain about specializations. They are not supposed to have
3218   // storage classes.
3219   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3220       New->getStorageClass() == SC_Static &&
3221       Old->hasExternalFormalLinkage() &&
3222       !New->getTemplateSpecializationInfo() &&
3223       !canRedefineFunction(Old, getLangOpts())) {
3224     if (getLangOpts().MicrosoftExt) {
3225       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3226       Diag(OldLocation, PrevDiag);
3227     } else {
3228       Diag(New->getLocation(), diag::err_static_non_static) << New;
3229       Diag(OldLocation, PrevDiag);
3230       return true;
3231     }
3232   }
3233 
3234   if (New->hasAttr<InternalLinkageAttr>() &&
3235       !Old->hasAttr<InternalLinkageAttr>()) {
3236     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3237         << New->getDeclName();
3238     notePreviousDefinition(Old, New->getLocation());
3239     New->dropAttr<InternalLinkageAttr>();
3240   }
3241 
3242   if (CheckRedeclarationModuleOwnership(New, Old))
3243     return true;
3244 
3245   if (!getLangOpts().CPlusPlus) {
3246     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3247     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3248       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3249         << New << OldOvl;
3250 
3251       // Try our best to find a decl that actually has the overloadable
3252       // attribute for the note. In most cases (e.g. programs with only one
3253       // broken declaration/definition), this won't matter.
3254       //
3255       // FIXME: We could do this if we juggled some extra state in
3256       // OverloadableAttr, rather than just removing it.
3257       const Decl *DiagOld = Old;
3258       if (OldOvl) {
3259         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3260           const auto *A = D->getAttr<OverloadableAttr>();
3261           return A && !A->isImplicit();
3262         });
3263         // If we've implicitly added *all* of the overloadable attrs to this
3264         // chain, emitting a "previous redecl" note is pointless.
3265         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3266       }
3267 
3268       if (DiagOld)
3269         Diag(DiagOld->getLocation(),
3270              diag::note_attribute_overloadable_prev_overload)
3271           << OldOvl;
3272 
3273       if (OldOvl)
3274         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3275       else
3276         New->dropAttr<OverloadableAttr>();
3277     }
3278   }
3279 
3280   // If a function is first declared with a calling convention, but is later
3281   // declared or defined without one, all following decls assume the calling
3282   // convention of the first.
3283   //
3284   // It's OK if a function is first declared without a calling convention,
3285   // but is later declared or defined with the default calling convention.
3286   //
3287   // To test if either decl has an explicit calling convention, we look for
3288   // AttributedType sugar nodes on the type as written.  If they are missing or
3289   // were canonicalized away, we assume the calling convention was implicit.
3290   //
3291   // Note also that we DO NOT return at this point, because we still have
3292   // other tests to run.
3293   QualType OldQType = Context.getCanonicalType(Old->getType());
3294   QualType NewQType = Context.getCanonicalType(New->getType());
3295   const FunctionType *OldType = cast<FunctionType>(OldQType);
3296   const FunctionType *NewType = cast<FunctionType>(NewQType);
3297   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3298   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3299   bool RequiresAdjustment = false;
3300 
3301   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3302     FunctionDecl *First = Old->getFirstDecl();
3303     const FunctionType *FT =
3304         First->getType().getCanonicalType()->castAs<FunctionType>();
3305     FunctionType::ExtInfo FI = FT->getExtInfo();
3306     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3307     if (!NewCCExplicit) {
3308       // Inherit the CC from the previous declaration if it was specified
3309       // there but not here.
3310       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3311       RequiresAdjustment = true;
3312     } else if (New->getBuiltinID()) {
3313       // Calling Conventions on a Builtin aren't really useful and setting a
3314       // default calling convention and cdecl'ing some builtin redeclarations is
3315       // common, so warn and ignore the calling convention on the redeclaration.
3316       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3317           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3318           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3319       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3320       RequiresAdjustment = true;
3321     } else {
3322       // Calling conventions aren't compatible, so complain.
3323       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3324       Diag(New->getLocation(), diag::err_cconv_change)
3325         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3326         << !FirstCCExplicit
3327         << (!FirstCCExplicit ? "" :
3328             FunctionType::getNameForCallConv(FI.getCC()));
3329 
3330       // Put the note on the first decl, since it is the one that matters.
3331       Diag(First->getLocation(), diag::note_previous_declaration);
3332       return true;
3333     }
3334   }
3335 
3336   // FIXME: diagnose the other way around?
3337   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3338     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3339     RequiresAdjustment = true;
3340   }
3341 
3342   // Merge regparm attribute.
3343   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3344       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3345     if (NewTypeInfo.getHasRegParm()) {
3346       Diag(New->getLocation(), diag::err_regparm_mismatch)
3347         << NewType->getRegParmType()
3348         << OldType->getRegParmType();
3349       Diag(OldLocation, diag::note_previous_declaration);
3350       return true;
3351     }
3352 
3353     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3354     RequiresAdjustment = true;
3355   }
3356 
3357   // Merge ns_returns_retained attribute.
3358   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3359     if (NewTypeInfo.getProducesResult()) {
3360       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3361           << "'ns_returns_retained'";
3362       Diag(OldLocation, diag::note_previous_declaration);
3363       return true;
3364     }
3365 
3366     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3367     RequiresAdjustment = true;
3368   }
3369 
3370   if (OldTypeInfo.getNoCallerSavedRegs() !=
3371       NewTypeInfo.getNoCallerSavedRegs()) {
3372     if (NewTypeInfo.getNoCallerSavedRegs()) {
3373       AnyX86NoCallerSavedRegistersAttr *Attr =
3374         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3375       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3376       Diag(OldLocation, diag::note_previous_declaration);
3377       return true;
3378     }
3379 
3380     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3381     RequiresAdjustment = true;
3382   }
3383 
3384   if (RequiresAdjustment) {
3385     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3386     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3387     New->setType(QualType(AdjustedType, 0));
3388     NewQType = Context.getCanonicalType(New->getType());
3389   }
3390 
3391   // If this redeclaration makes the function inline, we may need to add it to
3392   // UndefinedButUsed.
3393   if (!Old->isInlined() && New->isInlined() &&
3394       !New->hasAttr<GNUInlineAttr>() &&
3395       !getLangOpts().GNUInline &&
3396       Old->isUsed(false) &&
3397       !Old->isDefined() && !New->isThisDeclarationADefinition())
3398     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3399                                            SourceLocation()));
3400 
3401   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3402   // about it.
3403   if (New->hasAttr<GNUInlineAttr>() &&
3404       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3405     UndefinedButUsed.erase(Old->getCanonicalDecl());
3406   }
3407 
3408   // If pass_object_size params don't match up perfectly, this isn't a valid
3409   // redeclaration.
3410   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3411       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3412     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3413         << New->getDeclName();
3414     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3415     return true;
3416   }
3417 
3418   if (getLangOpts().CPlusPlus) {
3419     // C++1z [over.load]p2
3420     //   Certain function declarations cannot be overloaded:
3421     //     -- Function declarations that differ only in the return type,
3422     //        the exception specification, or both cannot be overloaded.
3423 
3424     // Check the exception specifications match. This may recompute the type of
3425     // both Old and New if it resolved exception specifications, so grab the
3426     // types again after this. Because this updates the type, we do this before
3427     // any of the other checks below, which may update the "de facto" NewQType
3428     // but do not necessarily update the type of New.
3429     if (CheckEquivalentExceptionSpec(Old, New))
3430       return true;
3431     OldQType = Context.getCanonicalType(Old->getType());
3432     NewQType = Context.getCanonicalType(New->getType());
3433 
3434     // Go back to the type source info to compare the declared return types,
3435     // per C++1y [dcl.type.auto]p13:
3436     //   Redeclarations or specializations of a function or function template
3437     //   with a declared return type that uses a placeholder type shall also
3438     //   use that placeholder, not a deduced type.
3439     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3440     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3441     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3442         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3443                                        OldDeclaredReturnType)) {
3444       QualType ResQT;
3445       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3446           OldDeclaredReturnType->isObjCObjectPointerType())
3447         // FIXME: This does the wrong thing for a deduced return type.
3448         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3449       if (ResQT.isNull()) {
3450         if (New->isCXXClassMember() && New->isOutOfLine())
3451           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3452               << New << New->getReturnTypeSourceRange();
3453         else
3454           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3455               << New->getReturnTypeSourceRange();
3456         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3457                                     << Old->getReturnTypeSourceRange();
3458         return true;
3459       }
3460       else
3461         NewQType = ResQT;
3462     }
3463 
3464     QualType OldReturnType = OldType->getReturnType();
3465     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3466     if (OldReturnType != NewReturnType) {
3467       // If this function has a deduced return type and has already been
3468       // defined, copy the deduced value from the old declaration.
3469       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3470       if (OldAT && OldAT->isDeduced()) {
3471         New->setType(
3472             SubstAutoType(New->getType(),
3473                           OldAT->isDependentType() ? Context.DependentTy
3474                                                    : OldAT->getDeducedType()));
3475         NewQType = Context.getCanonicalType(
3476             SubstAutoType(NewQType,
3477                           OldAT->isDependentType() ? Context.DependentTy
3478                                                    : OldAT->getDeducedType()));
3479       }
3480     }
3481 
3482     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3483     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3484     if (OldMethod && NewMethod) {
3485       // Preserve triviality.
3486       NewMethod->setTrivial(OldMethod->isTrivial());
3487 
3488       // MSVC allows explicit template specialization at class scope:
3489       // 2 CXXMethodDecls referring to the same function will be injected.
3490       // We don't want a redeclaration error.
3491       bool IsClassScopeExplicitSpecialization =
3492                               OldMethod->isFunctionTemplateSpecialization() &&
3493                               NewMethod->isFunctionTemplateSpecialization();
3494       bool isFriend = NewMethod->getFriendObjectKind();
3495 
3496       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3497           !IsClassScopeExplicitSpecialization) {
3498         //    -- Member function declarations with the same name and the
3499         //       same parameter types cannot be overloaded if any of them
3500         //       is a static member function declaration.
3501         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3502           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3503           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3504           return true;
3505         }
3506 
3507         // C++ [class.mem]p1:
3508         //   [...] A member shall not be declared twice in the
3509         //   member-specification, except that a nested class or member
3510         //   class template can be declared and then later defined.
3511         if (!inTemplateInstantiation()) {
3512           unsigned NewDiag;
3513           if (isa<CXXConstructorDecl>(OldMethod))
3514             NewDiag = diag::err_constructor_redeclared;
3515           else if (isa<CXXDestructorDecl>(NewMethod))
3516             NewDiag = diag::err_destructor_redeclared;
3517           else if (isa<CXXConversionDecl>(NewMethod))
3518             NewDiag = diag::err_conv_function_redeclared;
3519           else
3520             NewDiag = diag::err_member_redeclared;
3521 
3522           Diag(New->getLocation(), NewDiag);
3523         } else {
3524           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3525             << New << New->getType();
3526         }
3527         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3528         return true;
3529 
3530       // Complain if this is an explicit declaration of a special
3531       // member that was initially declared implicitly.
3532       //
3533       // As an exception, it's okay to befriend such methods in order
3534       // to permit the implicit constructor/destructor/operator calls.
3535       } else if (OldMethod->isImplicit()) {
3536         if (isFriend) {
3537           NewMethod->setImplicit();
3538         } else {
3539           Diag(NewMethod->getLocation(),
3540                diag::err_definition_of_implicitly_declared_member)
3541             << New << getSpecialMember(OldMethod);
3542           return true;
3543         }
3544       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3545         Diag(NewMethod->getLocation(),
3546              diag::err_definition_of_explicitly_defaulted_member)
3547           << getSpecialMember(OldMethod);
3548         return true;
3549       }
3550     }
3551 
3552     // C++11 [dcl.attr.noreturn]p1:
3553     //   The first declaration of a function shall specify the noreturn
3554     //   attribute if any declaration of that function specifies the noreturn
3555     //   attribute.
3556     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3557     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3558       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3559       Diag(Old->getFirstDecl()->getLocation(),
3560            diag::note_noreturn_missing_first_decl);
3561     }
3562 
3563     // C++11 [dcl.attr.depend]p2:
3564     //   The first declaration of a function shall specify the
3565     //   carries_dependency attribute for its declarator-id if any declaration
3566     //   of the function specifies the carries_dependency attribute.
3567     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3568     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3569       Diag(CDA->getLocation(),
3570            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3571       Diag(Old->getFirstDecl()->getLocation(),
3572            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3573     }
3574 
3575     // (C++98 8.3.5p3):
3576     //   All declarations for a function shall agree exactly in both the
3577     //   return type and the parameter-type-list.
3578     // We also want to respect all the extended bits except noreturn.
3579 
3580     // noreturn should now match unless the old type info didn't have it.
3581     QualType OldQTypeForComparison = OldQType;
3582     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3583       auto *OldType = OldQType->castAs<FunctionProtoType>();
3584       const FunctionType *OldTypeForComparison
3585         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3586       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3587       assert(OldQTypeForComparison.isCanonical());
3588     }
3589 
3590     if (haveIncompatibleLanguageLinkages(Old, New)) {
3591       // As a special case, retain the language linkage from previous
3592       // declarations of a friend function as an extension.
3593       //
3594       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3595       // and is useful because there's otherwise no way to specify language
3596       // linkage within class scope.
3597       //
3598       // Check cautiously as the friend object kind isn't yet complete.
3599       if (New->getFriendObjectKind() != Decl::FOK_None) {
3600         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3601         Diag(OldLocation, PrevDiag);
3602       } else {
3603         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3604         Diag(OldLocation, PrevDiag);
3605         return true;
3606       }
3607     }
3608 
3609     // If the function types are compatible, merge the declarations. Ignore the
3610     // exception specifier because it was already checked above in
3611     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3612     // about incompatible types under -fms-compatibility.
3613     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3614                                                          NewQType))
3615       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3616 
3617     // If the types are imprecise (due to dependent constructs in friends or
3618     // local extern declarations), it's OK if they differ. We'll check again
3619     // during instantiation.
3620     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3621       return false;
3622 
3623     // Fall through for conflicting redeclarations and redefinitions.
3624   }
3625 
3626   // C: Function types need to be compatible, not identical. This handles
3627   // duplicate function decls like "void f(int); void f(enum X);" properly.
3628   if (!getLangOpts().CPlusPlus &&
3629       Context.typesAreCompatible(OldQType, NewQType)) {
3630     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3631     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3632     const FunctionProtoType *OldProto = nullptr;
3633     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3634         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3635       // The old declaration provided a function prototype, but the
3636       // new declaration does not. Merge in the prototype.
3637       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3638       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3639       NewQType =
3640           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3641                                   OldProto->getExtProtoInfo());
3642       New->setType(NewQType);
3643       New->setHasInheritedPrototype();
3644 
3645       // Synthesize parameters with the same types.
3646       SmallVector<ParmVarDecl*, 16> Params;
3647       for (const auto &ParamType : OldProto->param_types()) {
3648         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3649                                                  SourceLocation(), nullptr,
3650                                                  ParamType, /*TInfo=*/nullptr,
3651                                                  SC_None, nullptr);
3652         Param->setScopeInfo(0, Params.size());
3653         Param->setImplicit();
3654         Params.push_back(Param);
3655       }
3656 
3657       New->setParams(Params);
3658     }
3659 
3660     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3661   }
3662 
3663   // Check if the function types are compatible when pointer size address
3664   // spaces are ignored.
3665   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3666     return false;
3667 
3668   // GNU C permits a K&R definition to follow a prototype declaration
3669   // if the declared types of the parameters in the K&R definition
3670   // match the types in the prototype declaration, even when the
3671   // promoted types of the parameters from the K&R definition differ
3672   // from the types in the prototype. GCC then keeps the types from
3673   // the prototype.
3674   //
3675   // If a variadic prototype is followed by a non-variadic K&R definition,
3676   // the K&R definition becomes variadic.  This is sort of an edge case, but
3677   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3678   // C99 6.9.1p8.
3679   if (!getLangOpts().CPlusPlus &&
3680       Old->hasPrototype() && !New->hasPrototype() &&
3681       New->getType()->getAs<FunctionProtoType>() &&
3682       Old->getNumParams() == New->getNumParams()) {
3683     SmallVector<QualType, 16> ArgTypes;
3684     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3685     const FunctionProtoType *OldProto
3686       = Old->getType()->getAs<FunctionProtoType>();
3687     const FunctionProtoType *NewProto
3688       = New->getType()->getAs<FunctionProtoType>();
3689 
3690     // Determine whether this is the GNU C extension.
3691     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3692                                                NewProto->getReturnType());
3693     bool LooseCompatible = !MergedReturn.isNull();
3694     for (unsigned Idx = 0, End = Old->getNumParams();
3695          LooseCompatible && Idx != End; ++Idx) {
3696       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3697       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3698       if (Context.typesAreCompatible(OldParm->getType(),
3699                                      NewProto->getParamType(Idx))) {
3700         ArgTypes.push_back(NewParm->getType());
3701       } else if (Context.typesAreCompatible(OldParm->getType(),
3702                                             NewParm->getType(),
3703                                             /*CompareUnqualified=*/true)) {
3704         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3705                                            NewProto->getParamType(Idx) };
3706         Warnings.push_back(Warn);
3707         ArgTypes.push_back(NewParm->getType());
3708       } else
3709         LooseCompatible = false;
3710     }
3711 
3712     if (LooseCompatible) {
3713       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3714         Diag(Warnings[Warn].NewParm->getLocation(),
3715              diag::ext_param_promoted_not_compatible_with_prototype)
3716           << Warnings[Warn].PromotedType
3717           << Warnings[Warn].OldParm->getType();
3718         if (Warnings[Warn].OldParm->getLocation().isValid())
3719           Diag(Warnings[Warn].OldParm->getLocation(),
3720                diag::note_previous_declaration);
3721       }
3722 
3723       if (MergeTypeWithOld)
3724         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3725                                              OldProto->getExtProtoInfo()));
3726       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3727     }
3728 
3729     // Fall through to diagnose conflicting types.
3730   }
3731 
3732   // A function that has already been declared has been redeclared or
3733   // defined with a different type; show an appropriate diagnostic.
3734 
3735   // If the previous declaration was an implicitly-generated builtin
3736   // declaration, then at the very least we should use a specialized note.
3737   unsigned BuiltinID;
3738   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3739     // If it's actually a library-defined builtin function like 'malloc'
3740     // or 'printf', just warn about the incompatible redeclaration.
3741     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3742       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3743       Diag(OldLocation, diag::note_previous_builtin_declaration)
3744         << Old << Old->getType();
3745 
3746       // If this is a global redeclaration, just forget hereafter
3747       // about the "builtin-ness" of the function.
3748       //
3749       // Doing this for local extern declarations is problematic.  If
3750       // the builtin declaration remains visible, a second invalid
3751       // local declaration will produce a hard error; if it doesn't
3752       // remain visible, a single bogus local redeclaration (which is
3753       // actually only a warning) could break all the downstream code.
3754       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3755         New->getIdentifier()->revertBuiltin();
3756 
3757       return false;
3758     }
3759 
3760     PrevDiag = diag::note_previous_builtin_declaration;
3761   }
3762 
3763   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3764   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3765   return true;
3766 }
3767 
3768 /// Completes the merge of two function declarations that are
3769 /// known to be compatible.
3770 ///
3771 /// This routine handles the merging of attributes and other
3772 /// properties of function declarations from the old declaration to
3773 /// the new declaration, once we know that New is in fact a
3774 /// redeclaration of Old.
3775 ///
3776 /// \returns false
3777 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3778                                         Scope *S, bool MergeTypeWithOld) {
3779   // Merge the attributes
3780   mergeDeclAttributes(New, Old);
3781 
3782   // Merge "pure" flag.
3783   if (Old->isPure())
3784     New->setPure();
3785 
3786   // Merge "used" flag.
3787   if (Old->getMostRecentDecl()->isUsed(false))
3788     New->setIsUsed();
3789 
3790   // Merge attributes from the parameters.  These can mismatch with K&R
3791   // declarations.
3792   if (New->getNumParams() == Old->getNumParams())
3793       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3794         ParmVarDecl *NewParam = New->getParamDecl(i);
3795         ParmVarDecl *OldParam = Old->getParamDecl(i);
3796         mergeParamDeclAttributes(NewParam, OldParam, *this);
3797         mergeParamDeclTypes(NewParam, OldParam, *this);
3798       }
3799 
3800   if (getLangOpts().CPlusPlus)
3801     return MergeCXXFunctionDecl(New, Old, S);
3802 
3803   // Merge the function types so the we get the composite types for the return
3804   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3805   // was visible.
3806   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3807   if (!Merged.isNull() && MergeTypeWithOld)
3808     New->setType(Merged);
3809 
3810   return false;
3811 }
3812 
3813 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3814                                 ObjCMethodDecl *oldMethod) {
3815   // Merge the attributes, including deprecated/unavailable
3816   AvailabilityMergeKind MergeKind =
3817     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3818       ? AMK_ProtocolImplementation
3819       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3820                                                        : AMK_Override;
3821 
3822   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3823 
3824   // Merge attributes from the parameters.
3825   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3826                                        oe = oldMethod->param_end();
3827   for (ObjCMethodDecl::param_iterator
3828          ni = newMethod->param_begin(), ne = newMethod->param_end();
3829        ni != ne && oi != oe; ++ni, ++oi)
3830     mergeParamDeclAttributes(*ni, *oi, *this);
3831 
3832   CheckObjCMethodOverride(newMethod, oldMethod);
3833 }
3834 
3835 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3836   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3837 
3838   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3839          ? diag::err_redefinition_different_type
3840          : diag::err_redeclaration_different_type)
3841     << New->getDeclName() << New->getType() << Old->getType();
3842 
3843   diag::kind PrevDiag;
3844   SourceLocation OldLocation;
3845   std::tie(PrevDiag, OldLocation)
3846     = getNoteDiagForInvalidRedeclaration(Old, New);
3847   S.Diag(OldLocation, PrevDiag);
3848   New->setInvalidDecl();
3849 }
3850 
3851 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3852 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3853 /// emitting diagnostics as appropriate.
3854 ///
3855 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3856 /// to here in AddInitializerToDecl. We can't check them before the initializer
3857 /// is attached.
3858 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3859                              bool MergeTypeWithOld) {
3860   if (New->isInvalidDecl() || Old->isInvalidDecl())
3861     return;
3862 
3863   QualType MergedT;
3864   if (getLangOpts().CPlusPlus) {
3865     if (New->getType()->isUndeducedType()) {
3866       // We don't know what the new type is until the initializer is attached.
3867       return;
3868     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3869       // These could still be something that needs exception specs checked.
3870       return MergeVarDeclExceptionSpecs(New, Old);
3871     }
3872     // C++ [basic.link]p10:
3873     //   [...] the types specified by all declarations referring to a given
3874     //   object or function shall be identical, except that declarations for an
3875     //   array object can specify array types that differ by the presence or
3876     //   absence of a major array bound (8.3.4).
3877     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3878       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3879       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3880 
3881       // We are merging a variable declaration New into Old. If it has an array
3882       // bound, and that bound differs from Old's bound, we should diagnose the
3883       // mismatch.
3884       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3885         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3886              PrevVD = PrevVD->getPreviousDecl()) {
3887           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3888           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3889             continue;
3890 
3891           if (!Context.hasSameType(NewArray, PrevVDTy))
3892             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3893         }
3894       }
3895 
3896       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3897         if (Context.hasSameType(OldArray->getElementType(),
3898                                 NewArray->getElementType()))
3899           MergedT = New->getType();
3900       }
3901       // FIXME: Check visibility. New is hidden but has a complete type. If New
3902       // has no array bound, it should not inherit one from Old, if Old is not
3903       // visible.
3904       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3905         if (Context.hasSameType(OldArray->getElementType(),
3906                                 NewArray->getElementType()))
3907           MergedT = Old->getType();
3908       }
3909     }
3910     else if (New->getType()->isObjCObjectPointerType() &&
3911                Old->getType()->isObjCObjectPointerType()) {
3912       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3913                                               Old->getType());
3914     }
3915   } else {
3916     // C 6.2.7p2:
3917     //   All declarations that refer to the same object or function shall have
3918     //   compatible type.
3919     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3920   }
3921   if (MergedT.isNull()) {
3922     // It's OK if we couldn't merge types if either type is dependent, for a
3923     // block-scope variable. In other cases (static data members of class
3924     // templates, variable templates, ...), we require the types to be
3925     // equivalent.
3926     // FIXME: The C++ standard doesn't say anything about this.
3927     if ((New->getType()->isDependentType() ||
3928          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3929       // If the old type was dependent, we can't merge with it, so the new type
3930       // becomes dependent for now. We'll reproduce the original type when we
3931       // instantiate the TypeSourceInfo for the variable.
3932       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3933         New->setType(Context.DependentTy);
3934       return;
3935     }
3936     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3937   }
3938 
3939   // Don't actually update the type on the new declaration if the old
3940   // declaration was an extern declaration in a different scope.
3941   if (MergeTypeWithOld)
3942     New->setType(MergedT);
3943 }
3944 
3945 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3946                                   LookupResult &Previous) {
3947   // C11 6.2.7p4:
3948   //   For an identifier with internal or external linkage declared
3949   //   in a scope in which a prior declaration of that identifier is
3950   //   visible, if the prior declaration specifies internal or
3951   //   external linkage, the type of the identifier at the later
3952   //   declaration becomes the composite type.
3953   //
3954   // If the variable isn't visible, we do not merge with its type.
3955   if (Previous.isShadowed())
3956     return false;
3957 
3958   if (S.getLangOpts().CPlusPlus) {
3959     // C++11 [dcl.array]p3:
3960     //   If there is a preceding declaration of the entity in the same
3961     //   scope in which the bound was specified, an omitted array bound
3962     //   is taken to be the same as in that earlier declaration.
3963     return NewVD->isPreviousDeclInSameBlockScope() ||
3964            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3965             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3966   } else {
3967     // If the old declaration was function-local, don't merge with its
3968     // type unless we're in the same function.
3969     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3970            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3971   }
3972 }
3973 
3974 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3975 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3976 /// situation, merging decls or emitting diagnostics as appropriate.
3977 ///
3978 /// Tentative definition rules (C99 6.9.2p2) are checked by
3979 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3980 /// definitions here, since the initializer hasn't been attached.
3981 ///
3982 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3983   // If the new decl is already invalid, don't do any other checking.
3984   if (New->isInvalidDecl())
3985     return;
3986 
3987   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3988     return;
3989 
3990   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3991 
3992   // Verify the old decl was also a variable or variable template.
3993   VarDecl *Old = nullptr;
3994   VarTemplateDecl *OldTemplate = nullptr;
3995   if (Previous.isSingleResult()) {
3996     if (NewTemplate) {
3997       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3998       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3999 
4000       if (auto *Shadow =
4001               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4002         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4003           return New->setInvalidDecl();
4004     } else {
4005       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4006 
4007       if (auto *Shadow =
4008               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4009         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4010           return New->setInvalidDecl();
4011     }
4012   }
4013   if (!Old) {
4014     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4015         << New->getDeclName();
4016     notePreviousDefinition(Previous.getRepresentativeDecl(),
4017                            New->getLocation());
4018     return New->setInvalidDecl();
4019   }
4020 
4021   // Ensure the template parameters are compatible.
4022   if (NewTemplate &&
4023       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4024                                       OldTemplate->getTemplateParameters(),
4025                                       /*Complain=*/true, TPL_TemplateMatch))
4026     return New->setInvalidDecl();
4027 
4028   // C++ [class.mem]p1:
4029   //   A member shall not be declared twice in the member-specification [...]
4030   //
4031   // Here, we need only consider static data members.
4032   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4033     Diag(New->getLocation(), diag::err_duplicate_member)
4034       << New->getIdentifier();
4035     Diag(Old->getLocation(), diag::note_previous_declaration);
4036     New->setInvalidDecl();
4037   }
4038 
4039   mergeDeclAttributes(New, Old);
4040   // Warn if an already-declared variable is made a weak_import in a subsequent
4041   // declaration
4042   if (New->hasAttr<WeakImportAttr>() &&
4043       Old->getStorageClass() == SC_None &&
4044       !Old->hasAttr<WeakImportAttr>()) {
4045     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4046     notePreviousDefinition(Old, New->getLocation());
4047     // Remove weak_import attribute on new declaration.
4048     New->dropAttr<WeakImportAttr>();
4049   }
4050 
4051   if (New->hasAttr<InternalLinkageAttr>() &&
4052       !Old->hasAttr<InternalLinkageAttr>()) {
4053     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
4054         << New->getDeclName();
4055     notePreviousDefinition(Old, New->getLocation());
4056     New->dropAttr<InternalLinkageAttr>();
4057   }
4058 
4059   // Merge the types.
4060   VarDecl *MostRecent = Old->getMostRecentDecl();
4061   if (MostRecent != Old) {
4062     MergeVarDeclTypes(New, MostRecent,
4063                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4064     if (New->isInvalidDecl())
4065       return;
4066   }
4067 
4068   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4069   if (New->isInvalidDecl())
4070     return;
4071 
4072   diag::kind PrevDiag;
4073   SourceLocation OldLocation;
4074   std::tie(PrevDiag, OldLocation) =
4075       getNoteDiagForInvalidRedeclaration(Old, New);
4076 
4077   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4078   if (New->getStorageClass() == SC_Static &&
4079       !New->isStaticDataMember() &&
4080       Old->hasExternalFormalLinkage()) {
4081     if (getLangOpts().MicrosoftExt) {
4082       Diag(New->getLocation(), diag::ext_static_non_static)
4083           << New->getDeclName();
4084       Diag(OldLocation, PrevDiag);
4085     } else {
4086       Diag(New->getLocation(), diag::err_static_non_static)
4087           << New->getDeclName();
4088       Diag(OldLocation, PrevDiag);
4089       return New->setInvalidDecl();
4090     }
4091   }
4092   // C99 6.2.2p4:
4093   //   For an identifier declared with the storage-class specifier
4094   //   extern in a scope in which a prior declaration of that
4095   //   identifier is visible,23) if the prior declaration specifies
4096   //   internal or external linkage, the linkage of the identifier at
4097   //   the later declaration is the same as the linkage specified at
4098   //   the prior declaration. If no prior declaration is visible, or
4099   //   if the prior declaration specifies no linkage, then the
4100   //   identifier has external linkage.
4101   if (New->hasExternalStorage() && Old->hasLinkage())
4102     /* Okay */;
4103   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4104            !New->isStaticDataMember() &&
4105            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4106     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4107     Diag(OldLocation, PrevDiag);
4108     return New->setInvalidDecl();
4109   }
4110 
4111   // Check if extern is followed by non-extern and vice-versa.
4112   if (New->hasExternalStorage() &&
4113       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4114     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4115     Diag(OldLocation, PrevDiag);
4116     return New->setInvalidDecl();
4117   }
4118   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4119       !New->hasExternalStorage()) {
4120     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4121     Diag(OldLocation, PrevDiag);
4122     return New->setInvalidDecl();
4123   }
4124 
4125   if (CheckRedeclarationModuleOwnership(New, Old))
4126     return;
4127 
4128   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4129 
4130   // FIXME: The test for external storage here seems wrong? We still
4131   // need to check for mismatches.
4132   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4133       // Don't complain about out-of-line definitions of static members.
4134       !(Old->getLexicalDeclContext()->isRecord() &&
4135         !New->getLexicalDeclContext()->isRecord())) {
4136     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4137     Diag(OldLocation, PrevDiag);
4138     return New->setInvalidDecl();
4139   }
4140 
4141   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4142     if (VarDecl *Def = Old->getDefinition()) {
4143       // C++1z [dcl.fcn.spec]p4:
4144       //   If the definition of a variable appears in a translation unit before
4145       //   its first declaration as inline, the program is ill-formed.
4146       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4147       Diag(Def->getLocation(), diag::note_previous_definition);
4148     }
4149   }
4150 
4151   // If this redeclaration makes the variable inline, we may need to add it to
4152   // UndefinedButUsed.
4153   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4154       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4155     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4156                                            SourceLocation()));
4157 
4158   if (New->getTLSKind() != Old->getTLSKind()) {
4159     if (!Old->getTLSKind()) {
4160       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4161       Diag(OldLocation, PrevDiag);
4162     } else if (!New->getTLSKind()) {
4163       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4164       Diag(OldLocation, PrevDiag);
4165     } else {
4166       // Do not allow redeclaration to change the variable between requiring
4167       // static and dynamic initialization.
4168       // FIXME: GCC allows this, but uses the TLS keyword on the first
4169       // declaration to determine the kind. Do we need to be compatible here?
4170       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4171         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4172       Diag(OldLocation, PrevDiag);
4173     }
4174   }
4175 
4176   // C++ doesn't have tentative definitions, so go right ahead and check here.
4177   if (getLangOpts().CPlusPlus &&
4178       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4179     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4180         Old->getCanonicalDecl()->isConstexpr()) {
4181       // This definition won't be a definition any more once it's been merged.
4182       Diag(New->getLocation(),
4183            diag::warn_deprecated_redundant_constexpr_static_def);
4184     } else if (VarDecl *Def = Old->getDefinition()) {
4185       if (checkVarDeclRedefinition(Def, New))
4186         return;
4187     }
4188   }
4189 
4190   if (haveIncompatibleLanguageLinkages(Old, New)) {
4191     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4192     Diag(OldLocation, PrevDiag);
4193     New->setInvalidDecl();
4194     return;
4195   }
4196 
4197   // Merge "used" flag.
4198   if (Old->getMostRecentDecl()->isUsed(false))
4199     New->setIsUsed();
4200 
4201   // Keep a chain of previous declarations.
4202   New->setPreviousDecl(Old);
4203   if (NewTemplate)
4204     NewTemplate->setPreviousDecl(OldTemplate);
4205   adjustDeclContextForDeclaratorDecl(New, Old);
4206 
4207   // Inherit access appropriately.
4208   New->setAccess(Old->getAccess());
4209   if (NewTemplate)
4210     NewTemplate->setAccess(New->getAccess());
4211 
4212   if (Old->isInline())
4213     New->setImplicitlyInline();
4214 }
4215 
4216 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4217   SourceManager &SrcMgr = getSourceManager();
4218   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4219   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4220   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4221   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4222   auto &HSI = PP.getHeaderSearchInfo();
4223   StringRef HdrFilename =
4224       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4225 
4226   auto noteFromModuleOrInclude = [&](Module *Mod,
4227                                      SourceLocation IncLoc) -> bool {
4228     // Redefinition errors with modules are common with non modular mapped
4229     // headers, example: a non-modular header H in module A that also gets
4230     // included directly in a TU. Pointing twice to the same header/definition
4231     // is confusing, try to get better diagnostics when modules is on.
4232     if (IncLoc.isValid()) {
4233       if (Mod) {
4234         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4235             << HdrFilename.str() << Mod->getFullModuleName();
4236         if (!Mod->DefinitionLoc.isInvalid())
4237           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4238               << Mod->getFullModuleName();
4239       } else {
4240         Diag(IncLoc, diag::note_redefinition_include_same_file)
4241             << HdrFilename.str();
4242       }
4243       return true;
4244     }
4245 
4246     return false;
4247   };
4248 
4249   // Is it the same file and same offset? Provide more information on why
4250   // this leads to a redefinition error.
4251   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4252     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4253     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4254     bool EmittedDiag =
4255         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4256     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4257 
4258     // If the header has no guards, emit a note suggesting one.
4259     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4260       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4261 
4262     if (EmittedDiag)
4263       return;
4264   }
4265 
4266   // Redefinition coming from different files or couldn't do better above.
4267   if (Old->getLocation().isValid())
4268     Diag(Old->getLocation(), diag::note_previous_definition);
4269 }
4270 
4271 /// We've just determined that \p Old and \p New both appear to be definitions
4272 /// of the same variable. Either diagnose or fix the problem.
4273 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4274   if (!hasVisibleDefinition(Old) &&
4275       (New->getFormalLinkage() == InternalLinkage ||
4276        New->isInline() ||
4277        New->getDescribedVarTemplate() ||
4278        New->getNumTemplateParameterLists() ||
4279        New->getDeclContext()->isDependentContext())) {
4280     // The previous definition is hidden, and multiple definitions are
4281     // permitted (in separate TUs). Demote this to a declaration.
4282     New->demoteThisDefinitionToDeclaration();
4283 
4284     // Make the canonical definition visible.
4285     if (auto *OldTD = Old->getDescribedVarTemplate())
4286       makeMergedDefinitionVisible(OldTD);
4287     makeMergedDefinitionVisible(Old);
4288     return false;
4289   } else {
4290     Diag(New->getLocation(), diag::err_redefinition) << New;
4291     notePreviousDefinition(Old, New->getLocation());
4292     New->setInvalidDecl();
4293     return true;
4294   }
4295 }
4296 
4297 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4298 /// no declarator (e.g. "struct foo;") is parsed.
4299 Decl *
4300 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4301                                  RecordDecl *&AnonRecord) {
4302   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4303                                     AnonRecord);
4304 }
4305 
4306 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4307 // disambiguate entities defined in different scopes.
4308 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4309 // compatibility.
4310 // We will pick our mangling number depending on which version of MSVC is being
4311 // targeted.
4312 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4313   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4314              ? S->getMSCurManglingNumber()
4315              : S->getMSLastManglingNumber();
4316 }
4317 
4318 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4319   if (!Context.getLangOpts().CPlusPlus)
4320     return;
4321 
4322   if (isa<CXXRecordDecl>(Tag->getParent())) {
4323     // If this tag is the direct child of a class, number it if
4324     // it is anonymous.
4325     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4326       return;
4327     MangleNumberingContext &MCtx =
4328         Context.getManglingNumberContext(Tag->getParent());
4329     Context.setManglingNumber(
4330         Tag, MCtx.getManglingNumber(
4331                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4332     return;
4333   }
4334 
4335   // If this tag isn't a direct child of a class, number it if it is local.
4336   MangleNumberingContext *MCtx;
4337   Decl *ManglingContextDecl;
4338   std::tie(MCtx, ManglingContextDecl) =
4339       getCurrentMangleNumberContext(Tag->getDeclContext());
4340   if (MCtx) {
4341     Context.setManglingNumber(
4342         Tag, MCtx->getManglingNumber(
4343                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4344   }
4345 }
4346 
4347 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4348                                         TypedefNameDecl *NewTD) {
4349   if (TagFromDeclSpec->isInvalidDecl())
4350     return;
4351 
4352   // Do nothing if the tag already has a name for linkage purposes.
4353   if (TagFromDeclSpec->hasNameForLinkage())
4354     return;
4355 
4356   // A well-formed anonymous tag must always be a TUK_Definition.
4357   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4358 
4359   // The type must match the tag exactly;  no qualifiers allowed.
4360   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4361                            Context.getTagDeclType(TagFromDeclSpec))) {
4362     if (getLangOpts().CPlusPlus)
4363       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4364     return;
4365   }
4366 
4367   // If we've already computed linkage for the anonymous tag, then
4368   // adding a typedef name for the anonymous decl can change that
4369   // linkage, which might be a serious problem.  Diagnose this as
4370   // unsupported and ignore the typedef name.  TODO: we should
4371   // pursue this as a language defect and establish a formal rule
4372   // for how to handle it.
4373   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4374     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4375 
4376     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4377     tagLoc = getLocForEndOfToken(tagLoc);
4378 
4379     llvm::SmallString<40> textToInsert;
4380     textToInsert += ' ';
4381     textToInsert += NewTD->getIdentifier()->getName();
4382     Diag(tagLoc, diag::note_typedef_changes_linkage)
4383         << FixItHint::CreateInsertion(tagLoc, textToInsert);
4384     return;
4385   }
4386 
4387   // Otherwise, set this is the anon-decl typedef for the tag.
4388   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4389 }
4390 
4391 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4392   switch (T) {
4393   case DeclSpec::TST_class:
4394     return 0;
4395   case DeclSpec::TST_struct:
4396     return 1;
4397   case DeclSpec::TST_interface:
4398     return 2;
4399   case DeclSpec::TST_union:
4400     return 3;
4401   case DeclSpec::TST_enum:
4402     return 4;
4403   default:
4404     llvm_unreachable("unexpected type specifier");
4405   }
4406 }
4407 
4408 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4409 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4410 /// parameters to cope with template friend declarations.
4411 Decl *
4412 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4413                                  MultiTemplateParamsArg TemplateParams,
4414                                  bool IsExplicitInstantiation,
4415                                  RecordDecl *&AnonRecord) {
4416   Decl *TagD = nullptr;
4417   TagDecl *Tag = nullptr;
4418   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4419       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4420       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4421       DS.getTypeSpecType() == DeclSpec::TST_union ||
4422       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4423     TagD = DS.getRepAsDecl();
4424 
4425     if (!TagD) // We probably had an error
4426       return nullptr;
4427 
4428     // Note that the above type specs guarantee that the
4429     // type rep is a Decl, whereas in many of the others
4430     // it's a Type.
4431     if (isa<TagDecl>(TagD))
4432       Tag = cast<TagDecl>(TagD);
4433     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4434       Tag = CTD->getTemplatedDecl();
4435   }
4436 
4437   if (Tag) {
4438     handleTagNumbering(Tag, S);
4439     Tag->setFreeStanding();
4440     if (Tag->isInvalidDecl())
4441       return Tag;
4442   }
4443 
4444   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4445     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4446     // or incomplete types shall not be restrict-qualified."
4447     if (TypeQuals & DeclSpec::TQ_restrict)
4448       Diag(DS.getRestrictSpecLoc(),
4449            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4450            << DS.getSourceRange();
4451   }
4452 
4453   if (DS.isInlineSpecified())
4454     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4455         << getLangOpts().CPlusPlus17;
4456 
4457   if (DS.hasConstexprSpecifier()) {
4458     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4459     // and definitions of functions and variables.
4460     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4461     // the declaration of a function or function template
4462     if (Tag)
4463       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4464           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4465           << DS.getConstexprSpecifier();
4466     else
4467       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4468           << DS.getConstexprSpecifier();
4469     // Don't emit warnings after this error.
4470     return TagD;
4471   }
4472 
4473   DiagnoseFunctionSpecifiers(DS);
4474 
4475   if (DS.isFriendSpecified()) {
4476     // If we're dealing with a decl but not a TagDecl, assume that
4477     // whatever routines created it handled the friendship aspect.
4478     if (TagD && !Tag)
4479       return nullptr;
4480     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4481   }
4482 
4483   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4484   bool IsExplicitSpecialization =
4485     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4486   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4487       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4488       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4489     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4490     // nested-name-specifier unless it is an explicit instantiation
4491     // or an explicit specialization.
4492     //
4493     // FIXME: We allow class template partial specializations here too, per the
4494     // obvious intent of DR1819.
4495     //
4496     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4497     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4498         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4499     return nullptr;
4500   }
4501 
4502   // Track whether this decl-specifier declares anything.
4503   bool DeclaresAnything = true;
4504 
4505   // Handle anonymous struct definitions.
4506   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4507     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4508         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4509       if (getLangOpts().CPlusPlus ||
4510           Record->getDeclContext()->isRecord()) {
4511         // If CurContext is a DeclContext that can contain statements,
4512         // RecursiveASTVisitor won't visit the decls that
4513         // BuildAnonymousStructOrUnion() will put into CurContext.
4514         // Also store them here so that they can be part of the
4515         // DeclStmt that gets created in this case.
4516         // FIXME: Also return the IndirectFieldDecls created by
4517         // BuildAnonymousStructOr union, for the same reason?
4518         if (CurContext->isFunctionOrMethod())
4519           AnonRecord = Record;
4520         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4521                                            Context.getPrintingPolicy());
4522       }
4523 
4524       DeclaresAnything = false;
4525     }
4526   }
4527 
4528   // C11 6.7.2.1p2:
4529   //   A struct-declaration that does not declare an anonymous structure or
4530   //   anonymous union shall contain a struct-declarator-list.
4531   //
4532   // This rule also existed in C89 and C99; the grammar for struct-declaration
4533   // did not permit a struct-declaration without a struct-declarator-list.
4534   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4535       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4536     // Check for Microsoft C extension: anonymous struct/union member.
4537     // Handle 2 kinds of anonymous struct/union:
4538     //   struct STRUCT;
4539     //   union UNION;
4540     // and
4541     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4542     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4543     if ((Tag && Tag->getDeclName()) ||
4544         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4545       RecordDecl *Record = nullptr;
4546       if (Tag)
4547         Record = dyn_cast<RecordDecl>(Tag);
4548       else if (const RecordType *RT =
4549                    DS.getRepAsType().get()->getAsStructureType())
4550         Record = RT->getDecl();
4551       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4552         Record = UT->getDecl();
4553 
4554       if (Record && getLangOpts().MicrosoftExt) {
4555         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4556             << Record->isUnion() << DS.getSourceRange();
4557         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4558       }
4559 
4560       DeclaresAnything = false;
4561     }
4562   }
4563 
4564   // Skip all the checks below if we have a type error.
4565   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4566       (TagD && TagD->isInvalidDecl()))
4567     return TagD;
4568 
4569   if (getLangOpts().CPlusPlus &&
4570       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4571     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4572       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4573           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4574         DeclaresAnything = false;
4575 
4576   if (!DS.isMissingDeclaratorOk()) {
4577     // Customize diagnostic for a typedef missing a name.
4578     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4579       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4580           << DS.getSourceRange();
4581     else
4582       DeclaresAnything = false;
4583   }
4584 
4585   if (DS.isModulePrivateSpecified() &&
4586       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4587     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4588       << Tag->getTagKind()
4589       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4590 
4591   ActOnDocumentableDecl(TagD);
4592 
4593   // C 6.7/2:
4594   //   A declaration [...] shall declare at least a declarator [...], a tag,
4595   //   or the members of an enumeration.
4596   // C++ [dcl.dcl]p3:
4597   //   [If there are no declarators], and except for the declaration of an
4598   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4599   //   names into the program, or shall redeclare a name introduced by a
4600   //   previous declaration.
4601   if (!DeclaresAnything) {
4602     // In C, we allow this as a (popular) extension / bug. Don't bother
4603     // producing further diagnostics for redundant qualifiers after this.
4604     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4605     return TagD;
4606   }
4607 
4608   // C++ [dcl.stc]p1:
4609   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4610   //   init-declarator-list of the declaration shall not be empty.
4611   // C++ [dcl.fct.spec]p1:
4612   //   If a cv-qualifier appears in a decl-specifier-seq, the
4613   //   init-declarator-list of the declaration shall not be empty.
4614   //
4615   // Spurious qualifiers here appear to be valid in C.
4616   unsigned DiagID = diag::warn_standalone_specifier;
4617   if (getLangOpts().CPlusPlus)
4618     DiagID = diag::ext_standalone_specifier;
4619 
4620   // Note that a linkage-specification sets a storage class, but
4621   // 'extern "C" struct foo;' is actually valid and not theoretically
4622   // useless.
4623   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4624     if (SCS == DeclSpec::SCS_mutable)
4625       // Since mutable is not a viable storage class specifier in C, there is
4626       // no reason to treat it as an extension. Instead, diagnose as an error.
4627       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4628     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4629       Diag(DS.getStorageClassSpecLoc(), DiagID)
4630         << DeclSpec::getSpecifierName(SCS);
4631   }
4632 
4633   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4634     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4635       << DeclSpec::getSpecifierName(TSCS);
4636   if (DS.getTypeQualifiers()) {
4637     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4638       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4639     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4640       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4641     // Restrict is covered above.
4642     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4643       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4644     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4645       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4646   }
4647 
4648   // Warn about ignored type attributes, for example:
4649   // __attribute__((aligned)) struct A;
4650   // Attributes should be placed after tag to apply to type declaration.
4651   if (!DS.getAttributes().empty()) {
4652     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4653     if (TypeSpecType == DeclSpec::TST_class ||
4654         TypeSpecType == DeclSpec::TST_struct ||
4655         TypeSpecType == DeclSpec::TST_interface ||
4656         TypeSpecType == DeclSpec::TST_union ||
4657         TypeSpecType == DeclSpec::TST_enum) {
4658       for (const ParsedAttr &AL : DS.getAttributes())
4659         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4660             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4661     }
4662   }
4663 
4664   return TagD;
4665 }
4666 
4667 /// We are trying to inject an anonymous member into the given scope;
4668 /// check if there's an existing declaration that can't be overloaded.
4669 ///
4670 /// \return true if this is a forbidden redeclaration
4671 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4672                                          Scope *S,
4673                                          DeclContext *Owner,
4674                                          DeclarationName Name,
4675                                          SourceLocation NameLoc,
4676                                          bool IsUnion) {
4677   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4678                  Sema::ForVisibleRedeclaration);
4679   if (!SemaRef.LookupName(R, S)) return false;
4680 
4681   // Pick a representative declaration.
4682   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4683   assert(PrevDecl && "Expected a non-null Decl");
4684 
4685   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4686     return false;
4687 
4688   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4689     << IsUnion << Name;
4690   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4691 
4692   return true;
4693 }
4694 
4695 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4696 /// anonymous struct or union AnonRecord into the owning context Owner
4697 /// and scope S. This routine will be invoked just after we realize
4698 /// that an unnamed union or struct is actually an anonymous union or
4699 /// struct, e.g.,
4700 ///
4701 /// @code
4702 /// union {
4703 ///   int i;
4704 ///   float f;
4705 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4706 ///    // f into the surrounding scope.x
4707 /// @endcode
4708 ///
4709 /// This routine is recursive, injecting the names of nested anonymous
4710 /// structs/unions into the owning context and scope as well.
4711 static bool
4712 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4713                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4714                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4715   bool Invalid = false;
4716 
4717   // Look every FieldDecl and IndirectFieldDecl with a name.
4718   for (auto *D : AnonRecord->decls()) {
4719     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4720         cast<NamedDecl>(D)->getDeclName()) {
4721       ValueDecl *VD = cast<ValueDecl>(D);
4722       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4723                                        VD->getLocation(),
4724                                        AnonRecord->isUnion())) {
4725         // C++ [class.union]p2:
4726         //   The names of the members of an anonymous union shall be
4727         //   distinct from the names of any other entity in the
4728         //   scope in which the anonymous union is declared.
4729         Invalid = true;
4730       } else {
4731         // C++ [class.union]p2:
4732         //   For the purpose of name lookup, after the anonymous union
4733         //   definition, the members of the anonymous union are
4734         //   considered to have been defined in the scope in which the
4735         //   anonymous union is declared.
4736         unsigned OldChainingSize = Chaining.size();
4737         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4738           Chaining.append(IF->chain_begin(), IF->chain_end());
4739         else
4740           Chaining.push_back(VD);
4741 
4742         assert(Chaining.size() >= 2);
4743         NamedDecl **NamedChain =
4744           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4745         for (unsigned i = 0; i < Chaining.size(); i++)
4746           NamedChain[i] = Chaining[i];
4747 
4748         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4749             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4750             VD->getType(), {NamedChain, Chaining.size()});
4751 
4752         for (const auto *Attr : VD->attrs())
4753           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4754 
4755         IndirectField->setAccess(AS);
4756         IndirectField->setImplicit();
4757         SemaRef.PushOnScopeChains(IndirectField, S);
4758 
4759         // That includes picking up the appropriate access specifier.
4760         if (AS != AS_none) IndirectField->setAccess(AS);
4761 
4762         Chaining.resize(OldChainingSize);
4763       }
4764     }
4765   }
4766 
4767   return Invalid;
4768 }
4769 
4770 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4771 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4772 /// illegal input values are mapped to SC_None.
4773 static StorageClass
4774 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4775   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4776   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4777          "Parser allowed 'typedef' as storage class VarDecl.");
4778   switch (StorageClassSpec) {
4779   case DeclSpec::SCS_unspecified:    return SC_None;
4780   case DeclSpec::SCS_extern:
4781     if (DS.isExternInLinkageSpec())
4782       return SC_None;
4783     return SC_Extern;
4784   case DeclSpec::SCS_static:         return SC_Static;
4785   case DeclSpec::SCS_auto:           return SC_Auto;
4786   case DeclSpec::SCS_register:       return SC_Register;
4787   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4788     // Illegal SCSs map to None: error reporting is up to the caller.
4789   case DeclSpec::SCS_mutable:        // Fall through.
4790   case DeclSpec::SCS_typedef:        return SC_None;
4791   }
4792   llvm_unreachable("unknown storage class specifier");
4793 }
4794 
4795 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4796   assert(Record->hasInClassInitializer());
4797 
4798   for (const auto *I : Record->decls()) {
4799     const auto *FD = dyn_cast<FieldDecl>(I);
4800     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4801       FD = IFD->getAnonField();
4802     if (FD && FD->hasInClassInitializer())
4803       return FD->getLocation();
4804   }
4805 
4806   llvm_unreachable("couldn't find in-class initializer");
4807 }
4808 
4809 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4810                                       SourceLocation DefaultInitLoc) {
4811   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4812     return;
4813 
4814   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4815   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4816 }
4817 
4818 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4819                                       CXXRecordDecl *AnonUnion) {
4820   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4821     return;
4822 
4823   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4824 }
4825 
4826 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4827 /// anonymous structure or union. Anonymous unions are a C++ feature
4828 /// (C++ [class.union]) and a C11 feature; anonymous structures
4829 /// are a C11 feature and GNU C++ extension.
4830 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4831                                         AccessSpecifier AS,
4832                                         RecordDecl *Record,
4833                                         const PrintingPolicy &Policy) {
4834   DeclContext *Owner = Record->getDeclContext();
4835 
4836   // Diagnose whether this anonymous struct/union is an extension.
4837   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4838     Diag(Record->getLocation(), diag::ext_anonymous_union);
4839   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4840     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4841   else if (!Record->isUnion() && !getLangOpts().C11)
4842     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4843 
4844   // C and C++ require different kinds of checks for anonymous
4845   // structs/unions.
4846   bool Invalid = false;
4847   if (getLangOpts().CPlusPlus) {
4848     const char *PrevSpec = nullptr;
4849     if (Record->isUnion()) {
4850       // C++ [class.union]p6:
4851       // C++17 [class.union.anon]p2:
4852       //   Anonymous unions declared in a named namespace or in the
4853       //   global namespace shall be declared static.
4854       unsigned DiagID;
4855       DeclContext *OwnerScope = Owner->getRedeclContext();
4856       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4857           (OwnerScope->isTranslationUnit() ||
4858            (OwnerScope->isNamespace() &&
4859             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
4860         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4861           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4862 
4863         // Recover by adding 'static'.
4864         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4865                                PrevSpec, DiagID, Policy);
4866       }
4867       // C++ [class.union]p6:
4868       //   A storage class is not allowed in a declaration of an
4869       //   anonymous union in a class scope.
4870       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4871                isa<RecordDecl>(Owner)) {
4872         Diag(DS.getStorageClassSpecLoc(),
4873              diag::err_anonymous_union_with_storage_spec)
4874           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4875 
4876         // Recover by removing the storage specifier.
4877         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4878                                SourceLocation(),
4879                                PrevSpec, DiagID, Context.getPrintingPolicy());
4880       }
4881     }
4882 
4883     // Ignore const/volatile/restrict qualifiers.
4884     if (DS.getTypeQualifiers()) {
4885       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4886         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4887           << Record->isUnion() << "const"
4888           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4889       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4890         Diag(DS.getVolatileSpecLoc(),
4891              diag::ext_anonymous_struct_union_qualified)
4892           << Record->isUnion() << "volatile"
4893           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4894       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4895         Diag(DS.getRestrictSpecLoc(),
4896              diag::ext_anonymous_struct_union_qualified)
4897           << Record->isUnion() << "restrict"
4898           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4899       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4900         Diag(DS.getAtomicSpecLoc(),
4901              diag::ext_anonymous_struct_union_qualified)
4902           << Record->isUnion() << "_Atomic"
4903           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4904       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4905         Diag(DS.getUnalignedSpecLoc(),
4906              diag::ext_anonymous_struct_union_qualified)
4907           << Record->isUnion() << "__unaligned"
4908           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4909 
4910       DS.ClearTypeQualifiers();
4911     }
4912 
4913     // C++ [class.union]p2:
4914     //   The member-specification of an anonymous union shall only
4915     //   define non-static data members. [Note: nested types and
4916     //   functions cannot be declared within an anonymous union. ]
4917     for (auto *Mem : Record->decls()) {
4918       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4919         // C++ [class.union]p3:
4920         //   An anonymous union shall not have private or protected
4921         //   members (clause 11).
4922         assert(FD->getAccess() != AS_none);
4923         if (FD->getAccess() != AS_public) {
4924           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4925             << Record->isUnion() << (FD->getAccess() == AS_protected);
4926           Invalid = true;
4927         }
4928 
4929         // C++ [class.union]p1
4930         //   An object of a class with a non-trivial constructor, a non-trivial
4931         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4932         //   assignment operator cannot be a member of a union, nor can an
4933         //   array of such objects.
4934         if (CheckNontrivialField(FD))
4935           Invalid = true;
4936       } else if (Mem->isImplicit()) {
4937         // Any implicit members are fine.
4938       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4939         // This is a type that showed up in an
4940         // elaborated-type-specifier inside the anonymous struct or
4941         // union, but which actually declares a type outside of the
4942         // anonymous struct or union. It's okay.
4943       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4944         if (!MemRecord->isAnonymousStructOrUnion() &&
4945             MemRecord->getDeclName()) {
4946           // Visual C++ allows type definition in anonymous struct or union.
4947           if (getLangOpts().MicrosoftExt)
4948             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4949               << Record->isUnion();
4950           else {
4951             // This is a nested type declaration.
4952             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4953               << Record->isUnion();
4954             Invalid = true;
4955           }
4956         } else {
4957           // This is an anonymous type definition within another anonymous type.
4958           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4959           // not part of standard C++.
4960           Diag(MemRecord->getLocation(),
4961                diag::ext_anonymous_record_with_anonymous_type)
4962             << Record->isUnion();
4963         }
4964       } else if (isa<AccessSpecDecl>(Mem)) {
4965         // Any access specifier is fine.
4966       } else if (isa<StaticAssertDecl>(Mem)) {
4967         // In C++1z, static_assert declarations are also fine.
4968       } else {
4969         // We have something that isn't a non-static data
4970         // member. Complain about it.
4971         unsigned DK = diag::err_anonymous_record_bad_member;
4972         if (isa<TypeDecl>(Mem))
4973           DK = diag::err_anonymous_record_with_type;
4974         else if (isa<FunctionDecl>(Mem))
4975           DK = diag::err_anonymous_record_with_function;
4976         else if (isa<VarDecl>(Mem))
4977           DK = diag::err_anonymous_record_with_static;
4978 
4979         // Visual C++ allows type definition in anonymous struct or union.
4980         if (getLangOpts().MicrosoftExt &&
4981             DK == diag::err_anonymous_record_with_type)
4982           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4983             << Record->isUnion();
4984         else {
4985           Diag(Mem->getLocation(), DK) << Record->isUnion();
4986           Invalid = true;
4987         }
4988       }
4989     }
4990 
4991     // C++11 [class.union]p8 (DR1460):
4992     //   At most one variant member of a union may have a
4993     //   brace-or-equal-initializer.
4994     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4995         Owner->isRecord())
4996       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4997                                 cast<CXXRecordDecl>(Record));
4998   }
4999 
5000   if (!Record->isUnion() && !Owner->isRecord()) {
5001     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5002       << getLangOpts().CPlusPlus;
5003     Invalid = true;
5004   }
5005 
5006   // C++ [dcl.dcl]p3:
5007   //   [If there are no declarators], and except for the declaration of an
5008   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5009   //   names into the program
5010   // C++ [class.mem]p2:
5011   //   each such member-declaration shall either declare at least one member
5012   //   name of the class or declare at least one unnamed bit-field
5013   //
5014   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5015   if (getLangOpts().CPlusPlus && Record->field_empty())
5016     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5017 
5018   // Mock up a declarator.
5019   Declarator Dc(DS, DeclaratorContext::MemberContext);
5020   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5021   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5022 
5023   // Create a declaration for this anonymous struct/union.
5024   NamedDecl *Anon = nullptr;
5025   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5026     Anon = FieldDecl::Create(
5027         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5028         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5029         /*BitWidth=*/nullptr, /*Mutable=*/false,
5030         /*InitStyle=*/ICIS_NoInit);
5031     Anon->setAccess(AS);
5032     ProcessDeclAttributes(S, Anon, Dc);
5033 
5034     if (getLangOpts().CPlusPlus)
5035       FieldCollector->Add(cast<FieldDecl>(Anon));
5036   } else {
5037     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5038     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5039     if (SCSpec == DeclSpec::SCS_mutable) {
5040       // mutable can only appear on non-static class members, so it's always
5041       // an error here
5042       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5043       Invalid = true;
5044       SC = SC_None;
5045     }
5046 
5047     assert(DS.getAttributes().empty() && "No attribute expected");
5048     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5049                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5050                            Context.getTypeDeclType(Record), TInfo, SC);
5051 
5052     // Default-initialize the implicit variable. This initialization will be
5053     // trivial in almost all cases, except if a union member has an in-class
5054     // initializer:
5055     //   union { int n = 0; };
5056     ActOnUninitializedDecl(Anon);
5057   }
5058   Anon->setImplicit();
5059 
5060   // Mark this as an anonymous struct/union type.
5061   Record->setAnonymousStructOrUnion(true);
5062 
5063   // Add the anonymous struct/union object to the current
5064   // context. We'll be referencing this object when we refer to one of
5065   // its members.
5066   Owner->addDecl(Anon);
5067 
5068   // Inject the members of the anonymous struct/union into the owning
5069   // context and into the identifier resolver chain for name lookup
5070   // purposes.
5071   SmallVector<NamedDecl*, 2> Chain;
5072   Chain.push_back(Anon);
5073 
5074   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5075     Invalid = true;
5076 
5077   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5078     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5079       MangleNumberingContext *MCtx;
5080       Decl *ManglingContextDecl;
5081       std::tie(MCtx, ManglingContextDecl) =
5082           getCurrentMangleNumberContext(NewVD->getDeclContext());
5083       if (MCtx) {
5084         Context.setManglingNumber(
5085             NewVD, MCtx->getManglingNumber(
5086                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5087         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5088       }
5089     }
5090   }
5091 
5092   if (Invalid)
5093     Anon->setInvalidDecl();
5094 
5095   return Anon;
5096 }
5097 
5098 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5099 /// Microsoft C anonymous structure.
5100 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5101 /// Example:
5102 ///
5103 /// struct A { int a; };
5104 /// struct B { struct A; int b; };
5105 ///
5106 /// void foo() {
5107 ///   B var;
5108 ///   var.a = 3;
5109 /// }
5110 ///
5111 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5112                                            RecordDecl *Record) {
5113   assert(Record && "expected a record!");
5114 
5115   // Mock up a declarator.
5116   Declarator Dc(DS, DeclaratorContext::TypeNameContext);
5117   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5118   assert(TInfo && "couldn't build declarator info for anonymous struct");
5119 
5120   auto *ParentDecl = cast<RecordDecl>(CurContext);
5121   QualType RecTy = Context.getTypeDeclType(Record);
5122 
5123   // Create a declaration for this anonymous struct.
5124   NamedDecl *Anon =
5125       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5126                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5127                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5128                         /*InitStyle=*/ICIS_NoInit);
5129   Anon->setImplicit();
5130 
5131   // Add the anonymous struct object to the current context.
5132   CurContext->addDecl(Anon);
5133 
5134   // Inject the members of the anonymous struct into the current
5135   // context and into the identifier resolver chain for name lookup
5136   // purposes.
5137   SmallVector<NamedDecl*, 2> Chain;
5138   Chain.push_back(Anon);
5139 
5140   RecordDecl *RecordDef = Record->getDefinition();
5141   if (RequireCompleteType(Anon->getLocation(), RecTy,
5142                           diag::err_field_incomplete) ||
5143       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5144                                           AS_none, Chain)) {
5145     Anon->setInvalidDecl();
5146     ParentDecl->setInvalidDecl();
5147   }
5148 
5149   return Anon;
5150 }
5151 
5152 /// GetNameForDeclarator - Determine the full declaration name for the
5153 /// given Declarator.
5154 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5155   return GetNameFromUnqualifiedId(D.getName());
5156 }
5157 
5158 /// Retrieves the declaration name from a parsed unqualified-id.
5159 DeclarationNameInfo
5160 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5161   DeclarationNameInfo NameInfo;
5162   NameInfo.setLoc(Name.StartLocation);
5163 
5164   switch (Name.getKind()) {
5165 
5166   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5167   case UnqualifiedIdKind::IK_Identifier:
5168     NameInfo.setName(Name.Identifier);
5169     return NameInfo;
5170 
5171   case UnqualifiedIdKind::IK_DeductionGuideName: {
5172     // C++ [temp.deduct.guide]p3:
5173     //   The simple-template-id shall name a class template specialization.
5174     //   The template-name shall be the same identifier as the template-name
5175     //   of the simple-template-id.
5176     // These together intend to imply that the template-name shall name a
5177     // class template.
5178     // FIXME: template<typename T> struct X {};
5179     //        template<typename T> using Y = X<T>;
5180     //        Y(int) -> Y<int>;
5181     //   satisfies these rules but does not name a class template.
5182     TemplateName TN = Name.TemplateName.get().get();
5183     auto *Template = TN.getAsTemplateDecl();
5184     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5185       Diag(Name.StartLocation,
5186            diag::err_deduction_guide_name_not_class_template)
5187         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5188       if (Template)
5189         Diag(Template->getLocation(), diag::note_template_decl_here);
5190       return DeclarationNameInfo();
5191     }
5192 
5193     NameInfo.setName(
5194         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5195     return NameInfo;
5196   }
5197 
5198   case UnqualifiedIdKind::IK_OperatorFunctionId:
5199     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5200                                            Name.OperatorFunctionId.Operator));
5201     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
5202       = Name.OperatorFunctionId.SymbolLocations[0];
5203     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
5204       = Name.EndLocation.getRawEncoding();
5205     return NameInfo;
5206 
5207   case UnqualifiedIdKind::IK_LiteralOperatorId:
5208     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5209                                                            Name.Identifier));
5210     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5211     return NameInfo;
5212 
5213   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5214     TypeSourceInfo *TInfo;
5215     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5216     if (Ty.isNull())
5217       return DeclarationNameInfo();
5218     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5219                                                Context.getCanonicalType(Ty)));
5220     NameInfo.setNamedTypeInfo(TInfo);
5221     return NameInfo;
5222   }
5223 
5224   case UnqualifiedIdKind::IK_ConstructorName: {
5225     TypeSourceInfo *TInfo;
5226     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5227     if (Ty.isNull())
5228       return DeclarationNameInfo();
5229     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5230                                               Context.getCanonicalType(Ty)));
5231     NameInfo.setNamedTypeInfo(TInfo);
5232     return NameInfo;
5233   }
5234 
5235   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5236     // In well-formed code, we can only have a constructor
5237     // template-id that refers to the current context, so go there
5238     // to find the actual type being constructed.
5239     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5240     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5241       return DeclarationNameInfo();
5242 
5243     // Determine the type of the class being constructed.
5244     QualType CurClassType = Context.getTypeDeclType(CurClass);
5245 
5246     // FIXME: Check two things: that the template-id names the same type as
5247     // CurClassType, and that the template-id does not occur when the name
5248     // was qualified.
5249 
5250     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5251                                     Context.getCanonicalType(CurClassType)));
5252     // FIXME: should we retrieve TypeSourceInfo?
5253     NameInfo.setNamedTypeInfo(nullptr);
5254     return NameInfo;
5255   }
5256 
5257   case UnqualifiedIdKind::IK_DestructorName: {
5258     TypeSourceInfo *TInfo;
5259     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5260     if (Ty.isNull())
5261       return DeclarationNameInfo();
5262     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5263                                               Context.getCanonicalType(Ty)));
5264     NameInfo.setNamedTypeInfo(TInfo);
5265     return NameInfo;
5266   }
5267 
5268   case UnqualifiedIdKind::IK_TemplateId: {
5269     TemplateName TName = Name.TemplateId->Template.get();
5270     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5271     return Context.getNameForTemplate(TName, TNameLoc);
5272   }
5273 
5274   } // switch (Name.getKind())
5275 
5276   llvm_unreachable("Unknown name kind");
5277 }
5278 
5279 static QualType getCoreType(QualType Ty) {
5280   do {
5281     if (Ty->isPointerType() || Ty->isReferenceType())
5282       Ty = Ty->getPointeeType();
5283     else if (Ty->isArrayType())
5284       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5285     else
5286       return Ty.withoutLocalFastQualifiers();
5287   } while (true);
5288 }
5289 
5290 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5291 /// and Definition have "nearly" matching parameters. This heuristic is
5292 /// used to improve diagnostics in the case where an out-of-line function
5293 /// definition doesn't match any declaration within the class or namespace.
5294 /// Also sets Params to the list of indices to the parameters that differ
5295 /// between the declaration and the definition. If hasSimilarParameters
5296 /// returns true and Params is empty, then all of the parameters match.
5297 static bool hasSimilarParameters(ASTContext &Context,
5298                                      FunctionDecl *Declaration,
5299                                      FunctionDecl *Definition,
5300                                      SmallVectorImpl<unsigned> &Params) {
5301   Params.clear();
5302   if (Declaration->param_size() != Definition->param_size())
5303     return false;
5304   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5305     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5306     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5307 
5308     // The parameter types are identical
5309     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5310       continue;
5311 
5312     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5313     QualType DefParamBaseTy = getCoreType(DefParamTy);
5314     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5315     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5316 
5317     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5318         (DeclTyName && DeclTyName == DefTyName))
5319       Params.push_back(Idx);
5320     else  // The two parameters aren't even close
5321       return false;
5322   }
5323 
5324   return true;
5325 }
5326 
5327 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5328 /// declarator needs to be rebuilt in the current instantiation.
5329 /// Any bits of declarator which appear before the name are valid for
5330 /// consideration here.  That's specifically the type in the decl spec
5331 /// and the base type in any member-pointer chunks.
5332 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5333                                                     DeclarationName Name) {
5334   // The types we specifically need to rebuild are:
5335   //   - typenames, typeofs, and decltypes
5336   //   - types which will become injected class names
5337   // Of course, we also need to rebuild any type referencing such a
5338   // type.  It's safest to just say "dependent", but we call out a
5339   // few cases here.
5340 
5341   DeclSpec &DS = D.getMutableDeclSpec();
5342   switch (DS.getTypeSpecType()) {
5343   case DeclSpec::TST_typename:
5344   case DeclSpec::TST_typeofType:
5345   case DeclSpec::TST_underlyingType:
5346   case DeclSpec::TST_atomic: {
5347     // Grab the type from the parser.
5348     TypeSourceInfo *TSI = nullptr;
5349     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5350     if (T.isNull() || !T->isDependentType()) break;
5351 
5352     // Make sure there's a type source info.  This isn't really much
5353     // of a waste; most dependent types should have type source info
5354     // attached already.
5355     if (!TSI)
5356       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5357 
5358     // Rebuild the type in the current instantiation.
5359     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5360     if (!TSI) return true;
5361 
5362     // Store the new type back in the decl spec.
5363     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5364     DS.UpdateTypeRep(LocType);
5365     break;
5366   }
5367 
5368   case DeclSpec::TST_decltype:
5369   case DeclSpec::TST_typeofExpr: {
5370     Expr *E = DS.getRepAsExpr();
5371     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5372     if (Result.isInvalid()) return true;
5373     DS.UpdateExprRep(Result.get());
5374     break;
5375   }
5376 
5377   default:
5378     // Nothing to do for these decl specs.
5379     break;
5380   }
5381 
5382   // It doesn't matter what order we do this in.
5383   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5384     DeclaratorChunk &Chunk = D.getTypeObject(I);
5385 
5386     // The only type information in the declarator which can come
5387     // before the declaration name is the base type of a member
5388     // pointer.
5389     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5390       continue;
5391 
5392     // Rebuild the scope specifier in-place.
5393     CXXScopeSpec &SS = Chunk.Mem.Scope();
5394     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5395       return true;
5396   }
5397 
5398   return false;
5399 }
5400 
5401 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5402   D.setFunctionDefinitionKind(FDK_Declaration);
5403   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5404 
5405   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5406       Dcl && Dcl->getDeclContext()->isFileContext())
5407     Dcl->setTopLevelDeclInObjCContainer();
5408 
5409   if (getLangOpts().OpenCL)
5410     setCurrentOpenCLExtensionForDecl(Dcl);
5411 
5412   return Dcl;
5413 }
5414 
5415 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5416 ///   If T is the name of a class, then each of the following shall have a
5417 ///   name different from T:
5418 ///     - every static data member of class T;
5419 ///     - every member function of class T
5420 ///     - every member of class T that is itself a type;
5421 /// \returns true if the declaration name violates these rules.
5422 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5423                                    DeclarationNameInfo NameInfo) {
5424   DeclarationName Name = NameInfo.getName();
5425 
5426   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5427   while (Record && Record->isAnonymousStructOrUnion())
5428     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5429   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5430     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5431     return true;
5432   }
5433 
5434   return false;
5435 }
5436 
5437 /// Diagnose a declaration whose declarator-id has the given
5438 /// nested-name-specifier.
5439 ///
5440 /// \param SS The nested-name-specifier of the declarator-id.
5441 ///
5442 /// \param DC The declaration context to which the nested-name-specifier
5443 /// resolves.
5444 ///
5445 /// \param Name The name of the entity being declared.
5446 ///
5447 /// \param Loc The location of the name of the entity being declared.
5448 ///
5449 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5450 /// we're declaring an explicit / partial specialization / instantiation.
5451 ///
5452 /// \returns true if we cannot safely recover from this error, false otherwise.
5453 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5454                                         DeclarationName Name,
5455                                         SourceLocation Loc, bool IsTemplateId) {
5456   DeclContext *Cur = CurContext;
5457   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5458     Cur = Cur->getParent();
5459 
5460   // If the user provided a superfluous scope specifier that refers back to the
5461   // class in which the entity is already declared, diagnose and ignore it.
5462   //
5463   // class X {
5464   //   void X::f();
5465   // };
5466   //
5467   // Note, it was once ill-formed to give redundant qualification in all
5468   // contexts, but that rule was removed by DR482.
5469   if (Cur->Equals(DC)) {
5470     if (Cur->isRecord()) {
5471       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5472                                       : diag::err_member_extra_qualification)
5473         << Name << FixItHint::CreateRemoval(SS.getRange());
5474       SS.clear();
5475     } else {
5476       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5477     }
5478     return false;
5479   }
5480 
5481   // Check whether the qualifying scope encloses the scope of the original
5482   // declaration. For a template-id, we perform the checks in
5483   // CheckTemplateSpecializationScope.
5484   if (!Cur->Encloses(DC) && !IsTemplateId) {
5485     if (Cur->isRecord())
5486       Diag(Loc, diag::err_member_qualification)
5487         << Name << SS.getRange();
5488     else if (isa<TranslationUnitDecl>(DC))
5489       Diag(Loc, diag::err_invalid_declarator_global_scope)
5490         << Name << SS.getRange();
5491     else if (isa<FunctionDecl>(Cur))
5492       Diag(Loc, diag::err_invalid_declarator_in_function)
5493         << Name << SS.getRange();
5494     else if (isa<BlockDecl>(Cur))
5495       Diag(Loc, diag::err_invalid_declarator_in_block)
5496         << Name << SS.getRange();
5497     else
5498       Diag(Loc, diag::err_invalid_declarator_scope)
5499       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5500 
5501     return true;
5502   }
5503 
5504   if (Cur->isRecord()) {
5505     // Cannot qualify members within a class.
5506     Diag(Loc, diag::err_member_qualification)
5507       << Name << SS.getRange();
5508     SS.clear();
5509 
5510     // C++ constructors and destructors with incorrect scopes can break
5511     // our AST invariants by having the wrong underlying types. If
5512     // that's the case, then drop this declaration entirely.
5513     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5514          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5515         !Context.hasSameType(Name.getCXXNameType(),
5516                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5517       return true;
5518 
5519     return false;
5520   }
5521 
5522   // C++11 [dcl.meaning]p1:
5523   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5524   //   not begin with a decltype-specifer"
5525   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5526   while (SpecLoc.getPrefix())
5527     SpecLoc = SpecLoc.getPrefix();
5528   if (dyn_cast_or_null<DecltypeType>(
5529         SpecLoc.getNestedNameSpecifier()->getAsType()))
5530     Diag(Loc, diag::err_decltype_in_declarator)
5531       << SpecLoc.getTypeLoc().getSourceRange();
5532 
5533   return false;
5534 }
5535 
5536 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5537                                   MultiTemplateParamsArg TemplateParamLists) {
5538   // TODO: consider using NameInfo for diagnostic.
5539   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5540   DeclarationName Name = NameInfo.getName();
5541 
5542   // All of these full declarators require an identifier.  If it doesn't have
5543   // one, the ParsedFreeStandingDeclSpec action should be used.
5544   if (D.isDecompositionDeclarator()) {
5545     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5546   } else if (!Name) {
5547     if (!D.isInvalidType())  // Reject this if we think it is valid.
5548       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5549           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5550     return nullptr;
5551   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5552     return nullptr;
5553 
5554   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5555   // we find one that is.
5556   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5557          (S->getFlags() & Scope::TemplateParamScope) != 0)
5558     S = S->getParent();
5559 
5560   DeclContext *DC = CurContext;
5561   if (D.getCXXScopeSpec().isInvalid())
5562     D.setInvalidType();
5563   else if (D.getCXXScopeSpec().isSet()) {
5564     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5565                                         UPPC_DeclarationQualifier))
5566       return nullptr;
5567 
5568     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5569     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5570     if (!DC || isa<EnumDecl>(DC)) {
5571       // If we could not compute the declaration context, it's because the
5572       // declaration context is dependent but does not refer to a class,
5573       // class template, or class template partial specialization. Complain
5574       // and return early, to avoid the coming semantic disaster.
5575       Diag(D.getIdentifierLoc(),
5576            diag::err_template_qualified_declarator_no_match)
5577         << D.getCXXScopeSpec().getScopeRep()
5578         << D.getCXXScopeSpec().getRange();
5579       return nullptr;
5580     }
5581     bool IsDependentContext = DC->isDependentContext();
5582 
5583     if (!IsDependentContext &&
5584         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5585       return nullptr;
5586 
5587     // If a class is incomplete, do not parse entities inside it.
5588     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5589       Diag(D.getIdentifierLoc(),
5590            diag::err_member_def_undefined_record)
5591         << Name << DC << D.getCXXScopeSpec().getRange();
5592       return nullptr;
5593     }
5594     if (!D.getDeclSpec().isFriendSpecified()) {
5595       if (diagnoseQualifiedDeclaration(
5596               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5597               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5598         if (DC->isRecord())
5599           return nullptr;
5600 
5601         D.setInvalidType();
5602       }
5603     }
5604 
5605     // Check whether we need to rebuild the type of the given
5606     // declaration in the current instantiation.
5607     if (EnteringContext && IsDependentContext &&
5608         TemplateParamLists.size() != 0) {
5609       ContextRAII SavedContext(*this, DC);
5610       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5611         D.setInvalidType();
5612     }
5613   }
5614 
5615   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5616   QualType R = TInfo->getType();
5617 
5618   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5619                                       UPPC_DeclarationType))
5620     D.setInvalidType();
5621 
5622   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5623                         forRedeclarationInCurContext());
5624 
5625   // See if this is a redefinition of a variable in the same scope.
5626   if (!D.getCXXScopeSpec().isSet()) {
5627     bool IsLinkageLookup = false;
5628     bool CreateBuiltins = false;
5629 
5630     // If the declaration we're planning to build will be a function
5631     // or object with linkage, then look for another declaration with
5632     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5633     //
5634     // If the declaration we're planning to build will be declared with
5635     // external linkage in the translation unit, create any builtin with
5636     // the same name.
5637     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5638       /* Do nothing*/;
5639     else if (CurContext->isFunctionOrMethod() &&
5640              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5641               R->isFunctionType())) {
5642       IsLinkageLookup = true;
5643       CreateBuiltins =
5644           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5645     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5646                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5647       CreateBuiltins = true;
5648 
5649     if (IsLinkageLookup) {
5650       Previous.clear(LookupRedeclarationWithLinkage);
5651       Previous.setRedeclarationKind(ForExternalRedeclaration);
5652     }
5653 
5654     LookupName(Previous, S, CreateBuiltins);
5655   } else { // Something like "int foo::x;"
5656     LookupQualifiedName(Previous, DC);
5657 
5658     // C++ [dcl.meaning]p1:
5659     //   When the declarator-id is qualified, the declaration shall refer to a
5660     //  previously declared member of the class or namespace to which the
5661     //  qualifier refers (or, in the case of a namespace, of an element of the
5662     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5663     //  thereof; [...]
5664     //
5665     // Note that we already checked the context above, and that we do not have
5666     // enough information to make sure that Previous contains the declaration
5667     // we want to match. For example, given:
5668     //
5669     //   class X {
5670     //     void f();
5671     //     void f(float);
5672     //   };
5673     //
5674     //   void X::f(int) { } // ill-formed
5675     //
5676     // In this case, Previous will point to the overload set
5677     // containing the two f's declared in X, but neither of them
5678     // matches.
5679 
5680     // C++ [dcl.meaning]p1:
5681     //   [...] the member shall not merely have been introduced by a
5682     //   using-declaration in the scope of the class or namespace nominated by
5683     //   the nested-name-specifier of the declarator-id.
5684     RemoveUsingDecls(Previous);
5685   }
5686 
5687   if (Previous.isSingleResult() &&
5688       Previous.getFoundDecl()->isTemplateParameter()) {
5689     // Maybe we will complain about the shadowed template parameter.
5690     if (!D.isInvalidType())
5691       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5692                                       Previous.getFoundDecl());
5693 
5694     // Just pretend that we didn't see the previous declaration.
5695     Previous.clear();
5696   }
5697 
5698   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5699     // Forget that the previous declaration is the injected-class-name.
5700     Previous.clear();
5701 
5702   // In C++, the previous declaration we find might be a tag type
5703   // (class or enum). In this case, the new declaration will hide the
5704   // tag type. Note that this applies to functions, function templates, and
5705   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5706   if (Previous.isSingleTagDecl() &&
5707       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5708       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5709     Previous.clear();
5710 
5711   // Check that there are no default arguments other than in the parameters
5712   // of a function declaration (C++ only).
5713   if (getLangOpts().CPlusPlus)
5714     CheckExtraCXXDefaultArguments(D);
5715 
5716   NamedDecl *New;
5717 
5718   bool AddToScope = true;
5719   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5720     if (TemplateParamLists.size()) {
5721       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5722       return nullptr;
5723     }
5724 
5725     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5726   } else if (R->isFunctionType()) {
5727     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5728                                   TemplateParamLists,
5729                                   AddToScope);
5730   } else {
5731     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5732                                   AddToScope);
5733   }
5734 
5735   if (!New)
5736     return nullptr;
5737 
5738   // If this has an identifier and is not a function template specialization,
5739   // add it to the scope stack.
5740   if (New->getDeclName() && AddToScope)
5741     PushOnScopeChains(New, S);
5742 
5743   if (isInOpenMPDeclareTargetContext())
5744     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5745 
5746   return New;
5747 }
5748 
5749 /// Helper method to turn variable array types into constant array
5750 /// types in certain situations which would otherwise be errors (for
5751 /// GCC compatibility).
5752 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5753                                                     ASTContext &Context,
5754                                                     bool &SizeIsNegative,
5755                                                     llvm::APSInt &Oversized) {
5756   // This method tries to turn a variable array into a constant
5757   // array even when the size isn't an ICE.  This is necessary
5758   // for compatibility with code that depends on gcc's buggy
5759   // constant expression folding, like struct {char x[(int)(char*)2];}
5760   SizeIsNegative = false;
5761   Oversized = 0;
5762 
5763   if (T->isDependentType())
5764     return QualType();
5765 
5766   QualifierCollector Qs;
5767   const Type *Ty = Qs.strip(T);
5768 
5769   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5770     QualType Pointee = PTy->getPointeeType();
5771     QualType FixedType =
5772         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5773                                             Oversized);
5774     if (FixedType.isNull()) return FixedType;
5775     FixedType = Context.getPointerType(FixedType);
5776     return Qs.apply(Context, FixedType);
5777   }
5778   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5779     QualType Inner = PTy->getInnerType();
5780     QualType FixedType =
5781         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5782                                             Oversized);
5783     if (FixedType.isNull()) return FixedType;
5784     FixedType = Context.getParenType(FixedType);
5785     return Qs.apply(Context, FixedType);
5786   }
5787 
5788   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5789   if (!VLATy)
5790     return QualType();
5791   // FIXME: We should probably handle this case
5792   if (VLATy->getElementType()->isVariablyModifiedType())
5793     return QualType();
5794 
5795   Expr::EvalResult Result;
5796   if (!VLATy->getSizeExpr() ||
5797       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5798     return QualType();
5799 
5800   llvm::APSInt Res = Result.Val.getInt();
5801 
5802   // Check whether the array size is negative.
5803   if (Res.isSigned() && Res.isNegative()) {
5804     SizeIsNegative = true;
5805     return QualType();
5806   }
5807 
5808   // Check whether the array is too large to be addressed.
5809   unsigned ActiveSizeBits
5810     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5811                                               Res);
5812   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5813     Oversized = Res;
5814     return QualType();
5815   }
5816 
5817   return Context.getConstantArrayType(
5818       VLATy->getElementType(), Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
5819 }
5820 
5821 static void
5822 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5823   SrcTL = SrcTL.getUnqualifiedLoc();
5824   DstTL = DstTL.getUnqualifiedLoc();
5825   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5826     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5827     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5828                                       DstPTL.getPointeeLoc());
5829     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5830     return;
5831   }
5832   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5833     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5834     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5835                                       DstPTL.getInnerLoc());
5836     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5837     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5838     return;
5839   }
5840   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5841   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5842   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5843   TypeLoc DstElemTL = DstATL.getElementLoc();
5844   DstElemTL.initializeFullCopy(SrcElemTL);
5845   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5846   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5847   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5848 }
5849 
5850 /// Helper method to turn variable array types into constant array
5851 /// types in certain situations which would otherwise be errors (for
5852 /// GCC compatibility).
5853 static TypeSourceInfo*
5854 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5855                                               ASTContext &Context,
5856                                               bool &SizeIsNegative,
5857                                               llvm::APSInt &Oversized) {
5858   QualType FixedTy
5859     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5860                                           SizeIsNegative, Oversized);
5861   if (FixedTy.isNull())
5862     return nullptr;
5863   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5864   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5865                                     FixedTInfo->getTypeLoc());
5866   return FixedTInfo;
5867 }
5868 
5869 /// Register the given locally-scoped extern "C" declaration so
5870 /// that it can be found later for redeclarations. We include any extern "C"
5871 /// declaration that is not visible in the translation unit here, not just
5872 /// function-scope declarations.
5873 void
5874 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5875   if (!getLangOpts().CPlusPlus &&
5876       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5877     // Don't need to track declarations in the TU in C.
5878     return;
5879 
5880   // Note that we have a locally-scoped external with this name.
5881   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5882 }
5883 
5884 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5885   // FIXME: We can have multiple results via __attribute__((overloadable)).
5886   auto Result = Context.getExternCContextDecl()->lookup(Name);
5887   return Result.empty() ? nullptr : *Result.begin();
5888 }
5889 
5890 /// Diagnose function specifiers on a declaration of an identifier that
5891 /// does not identify a function.
5892 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5893   // FIXME: We should probably indicate the identifier in question to avoid
5894   // confusion for constructs like "virtual int a(), b;"
5895   if (DS.isVirtualSpecified())
5896     Diag(DS.getVirtualSpecLoc(),
5897          diag::err_virtual_non_function);
5898 
5899   if (DS.hasExplicitSpecifier())
5900     Diag(DS.getExplicitSpecLoc(),
5901          diag::err_explicit_non_function);
5902 
5903   if (DS.isNoreturnSpecified())
5904     Diag(DS.getNoreturnSpecLoc(),
5905          diag::err_noreturn_non_function);
5906 }
5907 
5908 NamedDecl*
5909 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5910                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5911   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5912   if (D.getCXXScopeSpec().isSet()) {
5913     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5914       << D.getCXXScopeSpec().getRange();
5915     D.setInvalidType();
5916     // Pretend we didn't see the scope specifier.
5917     DC = CurContext;
5918     Previous.clear();
5919   }
5920 
5921   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5922 
5923   if (D.getDeclSpec().isInlineSpecified())
5924     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5925         << getLangOpts().CPlusPlus17;
5926   if (D.getDeclSpec().hasConstexprSpecifier())
5927     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5928         << 1 << D.getDeclSpec().getConstexprSpecifier();
5929 
5930   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
5931     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
5932       Diag(D.getName().StartLocation,
5933            diag::err_deduction_guide_invalid_specifier)
5934           << "typedef";
5935     else
5936       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5937           << D.getName().getSourceRange();
5938     return nullptr;
5939   }
5940 
5941   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5942   if (!NewTD) return nullptr;
5943 
5944   // Handle attributes prior to checking for duplicates in MergeVarDecl
5945   ProcessDeclAttributes(S, NewTD, D);
5946 
5947   CheckTypedefForVariablyModifiedType(S, NewTD);
5948 
5949   bool Redeclaration = D.isRedeclaration();
5950   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5951   D.setRedeclaration(Redeclaration);
5952   return ND;
5953 }
5954 
5955 void
5956 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5957   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5958   // then it shall have block scope.
5959   // Note that variably modified types must be fixed before merging the decl so
5960   // that redeclarations will match.
5961   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5962   QualType T = TInfo->getType();
5963   if (T->isVariablyModifiedType()) {
5964     setFunctionHasBranchProtectedScope();
5965 
5966     if (S->getFnParent() == nullptr) {
5967       bool SizeIsNegative;
5968       llvm::APSInt Oversized;
5969       TypeSourceInfo *FixedTInfo =
5970         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5971                                                       SizeIsNegative,
5972                                                       Oversized);
5973       if (FixedTInfo) {
5974         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5975         NewTD->setTypeSourceInfo(FixedTInfo);
5976       } else {
5977         if (SizeIsNegative)
5978           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5979         else if (T->isVariableArrayType())
5980           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5981         else if (Oversized.getBoolValue())
5982           Diag(NewTD->getLocation(), diag::err_array_too_large)
5983             << Oversized.toString(10);
5984         else
5985           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5986         NewTD->setInvalidDecl();
5987       }
5988     }
5989   }
5990 }
5991 
5992 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5993 /// declares a typedef-name, either using the 'typedef' type specifier or via
5994 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5995 NamedDecl*
5996 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5997                            LookupResult &Previous, bool &Redeclaration) {
5998 
5999   // Find the shadowed declaration before filtering for scope.
6000   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6001 
6002   // Merge the decl with the existing one if appropriate. If the decl is
6003   // in an outer scope, it isn't the same thing.
6004   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6005                        /*AllowInlineNamespace*/false);
6006   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6007   if (!Previous.empty()) {
6008     Redeclaration = true;
6009     MergeTypedefNameDecl(S, NewTD, Previous);
6010   } else {
6011     inferGslPointerAttribute(NewTD);
6012   }
6013 
6014   if (ShadowedDecl && !Redeclaration)
6015     CheckShadow(NewTD, ShadowedDecl, Previous);
6016 
6017   // If this is the C FILE type, notify the AST context.
6018   if (IdentifierInfo *II = NewTD->getIdentifier())
6019     if (!NewTD->isInvalidDecl() &&
6020         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6021       if (II->isStr("FILE"))
6022         Context.setFILEDecl(NewTD);
6023       else if (II->isStr("jmp_buf"))
6024         Context.setjmp_bufDecl(NewTD);
6025       else if (II->isStr("sigjmp_buf"))
6026         Context.setsigjmp_bufDecl(NewTD);
6027       else if (II->isStr("ucontext_t"))
6028         Context.setucontext_tDecl(NewTD);
6029     }
6030 
6031   return NewTD;
6032 }
6033 
6034 /// Determines whether the given declaration is an out-of-scope
6035 /// previous declaration.
6036 ///
6037 /// This routine should be invoked when name lookup has found a
6038 /// previous declaration (PrevDecl) that is not in the scope where a
6039 /// new declaration by the same name is being introduced. If the new
6040 /// declaration occurs in a local scope, previous declarations with
6041 /// linkage may still be considered previous declarations (C99
6042 /// 6.2.2p4-5, C++ [basic.link]p6).
6043 ///
6044 /// \param PrevDecl the previous declaration found by name
6045 /// lookup
6046 ///
6047 /// \param DC the context in which the new declaration is being
6048 /// declared.
6049 ///
6050 /// \returns true if PrevDecl is an out-of-scope previous declaration
6051 /// for a new delcaration with the same name.
6052 static bool
6053 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6054                                 ASTContext &Context) {
6055   if (!PrevDecl)
6056     return false;
6057 
6058   if (!PrevDecl->hasLinkage())
6059     return false;
6060 
6061   if (Context.getLangOpts().CPlusPlus) {
6062     // C++ [basic.link]p6:
6063     //   If there is a visible declaration of an entity with linkage
6064     //   having the same name and type, ignoring entities declared
6065     //   outside the innermost enclosing namespace scope, the block
6066     //   scope declaration declares that same entity and receives the
6067     //   linkage of the previous declaration.
6068     DeclContext *OuterContext = DC->getRedeclContext();
6069     if (!OuterContext->isFunctionOrMethod())
6070       // This rule only applies to block-scope declarations.
6071       return false;
6072 
6073     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6074     if (PrevOuterContext->isRecord())
6075       // We found a member function: ignore it.
6076       return false;
6077 
6078     // Find the innermost enclosing namespace for the new and
6079     // previous declarations.
6080     OuterContext = OuterContext->getEnclosingNamespaceContext();
6081     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6082 
6083     // The previous declaration is in a different namespace, so it
6084     // isn't the same function.
6085     if (!OuterContext->Equals(PrevOuterContext))
6086       return false;
6087   }
6088 
6089   return true;
6090 }
6091 
6092 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6093   CXXScopeSpec &SS = D.getCXXScopeSpec();
6094   if (!SS.isSet()) return;
6095   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6096 }
6097 
6098 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6099   QualType type = decl->getType();
6100   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6101   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6102     // Various kinds of declaration aren't allowed to be __autoreleasing.
6103     unsigned kind = -1U;
6104     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6105       if (var->hasAttr<BlocksAttr>())
6106         kind = 0; // __block
6107       else if (!var->hasLocalStorage())
6108         kind = 1; // global
6109     } else if (isa<ObjCIvarDecl>(decl)) {
6110       kind = 3; // ivar
6111     } else if (isa<FieldDecl>(decl)) {
6112       kind = 2; // field
6113     }
6114 
6115     if (kind != -1U) {
6116       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6117         << kind;
6118     }
6119   } else if (lifetime == Qualifiers::OCL_None) {
6120     // Try to infer lifetime.
6121     if (!type->isObjCLifetimeType())
6122       return false;
6123 
6124     lifetime = type->getObjCARCImplicitLifetime();
6125     type = Context.getLifetimeQualifiedType(type, lifetime);
6126     decl->setType(type);
6127   }
6128 
6129   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6130     // Thread-local variables cannot have lifetime.
6131     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6132         var->getTLSKind()) {
6133       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6134         << var->getType();
6135       return true;
6136     }
6137   }
6138 
6139   return false;
6140 }
6141 
6142 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6143   if (Decl->getType().hasAddressSpace())
6144     return;
6145   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6146     QualType Type = Var->getType();
6147     if (Type->isSamplerT() || Type->isVoidType())
6148       return;
6149     LangAS ImplAS = LangAS::opencl_private;
6150     if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) &&
6151         Var->hasGlobalStorage())
6152       ImplAS = LangAS::opencl_global;
6153     // If the original type from a decayed type is an array type and that array
6154     // type has no address space yet, deduce it now.
6155     if (auto DT = dyn_cast<DecayedType>(Type)) {
6156       auto OrigTy = DT->getOriginalType();
6157       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6158         // Add the address space to the original array type and then propagate
6159         // that to the element type through `getAsArrayType`.
6160         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6161         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6162         // Re-generate the decayed type.
6163         Type = Context.getDecayedType(OrigTy);
6164       }
6165     }
6166     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6167     // Apply any qualifiers (including address space) from the array type to
6168     // the element type. This implements C99 6.7.3p8: "If the specification of
6169     // an array type includes any type qualifiers, the element type is so
6170     // qualified, not the array type."
6171     if (Type->isArrayType())
6172       Type = QualType(Context.getAsArrayType(Type), 0);
6173     Decl->setType(Type);
6174   }
6175 }
6176 
6177 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6178   // Ensure that an auto decl is deduced otherwise the checks below might cache
6179   // the wrong linkage.
6180   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6181 
6182   // 'weak' only applies to declarations with external linkage.
6183   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6184     if (!ND.isExternallyVisible()) {
6185       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6186       ND.dropAttr<WeakAttr>();
6187     }
6188   }
6189   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6190     if (ND.isExternallyVisible()) {
6191       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6192       ND.dropAttr<WeakRefAttr>();
6193       ND.dropAttr<AliasAttr>();
6194     }
6195   }
6196 
6197   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6198     if (VD->hasInit()) {
6199       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6200         assert(VD->isThisDeclarationADefinition() &&
6201                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6202         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6203         VD->dropAttr<AliasAttr>();
6204       }
6205     }
6206   }
6207 
6208   // 'selectany' only applies to externally visible variable declarations.
6209   // It does not apply to functions.
6210   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6211     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6212       S.Diag(Attr->getLocation(),
6213              diag::err_attribute_selectany_non_extern_data);
6214       ND.dropAttr<SelectAnyAttr>();
6215     }
6216   }
6217 
6218   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6219     auto *VD = dyn_cast<VarDecl>(&ND);
6220     bool IsAnonymousNS = false;
6221     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6222     if (VD) {
6223       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6224       while (NS && !IsAnonymousNS) {
6225         IsAnonymousNS = NS->isAnonymousNamespace();
6226         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6227       }
6228     }
6229     // dll attributes require external linkage. Static locals may have external
6230     // linkage but still cannot be explicitly imported or exported.
6231     // In Microsoft mode, a variable defined in anonymous namespace must have
6232     // external linkage in order to be exported.
6233     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6234     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6235         (!AnonNSInMicrosoftMode &&
6236          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6237       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6238         << &ND << Attr;
6239       ND.setInvalidDecl();
6240     }
6241   }
6242 
6243   // Virtual functions cannot be marked as 'notail'.
6244   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
6245     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
6246       if (MD->isVirtual()) {
6247         S.Diag(ND.getLocation(),
6248                diag::err_invalid_attribute_on_virtual_function)
6249             << Attr;
6250         ND.dropAttr<NotTailCalledAttr>();
6251       }
6252 
6253   // Check the attributes on the function type, if any.
6254   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6255     // Don't declare this variable in the second operand of the for-statement;
6256     // GCC miscompiles that by ending its lifetime before evaluating the
6257     // third operand. See gcc.gnu.org/PR86769.
6258     AttributedTypeLoc ATL;
6259     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6260          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6261          TL = ATL.getModifiedLoc()) {
6262       // The [[lifetimebound]] attribute can be applied to the implicit object
6263       // parameter of a non-static member function (other than a ctor or dtor)
6264       // by applying it to the function type.
6265       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6266         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6267         if (!MD || MD->isStatic()) {
6268           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6269               << !MD << A->getRange();
6270         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6271           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6272               << isa<CXXDestructorDecl>(MD) << A->getRange();
6273         }
6274       }
6275     }
6276   }
6277 }
6278 
6279 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6280                                            NamedDecl *NewDecl,
6281                                            bool IsSpecialization,
6282                                            bool IsDefinition) {
6283   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6284     return;
6285 
6286   bool IsTemplate = false;
6287   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6288     OldDecl = OldTD->getTemplatedDecl();
6289     IsTemplate = true;
6290     if (!IsSpecialization)
6291       IsDefinition = false;
6292   }
6293   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6294     NewDecl = NewTD->getTemplatedDecl();
6295     IsTemplate = true;
6296   }
6297 
6298   if (!OldDecl || !NewDecl)
6299     return;
6300 
6301   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6302   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6303   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6304   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6305 
6306   // dllimport and dllexport are inheritable attributes so we have to exclude
6307   // inherited attribute instances.
6308   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6309                     (NewExportAttr && !NewExportAttr->isInherited());
6310 
6311   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6312   // the only exception being explicit specializations.
6313   // Implicitly generated declarations are also excluded for now because there
6314   // is no other way to switch these to use dllimport or dllexport.
6315   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6316 
6317   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6318     // Allow with a warning for free functions and global variables.
6319     bool JustWarn = false;
6320     if (!OldDecl->isCXXClassMember()) {
6321       auto *VD = dyn_cast<VarDecl>(OldDecl);
6322       if (VD && !VD->getDescribedVarTemplate())
6323         JustWarn = true;
6324       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6325       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6326         JustWarn = true;
6327     }
6328 
6329     // We cannot change a declaration that's been used because IR has already
6330     // been emitted. Dllimported functions will still work though (modulo
6331     // address equality) as they can use the thunk.
6332     if (OldDecl->isUsed())
6333       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6334         JustWarn = false;
6335 
6336     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6337                                : diag::err_attribute_dll_redeclaration;
6338     S.Diag(NewDecl->getLocation(), DiagID)
6339         << NewDecl
6340         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6341     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6342     if (!JustWarn) {
6343       NewDecl->setInvalidDecl();
6344       return;
6345     }
6346   }
6347 
6348   // A redeclaration is not allowed to drop a dllimport attribute, the only
6349   // exceptions being inline function definitions (except for function
6350   // templates), local extern declarations, qualified friend declarations or
6351   // special MSVC extension: in the last case, the declaration is treated as if
6352   // it were marked dllexport.
6353   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6354   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6355   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6356     // Ignore static data because out-of-line definitions are diagnosed
6357     // separately.
6358     IsStaticDataMember = VD->isStaticDataMember();
6359     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6360                    VarDecl::DeclarationOnly;
6361   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6362     IsInline = FD->isInlined();
6363     IsQualifiedFriend = FD->getQualifier() &&
6364                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6365   }
6366 
6367   if (OldImportAttr && !HasNewAttr &&
6368       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6369       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6370     if (IsMicrosoft && IsDefinition) {
6371       S.Diag(NewDecl->getLocation(),
6372              diag::warn_redeclaration_without_import_attribute)
6373           << NewDecl;
6374       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6375       NewDecl->dropAttr<DLLImportAttr>();
6376       NewDecl->addAttr(
6377           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6378     } else {
6379       S.Diag(NewDecl->getLocation(),
6380              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6381           << NewDecl << OldImportAttr;
6382       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6383       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6384       OldDecl->dropAttr<DLLImportAttr>();
6385       NewDecl->dropAttr<DLLImportAttr>();
6386     }
6387   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6388     // In MinGW, seeing a function declared inline drops the dllimport
6389     // attribute.
6390     OldDecl->dropAttr<DLLImportAttr>();
6391     NewDecl->dropAttr<DLLImportAttr>();
6392     S.Diag(NewDecl->getLocation(),
6393            diag::warn_dllimport_dropped_from_inline_function)
6394         << NewDecl << OldImportAttr;
6395   }
6396 
6397   // A specialization of a class template member function is processed here
6398   // since it's a redeclaration. If the parent class is dllexport, the
6399   // specialization inherits that attribute. This doesn't happen automatically
6400   // since the parent class isn't instantiated until later.
6401   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6402     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6403         !NewImportAttr && !NewExportAttr) {
6404       if (const DLLExportAttr *ParentExportAttr =
6405               MD->getParent()->getAttr<DLLExportAttr>()) {
6406         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6407         NewAttr->setInherited(true);
6408         NewDecl->addAttr(NewAttr);
6409       }
6410     }
6411   }
6412 }
6413 
6414 /// Given that we are within the definition of the given function,
6415 /// will that definition behave like C99's 'inline', where the
6416 /// definition is discarded except for optimization purposes?
6417 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6418   // Try to avoid calling GetGVALinkageForFunction.
6419 
6420   // All cases of this require the 'inline' keyword.
6421   if (!FD->isInlined()) return false;
6422 
6423   // This is only possible in C++ with the gnu_inline attribute.
6424   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6425     return false;
6426 
6427   // Okay, go ahead and call the relatively-more-expensive function.
6428   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6429 }
6430 
6431 /// Determine whether a variable is extern "C" prior to attaching
6432 /// an initializer. We can't just call isExternC() here, because that
6433 /// will also compute and cache whether the declaration is externally
6434 /// visible, which might change when we attach the initializer.
6435 ///
6436 /// This can only be used if the declaration is known to not be a
6437 /// redeclaration of an internal linkage declaration.
6438 ///
6439 /// For instance:
6440 ///
6441 ///   auto x = []{};
6442 ///
6443 /// Attaching the initializer here makes this declaration not externally
6444 /// visible, because its type has internal linkage.
6445 ///
6446 /// FIXME: This is a hack.
6447 template<typename T>
6448 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6449   if (S.getLangOpts().CPlusPlus) {
6450     // In C++, the overloadable attribute negates the effects of extern "C".
6451     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6452       return false;
6453 
6454     // So do CUDA's host/device attributes.
6455     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6456                                  D->template hasAttr<CUDAHostAttr>()))
6457       return false;
6458   }
6459   return D->isExternC();
6460 }
6461 
6462 static bool shouldConsiderLinkage(const VarDecl *VD) {
6463   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6464   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6465       isa<OMPDeclareMapperDecl>(DC))
6466     return VD->hasExternalStorage();
6467   if (DC->isFileContext())
6468     return true;
6469   if (DC->isRecord())
6470     return false;
6471   llvm_unreachable("Unexpected context");
6472 }
6473 
6474 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6475   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6476   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6477       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6478     return true;
6479   if (DC->isRecord())
6480     return false;
6481   llvm_unreachable("Unexpected context");
6482 }
6483 
6484 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6485                           ParsedAttr::Kind Kind) {
6486   // Check decl attributes on the DeclSpec.
6487   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6488     return true;
6489 
6490   // Walk the declarator structure, checking decl attributes that were in a type
6491   // position to the decl itself.
6492   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6493     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6494       return true;
6495   }
6496 
6497   // Finally, check attributes on the decl itself.
6498   return PD.getAttributes().hasAttribute(Kind);
6499 }
6500 
6501 /// Adjust the \c DeclContext for a function or variable that might be a
6502 /// function-local external declaration.
6503 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6504   if (!DC->isFunctionOrMethod())
6505     return false;
6506 
6507   // If this is a local extern function or variable declared within a function
6508   // template, don't add it into the enclosing namespace scope until it is
6509   // instantiated; it might have a dependent type right now.
6510   if (DC->isDependentContext())
6511     return true;
6512 
6513   // C++11 [basic.link]p7:
6514   //   When a block scope declaration of an entity with linkage is not found to
6515   //   refer to some other declaration, then that entity is a member of the
6516   //   innermost enclosing namespace.
6517   //
6518   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6519   // semantically-enclosing namespace, not a lexically-enclosing one.
6520   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6521     DC = DC->getParent();
6522   return true;
6523 }
6524 
6525 /// Returns true if given declaration has external C language linkage.
6526 static bool isDeclExternC(const Decl *D) {
6527   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6528     return FD->isExternC();
6529   if (const auto *VD = dyn_cast<VarDecl>(D))
6530     return VD->isExternC();
6531 
6532   llvm_unreachable("Unknown type of decl!");
6533 }
6534 /// Returns true if there hasn't been any invalid type diagnosed.
6535 static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D,
6536                                 DeclContext *DC, QualType R) {
6537   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6538   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6539   // argument.
6540   if (R->isImageType() || R->isPipeType()) {
6541     Se.Diag(D.getIdentifierLoc(),
6542             diag::err_opencl_type_can_only_be_used_as_function_parameter)
6543         << R;
6544     D.setInvalidType();
6545     return false;
6546   }
6547 
6548   // OpenCL v1.2 s6.9.r:
6549   // The event type cannot be used to declare a program scope variable.
6550   // OpenCL v2.0 s6.9.q:
6551   // The clk_event_t and reserve_id_t types cannot be declared in program
6552   // scope.
6553   if (NULL == S->getParent()) {
6554     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6555       Se.Diag(D.getIdentifierLoc(),
6556               diag::err_invalid_type_for_program_scope_var)
6557           << R;
6558       D.setInvalidType();
6559       return false;
6560     }
6561   }
6562 
6563   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6564   QualType NR = R;
6565   while (NR->isPointerType()) {
6566     if (NR->isFunctionPointerType()) {
6567       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6568       D.setInvalidType();
6569       return false;
6570     }
6571     NR = NR->getPointeeType();
6572   }
6573 
6574   if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6575     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6576     // half array type (unless the cl_khr_fp16 extension is enabled).
6577     if (Se.Context.getBaseElementType(R)->isHalfType()) {
6578       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6579       D.setInvalidType();
6580       return false;
6581     }
6582   }
6583 
6584   // OpenCL v1.2 s6.9.r:
6585   // The event type cannot be used with the __local, __constant and __global
6586   // address space qualifiers.
6587   if (R->isEventT()) {
6588     if (R.getAddressSpace() != LangAS::opencl_private) {
6589       Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6590       D.setInvalidType();
6591       return false;
6592     }
6593   }
6594 
6595   // C++ for OpenCL does not allow the thread_local storage qualifier.
6596   // OpenCL C does not support thread_local either, and
6597   // also reject all other thread storage class specifiers.
6598   DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6599   if (TSC != TSCS_unspecified) {
6600     bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus;
6601     Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6602             diag::err_opencl_unknown_type_specifier)
6603         << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString()
6604         << DeclSpec::getSpecifierName(TSC) << 1;
6605     D.setInvalidType();
6606     return false;
6607   }
6608 
6609   if (R->isSamplerT()) {
6610     // OpenCL v1.2 s6.9.b p4:
6611     // The sampler type cannot be used with the __local and __global address
6612     // space qualifiers.
6613     if (R.getAddressSpace() == LangAS::opencl_local ||
6614         R.getAddressSpace() == LangAS::opencl_global) {
6615       Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6616       D.setInvalidType();
6617     }
6618 
6619     // OpenCL v1.2 s6.12.14.1:
6620     // A global sampler must be declared with either the constant address
6621     // space qualifier or with the const qualifier.
6622     if (DC->isTranslationUnit() &&
6623         !(R.getAddressSpace() == LangAS::opencl_constant ||
6624           R.isConstQualified())) {
6625       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6626       D.setInvalidType();
6627     }
6628     if (D.isInvalidType())
6629       return false;
6630   }
6631   return true;
6632 }
6633 
6634 NamedDecl *Sema::ActOnVariableDeclarator(
6635     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6636     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6637     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6638   QualType R = TInfo->getType();
6639   DeclarationName Name = GetNameForDeclarator(D).getName();
6640 
6641   IdentifierInfo *II = Name.getAsIdentifierInfo();
6642 
6643   if (D.isDecompositionDeclarator()) {
6644     // Take the name of the first declarator as our name for diagnostic
6645     // purposes.
6646     auto &Decomp = D.getDecompositionDeclarator();
6647     if (!Decomp.bindings().empty()) {
6648       II = Decomp.bindings()[0].Name;
6649       Name = II;
6650     }
6651   } else if (!II) {
6652     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6653     return nullptr;
6654   }
6655 
6656 
6657   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6658   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6659 
6660   // dllimport globals without explicit storage class are treated as extern. We
6661   // have to change the storage class this early to get the right DeclContext.
6662   if (SC == SC_None && !DC->isRecord() &&
6663       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6664       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6665     SC = SC_Extern;
6666 
6667   DeclContext *OriginalDC = DC;
6668   bool IsLocalExternDecl = SC == SC_Extern &&
6669                            adjustContextForLocalExternDecl(DC);
6670 
6671   if (SCSpec == DeclSpec::SCS_mutable) {
6672     // mutable can only appear on non-static class members, so it's always
6673     // an error here
6674     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6675     D.setInvalidType();
6676     SC = SC_None;
6677   }
6678 
6679   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6680       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6681                               D.getDeclSpec().getStorageClassSpecLoc())) {
6682     // In C++11, the 'register' storage class specifier is deprecated.
6683     // Suppress the warning in system macros, it's used in macros in some
6684     // popular C system headers, such as in glibc's htonl() macro.
6685     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6686          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6687                                    : diag::warn_deprecated_register)
6688       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6689   }
6690 
6691   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6692 
6693   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6694     // C99 6.9p2: The storage-class specifiers auto and register shall not
6695     // appear in the declaration specifiers in an external declaration.
6696     // Global Register+Asm is a GNU extension we support.
6697     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6698       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6699       D.setInvalidType();
6700     }
6701   }
6702 
6703   bool IsMemberSpecialization = false;
6704   bool IsVariableTemplateSpecialization = false;
6705   bool IsPartialSpecialization = false;
6706   bool IsVariableTemplate = false;
6707   VarDecl *NewVD = nullptr;
6708   VarTemplateDecl *NewTemplate = nullptr;
6709   TemplateParameterList *TemplateParams = nullptr;
6710   if (!getLangOpts().CPlusPlus) {
6711     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6712                             II, R, TInfo, SC);
6713 
6714     if (R->getContainedDeducedType())
6715       ParsingInitForAutoVars.insert(NewVD);
6716 
6717     if (D.isInvalidType())
6718       NewVD->setInvalidDecl();
6719 
6720     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
6721         NewVD->hasLocalStorage())
6722       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
6723                             NTCUC_AutoVar, NTCUK_Destruct);
6724   } else {
6725     bool Invalid = false;
6726 
6727     if (DC->isRecord() && !CurContext->isRecord()) {
6728       // This is an out-of-line definition of a static data member.
6729       switch (SC) {
6730       case SC_None:
6731         break;
6732       case SC_Static:
6733         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6734              diag::err_static_out_of_line)
6735           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6736         break;
6737       case SC_Auto:
6738       case SC_Register:
6739       case SC_Extern:
6740         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6741         // to names of variables declared in a block or to function parameters.
6742         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6743         // of class members
6744 
6745         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6746              diag::err_storage_class_for_static_member)
6747           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6748         break;
6749       case SC_PrivateExtern:
6750         llvm_unreachable("C storage class in c++!");
6751       }
6752     }
6753 
6754     if (SC == SC_Static && CurContext->isRecord()) {
6755       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6756         if (RD->isLocalClass())
6757           Diag(D.getIdentifierLoc(),
6758                diag::err_static_data_member_not_allowed_in_local_class)
6759             << Name << RD->getDeclName();
6760 
6761         // C++98 [class.union]p1: If a union contains a static data member,
6762         // the program is ill-formed. C++11 drops this restriction.
6763         if (RD->isUnion())
6764           Diag(D.getIdentifierLoc(),
6765                getLangOpts().CPlusPlus11
6766                  ? diag::warn_cxx98_compat_static_data_member_in_union
6767                  : diag::ext_static_data_member_in_union) << Name;
6768         // We conservatively disallow static data members in anonymous structs.
6769         else if (!RD->getDeclName())
6770           Diag(D.getIdentifierLoc(),
6771                diag::err_static_data_member_not_allowed_in_anon_struct)
6772             << Name << RD->isUnion();
6773       }
6774     }
6775 
6776     // Match up the template parameter lists with the scope specifier, then
6777     // determine whether we have a template or a template specialization.
6778     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6779         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6780         D.getCXXScopeSpec(),
6781         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6782             ? D.getName().TemplateId
6783             : nullptr,
6784         TemplateParamLists,
6785         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6786 
6787     if (TemplateParams) {
6788       if (!TemplateParams->size() &&
6789           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6790         // There is an extraneous 'template<>' for this variable. Complain
6791         // about it, but allow the declaration of the variable.
6792         Diag(TemplateParams->getTemplateLoc(),
6793              diag::err_template_variable_noparams)
6794           << II
6795           << SourceRange(TemplateParams->getTemplateLoc(),
6796                          TemplateParams->getRAngleLoc());
6797         TemplateParams = nullptr;
6798       } else {
6799         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6800           // This is an explicit specialization or a partial specialization.
6801           // FIXME: Check that we can declare a specialization here.
6802           IsVariableTemplateSpecialization = true;
6803           IsPartialSpecialization = TemplateParams->size() > 0;
6804         } else { // if (TemplateParams->size() > 0)
6805           // This is a template declaration.
6806           IsVariableTemplate = true;
6807 
6808           // Check that we can declare a template here.
6809           if (CheckTemplateDeclScope(S, TemplateParams))
6810             return nullptr;
6811 
6812           // Only C++1y supports variable templates (N3651).
6813           Diag(D.getIdentifierLoc(),
6814                getLangOpts().CPlusPlus14
6815                    ? diag::warn_cxx11_compat_variable_template
6816                    : diag::ext_variable_template);
6817         }
6818       }
6819     } else {
6820       assert((Invalid ||
6821               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
6822              "should have a 'template<>' for this decl");
6823     }
6824 
6825     if (IsVariableTemplateSpecialization) {
6826       SourceLocation TemplateKWLoc =
6827           TemplateParamLists.size() > 0
6828               ? TemplateParamLists[0]->getTemplateLoc()
6829               : SourceLocation();
6830       DeclResult Res = ActOnVarTemplateSpecialization(
6831           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6832           IsPartialSpecialization);
6833       if (Res.isInvalid())
6834         return nullptr;
6835       NewVD = cast<VarDecl>(Res.get());
6836       AddToScope = false;
6837     } else if (D.isDecompositionDeclarator()) {
6838       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
6839                                         D.getIdentifierLoc(), R, TInfo, SC,
6840                                         Bindings);
6841     } else
6842       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
6843                               D.getIdentifierLoc(), II, R, TInfo, SC);
6844 
6845     // If this is supposed to be a variable template, create it as such.
6846     if (IsVariableTemplate) {
6847       NewTemplate =
6848           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6849                                   TemplateParams, NewVD);
6850       NewVD->setDescribedVarTemplate(NewTemplate);
6851     }
6852 
6853     // If this decl has an auto type in need of deduction, make a note of the
6854     // Decl so we can diagnose uses of it in its own initializer.
6855     if (R->getContainedDeducedType())
6856       ParsingInitForAutoVars.insert(NewVD);
6857 
6858     if (D.isInvalidType() || Invalid) {
6859       NewVD->setInvalidDecl();
6860       if (NewTemplate)
6861         NewTemplate->setInvalidDecl();
6862     }
6863 
6864     SetNestedNameSpecifier(*this, NewVD, D);
6865 
6866     // If we have any template parameter lists that don't directly belong to
6867     // the variable (matching the scope specifier), store them.
6868     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6869     if (TemplateParamLists.size() > VDTemplateParamLists)
6870       NewVD->setTemplateParameterListsInfo(
6871           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6872   }
6873 
6874   if (D.getDeclSpec().isInlineSpecified()) {
6875     if (!getLangOpts().CPlusPlus) {
6876       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6877           << 0;
6878     } else if (CurContext->isFunctionOrMethod()) {
6879       // 'inline' is not allowed on block scope variable declaration.
6880       Diag(D.getDeclSpec().getInlineSpecLoc(),
6881            diag::err_inline_declaration_block_scope) << Name
6882         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6883     } else {
6884       Diag(D.getDeclSpec().getInlineSpecLoc(),
6885            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
6886                                      : diag::ext_inline_variable);
6887       NewVD->setInlineSpecified();
6888     }
6889   }
6890 
6891   // Set the lexical context. If the declarator has a C++ scope specifier, the
6892   // lexical context will be different from the semantic context.
6893   NewVD->setLexicalDeclContext(CurContext);
6894   if (NewTemplate)
6895     NewTemplate->setLexicalDeclContext(CurContext);
6896 
6897   if (IsLocalExternDecl) {
6898     if (D.isDecompositionDeclarator())
6899       for (auto *B : Bindings)
6900         B->setLocalExternDecl();
6901     else
6902       NewVD->setLocalExternDecl();
6903   }
6904 
6905   bool EmitTLSUnsupportedError = false;
6906   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6907     // C++11 [dcl.stc]p4:
6908     //   When thread_local is applied to a variable of block scope the
6909     //   storage-class-specifier static is implied if it does not appear
6910     //   explicitly.
6911     // Core issue: 'static' is not implied if the variable is declared
6912     //   'extern'.
6913     if (NewVD->hasLocalStorage() &&
6914         (SCSpec != DeclSpec::SCS_unspecified ||
6915          TSCS != DeclSpec::TSCS_thread_local ||
6916          !DC->isFunctionOrMethod()))
6917       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6918            diag::err_thread_non_global)
6919         << DeclSpec::getSpecifierName(TSCS);
6920     else if (!Context.getTargetInfo().isTLSSupported()) {
6921       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6922         // Postpone error emission until we've collected attributes required to
6923         // figure out whether it's a host or device variable and whether the
6924         // error should be ignored.
6925         EmitTLSUnsupportedError = true;
6926         // We still need to mark the variable as TLS so it shows up in AST with
6927         // proper storage class for other tools to use even if we're not going
6928         // to emit any code for it.
6929         NewVD->setTSCSpec(TSCS);
6930       } else
6931         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6932              diag::err_thread_unsupported);
6933     } else
6934       NewVD->setTSCSpec(TSCS);
6935   }
6936 
6937   switch (D.getDeclSpec().getConstexprSpecifier()) {
6938   case CSK_unspecified:
6939     break;
6940 
6941   case CSK_consteval:
6942     Diag(D.getDeclSpec().getConstexprSpecLoc(),
6943         diag::err_constexpr_wrong_decl_kind)
6944       << D.getDeclSpec().getConstexprSpecifier();
6945     LLVM_FALLTHROUGH;
6946 
6947   case CSK_constexpr:
6948     NewVD->setConstexpr(true);
6949     // C++1z [dcl.spec.constexpr]p1:
6950     //   A static data member declared with the constexpr specifier is
6951     //   implicitly an inline variable.
6952     if (NewVD->isStaticDataMember() &&
6953         (getLangOpts().CPlusPlus17 ||
6954          Context.getTargetInfo().getCXXABI().isMicrosoft()))
6955       NewVD->setImplicitlyInline();
6956     break;
6957 
6958   case CSK_constinit:
6959     if (!NewVD->hasGlobalStorage())
6960       Diag(D.getDeclSpec().getConstexprSpecLoc(),
6961            diag::err_constinit_local_variable);
6962     else
6963       NewVD->addAttr(ConstInitAttr::Create(
6964           Context, D.getDeclSpec().getConstexprSpecLoc(),
6965           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
6966     break;
6967   }
6968 
6969   // C99 6.7.4p3
6970   //   An inline definition of a function with external linkage shall
6971   //   not contain a definition of a modifiable object with static or
6972   //   thread storage duration...
6973   // We only apply this when the function is required to be defined
6974   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6975   // that a local variable with thread storage duration still has to
6976   // be marked 'static'.  Also note that it's possible to get these
6977   // semantics in C++ using __attribute__((gnu_inline)).
6978   if (SC == SC_Static && S->getFnParent() != nullptr &&
6979       !NewVD->getType().isConstQualified()) {
6980     FunctionDecl *CurFD = getCurFunctionDecl();
6981     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6982       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6983            diag::warn_static_local_in_extern_inline);
6984       MaybeSuggestAddingStaticToDecl(CurFD);
6985     }
6986   }
6987 
6988   if (D.getDeclSpec().isModulePrivateSpecified()) {
6989     if (IsVariableTemplateSpecialization)
6990       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6991           << (IsPartialSpecialization ? 1 : 0)
6992           << FixItHint::CreateRemoval(
6993                  D.getDeclSpec().getModulePrivateSpecLoc());
6994     else if (IsMemberSpecialization)
6995       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6996         << 2
6997         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6998     else if (NewVD->hasLocalStorage())
6999       Diag(NewVD->getLocation(), diag::err_module_private_local)
7000         << 0 << NewVD->getDeclName()
7001         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7002         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7003     else {
7004       NewVD->setModulePrivate();
7005       if (NewTemplate)
7006         NewTemplate->setModulePrivate();
7007       for (auto *B : Bindings)
7008         B->setModulePrivate();
7009     }
7010   }
7011 
7012   if (getLangOpts().OpenCL) {
7013 
7014     deduceOpenCLAddressSpace(NewVD);
7015 
7016     diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType());
7017   }
7018 
7019   // Handle attributes prior to checking for duplicates in MergeVarDecl
7020   ProcessDeclAttributes(S, NewVD, D);
7021 
7022   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
7023     if (EmitTLSUnsupportedError &&
7024         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7025          (getLangOpts().OpenMPIsDevice &&
7026           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7027       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7028            diag::err_thread_unsupported);
7029     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7030     // storage [duration]."
7031     if (SC == SC_None && S->getFnParent() != nullptr &&
7032         (NewVD->hasAttr<CUDASharedAttr>() ||
7033          NewVD->hasAttr<CUDAConstantAttr>())) {
7034       NewVD->setStorageClass(SC_Static);
7035     }
7036   }
7037 
7038   // Ensure that dllimport globals without explicit storage class are treated as
7039   // extern. The storage class is set above using parsed attributes. Now we can
7040   // check the VarDecl itself.
7041   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7042          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7043          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7044 
7045   // In auto-retain/release, infer strong retension for variables of
7046   // retainable type.
7047   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7048     NewVD->setInvalidDecl();
7049 
7050   // Handle GNU asm-label extension (encoded as an attribute).
7051   if (Expr *E = (Expr*)D.getAsmLabel()) {
7052     // The parser guarantees this is a string.
7053     StringLiteral *SE = cast<StringLiteral>(E);
7054     StringRef Label = SE->getString();
7055     if (S->getFnParent() != nullptr) {
7056       switch (SC) {
7057       case SC_None:
7058       case SC_Auto:
7059         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7060         break;
7061       case SC_Register:
7062         // Local Named register
7063         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7064             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7065           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7066         break;
7067       case SC_Static:
7068       case SC_Extern:
7069       case SC_PrivateExtern:
7070         break;
7071       }
7072     } else if (SC == SC_Register) {
7073       // Global Named register
7074       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7075         const auto &TI = Context.getTargetInfo();
7076         bool HasSizeMismatch;
7077 
7078         if (!TI.isValidGCCRegisterName(Label))
7079           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7080         else if (!TI.validateGlobalRegisterVariable(Label,
7081                                                     Context.getTypeSize(R),
7082                                                     HasSizeMismatch))
7083           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7084         else if (HasSizeMismatch)
7085           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7086       }
7087 
7088       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7089         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7090         NewVD->setInvalidDecl(true);
7091       }
7092     }
7093 
7094     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7095                                         /*IsLiteralLabel=*/true,
7096                                         SE->getStrTokenLoc(0)));
7097   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7098     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7099       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7100     if (I != ExtnameUndeclaredIdentifiers.end()) {
7101       if (isDeclExternC(NewVD)) {
7102         NewVD->addAttr(I->second);
7103         ExtnameUndeclaredIdentifiers.erase(I);
7104       } else
7105         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7106             << /*Variable*/1 << NewVD;
7107     }
7108   }
7109 
7110   // Find the shadowed declaration before filtering for scope.
7111   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7112                                 ? getShadowedDeclaration(NewVD, Previous)
7113                                 : nullptr;
7114 
7115   // Don't consider existing declarations that are in a different
7116   // scope and are out-of-semantic-context declarations (if the new
7117   // declaration has linkage).
7118   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7119                        D.getCXXScopeSpec().isNotEmpty() ||
7120                        IsMemberSpecialization ||
7121                        IsVariableTemplateSpecialization);
7122 
7123   // Check whether the previous declaration is in the same block scope. This
7124   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7125   if (getLangOpts().CPlusPlus &&
7126       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7127     NewVD->setPreviousDeclInSameBlockScope(
7128         Previous.isSingleResult() && !Previous.isShadowed() &&
7129         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7130 
7131   if (!getLangOpts().CPlusPlus) {
7132     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7133   } else {
7134     // If this is an explicit specialization of a static data member, check it.
7135     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7136         CheckMemberSpecialization(NewVD, Previous))
7137       NewVD->setInvalidDecl();
7138 
7139     // Merge the decl with the existing one if appropriate.
7140     if (!Previous.empty()) {
7141       if (Previous.isSingleResult() &&
7142           isa<FieldDecl>(Previous.getFoundDecl()) &&
7143           D.getCXXScopeSpec().isSet()) {
7144         // The user tried to define a non-static data member
7145         // out-of-line (C++ [dcl.meaning]p1).
7146         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7147           << D.getCXXScopeSpec().getRange();
7148         Previous.clear();
7149         NewVD->setInvalidDecl();
7150       }
7151     } else if (D.getCXXScopeSpec().isSet()) {
7152       // No previous declaration in the qualifying scope.
7153       Diag(D.getIdentifierLoc(), diag::err_no_member)
7154         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7155         << D.getCXXScopeSpec().getRange();
7156       NewVD->setInvalidDecl();
7157     }
7158 
7159     if (!IsVariableTemplateSpecialization)
7160       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7161 
7162     if (NewTemplate) {
7163       VarTemplateDecl *PrevVarTemplate =
7164           NewVD->getPreviousDecl()
7165               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7166               : nullptr;
7167 
7168       // Check the template parameter list of this declaration, possibly
7169       // merging in the template parameter list from the previous variable
7170       // template declaration.
7171       if (CheckTemplateParameterList(
7172               TemplateParams,
7173               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7174                               : nullptr,
7175               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7176                DC->isDependentContext())
7177                   ? TPC_ClassTemplateMember
7178                   : TPC_VarTemplate))
7179         NewVD->setInvalidDecl();
7180 
7181       // If we are providing an explicit specialization of a static variable
7182       // template, make a note of that.
7183       if (PrevVarTemplate &&
7184           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7185         PrevVarTemplate->setMemberSpecialization();
7186     }
7187   }
7188 
7189   // Diagnose shadowed variables iff this isn't a redeclaration.
7190   if (ShadowedDecl && !D.isRedeclaration())
7191     CheckShadow(NewVD, ShadowedDecl, Previous);
7192 
7193   ProcessPragmaWeak(S, NewVD);
7194 
7195   // If this is the first declaration of an extern C variable, update
7196   // the map of such variables.
7197   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7198       isIncompleteDeclExternC(*this, NewVD))
7199     RegisterLocallyScopedExternCDecl(NewVD, S);
7200 
7201   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7202     MangleNumberingContext *MCtx;
7203     Decl *ManglingContextDecl;
7204     std::tie(MCtx, ManglingContextDecl) =
7205         getCurrentMangleNumberContext(NewVD->getDeclContext());
7206     if (MCtx) {
7207       Context.setManglingNumber(
7208           NewVD, MCtx->getManglingNumber(
7209                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7210       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7211     }
7212   }
7213 
7214   // Special handling of variable named 'main'.
7215   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7216       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7217       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7218 
7219     // C++ [basic.start.main]p3
7220     // A program that declares a variable main at global scope is ill-formed.
7221     if (getLangOpts().CPlusPlus)
7222       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7223 
7224     // In C, and external-linkage variable named main results in undefined
7225     // behavior.
7226     else if (NewVD->hasExternalFormalLinkage())
7227       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7228   }
7229 
7230   if (D.isRedeclaration() && !Previous.empty()) {
7231     NamedDecl *Prev = Previous.getRepresentativeDecl();
7232     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7233                                    D.isFunctionDefinition());
7234   }
7235 
7236   if (NewTemplate) {
7237     if (NewVD->isInvalidDecl())
7238       NewTemplate->setInvalidDecl();
7239     ActOnDocumentableDecl(NewTemplate);
7240     return NewTemplate;
7241   }
7242 
7243   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7244     CompleteMemberSpecialization(NewVD, Previous);
7245 
7246   return NewVD;
7247 }
7248 
7249 /// Enum describing the %select options in diag::warn_decl_shadow.
7250 enum ShadowedDeclKind {
7251   SDK_Local,
7252   SDK_Global,
7253   SDK_StaticMember,
7254   SDK_Field,
7255   SDK_Typedef,
7256   SDK_Using
7257 };
7258 
7259 /// Determine what kind of declaration we're shadowing.
7260 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7261                                                 const DeclContext *OldDC) {
7262   if (isa<TypeAliasDecl>(ShadowedDecl))
7263     return SDK_Using;
7264   else if (isa<TypedefDecl>(ShadowedDecl))
7265     return SDK_Typedef;
7266   else if (isa<RecordDecl>(OldDC))
7267     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7268 
7269   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7270 }
7271 
7272 /// Return the location of the capture if the given lambda captures the given
7273 /// variable \p VD, or an invalid source location otherwise.
7274 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7275                                          const VarDecl *VD) {
7276   for (const Capture &Capture : LSI->Captures) {
7277     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7278       return Capture.getLocation();
7279   }
7280   return SourceLocation();
7281 }
7282 
7283 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7284                                      const LookupResult &R) {
7285   // Only diagnose if we're shadowing an unambiguous field or variable.
7286   if (R.getResultKind() != LookupResult::Found)
7287     return false;
7288 
7289   // Return false if warning is ignored.
7290   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7291 }
7292 
7293 /// Return the declaration shadowed by the given variable \p D, or null
7294 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7295 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7296                                         const LookupResult &R) {
7297   if (!shouldWarnIfShadowedDecl(Diags, R))
7298     return nullptr;
7299 
7300   // Don't diagnose declarations at file scope.
7301   if (D->hasGlobalStorage())
7302     return nullptr;
7303 
7304   NamedDecl *ShadowedDecl = R.getFoundDecl();
7305   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
7306              ? ShadowedDecl
7307              : nullptr;
7308 }
7309 
7310 /// Return the declaration shadowed by the given typedef \p D, or null
7311 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7312 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7313                                         const LookupResult &R) {
7314   // Don't warn if typedef declaration is part of a class
7315   if (D->getDeclContext()->isRecord())
7316     return nullptr;
7317 
7318   if (!shouldWarnIfShadowedDecl(Diags, R))
7319     return nullptr;
7320 
7321   NamedDecl *ShadowedDecl = R.getFoundDecl();
7322   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7323 }
7324 
7325 /// Diagnose variable or built-in function shadowing.  Implements
7326 /// -Wshadow.
7327 ///
7328 /// This method is called whenever a VarDecl is added to a "useful"
7329 /// scope.
7330 ///
7331 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7332 /// \param R the lookup of the name
7333 ///
7334 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7335                        const LookupResult &R) {
7336   DeclContext *NewDC = D->getDeclContext();
7337 
7338   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7339     // Fields are not shadowed by variables in C++ static methods.
7340     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7341       if (MD->isStatic())
7342         return;
7343 
7344     // Fields shadowed by constructor parameters are a special case. Usually
7345     // the constructor initializes the field with the parameter.
7346     if (isa<CXXConstructorDecl>(NewDC))
7347       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7348         // Remember that this was shadowed so we can either warn about its
7349         // modification or its existence depending on warning settings.
7350         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7351         return;
7352       }
7353   }
7354 
7355   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7356     if (shadowedVar->isExternC()) {
7357       // For shadowing external vars, make sure that we point to the global
7358       // declaration, not a locally scoped extern declaration.
7359       for (auto I : shadowedVar->redecls())
7360         if (I->isFileVarDecl()) {
7361           ShadowedDecl = I;
7362           break;
7363         }
7364     }
7365 
7366   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7367 
7368   unsigned WarningDiag = diag::warn_decl_shadow;
7369   SourceLocation CaptureLoc;
7370   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7371       isa<CXXMethodDecl>(NewDC)) {
7372     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7373       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7374         if (RD->getLambdaCaptureDefault() == LCD_None) {
7375           // Try to avoid warnings for lambdas with an explicit capture list.
7376           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7377           // Warn only when the lambda captures the shadowed decl explicitly.
7378           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7379           if (CaptureLoc.isInvalid())
7380             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7381         } else {
7382           // Remember that this was shadowed so we can avoid the warning if the
7383           // shadowed decl isn't captured and the warning settings allow it.
7384           cast<LambdaScopeInfo>(getCurFunction())
7385               ->ShadowingDecls.push_back(
7386                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7387           return;
7388         }
7389       }
7390 
7391       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7392         // A variable can't shadow a local variable in an enclosing scope, if
7393         // they are separated by a non-capturing declaration context.
7394         for (DeclContext *ParentDC = NewDC;
7395              ParentDC && !ParentDC->Equals(OldDC);
7396              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7397           // Only block literals, captured statements, and lambda expressions
7398           // can capture; other scopes don't.
7399           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7400               !isLambdaCallOperator(ParentDC)) {
7401             return;
7402           }
7403         }
7404       }
7405     }
7406   }
7407 
7408   // Only warn about certain kinds of shadowing for class members.
7409   if (NewDC && NewDC->isRecord()) {
7410     // In particular, don't warn about shadowing non-class members.
7411     if (!OldDC->isRecord())
7412       return;
7413 
7414     // TODO: should we warn about static data members shadowing
7415     // static data members from base classes?
7416 
7417     // TODO: don't diagnose for inaccessible shadowed members.
7418     // This is hard to do perfectly because we might friend the
7419     // shadowing context, but that's just a false negative.
7420   }
7421 
7422 
7423   DeclarationName Name = R.getLookupName();
7424 
7425   // Emit warning and note.
7426   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7427     return;
7428   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7429   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7430   if (!CaptureLoc.isInvalid())
7431     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7432         << Name << /*explicitly*/ 1;
7433   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7434 }
7435 
7436 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7437 /// when these variables are captured by the lambda.
7438 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7439   for (const auto &Shadow : LSI->ShadowingDecls) {
7440     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7441     // Try to avoid the warning when the shadowed decl isn't captured.
7442     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7443     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7444     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7445                                        ? diag::warn_decl_shadow_uncaptured_local
7446                                        : diag::warn_decl_shadow)
7447         << Shadow.VD->getDeclName()
7448         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7449     if (!CaptureLoc.isInvalid())
7450       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7451           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7452     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7453   }
7454 }
7455 
7456 /// Check -Wshadow without the advantage of a previous lookup.
7457 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7458   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7459     return;
7460 
7461   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7462                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7463   LookupName(R, S);
7464   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7465     CheckShadow(D, ShadowedDecl, R);
7466 }
7467 
7468 /// Check if 'E', which is an expression that is about to be modified, refers
7469 /// to a constructor parameter that shadows a field.
7470 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7471   // Quickly ignore expressions that can't be shadowing ctor parameters.
7472   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7473     return;
7474   E = E->IgnoreParenImpCasts();
7475   auto *DRE = dyn_cast<DeclRefExpr>(E);
7476   if (!DRE)
7477     return;
7478   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7479   auto I = ShadowingDecls.find(D);
7480   if (I == ShadowingDecls.end())
7481     return;
7482   const NamedDecl *ShadowedDecl = I->second;
7483   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7484   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7485   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7486   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7487 
7488   // Avoid issuing multiple warnings about the same decl.
7489   ShadowingDecls.erase(I);
7490 }
7491 
7492 /// Check for conflict between this global or extern "C" declaration and
7493 /// previous global or extern "C" declarations. This is only used in C++.
7494 template<typename T>
7495 static bool checkGlobalOrExternCConflict(
7496     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7497   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7498   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7499 
7500   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7501     // The common case: this global doesn't conflict with any extern "C"
7502     // declaration.
7503     return false;
7504   }
7505 
7506   if (Prev) {
7507     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7508       // Both the old and new declarations have C language linkage. This is a
7509       // redeclaration.
7510       Previous.clear();
7511       Previous.addDecl(Prev);
7512       return true;
7513     }
7514 
7515     // This is a global, non-extern "C" declaration, and there is a previous
7516     // non-global extern "C" declaration. Diagnose if this is a variable
7517     // declaration.
7518     if (!isa<VarDecl>(ND))
7519       return false;
7520   } else {
7521     // The declaration is extern "C". Check for any declaration in the
7522     // translation unit which might conflict.
7523     if (IsGlobal) {
7524       // We have already performed the lookup into the translation unit.
7525       IsGlobal = false;
7526       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7527            I != E; ++I) {
7528         if (isa<VarDecl>(*I)) {
7529           Prev = *I;
7530           break;
7531         }
7532       }
7533     } else {
7534       DeclContext::lookup_result R =
7535           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7536       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7537            I != E; ++I) {
7538         if (isa<VarDecl>(*I)) {
7539           Prev = *I;
7540           break;
7541         }
7542         // FIXME: If we have any other entity with this name in global scope,
7543         // the declaration is ill-formed, but that is a defect: it breaks the
7544         // 'stat' hack, for instance. Only variables can have mangled name
7545         // clashes with extern "C" declarations, so only they deserve a
7546         // diagnostic.
7547       }
7548     }
7549 
7550     if (!Prev)
7551       return false;
7552   }
7553 
7554   // Use the first declaration's location to ensure we point at something which
7555   // is lexically inside an extern "C" linkage-spec.
7556   assert(Prev && "should have found a previous declaration to diagnose");
7557   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7558     Prev = FD->getFirstDecl();
7559   else
7560     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7561 
7562   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7563     << IsGlobal << ND;
7564   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7565     << IsGlobal;
7566   return false;
7567 }
7568 
7569 /// Apply special rules for handling extern "C" declarations. Returns \c true
7570 /// if we have found that this is a redeclaration of some prior entity.
7571 ///
7572 /// Per C++ [dcl.link]p6:
7573 ///   Two declarations [for a function or variable] with C language linkage
7574 ///   with the same name that appear in different scopes refer to the same
7575 ///   [entity]. An entity with C language linkage shall not be declared with
7576 ///   the same name as an entity in global scope.
7577 template<typename T>
7578 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7579                                                   LookupResult &Previous) {
7580   if (!S.getLangOpts().CPlusPlus) {
7581     // In C, when declaring a global variable, look for a corresponding 'extern'
7582     // variable declared in function scope. We don't need this in C++, because
7583     // we find local extern decls in the surrounding file-scope DeclContext.
7584     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7585       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7586         Previous.clear();
7587         Previous.addDecl(Prev);
7588         return true;
7589       }
7590     }
7591     return false;
7592   }
7593 
7594   // A declaration in the translation unit can conflict with an extern "C"
7595   // declaration.
7596   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7597     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7598 
7599   // An extern "C" declaration can conflict with a declaration in the
7600   // translation unit or can be a redeclaration of an extern "C" declaration
7601   // in another scope.
7602   if (isIncompleteDeclExternC(S,ND))
7603     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7604 
7605   // Neither global nor extern "C": nothing to do.
7606   return false;
7607 }
7608 
7609 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7610   // If the decl is already known invalid, don't check it.
7611   if (NewVD->isInvalidDecl())
7612     return;
7613 
7614   QualType T = NewVD->getType();
7615 
7616   // Defer checking an 'auto' type until its initializer is attached.
7617   if (T->isUndeducedType())
7618     return;
7619 
7620   if (NewVD->hasAttrs())
7621     CheckAlignasUnderalignment(NewVD);
7622 
7623   if (T->isObjCObjectType()) {
7624     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7625       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7626     T = Context.getObjCObjectPointerType(T);
7627     NewVD->setType(T);
7628   }
7629 
7630   // Emit an error if an address space was applied to decl with local storage.
7631   // This includes arrays of objects with address space qualifiers, but not
7632   // automatic variables that point to other address spaces.
7633   // ISO/IEC TR 18037 S5.1.2
7634   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7635       T.getAddressSpace() != LangAS::Default) {
7636     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7637     NewVD->setInvalidDecl();
7638     return;
7639   }
7640 
7641   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7642   // scope.
7643   if (getLangOpts().OpenCLVersion == 120 &&
7644       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7645       NewVD->isStaticLocal()) {
7646     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7647     NewVD->setInvalidDecl();
7648     return;
7649   }
7650 
7651   if (getLangOpts().OpenCL) {
7652     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7653     if (NewVD->hasAttr<BlocksAttr>()) {
7654       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7655       return;
7656     }
7657 
7658     if (T->isBlockPointerType()) {
7659       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7660       // can't use 'extern' storage class.
7661       if (!T.isConstQualified()) {
7662         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7663             << 0 /*const*/;
7664         NewVD->setInvalidDecl();
7665         return;
7666       }
7667       if (NewVD->hasExternalStorage()) {
7668         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7669         NewVD->setInvalidDecl();
7670         return;
7671       }
7672     }
7673     // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7674     // __constant address space.
7675     // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7676     // variables inside a function can also be declared in the global
7677     // address space.
7678     // C++ for OpenCL inherits rule from OpenCL C v2.0.
7679     // FIXME: Adding local AS in C++ for OpenCL might make sense.
7680     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7681         NewVD->hasExternalStorage()) {
7682       if (!T->isSamplerT() &&
7683           !(T.getAddressSpace() == LangAS::opencl_constant ||
7684             (T.getAddressSpace() == LangAS::opencl_global &&
7685              (getLangOpts().OpenCLVersion == 200 ||
7686               getLangOpts().OpenCLCPlusPlus)))) {
7687         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7688         if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7689           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7690               << Scope << "global or constant";
7691         else
7692           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7693               << Scope << "constant";
7694         NewVD->setInvalidDecl();
7695         return;
7696       }
7697     } else {
7698       if (T.getAddressSpace() == LangAS::opencl_global) {
7699         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7700             << 1 /*is any function*/ << "global";
7701         NewVD->setInvalidDecl();
7702         return;
7703       }
7704       if (T.getAddressSpace() == LangAS::opencl_constant ||
7705           T.getAddressSpace() == LangAS::opencl_local) {
7706         FunctionDecl *FD = getCurFunctionDecl();
7707         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7708         // in functions.
7709         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7710           if (T.getAddressSpace() == LangAS::opencl_constant)
7711             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7712                 << 0 /*non-kernel only*/ << "constant";
7713           else
7714             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7715                 << 0 /*non-kernel only*/ << "local";
7716           NewVD->setInvalidDecl();
7717           return;
7718         }
7719         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7720         // in the outermost scope of a kernel function.
7721         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7722           if (!getCurScope()->isFunctionScope()) {
7723             if (T.getAddressSpace() == LangAS::opencl_constant)
7724               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7725                   << "constant";
7726             else
7727               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7728                   << "local";
7729             NewVD->setInvalidDecl();
7730             return;
7731           }
7732         }
7733       } else if (T.getAddressSpace() != LangAS::opencl_private &&
7734                  // If we are parsing a template we didn't deduce an addr
7735                  // space yet.
7736                  T.getAddressSpace() != LangAS::Default) {
7737         // Do not allow other address spaces on automatic variable.
7738         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7739         NewVD->setInvalidDecl();
7740         return;
7741       }
7742     }
7743   }
7744 
7745   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7746       && !NewVD->hasAttr<BlocksAttr>()) {
7747     if (getLangOpts().getGC() != LangOptions::NonGC)
7748       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7749     else {
7750       assert(!getLangOpts().ObjCAutoRefCount);
7751       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7752     }
7753   }
7754 
7755   bool isVM = T->isVariablyModifiedType();
7756   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7757       NewVD->hasAttr<BlocksAttr>())
7758     setFunctionHasBranchProtectedScope();
7759 
7760   if ((isVM && NewVD->hasLinkage()) ||
7761       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7762     bool SizeIsNegative;
7763     llvm::APSInt Oversized;
7764     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7765         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7766     QualType FixedT;
7767     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
7768       FixedT = FixedTInfo->getType();
7769     else if (FixedTInfo) {
7770       // Type and type-as-written are canonically different. We need to fix up
7771       // both types separately.
7772       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7773                                                    Oversized);
7774     }
7775     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7776       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7777       // FIXME: This won't give the correct result for
7778       // int a[10][n];
7779       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7780 
7781       if (NewVD->isFileVarDecl())
7782         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7783         << SizeRange;
7784       else if (NewVD->isStaticLocal())
7785         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7786         << SizeRange;
7787       else
7788         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7789         << SizeRange;
7790       NewVD->setInvalidDecl();
7791       return;
7792     }
7793 
7794     if (!FixedTInfo) {
7795       if (NewVD->isFileVarDecl())
7796         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7797       else
7798         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7799       NewVD->setInvalidDecl();
7800       return;
7801     }
7802 
7803     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7804     NewVD->setType(FixedT);
7805     NewVD->setTypeSourceInfo(FixedTInfo);
7806   }
7807 
7808   if (T->isVoidType()) {
7809     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7810     //                    of objects and functions.
7811     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7812       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7813         << T;
7814       NewVD->setInvalidDecl();
7815       return;
7816     }
7817   }
7818 
7819   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7820     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7821     NewVD->setInvalidDecl();
7822     return;
7823   }
7824 
7825   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7826     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7827     NewVD->setInvalidDecl();
7828     return;
7829   }
7830 
7831   if (NewVD->isConstexpr() && !T->isDependentType() &&
7832       RequireLiteralType(NewVD->getLocation(), T,
7833                          diag::err_constexpr_var_non_literal)) {
7834     NewVD->setInvalidDecl();
7835     return;
7836   }
7837 }
7838 
7839 /// Perform semantic checking on a newly-created variable
7840 /// declaration.
7841 ///
7842 /// This routine performs all of the type-checking required for a
7843 /// variable declaration once it has been built. It is used both to
7844 /// check variables after they have been parsed and their declarators
7845 /// have been translated into a declaration, and to check variables
7846 /// that have been instantiated from a template.
7847 ///
7848 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7849 ///
7850 /// Returns true if the variable declaration is a redeclaration.
7851 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7852   CheckVariableDeclarationType(NewVD);
7853 
7854   // If the decl is already known invalid, don't check it.
7855   if (NewVD->isInvalidDecl())
7856     return false;
7857 
7858   // If we did not find anything by this name, look for a non-visible
7859   // extern "C" declaration with the same name.
7860   if (Previous.empty() &&
7861       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7862     Previous.setShadowed();
7863 
7864   if (!Previous.empty()) {
7865     MergeVarDecl(NewVD, Previous);
7866     return true;
7867   }
7868   return false;
7869 }
7870 
7871 namespace {
7872 struct FindOverriddenMethod {
7873   Sema *S;
7874   CXXMethodDecl *Method;
7875 
7876   /// Member lookup function that determines whether a given C++
7877   /// method overrides a method in a base class, to be used with
7878   /// CXXRecordDecl::lookupInBases().
7879   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7880     RecordDecl *BaseRecord =
7881         Specifier->getType()->castAs<RecordType>()->getDecl();
7882 
7883     DeclarationName Name = Method->getDeclName();
7884 
7885     // FIXME: Do we care about other names here too?
7886     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7887       // We really want to find the base class destructor here.
7888       QualType T = S->Context.getTypeDeclType(BaseRecord);
7889       CanQualType CT = S->Context.getCanonicalType(T);
7890 
7891       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7892     }
7893 
7894     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7895          Path.Decls = Path.Decls.slice(1)) {
7896       NamedDecl *D = Path.Decls.front();
7897       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7898         if (MD->isVirtual() &&
7899             !S->IsOverload(
7900                 Method, MD, /*UseMemberUsingDeclRules=*/false,
7901                 /*ConsiderCudaAttrs=*/true,
7902                 // C++2a [class.virtual]p2 does not consider requires clauses
7903                 // when overriding.
7904                 /*ConsiderRequiresClauses=*/false))
7905           return true;
7906       }
7907     }
7908 
7909     return false;
7910   }
7911 };
7912 
7913 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7914 } // end anonymous namespace
7915 
7916 /// Report an error regarding overriding, along with any relevant
7917 /// overridden methods.
7918 ///
7919 /// \param DiagID the primary error to report.
7920 /// \param MD the overriding method.
7921 /// \param OEK which overrides to include as notes.
7922 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7923                             OverrideErrorKind OEK = OEK_All) {
7924   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7925   for (const CXXMethodDecl *O : MD->overridden_methods()) {
7926     // This check (& the OEK parameter) could be replaced by a predicate, but
7927     // without lambdas that would be overkill. This is still nicer than writing
7928     // out the diag loop 3 times.
7929     if ((OEK == OEK_All) ||
7930         (OEK == OEK_NonDeleted && !O->isDeleted()) ||
7931         (OEK == OEK_Deleted && O->isDeleted()))
7932       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7933   }
7934 }
7935 
7936 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7937 /// and if so, check that it's a valid override and remember it.
7938 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7939   // Look for methods in base classes that this method might override.
7940   CXXBasePaths Paths;
7941   FindOverriddenMethod FOM;
7942   FOM.Method = MD;
7943   FOM.S = this;
7944   bool hasDeletedOverridenMethods = false;
7945   bool hasNonDeletedOverridenMethods = false;
7946   bool AddedAny = false;
7947   if (DC->lookupInBases(FOM, Paths)) {
7948     for (auto *I : Paths.found_decls()) {
7949       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7950         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7951         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7952             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7953             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7954             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7955           hasDeletedOverridenMethods |= OldMD->isDeleted();
7956           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7957           AddedAny = true;
7958         }
7959       }
7960     }
7961   }
7962 
7963   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7964     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7965   }
7966   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7967     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7968   }
7969 
7970   return AddedAny;
7971 }
7972 
7973 namespace {
7974   // Struct for holding all of the extra arguments needed by
7975   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7976   struct ActOnFDArgs {
7977     Scope *S;
7978     Declarator &D;
7979     MultiTemplateParamsArg TemplateParamLists;
7980     bool AddToScope;
7981   };
7982 } // end anonymous namespace
7983 
7984 namespace {
7985 
7986 // Callback to only accept typo corrections that have a non-zero edit distance.
7987 // Also only accept corrections that have the same parent decl.
7988 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
7989  public:
7990   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7991                             CXXRecordDecl *Parent)
7992       : Context(Context), OriginalFD(TypoFD),
7993         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7994 
7995   bool ValidateCandidate(const TypoCorrection &candidate) override {
7996     if (candidate.getEditDistance() == 0)
7997       return false;
7998 
7999     SmallVector<unsigned, 1> MismatchedParams;
8000     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8001                                           CDeclEnd = candidate.end();
8002          CDecl != CDeclEnd; ++CDecl) {
8003       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8004 
8005       if (FD && !FD->hasBody() &&
8006           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8007         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8008           CXXRecordDecl *Parent = MD->getParent();
8009           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8010             return true;
8011         } else if (!ExpectedParent) {
8012           return true;
8013         }
8014       }
8015     }
8016 
8017     return false;
8018   }
8019 
8020   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8021     return std::make_unique<DifferentNameValidatorCCC>(*this);
8022   }
8023 
8024  private:
8025   ASTContext &Context;
8026   FunctionDecl *OriginalFD;
8027   CXXRecordDecl *ExpectedParent;
8028 };
8029 
8030 } // end anonymous namespace
8031 
8032 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8033   TypoCorrectedFunctionDefinitions.insert(F);
8034 }
8035 
8036 /// Generate diagnostics for an invalid function redeclaration.
8037 ///
8038 /// This routine handles generating the diagnostic messages for an invalid
8039 /// function redeclaration, including finding possible similar declarations
8040 /// or performing typo correction if there are no previous declarations with
8041 /// the same name.
8042 ///
8043 /// Returns a NamedDecl iff typo correction was performed and substituting in
8044 /// the new declaration name does not cause new errors.
8045 static NamedDecl *DiagnoseInvalidRedeclaration(
8046     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8047     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8048   DeclarationName Name = NewFD->getDeclName();
8049   DeclContext *NewDC = NewFD->getDeclContext();
8050   SmallVector<unsigned, 1> MismatchedParams;
8051   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8052   TypoCorrection Correction;
8053   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8054   unsigned DiagMsg =
8055     IsLocalFriend ? diag::err_no_matching_local_friend :
8056     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8057     diag::err_member_decl_does_not_match;
8058   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8059                     IsLocalFriend ? Sema::LookupLocalFriendName
8060                                   : Sema::LookupOrdinaryName,
8061                     Sema::ForVisibleRedeclaration);
8062 
8063   NewFD->setInvalidDecl();
8064   if (IsLocalFriend)
8065     SemaRef.LookupName(Prev, S);
8066   else
8067     SemaRef.LookupQualifiedName(Prev, NewDC);
8068   assert(!Prev.isAmbiguous() &&
8069          "Cannot have an ambiguity in previous-declaration lookup");
8070   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8071   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8072                                 MD ? MD->getParent() : nullptr);
8073   if (!Prev.empty()) {
8074     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8075          Func != FuncEnd; ++Func) {
8076       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8077       if (FD &&
8078           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8079         // Add 1 to the index so that 0 can mean the mismatch didn't
8080         // involve a parameter
8081         unsigned ParamNum =
8082             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8083         NearMatches.push_back(std::make_pair(FD, ParamNum));
8084       }
8085     }
8086   // If the qualified name lookup yielded nothing, try typo correction
8087   } else if ((Correction = SemaRef.CorrectTypo(
8088                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8089                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8090                   IsLocalFriend ? nullptr : NewDC))) {
8091     // Set up everything for the call to ActOnFunctionDeclarator
8092     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8093                               ExtraArgs.D.getIdentifierLoc());
8094     Previous.clear();
8095     Previous.setLookupName(Correction.getCorrection());
8096     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8097                                     CDeclEnd = Correction.end();
8098          CDecl != CDeclEnd; ++CDecl) {
8099       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8100       if (FD && !FD->hasBody() &&
8101           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8102         Previous.addDecl(FD);
8103       }
8104     }
8105     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8106 
8107     NamedDecl *Result;
8108     // Retry building the function declaration with the new previous
8109     // declarations, and with errors suppressed.
8110     {
8111       // Trap errors.
8112       Sema::SFINAETrap Trap(SemaRef);
8113 
8114       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8115       // pieces need to verify the typo-corrected C++ declaration and hopefully
8116       // eliminate the need for the parameter pack ExtraArgs.
8117       Result = SemaRef.ActOnFunctionDeclarator(
8118           ExtraArgs.S, ExtraArgs.D,
8119           Correction.getCorrectionDecl()->getDeclContext(),
8120           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8121           ExtraArgs.AddToScope);
8122 
8123       if (Trap.hasErrorOccurred())
8124         Result = nullptr;
8125     }
8126 
8127     if (Result) {
8128       // Determine which correction we picked.
8129       Decl *Canonical = Result->getCanonicalDecl();
8130       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8131            I != E; ++I)
8132         if ((*I)->getCanonicalDecl() == Canonical)
8133           Correction.setCorrectionDecl(*I);
8134 
8135       // Let Sema know about the correction.
8136       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8137       SemaRef.diagnoseTypo(
8138           Correction,
8139           SemaRef.PDiag(IsLocalFriend
8140                           ? diag::err_no_matching_local_friend_suggest
8141                           : diag::err_member_decl_does_not_match_suggest)
8142             << Name << NewDC << IsDefinition);
8143       return Result;
8144     }
8145 
8146     // Pretend the typo correction never occurred
8147     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8148                               ExtraArgs.D.getIdentifierLoc());
8149     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8150     Previous.clear();
8151     Previous.setLookupName(Name);
8152   }
8153 
8154   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8155       << Name << NewDC << IsDefinition << NewFD->getLocation();
8156 
8157   bool NewFDisConst = false;
8158   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8159     NewFDisConst = NewMD->isConst();
8160 
8161   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8162        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8163        NearMatch != NearMatchEnd; ++NearMatch) {
8164     FunctionDecl *FD = NearMatch->first;
8165     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8166     bool FDisConst = MD && MD->isConst();
8167     bool IsMember = MD || !IsLocalFriend;
8168 
8169     // FIXME: These notes are poorly worded for the local friend case.
8170     if (unsigned Idx = NearMatch->second) {
8171       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8172       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8173       if (Loc.isInvalid()) Loc = FD->getLocation();
8174       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8175                                  : diag::note_local_decl_close_param_match)
8176         << Idx << FDParam->getType()
8177         << NewFD->getParamDecl(Idx - 1)->getType();
8178     } else if (FDisConst != NewFDisConst) {
8179       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8180           << NewFDisConst << FD->getSourceRange().getEnd();
8181     } else
8182       SemaRef.Diag(FD->getLocation(),
8183                    IsMember ? diag::note_member_def_close_match
8184                             : diag::note_local_decl_close_match);
8185   }
8186   return nullptr;
8187 }
8188 
8189 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8190   switch (D.getDeclSpec().getStorageClassSpec()) {
8191   default: llvm_unreachable("Unknown storage class!");
8192   case DeclSpec::SCS_auto:
8193   case DeclSpec::SCS_register:
8194   case DeclSpec::SCS_mutable:
8195     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8196                  diag::err_typecheck_sclass_func);
8197     D.getMutableDeclSpec().ClearStorageClassSpecs();
8198     D.setInvalidType();
8199     break;
8200   case DeclSpec::SCS_unspecified: break;
8201   case DeclSpec::SCS_extern:
8202     if (D.getDeclSpec().isExternInLinkageSpec())
8203       return SC_None;
8204     return SC_Extern;
8205   case DeclSpec::SCS_static: {
8206     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8207       // C99 6.7.1p5:
8208       //   The declaration of an identifier for a function that has
8209       //   block scope shall have no explicit storage-class specifier
8210       //   other than extern
8211       // See also (C++ [dcl.stc]p4).
8212       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8213                    diag::err_static_block_func);
8214       break;
8215     } else
8216       return SC_Static;
8217   }
8218   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8219   }
8220 
8221   // No explicit storage class has already been returned
8222   return SC_None;
8223 }
8224 
8225 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8226                                            DeclContext *DC, QualType &R,
8227                                            TypeSourceInfo *TInfo,
8228                                            StorageClass SC,
8229                                            bool &IsVirtualOkay) {
8230   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8231   DeclarationName Name = NameInfo.getName();
8232 
8233   FunctionDecl *NewFD = nullptr;
8234   bool isInline = D.getDeclSpec().isInlineSpecified();
8235 
8236   if (!SemaRef.getLangOpts().CPlusPlus) {
8237     // Determine whether the function was written with a
8238     // prototype. This true when:
8239     //   - there is a prototype in the declarator, or
8240     //   - the type R of the function is some kind of typedef or other non-
8241     //     attributed reference to a type name (which eventually refers to a
8242     //     function type).
8243     bool HasPrototype =
8244       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8245       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8246 
8247     NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8248                                  R, TInfo, SC, isInline, HasPrototype,
8249                                  CSK_unspecified,
8250                                  /*TrailingRequiresClause=*/nullptr);
8251     if (D.isInvalidType())
8252       NewFD->setInvalidDecl();
8253 
8254     return NewFD;
8255   }
8256 
8257   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8258 
8259   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8260   if (ConstexprKind == CSK_constinit) {
8261     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8262                  diag::err_constexpr_wrong_decl_kind)
8263         << ConstexprKind;
8264     ConstexprKind = CSK_unspecified;
8265     D.getMutableDeclSpec().ClearConstexprSpec();
8266   }
8267   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8268 
8269   // Check that the return type is not an abstract class type.
8270   // For record types, this is done by the AbstractClassUsageDiagnoser once
8271   // the class has been completely parsed.
8272   if (!DC->isRecord() &&
8273       SemaRef.RequireNonAbstractType(
8274           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8275           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8276     D.setInvalidType();
8277 
8278   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8279     // This is a C++ constructor declaration.
8280     assert(DC->isRecord() &&
8281            "Constructors can only be declared in a member context");
8282 
8283     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8284     return CXXConstructorDecl::Create(
8285         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8286         TInfo, ExplicitSpecifier, isInline,
8287         /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(),
8288         TrailingRequiresClause);
8289 
8290   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8291     // This is a C++ destructor declaration.
8292     if (DC->isRecord()) {
8293       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8294       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8295       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8296           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8297           isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8298           TrailingRequiresClause);
8299 
8300       // If the destructor needs an implicit exception specification, set it
8301       // now. FIXME: It'd be nice to be able to create the right type to start
8302       // with, but the type needs to reference the destructor declaration.
8303       if (SemaRef.getLangOpts().CPlusPlus11)
8304         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8305 
8306       IsVirtualOkay = true;
8307       return NewDD;
8308 
8309     } else {
8310       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8311       D.setInvalidType();
8312 
8313       // Create a FunctionDecl to satisfy the function definition parsing
8314       // code path.
8315       return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8316                                   D.getIdentifierLoc(), Name, R, TInfo, SC,
8317                                   isInline,
8318                                   /*hasPrototype=*/true, ConstexprKind,
8319                                   TrailingRequiresClause);
8320     }
8321 
8322   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8323     if (!DC->isRecord()) {
8324       SemaRef.Diag(D.getIdentifierLoc(),
8325            diag::err_conv_function_not_member);
8326       return nullptr;
8327     }
8328 
8329     SemaRef.CheckConversionDeclarator(D, R, SC);
8330     if (D.isInvalidType())
8331       return nullptr;
8332 
8333     IsVirtualOkay = true;
8334     return CXXConversionDecl::Create(
8335         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8336         TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(),
8337         TrailingRequiresClause);
8338 
8339   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8340     if (TrailingRequiresClause)
8341       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8342                    diag::err_trailing_requires_clause_on_deduction_guide)
8343           << TrailingRequiresClause->getSourceRange();
8344     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8345 
8346     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8347                                          ExplicitSpecifier, NameInfo, R, TInfo,
8348                                          D.getEndLoc());
8349   } else if (DC->isRecord()) {
8350     // If the name of the function is the same as the name of the record,
8351     // then this must be an invalid constructor that has a return type.
8352     // (The parser checks for a return type and makes the declarator a
8353     // constructor if it has no return type).
8354     if (Name.getAsIdentifierInfo() &&
8355         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8356       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8357         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8358         << SourceRange(D.getIdentifierLoc());
8359       return nullptr;
8360     }
8361 
8362     // This is a C++ method declaration.
8363     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8364         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8365         TInfo, SC, isInline, ConstexprKind, SourceLocation(),
8366         TrailingRequiresClause);
8367     IsVirtualOkay = !Ret->isStatic();
8368     return Ret;
8369   } else {
8370     bool isFriend =
8371         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8372     if (!isFriend && SemaRef.CurContext->isRecord())
8373       return nullptr;
8374 
8375     // Determine whether the function was written with a
8376     // prototype. This true when:
8377     //   - we're in C++ (where every function has a prototype),
8378     return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8379                                 R, TInfo, SC, isInline, true /*HasPrototype*/,
8380                                 ConstexprKind, TrailingRequiresClause);
8381   }
8382 }
8383 
8384 enum OpenCLParamType {
8385   ValidKernelParam,
8386   PtrPtrKernelParam,
8387   PtrKernelParam,
8388   InvalidAddrSpacePtrKernelParam,
8389   InvalidKernelParam,
8390   RecordKernelParam
8391 };
8392 
8393 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8394   // Size dependent types are just typedefs to normal integer types
8395   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8396   // integers other than by their names.
8397   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8398 
8399   // Remove typedefs one by one until we reach a typedef
8400   // for a size dependent type.
8401   QualType DesugaredTy = Ty;
8402   do {
8403     ArrayRef<StringRef> Names(SizeTypeNames);
8404     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8405     if (Names.end() != Match)
8406       return true;
8407 
8408     Ty = DesugaredTy;
8409     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8410   } while (DesugaredTy != Ty);
8411 
8412   return false;
8413 }
8414 
8415 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8416   if (PT->isPointerType()) {
8417     QualType PointeeType = PT->getPointeeType();
8418     if (PointeeType->isPointerType())
8419       return PtrPtrKernelParam;
8420     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8421         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8422         PointeeType.getAddressSpace() == LangAS::Default)
8423       return InvalidAddrSpacePtrKernelParam;
8424     return PtrKernelParam;
8425   }
8426 
8427   // OpenCL v1.2 s6.9.k:
8428   // Arguments to kernel functions in a program cannot be declared with the
8429   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8430   // uintptr_t or a struct and/or union that contain fields declared to be one
8431   // of these built-in scalar types.
8432   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8433     return InvalidKernelParam;
8434 
8435   if (PT->isImageType())
8436     return PtrKernelParam;
8437 
8438   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8439     return InvalidKernelParam;
8440 
8441   // OpenCL extension spec v1.2 s9.5:
8442   // This extension adds support for half scalar and vector types as built-in
8443   // types that can be used for arithmetic operations, conversions etc.
8444   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8445     return InvalidKernelParam;
8446 
8447   if (PT->isRecordType())
8448     return RecordKernelParam;
8449 
8450   // Look into an array argument to check if it has a forbidden type.
8451   if (PT->isArrayType()) {
8452     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8453     // Call ourself to check an underlying type of an array. Since the
8454     // getPointeeOrArrayElementType returns an innermost type which is not an
8455     // array, this recursive call only happens once.
8456     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8457   }
8458 
8459   return ValidKernelParam;
8460 }
8461 
8462 static void checkIsValidOpenCLKernelParameter(
8463   Sema &S,
8464   Declarator &D,
8465   ParmVarDecl *Param,
8466   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8467   QualType PT = Param->getType();
8468 
8469   // Cache the valid types we encounter to avoid rechecking structs that are
8470   // used again
8471   if (ValidTypes.count(PT.getTypePtr()))
8472     return;
8473 
8474   switch (getOpenCLKernelParameterType(S, PT)) {
8475   case PtrPtrKernelParam:
8476     // OpenCL v1.2 s6.9.a:
8477     // A kernel function argument cannot be declared as a
8478     // pointer to a pointer type.
8479     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8480     D.setInvalidType();
8481     return;
8482 
8483   case InvalidAddrSpacePtrKernelParam:
8484     // OpenCL v1.0 s6.5:
8485     // __kernel function arguments declared to be a pointer of a type can point
8486     // to one of the following address spaces only : __global, __local or
8487     // __constant.
8488     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8489     D.setInvalidType();
8490     return;
8491 
8492     // OpenCL v1.2 s6.9.k:
8493     // Arguments to kernel functions in a program cannot be declared with the
8494     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8495     // uintptr_t or a struct and/or union that contain fields declared to be
8496     // one of these built-in scalar types.
8497 
8498   case InvalidKernelParam:
8499     // OpenCL v1.2 s6.8 n:
8500     // A kernel function argument cannot be declared
8501     // of event_t type.
8502     // Do not diagnose half type since it is diagnosed as invalid argument
8503     // type for any function elsewhere.
8504     if (!PT->isHalfType()) {
8505       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8506 
8507       // Explain what typedefs are involved.
8508       const TypedefType *Typedef = nullptr;
8509       while ((Typedef = PT->getAs<TypedefType>())) {
8510         SourceLocation Loc = Typedef->getDecl()->getLocation();
8511         // SourceLocation may be invalid for a built-in type.
8512         if (Loc.isValid())
8513           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8514         PT = Typedef->desugar();
8515       }
8516     }
8517 
8518     D.setInvalidType();
8519     return;
8520 
8521   case PtrKernelParam:
8522   case ValidKernelParam:
8523     ValidTypes.insert(PT.getTypePtr());
8524     return;
8525 
8526   case RecordKernelParam:
8527     break;
8528   }
8529 
8530   // Track nested structs we will inspect
8531   SmallVector<const Decl *, 4> VisitStack;
8532 
8533   // Track where we are in the nested structs. Items will migrate from
8534   // VisitStack to HistoryStack as we do the DFS for bad field.
8535   SmallVector<const FieldDecl *, 4> HistoryStack;
8536   HistoryStack.push_back(nullptr);
8537 
8538   // At this point we already handled everything except of a RecordType or
8539   // an ArrayType of a RecordType.
8540   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8541   const RecordType *RecTy =
8542       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8543   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8544 
8545   VisitStack.push_back(RecTy->getDecl());
8546   assert(VisitStack.back() && "First decl null?");
8547 
8548   do {
8549     const Decl *Next = VisitStack.pop_back_val();
8550     if (!Next) {
8551       assert(!HistoryStack.empty());
8552       // Found a marker, we have gone up a level
8553       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8554         ValidTypes.insert(Hist->getType().getTypePtr());
8555 
8556       continue;
8557     }
8558 
8559     // Adds everything except the original parameter declaration (which is not a
8560     // field itself) to the history stack.
8561     const RecordDecl *RD;
8562     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8563       HistoryStack.push_back(Field);
8564 
8565       QualType FieldTy = Field->getType();
8566       // Other field types (known to be valid or invalid) are handled while we
8567       // walk around RecordDecl::fields().
8568       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8569              "Unexpected type.");
8570       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8571 
8572       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8573     } else {
8574       RD = cast<RecordDecl>(Next);
8575     }
8576 
8577     // Add a null marker so we know when we've gone back up a level
8578     VisitStack.push_back(nullptr);
8579 
8580     for (const auto *FD : RD->fields()) {
8581       QualType QT = FD->getType();
8582 
8583       if (ValidTypes.count(QT.getTypePtr()))
8584         continue;
8585 
8586       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8587       if (ParamType == ValidKernelParam)
8588         continue;
8589 
8590       if (ParamType == RecordKernelParam) {
8591         VisitStack.push_back(FD);
8592         continue;
8593       }
8594 
8595       // OpenCL v1.2 s6.9.p:
8596       // Arguments to kernel functions that are declared to be a struct or union
8597       // do not allow OpenCL objects to be passed as elements of the struct or
8598       // union.
8599       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8600           ParamType == InvalidAddrSpacePtrKernelParam) {
8601         S.Diag(Param->getLocation(),
8602                diag::err_record_with_pointers_kernel_param)
8603           << PT->isUnionType()
8604           << PT;
8605       } else {
8606         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8607       }
8608 
8609       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8610           << OrigRecDecl->getDeclName();
8611 
8612       // We have an error, now let's go back up through history and show where
8613       // the offending field came from
8614       for (ArrayRef<const FieldDecl *>::const_iterator
8615                I = HistoryStack.begin() + 1,
8616                E = HistoryStack.end();
8617            I != E; ++I) {
8618         const FieldDecl *OuterField = *I;
8619         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8620           << OuterField->getType();
8621       }
8622 
8623       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8624         << QT->isPointerType()
8625         << QT;
8626       D.setInvalidType();
8627       return;
8628     }
8629   } while (!VisitStack.empty());
8630 }
8631 
8632 /// Find the DeclContext in which a tag is implicitly declared if we see an
8633 /// elaborated type specifier in the specified context, and lookup finds
8634 /// nothing.
8635 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8636   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8637     DC = DC->getParent();
8638   return DC;
8639 }
8640 
8641 /// Find the Scope in which a tag is implicitly declared if we see an
8642 /// elaborated type specifier in the specified context, and lookup finds
8643 /// nothing.
8644 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8645   while (S->isClassScope() ||
8646          (LangOpts.CPlusPlus &&
8647           S->isFunctionPrototypeScope()) ||
8648          ((S->getFlags() & Scope::DeclScope) == 0) ||
8649          (S->getEntity() && S->getEntity()->isTransparentContext()))
8650     S = S->getParent();
8651   return S;
8652 }
8653 
8654 NamedDecl*
8655 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8656                               TypeSourceInfo *TInfo, LookupResult &Previous,
8657                               MultiTemplateParamsArg TemplateParamLists,
8658                               bool &AddToScope) {
8659   QualType R = TInfo->getType();
8660 
8661   assert(R->isFunctionType());
8662 
8663   // TODO: consider using NameInfo for diagnostic.
8664   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8665   DeclarationName Name = NameInfo.getName();
8666   StorageClass SC = getFunctionStorageClass(*this, D);
8667 
8668   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8669     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8670          diag::err_invalid_thread)
8671       << DeclSpec::getSpecifierName(TSCS);
8672 
8673   if (D.isFirstDeclarationOfMember())
8674     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8675                            D.getIdentifierLoc());
8676 
8677   bool isFriend = false;
8678   FunctionTemplateDecl *FunctionTemplate = nullptr;
8679   bool isMemberSpecialization = false;
8680   bool isFunctionTemplateSpecialization = false;
8681 
8682   bool isDependentClassScopeExplicitSpecialization = false;
8683   bool HasExplicitTemplateArgs = false;
8684   TemplateArgumentListInfo TemplateArgs;
8685 
8686   bool isVirtualOkay = false;
8687 
8688   DeclContext *OriginalDC = DC;
8689   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8690 
8691   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8692                                               isVirtualOkay);
8693   if (!NewFD) return nullptr;
8694 
8695   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8696     NewFD->setTopLevelDeclInObjCContainer();
8697 
8698   // Set the lexical context. If this is a function-scope declaration, or has a
8699   // C++ scope specifier, or is the object of a friend declaration, the lexical
8700   // context will be different from the semantic context.
8701   NewFD->setLexicalDeclContext(CurContext);
8702 
8703   if (IsLocalExternDecl)
8704     NewFD->setLocalExternDecl();
8705 
8706   if (getLangOpts().CPlusPlus) {
8707     bool isInline = D.getDeclSpec().isInlineSpecified();
8708     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8709     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
8710     isFriend = D.getDeclSpec().isFriendSpecified();
8711     if (isFriend && !isInline && D.isFunctionDefinition()) {
8712       // C++ [class.friend]p5
8713       //   A function can be defined in a friend declaration of a
8714       //   class . . . . Such a function is implicitly inline.
8715       NewFD->setImplicitlyInline();
8716     }
8717 
8718     // If this is a method defined in an __interface, and is not a constructor
8719     // or an overloaded operator, then set the pure flag (isVirtual will already
8720     // return true).
8721     if (const CXXRecordDecl *Parent =
8722           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8723       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8724         NewFD->setPure(true);
8725 
8726       // C++ [class.union]p2
8727       //   A union can have member functions, but not virtual functions.
8728       if (isVirtual && Parent->isUnion())
8729         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8730     }
8731 
8732     SetNestedNameSpecifier(*this, NewFD, D);
8733     isMemberSpecialization = false;
8734     isFunctionTemplateSpecialization = false;
8735     if (D.isInvalidType())
8736       NewFD->setInvalidDecl();
8737 
8738     // Match up the template parameter lists with the scope specifier, then
8739     // determine whether we have a template or a template specialization.
8740     bool Invalid = false;
8741     if (TemplateParameterList *TemplateParams =
8742             MatchTemplateParametersToScopeSpecifier(
8743                 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8744                 D.getCXXScopeSpec(),
8745                 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8746                     ? D.getName().TemplateId
8747                     : nullptr,
8748                 TemplateParamLists, isFriend, isMemberSpecialization,
8749                 Invalid)) {
8750       if (TemplateParams->size() > 0) {
8751         // This is a function template
8752 
8753         // Check that we can declare a template here.
8754         if (CheckTemplateDeclScope(S, TemplateParams))
8755           NewFD->setInvalidDecl();
8756 
8757         // A destructor cannot be a template.
8758         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8759           Diag(NewFD->getLocation(), diag::err_destructor_template);
8760           NewFD->setInvalidDecl();
8761         }
8762 
8763         // If we're adding a template to a dependent context, we may need to
8764         // rebuilding some of the types used within the template parameter list,
8765         // now that we know what the current instantiation is.
8766         if (DC->isDependentContext()) {
8767           ContextRAII SavedContext(*this, DC);
8768           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8769             Invalid = true;
8770         }
8771 
8772         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8773                                                         NewFD->getLocation(),
8774                                                         Name, TemplateParams,
8775                                                         NewFD);
8776         FunctionTemplate->setLexicalDeclContext(CurContext);
8777         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8778 
8779         // For source fidelity, store the other template param lists.
8780         if (TemplateParamLists.size() > 1) {
8781           NewFD->setTemplateParameterListsInfo(Context,
8782                                                TemplateParamLists.drop_back(1));
8783         }
8784       } else {
8785         // This is a function template specialization.
8786         isFunctionTemplateSpecialization = true;
8787         // For source fidelity, store all the template param lists.
8788         if (TemplateParamLists.size() > 0)
8789           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8790 
8791         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8792         if (isFriend) {
8793           // We want to remove the "template<>", found here.
8794           SourceRange RemoveRange = TemplateParams->getSourceRange();
8795 
8796           // If we remove the template<> and the name is not a
8797           // template-id, we're actually silently creating a problem:
8798           // the friend declaration will refer to an untemplated decl,
8799           // and clearly the user wants a template specialization.  So
8800           // we need to insert '<>' after the name.
8801           SourceLocation InsertLoc;
8802           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8803             InsertLoc = D.getName().getSourceRange().getEnd();
8804             InsertLoc = getLocForEndOfToken(InsertLoc);
8805           }
8806 
8807           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8808             << Name << RemoveRange
8809             << FixItHint::CreateRemoval(RemoveRange)
8810             << FixItHint::CreateInsertion(InsertLoc, "<>");
8811         }
8812       }
8813     } else {
8814       // All template param lists were matched against the scope specifier:
8815       // this is NOT (an explicit specialization of) a template.
8816       if (TemplateParamLists.size() > 0)
8817         // For source fidelity, store all the template param lists.
8818         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8819     }
8820 
8821     if (Invalid) {
8822       NewFD->setInvalidDecl();
8823       if (FunctionTemplate)
8824         FunctionTemplate->setInvalidDecl();
8825     }
8826 
8827     // C++ [dcl.fct.spec]p5:
8828     //   The virtual specifier shall only be used in declarations of
8829     //   nonstatic class member functions that appear within a
8830     //   member-specification of a class declaration; see 10.3.
8831     //
8832     if (isVirtual && !NewFD->isInvalidDecl()) {
8833       if (!isVirtualOkay) {
8834         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8835              diag::err_virtual_non_function);
8836       } else if (!CurContext->isRecord()) {
8837         // 'virtual' was specified outside of the class.
8838         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8839              diag::err_virtual_out_of_class)
8840           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8841       } else if (NewFD->getDescribedFunctionTemplate()) {
8842         // C++ [temp.mem]p3:
8843         //  A member function template shall not be virtual.
8844         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8845              diag::err_virtual_member_function_template)
8846           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8847       } else {
8848         // Okay: Add virtual to the method.
8849         NewFD->setVirtualAsWritten(true);
8850       }
8851 
8852       if (getLangOpts().CPlusPlus14 &&
8853           NewFD->getReturnType()->isUndeducedType())
8854         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8855     }
8856 
8857     if (getLangOpts().CPlusPlus14 &&
8858         (NewFD->isDependentContext() ||
8859          (isFriend && CurContext->isDependentContext())) &&
8860         NewFD->getReturnType()->isUndeducedType()) {
8861       // If the function template is referenced directly (for instance, as a
8862       // member of the current instantiation), pretend it has a dependent type.
8863       // This is not really justified by the standard, but is the only sane
8864       // thing to do.
8865       // FIXME: For a friend function, we have not marked the function as being
8866       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8867       const FunctionProtoType *FPT =
8868           NewFD->getType()->castAs<FunctionProtoType>();
8869       QualType Result =
8870           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8871       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8872                                              FPT->getExtProtoInfo()));
8873     }
8874 
8875     // C++ [dcl.fct.spec]p3:
8876     //  The inline specifier shall not appear on a block scope function
8877     //  declaration.
8878     if (isInline && !NewFD->isInvalidDecl()) {
8879       if (CurContext->isFunctionOrMethod()) {
8880         // 'inline' is not allowed on block scope function declaration.
8881         Diag(D.getDeclSpec().getInlineSpecLoc(),
8882              diag::err_inline_declaration_block_scope) << Name
8883           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8884       }
8885     }
8886 
8887     // C++ [dcl.fct.spec]p6:
8888     //  The explicit specifier shall be used only in the declaration of a
8889     //  constructor or conversion function within its class definition;
8890     //  see 12.3.1 and 12.3.2.
8891     if (hasExplicit && !NewFD->isInvalidDecl() &&
8892         !isa<CXXDeductionGuideDecl>(NewFD)) {
8893       if (!CurContext->isRecord()) {
8894         // 'explicit' was specified outside of the class.
8895         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8896              diag::err_explicit_out_of_class)
8897             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
8898       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8899                  !isa<CXXConversionDecl>(NewFD)) {
8900         // 'explicit' was specified on a function that wasn't a constructor
8901         // or conversion function.
8902         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8903              diag::err_explicit_non_ctor_or_conv_function)
8904             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
8905       }
8906     }
8907 
8908     if (ConstexprSpecKind ConstexprKind =
8909             D.getDeclSpec().getConstexprSpecifier()) {
8910       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8911       // are implicitly inline.
8912       NewFD->setImplicitlyInline();
8913 
8914       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8915       // be either constructors or to return a literal type. Therefore,
8916       // destructors cannot be declared constexpr.
8917       if (isa<CXXDestructorDecl>(NewFD) && !getLangOpts().CPlusPlus2a) {
8918         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
8919             << ConstexprKind;
8920       }
8921     }
8922 
8923     // If __module_private__ was specified, mark the function accordingly.
8924     if (D.getDeclSpec().isModulePrivateSpecified()) {
8925       if (isFunctionTemplateSpecialization) {
8926         SourceLocation ModulePrivateLoc
8927           = D.getDeclSpec().getModulePrivateSpecLoc();
8928         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8929           << 0
8930           << FixItHint::CreateRemoval(ModulePrivateLoc);
8931       } else {
8932         NewFD->setModulePrivate();
8933         if (FunctionTemplate)
8934           FunctionTemplate->setModulePrivate();
8935       }
8936     }
8937 
8938     if (isFriend) {
8939       if (FunctionTemplate) {
8940         FunctionTemplate->setObjectOfFriendDecl();
8941         FunctionTemplate->setAccess(AS_public);
8942       }
8943       NewFD->setObjectOfFriendDecl();
8944       NewFD->setAccess(AS_public);
8945     }
8946 
8947     // If a function is defined as defaulted or deleted, mark it as such now.
8948     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8949     // definition kind to FDK_Definition.
8950     switch (D.getFunctionDefinitionKind()) {
8951       case FDK_Declaration:
8952       case FDK_Definition:
8953         break;
8954 
8955       case FDK_Defaulted:
8956         NewFD->setDefaulted();
8957         break;
8958 
8959       case FDK_Deleted:
8960         NewFD->setDeletedAsWritten();
8961         break;
8962     }
8963 
8964     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8965         D.isFunctionDefinition()) {
8966       // C++ [class.mfct]p2:
8967       //   A member function may be defined (8.4) in its class definition, in
8968       //   which case it is an inline member function (7.1.2)
8969       NewFD->setImplicitlyInline();
8970     }
8971 
8972     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8973         !CurContext->isRecord()) {
8974       // C++ [class.static]p1:
8975       //   A data or function member of a class may be declared static
8976       //   in a class definition, in which case it is a static member of
8977       //   the class.
8978 
8979       // Complain about the 'static' specifier if it's on an out-of-line
8980       // member function definition.
8981 
8982       // MSVC permits the use of a 'static' storage specifier on an out-of-line
8983       // member function template declaration and class member template
8984       // declaration (MSVC versions before 2015), warn about this.
8985       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8986            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
8987              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
8988            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
8989            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
8990         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8991     }
8992 
8993     // C++11 [except.spec]p15:
8994     //   A deallocation function with no exception-specification is treated
8995     //   as if it were specified with noexcept(true).
8996     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8997     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8998          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8999         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9000       NewFD->setType(Context.getFunctionType(
9001           FPT->getReturnType(), FPT->getParamTypes(),
9002           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9003   }
9004 
9005   // Filter out previous declarations that don't match the scope.
9006   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9007                        D.getCXXScopeSpec().isNotEmpty() ||
9008                        isMemberSpecialization ||
9009                        isFunctionTemplateSpecialization);
9010 
9011   // Handle GNU asm-label extension (encoded as an attribute).
9012   if (Expr *E = (Expr*) D.getAsmLabel()) {
9013     // The parser guarantees this is a string.
9014     StringLiteral *SE = cast<StringLiteral>(E);
9015     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9016                                         /*IsLiteralLabel=*/true,
9017                                         SE->getStrTokenLoc(0)));
9018   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9019     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9020       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9021     if (I != ExtnameUndeclaredIdentifiers.end()) {
9022       if (isDeclExternC(NewFD)) {
9023         NewFD->addAttr(I->second);
9024         ExtnameUndeclaredIdentifiers.erase(I);
9025       } else
9026         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9027             << /*Variable*/0 << NewFD;
9028     }
9029   }
9030 
9031   // Copy the parameter declarations from the declarator D to the function
9032   // declaration NewFD, if they are available.  First scavenge them into Params.
9033   SmallVector<ParmVarDecl*, 16> Params;
9034   unsigned FTIIdx;
9035   if (D.isFunctionDeclarator(FTIIdx)) {
9036     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9037 
9038     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9039     // function that takes no arguments, not a function that takes a
9040     // single void argument.
9041     // We let through "const void" here because Sema::GetTypeForDeclarator
9042     // already checks for that case.
9043     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9044       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9045         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9046         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9047         Param->setDeclContext(NewFD);
9048         Params.push_back(Param);
9049 
9050         if (Param->isInvalidDecl())
9051           NewFD->setInvalidDecl();
9052       }
9053     }
9054 
9055     if (!getLangOpts().CPlusPlus) {
9056       // In C, find all the tag declarations from the prototype and move them
9057       // into the function DeclContext. Remove them from the surrounding tag
9058       // injection context of the function, which is typically but not always
9059       // the TU.
9060       DeclContext *PrototypeTagContext =
9061           getTagInjectionContext(NewFD->getLexicalDeclContext());
9062       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9063         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9064 
9065         // We don't want to reparent enumerators. Look at their parent enum
9066         // instead.
9067         if (!TD) {
9068           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9069             TD = cast<EnumDecl>(ECD->getDeclContext());
9070         }
9071         if (!TD)
9072           continue;
9073         DeclContext *TagDC = TD->getLexicalDeclContext();
9074         if (!TagDC->containsDecl(TD))
9075           continue;
9076         TagDC->removeDecl(TD);
9077         TD->setDeclContext(NewFD);
9078         NewFD->addDecl(TD);
9079 
9080         // Preserve the lexical DeclContext if it is not the surrounding tag
9081         // injection context of the FD. In this example, the semantic context of
9082         // E will be f and the lexical context will be S, while both the
9083         // semantic and lexical contexts of S will be f:
9084         //   void f(struct S { enum E { a } f; } s);
9085         if (TagDC != PrototypeTagContext)
9086           TD->setLexicalDeclContext(TagDC);
9087       }
9088     }
9089   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9090     // When we're declaring a function with a typedef, typeof, etc as in the
9091     // following example, we'll need to synthesize (unnamed)
9092     // parameters for use in the declaration.
9093     //
9094     // @code
9095     // typedef void fn(int);
9096     // fn f;
9097     // @endcode
9098 
9099     // Synthesize a parameter for each argument type.
9100     for (const auto &AI : FT->param_types()) {
9101       ParmVarDecl *Param =
9102           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9103       Param->setScopeInfo(0, Params.size());
9104       Params.push_back(Param);
9105     }
9106   } else {
9107     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9108            "Should not need args for typedef of non-prototype fn");
9109   }
9110 
9111   // Finally, we know we have the right number of parameters, install them.
9112   NewFD->setParams(Params);
9113 
9114   if (D.getDeclSpec().isNoreturnSpecified())
9115     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9116                                            D.getDeclSpec().getNoreturnSpecLoc(),
9117                                            AttributeCommonInfo::AS_Keyword));
9118 
9119   // Functions returning a variably modified type violate C99 6.7.5.2p2
9120   // because all functions have linkage.
9121   if (!NewFD->isInvalidDecl() &&
9122       NewFD->getReturnType()->isVariablyModifiedType()) {
9123     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9124     NewFD->setInvalidDecl();
9125   }
9126 
9127   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9128   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9129       !NewFD->hasAttr<SectionAttr>())
9130     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9131         Context, PragmaClangTextSection.SectionName,
9132         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9133 
9134   // Apply an implicit SectionAttr if #pragma code_seg is active.
9135   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9136       !NewFD->hasAttr<SectionAttr>()) {
9137     NewFD->addAttr(SectionAttr::CreateImplicit(
9138         Context, CodeSegStack.CurrentValue->getString(),
9139         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9140         SectionAttr::Declspec_allocate));
9141     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9142                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9143                          ASTContext::PSF_Read,
9144                      NewFD))
9145       NewFD->dropAttr<SectionAttr>();
9146   }
9147 
9148   // Apply an implicit CodeSegAttr from class declspec or
9149   // apply an implicit SectionAttr from #pragma code_seg if active.
9150   if (!NewFD->hasAttr<CodeSegAttr>()) {
9151     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9152                                                                  D.isFunctionDefinition())) {
9153       NewFD->addAttr(SAttr);
9154     }
9155   }
9156 
9157   // Handle attributes.
9158   ProcessDeclAttributes(S, NewFD, D);
9159 
9160   if (getLangOpts().OpenCL) {
9161     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9162     // type declaration will generate a compilation error.
9163     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9164     if (AddressSpace != LangAS::Default) {
9165       Diag(NewFD->getLocation(),
9166            diag::err_opencl_return_value_with_address_space);
9167       NewFD->setInvalidDecl();
9168     }
9169   }
9170 
9171   if (!getLangOpts().CPlusPlus) {
9172     // Perform semantic checking on the function declaration.
9173     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9174       CheckMain(NewFD, D.getDeclSpec());
9175 
9176     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9177       CheckMSVCRTEntryPoint(NewFD);
9178 
9179     if (!NewFD->isInvalidDecl())
9180       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9181                                                   isMemberSpecialization));
9182     else if (!Previous.empty())
9183       // Recover gracefully from an invalid redeclaration.
9184       D.setRedeclaration(true);
9185     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9186             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9187            "previous declaration set still overloaded");
9188 
9189     // Diagnose no-prototype function declarations with calling conventions that
9190     // don't support variadic calls. Only do this in C and do it after merging
9191     // possibly prototyped redeclarations.
9192     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9193     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9194       CallingConv CC = FT->getExtInfo().getCC();
9195       if (!supportsVariadicCall(CC)) {
9196         // Windows system headers sometimes accidentally use stdcall without
9197         // (void) parameters, so we relax this to a warning.
9198         int DiagID =
9199             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9200         Diag(NewFD->getLocation(), DiagID)
9201             << FunctionType::getNameForCallConv(CC);
9202       }
9203     }
9204 
9205    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9206        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9207      checkNonTrivialCUnion(NewFD->getReturnType(),
9208                            NewFD->getReturnTypeSourceRange().getBegin(),
9209                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9210   } else {
9211     // C++11 [replacement.functions]p3:
9212     //  The program's definitions shall not be specified as inline.
9213     //
9214     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9215     //
9216     // Suppress the diagnostic if the function is __attribute__((used)), since
9217     // that forces an external definition to be emitted.
9218     if (D.getDeclSpec().isInlineSpecified() &&
9219         NewFD->isReplaceableGlobalAllocationFunction() &&
9220         !NewFD->hasAttr<UsedAttr>())
9221       Diag(D.getDeclSpec().getInlineSpecLoc(),
9222            diag::ext_operator_new_delete_declared_inline)
9223         << NewFD->getDeclName();
9224 
9225     // If the declarator is a template-id, translate the parser's template
9226     // argument list into our AST format.
9227     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9228       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9229       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9230       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9231       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9232                                          TemplateId->NumArgs);
9233       translateTemplateArguments(TemplateArgsPtr,
9234                                  TemplateArgs);
9235 
9236       HasExplicitTemplateArgs = true;
9237 
9238       if (NewFD->isInvalidDecl()) {
9239         HasExplicitTemplateArgs = false;
9240       } else if (FunctionTemplate) {
9241         // Function template with explicit template arguments.
9242         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9243           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9244 
9245         HasExplicitTemplateArgs = false;
9246       } else {
9247         assert((isFunctionTemplateSpecialization ||
9248                 D.getDeclSpec().isFriendSpecified()) &&
9249                "should have a 'template<>' for this decl");
9250         // "friend void foo<>(int);" is an implicit specialization decl.
9251         isFunctionTemplateSpecialization = true;
9252       }
9253     } else if (isFriend && isFunctionTemplateSpecialization) {
9254       // This combination is only possible in a recovery case;  the user
9255       // wrote something like:
9256       //   template <> friend void foo(int);
9257       // which we're recovering from as if the user had written:
9258       //   friend void foo<>(int);
9259       // Go ahead and fake up a template id.
9260       HasExplicitTemplateArgs = true;
9261       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9262       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9263     }
9264 
9265     // We do not add HD attributes to specializations here because
9266     // they may have different constexpr-ness compared to their
9267     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9268     // may end up with different effective targets. Instead, a
9269     // specialization inherits its target attributes from its template
9270     // in the CheckFunctionTemplateSpecialization() call below.
9271     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9272       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9273 
9274     // If it's a friend (and only if it's a friend), it's possible
9275     // that either the specialized function type or the specialized
9276     // template is dependent, and therefore matching will fail.  In
9277     // this case, don't check the specialization yet.
9278     bool InstantiationDependent = false;
9279     if (isFunctionTemplateSpecialization && isFriend &&
9280         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9281          TemplateSpecializationType::anyDependentTemplateArguments(
9282             TemplateArgs,
9283             InstantiationDependent))) {
9284       assert(HasExplicitTemplateArgs &&
9285              "friend function specialization without template args");
9286       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9287                                                        Previous))
9288         NewFD->setInvalidDecl();
9289     } else if (isFunctionTemplateSpecialization) {
9290       if (CurContext->isDependentContext() && CurContext->isRecord()
9291           && !isFriend) {
9292         isDependentClassScopeExplicitSpecialization = true;
9293       } else if (!NewFD->isInvalidDecl() &&
9294                  CheckFunctionTemplateSpecialization(
9295                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9296                      Previous))
9297         NewFD->setInvalidDecl();
9298 
9299       // C++ [dcl.stc]p1:
9300       //   A storage-class-specifier shall not be specified in an explicit
9301       //   specialization (14.7.3)
9302       FunctionTemplateSpecializationInfo *Info =
9303           NewFD->getTemplateSpecializationInfo();
9304       if (Info && SC != SC_None) {
9305         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9306           Diag(NewFD->getLocation(),
9307                diag::err_explicit_specialization_inconsistent_storage_class)
9308             << SC
9309             << FixItHint::CreateRemoval(
9310                                       D.getDeclSpec().getStorageClassSpecLoc());
9311 
9312         else
9313           Diag(NewFD->getLocation(),
9314                diag::ext_explicit_specialization_storage_class)
9315             << FixItHint::CreateRemoval(
9316                                       D.getDeclSpec().getStorageClassSpecLoc());
9317       }
9318     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9319       if (CheckMemberSpecialization(NewFD, Previous))
9320           NewFD->setInvalidDecl();
9321     }
9322 
9323     // Perform semantic checking on the function declaration.
9324     if (!isDependentClassScopeExplicitSpecialization) {
9325       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9326         CheckMain(NewFD, D.getDeclSpec());
9327 
9328       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9329         CheckMSVCRTEntryPoint(NewFD);
9330 
9331       if (!NewFD->isInvalidDecl())
9332         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9333                                                     isMemberSpecialization));
9334       else if (!Previous.empty())
9335         // Recover gracefully from an invalid redeclaration.
9336         D.setRedeclaration(true);
9337     }
9338 
9339     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9340             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9341            "previous declaration set still overloaded");
9342 
9343     NamedDecl *PrincipalDecl = (FunctionTemplate
9344                                 ? cast<NamedDecl>(FunctionTemplate)
9345                                 : NewFD);
9346 
9347     if (isFriend && NewFD->getPreviousDecl()) {
9348       AccessSpecifier Access = AS_public;
9349       if (!NewFD->isInvalidDecl())
9350         Access = NewFD->getPreviousDecl()->getAccess();
9351 
9352       NewFD->setAccess(Access);
9353       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9354     }
9355 
9356     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9357         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9358       PrincipalDecl->setNonMemberOperator();
9359 
9360     // If we have a function template, check the template parameter
9361     // list. This will check and merge default template arguments.
9362     if (FunctionTemplate) {
9363       FunctionTemplateDecl *PrevTemplate =
9364                                      FunctionTemplate->getPreviousDecl();
9365       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9366                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9367                                     : nullptr,
9368                             D.getDeclSpec().isFriendSpecified()
9369                               ? (D.isFunctionDefinition()
9370                                    ? TPC_FriendFunctionTemplateDefinition
9371                                    : TPC_FriendFunctionTemplate)
9372                               : (D.getCXXScopeSpec().isSet() &&
9373                                  DC && DC->isRecord() &&
9374                                  DC->isDependentContext())
9375                                   ? TPC_ClassTemplateMember
9376                                   : TPC_FunctionTemplate);
9377     }
9378 
9379     if (NewFD->isInvalidDecl()) {
9380       // Ignore all the rest of this.
9381     } else if (!D.isRedeclaration()) {
9382       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9383                                        AddToScope };
9384       // Fake up an access specifier if it's supposed to be a class member.
9385       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9386         NewFD->setAccess(AS_public);
9387 
9388       // Qualified decls generally require a previous declaration.
9389       if (D.getCXXScopeSpec().isSet()) {
9390         // ...with the major exception of templated-scope or
9391         // dependent-scope friend declarations.
9392 
9393         // TODO: we currently also suppress this check in dependent
9394         // contexts because (1) the parameter depth will be off when
9395         // matching friend templates and (2) we might actually be
9396         // selecting a friend based on a dependent factor.  But there
9397         // are situations where these conditions don't apply and we
9398         // can actually do this check immediately.
9399         //
9400         // Unless the scope is dependent, it's always an error if qualified
9401         // redeclaration lookup found nothing at all. Diagnose that now;
9402         // nothing will diagnose that error later.
9403         if (isFriend &&
9404             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9405              (!Previous.empty() && CurContext->isDependentContext()))) {
9406           // ignore these
9407         } else {
9408           // The user tried to provide an out-of-line definition for a
9409           // function that is a member of a class or namespace, but there
9410           // was no such member function declared (C++ [class.mfct]p2,
9411           // C++ [namespace.memdef]p2). For example:
9412           //
9413           // class X {
9414           //   void f() const;
9415           // };
9416           //
9417           // void X::f() { } // ill-formed
9418           //
9419           // Complain about this problem, and attempt to suggest close
9420           // matches (e.g., those that differ only in cv-qualifiers and
9421           // whether the parameter types are references).
9422 
9423           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9424                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9425             AddToScope = ExtraArgs.AddToScope;
9426             return Result;
9427           }
9428         }
9429 
9430         // Unqualified local friend declarations are required to resolve
9431         // to something.
9432       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9433         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9434                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9435           AddToScope = ExtraArgs.AddToScope;
9436           return Result;
9437         }
9438       }
9439     } else if (!D.isFunctionDefinition() &&
9440                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9441                !isFriend && !isFunctionTemplateSpecialization &&
9442                !isMemberSpecialization) {
9443       // An out-of-line member function declaration must also be a
9444       // definition (C++ [class.mfct]p2).
9445       // Note that this is not the case for explicit specializations of
9446       // function templates or member functions of class templates, per
9447       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9448       // extension for compatibility with old SWIG code which likes to
9449       // generate them.
9450       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9451         << D.getCXXScopeSpec().getRange();
9452     }
9453   }
9454 
9455   ProcessPragmaWeak(S, NewFD);
9456   checkAttributesAfterMerging(*this, *NewFD);
9457 
9458   AddKnownFunctionAttributes(NewFD);
9459 
9460   if (NewFD->hasAttr<OverloadableAttr>() &&
9461       !NewFD->getType()->getAs<FunctionProtoType>()) {
9462     Diag(NewFD->getLocation(),
9463          diag::err_attribute_overloadable_no_prototype)
9464       << NewFD;
9465 
9466     // Turn this into a variadic function with no parameters.
9467     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9468     FunctionProtoType::ExtProtoInfo EPI(
9469         Context.getDefaultCallingConvention(true, false));
9470     EPI.Variadic = true;
9471     EPI.ExtInfo = FT->getExtInfo();
9472 
9473     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9474     NewFD->setType(R);
9475   }
9476 
9477   // If there's a #pragma GCC visibility in scope, and this isn't a class
9478   // member, set the visibility of this function.
9479   if (!DC->isRecord() && NewFD->isExternallyVisible())
9480     AddPushedVisibilityAttribute(NewFD);
9481 
9482   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9483   // marking the function.
9484   AddCFAuditedAttribute(NewFD);
9485 
9486   // If this is a function definition, check if we have to apply optnone due to
9487   // a pragma.
9488   if(D.isFunctionDefinition())
9489     AddRangeBasedOptnone(NewFD);
9490 
9491   // If this is the first declaration of an extern C variable, update
9492   // the map of such variables.
9493   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9494       isIncompleteDeclExternC(*this, NewFD))
9495     RegisterLocallyScopedExternCDecl(NewFD, S);
9496 
9497   // Set this FunctionDecl's range up to the right paren.
9498   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9499 
9500   if (D.isRedeclaration() && !Previous.empty()) {
9501     NamedDecl *Prev = Previous.getRepresentativeDecl();
9502     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9503                                    isMemberSpecialization ||
9504                                        isFunctionTemplateSpecialization,
9505                                    D.isFunctionDefinition());
9506   }
9507 
9508   if (getLangOpts().CUDA) {
9509     IdentifierInfo *II = NewFD->getIdentifier();
9510     if (II && II->isStr(getCudaConfigureFuncName()) &&
9511         !NewFD->isInvalidDecl() &&
9512         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9513       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9514         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9515             << getCudaConfigureFuncName();
9516       Context.setcudaConfigureCallDecl(NewFD);
9517     }
9518 
9519     // Variadic functions, other than a *declaration* of printf, are not allowed
9520     // in device-side CUDA code, unless someone passed
9521     // -fcuda-allow-variadic-functions.
9522     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9523         (NewFD->hasAttr<CUDADeviceAttr>() ||
9524          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9525         !(II && II->isStr("printf") && NewFD->isExternC() &&
9526           !D.isFunctionDefinition())) {
9527       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9528     }
9529   }
9530 
9531   MarkUnusedFileScopedDecl(NewFD);
9532 
9533 
9534 
9535   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9536     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9537     if ((getLangOpts().OpenCLVersion >= 120)
9538         && (SC == SC_Static)) {
9539       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9540       D.setInvalidType();
9541     }
9542 
9543     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9544     if (!NewFD->getReturnType()->isVoidType()) {
9545       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9546       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9547           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9548                                 : FixItHint());
9549       D.setInvalidType();
9550     }
9551 
9552     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9553     for (auto Param : NewFD->parameters())
9554       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9555 
9556     if (getLangOpts().OpenCLCPlusPlus) {
9557       if (DC->isRecord()) {
9558         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9559         D.setInvalidType();
9560       }
9561       if (FunctionTemplate) {
9562         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9563         D.setInvalidType();
9564       }
9565     }
9566   }
9567 
9568   if (getLangOpts().CPlusPlus) {
9569     if (FunctionTemplate) {
9570       if (NewFD->isInvalidDecl())
9571         FunctionTemplate->setInvalidDecl();
9572       return FunctionTemplate;
9573     }
9574 
9575     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9576       CompleteMemberSpecialization(NewFD, Previous);
9577   }
9578 
9579   for (const ParmVarDecl *Param : NewFD->parameters()) {
9580     QualType PT = Param->getType();
9581 
9582     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9583     // types.
9584     if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
9585       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9586         QualType ElemTy = PipeTy->getElementType();
9587           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9588             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9589             D.setInvalidType();
9590           }
9591       }
9592     }
9593   }
9594 
9595   // Here we have an function template explicit specialization at class scope.
9596   // The actual specialization will be postponed to template instatiation
9597   // time via the ClassScopeFunctionSpecializationDecl node.
9598   if (isDependentClassScopeExplicitSpecialization) {
9599     ClassScopeFunctionSpecializationDecl *NewSpec =
9600                          ClassScopeFunctionSpecializationDecl::Create(
9601                                 Context, CurContext, NewFD->getLocation(),
9602                                 cast<CXXMethodDecl>(NewFD),
9603                                 HasExplicitTemplateArgs, TemplateArgs);
9604     CurContext->addDecl(NewSpec);
9605     AddToScope = false;
9606   }
9607 
9608   // Diagnose availability attributes. Availability cannot be used on functions
9609   // that are run during load/unload.
9610   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9611     if (NewFD->hasAttr<ConstructorAttr>()) {
9612       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9613           << 1;
9614       NewFD->dropAttr<AvailabilityAttr>();
9615     }
9616     if (NewFD->hasAttr<DestructorAttr>()) {
9617       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9618           << 2;
9619       NewFD->dropAttr<AvailabilityAttr>();
9620     }
9621   }
9622 
9623   // Diagnose no_builtin attribute on function declaration that are not a
9624   // definition.
9625   // FIXME: We should really be doing this in
9626   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
9627   // the FunctionDecl and at this point of the code
9628   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
9629   // because Sema::ActOnStartOfFunctionDef has not been called yet.
9630   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
9631     switch (D.getFunctionDefinitionKind()) {
9632     case FDK_Defaulted:
9633     case FDK_Deleted:
9634       Diag(NBA->getLocation(),
9635            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
9636           << NBA->getSpelling();
9637       break;
9638     case FDK_Declaration:
9639       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
9640           << NBA->getSpelling();
9641       break;
9642     case FDK_Definition:
9643       break;
9644     }
9645 
9646   return NewFD;
9647 }
9648 
9649 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
9650 /// when __declspec(code_seg) "is applied to a class, all member functions of
9651 /// the class and nested classes -- this includes compiler-generated special
9652 /// member functions -- are put in the specified segment."
9653 /// The actual behavior is a little more complicated. The Microsoft compiler
9654 /// won't check outer classes if there is an active value from #pragma code_seg.
9655 /// The CodeSeg is always applied from the direct parent but only from outer
9656 /// classes when the #pragma code_seg stack is empty. See:
9657 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9658 /// available since MS has removed the page.
9659 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9660   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9661   if (!Method)
9662     return nullptr;
9663   const CXXRecordDecl *Parent = Method->getParent();
9664   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9665     Attr *NewAttr = SAttr->clone(S.getASTContext());
9666     NewAttr->setImplicit(true);
9667     return NewAttr;
9668   }
9669 
9670   // The Microsoft compiler won't check outer classes for the CodeSeg
9671   // when the #pragma code_seg stack is active.
9672   if (S.CodeSegStack.CurrentValue)
9673    return nullptr;
9674 
9675   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9676     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9677       Attr *NewAttr = SAttr->clone(S.getASTContext());
9678       NewAttr->setImplicit(true);
9679       return NewAttr;
9680     }
9681   }
9682   return nullptr;
9683 }
9684 
9685 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9686 /// containing class. Otherwise it will return implicit SectionAttr if the
9687 /// function is a definition and there is an active value on CodeSegStack
9688 /// (from the current #pragma code-seg value).
9689 ///
9690 /// \param FD Function being declared.
9691 /// \param IsDefinition Whether it is a definition or just a declarartion.
9692 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
9693 ///          nullptr if no attribute should be added.
9694 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9695                                                        bool IsDefinition) {
9696   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9697     return A;
9698   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9699       CodeSegStack.CurrentValue)
9700     return SectionAttr::CreateImplicit(
9701         getASTContext(), CodeSegStack.CurrentValue->getString(),
9702         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9703         SectionAttr::Declspec_allocate);
9704   return nullptr;
9705 }
9706 
9707 /// Determines if we can perform a correct type check for \p D as a
9708 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
9709 /// best-effort check.
9710 ///
9711 /// \param NewD The new declaration.
9712 /// \param OldD The old declaration.
9713 /// \param NewT The portion of the type of the new declaration to check.
9714 /// \param OldT The portion of the type of the old declaration to check.
9715 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
9716                                           QualType NewT, QualType OldT) {
9717   if (!NewD->getLexicalDeclContext()->isDependentContext())
9718     return true;
9719 
9720   // For dependently-typed local extern declarations and friends, we can't
9721   // perform a correct type check in general until instantiation:
9722   //
9723   //   int f();
9724   //   template<typename T> void g() { T f(); }
9725   //
9726   // (valid if g() is only instantiated with T = int).
9727   if (NewT->isDependentType() &&
9728       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
9729     return false;
9730 
9731   // Similarly, if the previous declaration was a dependent local extern
9732   // declaration, we don't really know its type yet.
9733   if (OldT->isDependentType() && OldD->isLocalExternDecl())
9734     return false;
9735 
9736   return true;
9737 }
9738 
9739 /// Checks if the new declaration declared in dependent context must be
9740 /// put in the same redeclaration chain as the specified declaration.
9741 ///
9742 /// \param D Declaration that is checked.
9743 /// \param PrevDecl Previous declaration found with proper lookup method for the
9744 ///                 same declaration name.
9745 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9746 ///          belongs to.
9747 ///
9748 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9749   if (!D->getLexicalDeclContext()->isDependentContext())
9750     return true;
9751 
9752   // Don't chain dependent friend function definitions until instantiation, to
9753   // permit cases like
9754   //
9755   //   void func();
9756   //   template<typename T> class C1 { friend void func() {} };
9757   //   template<typename T> class C2 { friend void func() {} };
9758   //
9759   // ... which is valid if only one of C1 and C2 is ever instantiated.
9760   //
9761   // FIXME: This need only apply to function definitions. For now, we proxy
9762   // this by checking for a file-scope function. We do not want this to apply
9763   // to friend declarations nominating member functions, because that gets in
9764   // the way of access checks.
9765   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
9766     return false;
9767 
9768   auto *VD = dyn_cast<ValueDecl>(D);
9769   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
9770   return !VD || !PrevVD ||
9771          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
9772                                         PrevVD->getType());
9773 }
9774 
9775 /// Check the target attribute of the function for MultiVersion
9776 /// validity.
9777 ///
9778 /// Returns true if there was an error, false otherwise.
9779 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9780   const auto *TA = FD->getAttr<TargetAttr>();
9781   assert(TA && "MultiVersion Candidate requires a target attribute");
9782   ParsedTargetAttr ParseInfo = TA->parse();
9783   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9784   enum ErrType { Feature = 0, Architecture = 1 };
9785 
9786   if (!ParseInfo.Architecture.empty() &&
9787       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
9788     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9789         << Architecture << ParseInfo.Architecture;
9790     return true;
9791   }
9792 
9793   for (const auto &Feat : ParseInfo.Features) {
9794     auto BareFeat = StringRef{Feat}.substr(1);
9795     if (Feat[0] == '-') {
9796       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9797           << Feature << ("no-" + BareFeat).str();
9798       return true;
9799     }
9800 
9801     if (!TargetInfo.validateCpuSupports(BareFeat) ||
9802         !TargetInfo.isValidFeatureName(BareFeat)) {
9803       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9804           << Feature << BareFeat;
9805       return true;
9806     }
9807   }
9808   return false;
9809 }
9810 
9811 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD,
9812                                          MultiVersionKind MVType) {
9813   for (const Attr *A : FD->attrs()) {
9814     switch (A->getKind()) {
9815     case attr::CPUDispatch:
9816     case attr::CPUSpecific:
9817       if (MVType != MultiVersionKind::CPUDispatch &&
9818           MVType != MultiVersionKind::CPUSpecific)
9819         return true;
9820       break;
9821     case attr::Target:
9822       if (MVType != MultiVersionKind::Target)
9823         return true;
9824       break;
9825     default:
9826       return true;
9827     }
9828   }
9829   return false;
9830 }
9831 
9832 bool Sema::areMultiversionVariantFunctionsCompatible(
9833     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
9834     const PartialDiagnostic &NoProtoDiagID,
9835     const PartialDiagnosticAt &NoteCausedDiagIDAt,
9836     const PartialDiagnosticAt &NoSupportDiagIDAt,
9837     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
9838     bool ConstexprSupported, bool CLinkageMayDiffer) {
9839   enum DoesntSupport {
9840     FuncTemplates = 0,
9841     VirtFuncs = 1,
9842     DeducedReturn = 2,
9843     Constructors = 3,
9844     Destructors = 4,
9845     DeletedFuncs = 5,
9846     DefaultedFuncs = 6,
9847     ConstexprFuncs = 7,
9848     ConstevalFuncs = 8,
9849   };
9850   enum Different {
9851     CallingConv = 0,
9852     ReturnType = 1,
9853     ConstexprSpec = 2,
9854     InlineSpec = 3,
9855     StorageClass = 4,
9856     Linkage = 5,
9857   };
9858 
9859   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
9860       !OldFD->getType()->getAs<FunctionProtoType>()) {
9861     Diag(OldFD->getLocation(), NoProtoDiagID);
9862     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
9863     return true;
9864   }
9865 
9866   if (NoProtoDiagID.getDiagID() != 0 &&
9867       !NewFD->getType()->getAs<FunctionProtoType>())
9868     return Diag(NewFD->getLocation(), NoProtoDiagID);
9869 
9870   if (!TemplatesSupported &&
9871       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9872     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9873            << FuncTemplates;
9874 
9875   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
9876     if (NewCXXFD->isVirtual())
9877       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9878              << VirtFuncs;
9879 
9880     if (isa<CXXConstructorDecl>(NewCXXFD))
9881       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9882              << Constructors;
9883 
9884     if (isa<CXXDestructorDecl>(NewCXXFD))
9885       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9886              << Destructors;
9887   }
9888 
9889   if (NewFD->isDeleted())
9890     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9891            << DeletedFuncs;
9892 
9893   if (NewFD->isDefaulted())
9894     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9895            << DefaultedFuncs;
9896 
9897   if (!ConstexprSupported && NewFD->isConstexpr())
9898     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9899            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
9900 
9901   QualType NewQType = Context.getCanonicalType(NewFD->getType());
9902   const auto *NewType = cast<FunctionType>(NewQType);
9903   QualType NewReturnType = NewType->getReturnType();
9904 
9905   if (NewReturnType->isUndeducedType())
9906     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9907            << DeducedReturn;
9908 
9909   // Ensure the return type is identical.
9910   if (OldFD) {
9911     QualType OldQType = Context.getCanonicalType(OldFD->getType());
9912     const auto *OldType = cast<FunctionType>(OldQType);
9913     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
9914     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
9915 
9916     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
9917       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
9918 
9919     QualType OldReturnType = OldType->getReturnType();
9920 
9921     if (OldReturnType != NewReturnType)
9922       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
9923 
9924     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
9925       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
9926 
9927     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
9928       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
9929 
9930     if (OldFD->getStorageClass() != NewFD->getStorageClass())
9931       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass;
9932 
9933     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
9934       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
9935 
9936     if (CheckEquivalentExceptionSpec(
9937             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
9938             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
9939       return true;
9940   }
9941   return false;
9942 }
9943 
9944 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
9945                                              const FunctionDecl *NewFD,
9946                                              bool CausesMV,
9947                                              MultiVersionKind MVType) {
9948   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9949     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9950     if (OldFD)
9951       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9952     return true;
9953   }
9954 
9955   bool IsCPUSpecificCPUDispatchMVType =
9956       MVType == MultiVersionKind::CPUDispatch ||
9957       MVType == MultiVersionKind::CPUSpecific;
9958 
9959   // For now, disallow all other attributes.  These should be opt-in, but
9960   // an analysis of all of them is a future FIXME.
9961   if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) {
9962     S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
9963         << IsCPUSpecificCPUDispatchMVType;
9964     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9965     return true;
9966   }
9967 
9968   if (HasNonMultiVersionAttributes(NewFD, MVType))
9969     return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
9970            << IsCPUSpecificCPUDispatchMVType;
9971 
9972   // Only allow transition to MultiVersion if it hasn't been used.
9973   if (OldFD && CausesMV && OldFD->isUsed(false))
9974     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
9975 
9976   return S.areMultiversionVariantFunctionsCompatible(
9977       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
9978       PartialDiagnosticAt(NewFD->getLocation(),
9979                           S.PDiag(diag::note_multiversioning_caused_here)),
9980       PartialDiagnosticAt(NewFD->getLocation(),
9981                           S.PDiag(diag::err_multiversion_doesnt_support)
9982                               << IsCPUSpecificCPUDispatchMVType),
9983       PartialDiagnosticAt(NewFD->getLocation(),
9984                           S.PDiag(diag::err_multiversion_diff)),
9985       /*TemplatesSupported=*/false,
9986       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
9987       /*CLinkageMayDiffer=*/false);
9988 }
9989 
9990 /// Check the validity of a multiversion function declaration that is the
9991 /// first of its kind. Also sets the multiversion'ness' of the function itself.
9992 ///
9993 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9994 ///
9995 /// Returns true if there was an error, false otherwise.
9996 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
9997                                            MultiVersionKind MVType,
9998                                            const TargetAttr *TA) {
9999   assert(MVType != MultiVersionKind::None &&
10000          "Function lacks multiversion attribute");
10001 
10002   // Target only causes MV if it is default, otherwise this is a normal
10003   // function.
10004   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
10005     return false;
10006 
10007   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10008     FD->setInvalidDecl();
10009     return true;
10010   }
10011 
10012   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
10013     FD->setInvalidDecl();
10014     return true;
10015   }
10016 
10017   FD->setIsMultiVersion();
10018   return false;
10019 }
10020 
10021 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10022   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10023     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10024       return true;
10025   }
10026 
10027   return false;
10028 }
10029 
10030 static bool CheckTargetCausesMultiVersioning(
10031     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10032     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10033     LookupResult &Previous) {
10034   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10035   ParsedTargetAttr NewParsed = NewTA->parse();
10036   // Sort order doesn't matter, it just needs to be consistent.
10037   llvm::sort(NewParsed.Features);
10038 
10039   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10040   // to change, this is a simple redeclaration.
10041   if (!NewTA->isDefaultVersion() &&
10042       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10043     return false;
10044 
10045   // Otherwise, this decl causes MultiVersioning.
10046   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10047     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10048     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10049     NewFD->setInvalidDecl();
10050     return true;
10051   }
10052 
10053   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10054                                        MultiVersionKind::Target)) {
10055     NewFD->setInvalidDecl();
10056     return true;
10057   }
10058 
10059   if (CheckMultiVersionValue(S, NewFD)) {
10060     NewFD->setInvalidDecl();
10061     return true;
10062   }
10063 
10064   // If this is 'default', permit the forward declaration.
10065   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10066     Redeclaration = true;
10067     OldDecl = OldFD;
10068     OldFD->setIsMultiVersion();
10069     NewFD->setIsMultiVersion();
10070     return false;
10071   }
10072 
10073   if (CheckMultiVersionValue(S, OldFD)) {
10074     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10075     NewFD->setInvalidDecl();
10076     return true;
10077   }
10078 
10079   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10080 
10081   if (OldParsed == NewParsed) {
10082     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10083     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10084     NewFD->setInvalidDecl();
10085     return true;
10086   }
10087 
10088   for (const auto *FD : OldFD->redecls()) {
10089     const auto *CurTA = FD->getAttr<TargetAttr>();
10090     // We allow forward declarations before ANY multiversioning attributes, but
10091     // nothing after the fact.
10092     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10093         (!CurTA || CurTA->isInherited())) {
10094       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10095           << 0;
10096       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10097       NewFD->setInvalidDecl();
10098       return true;
10099     }
10100   }
10101 
10102   OldFD->setIsMultiVersion();
10103   NewFD->setIsMultiVersion();
10104   Redeclaration = false;
10105   MergeTypeWithPrevious = false;
10106   OldDecl = nullptr;
10107   Previous.clear();
10108   return false;
10109 }
10110 
10111 /// Check the validity of a new function declaration being added to an existing
10112 /// multiversioned declaration collection.
10113 static bool CheckMultiVersionAdditionalDecl(
10114     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10115     MultiVersionKind NewMVType, const TargetAttr *NewTA,
10116     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10117     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10118     LookupResult &Previous) {
10119 
10120   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10121   // Disallow mixing of multiversioning types.
10122   if ((OldMVType == MultiVersionKind::Target &&
10123        NewMVType != MultiVersionKind::Target) ||
10124       (NewMVType == MultiVersionKind::Target &&
10125        OldMVType != MultiVersionKind::Target)) {
10126     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10127     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10128     NewFD->setInvalidDecl();
10129     return true;
10130   }
10131 
10132   ParsedTargetAttr NewParsed;
10133   if (NewTA) {
10134     NewParsed = NewTA->parse();
10135     llvm::sort(NewParsed.Features);
10136   }
10137 
10138   bool UseMemberUsingDeclRules =
10139       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10140 
10141   // Next, check ALL non-overloads to see if this is a redeclaration of a
10142   // previous member of the MultiVersion set.
10143   for (NamedDecl *ND : Previous) {
10144     FunctionDecl *CurFD = ND->getAsFunction();
10145     if (!CurFD)
10146       continue;
10147     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10148       continue;
10149 
10150     if (NewMVType == MultiVersionKind::Target) {
10151       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10152       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10153         NewFD->setIsMultiVersion();
10154         Redeclaration = true;
10155         OldDecl = ND;
10156         return false;
10157       }
10158 
10159       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10160       if (CurParsed == NewParsed) {
10161         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10162         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10163         NewFD->setInvalidDecl();
10164         return true;
10165       }
10166     } else {
10167       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10168       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10169       // Handle CPUDispatch/CPUSpecific versions.
10170       // Only 1 CPUDispatch function is allowed, this will make it go through
10171       // the redeclaration errors.
10172       if (NewMVType == MultiVersionKind::CPUDispatch &&
10173           CurFD->hasAttr<CPUDispatchAttr>()) {
10174         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10175             std::equal(
10176                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10177                 NewCPUDisp->cpus_begin(),
10178                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10179                   return Cur->getName() == New->getName();
10180                 })) {
10181           NewFD->setIsMultiVersion();
10182           Redeclaration = true;
10183           OldDecl = ND;
10184           return false;
10185         }
10186 
10187         // If the declarations don't match, this is an error condition.
10188         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10189         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10190         NewFD->setInvalidDecl();
10191         return true;
10192       }
10193       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10194 
10195         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10196             std::equal(
10197                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10198                 NewCPUSpec->cpus_begin(),
10199                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10200                   return Cur->getName() == New->getName();
10201                 })) {
10202           NewFD->setIsMultiVersion();
10203           Redeclaration = true;
10204           OldDecl = ND;
10205           return false;
10206         }
10207 
10208         // Only 1 version of CPUSpecific is allowed for each CPU.
10209         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10210           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10211             if (CurII == NewII) {
10212               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10213                   << NewII;
10214               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10215               NewFD->setInvalidDecl();
10216               return true;
10217             }
10218           }
10219         }
10220       }
10221       // If the two decls aren't the same MVType, there is no possible error
10222       // condition.
10223     }
10224   }
10225 
10226   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10227   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10228   // handled in the attribute adding step.
10229   if (NewMVType == MultiVersionKind::Target &&
10230       CheckMultiVersionValue(S, NewFD)) {
10231     NewFD->setInvalidDecl();
10232     return true;
10233   }
10234 
10235   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10236                                        !OldFD->isMultiVersion(), NewMVType)) {
10237     NewFD->setInvalidDecl();
10238     return true;
10239   }
10240 
10241   // Permit forward declarations in the case where these two are compatible.
10242   if (!OldFD->isMultiVersion()) {
10243     OldFD->setIsMultiVersion();
10244     NewFD->setIsMultiVersion();
10245     Redeclaration = true;
10246     OldDecl = OldFD;
10247     return false;
10248   }
10249 
10250   NewFD->setIsMultiVersion();
10251   Redeclaration = false;
10252   MergeTypeWithPrevious = false;
10253   OldDecl = nullptr;
10254   Previous.clear();
10255   return false;
10256 }
10257 
10258 
10259 /// Check the validity of a mulitversion function declaration.
10260 /// Also sets the multiversion'ness' of the function itself.
10261 ///
10262 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10263 ///
10264 /// Returns true if there was an error, false otherwise.
10265 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10266                                       bool &Redeclaration, NamedDecl *&OldDecl,
10267                                       bool &MergeTypeWithPrevious,
10268                                       LookupResult &Previous) {
10269   const auto *NewTA = NewFD->getAttr<TargetAttr>();
10270   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10271   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10272 
10273   // Mixing Multiversioning types is prohibited.
10274   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
10275       (NewCPUDisp && NewCPUSpec)) {
10276     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10277     NewFD->setInvalidDecl();
10278     return true;
10279   }
10280 
10281   MultiVersionKind  MVType = NewFD->getMultiVersionKind();
10282 
10283   // Main isn't allowed to become a multiversion function, however it IS
10284   // permitted to have 'main' be marked with the 'target' optimization hint.
10285   if (NewFD->isMain()) {
10286     if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10287         MVType == MultiVersionKind::CPUDispatch ||
10288         MVType == MultiVersionKind::CPUSpecific) {
10289       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10290       NewFD->setInvalidDecl();
10291       return true;
10292     }
10293     return false;
10294   }
10295 
10296   if (!OldDecl || !OldDecl->getAsFunction() ||
10297       OldDecl->getDeclContext()->getRedeclContext() !=
10298           NewFD->getDeclContext()->getRedeclContext()) {
10299     // If there's no previous declaration, AND this isn't attempting to cause
10300     // multiversioning, this isn't an error condition.
10301     if (MVType == MultiVersionKind::None)
10302       return false;
10303     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10304   }
10305 
10306   FunctionDecl *OldFD = OldDecl->getAsFunction();
10307 
10308   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10309     return false;
10310 
10311   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10312     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10313         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10314     NewFD->setInvalidDecl();
10315     return true;
10316   }
10317 
10318   // Handle the target potentially causes multiversioning case.
10319   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10320     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10321                                             Redeclaration, OldDecl,
10322                                             MergeTypeWithPrevious, Previous);
10323 
10324   // At this point, we have a multiversion function decl (in OldFD) AND an
10325   // appropriate attribute in the current function decl.  Resolve that these are
10326   // still compatible with previous declarations.
10327   return CheckMultiVersionAdditionalDecl(
10328       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10329       OldDecl, MergeTypeWithPrevious, Previous);
10330 }
10331 
10332 /// Perform semantic checking of a new function declaration.
10333 ///
10334 /// Performs semantic analysis of the new function declaration
10335 /// NewFD. This routine performs all semantic checking that does not
10336 /// require the actual declarator involved in the declaration, and is
10337 /// used both for the declaration of functions as they are parsed
10338 /// (called via ActOnDeclarator) and for the declaration of functions
10339 /// that have been instantiated via C++ template instantiation (called
10340 /// via InstantiateDecl).
10341 ///
10342 /// \param IsMemberSpecialization whether this new function declaration is
10343 /// a member specialization (that replaces any definition provided by the
10344 /// previous declaration).
10345 ///
10346 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10347 ///
10348 /// \returns true if the function declaration is a redeclaration.
10349 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10350                                     LookupResult &Previous,
10351                                     bool IsMemberSpecialization) {
10352   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10353          "Variably modified return types are not handled here");
10354 
10355   // Determine whether the type of this function should be merged with
10356   // a previous visible declaration. This never happens for functions in C++,
10357   // and always happens in C if the previous declaration was visible.
10358   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10359                                !Previous.isShadowed();
10360 
10361   bool Redeclaration = false;
10362   NamedDecl *OldDecl = nullptr;
10363   bool MayNeedOverloadableChecks = false;
10364 
10365   // Merge or overload the declaration with an existing declaration of
10366   // the same name, if appropriate.
10367   if (!Previous.empty()) {
10368     // Determine whether NewFD is an overload of PrevDecl or
10369     // a declaration that requires merging. If it's an overload,
10370     // there's no more work to do here; we'll just add the new
10371     // function to the scope.
10372     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10373       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10374       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10375         Redeclaration = true;
10376         OldDecl = Candidate;
10377       }
10378     } else {
10379       MayNeedOverloadableChecks = true;
10380       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10381                             /*NewIsUsingDecl*/ false)) {
10382       case Ovl_Match:
10383         Redeclaration = true;
10384         break;
10385 
10386       case Ovl_NonFunction:
10387         Redeclaration = true;
10388         break;
10389 
10390       case Ovl_Overload:
10391         Redeclaration = false;
10392         break;
10393       }
10394     }
10395   }
10396 
10397   // Check for a previous extern "C" declaration with this name.
10398   if (!Redeclaration &&
10399       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10400     if (!Previous.empty()) {
10401       // This is an extern "C" declaration with the same name as a previous
10402       // declaration, and thus redeclares that entity...
10403       Redeclaration = true;
10404       OldDecl = Previous.getFoundDecl();
10405       MergeTypeWithPrevious = false;
10406 
10407       // ... except in the presence of __attribute__((overloadable)).
10408       if (OldDecl->hasAttr<OverloadableAttr>() ||
10409           NewFD->hasAttr<OverloadableAttr>()) {
10410         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10411           MayNeedOverloadableChecks = true;
10412           Redeclaration = false;
10413           OldDecl = nullptr;
10414         }
10415       }
10416     }
10417   }
10418 
10419   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10420                                 MergeTypeWithPrevious, Previous))
10421     return Redeclaration;
10422 
10423   // C++11 [dcl.constexpr]p8:
10424   //   A constexpr specifier for a non-static member function that is not
10425   //   a constructor declares that member function to be const.
10426   //
10427   // This needs to be delayed until we know whether this is an out-of-line
10428   // definition of a static member function.
10429   //
10430   // This rule is not present in C++1y, so we produce a backwards
10431   // compatibility warning whenever it happens in C++11.
10432   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10433   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10434       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10435       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10436     CXXMethodDecl *OldMD = nullptr;
10437     if (OldDecl)
10438       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10439     if (!OldMD || !OldMD->isStatic()) {
10440       const FunctionProtoType *FPT =
10441         MD->getType()->castAs<FunctionProtoType>();
10442       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10443       EPI.TypeQuals.addConst();
10444       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10445                                           FPT->getParamTypes(), EPI));
10446 
10447       // Warn that we did this, if we're not performing template instantiation.
10448       // In that case, we'll have warned already when the template was defined.
10449       if (!inTemplateInstantiation()) {
10450         SourceLocation AddConstLoc;
10451         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10452                 .IgnoreParens().getAs<FunctionTypeLoc>())
10453           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10454 
10455         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10456           << FixItHint::CreateInsertion(AddConstLoc, " const");
10457       }
10458     }
10459   }
10460 
10461   if (Redeclaration) {
10462     // NewFD and OldDecl represent declarations that need to be
10463     // merged.
10464     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10465       NewFD->setInvalidDecl();
10466       return Redeclaration;
10467     }
10468 
10469     Previous.clear();
10470     Previous.addDecl(OldDecl);
10471 
10472     if (FunctionTemplateDecl *OldTemplateDecl =
10473             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10474       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10475       FunctionTemplateDecl *NewTemplateDecl
10476         = NewFD->getDescribedFunctionTemplate();
10477       assert(NewTemplateDecl && "Template/non-template mismatch");
10478 
10479       // The call to MergeFunctionDecl above may have created some state in
10480       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10481       // can add it as a redeclaration.
10482       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10483 
10484       NewFD->setPreviousDeclaration(OldFD);
10485       adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10486       if (NewFD->isCXXClassMember()) {
10487         NewFD->setAccess(OldTemplateDecl->getAccess());
10488         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10489       }
10490 
10491       // If this is an explicit specialization of a member that is a function
10492       // template, mark it as a member specialization.
10493       if (IsMemberSpecialization &&
10494           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10495         NewTemplateDecl->setMemberSpecialization();
10496         assert(OldTemplateDecl->isMemberSpecialization());
10497         // Explicit specializations of a member template do not inherit deleted
10498         // status from the parent member template that they are specializing.
10499         if (OldFD->isDeleted()) {
10500           // FIXME: This assert will not hold in the presence of modules.
10501           assert(OldFD->getCanonicalDecl() == OldFD);
10502           // FIXME: We need an update record for this AST mutation.
10503           OldFD->setDeletedAsWritten(false);
10504         }
10505       }
10506 
10507     } else {
10508       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10509         auto *OldFD = cast<FunctionDecl>(OldDecl);
10510         // This needs to happen first so that 'inline' propagates.
10511         NewFD->setPreviousDeclaration(OldFD);
10512         adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10513         if (NewFD->isCXXClassMember())
10514           NewFD->setAccess(OldFD->getAccess());
10515       }
10516     }
10517   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10518              !NewFD->getAttr<OverloadableAttr>()) {
10519     assert((Previous.empty() ||
10520             llvm::any_of(Previous,
10521                          [](const NamedDecl *ND) {
10522                            return ND->hasAttr<OverloadableAttr>();
10523                          })) &&
10524            "Non-redecls shouldn't happen without overloadable present");
10525 
10526     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10527       const auto *FD = dyn_cast<FunctionDecl>(ND);
10528       return FD && !FD->hasAttr<OverloadableAttr>();
10529     });
10530 
10531     if (OtherUnmarkedIter != Previous.end()) {
10532       Diag(NewFD->getLocation(),
10533            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10534       Diag((*OtherUnmarkedIter)->getLocation(),
10535            diag::note_attribute_overloadable_prev_overload)
10536           << false;
10537 
10538       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10539     }
10540   }
10541 
10542   // Semantic checking for this function declaration (in isolation).
10543 
10544   if (getLangOpts().CPlusPlus) {
10545     // C++-specific checks.
10546     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10547       CheckConstructor(Constructor);
10548     } else if (CXXDestructorDecl *Destructor =
10549                 dyn_cast<CXXDestructorDecl>(NewFD)) {
10550       CXXRecordDecl *Record = Destructor->getParent();
10551       QualType ClassType = Context.getTypeDeclType(Record);
10552 
10553       // FIXME: Shouldn't we be able to perform this check even when the class
10554       // type is dependent? Both gcc and edg can handle that.
10555       if (!ClassType->isDependentType()) {
10556         DeclarationName Name
10557           = Context.DeclarationNames.getCXXDestructorName(
10558                                         Context.getCanonicalType(ClassType));
10559         if (NewFD->getDeclName() != Name) {
10560           Diag(NewFD->getLocation(), diag::err_destructor_name);
10561           NewFD->setInvalidDecl();
10562           return Redeclaration;
10563         }
10564       }
10565     } else if (CXXConversionDecl *Conversion
10566                = dyn_cast<CXXConversionDecl>(NewFD)) {
10567       ActOnConversionDeclarator(Conversion);
10568     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10569       if (auto *TD = Guide->getDescribedFunctionTemplate())
10570         CheckDeductionGuideTemplate(TD);
10571 
10572       // A deduction guide is not on the list of entities that can be
10573       // explicitly specialized.
10574       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10575         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10576             << /*explicit specialization*/ 1;
10577     }
10578 
10579     // Find any virtual functions that this function overrides.
10580     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10581       if (!Method->isFunctionTemplateSpecialization() &&
10582           !Method->getDescribedFunctionTemplate() &&
10583           Method->isCanonicalDecl()) {
10584         if (AddOverriddenMethods(Method->getParent(), Method)) {
10585           // If the function was marked as "static", we have a problem.
10586           if (NewFD->getStorageClass() == SC_Static) {
10587             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
10588           }
10589         }
10590       }
10591       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
10592         // C++2a [class.virtual]p6
10593         // A virtual method shall not have a requires-clause.
10594         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
10595              diag::err_constrained_virtual_method);
10596 
10597       if (Method->isStatic())
10598         checkThisInStaticMemberFunctionType(Method);
10599     }
10600 
10601     // Extra checking for C++ overloaded operators (C++ [over.oper]).
10602     if (NewFD->isOverloadedOperator() &&
10603         CheckOverloadedOperatorDeclaration(NewFD)) {
10604       NewFD->setInvalidDecl();
10605       return Redeclaration;
10606     }
10607 
10608     // Extra checking for C++0x literal operators (C++0x [over.literal]).
10609     if (NewFD->getLiteralIdentifier() &&
10610         CheckLiteralOperatorDeclaration(NewFD)) {
10611       NewFD->setInvalidDecl();
10612       return Redeclaration;
10613     }
10614 
10615     // In C++, check default arguments now that we have merged decls. Unless
10616     // the lexical context is the class, because in this case this is done
10617     // during delayed parsing anyway.
10618     if (!CurContext->isRecord())
10619       CheckCXXDefaultArguments(NewFD);
10620 
10621     // If this function declares a builtin function, check the type of this
10622     // declaration against the expected type for the builtin.
10623     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10624       ASTContext::GetBuiltinTypeError Error;
10625       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
10626       QualType T = Context.GetBuiltinType(BuiltinID, Error);
10627       // If the type of the builtin differs only in its exception
10628       // specification, that's OK.
10629       // FIXME: If the types do differ in this way, it would be better to
10630       // retain the 'noexcept' form of the type.
10631       if (!T.isNull() &&
10632           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10633                                                             NewFD->getType()))
10634         // The type of this function differs from the type of the builtin,
10635         // so forget about the builtin entirely.
10636         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10637     }
10638 
10639     // If this function is declared as being extern "C", then check to see if
10640     // the function returns a UDT (class, struct, or union type) that is not C
10641     // compatible, and if it does, warn the user.
10642     // But, issue any diagnostic on the first declaration only.
10643     if (Previous.empty() && NewFD->isExternC()) {
10644       QualType R = NewFD->getReturnType();
10645       if (R->isIncompleteType() && !R->isVoidType())
10646         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10647             << NewFD << R;
10648       else if (!R.isPODType(Context) && !R->isVoidType() &&
10649                !R->isObjCObjectPointerType())
10650         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10651     }
10652 
10653     // C++1z [dcl.fct]p6:
10654     //   [...] whether the function has a non-throwing exception-specification
10655     //   [is] part of the function type
10656     //
10657     // This results in an ABI break between C++14 and C++17 for functions whose
10658     // declared type includes an exception-specification in a parameter or
10659     // return type. (Exception specifications on the function itself are OK in
10660     // most cases, and exception specifications are not permitted in most other
10661     // contexts where they could make it into a mangling.)
10662     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10663       auto HasNoexcept = [&](QualType T) -> bool {
10664         // Strip off declarator chunks that could be between us and a function
10665         // type. We don't need to look far, exception specifications are very
10666         // restricted prior to C++17.
10667         if (auto *RT = T->getAs<ReferenceType>())
10668           T = RT->getPointeeType();
10669         else if (T->isAnyPointerType())
10670           T = T->getPointeeType();
10671         else if (auto *MPT = T->getAs<MemberPointerType>())
10672           T = MPT->getPointeeType();
10673         if (auto *FPT = T->getAs<FunctionProtoType>())
10674           if (FPT->isNothrow())
10675             return true;
10676         return false;
10677       };
10678 
10679       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10680       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10681       for (QualType T : FPT->param_types())
10682         AnyNoexcept |= HasNoexcept(T);
10683       if (AnyNoexcept)
10684         Diag(NewFD->getLocation(),
10685              diag::warn_cxx17_compat_exception_spec_in_signature)
10686             << NewFD;
10687     }
10688 
10689     if (!Redeclaration && LangOpts.CUDA)
10690       checkCUDATargetOverload(NewFD, Previous);
10691   }
10692   return Redeclaration;
10693 }
10694 
10695 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10696   // C++11 [basic.start.main]p3:
10697   //   A program that [...] declares main to be inline, static or
10698   //   constexpr is ill-formed.
10699   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
10700   //   appear in a declaration of main.
10701   // static main is not an error under C99, but we should warn about it.
10702   // We accept _Noreturn main as an extension.
10703   if (FD->getStorageClass() == SC_Static)
10704     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10705          ? diag::err_static_main : diag::warn_static_main)
10706       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10707   if (FD->isInlineSpecified())
10708     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10709       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10710   if (DS.isNoreturnSpecified()) {
10711     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10712     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10713     Diag(NoreturnLoc, diag::ext_noreturn_main);
10714     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10715       << FixItHint::CreateRemoval(NoreturnRange);
10716   }
10717   if (FD->isConstexpr()) {
10718     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10719         << FD->isConsteval()
10720         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10721     FD->setConstexprKind(CSK_unspecified);
10722   }
10723 
10724   if (getLangOpts().OpenCL) {
10725     Diag(FD->getLocation(), diag::err_opencl_no_main)
10726         << FD->hasAttr<OpenCLKernelAttr>();
10727     FD->setInvalidDecl();
10728     return;
10729   }
10730 
10731   QualType T = FD->getType();
10732   assert(T->isFunctionType() && "function decl is not of function type");
10733   const FunctionType* FT = T->castAs<FunctionType>();
10734 
10735   // Set default calling convention for main()
10736   if (FT->getCallConv() != CC_C) {
10737     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10738     FD->setType(QualType(FT, 0));
10739     T = Context.getCanonicalType(FD->getType());
10740   }
10741 
10742   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10743     // In C with GNU extensions we allow main() to have non-integer return
10744     // type, but we should warn about the extension, and we disable the
10745     // implicit-return-zero rule.
10746 
10747     // GCC in C mode accepts qualified 'int'.
10748     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
10749       FD->setHasImplicitReturnZero(true);
10750     else {
10751       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
10752       SourceRange RTRange = FD->getReturnTypeSourceRange();
10753       if (RTRange.isValid())
10754         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
10755             << FixItHint::CreateReplacement(RTRange, "int");
10756     }
10757   } else {
10758     // In C and C++, main magically returns 0 if you fall off the end;
10759     // set the flag which tells us that.
10760     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
10761 
10762     // All the standards say that main() should return 'int'.
10763     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
10764       FD->setHasImplicitReturnZero(true);
10765     else {
10766       // Otherwise, this is just a flat-out error.
10767       SourceRange RTRange = FD->getReturnTypeSourceRange();
10768       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
10769           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
10770                                 : FixItHint());
10771       FD->setInvalidDecl(true);
10772     }
10773   }
10774 
10775   // Treat protoless main() as nullary.
10776   if (isa<FunctionNoProtoType>(FT)) return;
10777 
10778   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
10779   unsigned nparams = FTP->getNumParams();
10780   assert(FD->getNumParams() == nparams);
10781 
10782   bool HasExtraParameters = (nparams > 3);
10783 
10784   if (FTP->isVariadic()) {
10785     Diag(FD->getLocation(), diag::ext_variadic_main);
10786     // FIXME: if we had information about the location of the ellipsis, we
10787     // could add a FixIt hint to remove it as a parameter.
10788   }
10789 
10790   // Darwin passes an undocumented fourth argument of type char**.  If
10791   // other platforms start sprouting these, the logic below will start
10792   // getting shifty.
10793   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
10794     HasExtraParameters = false;
10795 
10796   if (HasExtraParameters) {
10797     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
10798     FD->setInvalidDecl(true);
10799     nparams = 3;
10800   }
10801 
10802   // FIXME: a lot of the following diagnostics would be improved
10803   // if we had some location information about types.
10804 
10805   QualType CharPP =
10806     Context.getPointerType(Context.getPointerType(Context.CharTy));
10807   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
10808 
10809   for (unsigned i = 0; i < nparams; ++i) {
10810     QualType AT = FTP->getParamType(i);
10811 
10812     bool mismatch = true;
10813 
10814     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
10815       mismatch = false;
10816     else if (Expected[i] == CharPP) {
10817       // As an extension, the following forms are okay:
10818       //   char const **
10819       //   char const * const *
10820       //   char * const *
10821 
10822       QualifierCollector qs;
10823       const PointerType* PT;
10824       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
10825           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
10826           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
10827                               Context.CharTy)) {
10828         qs.removeConst();
10829         mismatch = !qs.empty();
10830       }
10831     }
10832 
10833     if (mismatch) {
10834       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
10835       // TODO: suggest replacing given type with expected type
10836       FD->setInvalidDecl(true);
10837     }
10838   }
10839 
10840   if (nparams == 1 && !FD->isInvalidDecl()) {
10841     Diag(FD->getLocation(), diag::warn_main_one_arg);
10842   }
10843 
10844   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10845     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10846     FD->setInvalidDecl();
10847   }
10848 }
10849 
10850 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
10851   QualType T = FD->getType();
10852   assert(T->isFunctionType() && "function decl is not of function type");
10853   const FunctionType *FT = T->castAs<FunctionType>();
10854 
10855   // Set an implicit return of 'zero' if the function can return some integral,
10856   // enumeration, pointer or nullptr type.
10857   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
10858       FT->getReturnType()->isAnyPointerType() ||
10859       FT->getReturnType()->isNullPtrType())
10860     // DllMain is exempt because a return value of zero means it failed.
10861     if (FD->getName() != "DllMain")
10862       FD->setHasImplicitReturnZero(true);
10863 
10864   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10865     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10866     FD->setInvalidDecl();
10867   }
10868 }
10869 
10870 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
10871   // FIXME: Need strict checking.  In C89, we need to check for
10872   // any assignment, increment, decrement, function-calls, or
10873   // commas outside of a sizeof.  In C99, it's the same list,
10874   // except that the aforementioned are allowed in unevaluated
10875   // expressions.  Everything else falls under the
10876   // "may accept other forms of constant expressions" exception.
10877   // (We never end up here for C++, so the constant expression
10878   // rules there don't matter.)
10879   const Expr *Culprit;
10880   if (Init->isConstantInitializer(Context, false, &Culprit))
10881     return false;
10882   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
10883     << Culprit->getSourceRange();
10884   return true;
10885 }
10886 
10887 namespace {
10888   // Visits an initialization expression to see if OrigDecl is evaluated in
10889   // its own initialization and throws a warning if it does.
10890   class SelfReferenceChecker
10891       : public EvaluatedExprVisitor<SelfReferenceChecker> {
10892     Sema &S;
10893     Decl *OrigDecl;
10894     bool isRecordType;
10895     bool isPODType;
10896     bool isReferenceType;
10897 
10898     bool isInitList;
10899     llvm::SmallVector<unsigned, 4> InitFieldIndex;
10900 
10901   public:
10902     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
10903 
10904     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
10905                                                     S(S), OrigDecl(OrigDecl) {
10906       isPODType = false;
10907       isRecordType = false;
10908       isReferenceType = false;
10909       isInitList = false;
10910       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
10911         isPODType = VD->getType().isPODType(S.Context);
10912         isRecordType = VD->getType()->isRecordType();
10913         isReferenceType = VD->getType()->isReferenceType();
10914       }
10915     }
10916 
10917     // For most expressions, just call the visitor.  For initializer lists,
10918     // track the index of the field being initialized since fields are
10919     // initialized in order allowing use of previously initialized fields.
10920     void CheckExpr(Expr *E) {
10921       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
10922       if (!InitList) {
10923         Visit(E);
10924         return;
10925       }
10926 
10927       // Track and increment the index here.
10928       isInitList = true;
10929       InitFieldIndex.push_back(0);
10930       for (auto Child : InitList->children()) {
10931         CheckExpr(cast<Expr>(Child));
10932         ++InitFieldIndex.back();
10933       }
10934       InitFieldIndex.pop_back();
10935     }
10936 
10937     // Returns true if MemberExpr is checked and no further checking is needed.
10938     // Returns false if additional checking is required.
10939     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
10940       llvm::SmallVector<FieldDecl*, 4> Fields;
10941       Expr *Base = E;
10942       bool ReferenceField = false;
10943 
10944       // Get the field members used.
10945       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10946         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
10947         if (!FD)
10948           return false;
10949         Fields.push_back(FD);
10950         if (FD->getType()->isReferenceType())
10951           ReferenceField = true;
10952         Base = ME->getBase()->IgnoreParenImpCasts();
10953       }
10954 
10955       // Keep checking only if the base Decl is the same.
10956       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
10957       if (!DRE || DRE->getDecl() != OrigDecl)
10958         return false;
10959 
10960       // A reference field can be bound to an unininitialized field.
10961       if (CheckReference && !ReferenceField)
10962         return true;
10963 
10964       // Convert FieldDecls to their index number.
10965       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
10966       for (const FieldDecl *I : llvm::reverse(Fields))
10967         UsedFieldIndex.push_back(I->getFieldIndex());
10968 
10969       // See if a warning is needed by checking the first difference in index
10970       // numbers.  If field being used has index less than the field being
10971       // initialized, then the use is safe.
10972       for (auto UsedIter = UsedFieldIndex.begin(),
10973                 UsedEnd = UsedFieldIndex.end(),
10974                 OrigIter = InitFieldIndex.begin(),
10975                 OrigEnd = InitFieldIndex.end();
10976            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
10977         if (*UsedIter < *OrigIter)
10978           return true;
10979         if (*UsedIter > *OrigIter)
10980           break;
10981       }
10982 
10983       // TODO: Add a different warning which will print the field names.
10984       HandleDeclRefExpr(DRE);
10985       return true;
10986     }
10987 
10988     // For most expressions, the cast is directly above the DeclRefExpr.
10989     // For conditional operators, the cast can be outside the conditional
10990     // operator if both expressions are DeclRefExpr's.
10991     void HandleValue(Expr *E) {
10992       E = E->IgnoreParens();
10993       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
10994         HandleDeclRefExpr(DRE);
10995         return;
10996       }
10997 
10998       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
10999         Visit(CO->getCond());
11000         HandleValue(CO->getTrueExpr());
11001         HandleValue(CO->getFalseExpr());
11002         return;
11003       }
11004 
11005       if (BinaryConditionalOperator *BCO =
11006               dyn_cast<BinaryConditionalOperator>(E)) {
11007         Visit(BCO->getCond());
11008         HandleValue(BCO->getFalseExpr());
11009         return;
11010       }
11011 
11012       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11013         HandleValue(OVE->getSourceExpr());
11014         return;
11015       }
11016 
11017       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11018         if (BO->getOpcode() == BO_Comma) {
11019           Visit(BO->getLHS());
11020           HandleValue(BO->getRHS());
11021           return;
11022         }
11023       }
11024 
11025       if (isa<MemberExpr>(E)) {
11026         if (isInitList) {
11027           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11028                                       false /*CheckReference*/))
11029             return;
11030         }
11031 
11032         Expr *Base = E->IgnoreParenImpCasts();
11033         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11034           // Check for static member variables and don't warn on them.
11035           if (!isa<FieldDecl>(ME->getMemberDecl()))
11036             return;
11037           Base = ME->getBase()->IgnoreParenImpCasts();
11038         }
11039         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11040           HandleDeclRefExpr(DRE);
11041         return;
11042       }
11043 
11044       Visit(E);
11045     }
11046 
11047     // Reference types not handled in HandleValue are handled here since all
11048     // uses of references are bad, not just r-value uses.
11049     void VisitDeclRefExpr(DeclRefExpr *E) {
11050       if (isReferenceType)
11051         HandleDeclRefExpr(E);
11052     }
11053 
11054     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11055       if (E->getCastKind() == CK_LValueToRValue) {
11056         HandleValue(E->getSubExpr());
11057         return;
11058       }
11059 
11060       Inherited::VisitImplicitCastExpr(E);
11061     }
11062 
11063     void VisitMemberExpr(MemberExpr *E) {
11064       if (isInitList) {
11065         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11066           return;
11067       }
11068 
11069       // Don't warn on arrays since they can be treated as pointers.
11070       if (E->getType()->canDecayToPointerType()) return;
11071 
11072       // Warn when a non-static method call is followed by non-static member
11073       // field accesses, which is followed by a DeclRefExpr.
11074       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11075       bool Warn = (MD && !MD->isStatic());
11076       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11077       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11078         if (!isa<FieldDecl>(ME->getMemberDecl()))
11079           Warn = false;
11080         Base = ME->getBase()->IgnoreParenImpCasts();
11081       }
11082 
11083       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11084         if (Warn)
11085           HandleDeclRefExpr(DRE);
11086         return;
11087       }
11088 
11089       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11090       // Visit that expression.
11091       Visit(Base);
11092     }
11093 
11094     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11095       Expr *Callee = E->getCallee();
11096 
11097       if (isa<UnresolvedLookupExpr>(Callee))
11098         return Inherited::VisitCXXOperatorCallExpr(E);
11099 
11100       Visit(Callee);
11101       for (auto Arg: E->arguments())
11102         HandleValue(Arg->IgnoreParenImpCasts());
11103     }
11104 
11105     void VisitUnaryOperator(UnaryOperator *E) {
11106       // For POD record types, addresses of its own members are well-defined.
11107       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11108           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11109         if (!isPODType)
11110           HandleValue(E->getSubExpr());
11111         return;
11112       }
11113 
11114       if (E->isIncrementDecrementOp()) {
11115         HandleValue(E->getSubExpr());
11116         return;
11117       }
11118 
11119       Inherited::VisitUnaryOperator(E);
11120     }
11121 
11122     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11123 
11124     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11125       if (E->getConstructor()->isCopyConstructor()) {
11126         Expr *ArgExpr = E->getArg(0);
11127         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11128           if (ILE->getNumInits() == 1)
11129             ArgExpr = ILE->getInit(0);
11130         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11131           if (ICE->getCastKind() == CK_NoOp)
11132             ArgExpr = ICE->getSubExpr();
11133         HandleValue(ArgExpr);
11134         return;
11135       }
11136       Inherited::VisitCXXConstructExpr(E);
11137     }
11138 
11139     void VisitCallExpr(CallExpr *E) {
11140       // Treat std::move as a use.
11141       if (E->isCallToStdMove()) {
11142         HandleValue(E->getArg(0));
11143         return;
11144       }
11145 
11146       Inherited::VisitCallExpr(E);
11147     }
11148 
11149     void VisitBinaryOperator(BinaryOperator *E) {
11150       if (E->isCompoundAssignmentOp()) {
11151         HandleValue(E->getLHS());
11152         Visit(E->getRHS());
11153         return;
11154       }
11155 
11156       Inherited::VisitBinaryOperator(E);
11157     }
11158 
11159     // A custom visitor for BinaryConditionalOperator is needed because the
11160     // regular visitor would check the condition and true expression separately
11161     // but both point to the same place giving duplicate diagnostics.
11162     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11163       Visit(E->getCond());
11164       Visit(E->getFalseExpr());
11165     }
11166 
11167     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11168       Decl* ReferenceDecl = DRE->getDecl();
11169       if (OrigDecl != ReferenceDecl) return;
11170       unsigned diag;
11171       if (isReferenceType) {
11172         diag = diag::warn_uninit_self_reference_in_reference_init;
11173       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11174         diag = diag::warn_static_self_reference_in_init;
11175       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11176                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11177                  DRE->getDecl()->getType()->isRecordType()) {
11178         diag = diag::warn_uninit_self_reference_in_init;
11179       } else {
11180         // Local variables will be handled by the CFG analysis.
11181         return;
11182       }
11183 
11184       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11185                             S.PDiag(diag)
11186                                 << DRE->getDecl() << OrigDecl->getLocation()
11187                                 << DRE->getSourceRange());
11188     }
11189   };
11190 
11191   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11192   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11193                                  bool DirectInit) {
11194     // Parameters arguments are occassionially constructed with itself,
11195     // for instance, in recursive functions.  Skip them.
11196     if (isa<ParmVarDecl>(OrigDecl))
11197       return;
11198 
11199     E = E->IgnoreParens();
11200 
11201     // Skip checking T a = a where T is not a record or reference type.
11202     // Doing so is a way to silence uninitialized warnings.
11203     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11204       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11205         if (ICE->getCastKind() == CK_LValueToRValue)
11206           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11207             if (DRE->getDecl() == OrigDecl)
11208               return;
11209 
11210     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11211   }
11212 } // end anonymous namespace
11213 
11214 namespace {
11215   // Simple wrapper to add the name of a variable or (if no variable is
11216   // available) a DeclarationName into a diagnostic.
11217   struct VarDeclOrName {
11218     VarDecl *VDecl;
11219     DeclarationName Name;
11220 
11221     friend const Sema::SemaDiagnosticBuilder &
11222     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11223       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11224     }
11225   };
11226 } // end anonymous namespace
11227 
11228 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11229                                             DeclarationName Name, QualType Type,
11230                                             TypeSourceInfo *TSI,
11231                                             SourceRange Range, bool DirectInit,
11232                                             Expr *Init) {
11233   bool IsInitCapture = !VDecl;
11234   assert((!VDecl || !VDecl->isInitCapture()) &&
11235          "init captures are expected to be deduced prior to initialization");
11236 
11237   VarDeclOrName VN{VDecl, Name};
11238 
11239   DeducedType *Deduced = Type->getContainedDeducedType();
11240   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11241 
11242   // C++11 [dcl.spec.auto]p3
11243   if (!Init) {
11244     assert(VDecl && "no init for init capture deduction?");
11245 
11246     // Except for class argument deduction, and then for an initializing
11247     // declaration only, i.e. no static at class scope or extern.
11248     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11249         VDecl->hasExternalStorage() ||
11250         VDecl->isStaticDataMember()) {
11251       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11252         << VDecl->getDeclName() << Type;
11253       return QualType();
11254     }
11255   }
11256 
11257   ArrayRef<Expr*> DeduceInits;
11258   if (Init)
11259     DeduceInits = Init;
11260 
11261   if (DirectInit) {
11262     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11263       DeduceInits = PL->exprs();
11264   }
11265 
11266   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11267     assert(VDecl && "non-auto type for init capture deduction?");
11268     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11269     InitializationKind Kind = InitializationKind::CreateForInit(
11270         VDecl->getLocation(), DirectInit, Init);
11271     // FIXME: Initialization should not be taking a mutable list of inits.
11272     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11273     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11274                                                        InitsCopy);
11275   }
11276 
11277   if (DirectInit) {
11278     if (auto *IL = dyn_cast<InitListExpr>(Init))
11279       DeduceInits = IL->inits();
11280   }
11281 
11282   // Deduction only works if we have exactly one source expression.
11283   if (DeduceInits.empty()) {
11284     // It isn't possible to write this directly, but it is possible to
11285     // end up in this situation with "auto x(some_pack...);"
11286     Diag(Init->getBeginLoc(), IsInitCapture
11287                                   ? diag::err_init_capture_no_expression
11288                                   : diag::err_auto_var_init_no_expression)
11289         << VN << Type << Range;
11290     return QualType();
11291   }
11292 
11293   if (DeduceInits.size() > 1) {
11294     Diag(DeduceInits[1]->getBeginLoc(),
11295          IsInitCapture ? diag::err_init_capture_multiple_expressions
11296                        : diag::err_auto_var_init_multiple_expressions)
11297         << VN << Type << Range;
11298     return QualType();
11299   }
11300 
11301   Expr *DeduceInit = DeduceInits[0];
11302   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11303     Diag(Init->getBeginLoc(), IsInitCapture
11304                                   ? diag::err_init_capture_paren_braces
11305                                   : diag::err_auto_var_init_paren_braces)
11306         << isa<InitListExpr>(Init) << VN << Type << Range;
11307     return QualType();
11308   }
11309 
11310   // Expressions default to 'id' when we're in a debugger.
11311   bool DefaultedAnyToId = false;
11312   if (getLangOpts().DebuggerCastResultToId &&
11313       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11314     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11315     if (Result.isInvalid()) {
11316       return QualType();
11317     }
11318     Init = Result.get();
11319     DefaultedAnyToId = true;
11320   }
11321 
11322   // C++ [dcl.decomp]p1:
11323   //   If the assignment-expression [...] has array type A and no ref-qualifier
11324   //   is present, e has type cv A
11325   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11326       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11327       DeduceInit->getType()->isConstantArrayType())
11328     return Context.getQualifiedType(DeduceInit->getType(),
11329                                     Type.getQualifiers());
11330 
11331   QualType DeducedType;
11332   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11333     if (!IsInitCapture)
11334       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11335     else if (isa<InitListExpr>(Init))
11336       Diag(Range.getBegin(),
11337            diag::err_init_capture_deduction_failure_from_init_list)
11338           << VN
11339           << (DeduceInit->getType().isNull() ? TSI->getType()
11340                                              : DeduceInit->getType())
11341           << DeduceInit->getSourceRange();
11342     else
11343       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11344           << VN << TSI->getType()
11345           << (DeduceInit->getType().isNull() ? TSI->getType()
11346                                              : DeduceInit->getType())
11347           << DeduceInit->getSourceRange();
11348   }
11349 
11350   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11351   // 'id' instead of a specific object type prevents most of our usual
11352   // checks.
11353   // We only want to warn outside of template instantiations, though:
11354   // inside a template, the 'id' could have come from a parameter.
11355   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11356       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11357     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11358     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11359   }
11360 
11361   return DeducedType;
11362 }
11363 
11364 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11365                                          Expr *Init) {
11366   QualType DeducedType = deduceVarTypeFromInitializer(
11367       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11368       VDecl->getSourceRange(), DirectInit, Init);
11369   if (DeducedType.isNull()) {
11370     VDecl->setInvalidDecl();
11371     return true;
11372   }
11373 
11374   VDecl->setType(DeducedType);
11375   assert(VDecl->isLinkageValid());
11376 
11377   // In ARC, infer lifetime.
11378   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11379     VDecl->setInvalidDecl();
11380 
11381   if (getLangOpts().OpenCL)
11382     deduceOpenCLAddressSpace(VDecl);
11383 
11384   // If this is a redeclaration, check that the type we just deduced matches
11385   // the previously declared type.
11386   if (VarDecl *Old = VDecl->getPreviousDecl()) {
11387     // We never need to merge the type, because we cannot form an incomplete
11388     // array of auto, nor deduce such a type.
11389     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11390   }
11391 
11392   // Check the deduced type is valid for a variable declaration.
11393   CheckVariableDeclarationType(VDecl);
11394   return VDecl->isInvalidDecl();
11395 }
11396 
11397 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11398                                               SourceLocation Loc) {
11399   if (auto *CE = dyn_cast<ConstantExpr>(Init))
11400     Init = CE->getSubExpr();
11401 
11402   QualType InitType = Init->getType();
11403   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11404           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
11405          "shouldn't be called if type doesn't have a non-trivial C struct");
11406   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11407     for (auto I : ILE->inits()) {
11408       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11409           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11410         continue;
11411       SourceLocation SL = I->getExprLoc();
11412       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11413     }
11414     return;
11415   }
11416 
11417   if (isa<ImplicitValueInitExpr>(Init)) {
11418     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11419       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11420                             NTCUK_Init);
11421   } else {
11422     // Assume all other explicit initializers involving copying some existing
11423     // object.
11424     // TODO: ignore any explicit initializers where we can guarantee
11425     // copy-elision.
11426     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11427       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11428   }
11429 }
11430 
11431 namespace {
11432 
11433 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11434   // Ignore unavailable fields. A field can be marked as unavailable explicitly
11435   // in the source code or implicitly by the compiler if it is in a union
11436   // defined in a system header and has non-trivial ObjC ownership
11437   // qualifications. We don't want those fields to participate in determining
11438   // whether the containing union is non-trivial.
11439   return FD->hasAttr<UnavailableAttr>();
11440 }
11441 
11442 struct DiagNonTrivalCUnionDefaultInitializeVisitor
11443     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11444                                     void> {
11445   using Super =
11446       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11447                                     void>;
11448 
11449   DiagNonTrivalCUnionDefaultInitializeVisitor(
11450       QualType OrigTy, SourceLocation OrigLoc,
11451       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11452       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11453 
11454   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11455                      const FieldDecl *FD, bool InNonTrivialUnion) {
11456     if (const auto *AT = S.Context.getAsArrayType(QT))
11457       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11458                                      InNonTrivialUnion);
11459     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11460   }
11461 
11462   void visitARCStrong(QualType QT, const FieldDecl *FD,
11463                       bool InNonTrivialUnion) {
11464     if (InNonTrivialUnion)
11465       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11466           << 1 << 0 << QT << FD->getName();
11467   }
11468 
11469   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11470     if (InNonTrivialUnion)
11471       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11472           << 1 << 0 << QT << FD->getName();
11473   }
11474 
11475   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11476     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11477     if (RD->isUnion()) {
11478       if (OrigLoc.isValid()) {
11479         bool IsUnion = false;
11480         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11481           IsUnion = OrigRD->isUnion();
11482         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11483             << 0 << OrigTy << IsUnion << UseContext;
11484         // Reset OrigLoc so that this diagnostic is emitted only once.
11485         OrigLoc = SourceLocation();
11486       }
11487       InNonTrivialUnion = true;
11488     }
11489 
11490     if (InNonTrivialUnion)
11491       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11492           << 0 << 0 << QT.getUnqualifiedType() << "";
11493 
11494     for (const FieldDecl *FD : RD->fields())
11495       if (!shouldIgnoreForRecordTriviality(FD))
11496         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11497   }
11498 
11499   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11500 
11501   // The non-trivial C union type or the struct/union type that contains a
11502   // non-trivial C union.
11503   QualType OrigTy;
11504   SourceLocation OrigLoc;
11505   Sema::NonTrivialCUnionContext UseContext;
11506   Sema &S;
11507 };
11508 
11509 struct DiagNonTrivalCUnionDestructedTypeVisitor
11510     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
11511   using Super =
11512       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
11513 
11514   DiagNonTrivalCUnionDestructedTypeVisitor(
11515       QualType OrigTy, SourceLocation OrigLoc,
11516       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11517       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11518 
11519   void visitWithKind(QualType::DestructionKind DK, QualType QT,
11520                      const FieldDecl *FD, bool InNonTrivialUnion) {
11521     if (const auto *AT = S.Context.getAsArrayType(QT))
11522       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11523                                      InNonTrivialUnion);
11524     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
11525   }
11526 
11527   void visitARCStrong(QualType QT, const FieldDecl *FD,
11528                       bool InNonTrivialUnion) {
11529     if (InNonTrivialUnion)
11530       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11531           << 1 << 1 << QT << FD->getName();
11532   }
11533 
11534   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11535     if (InNonTrivialUnion)
11536       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11537           << 1 << 1 << QT << FD->getName();
11538   }
11539 
11540   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11541     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11542     if (RD->isUnion()) {
11543       if (OrigLoc.isValid()) {
11544         bool IsUnion = false;
11545         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11546           IsUnion = OrigRD->isUnion();
11547         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11548             << 1 << OrigTy << IsUnion << UseContext;
11549         // Reset OrigLoc so that this diagnostic is emitted only once.
11550         OrigLoc = SourceLocation();
11551       }
11552       InNonTrivialUnion = true;
11553     }
11554 
11555     if (InNonTrivialUnion)
11556       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11557           << 0 << 1 << QT.getUnqualifiedType() << "";
11558 
11559     for (const FieldDecl *FD : RD->fields())
11560       if (!shouldIgnoreForRecordTriviality(FD))
11561         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11562   }
11563 
11564   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11565   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
11566                           bool InNonTrivialUnion) {}
11567 
11568   // The non-trivial C union type or the struct/union type that contains a
11569   // non-trivial C union.
11570   QualType OrigTy;
11571   SourceLocation OrigLoc;
11572   Sema::NonTrivialCUnionContext UseContext;
11573   Sema &S;
11574 };
11575 
11576 struct DiagNonTrivalCUnionCopyVisitor
11577     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
11578   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
11579 
11580   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
11581                                  Sema::NonTrivialCUnionContext UseContext,
11582                                  Sema &S)
11583       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11584 
11585   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
11586                      const FieldDecl *FD, bool InNonTrivialUnion) {
11587     if (const auto *AT = S.Context.getAsArrayType(QT))
11588       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11589                                      InNonTrivialUnion);
11590     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
11591   }
11592 
11593   void visitARCStrong(QualType QT, const FieldDecl *FD,
11594                       bool InNonTrivialUnion) {
11595     if (InNonTrivialUnion)
11596       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11597           << 1 << 2 << QT << FD->getName();
11598   }
11599 
11600   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11601     if (InNonTrivialUnion)
11602       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11603           << 1 << 2 << QT << FD->getName();
11604   }
11605 
11606   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11607     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11608     if (RD->isUnion()) {
11609       if (OrigLoc.isValid()) {
11610         bool IsUnion = false;
11611         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11612           IsUnion = OrigRD->isUnion();
11613         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11614             << 2 << OrigTy << IsUnion << UseContext;
11615         // Reset OrigLoc so that this diagnostic is emitted only once.
11616         OrigLoc = SourceLocation();
11617       }
11618       InNonTrivialUnion = true;
11619     }
11620 
11621     if (InNonTrivialUnion)
11622       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11623           << 0 << 2 << QT.getUnqualifiedType() << "";
11624 
11625     for (const FieldDecl *FD : RD->fields())
11626       if (!shouldIgnoreForRecordTriviality(FD))
11627         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11628   }
11629 
11630   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
11631                 const FieldDecl *FD, bool InNonTrivialUnion) {}
11632   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11633   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
11634                             bool InNonTrivialUnion) {}
11635 
11636   // The non-trivial C union type or the struct/union type that contains a
11637   // non-trivial C union.
11638   QualType OrigTy;
11639   SourceLocation OrigLoc;
11640   Sema::NonTrivialCUnionContext UseContext;
11641   Sema &S;
11642 };
11643 
11644 } // namespace
11645 
11646 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
11647                                  NonTrivialCUnionContext UseContext,
11648                                  unsigned NonTrivialKind) {
11649   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11650           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
11651           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
11652          "shouldn't be called if type doesn't have a non-trivial C union");
11653 
11654   if ((NonTrivialKind & NTCUK_Init) &&
11655       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11656     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
11657         .visit(QT, nullptr, false);
11658   if ((NonTrivialKind & NTCUK_Destruct) &&
11659       QT.hasNonTrivialToPrimitiveDestructCUnion())
11660     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
11661         .visit(QT, nullptr, false);
11662   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
11663     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
11664         .visit(QT, nullptr, false);
11665 }
11666 
11667 /// AddInitializerToDecl - Adds the initializer Init to the
11668 /// declaration dcl. If DirectInit is true, this is C++ direct
11669 /// initialization rather than copy initialization.
11670 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
11671   // If there is no declaration, there was an error parsing it.  Just ignore
11672   // the initializer.
11673   if (!RealDecl || RealDecl->isInvalidDecl()) {
11674     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
11675     return;
11676   }
11677 
11678   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
11679     // Pure-specifiers are handled in ActOnPureSpecifier.
11680     Diag(Method->getLocation(), diag::err_member_function_initialization)
11681       << Method->getDeclName() << Init->getSourceRange();
11682     Method->setInvalidDecl();
11683     return;
11684   }
11685 
11686   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
11687   if (!VDecl) {
11688     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
11689     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
11690     RealDecl->setInvalidDecl();
11691     return;
11692   }
11693 
11694   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
11695   if (VDecl->getType()->isUndeducedType()) {
11696     // Attempt typo correction early so that the type of the init expression can
11697     // be deduced based on the chosen correction if the original init contains a
11698     // TypoExpr.
11699     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
11700     if (!Res.isUsable()) {
11701       RealDecl->setInvalidDecl();
11702       return;
11703     }
11704     Init = Res.get();
11705 
11706     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
11707       return;
11708   }
11709 
11710   // dllimport cannot be used on variable definitions.
11711   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
11712     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
11713     VDecl->setInvalidDecl();
11714     return;
11715   }
11716 
11717   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
11718     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
11719     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
11720     VDecl->setInvalidDecl();
11721     return;
11722   }
11723 
11724   if (!VDecl->getType()->isDependentType()) {
11725     // A definition must end up with a complete type, which means it must be
11726     // complete with the restriction that an array type might be completed by
11727     // the initializer; note that later code assumes this restriction.
11728     QualType BaseDeclType = VDecl->getType();
11729     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
11730       BaseDeclType = Array->getElementType();
11731     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
11732                             diag::err_typecheck_decl_incomplete_type)) {
11733       RealDecl->setInvalidDecl();
11734       return;
11735     }
11736 
11737     // The variable can not have an abstract class type.
11738     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
11739                                diag::err_abstract_type_in_decl,
11740                                AbstractVariableType))
11741       VDecl->setInvalidDecl();
11742   }
11743 
11744   // If adding the initializer will turn this declaration into a definition,
11745   // and we already have a definition for this variable, diagnose or otherwise
11746   // handle the situation.
11747   VarDecl *Def;
11748   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
11749       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
11750       !VDecl->isThisDeclarationADemotedDefinition() &&
11751       checkVarDeclRedefinition(Def, VDecl))
11752     return;
11753 
11754   if (getLangOpts().CPlusPlus) {
11755     // C++ [class.static.data]p4
11756     //   If a static data member is of const integral or const
11757     //   enumeration type, its declaration in the class definition can
11758     //   specify a constant-initializer which shall be an integral
11759     //   constant expression (5.19). In that case, the member can appear
11760     //   in integral constant expressions. The member shall still be
11761     //   defined in a namespace scope if it is used in the program and the
11762     //   namespace scope definition shall not contain an initializer.
11763     //
11764     // We already performed a redefinition check above, but for static
11765     // data members we also need to check whether there was an in-class
11766     // declaration with an initializer.
11767     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
11768       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
11769           << VDecl->getDeclName();
11770       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
11771            diag::note_previous_initializer)
11772           << 0;
11773       return;
11774     }
11775 
11776     if (VDecl->hasLocalStorage())
11777       setFunctionHasBranchProtectedScope();
11778 
11779     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
11780       VDecl->setInvalidDecl();
11781       return;
11782     }
11783   }
11784 
11785   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
11786   // a kernel function cannot be initialized."
11787   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
11788     Diag(VDecl->getLocation(), diag::err_local_cant_init);
11789     VDecl->setInvalidDecl();
11790     return;
11791   }
11792 
11793   // Get the decls type and save a reference for later, since
11794   // CheckInitializerTypes may change it.
11795   QualType DclT = VDecl->getType(), SavT = DclT;
11796 
11797   // Expressions default to 'id' when we're in a debugger
11798   // and we are assigning it to a variable of Objective-C pointer type.
11799   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
11800       Init->getType() == Context.UnknownAnyTy) {
11801     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11802     if (Result.isInvalid()) {
11803       VDecl->setInvalidDecl();
11804       return;
11805     }
11806     Init = Result.get();
11807   }
11808 
11809   // Perform the initialization.
11810   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
11811   if (!VDecl->isInvalidDecl()) {
11812     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11813     InitializationKind Kind = InitializationKind::CreateForInit(
11814         VDecl->getLocation(), DirectInit, Init);
11815 
11816     MultiExprArg Args = Init;
11817     if (CXXDirectInit)
11818       Args = MultiExprArg(CXXDirectInit->getExprs(),
11819                           CXXDirectInit->getNumExprs());
11820 
11821     // Try to correct any TypoExprs in the initialization arguments.
11822     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
11823       ExprResult Res = CorrectDelayedTyposInExpr(
11824           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
11825             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
11826             return Init.Failed() ? ExprError() : E;
11827           });
11828       if (Res.isInvalid()) {
11829         VDecl->setInvalidDecl();
11830       } else if (Res.get() != Args[Idx]) {
11831         Args[Idx] = Res.get();
11832       }
11833     }
11834     if (VDecl->isInvalidDecl())
11835       return;
11836 
11837     InitializationSequence InitSeq(*this, Entity, Kind, Args,
11838                                    /*TopLevelOfInitList=*/false,
11839                                    /*TreatUnavailableAsInvalid=*/false);
11840     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
11841     if (Result.isInvalid()) {
11842       VDecl->setInvalidDecl();
11843       return;
11844     }
11845 
11846     Init = Result.getAs<Expr>();
11847   }
11848 
11849   // Check for self-references within variable initializers.
11850   // Variables declared within a function/method body (except for references)
11851   // are handled by a dataflow analysis.
11852   // This is undefined behavior in C++, but valid in C.
11853   if (getLangOpts().CPlusPlus) {
11854     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
11855         VDecl->getType()->isReferenceType()) {
11856       CheckSelfReference(*this, RealDecl, Init, DirectInit);
11857     }
11858   }
11859 
11860   // If the type changed, it means we had an incomplete type that was
11861   // completed by the initializer. For example:
11862   //   int ary[] = { 1, 3, 5 };
11863   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
11864   if (!VDecl->isInvalidDecl() && (DclT != SavT))
11865     VDecl->setType(DclT);
11866 
11867   if (!VDecl->isInvalidDecl()) {
11868     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
11869 
11870     if (VDecl->hasAttr<BlocksAttr>())
11871       checkRetainCycles(VDecl, Init);
11872 
11873     // It is safe to assign a weak reference into a strong variable.
11874     // Although this code can still have problems:
11875     //   id x = self.weakProp;
11876     //   id y = self.weakProp;
11877     // we do not warn to warn spuriously when 'x' and 'y' are on separate
11878     // paths through the function. This should be revisited if
11879     // -Wrepeated-use-of-weak is made flow-sensitive.
11880     if (FunctionScopeInfo *FSI = getCurFunction())
11881       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
11882            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
11883           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11884                            Init->getBeginLoc()))
11885         FSI->markSafeWeakUse(Init);
11886   }
11887 
11888   // The initialization is usually a full-expression.
11889   //
11890   // FIXME: If this is a braced initialization of an aggregate, it is not
11891   // an expression, and each individual field initializer is a separate
11892   // full-expression. For instance, in:
11893   //
11894   //   struct Temp { ~Temp(); };
11895   //   struct S { S(Temp); };
11896   //   struct T { S a, b; } t = { Temp(), Temp() }
11897   //
11898   // we should destroy the first Temp before constructing the second.
11899   ExprResult Result =
11900       ActOnFinishFullExpr(Init, VDecl->getLocation(),
11901                           /*DiscardedValue*/ false, VDecl->isConstexpr());
11902   if (Result.isInvalid()) {
11903     VDecl->setInvalidDecl();
11904     return;
11905   }
11906   Init = Result.get();
11907 
11908   // Attach the initializer to the decl.
11909   VDecl->setInit(Init);
11910 
11911   if (VDecl->isLocalVarDecl()) {
11912     // Don't check the initializer if the declaration is malformed.
11913     if (VDecl->isInvalidDecl()) {
11914       // do nothing
11915 
11916     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
11917     // This is true even in C++ for OpenCL.
11918     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
11919       CheckForConstantInitializer(Init, DclT);
11920 
11921     // Otherwise, C++ does not restrict the initializer.
11922     } else if (getLangOpts().CPlusPlus) {
11923       // do nothing
11924 
11925     // C99 6.7.8p4: All the expressions in an initializer for an object that has
11926     // static storage duration shall be constant expressions or string literals.
11927     } else if (VDecl->getStorageClass() == SC_Static) {
11928       CheckForConstantInitializer(Init, DclT);
11929 
11930     // C89 is stricter than C99 for aggregate initializers.
11931     // C89 6.5.7p3: All the expressions [...] in an initializer list
11932     // for an object that has aggregate or union type shall be
11933     // constant expressions.
11934     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
11935                isa<InitListExpr>(Init)) {
11936       const Expr *Culprit;
11937       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
11938         Diag(Culprit->getExprLoc(),
11939              diag::ext_aggregate_init_not_constant)
11940           << Culprit->getSourceRange();
11941       }
11942     }
11943 
11944     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
11945       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
11946         if (VDecl->hasLocalStorage())
11947           BE->getBlockDecl()->setCanAvoidCopyToHeap();
11948   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
11949              VDecl->getLexicalDeclContext()->isRecord()) {
11950     // This is an in-class initialization for a static data member, e.g.,
11951     //
11952     // struct S {
11953     //   static const int value = 17;
11954     // };
11955 
11956     // C++ [class.mem]p4:
11957     //   A member-declarator can contain a constant-initializer only
11958     //   if it declares a static member (9.4) of const integral or
11959     //   const enumeration type, see 9.4.2.
11960     //
11961     // C++11 [class.static.data]p3:
11962     //   If a non-volatile non-inline const static data member is of integral
11963     //   or enumeration type, its declaration in the class definition can
11964     //   specify a brace-or-equal-initializer in which every initializer-clause
11965     //   that is an assignment-expression is a constant expression. A static
11966     //   data member of literal type can be declared in the class definition
11967     //   with the constexpr specifier; if so, its declaration shall specify a
11968     //   brace-or-equal-initializer in which every initializer-clause that is
11969     //   an assignment-expression is a constant expression.
11970 
11971     // Do nothing on dependent types.
11972     if (DclT->isDependentType()) {
11973 
11974     // Allow any 'static constexpr' members, whether or not they are of literal
11975     // type. We separately check that every constexpr variable is of literal
11976     // type.
11977     } else if (VDecl->isConstexpr()) {
11978 
11979     // Require constness.
11980     } else if (!DclT.isConstQualified()) {
11981       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
11982         << Init->getSourceRange();
11983       VDecl->setInvalidDecl();
11984 
11985     // We allow integer constant expressions in all cases.
11986     } else if (DclT->isIntegralOrEnumerationType()) {
11987       // Check whether the expression is a constant expression.
11988       SourceLocation Loc;
11989       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
11990         // In C++11, a non-constexpr const static data member with an
11991         // in-class initializer cannot be volatile.
11992         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
11993       else if (Init->isValueDependent())
11994         ; // Nothing to check.
11995       else if (Init->isIntegerConstantExpr(Context, &Loc))
11996         ; // Ok, it's an ICE!
11997       else if (Init->getType()->isScopedEnumeralType() &&
11998                Init->isCXX11ConstantExpr(Context))
11999         ; // Ok, it is a scoped-enum constant expression.
12000       else if (Init->isEvaluatable(Context)) {
12001         // If we can constant fold the initializer through heroics, accept it,
12002         // but report this as a use of an extension for -pedantic.
12003         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12004           << Init->getSourceRange();
12005       } else {
12006         // Otherwise, this is some crazy unknown case.  Report the issue at the
12007         // location provided by the isIntegerConstantExpr failed check.
12008         Diag(Loc, diag::err_in_class_initializer_non_constant)
12009           << Init->getSourceRange();
12010         VDecl->setInvalidDecl();
12011       }
12012 
12013     // We allow foldable floating-point constants as an extension.
12014     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12015       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12016       // it anyway and provide a fixit to add the 'constexpr'.
12017       if (getLangOpts().CPlusPlus11) {
12018         Diag(VDecl->getLocation(),
12019              diag::ext_in_class_initializer_float_type_cxx11)
12020             << DclT << Init->getSourceRange();
12021         Diag(VDecl->getBeginLoc(),
12022              diag::note_in_class_initializer_float_type_cxx11)
12023             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12024       } else {
12025         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12026           << DclT << Init->getSourceRange();
12027 
12028         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12029           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12030             << Init->getSourceRange();
12031           VDecl->setInvalidDecl();
12032         }
12033       }
12034 
12035     // Suggest adding 'constexpr' in C++11 for literal types.
12036     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12037       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12038           << DclT << Init->getSourceRange()
12039           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12040       VDecl->setConstexpr(true);
12041 
12042     } else {
12043       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12044         << DclT << Init->getSourceRange();
12045       VDecl->setInvalidDecl();
12046     }
12047   } else if (VDecl->isFileVarDecl()) {
12048     // In C, extern is typically used to avoid tentative definitions when
12049     // declaring variables in headers, but adding an intializer makes it a
12050     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12051     // In C++, extern is often used to give implictly static const variables
12052     // external linkage, so don't warn in that case. If selectany is present,
12053     // this might be header code intended for C and C++ inclusion, so apply the
12054     // C++ rules.
12055     if (VDecl->getStorageClass() == SC_Extern &&
12056         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12057          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12058         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12059         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12060       Diag(VDecl->getLocation(), diag::warn_extern_init);
12061 
12062     // In Microsoft C++ mode, a const variable defined in namespace scope has
12063     // external linkage by default if the variable is declared with
12064     // __declspec(dllexport).
12065     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12066         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12067         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12068       VDecl->setStorageClass(SC_Extern);
12069 
12070     // C99 6.7.8p4. All file scoped initializers need to be constant.
12071     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12072       CheckForConstantInitializer(Init, DclT);
12073   }
12074 
12075   QualType InitType = Init->getType();
12076   if (!InitType.isNull() &&
12077       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12078        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12079     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12080 
12081   // We will represent direct-initialization similarly to copy-initialization:
12082   //    int x(1);  -as-> int x = 1;
12083   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12084   //
12085   // Clients that want to distinguish between the two forms, can check for
12086   // direct initializer using VarDecl::getInitStyle().
12087   // A major benefit is that clients that don't particularly care about which
12088   // exactly form was it (like the CodeGen) can handle both cases without
12089   // special case code.
12090 
12091   // C++ 8.5p11:
12092   // The form of initialization (using parentheses or '=') is generally
12093   // insignificant, but does matter when the entity being initialized has a
12094   // class type.
12095   if (CXXDirectInit) {
12096     assert(DirectInit && "Call-style initializer must be direct init.");
12097     VDecl->setInitStyle(VarDecl::CallInit);
12098   } else if (DirectInit) {
12099     // This must be list-initialization. No other way is direct-initialization.
12100     VDecl->setInitStyle(VarDecl::ListInit);
12101   }
12102 
12103   CheckCompleteVariableDeclaration(VDecl);
12104 }
12105 
12106 /// ActOnInitializerError - Given that there was an error parsing an
12107 /// initializer for the given declaration, try to return to some form
12108 /// of sanity.
12109 void Sema::ActOnInitializerError(Decl *D) {
12110   // Our main concern here is re-establishing invariants like "a
12111   // variable's type is either dependent or complete".
12112   if (!D || D->isInvalidDecl()) return;
12113 
12114   VarDecl *VD = dyn_cast<VarDecl>(D);
12115   if (!VD) return;
12116 
12117   // Bindings are not usable if we can't make sense of the initializer.
12118   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12119     for (auto *BD : DD->bindings())
12120       BD->setInvalidDecl();
12121 
12122   // Auto types are meaningless if we can't make sense of the initializer.
12123   if (ParsingInitForAutoVars.count(D)) {
12124     D->setInvalidDecl();
12125     return;
12126   }
12127 
12128   QualType Ty = VD->getType();
12129   if (Ty->isDependentType()) return;
12130 
12131   // Require a complete type.
12132   if (RequireCompleteType(VD->getLocation(),
12133                           Context.getBaseElementType(Ty),
12134                           diag::err_typecheck_decl_incomplete_type)) {
12135     VD->setInvalidDecl();
12136     return;
12137   }
12138 
12139   // Require a non-abstract type.
12140   if (RequireNonAbstractType(VD->getLocation(), Ty,
12141                              diag::err_abstract_type_in_decl,
12142                              AbstractVariableType)) {
12143     VD->setInvalidDecl();
12144     return;
12145   }
12146 
12147   // Don't bother complaining about constructors or destructors,
12148   // though.
12149 }
12150 
12151 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12152   // If there is no declaration, there was an error parsing it. Just ignore it.
12153   if (!RealDecl)
12154     return;
12155 
12156   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12157     QualType Type = Var->getType();
12158 
12159     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12160     if (isa<DecompositionDecl>(RealDecl)) {
12161       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12162       Var->setInvalidDecl();
12163       return;
12164     }
12165 
12166     if (Type->isUndeducedType() &&
12167         DeduceVariableDeclarationType(Var, false, nullptr))
12168       return;
12169 
12170     // C++11 [class.static.data]p3: A static data member can be declared with
12171     // the constexpr specifier; if so, its declaration shall specify
12172     // a brace-or-equal-initializer.
12173     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12174     // the definition of a variable [...] or the declaration of a static data
12175     // member.
12176     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12177         !Var->isThisDeclarationADemotedDefinition()) {
12178       if (Var->isStaticDataMember()) {
12179         // C++1z removes the relevant rule; the in-class declaration is always
12180         // a definition there.
12181         if (!getLangOpts().CPlusPlus17 &&
12182             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12183           Diag(Var->getLocation(),
12184                diag::err_constexpr_static_mem_var_requires_init)
12185             << Var->getDeclName();
12186           Var->setInvalidDecl();
12187           return;
12188         }
12189       } else {
12190         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12191         Var->setInvalidDecl();
12192         return;
12193       }
12194     }
12195 
12196     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12197     // be initialized.
12198     if (!Var->isInvalidDecl() &&
12199         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12200         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12201       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12202       Var->setInvalidDecl();
12203       return;
12204     }
12205 
12206     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12207     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12208         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12209       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12210                             NTCUC_DefaultInitializedObject, NTCUK_Init);
12211 
12212 
12213     switch (DefKind) {
12214     case VarDecl::Definition:
12215       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12216         break;
12217 
12218       // We have an out-of-line definition of a static data member
12219       // that has an in-class initializer, so we type-check this like
12220       // a declaration.
12221       //
12222       LLVM_FALLTHROUGH;
12223 
12224     case VarDecl::DeclarationOnly:
12225       // It's only a declaration.
12226 
12227       // Block scope. C99 6.7p7: If an identifier for an object is
12228       // declared with no linkage (C99 6.2.2p6), the type for the
12229       // object shall be complete.
12230       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12231           !Var->hasLinkage() && !Var->isInvalidDecl() &&
12232           RequireCompleteType(Var->getLocation(), Type,
12233                               diag::err_typecheck_decl_incomplete_type))
12234         Var->setInvalidDecl();
12235 
12236       // Make sure that the type is not abstract.
12237       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12238           RequireNonAbstractType(Var->getLocation(), Type,
12239                                  diag::err_abstract_type_in_decl,
12240                                  AbstractVariableType))
12241         Var->setInvalidDecl();
12242       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12243           Var->getStorageClass() == SC_PrivateExtern) {
12244         Diag(Var->getLocation(), diag::warn_private_extern);
12245         Diag(Var->getLocation(), diag::note_private_extern);
12246       }
12247 
12248       if (Context.getTargetInfo().allowDebugInfoForExternalVar() &&
12249           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12250         ExternalDeclarations.push_back(Var);
12251 
12252       return;
12253 
12254     case VarDecl::TentativeDefinition:
12255       // File scope. C99 6.9.2p2: A declaration of an identifier for an
12256       // object that has file scope without an initializer, and without a
12257       // storage-class specifier or with the storage-class specifier "static",
12258       // constitutes a tentative definition. Note: A tentative definition with
12259       // external linkage is valid (C99 6.2.2p5).
12260       if (!Var->isInvalidDecl()) {
12261         if (const IncompleteArrayType *ArrayT
12262                                     = Context.getAsIncompleteArrayType(Type)) {
12263           if (RequireCompleteType(Var->getLocation(),
12264                                   ArrayT->getElementType(),
12265                                   diag::err_illegal_decl_array_incomplete_type))
12266             Var->setInvalidDecl();
12267         } else if (Var->getStorageClass() == SC_Static) {
12268           // C99 6.9.2p3: If the declaration of an identifier for an object is
12269           // a tentative definition and has internal linkage (C99 6.2.2p3), the
12270           // declared type shall not be an incomplete type.
12271           // NOTE: code such as the following
12272           //     static struct s;
12273           //     struct s { int a; };
12274           // is accepted by gcc. Hence here we issue a warning instead of
12275           // an error and we do not invalidate the static declaration.
12276           // NOTE: to avoid multiple warnings, only check the first declaration.
12277           if (Var->isFirstDecl())
12278             RequireCompleteType(Var->getLocation(), Type,
12279                                 diag::ext_typecheck_decl_incomplete_type);
12280         }
12281       }
12282 
12283       // Record the tentative definition; we're done.
12284       if (!Var->isInvalidDecl())
12285         TentativeDefinitions.push_back(Var);
12286       return;
12287     }
12288 
12289     // Provide a specific diagnostic for uninitialized variable
12290     // definitions with incomplete array type.
12291     if (Type->isIncompleteArrayType()) {
12292       Diag(Var->getLocation(),
12293            diag::err_typecheck_incomplete_array_needs_initializer);
12294       Var->setInvalidDecl();
12295       return;
12296     }
12297 
12298     // Provide a specific diagnostic for uninitialized variable
12299     // definitions with reference type.
12300     if (Type->isReferenceType()) {
12301       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12302         << Var->getDeclName()
12303         << SourceRange(Var->getLocation(), Var->getLocation());
12304       Var->setInvalidDecl();
12305       return;
12306     }
12307 
12308     // Do not attempt to type-check the default initializer for a
12309     // variable with dependent type.
12310     if (Type->isDependentType())
12311       return;
12312 
12313     if (Var->isInvalidDecl())
12314       return;
12315 
12316     if (!Var->hasAttr<AliasAttr>()) {
12317       if (RequireCompleteType(Var->getLocation(),
12318                               Context.getBaseElementType(Type),
12319                               diag::err_typecheck_decl_incomplete_type)) {
12320         Var->setInvalidDecl();
12321         return;
12322       }
12323     } else {
12324       return;
12325     }
12326 
12327     // The variable can not have an abstract class type.
12328     if (RequireNonAbstractType(Var->getLocation(), Type,
12329                                diag::err_abstract_type_in_decl,
12330                                AbstractVariableType)) {
12331       Var->setInvalidDecl();
12332       return;
12333     }
12334 
12335     // Check for jumps past the implicit initializer.  C++0x
12336     // clarifies that this applies to a "variable with automatic
12337     // storage duration", not a "local variable".
12338     // C++11 [stmt.dcl]p3
12339     //   A program that jumps from a point where a variable with automatic
12340     //   storage duration is not in scope to a point where it is in scope is
12341     //   ill-formed unless the variable has scalar type, class type with a
12342     //   trivial default constructor and a trivial destructor, a cv-qualified
12343     //   version of one of these types, or an array of one of the preceding
12344     //   types and is declared without an initializer.
12345     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12346       if (const RecordType *Record
12347             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12348         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12349         // Mark the function (if we're in one) for further checking even if the
12350         // looser rules of C++11 do not require such checks, so that we can
12351         // diagnose incompatibilities with C++98.
12352         if (!CXXRecord->isPOD())
12353           setFunctionHasBranchProtectedScope();
12354       }
12355     }
12356     // In OpenCL, we can't initialize objects in the __local address space,
12357     // even implicitly, so don't synthesize an implicit initializer.
12358     if (getLangOpts().OpenCL &&
12359         Var->getType().getAddressSpace() == LangAS::opencl_local)
12360       return;
12361     // C++03 [dcl.init]p9:
12362     //   If no initializer is specified for an object, and the
12363     //   object is of (possibly cv-qualified) non-POD class type (or
12364     //   array thereof), the object shall be default-initialized; if
12365     //   the object is of const-qualified type, the underlying class
12366     //   type shall have a user-declared default
12367     //   constructor. Otherwise, if no initializer is specified for
12368     //   a non- static object, the object and its subobjects, if
12369     //   any, have an indeterminate initial value); if the object
12370     //   or any of its subobjects are of const-qualified type, the
12371     //   program is ill-formed.
12372     // C++0x [dcl.init]p11:
12373     //   If no initializer is specified for an object, the object is
12374     //   default-initialized; [...].
12375     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12376     InitializationKind Kind
12377       = InitializationKind::CreateDefault(Var->getLocation());
12378 
12379     InitializationSequence InitSeq(*this, Entity, Kind, None);
12380     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12381     if (Init.isInvalid())
12382       Var->setInvalidDecl();
12383     else if (Init.get()) {
12384       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12385       // This is important for template substitution.
12386       Var->setInitStyle(VarDecl::CallInit);
12387     }
12388 
12389     CheckCompleteVariableDeclaration(Var);
12390   }
12391 }
12392 
12393 void Sema::ActOnCXXForRangeDecl(Decl *D) {
12394   // If there is no declaration, there was an error parsing it. Ignore it.
12395   if (!D)
12396     return;
12397 
12398   VarDecl *VD = dyn_cast<VarDecl>(D);
12399   if (!VD) {
12400     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12401     D->setInvalidDecl();
12402     return;
12403   }
12404 
12405   VD->setCXXForRangeDecl(true);
12406 
12407   // for-range-declaration cannot be given a storage class specifier.
12408   int Error = -1;
12409   switch (VD->getStorageClass()) {
12410   case SC_None:
12411     break;
12412   case SC_Extern:
12413     Error = 0;
12414     break;
12415   case SC_Static:
12416     Error = 1;
12417     break;
12418   case SC_PrivateExtern:
12419     Error = 2;
12420     break;
12421   case SC_Auto:
12422     Error = 3;
12423     break;
12424   case SC_Register:
12425     Error = 4;
12426     break;
12427   }
12428   if (Error != -1) {
12429     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12430       << VD->getDeclName() << Error;
12431     D->setInvalidDecl();
12432   }
12433 }
12434 
12435 StmtResult
12436 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
12437                                  IdentifierInfo *Ident,
12438                                  ParsedAttributes &Attrs,
12439                                  SourceLocation AttrEnd) {
12440   // C++1y [stmt.iter]p1:
12441   //   A range-based for statement of the form
12442   //      for ( for-range-identifier : for-range-initializer ) statement
12443   //   is equivalent to
12444   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
12445   DeclSpec DS(Attrs.getPool().getFactory());
12446 
12447   const char *PrevSpec;
12448   unsigned DiagID;
12449   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
12450                      getPrintingPolicy());
12451 
12452   Declarator D(DS, DeclaratorContext::ForContext);
12453   D.SetIdentifier(Ident, IdentLoc);
12454   D.takeAttributes(Attrs, AttrEnd);
12455 
12456   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
12457                 IdentLoc);
12458   Decl *Var = ActOnDeclarator(S, D);
12459   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
12460   FinalizeDeclaration(Var);
12461   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
12462                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
12463 }
12464 
12465 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
12466   if (var->isInvalidDecl()) return;
12467 
12468   if (getLangOpts().OpenCL) {
12469     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
12470     // initialiser
12471     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
12472         !var->hasInit()) {
12473       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
12474           << 1 /*Init*/;
12475       var->setInvalidDecl();
12476       return;
12477     }
12478   }
12479 
12480   // In Objective-C, don't allow jumps past the implicit initialization of a
12481   // local retaining variable.
12482   if (getLangOpts().ObjC &&
12483       var->hasLocalStorage()) {
12484     switch (var->getType().getObjCLifetime()) {
12485     case Qualifiers::OCL_None:
12486     case Qualifiers::OCL_ExplicitNone:
12487     case Qualifiers::OCL_Autoreleasing:
12488       break;
12489 
12490     case Qualifiers::OCL_Weak:
12491     case Qualifiers::OCL_Strong:
12492       setFunctionHasBranchProtectedScope();
12493       break;
12494     }
12495   }
12496 
12497   if (var->hasLocalStorage() &&
12498       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
12499     setFunctionHasBranchProtectedScope();
12500 
12501   // Warn about externally-visible variables being defined without a
12502   // prior declaration.  We only want to do this for global
12503   // declarations, but we also specifically need to avoid doing it for
12504   // class members because the linkage of an anonymous class can
12505   // change if it's later given a typedef name.
12506   if (var->isThisDeclarationADefinition() &&
12507       var->getDeclContext()->getRedeclContext()->isFileContext() &&
12508       var->isExternallyVisible() && var->hasLinkage() &&
12509       !var->isInline() && !var->getDescribedVarTemplate() &&
12510       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
12511       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
12512                                   var->getLocation())) {
12513     // Find a previous declaration that's not a definition.
12514     VarDecl *prev = var->getPreviousDecl();
12515     while (prev && prev->isThisDeclarationADefinition())
12516       prev = prev->getPreviousDecl();
12517 
12518     if (!prev) {
12519       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
12520       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
12521           << /* variable */ 0;
12522     }
12523   }
12524 
12525   // Cache the result of checking for constant initialization.
12526   Optional<bool> CacheHasConstInit;
12527   const Expr *CacheCulprit = nullptr;
12528   auto checkConstInit = [&]() mutable {
12529     if (!CacheHasConstInit)
12530       CacheHasConstInit = var->getInit()->isConstantInitializer(
12531             Context, var->getType()->isReferenceType(), &CacheCulprit);
12532     return *CacheHasConstInit;
12533   };
12534 
12535   if (var->getTLSKind() == VarDecl::TLS_Static) {
12536     if (var->getType().isDestructedType()) {
12537       // GNU C++98 edits for __thread, [basic.start.term]p3:
12538       //   The type of an object with thread storage duration shall not
12539       //   have a non-trivial destructor.
12540       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
12541       if (getLangOpts().CPlusPlus11)
12542         Diag(var->getLocation(), diag::note_use_thread_local);
12543     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
12544       if (!checkConstInit()) {
12545         // GNU C++98 edits for __thread, [basic.start.init]p4:
12546         //   An object of thread storage duration shall not require dynamic
12547         //   initialization.
12548         // FIXME: Need strict checking here.
12549         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
12550           << CacheCulprit->getSourceRange();
12551         if (getLangOpts().CPlusPlus11)
12552           Diag(var->getLocation(), diag::note_use_thread_local);
12553       }
12554     }
12555   }
12556 
12557   // Apply section attributes and pragmas to global variables.
12558   bool GlobalStorage = var->hasGlobalStorage();
12559   if (GlobalStorage && var->isThisDeclarationADefinition() &&
12560       !inTemplateInstantiation()) {
12561     PragmaStack<StringLiteral *> *Stack = nullptr;
12562     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
12563     if (var->getType().isConstQualified())
12564       Stack = &ConstSegStack;
12565     else if (!var->getInit()) {
12566       Stack = &BSSSegStack;
12567       SectionFlags |= ASTContext::PSF_Write;
12568     } else {
12569       Stack = &DataSegStack;
12570       SectionFlags |= ASTContext::PSF_Write;
12571     }
12572     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>())
12573       var->addAttr(SectionAttr::CreateImplicit(
12574           Context, Stack->CurrentValue->getString(),
12575           Stack->CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
12576           SectionAttr::Declspec_allocate));
12577     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
12578       if (UnifySection(SA->getName(), SectionFlags, var))
12579         var->dropAttr<SectionAttr>();
12580 
12581     // Apply the init_seg attribute if this has an initializer.  If the
12582     // initializer turns out to not be dynamic, we'll end up ignoring this
12583     // attribute.
12584     if (CurInitSeg && var->getInit())
12585       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
12586                                                CurInitSegLoc,
12587                                                AttributeCommonInfo::AS_Pragma));
12588   }
12589 
12590   // All the following checks are C++ only.
12591   if (!getLangOpts().CPlusPlus) {
12592       // If this variable must be emitted, add it as an initializer for the
12593       // current module.
12594      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12595        Context.addModuleInitializer(ModuleScopes.back().Module, var);
12596      return;
12597   }
12598 
12599   if (auto *DD = dyn_cast<DecompositionDecl>(var))
12600     CheckCompleteDecompositionDeclaration(DD);
12601 
12602   QualType type = var->getType();
12603   if (type->isDependentType()) return;
12604 
12605   if (var->hasAttr<BlocksAttr>())
12606     getCurFunction()->addByrefBlockVar(var);
12607 
12608   Expr *Init = var->getInit();
12609   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
12610   QualType baseType = Context.getBaseElementType(type);
12611 
12612   if (Init && !Init->isValueDependent()) {
12613     if (var->isConstexpr()) {
12614       SmallVector<PartialDiagnosticAt, 8> Notes;
12615       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
12616         SourceLocation DiagLoc = var->getLocation();
12617         // If the note doesn't add any useful information other than a source
12618         // location, fold it into the primary diagnostic.
12619         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12620               diag::note_invalid_subexpr_in_const_expr) {
12621           DiagLoc = Notes[0].first;
12622           Notes.clear();
12623         }
12624         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
12625           << var << Init->getSourceRange();
12626         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
12627           Diag(Notes[I].first, Notes[I].second);
12628       }
12629     } else if (var->mightBeUsableInConstantExpressions(Context)) {
12630       // Check whether the initializer of a const variable of integral or
12631       // enumeration type is an ICE now, since we can't tell whether it was
12632       // initialized by a constant expression if we check later.
12633       var->checkInitIsICE();
12634     }
12635 
12636     // Don't emit further diagnostics about constexpr globals since they
12637     // were just diagnosed.
12638     if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) {
12639       // FIXME: Need strict checking in C++03 here.
12640       bool DiagErr = getLangOpts().CPlusPlus11
12641           ? !var->checkInitIsICE() : !checkConstInit();
12642       if (DiagErr) {
12643         auto *Attr = var->getAttr<ConstInitAttr>();
12644         Diag(var->getLocation(), diag::err_require_constant_init_failed)
12645           << Init->getSourceRange();
12646         Diag(Attr->getLocation(),
12647              diag::note_declared_required_constant_init_here)
12648             << Attr->getRange() << Attr->isConstinit();
12649         if (getLangOpts().CPlusPlus11) {
12650           APValue Value;
12651           SmallVector<PartialDiagnosticAt, 8> Notes;
12652           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
12653           for (auto &it : Notes)
12654             Diag(it.first, it.second);
12655         } else {
12656           Diag(CacheCulprit->getExprLoc(),
12657                diag::note_invalid_subexpr_in_const_expr)
12658               << CacheCulprit->getSourceRange();
12659         }
12660       }
12661     }
12662     else if (!var->isConstexpr() && IsGlobal &&
12663              !getDiagnostics().isIgnored(diag::warn_global_constructor,
12664                                     var->getLocation())) {
12665       // Warn about globals which don't have a constant initializer.  Don't
12666       // warn about globals with a non-trivial destructor because we already
12667       // warned about them.
12668       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
12669       if (!(RD && !RD->hasTrivialDestructor())) {
12670         if (!checkConstInit())
12671           Diag(var->getLocation(), diag::warn_global_constructor)
12672             << Init->getSourceRange();
12673       }
12674     }
12675   }
12676 
12677   // Require the destructor.
12678   if (const RecordType *recordType = baseType->getAs<RecordType>())
12679     FinalizeVarWithDestructor(var, recordType);
12680 
12681   // If this variable must be emitted, add it as an initializer for the current
12682   // module.
12683   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12684     Context.addModuleInitializer(ModuleScopes.back().Module, var);
12685 }
12686 
12687 /// Determines if a variable's alignment is dependent.
12688 static bool hasDependentAlignment(VarDecl *VD) {
12689   if (VD->getType()->isDependentType())
12690     return true;
12691   for (auto *I : VD->specific_attrs<AlignedAttr>())
12692     if (I->isAlignmentDependent())
12693       return true;
12694   return false;
12695 }
12696 
12697 /// Check if VD needs to be dllexport/dllimport due to being in a
12698 /// dllexport/import function.
12699 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
12700   assert(VD->isStaticLocal());
12701 
12702   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12703 
12704   // Find outermost function when VD is in lambda function.
12705   while (FD && !getDLLAttr(FD) &&
12706          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
12707          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
12708     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
12709   }
12710 
12711   if (!FD)
12712     return;
12713 
12714   // Static locals inherit dll attributes from their function.
12715   if (Attr *A = getDLLAttr(FD)) {
12716     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
12717     NewAttr->setInherited(true);
12718     VD->addAttr(NewAttr);
12719   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
12720     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
12721     NewAttr->setInherited(true);
12722     VD->addAttr(NewAttr);
12723 
12724     // Export this function to enforce exporting this static variable even
12725     // if it is not used in this compilation unit.
12726     if (!FD->hasAttr<DLLExportAttr>())
12727       FD->addAttr(NewAttr);
12728 
12729   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
12730     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
12731     NewAttr->setInherited(true);
12732     VD->addAttr(NewAttr);
12733   }
12734 }
12735 
12736 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
12737 /// any semantic actions necessary after any initializer has been attached.
12738 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
12739   // Note that we are no longer parsing the initializer for this declaration.
12740   ParsingInitForAutoVars.erase(ThisDecl);
12741 
12742   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
12743   if (!VD)
12744     return;
12745 
12746   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
12747   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
12748       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
12749     if (PragmaClangBSSSection.Valid)
12750       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
12751           Context, PragmaClangBSSSection.SectionName,
12752           PragmaClangBSSSection.PragmaLocation,
12753           AttributeCommonInfo::AS_Pragma));
12754     if (PragmaClangDataSection.Valid)
12755       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
12756           Context, PragmaClangDataSection.SectionName,
12757           PragmaClangDataSection.PragmaLocation,
12758           AttributeCommonInfo::AS_Pragma));
12759     if (PragmaClangRodataSection.Valid)
12760       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
12761           Context, PragmaClangRodataSection.SectionName,
12762           PragmaClangRodataSection.PragmaLocation,
12763           AttributeCommonInfo::AS_Pragma));
12764     if (PragmaClangRelroSection.Valid)
12765       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
12766           Context, PragmaClangRelroSection.SectionName,
12767           PragmaClangRelroSection.PragmaLocation,
12768           AttributeCommonInfo::AS_Pragma));
12769   }
12770 
12771   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
12772     for (auto *BD : DD->bindings()) {
12773       FinalizeDeclaration(BD);
12774     }
12775   }
12776 
12777   checkAttributesAfterMerging(*this, *VD);
12778 
12779   // Perform TLS alignment check here after attributes attached to the variable
12780   // which may affect the alignment have been processed. Only perform the check
12781   // if the target has a maximum TLS alignment (zero means no constraints).
12782   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
12783     // Protect the check so that it's not performed on dependent types and
12784     // dependent alignments (we can't determine the alignment in that case).
12785     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
12786         !VD->isInvalidDecl()) {
12787       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
12788       if (Context.getDeclAlign(VD) > MaxAlignChars) {
12789         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
12790           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
12791           << (unsigned)MaxAlignChars.getQuantity();
12792       }
12793     }
12794   }
12795 
12796   if (VD->isStaticLocal()) {
12797     CheckStaticLocalForDllExport(VD);
12798 
12799     if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
12800       // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
12801       // function, only __shared__ variables or variables without any device
12802       // memory qualifiers may be declared with static storage class.
12803       // Note: It is unclear how a function-scope non-const static variable
12804       // without device memory qualifier is implemented, therefore only static
12805       // const variable without device memory qualifier is allowed.
12806       [&]() {
12807         if (!getLangOpts().CUDA)
12808           return;
12809         if (VD->hasAttr<CUDASharedAttr>())
12810           return;
12811         if (VD->getType().isConstQualified() &&
12812             !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
12813           return;
12814         if (CUDADiagIfDeviceCode(VD->getLocation(),
12815                                  diag::err_device_static_local_var)
12816             << CurrentCUDATarget())
12817           VD->setInvalidDecl();
12818       }();
12819     }
12820   }
12821 
12822   // Perform check for initializers of device-side global variables.
12823   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
12824   // 7.5). We must also apply the same checks to all __shared__
12825   // variables whether they are local or not. CUDA also allows
12826   // constant initializers for __constant__ and __device__ variables.
12827   if (getLangOpts().CUDA)
12828     checkAllowedCUDAInitializer(VD);
12829 
12830   // Grab the dllimport or dllexport attribute off of the VarDecl.
12831   const InheritableAttr *DLLAttr = getDLLAttr(VD);
12832 
12833   // Imported static data members cannot be defined out-of-line.
12834   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
12835     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
12836         VD->isThisDeclarationADefinition()) {
12837       // We allow definitions of dllimport class template static data members
12838       // with a warning.
12839       CXXRecordDecl *Context =
12840         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
12841       bool IsClassTemplateMember =
12842           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
12843           Context->getDescribedClassTemplate();
12844 
12845       Diag(VD->getLocation(),
12846            IsClassTemplateMember
12847                ? diag::warn_attribute_dllimport_static_field_definition
12848                : diag::err_attribute_dllimport_static_field_definition);
12849       Diag(IA->getLocation(), diag::note_attribute);
12850       if (!IsClassTemplateMember)
12851         VD->setInvalidDecl();
12852     }
12853   }
12854 
12855   // dllimport/dllexport variables cannot be thread local, their TLS index
12856   // isn't exported with the variable.
12857   if (DLLAttr && VD->getTLSKind()) {
12858     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12859     if (F && getDLLAttr(F)) {
12860       assert(VD->isStaticLocal());
12861       // But if this is a static local in a dlimport/dllexport function, the
12862       // function will never be inlined, which means the var would never be
12863       // imported, so having it marked import/export is safe.
12864     } else {
12865       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
12866                                                                     << DLLAttr;
12867       VD->setInvalidDecl();
12868     }
12869   }
12870 
12871   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
12872     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
12873       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
12874       VD->dropAttr<UsedAttr>();
12875     }
12876   }
12877 
12878   const DeclContext *DC = VD->getDeclContext();
12879   // If there's a #pragma GCC visibility in scope, and this isn't a class
12880   // member, set the visibility of this variable.
12881   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
12882     AddPushedVisibilityAttribute(VD);
12883 
12884   // FIXME: Warn on unused var template partial specializations.
12885   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
12886     MarkUnusedFileScopedDecl(VD);
12887 
12888   // Now we have parsed the initializer and can update the table of magic
12889   // tag values.
12890   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
12891       !VD->getType()->isIntegralOrEnumerationType())
12892     return;
12893 
12894   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
12895     const Expr *MagicValueExpr = VD->getInit();
12896     if (!MagicValueExpr) {
12897       continue;
12898     }
12899     llvm::APSInt MagicValueInt;
12900     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
12901       Diag(I->getRange().getBegin(),
12902            diag::err_type_tag_for_datatype_not_ice)
12903         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12904       continue;
12905     }
12906     if (MagicValueInt.getActiveBits() > 64) {
12907       Diag(I->getRange().getBegin(),
12908            diag::err_type_tag_for_datatype_too_large)
12909         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12910       continue;
12911     }
12912     uint64_t MagicValue = MagicValueInt.getZExtValue();
12913     RegisterTypeTagForDatatype(I->getArgumentKind(),
12914                                MagicValue,
12915                                I->getMatchingCType(),
12916                                I->getLayoutCompatible(),
12917                                I->getMustBeNull());
12918   }
12919 }
12920 
12921 static bool hasDeducedAuto(DeclaratorDecl *DD) {
12922   auto *VD = dyn_cast<VarDecl>(DD);
12923   return VD && !VD->getType()->hasAutoForTrailingReturnType();
12924 }
12925 
12926 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
12927                                                    ArrayRef<Decl *> Group) {
12928   SmallVector<Decl*, 8> Decls;
12929 
12930   if (DS.isTypeSpecOwned())
12931     Decls.push_back(DS.getRepAsDecl());
12932 
12933   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
12934   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
12935   bool DiagnosedMultipleDecomps = false;
12936   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
12937   bool DiagnosedNonDeducedAuto = false;
12938 
12939   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12940     if (Decl *D = Group[i]) {
12941       // For declarators, there are some additional syntactic-ish checks we need
12942       // to perform.
12943       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
12944         if (!FirstDeclaratorInGroup)
12945           FirstDeclaratorInGroup = DD;
12946         if (!FirstDecompDeclaratorInGroup)
12947           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
12948         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
12949             !hasDeducedAuto(DD))
12950           FirstNonDeducedAutoInGroup = DD;
12951 
12952         if (FirstDeclaratorInGroup != DD) {
12953           // A decomposition declaration cannot be combined with any other
12954           // declaration in the same group.
12955           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
12956             Diag(FirstDecompDeclaratorInGroup->getLocation(),
12957                  diag::err_decomp_decl_not_alone)
12958                 << FirstDeclaratorInGroup->getSourceRange()
12959                 << DD->getSourceRange();
12960             DiagnosedMultipleDecomps = true;
12961           }
12962 
12963           // A declarator that uses 'auto' in any way other than to declare a
12964           // variable with a deduced type cannot be combined with any other
12965           // declarator in the same group.
12966           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
12967             Diag(FirstNonDeducedAutoInGroup->getLocation(),
12968                  diag::err_auto_non_deduced_not_alone)
12969                 << FirstNonDeducedAutoInGroup->getType()
12970                        ->hasAutoForTrailingReturnType()
12971                 << FirstDeclaratorInGroup->getSourceRange()
12972                 << DD->getSourceRange();
12973             DiagnosedNonDeducedAuto = true;
12974           }
12975         }
12976       }
12977 
12978       Decls.push_back(D);
12979     }
12980   }
12981 
12982   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
12983     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
12984       handleTagNumbering(Tag, S);
12985       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
12986           getLangOpts().CPlusPlus)
12987         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
12988     }
12989   }
12990 
12991   return BuildDeclaratorGroup(Decls);
12992 }
12993 
12994 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
12995 /// group, performing any necessary semantic checking.
12996 Sema::DeclGroupPtrTy
12997 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
12998   // C++14 [dcl.spec.auto]p7: (DR1347)
12999   //   If the type that replaces the placeholder type is not the same in each
13000   //   deduction, the program is ill-formed.
13001   if (Group.size() > 1) {
13002     QualType Deduced;
13003     VarDecl *DeducedDecl = nullptr;
13004     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13005       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13006       if (!D || D->isInvalidDecl())
13007         break;
13008       DeducedType *DT = D->getType()->getContainedDeducedType();
13009       if (!DT || DT->getDeducedType().isNull())
13010         continue;
13011       if (Deduced.isNull()) {
13012         Deduced = DT->getDeducedType();
13013         DeducedDecl = D;
13014       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13015         auto *AT = dyn_cast<AutoType>(DT);
13016         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13017              diag::err_auto_different_deductions)
13018           << (AT ? (unsigned)AT->getKeyword() : 3)
13019           << Deduced << DeducedDecl->getDeclName()
13020           << DT->getDeducedType() << D->getDeclName()
13021           << DeducedDecl->getInit()->getSourceRange()
13022           << D->getInit()->getSourceRange();
13023         D->setInvalidDecl();
13024         break;
13025       }
13026     }
13027   }
13028 
13029   ActOnDocumentableDecls(Group);
13030 
13031   return DeclGroupPtrTy::make(
13032       DeclGroupRef::Create(Context, Group.data(), Group.size()));
13033 }
13034 
13035 void Sema::ActOnDocumentableDecl(Decl *D) {
13036   ActOnDocumentableDecls(D);
13037 }
13038 
13039 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13040   // Don't parse the comment if Doxygen diagnostics are ignored.
13041   if (Group.empty() || !Group[0])
13042     return;
13043 
13044   if (Diags.isIgnored(diag::warn_doc_param_not_found,
13045                       Group[0]->getLocation()) &&
13046       Diags.isIgnored(diag::warn_unknown_comment_command_name,
13047                       Group[0]->getLocation()))
13048     return;
13049 
13050   if (Group.size() >= 2) {
13051     // This is a decl group.  Normally it will contain only declarations
13052     // produced from declarator list.  But in case we have any definitions or
13053     // additional declaration references:
13054     //   'typedef struct S {} S;'
13055     //   'typedef struct S *S;'
13056     //   'struct S *pS;'
13057     // FinalizeDeclaratorGroup adds these as separate declarations.
13058     Decl *MaybeTagDecl = Group[0];
13059     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13060       Group = Group.slice(1);
13061     }
13062   }
13063 
13064   // FIMXE: We assume every Decl in the group is in the same file.
13065   // This is false when preprocessor constructs the group from decls in
13066   // different files (e. g. macros or #include).
13067   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13068 }
13069 
13070 /// Common checks for a parameter-declaration that should apply to both function
13071 /// parameters and non-type template parameters.
13072 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13073   // Check that there are no default arguments inside the type of this
13074   // parameter.
13075   if (getLangOpts().CPlusPlus)
13076     CheckExtraCXXDefaultArguments(D);
13077 
13078   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13079   if (D.getCXXScopeSpec().isSet()) {
13080     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13081       << D.getCXXScopeSpec().getRange();
13082   }
13083 
13084   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13085   // simple identifier except [...irrelevant cases...].
13086   switch (D.getName().getKind()) {
13087   case UnqualifiedIdKind::IK_Identifier:
13088     break;
13089 
13090   case UnqualifiedIdKind::IK_OperatorFunctionId:
13091   case UnqualifiedIdKind::IK_ConversionFunctionId:
13092   case UnqualifiedIdKind::IK_LiteralOperatorId:
13093   case UnqualifiedIdKind::IK_ConstructorName:
13094   case UnqualifiedIdKind::IK_DestructorName:
13095   case UnqualifiedIdKind::IK_ImplicitSelfParam:
13096   case UnqualifiedIdKind::IK_DeductionGuideName:
13097     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13098       << GetNameForDeclarator(D).getName();
13099     break;
13100 
13101   case UnqualifiedIdKind::IK_TemplateId:
13102   case UnqualifiedIdKind::IK_ConstructorTemplateId:
13103     // GetNameForDeclarator would not produce a useful name in this case.
13104     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13105     break;
13106   }
13107 }
13108 
13109 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13110 /// to introduce parameters into function prototype scope.
13111 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13112   const DeclSpec &DS = D.getDeclSpec();
13113 
13114   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13115 
13116   // C++03 [dcl.stc]p2 also permits 'auto'.
13117   StorageClass SC = SC_None;
13118   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13119     SC = SC_Register;
13120     // In C++11, the 'register' storage class specifier is deprecated.
13121     // In C++17, it is not allowed, but we tolerate it as an extension.
13122     if (getLangOpts().CPlusPlus11) {
13123       Diag(DS.getStorageClassSpecLoc(),
13124            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13125                                      : diag::warn_deprecated_register)
13126         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13127     }
13128   } else if (getLangOpts().CPlusPlus &&
13129              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13130     SC = SC_Auto;
13131   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13132     Diag(DS.getStorageClassSpecLoc(),
13133          diag::err_invalid_storage_class_in_func_decl);
13134     D.getMutableDeclSpec().ClearStorageClassSpecs();
13135   }
13136 
13137   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13138     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13139       << DeclSpec::getSpecifierName(TSCS);
13140   if (DS.isInlineSpecified())
13141     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13142         << getLangOpts().CPlusPlus17;
13143   if (DS.hasConstexprSpecifier())
13144     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13145         << 0 << D.getDeclSpec().getConstexprSpecifier();
13146 
13147   DiagnoseFunctionSpecifiers(DS);
13148 
13149   CheckFunctionOrTemplateParamDeclarator(S, D);
13150 
13151   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13152   QualType parmDeclType = TInfo->getType();
13153 
13154   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13155   IdentifierInfo *II = D.getIdentifier();
13156   if (II) {
13157     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13158                    ForVisibleRedeclaration);
13159     LookupName(R, S);
13160     if (R.isSingleResult()) {
13161       NamedDecl *PrevDecl = R.getFoundDecl();
13162       if (PrevDecl->isTemplateParameter()) {
13163         // Maybe we will complain about the shadowed template parameter.
13164         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13165         // Just pretend that we didn't see the previous declaration.
13166         PrevDecl = nullptr;
13167       } else if (S->isDeclScope(PrevDecl)) {
13168         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13169         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13170 
13171         // Recover by removing the name
13172         II = nullptr;
13173         D.SetIdentifier(nullptr, D.getIdentifierLoc());
13174         D.setInvalidType(true);
13175       }
13176     }
13177   }
13178 
13179   // Temporarily put parameter variables in the translation unit, not
13180   // the enclosing context.  This prevents them from accidentally
13181   // looking like class members in C++.
13182   ParmVarDecl *New =
13183       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13184                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13185 
13186   if (D.isInvalidType())
13187     New->setInvalidDecl();
13188 
13189   assert(S->isFunctionPrototypeScope());
13190   assert(S->getFunctionPrototypeDepth() >= 1);
13191   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13192                     S->getNextFunctionPrototypeIndex());
13193 
13194   // Add the parameter declaration into this scope.
13195   S->AddDecl(New);
13196   if (II)
13197     IdResolver.AddDecl(New);
13198 
13199   ProcessDeclAttributes(S, New, D);
13200 
13201   if (D.getDeclSpec().isModulePrivateSpecified())
13202     Diag(New->getLocation(), diag::err_module_private_local)
13203       << 1 << New->getDeclName()
13204       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13205       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13206 
13207   if (New->hasAttr<BlocksAttr>()) {
13208     Diag(New->getLocation(), diag::err_block_on_nonlocal);
13209   }
13210 
13211   if (getLangOpts().OpenCL)
13212     deduceOpenCLAddressSpace(New);
13213 
13214   return New;
13215 }
13216 
13217 /// Synthesizes a variable for a parameter arising from a
13218 /// typedef.
13219 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13220                                               SourceLocation Loc,
13221                                               QualType T) {
13222   /* FIXME: setting StartLoc == Loc.
13223      Would it be worth to modify callers so as to provide proper source
13224      location for the unnamed parameters, embedding the parameter's type? */
13225   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13226                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
13227                                            SC_None, nullptr);
13228   Param->setImplicit();
13229   return Param;
13230 }
13231 
13232 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13233   // Don't diagnose unused-parameter errors in template instantiations; we
13234   // will already have done so in the template itself.
13235   if (inTemplateInstantiation())
13236     return;
13237 
13238   for (const ParmVarDecl *Parameter : Parameters) {
13239     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13240         !Parameter->hasAttr<UnusedAttr>()) {
13241       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13242         << Parameter->getDeclName();
13243     }
13244   }
13245 }
13246 
13247 void Sema::DiagnoseSizeOfParametersAndReturnValue(
13248     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13249   if (LangOpts.NumLargeByValueCopy == 0) // No check.
13250     return;
13251 
13252   // Warn if the return value is pass-by-value and larger than the specified
13253   // threshold.
13254   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13255     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13256     if (Size > LangOpts.NumLargeByValueCopy)
13257       Diag(D->getLocation(), diag::warn_return_value_size)
13258           << D->getDeclName() << Size;
13259   }
13260 
13261   // Warn if any parameter is pass-by-value and larger than the specified
13262   // threshold.
13263   for (const ParmVarDecl *Parameter : Parameters) {
13264     QualType T = Parameter->getType();
13265     if (T->isDependentType() || !T.isPODType(Context))
13266       continue;
13267     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13268     if (Size > LangOpts.NumLargeByValueCopy)
13269       Diag(Parameter->getLocation(), diag::warn_parameter_size)
13270           << Parameter->getDeclName() << Size;
13271   }
13272 }
13273 
13274 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13275                                   SourceLocation NameLoc, IdentifierInfo *Name,
13276                                   QualType T, TypeSourceInfo *TSInfo,
13277                                   StorageClass SC) {
13278   // In ARC, infer a lifetime qualifier for appropriate parameter types.
13279   if (getLangOpts().ObjCAutoRefCount &&
13280       T.getObjCLifetime() == Qualifiers::OCL_None &&
13281       T->isObjCLifetimeType()) {
13282 
13283     Qualifiers::ObjCLifetime lifetime;
13284 
13285     // Special cases for arrays:
13286     //   - if it's const, use __unsafe_unretained
13287     //   - otherwise, it's an error
13288     if (T->isArrayType()) {
13289       if (!T.isConstQualified()) {
13290         if (DelayedDiagnostics.shouldDelayDiagnostics())
13291           DelayedDiagnostics.add(
13292               sema::DelayedDiagnostic::makeForbiddenType(
13293               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13294         else
13295           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13296               << TSInfo->getTypeLoc().getSourceRange();
13297       }
13298       lifetime = Qualifiers::OCL_ExplicitNone;
13299     } else {
13300       lifetime = T->getObjCARCImplicitLifetime();
13301     }
13302     T = Context.getLifetimeQualifiedType(T, lifetime);
13303   }
13304 
13305   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13306                                          Context.getAdjustedParameterType(T),
13307                                          TSInfo, SC, nullptr);
13308 
13309   // Make a note if we created a new pack in the scope of a lambda, so that
13310   // we know that references to that pack must also be expanded within the
13311   // lambda scope.
13312   if (New->isParameterPack())
13313     if (auto *LSI = getEnclosingLambda())
13314       LSI->LocalPacks.push_back(New);
13315 
13316   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13317       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13318     checkNonTrivialCUnion(New->getType(), New->getLocation(),
13319                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13320 
13321   // Parameters can not be abstract class types.
13322   // For record types, this is done by the AbstractClassUsageDiagnoser once
13323   // the class has been completely parsed.
13324   if (!CurContext->isRecord() &&
13325       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13326                              AbstractParamType))
13327     New->setInvalidDecl();
13328 
13329   // Parameter declarators cannot be interface types. All ObjC objects are
13330   // passed by reference.
13331   if (T->isObjCObjectType()) {
13332     SourceLocation TypeEndLoc =
13333         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13334     Diag(NameLoc,
13335          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13336       << FixItHint::CreateInsertion(TypeEndLoc, "*");
13337     T = Context.getObjCObjectPointerType(T);
13338     New->setType(T);
13339   }
13340 
13341   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13342   // duration shall not be qualified by an address-space qualifier."
13343   // Since all parameters have automatic store duration, they can not have
13344   // an address space.
13345   if (T.getAddressSpace() != LangAS::Default &&
13346       // OpenCL allows function arguments declared to be an array of a type
13347       // to be qualified with an address space.
13348       !(getLangOpts().OpenCL &&
13349         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13350     Diag(NameLoc, diag::err_arg_with_address_space);
13351     New->setInvalidDecl();
13352   }
13353 
13354   return New;
13355 }
13356 
13357 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
13358                                            SourceLocation LocAfterDecls) {
13359   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
13360 
13361   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
13362   // for a K&R function.
13363   if (!FTI.hasPrototype) {
13364     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
13365       --i;
13366       if (FTI.Params[i].Param == nullptr) {
13367         SmallString<256> Code;
13368         llvm::raw_svector_ostream(Code)
13369             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
13370         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
13371             << FTI.Params[i].Ident
13372             << FixItHint::CreateInsertion(LocAfterDecls, Code);
13373 
13374         // Implicitly declare the argument as type 'int' for lack of a better
13375         // type.
13376         AttributeFactory attrs;
13377         DeclSpec DS(attrs);
13378         const char* PrevSpec; // unused
13379         unsigned DiagID; // unused
13380         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
13381                            DiagID, Context.getPrintingPolicy());
13382         // Use the identifier location for the type source range.
13383         DS.SetRangeStart(FTI.Params[i].IdentLoc);
13384         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
13385         Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
13386         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
13387         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
13388       }
13389     }
13390   }
13391 }
13392 
13393 Decl *
13394 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
13395                               MultiTemplateParamsArg TemplateParameterLists,
13396                               SkipBodyInfo *SkipBody) {
13397   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
13398   assert(D.isFunctionDeclarator() && "Not a function declarator!");
13399   Scope *ParentScope = FnBodyScope->getParent();
13400 
13401   D.setFunctionDefinitionKind(FDK_Definition);
13402   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
13403   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
13404 }
13405 
13406 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
13407   Consumer.HandleInlineFunctionDefinition(D);
13408 }
13409 
13410 static bool
13411 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
13412                                 const FunctionDecl *&PossiblePrototype) {
13413   // Don't warn about invalid declarations.
13414   if (FD->isInvalidDecl())
13415     return false;
13416 
13417   // Or declarations that aren't global.
13418   if (!FD->isGlobal())
13419     return false;
13420 
13421   // Don't warn about C++ member functions.
13422   if (isa<CXXMethodDecl>(FD))
13423     return false;
13424 
13425   // Don't warn about 'main'.
13426   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
13427     if (IdentifierInfo *II = FD->getIdentifier())
13428       if (II->isStr("main"))
13429         return false;
13430 
13431   // Don't warn about inline functions.
13432   if (FD->isInlined())
13433     return false;
13434 
13435   // Don't warn about function templates.
13436   if (FD->getDescribedFunctionTemplate())
13437     return false;
13438 
13439   // Don't warn about function template specializations.
13440   if (FD->isFunctionTemplateSpecialization())
13441     return false;
13442 
13443   // Don't warn for OpenCL kernels.
13444   if (FD->hasAttr<OpenCLKernelAttr>())
13445     return false;
13446 
13447   // Don't warn on explicitly deleted functions.
13448   if (FD->isDeleted())
13449     return false;
13450 
13451   for (const FunctionDecl *Prev = FD->getPreviousDecl();
13452        Prev; Prev = Prev->getPreviousDecl()) {
13453     // Ignore any declarations that occur in function or method
13454     // scope, because they aren't visible from the header.
13455     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
13456       continue;
13457 
13458     PossiblePrototype = Prev;
13459     return Prev->getType()->isFunctionNoProtoType();
13460   }
13461 
13462   return true;
13463 }
13464 
13465 void
13466 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
13467                                    const FunctionDecl *EffectiveDefinition,
13468                                    SkipBodyInfo *SkipBody) {
13469   const FunctionDecl *Definition = EffectiveDefinition;
13470   if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
13471     // If this is a friend function defined in a class template, it does not
13472     // have a body until it is used, nevertheless it is a definition, see
13473     // [temp.inst]p2:
13474     //
13475     // ... for the purpose of determining whether an instantiated redeclaration
13476     // is valid according to [basic.def.odr] and [class.mem], a declaration that
13477     // corresponds to a definition in the template is considered to be a
13478     // definition.
13479     //
13480     // The following code must produce redefinition error:
13481     //
13482     //     template<typename T> struct C20 { friend void func_20() {} };
13483     //     C20<int> c20i;
13484     //     void func_20() {}
13485     //
13486     for (auto I : FD->redecls()) {
13487       if (I != FD && !I->isInvalidDecl() &&
13488           I->getFriendObjectKind() != Decl::FOK_None) {
13489         if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
13490           if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
13491             // A merged copy of the same function, instantiated as a member of
13492             // the same class, is OK.
13493             if (declaresSameEntity(OrigFD, Original) &&
13494                 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
13495                                    cast<Decl>(FD->getLexicalDeclContext())))
13496               continue;
13497           }
13498 
13499           if (Original->isThisDeclarationADefinition()) {
13500             Definition = I;
13501             break;
13502           }
13503         }
13504       }
13505     }
13506   }
13507 
13508   if (!Definition)
13509     // Similar to friend functions a friend function template may be a
13510     // definition and do not have a body if it is instantiated in a class
13511     // template.
13512     if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
13513       for (auto I : FTD->redecls()) {
13514         auto D = cast<FunctionTemplateDecl>(I);
13515         if (D != FTD) {
13516           assert(!D->isThisDeclarationADefinition() &&
13517                  "More than one definition in redeclaration chain");
13518           if (D->getFriendObjectKind() != Decl::FOK_None)
13519             if (FunctionTemplateDecl *FT =
13520                                        D->getInstantiatedFromMemberTemplate()) {
13521               if (FT->isThisDeclarationADefinition()) {
13522                 Definition = D->getTemplatedDecl();
13523                 break;
13524               }
13525             }
13526         }
13527       }
13528     }
13529 
13530   if (!Definition)
13531     return;
13532 
13533   if (canRedefineFunction(Definition, getLangOpts()))
13534     return;
13535 
13536   // Don't emit an error when this is redefinition of a typo-corrected
13537   // definition.
13538   if (TypoCorrectedFunctionDefinitions.count(Definition))
13539     return;
13540 
13541   // If we don't have a visible definition of the function, and it's inline or
13542   // a template, skip the new definition.
13543   if (SkipBody && !hasVisibleDefinition(Definition) &&
13544       (Definition->getFormalLinkage() == InternalLinkage ||
13545        Definition->isInlined() ||
13546        Definition->getDescribedFunctionTemplate() ||
13547        Definition->getNumTemplateParameterLists())) {
13548     SkipBody->ShouldSkip = true;
13549     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
13550     if (auto *TD = Definition->getDescribedFunctionTemplate())
13551       makeMergedDefinitionVisible(TD);
13552     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
13553     return;
13554   }
13555 
13556   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
13557       Definition->getStorageClass() == SC_Extern)
13558     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
13559         << FD->getDeclName() << getLangOpts().CPlusPlus;
13560   else
13561     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
13562 
13563   Diag(Definition->getLocation(), diag::note_previous_definition);
13564   FD->setInvalidDecl();
13565 }
13566 
13567 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
13568                                    Sema &S) {
13569   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
13570 
13571   LambdaScopeInfo *LSI = S.PushLambdaScope();
13572   LSI->CallOperator = CallOperator;
13573   LSI->Lambda = LambdaClass;
13574   LSI->ReturnType = CallOperator->getReturnType();
13575   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
13576 
13577   if (LCD == LCD_None)
13578     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
13579   else if (LCD == LCD_ByCopy)
13580     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
13581   else if (LCD == LCD_ByRef)
13582     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
13583   DeclarationNameInfo DNI = CallOperator->getNameInfo();
13584 
13585   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
13586   LSI->Mutable = !CallOperator->isConst();
13587 
13588   // Add the captures to the LSI so they can be noted as already
13589   // captured within tryCaptureVar.
13590   auto I = LambdaClass->field_begin();
13591   for (const auto &C : LambdaClass->captures()) {
13592     if (C.capturesVariable()) {
13593       VarDecl *VD = C.getCapturedVar();
13594       if (VD->isInitCapture())
13595         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
13596       QualType CaptureType = VD->getType();
13597       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
13598       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
13599           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
13600           /*EllipsisLoc*/C.isPackExpansion()
13601                          ? C.getEllipsisLoc() : SourceLocation(),
13602           CaptureType, /*Invalid*/false);
13603 
13604     } else if (C.capturesThis()) {
13605       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
13606                           C.getCaptureKind() == LCK_StarThis);
13607     } else {
13608       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
13609                              I->getType());
13610     }
13611     ++I;
13612   }
13613 }
13614 
13615 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
13616                                     SkipBodyInfo *SkipBody) {
13617   if (!D) {
13618     // Parsing the function declaration failed in some way. Push on a fake scope
13619     // anyway so we can try to parse the function body.
13620     PushFunctionScope();
13621     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13622     return D;
13623   }
13624 
13625   FunctionDecl *FD = nullptr;
13626 
13627   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
13628     FD = FunTmpl->getTemplatedDecl();
13629   else
13630     FD = cast<FunctionDecl>(D);
13631 
13632   // Do not push if it is a lambda because one is already pushed when building
13633   // the lambda in ActOnStartOfLambdaDefinition().
13634   if (!isLambdaCallOperator(FD))
13635     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13636 
13637   // Check for defining attributes before the check for redefinition.
13638   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
13639     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
13640     FD->dropAttr<AliasAttr>();
13641     FD->setInvalidDecl();
13642   }
13643   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
13644     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
13645     FD->dropAttr<IFuncAttr>();
13646     FD->setInvalidDecl();
13647   }
13648 
13649   // See if this is a redefinition. If 'will have body' is already set, then
13650   // these checks were already performed when it was set.
13651   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
13652     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
13653 
13654     // If we're skipping the body, we're done. Don't enter the scope.
13655     if (SkipBody && SkipBody->ShouldSkip)
13656       return D;
13657   }
13658 
13659   // Mark this function as "will have a body eventually".  This lets users to
13660   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
13661   // this function.
13662   FD->setWillHaveBody();
13663 
13664   // If we are instantiating a generic lambda call operator, push
13665   // a LambdaScopeInfo onto the function stack.  But use the information
13666   // that's already been calculated (ActOnLambdaExpr) to prime the current
13667   // LambdaScopeInfo.
13668   // When the template operator is being specialized, the LambdaScopeInfo,
13669   // has to be properly restored so that tryCaptureVariable doesn't try
13670   // and capture any new variables. In addition when calculating potential
13671   // captures during transformation of nested lambdas, it is necessary to
13672   // have the LSI properly restored.
13673   if (isGenericLambdaCallOperatorSpecialization(FD)) {
13674     assert(inTemplateInstantiation() &&
13675            "There should be an active template instantiation on the stack "
13676            "when instantiating a generic lambda!");
13677     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
13678   } else {
13679     // Enter a new function scope
13680     PushFunctionScope();
13681   }
13682 
13683   // Builtin functions cannot be defined.
13684   if (unsigned BuiltinID = FD->getBuiltinID()) {
13685     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
13686         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
13687       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
13688       FD->setInvalidDecl();
13689     }
13690   }
13691 
13692   // The return type of a function definition must be complete
13693   // (C99 6.9.1p3, C++ [dcl.fct]p6).
13694   QualType ResultType = FD->getReturnType();
13695   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
13696       !FD->isInvalidDecl() &&
13697       RequireCompleteType(FD->getLocation(), ResultType,
13698                           diag::err_func_def_incomplete_result))
13699     FD->setInvalidDecl();
13700 
13701   if (FnBodyScope)
13702     PushDeclContext(FnBodyScope, FD);
13703 
13704   // Check the validity of our function parameters
13705   CheckParmsForFunctionDef(FD->parameters(),
13706                            /*CheckParameterNames=*/true);
13707 
13708   // Add non-parameter declarations already in the function to the current
13709   // scope.
13710   if (FnBodyScope) {
13711     for (Decl *NPD : FD->decls()) {
13712       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
13713       if (!NonParmDecl)
13714         continue;
13715       assert(!isa<ParmVarDecl>(NonParmDecl) &&
13716              "parameters should not be in newly created FD yet");
13717 
13718       // If the decl has a name, make it accessible in the current scope.
13719       if (NonParmDecl->getDeclName())
13720         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
13721 
13722       // Similarly, dive into enums and fish their constants out, making them
13723       // accessible in this scope.
13724       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
13725         for (auto *EI : ED->enumerators())
13726           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
13727       }
13728     }
13729   }
13730 
13731   // Introduce our parameters into the function scope
13732   for (auto Param : FD->parameters()) {
13733     Param->setOwningFunction(FD);
13734 
13735     // If this has an identifier, add it to the scope stack.
13736     if (Param->getIdentifier() && FnBodyScope) {
13737       CheckShadow(FnBodyScope, Param);
13738 
13739       PushOnScopeChains(Param, FnBodyScope);
13740     }
13741   }
13742 
13743   // Ensure that the function's exception specification is instantiated.
13744   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
13745     ResolveExceptionSpec(D->getLocation(), FPT);
13746 
13747   // dllimport cannot be applied to non-inline function definitions.
13748   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
13749       !FD->isTemplateInstantiation()) {
13750     assert(!FD->hasAttr<DLLExportAttr>());
13751     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
13752     FD->setInvalidDecl();
13753     return D;
13754   }
13755   // We want to attach documentation to original Decl (which might be
13756   // a function template).
13757   ActOnDocumentableDecl(D);
13758   if (getCurLexicalContext()->isObjCContainer() &&
13759       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
13760       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
13761     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
13762 
13763   return D;
13764 }
13765 
13766 /// Given the set of return statements within a function body,
13767 /// compute the variables that are subject to the named return value
13768 /// optimization.
13769 ///
13770 /// Each of the variables that is subject to the named return value
13771 /// optimization will be marked as NRVO variables in the AST, and any
13772 /// return statement that has a marked NRVO variable as its NRVO candidate can
13773 /// use the named return value optimization.
13774 ///
13775 /// This function applies a very simplistic algorithm for NRVO: if every return
13776 /// statement in the scope of a variable has the same NRVO candidate, that
13777 /// candidate is an NRVO variable.
13778 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
13779   ReturnStmt **Returns = Scope->Returns.data();
13780 
13781   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
13782     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
13783       if (!NRVOCandidate->isNRVOVariable())
13784         Returns[I]->setNRVOCandidate(nullptr);
13785     }
13786   }
13787 }
13788 
13789 bool Sema::canDelayFunctionBody(const Declarator &D) {
13790   // We can't delay parsing the body of a constexpr function template (yet).
13791   if (D.getDeclSpec().hasConstexprSpecifier())
13792     return false;
13793 
13794   // We can't delay parsing the body of a function template with a deduced
13795   // return type (yet).
13796   if (D.getDeclSpec().hasAutoTypeSpec()) {
13797     // If the placeholder introduces a non-deduced trailing return type,
13798     // we can still delay parsing it.
13799     if (D.getNumTypeObjects()) {
13800       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
13801       if (Outer.Kind == DeclaratorChunk::Function &&
13802           Outer.Fun.hasTrailingReturnType()) {
13803         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
13804         return Ty.isNull() || !Ty->isUndeducedType();
13805       }
13806     }
13807     return false;
13808   }
13809 
13810   return true;
13811 }
13812 
13813 bool Sema::canSkipFunctionBody(Decl *D) {
13814   // We cannot skip the body of a function (or function template) which is
13815   // constexpr, since we may need to evaluate its body in order to parse the
13816   // rest of the file.
13817   // We cannot skip the body of a function with an undeduced return type,
13818   // because any callers of that function need to know the type.
13819   if (const FunctionDecl *FD = D->getAsFunction()) {
13820     if (FD->isConstexpr())
13821       return false;
13822     // We can't simply call Type::isUndeducedType here, because inside template
13823     // auto can be deduced to a dependent type, which is not considered
13824     // "undeduced".
13825     if (FD->getReturnType()->getContainedDeducedType())
13826       return false;
13827   }
13828   return Consumer.shouldSkipFunctionBody(D);
13829 }
13830 
13831 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
13832   if (!Decl)
13833     return nullptr;
13834   if (FunctionDecl *FD = Decl->getAsFunction())
13835     FD->setHasSkippedBody();
13836   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
13837     MD->setHasSkippedBody();
13838   return Decl;
13839 }
13840 
13841 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
13842   return ActOnFinishFunctionBody(D, BodyArg, false);
13843 }
13844 
13845 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
13846 /// body.
13847 class ExitFunctionBodyRAII {
13848 public:
13849   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
13850   ~ExitFunctionBodyRAII() {
13851     if (!IsLambda)
13852       S.PopExpressionEvaluationContext();
13853   }
13854 
13855 private:
13856   Sema &S;
13857   bool IsLambda = false;
13858 };
13859 
13860 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
13861   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
13862 
13863   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
13864     if (EscapeInfo.count(BD))
13865       return EscapeInfo[BD];
13866 
13867     bool R = false;
13868     const BlockDecl *CurBD = BD;
13869 
13870     do {
13871       R = !CurBD->doesNotEscape();
13872       if (R)
13873         break;
13874       CurBD = CurBD->getParent()->getInnermostBlockDecl();
13875     } while (CurBD);
13876 
13877     return EscapeInfo[BD] = R;
13878   };
13879 
13880   // If the location where 'self' is implicitly retained is inside a escaping
13881   // block, emit a diagnostic.
13882   for (const std::pair<SourceLocation, const BlockDecl *> &P :
13883        S.ImplicitlyRetainedSelfLocs)
13884     if (IsOrNestedInEscapingBlock(P.second))
13885       S.Diag(P.first, diag::warn_implicitly_retains_self)
13886           << FixItHint::CreateInsertion(P.first, "self->");
13887 }
13888 
13889 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
13890                                     bool IsInstantiation) {
13891   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
13892 
13893   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13894   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
13895 
13896   if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
13897     CheckCompletedCoroutineBody(FD, Body);
13898 
13899   // Do not call PopExpressionEvaluationContext() if it is a lambda because one
13900   // is already popped when finishing the lambda in BuildLambdaExpr(). This is
13901   // meant to pop the context added in ActOnStartOfFunctionDef().
13902   ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
13903 
13904   if (FD) {
13905     FD->setBody(Body);
13906     FD->setWillHaveBody(false);
13907 
13908     if (getLangOpts().CPlusPlus14) {
13909       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
13910           FD->getReturnType()->isUndeducedType()) {
13911         // If the function has a deduced result type but contains no 'return'
13912         // statements, the result type as written must be exactly 'auto', and
13913         // the deduced result type is 'void'.
13914         if (!FD->getReturnType()->getAs<AutoType>()) {
13915           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
13916               << FD->getReturnType();
13917           FD->setInvalidDecl();
13918         } else {
13919           // Substitute 'void' for the 'auto' in the type.
13920           TypeLoc ResultType = getReturnTypeLoc(FD);
13921           Context.adjustDeducedFunctionResultType(
13922               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
13923         }
13924       }
13925     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
13926       // In C++11, we don't use 'auto' deduction rules for lambda call
13927       // operators because we don't support return type deduction.
13928       auto *LSI = getCurLambda();
13929       if (LSI->HasImplicitReturnType) {
13930         deduceClosureReturnType(*LSI);
13931 
13932         // C++11 [expr.prim.lambda]p4:
13933         //   [...] if there are no return statements in the compound-statement
13934         //   [the deduced type is] the type void
13935         QualType RetType =
13936             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
13937 
13938         // Update the return type to the deduced type.
13939         const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
13940         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
13941                                             Proto->getExtProtoInfo()));
13942       }
13943     }
13944 
13945     // If the function implicitly returns zero (like 'main') or is naked,
13946     // don't complain about missing return statements.
13947     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
13948       WP.disableCheckFallThrough();
13949 
13950     // MSVC permits the use of pure specifier (=0) on function definition,
13951     // defined at class scope, warn about this non-standard construct.
13952     if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
13953       Diag(FD->getLocation(), diag::ext_pure_function_definition);
13954 
13955     if (!FD->isInvalidDecl()) {
13956       // Don't diagnose unused parameters of defaulted or deleted functions.
13957       if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
13958         DiagnoseUnusedParameters(FD->parameters());
13959       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
13960                                              FD->getReturnType(), FD);
13961 
13962       // If this is a structor, we need a vtable.
13963       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
13964         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
13965       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
13966         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
13967 
13968       // Try to apply the named return value optimization. We have to check
13969       // if we can do this here because lambdas keep return statements around
13970       // to deduce an implicit return type.
13971       if (FD->getReturnType()->isRecordType() &&
13972           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
13973         computeNRVO(Body, getCurFunction());
13974     }
13975 
13976     // GNU warning -Wmissing-prototypes:
13977     //   Warn if a global function is defined without a previous
13978     //   prototype declaration. This warning is issued even if the
13979     //   definition itself provides a prototype. The aim is to detect
13980     //   global functions that fail to be declared in header files.
13981     const FunctionDecl *PossiblePrototype = nullptr;
13982     if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
13983       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
13984 
13985       if (PossiblePrototype) {
13986         // We found a declaration that is not a prototype,
13987         // but that could be a zero-parameter prototype
13988         if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
13989           TypeLoc TL = TI->getTypeLoc();
13990           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
13991             Diag(PossiblePrototype->getLocation(),
13992                  diag::note_declaration_not_a_prototype)
13993                 << (FD->getNumParams() != 0)
13994                 << (FD->getNumParams() == 0
13995                         ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
13996                         : FixItHint{});
13997         }
13998       } else {
13999         Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14000             << /* function */ 1
14001             << (FD->getStorageClass() == SC_None
14002                     ? FixItHint::CreateInsertion(FD->getTypeSpecStartLoc(),
14003                                                  "static ")
14004                     : FixItHint{});
14005       }
14006 
14007       // GNU warning -Wstrict-prototypes
14008       //   Warn if K&R function is defined without a previous declaration.
14009       //   This warning is issued only if the definition itself does not provide
14010       //   a prototype. Only K&R definitions do not provide a prototype.
14011       //   An empty list in a function declarator that is part of a definition
14012       //   of that function specifies that the function has no parameters
14013       //   (C99 6.7.5.3p14)
14014       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
14015           !LangOpts.CPlusPlus) {
14016         TypeSourceInfo *TI = FD->getTypeSourceInfo();
14017         TypeLoc TL = TI->getTypeLoc();
14018         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
14019         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14020       }
14021     }
14022 
14023     // Warn on CPUDispatch with an actual body.
14024     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14025       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14026         if (!CmpndBody->body_empty())
14027           Diag(CmpndBody->body_front()->getBeginLoc(),
14028                diag::warn_dispatch_body_ignored);
14029 
14030     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14031       const CXXMethodDecl *KeyFunction;
14032       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14033           MD->isVirtual() &&
14034           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14035           MD == KeyFunction->getCanonicalDecl()) {
14036         // Update the key-function state if necessary for this ABI.
14037         if (FD->isInlined() &&
14038             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14039           Context.setNonKeyFunction(MD);
14040 
14041           // If the newly-chosen key function is already defined, then we
14042           // need to mark the vtable as used retroactively.
14043           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14044           const FunctionDecl *Definition;
14045           if (KeyFunction && KeyFunction->isDefined(Definition))
14046             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14047         } else {
14048           // We just defined they key function; mark the vtable as used.
14049           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14050         }
14051       }
14052     }
14053 
14054     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
14055            "Function parsing confused");
14056   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14057     assert(MD == getCurMethodDecl() && "Method parsing confused");
14058     MD->setBody(Body);
14059     if (!MD->isInvalidDecl()) {
14060       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14061                                              MD->getReturnType(), MD);
14062 
14063       if (Body)
14064         computeNRVO(Body, getCurFunction());
14065     }
14066     if (getCurFunction()->ObjCShouldCallSuper) {
14067       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14068           << MD->getSelector().getAsString();
14069       getCurFunction()->ObjCShouldCallSuper = false;
14070     }
14071     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
14072       const ObjCMethodDecl *InitMethod = nullptr;
14073       bool isDesignated =
14074           MD->isDesignatedInitializerForTheInterface(&InitMethod);
14075       assert(isDesignated && InitMethod);
14076       (void)isDesignated;
14077 
14078       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14079         auto IFace = MD->getClassInterface();
14080         if (!IFace)
14081           return false;
14082         auto SuperD = IFace->getSuperClass();
14083         if (!SuperD)
14084           return false;
14085         return SuperD->getIdentifier() ==
14086             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14087       };
14088       // Don't issue this warning for unavailable inits or direct subclasses
14089       // of NSObject.
14090       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14091         Diag(MD->getLocation(),
14092              diag::warn_objc_designated_init_missing_super_call);
14093         Diag(InitMethod->getLocation(),
14094              diag::note_objc_designated_init_marked_here);
14095       }
14096       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
14097     }
14098     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
14099       // Don't issue this warning for unavaialable inits.
14100       if (!MD->isUnavailable())
14101         Diag(MD->getLocation(),
14102              diag::warn_objc_secondary_init_missing_init_call);
14103       getCurFunction()->ObjCWarnForNoInitDelegation = false;
14104     }
14105 
14106     diagnoseImplicitlyRetainedSelf(*this);
14107   } else {
14108     // Parsing the function declaration failed in some way. Pop the fake scope
14109     // we pushed on.
14110     PopFunctionScopeInfo(ActivePolicy, dcl);
14111     return nullptr;
14112   }
14113 
14114   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
14115     DiagnoseUnguardedAvailabilityViolations(dcl);
14116 
14117   assert(!getCurFunction()->ObjCShouldCallSuper &&
14118          "This should only be set for ObjC methods, which should have been "
14119          "handled in the block above.");
14120 
14121   // Verify and clean out per-function state.
14122   if (Body && (!FD || !FD->isDefaulted())) {
14123     // C++ constructors that have function-try-blocks can't have return
14124     // statements in the handlers of that block. (C++ [except.handle]p14)
14125     // Verify this.
14126     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14127       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14128 
14129     // Verify that gotos and switch cases don't jump into scopes illegally.
14130     if (getCurFunction()->NeedsScopeChecking() &&
14131         !PP.isCodeCompletionEnabled())
14132       DiagnoseInvalidJumps(Body);
14133 
14134     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14135       if (!Destructor->getParent()->isDependentType())
14136         CheckDestructor(Destructor);
14137 
14138       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14139                                              Destructor->getParent());
14140     }
14141 
14142     // If any errors have occurred, clear out any temporaries that may have
14143     // been leftover. This ensures that these temporaries won't be picked up for
14144     // deletion in some later function.
14145     if (getDiagnostics().hasErrorOccurred() ||
14146         getDiagnostics().getSuppressAllDiagnostics()) {
14147       DiscardCleanupsInEvaluationContext();
14148     }
14149     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
14150         !isa<FunctionTemplateDecl>(dcl)) {
14151       // Since the body is valid, issue any analysis-based warnings that are
14152       // enabled.
14153       ActivePolicy = &WP;
14154     }
14155 
14156     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14157         !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14158       FD->setInvalidDecl();
14159 
14160     if (FD && FD->hasAttr<NakedAttr>()) {
14161       for (const Stmt *S : Body->children()) {
14162         // Allow local register variables without initializer as they don't
14163         // require prologue.
14164         bool RegisterVariables = false;
14165         if (auto *DS = dyn_cast<DeclStmt>(S)) {
14166           for (const auto *Decl : DS->decls()) {
14167             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14168               RegisterVariables =
14169                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14170               if (!RegisterVariables)
14171                 break;
14172             }
14173           }
14174         }
14175         if (RegisterVariables)
14176           continue;
14177         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14178           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14179           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14180           FD->setInvalidDecl();
14181           break;
14182         }
14183       }
14184     }
14185 
14186     assert(ExprCleanupObjects.size() ==
14187                ExprEvalContexts.back().NumCleanupObjects &&
14188            "Leftover temporaries in function");
14189     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
14190     assert(MaybeODRUseExprs.empty() &&
14191            "Leftover expressions for odr-use checking");
14192   }
14193 
14194   if (!IsInstantiation)
14195     PopDeclContext();
14196 
14197   PopFunctionScopeInfo(ActivePolicy, dcl);
14198   // If any errors have occurred, clear out any temporaries that may have
14199   // been leftover. This ensures that these temporaries won't be picked up for
14200   // deletion in some later function.
14201   if (getDiagnostics().hasErrorOccurred()) {
14202     DiscardCleanupsInEvaluationContext();
14203   }
14204 
14205   return dcl;
14206 }
14207 
14208 /// When we finish delayed parsing of an attribute, we must attach it to the
14209 /// relevant Decl.
14210 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14211                                        ParsedAttributes &Attrs) {
14212   // Always attach attributes to the underlying decl.
14213   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14214     D = TD->getTemplatedDecl();
14215   ProcessDeclAttributeList(S, D, Attrs);
14216 
14217   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14218     if (Method->isStatic())
14219       checkThisInStaticMemberFunctionAttributes(Method);
14220 }
14221 
14222 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14223 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
14224 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14225                                           IdentifierInfo &II, Scope *S) {
14226   // Find the scope in which the identifier is injected and the corresponding
14227   // DeclContext.
14228   // FIXME: C89 does not say what happens if there is no enclosing block scope.
14229   // In that case, we inject the declaration into the translation unit scope
14230   // instead.
14231   Scope *BlockScope = S;
14232   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14233     BlockScope = BlockScope->getParent();
14234 
14235   Scope *ContextScope = BlockScope;
14236   while (!ContextScope->getEntity())
14237     ContextScope = ContextScope->getParent();
14238   ContextRAII SavedContext(*this, ContextScope->getEntity());
14239 
14240   // Before we produce a declaration for an implicitly defined
14241   // function, see whether there was a locally-scoped declaration of
14242   // this name as a function or variable. If so, use that
14243   // (non-visible) declaration, and complain about it.
14244   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14245   if (ExternCPrev) {
14246     // We still need to inject the function into the enclosing block scope so
14247     // that later (non-call) uses can see it.
14248     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14249 
14250     // C89 footnote 38:
14251     //   If in fact it is not defined as having type "function returning int",
14252     //   the behavior is undefined.
14253     if (!isa<FunctionDecl>(ExternCPrev) ||
14254         !Context.typesAreCompatible(
14255             cast<FunctionDecl>(ExternCPrev)->getType(),
14256             Context.getFunctionNoProtoType(Context.IntTy))) {
14257       Diag(Loc, diag::ext_use_out_of_scope_declaration)
14258           << ExternCPrev << !getLangOpts().C99;
14259       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14260       return ExternCPrev;
14261     }
14262   }
14263 
14264   // Extension in C99.  Legal in C90, but warn about it.
14265   unsigned diag_id;
14266   if (II.getName().startswith("__builtin_"))
14267     diag_id = diag::warn_builtin_unknown;
14268   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14269   else if (getLangOpts().OpenCL)
14270     diag_id = diag::err_opencl_implicit_function_decl;
14271   else if (getLangOpts().C99)
14272     diag_id = diag::ext_implicit_function_decl;
14273   else
14274     diag_id = diag::warn_implicit_function_decl;
14275   Diag(Loc, diag_id) << &II;
14276 
14277   // If we found a prior declaration of this function, don't bother building
14278   // another one. We've already pushed that one into scope, so there's nothing
14279   // more to do.
14280   if (ExternCPrev)
14281     return ExternCPrev;
14282 
14283   // Because typo correction is expensive, only do it if the implicit
14284   // function declaration is going to be treated as an error.
14285   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
14286     TypoCorrection Corrected;
14287     DeclFilterCCC<FunctionDecl> CCC{};
14288     if (S && (Corrected =
14289                   CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
14290                               S, nullptr, CCC, CTK_NonError)))
14291       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
14292                    /*ErrorRecovery*/false);
14293   }
14294 
14295   // Set a Declarator for the implicit definition: int foo();
14296   const char *Dummy;
14297   AttributeFactory attrFactory;
14298   DeclSpec DS(attrFactory);
14299   unsigned DiagID;
14300   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
14301                                   Context.getPrintingPolicy());
14302   (void)Error; // Silence warning.
14303   assert(!Error && "Error setting up implicit decl!");
14304   SourceLocation NoLoc;
14305   Declarator D(DS, DeclaratorContext::BlockContext);
14306   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
14307                                              /*IsAmbiguous=*/false,
14308                                              /*LParenLoc=*/NoLoc,
14309                                              /*Params=*/nullptr,
14310                                              /*NumParams=*/0,
14311                                              /*EllipsisLoc=*/NoLoc,
14312                                              /*RParenLoc=*/NoLoc,
14313                                              /*RefQualifierIsLvalueRef=*/true,
14314                                              /*RefQualifierLoc=*/NoLoc,
14315                                              /*MutableLoc=*/NoLoc, EST_None,
14316                                              /*ESpecRange=*/SourceRange(),
14317                                              /*Exceptions=*/nullptr,
14318                                              /*ExceptionRanges=*/nullptr,
14319                                              /*NumExceptions=*/0,
14320                                              /*NoexceptExpr=*/nullptr,
14321                                              /*ExceptionSpecTokens=*/nullptr,
14322                                              /*DeclsInPrototype=*/None, Loc,
14323                                              Loc, D),
14324                 std::move(DS.getAttributes()), SourceLocation());
14325   D.SetIdentifier(&II, Loc);
14326 
14327   // Insert this function into the enclosing block scope.
14328   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
14329   FD->setImplicit();
14330 
14331   AddKnownFunctionAttributes(FD);
14332 
14333   return FD;
14334 }
14335 
14336 /// Adds any function attributes that we know a priori based on
14337 /// the declaration of this function.
14338 ///
14339 /// These attributes can apply both to implicitly-declared builtins
14340 /// (like __builtin___printf_chk) or to library-declared functions
14341 /// like NSLog or printf.
14342 ///
14343 /// We need to check for duplicate attributes both here and where user-written
14344 /// attributes are applied to declarations.
14345 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
14346   if (FD->isInvalidDecl())
14347     return;
14348 
14349   // If this is a built-in function, map its builtin attributes to
14350   // actual attributes.
14351   if (unsigned BuiltinID = FD->getBuiltinID()) {
14352     // Handle printf-formatting attributes.
14353     unsigned FormatIdx;
14354     bool HasVAListArg;
14355     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
14356       if (!FD->hasAttr<FormatAttr>()) {
14357         const char *fmt = "printf";
14358         unsigned int NumParams = FD->getNumParams();
14359         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
14360             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
14361           fmt = "NSString";
14362         FD->addAttr(FormatAttr::CreateImplicit(Context,
14363                                                &Context.Idents.get(fmt),
14364                                                FormatIdx+1,
14365                                                HasVAListArg ? 0 : FormatIdx+2,
14366                                                FD->getLocation()));
14367       }
14368     }
14369     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
14370                                              HasVAListArg)) {
14371      if (!FD->hasAttr<FormatAttr>())
14372        FD->addAttr(FormatAttr::CreateImplicit(Context,
14373                                               &Context.Idents.get("scanf"),
14374                                               FormatIdx+1,
14375                                               HasVAListArg ? 0 : FormatIdx+2,
14376                                               FD->getLocation()));
14377     }
14378 
14379     // Handle automatically recognized callbacks.
14380     SmallVector<int, 4> Encoding;
14381     if (!FD->hasAttr<CallbackAttr>() &&
14382         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
14383       FD->addAttr(CallbackAttr::CreateImplicit(
14384           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
14385 
14386     // Mark const if we don't care about errno and that is the only thing
14387     // preventing the function from being const. This allows IRgen to use LLVM
14388     // intrinsics for such functions.
14389     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
14390         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
14391       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14392 
14393     // We make "fma" on some platforms const because we know it does not set
14394     // errno in those environments even though it could set errno based on the
14395     // C standard.
14396     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
14397     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
14398         !FD->hasAttr<ConstAttr>()) {
14399       switch (BuiltinID) {
14400       case Builtin::BI__builtin_fma:
14401       case Builtin::BI__builtin_fmaf:
14402       case Builtin::BI__builtin_fmal:
14403       case Builtin::BIfma:
14404       case Builtin::BIfmaf:
14405       case Builtin::BIfmal:
14406         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14407         break;
14408       default:
14409         break;
14410       }
14411     }
14412 
14413     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
14414         !FD->hasAttr<ReturnsTwiceAttr>())
14415       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
14416                                          FD->getLocation()));
14417     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
14418       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14419     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
14420       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
14421     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
14422       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14423     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
14424         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
14425       // Add the appropriate attribute, depending on the CUDA compilation mode
14426       // and which target the builtin belongs to. For example, during host
14427       // compilation, aux builtins are __device__, while the rest are __host__.
14428       if (getLangOpts().CUDAIsDevice !=
14429           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
14430         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
14431       else
14432         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
14433     }
14434   }
14435 
14436   // If C++ exceptions are enabled but we are told extern "C" functions cannot
14437   // throw, add an implicit nothrow attribute to any extern "C" function we come
14438   // across.
14439   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
14440       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
14441     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
14442     if (!FPT || FPT->getExceptionSpecType() == EST_None)
14443       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14444   }
14445 
14446   IdentifierInfo *Name = FD->getIdentifier();
14447   if (!Name)
14448     return;
14449   if ((!getLangOpts().CPlusPlus &&
14450        FD->getDeclContext()->isTranslationUnit()) ||
14451       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
14452        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
14453        LinkageSpecDecl::lang_c)) {
14454     // Okay: this could be a libc/libm/Objective-C function we know
14455     // about.
14456   } else
14457     return;
14458 
14459   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
14460     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
14461     // target-specific builtins, perhaps?
14462     if (!FD->hasAttr<FormatAttr>())
14463       FD->addAttr(FormatAttr::CreateImplicit(Context,
14464                                              &Context.Idents.get("printf"), 2,
14465                                              Name->isStr("vasprintf") ? 0 : 3,
14466                                              FD->getLocation()));
14467   }
14468 
14469   if (Name->isStr("__CFStringMakeConstantString")) {
14470     // We already have a __builtin___CFStringMakeConstantString,
14471     // but builds that use -fno-constant-cfstrings don't go through that.
14472     if (!FD->hasAttr<FormatArgAttr>())
14473       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
14474                                                 FD->getLocation()));
14475   }
14476 }
14477 
14478 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
14479                                     TypeSourceInfo *TInfo) {
14480   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
14481   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
14482 
14483   if (!TInfo) {
14484     assert(D.isInvalidType() && "no declarator info for valid type");
14485     TInfo = Context.getTrivialTypeSourceInfo(T);
14486   }
14487 
14488   // Scope manipulation handled by caller.
14489   TypedefDecl *NewTD =
14490       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
14491                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
14492 
14493   // Bail out immediately if we have an invalid declaration.
14494   if (D.isInvalidType()) {
14495     NewTD->setInvalidDecl();
14496     return NewTD;
14497   }
14498 
14499   if (D.getDeclSpec().isModulePrivateSpecified()) {
14500     if (CurContext->isFunctionOrMethod())
14501       Diag(NewTD->getLocation(), diag::err_module_private_local)
14502         << 2 << NewTD->getDeclName()
14503         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14504         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
14505     else
14506       NewTD->setModulePrivate();
14507   }
14508 
14509   // C++ [dcl.typedef]p8:
14510   //   If the typedef declaration defines an unnamed class (or
14511   //   enum), the first typedef-name declared by the declaration
14512   //   to be that class type (or enum type) is used to denote the
14513   //   class type (or enum type) for linkage purposes only.
14514   // We need to check whether the type was declared in the declaration.
14515   switch (D.getDeclSpec().getTypeSpecType()) {
14516   case TST_enum:
14517   case TST_struct:
14518   case TST_interface:
14519   case TST_union:
14520   case TST_class: {
14521     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
14522     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
14523     break;
14524   }
14525 
14526   default:
14527     break;
14528   }
14529 
14530   return NewTD;
14531 }
14532 
14533 /// Check that this is a valid underlying type for an enum declaration.
14534 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
14535   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
14536   QualType T = TI->getType();
14537 
14538   if (T->isDependentType())
14539     return false;
14540 
14541   if (const BuiltinType *BT = T->getAs<BuiltinType>())
14542     if (BT->isInteger())
14543       return false;
14544 
14545   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
14546   return true;
14547 }
14548 
14549 /// Check whether this is a valid redeclaration of a previous enumeration.
14550 /// \return true if the redeclaration was invalid.
14551 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
14552                                   QualType EnumUnderlyingTy, bool IsFixed,
14553                                   const EnumDecl *Prev) {
14554   if (IsScoped != Prev->isScoped()) {
14555     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
14556       << Prev->isScoped();
14557     Diag(Prev->getLocation(), diag::note_previous_declaration);
14558     return true;
14559   }
14560 
14561   if (IsFixed && Prev->isFixed()) {
14562     if (!EnumUnderlyingTy->isDependentType() &&
14563         !Prev->getIntegerType()->isDependentType() &&
14564         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
14565                                         Prev->getIntegerType())) {
14566       // TODO: Highlight the underlying type of the redeclaration.
14567       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
14568         << EnumUnderlyingTy << Prev->getIntegerType();
14569       Diag(Prev->getLocation(), diag::note_previous_declaration)
14570           << Prev->getIntegerTypeRange();
14571       return true;
14572     }
14573   } else if (IsFixed != Prev->isFixed()) {
14574     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
14575       << Prev->isFixed();
14576     Diag(Prev->getLocation(), diag::note_previous_declaration);
14577     return true;
14578   }
14579 
14580   return false;
14581 }
14582 
14583 /// Get diagnostic %select index for tag kind for
14584 /// redeclaration diagnostic message.
14585 /// WARNING: Indexes apply to particular diagnostics only!
14586 ///
14587 /// \returns diagnostic %select index.
14588 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
14589   switch (Tag) {
14590   case TTK_Struct: return 0;
14591   case TTK_Interface: return 1;
14592   case TTK_Class:  return 2;
14593   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
14594   }
14595 }
14596 
14597 /// Determine if tag kind is a class-key compatible with
14598 /// class for redeclaration (class, struct, or __interface).
14599 ///
14600 /// \returns true iff the tag kind is compatible.
14601 static bool isClassCompatTagKind(TagTypeKind Tag)
14602 {
14603   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
14604 }
14605 
14606 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
14607                                              TagTypeKind TTK) {
14608   if (isa<TypedefDecl>(PrevDecl))
14609     return NTK_Typedef;
14610   else if (isa<TypeAliasDecl>(PrevDecl))
14611     return NTK_TypeAlias;
14612   else if (isa<ClassTemplateDecl>(PrevDecl))
14613     return NTK_Template;
14614   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
14615     return NTK_TypeAliasTemplate;
14616   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
14617     return NTK_TemplateTemplateArgument;
14618   switch (TTK) {
14619   case TTK_Struct:
14620   case TTK_Interface:
14621   case TTK_Class:
14622     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
14623   case TTK_Union:
14624     return NTK_NonUnion;
14625   case TTK_Enum:
14626     return NTK_NonEnum;
14627   }
14628   llvm_unreachable("invalid TTK");
14629 }
14630 
14631 /// Determine whether a tag with a given kind is acceptable
14632 /// as a redeclaration of the given tag declaration.
14633 ///
14634 /// \returns true if the new tag kind is acceptable, false otherwise.
14635 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
14636                                         TagTypeKind NewTag, bool isDefinition,
14637                                         SourceLocation NewTagLoc,
14638                                         const IdentifierInfo *Name) {
14639   // C++ [dcl.type.elab]p3:
14640   //   The class-key or enum keyword present in the
14641   //   elaborated-type-specifier shall agree in kind with the
14642   //   declaration to which the name in the elaborated-type-specifier
14643   //   refers. This rule also applies to the form of
14644   //   elaborated-type-specifier that declares a class-name or
14645   //   friend class since it can be construed as referring to the
14646   //   definition of the class. Thus, in any
14647   //   elaborated-type-specifier, the enum keyword shall be used to
14648   //   refer to an enumeration (7.2), the union class-key shall be
14649   //   used to refer to a union (clause 9), and either the class or
14650   //   struct class-key shall be used to refer to a class (clause 9)
14651   //   declared using the class or struct class-key.
14652   TagTypeKind OldTag = Previous->getTagKind();
14653   if (OldTag != NewTag &&
14654       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
14655     return false;
14656 
14657   // Tags are compatible, but we might still want to warn on mismatched tags.
14658   // Non-class tags can't be mismatched at this point.
14659   if (!isClassCompatTagKind(NewTag))
14660     return true;
14661 
14662   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
14663   // by our warning analysis. We don't want to warn about mismatches with (eg)
14664   // declarations in system headers that are designed to be specialized, but if
14665   // a user asks us to warn, we should warn if their code contains mismatched
14666   // declarations.
14667   auto IsIgnoredLoc = [&](SourceLocation Loc) {
14668     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
14669                                       Loc);
14670   };
14671   if (IsIgnoredLoc(NewTagLoc))
14672     return true;
14673 
14674   auto IsIgnored = [&](const TagDecl *Tag) {
14675     return IsIgnoredLoc(Tag->getLocation());
14676   };
14677   while (IsIgnored(Previous)) {
14678     Previous = Previous->getPreviousDecl();
14679     if (!Previous)
14680       return true;
14681     OldTag = Previous->getTagKind();
14682   }
14683 
14684   bool isTemplate = false;
14685   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
14686     isTemplate = Record->getDescribedClassTemplate();
14687 
14688   if (inTemplateInstantiation()) {
14689     if (OldTag != NewTag) {
14690       // In a template instantiation, do not offer fix-its for tag mismatches
14691       // since they usually mess up the template instead of fixing the problem.
14692       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14693         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14694         << getRedeclDiagFromTagKind(OldTag);
14695       // FIXME: Note previous location?
14696     }
14697     return true;
14698   }
14699 
14700   if (isDefinition) {
14701     // On definitions, check all previous tags and issue a fix-it for each
14702     // one that doesn't match the current tag.
14703     if (Previous->getDefinition()) {
14704       // Don't suggest fix-its for redefinitions.
14705       return true;
14706     }
14707 
14708     bool previousMismatch = false;
14709     for (const TagDecl *I : Previous->redecls()) {
14710       if (I->getTagKind() != NewTag) {
14711         // Ignore previous declarations for which the warning was disabled.
14712         if (IsIgnored(I))
14713           continue;
14714 
14715         if (!previousMismatch) {
14716           previousMismatch = true;
14717           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
14718             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14719             << getRedeclDiagFromTagKind(I->getTagKind());
14720         }
14721         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
14722           << getRedeclDiagFromTagKind(NewTag)
14723           << FixItHint::CreateReplacement(I->getInnerLocStart(),
14724                TypeWithKeyword::getTagTypeKindName(NewTag));
14725       }
14726     }
14727     return true;
14728   }
14729 
14730   // Identify the prevailing tag kind: this is the kind of the definition (if
14731   // there is a non-ignored definition), or otherwise the kind of the prior
14732   // (non-ignored) declaration.
14733   const TagDecl *PrevDef = Previous->getDefinition();
14734   if (PrevDef && IsIgnored(PrevDef))
14735     PrevDef = nullptr;
14736   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
14737   if (Redecl->getTagKind() != NewTag) {
14738     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14739       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14740       << getRedeclDiagFromTagKind(OldTag);
14741     Diag(Redecl->getLocation(), diag::note_previous_use);
14742 
14743     // If there is a previous definition, suggest a fix-it.
14744     if (PrevDef) {
14745       Diag(NewTagLoc, diag::note_struct_class_suggestion)
14746         << getRedeclDiagFromTagKind(Redecl->getTagKind())
14747         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
14748              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
14749     }
14750   }
14751 
14752   return true;
14753 }
14754 
14755 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
14756 /// from an outer enclosing namespace or file scope inside a friend declaration.
14757 /// This should provide the commented out code in the following snippet:
14758 ///   namespace N {
14759 ///     struct X;
14760 ///     namespace M {
14761 ///       struct Y { friend struct /*N::*/ X; };
14762 ///     }
14763 ///   }
14764 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
14765                                          SourceLocation NameLoc) {
14766   // While the decl is in a namespace, do repeated lookup of that name and see
14767   // if we get the same namespace back.  If we do not, continue until
14768   // translation unit scope, at which point we have a fully qualified NNS.
14769   SmallVector<IdentifierInfo *, 4> Namespaces;
14770   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14771   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
14772     // This tag should be declared in a namespace, which can only be enclosed by
14773     // other namespaces.  Bail if there's an anonymous namespace in the chain.
14774     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
14775     if (!Namespace || Namespace->isAnonymousNamespace())
14776       return FixItHint();
14777     IdentifierInfo *II = Namespace->getIdentifier();
14778     Namespaces.push_back(II);
14779     NamedDecl *Lookup = SemaRef.LookupSingleName(
14780         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
14781     if (Lookup == Namespace)
14782       break;
14783   }
14784 
14785   // Once we have all the namespaces, reverse them to go outermost first, and
14786   // build an NNS.
14787   SmallString<64> Insertion;
14788   llvm::raw_svector_ostream OS(Insertion);
14789   if (DC->isTranslationUnit())
14790     OS << "::";
14791   std::reverse(Namespaces.begin(), Namespaces.end());
14792   for (auto *II : Namespaces)
14793     OS << II->getName() << "::";
14794   return FixItHint::CreateInsertion(NameLoc, Insertion);
14795 }
14796 
14797 /// Determine whether a tag originally declared in context \p OldDC can
14798 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
14799 /// found a declaration in \p OldDC as a previous decl, perhaps through a
14800 /// using-declaration).
14801 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
14802                                          DeclContext *NewDC) {
14803   OldDC = OldDC->getRedeclContext();
14804   NewDC = NewDC->getRedeclContext();
14805 
14806   if (OldDC->Equals(NewDC))
14807     return true;
14808 
14809   // In MSVC mode, we allow a redeclaration if the contexts are related (either
14810   // encloses the other).
14811   if (S.getLangOpts().MSVCCompat &&
14812       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
14813     return true;
14814 
14815   return false;
14816 }
14817 
14818 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
14819 /// former case, Name will be non-null.  In the later case, Name will be null.
14820 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
14821 /// reference/declaration/definition of a tag.
14822 ///
14823 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
14824 /// trailing-type-specifier) other than one in an alias-declaration.
14825 ///
14826 /// \param SkipBody If non-null, will be set to indicate if the caller should
14827 /// skip the definition of this tag and treat it as if it were a declaration.
14828 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
14829                      SourceLocation KWLoc, CXXScopeSpec &SS,
14830                      IdentifierInfo *Name, SourceLocation NameLoc,
14831                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
14832                      SourceLocation ModulePrivateLoc,
14833                      MultiTemplateParamsArg TemplateParameterLists,
14834                      bool &OwnedDecl, bool &IsDependent,
14835                      SourceLocation ScopedEnumKWLoc,
14836                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
14837                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
14838                      SkipBodyInfo *SkipBody) {
14839   // If this is not a definition, it must have a name.
14840   IdentifierInfo *OrigName = Name;
14841   assert((Name != nullptr || TUK == TUK_Definition) &&
14842          "Nameless record must be a definition!");
14843   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
14844 
14845   OwnedDecl = false;
14846   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14847   bool ScopedEnum = ScopedEnumKWLoc.isValid();
14848 
14849   // FIXME: Check member specializations more carefully.
14850   bool isMemberSpecialization = false;
14851   bool Invalid = false;
14852 
14853   // We only need to do this matching if we have template parameters
14854   // or a scope specifier, which also conveniently avoids this work
14855   // for non-C++ cases.
14856   if (TemplateParameterLists.size() > 0 ||
14857       (SS.isNotEmpty() && TUK != TUK_Reference)) {
14858     if (TemplateParameterList *TemplateParams =
14859             MatchTemplateParametersToScopeSpecifier(
14860                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
14861                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
14862       if (Kind == TTK_Enum) {
14863         Diag(KWLoc, diag::err_enum_template);
14864         return nullptr;
14865       }
14866 
14867       if (TemplateParams->size() > 0) {
14868         // This is a declaration or definition of a class template (which may
14869         // be a member of another template).
14870 
14871         if (Invalid)
14872           return nullptr;
14873 
14874         OwnedDecl = false;
14875         DeclResult Result = CheckClassTemplate(
14876             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
14877             AS, ModulePrivateLoc,
14878             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
14879             TemplateParameterLists.data(), SkipBody);
14880         return Result.get();
14881       } else {
14882         // The "template<>" header is extraneous.
14883         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14884           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14885         isMemberSpecialization = true;
14886       }
14887     }
14888   }
14889 
14890   // Figure out the underlying type if this a enum declaration. We need to do
14891   // this early, because it's needed to detect if this is an incompatible
14892   // redeclaration.
14893   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
14894   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
14895 
14896   if (Kind == TTK_Enum) {
14897     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
14898       // No underlying type explicitly specified, or we failed to parse the
14899       // type, default to int.
14900       EnumUnderlying = Context.IntTy.getTypePtr();
14901     } else if (UnderlyingType.get()) {
14902       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
14903       // integral type; any cv-qualification is ignored.
14904       TypeSourceInfo *TI = nullptr;
14905       GetTypeFromParser(UnderlyingType.get(), &TI);
14906       EnumUnderlying = TI;
14907 
14908       if (CheckEnumUnderlyingType(TI))
14909         // Recover by falling back to int.
14910         EnumUnderlying = Context.IntTy.getTypePtr();
14911 
14912       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
14913                                           UPPC_FixedUnderlyingType))
14914         EnumUnderlying = Context.IntTy.getTypePtr();
14915 
14916     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
14917       // For MSVC ABI compatibility, unfixed enums must use an underlying type
14918       // of 'int'. However, if this is an unfixed forward declaration, don't set
14919       // the underlying type unless the user enables -fms-compatibility. This
14920       // makes unfixed forward declared enums incomplete and is more conforming.
14921       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
14922         EnumUnderlying = Context.IntTy.getTypePtr();
14923     }
14924   }
14925 
14926   DeclContext *SearchDC = CurContext;
14927   DeclContext *DC = CurContext;
14928   bool isStdBadAlloc = false;
14929   bool isStdAlignValT = false;
14930 
14931   RedeclarationKind Redecl = forRedeclarationInCurContext();
14932   if (TUK == TUK_Friend || TUK == TUK_Reference)
14933     Redecl = NotForRedeclaration;
14934 
14935   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
14936   /// implemented asks for structural equivalence checking, the returned decl
14937   /// here is passed back to the parser, allowing the tag body to be parsed.
14938   auto createTagFromNewDecl = [&]() -> TagDecl * {
14939     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
14940     // If there is an identifier, use the location of the identifier as the
14941     // location of the decl, otherwise use the location of the struct/union
14942     // keyword.
14943     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14944     TagDecl *New = nullptr;
14945 
14946     if (Kind == TTK_Enum) {
14947       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
14948                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
14949       // If this is an undefined enum, bail.
14950       if (TUK != TUK_Definition && !Invalid)
14951         return nullptr;
14952       if (EnumUnderlying) {
14953         EnumDecl *ED = cast<EnumDecl>(New);
14954         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
14955           ED->setIntegerTypeSourceInfo(TI);
14956         else
14957           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
14958         ED->setPromotionType(ED->getIntegerType());
14959       }
14960     } else { // struct/union
14961       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14962                                nullptr);
14963     }
14964 
14965     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14966       // Add alignment attributes if necessary; these attributes are checked
14967       // when the ASTContext lays out the structure.
14968       //
14969       // It is important for implementing the correct semantics that this
14970       // happen here (in ActOnTag). The #pragma pack stack is
14971       // maintained as a result of parser callbacks which can occur at
14972       // many points during the parsing of a struct declaration (because
14973       // the #pragma tokens are effectively skipped over during the
14974       // parsing of the struct).
14975       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
14976         AddAlignmentAttributesForRecord(RD);
14977         AddMsStructLayoutForRecord(RD);
14978       }
14979     }
14980     New->setLexicalDeclContext(CurContext);
14981     return New;
14982   };
14983 
14984   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
14985   if (Name && SS.isNotEmpty()) {
14986     // We have a nested-name tag ('struct foo::bar').
14987 
14988     // Check for invalid 'foo::'.
14989     if (SS.isInvalid()) {
14990       Name = nullptr;
14991       goto CreateNewDecl;
14992     }
14993 
14994     // If this is a friend or a reference to a class in a dependent
14995     // context, don't try to make a decl for it.
14996     if (TUK == TUK_Friend || TUK == TUK_Reference) {
14997       DC = computeDeclContext(SS, false);
14998       if (!DC) {
14999         IsDependent = true;
15000         return nullptr;
15001       }
15002     } else {
15003       DC = computeDeclContext(SS, true);
15004       if (!DC) {
15005         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
15006           << SS.getRange();
15007         return nullptr;
15008       }
15009     }
15010 
15011     if (RequireCompleteDeclContext(SS, DC))
15012       return nullptr;
15013 
15014     SearchDC = DC;
15015     // Look-up name inside 'foo::'.
15016     LookupQualifiedName(Previous, DC);
15017 
15018     if (Previous.isAmbiguous())
15019       return nullptr;
15020 
15021     if (Previous.empty()) {
15022       // Name lookup did not find anything. However, if the
15023       // nested-name-specifier refers to the current instantiation,
15024       // and that current instantiation has any dependent base
15025       // classes, we might find something at instantiation time: treat
15026       // this as a dependent elaborated-type-specifier.
15027       // But this only makes any sense for reference-like lookups.
15028       if (Previous.wasNotFoundInCurrentInstantiation() &&
15029           (TUK == TUK_Reference || TUK == TUK_Friend)) {
15030         IsDependent = true;
15031         return nullptr;
15032       }
15033 
15034       // A tag 'foo::bar' must already exist.
15035       Diag(NameLoc, diag::err_not_tag_in_scope)
15036         << Kind << Name << DC << SS.getRange();
15037       Name = nullptr;
15038       Invalid = true;
15039       goto CreateNewDecl;
15040     }
15041   } else if (Name) {
15042     // C++14 [class.mem]p14:
15043     //   If T is the name of a class, then each of the following shall have a
15044     //   name different from T:
15045     //    -- every member of class T that is itself a type
15046     if (TUK != TUK_Reference && TUK != TUK_Friend &&
15047         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15048       return nullptr;
15049 
15050     // If this is a named struct, check to see if there was a previous forward
15051     // declaration or definition.
15052     // FIXME: We're looking into outer scopes here, even when we
15053     // shouldn't be. Doing so can result in ambiguities that we
15054     // shouldn't be diagnosing.
15055     LookupName(Previous, S);
15056 
15057     // When declaring or defining a tag, ignore ambiguities introduced
15058     // by types using'ed into this scope.
15059     if (Previous.isAmbiguous() &&
15060         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
15061       LookupResult::Filter F = Previous.makeFilter();
15062       while (F.hasNext()) {
15063         NamedDecl *ND = F.next();
15064         if (!ND->getDeclContext()->getRedeclContext()->Equals(
15065                 SearchDC->getRedeclContext()))
15066           F.erase();
15067       }
15068       F.done();
15069     }
15070 
15071     // C++11 [namespace.memdef]p3:
15072     //   If the name in a friend declaration is neither qualified nor
15073     //   a template-id and the declaration is a function or an
15074     //   elaborated-type-specifier, the lookup to determine whether
15075     //   the entity has been previously declared shall not consider
15076     //   any scopes outside the innermost enclosing namespace.
15077     //
15078     // MSVC doesn't implement the above rule for types, so a friend tag
15079     // declaration may be a redeclaration of a type declared in an enclosing
15080     // scope.  They do implement this rule for friend functions.
15081     //
15082     // Does it matter that this should be by scope instead of by
15083     // semantic context?
15084     if (!Previous.empty() && TUK == TUK_Friend) {
15085       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
15086       LookupResult::Filter F = Previous.makeFilter();
15087       bool FriendSawTagOutsideEnclosingNamespace = false;
15088       while (F.hasNext()) {
15089         NamedDecl *ND = F.next();
15090         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15091         if (DC->isFileContext() &&
15092             !EnclosingNS->Encloses(ND->getDeclContext())) {
15093           if (getLangOpts().MSVCCompat)
15094             FriendSawTagOutsideEnclosingNamespace = true;
15095           else
15096             F.erase();
15097         }
15098       }
15099       F.done();
15100 
15101       // Diagnose this MSVC extension in the easy case where lookup would have
15102       // unambiguously found something outside the enclosing namespace.
15103       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
15104         NamedDecl *ND = Previous.getFoundDecl();
15105         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
15106             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
15107       }
15108     }
15109 
15110     // Note:  there used to be some attempt at recovery here.
15111     if (Previous.isAmbiguous())
15112       return nullptr;
15113 
15114     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
15115       // FIXME: This makes sure that we ignore the contexts associated
15116       // with C structs, unions, and enums when looking for a matching
15117       // tag declaration or definition. See the similar lookup tweak
15118       // in Sema::LookupName; is there a better way to deal with this?
15119       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
15120         SearchDC = SearchDC->getParent();
15121     }
15122   }
15123 
15124   if (Previous.isSingleResult() &&
15125       Previous.getFoundDecl()->isTemplateParameter()) {
15126     // Maybe we will complain about the shadowed template parameter.
15127     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
15128     // Just pretend that we didn't see the previous declaration.
15129     Previous.clear();
15130   }
15131 
15132   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
15133       DC->Equals(getStdNamespace())) {
15134     if (Name->isStr("bad_alloc")) {
15135       // This is a declaration of or a reference to "std::bad_alloc".
15136       isStdBadAlloc = true;
15137 
15138       // If std::bad_alloc has been implicitly declared (but made invisible to
15139       // name lookup), fill in this implicit declaration as the previous
15140       // declaration, so that the declarations get chained appropriately.
15141       if (Previous.empty() && StdBadAlloc)
15142         Previous.addDecl(getStdBadAlloc());
15143     } else if (Name->isStr("align_val_t")) {
15144       isStdAlignValT = true;
15145       if (Previous.empty() && StdAlignValT)
15146         Previous.addDecl(getStdAlignValT());
15147     }
15148   }
15149 
15150   // If we didn't find a previous declaration, and this is a reference
15151   // (or friend reference), move to the correct scope.  In C++, we
15152   // also need to do a redeclaration lookup there, just in case
15153   // there's a shadow friend decl.
15154   if (Name && Previous.empty() &&
15155       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
15156     if (Invalid) goto CreateNewDecl;
15157     assert(SS.isEmpty());
15158 
15159     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
15160       // C++ [basic.scope.pdecl]p5:
15161       //   -- for an elaborated-type-specifier of the form
15162       //
15163       //          class-key identifier
15164       //
15165       //      if the elaborated-type-specifier is used in the
15166       //      decl-specifier-seq or parameter-declaration-clause of a
15167       //      function defined in namespace scope, the identifier is
15168       //      declared as a class-name in the namespace that contains
15169       //      the declaration; otherwise, except as a friend
15170       //      declaration, the identifier is declared in the smallest
15171       //      non-class, non-function-prototype scope that contains the
15172       //      declaration.
15173       //
15174       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
15175       // C structs and unions.
15176       //
15177       // It is an error in C++ to declare (rather than define) an enum
15178       // type, including via an elaborated type specifier.  We'll
15179       // diagnose that later; for now, declare the enum in the same
15180       // scope as we would have picked for any other tag type.
15181       //
15182       // GNU C also supports this behavior as part of its incomplete
15183       // enum types extension, while GNU C++ does not.
15184       //
15185       // Find the context where we'll be declaring the tag.
15186       // FIXME: We would like to maintain the current DeclContext as the
15187       // lexical context,
15188       SearchDC = getTagInjectionContext(SearchDC);
15189 
15190       // Find the scope where we'll be declaring the tag.
15191       S = getTagInjectionScope(S, getLangOpts());
15192     } else {
15193       assert(TUK == TUK_Friend);
15194       // C++ [namespace.memdef]p3:
15195       //   If a friend declaration in a non-local class first declares a
15196       //   class or function, the friend class or function is a member of
15197       //   the innermost enclosing namespace.
15198       SearchDC = SearchDC->getEnclosingNamespaceContext();
15199     }
15200 
15201     // In C++, we need to do a redeclaration lookup to properly
15202     // diagnose some problems.
15203     // FIXME: redeclaration lookup is also used (with and without C++) to find a
15204     // hidden declaration so that we don't get ambiguity errors when using a
15205     // type declared by an elaborated-type-specifier.  In C that is not correct
15206     // and we should instead merge compatible types found by lookup.
15207     if (getLangOpts().CPlusPlus) {
15208       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15209       LookupQualifiedName(Previous, SearchDC);
15210     } else {
15211       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15212       LookupName(Previous, S);
15213     }
15214   }
15215 
15216   // If we have a known previous declaration to use, then use it.
15217   if (Previous.empty() && SkipBody && SkipBody->Previous)
15218     Previous.addDecl(SkipBody->Previous);
15219 
15220   if (!Previous.empty()) {
15221     NamedDecl *PrevDecl = Previous.getFoundDecl();
15222     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
15223 
15224     // It's okay to have a tag decl in the same scope as a typedef
15225     // which hides a tag decl in the same scope.  Finding this
15226     // insanity with a redeclaration lookup can only actually happen
15227     // in C++.
15228     //
15229     // This is also okay for elaborated-type-specifiers, which is
15230     // technically forbidden by the current standard but which is
15231     // okay according to the likely resolution of an open issue;
15232     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
15233     if (getLangOpts().CPlusPlus) {
15234       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15235         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
15236           TagDecl *Tag = TT->getDecl();
15237           if (Tag->getDeclName() == Name &&
15238               Tag->getDeclContext()->getRedeclContext()
15239                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
15240             PrevDecl = Tag;
15241             Previous.clear();
15242             Previous.addDecl(Tag);
15243             Previous.resolveKind();
15244           }
15245         }
15246       }
15247     }
15248 
15249     // If this is a redeclaration of a using shadow declaration, it must
15250     // declare a tag in the same context. In MSVC mode, we allow a
15251     // redefinition if either context is within the other.
15252     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
15253       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
15254       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
15255           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
15256           !(OldTag && isAcceptableTagRedeclContext(
15257                           *this, OldTag->getDeclContext(), SearchDC))) {
15258         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
15259         Diag(Shadow->getTargetDecl()->getLocation(),
15260              diag::note_using_decl_target);
15261         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
15262             << 0;
15263         // Recover by ignoring the old declaration.
15264         Previous.clear();
15265         goto CreateNewDecl;
15266       }
15267     }
15268 
15269     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
15270       // If this is a use of a previous tag, or if the tag is already declared
15271       // in the same scope (so that the definition/declaration completes or
15272       // rementions the tag), reuse the decl.
15273       if (TUK == TUK_Reference || TUK == TUK_Friend ||
15274           isDeclInScope(DirectPrevDecl, SearchDC, S,
15275                         SS.isNotEmpty() || isMemberSpecialization)) {
15276         // Make sure that this wasn't declared as an enum and now used as a
15277         // struct or something similar.
15278         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
15279                                           TUK == TUK_Definition, KWLoc,
15280                                           Name)) {
15281           bool SafeToContinue
15282             = (PrevTagDecl->getTagKind() != TTK_Enum &&
15283                Kind != TTK_Enum);
15284           if (SafeToContinue)
15285             Diag(KWLoc, diag::err_use_with_wrong_tag)
15286               << Name
15287               << FixItHint::CreateReplacement(SourceRange(KWLoc),
15288                                               PrevTagDecl->getKindName());
15289           else
15290             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
15291           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
15292 
15293           if (SafeToContinue)
15294             Kind = PrevTagDecl->getTagKind();
15295           else {
15296             // Recover by making this an anonymous redefinition.
15297             Name = nullptr;
15298             Previous.clear();
15299             Invalid = true;
15300           }
15301         }
15302 
15303         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
15304           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
15305 
15306           // If this is an elaborated-type-specifier for a scoped enumeration,
15307           // the 'class' keyword is not necessary and not permitted.
15308           if (TUK == TUK_Reference || TUK == TUK_Friend) {
15309             if (ScopedEnum)
15310               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
15311                 << PrevEnum->isScoped()
15312                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
15313             return PrevTagDecl;
15314           }
15315 
15316           QualType EnumUnderlyingTy;
15317           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15318             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
15319           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
15320             EnumUnderlyingTy = QualType(T, 0);
15321 
15322           // All conflicts with previous declarations are recovered by
15323           // returning the previous declaration, unless this is a definition,
15324           // in which case we want the caller to bail out.
15325           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
15326                                      ScopedEnum, EnumUnderlyingTy,
15327                                      IsFixed, PrevEnum))
15328             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
15329         }
15330 
15331         // C++11 [class.mem]p1:
15332         //   A member shall not be declared twice in the member-specification,
15333         //   except that a nested class or member class template can be declared
15334         //   and then later defined.
15335         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
15336             S->isDeclScope(PrevDecl)) {
15337           Diag(NameLoc, diag::ext_member_redeclared);
15338           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
15339         }
15340 
15341         if (!Invalid) {
15342           // If this is a use, just return the declaration we found, unless
15343           // we have attributes.
15344           if (TUK == TUK_Reference || TUK == TUK_Friend) {
15345             if (!Attrs.empty()) {
15346               // FIXME: Diagnose these attributes. For now, we create a new
15347               // declaration to hold them.
15348             } else if (TUK == TUK_Reference &&
15349                        (PrevTagDecl->getFriendObjectKind() ==
15350                             Decl::FOK_Undeclared ||
15351                         PrevDecl->getOwningModule() != getCurrentModule()) &&
15352                        SS.isEmpty()) {
15353               // This declaration is a reference to an existing entity, but
15354               // has different visibility from that entity: it either makes
15355               // a friend visible or it makes a type visible in a new module.
15356               // In either case, create a new declaration. We only do this if
15357               // the declaration would have meant the same thing if no prior
15358               // declaration were found, that is, if it was found in the same
15359               // scope where we would have injected a declaration.
15360               if (!getTagInjectionContext(CurContext)->getRedeclContext()
15361                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
15362                 return PrevTagDecl;
15363               // This is in the injected scope, create a new declaration in
15364               // that scope.
15365               S = getTagInjectionScope(S, getLangOpts());
15366             } else {
15367               return PrevTagDecl;
15368             }
15369           }
15370 
15371           // Diagnose attempts to redefine a tag.
15372           if (TUK == TUK_Definition) {
15373             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
15374               // If we're defining a specialization and the previous definition
15375               // is from an implicit instantiation, don't emit an error
15376               // here; we'll catch this in the general case below.
15377               bool IsExplicitSpecializationAfterInstantiation = false;
15378               if (isMemberSpecialization) {
15379                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
15380                   IsExplicitSpecializationAfterInstantiation =
15381                     RD->getTemplateSpecializationKind() !=
15382                     TSK_ExplicitSpecialization;
15383                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
15384                   IsExplicitSpecializationAfterInstantiation =
15385                     ED->getTemplateSpecializationKind() !=
15386                     TSK_ExplicitSpecialization;
15387               }
15388 
15389               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
15390               // not keep more that one definition around (merge them). However,
15391               // ensure the decl passes the structural compatibility check in
15392               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
15393               NamedDecl *Hidden = nullptr;
15394               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
15395                 // There is a definition of this tag, but it is not visible. We
15396                 // explicitly make use of C++'s one definition rule here, and
15397                 // assume that this definition is identical to the hidden one
15398                 // we already have. Make the existing definition visible and
15399                 // use it in place of this one.
15400                 if (!getLangOpts().CPlusPlus) {
15401                   // Postpone making the old definition visible until after we
15402                   // complete parsing the new one and do the structural
15403                   // comparison.
15404                   SkipBody->CheckSameAsPrevious = true;
15405                   SkipBody->New = createTagFromNewDecl();
15406                   SkipBody->Previous = Def;
15407                   return Def;
15408                 } else {
15409                   SkipBody->ShouldSkip = true;
15410                   SkipBody->Previous = Def;
15411                   makeMergedDefinitionVisible(Hidden);
15412                   // Carry on and handle it like a normal definition. We'll
15413                   // skip starting the definitiion later.
15414                 }
15415               } else if (!IsExplicitSpecializationAfterInstantiation) {
15416                 // A redeclaration in function prototype scope in C isn't
15417                 // visible elsewhere, so merely issue a warning.
15418                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
15419                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
15420                 else
15421                   Diag(NameLoc, diag::err_redefinition) << Name;
15422                 notePreviousDefinition(Def,
15423                                        NameLoc.isValid() ? NameLoc : KWLoc);
15424                 // If this is a redefinition, recover by making this
15425                 // struct be anonymous, which will make any later
15426                 // references get the previous definition.
15427                 Name = nullptr;
15428                 Previous.clear();
15429                 Invalid = true;
15430               }
15431             } else {
15432               // If the type is currently being defined, complain
15433               // about a nested redefinition.
15434               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
15435               if (TD->isBeingDefined()) {
15436                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
15437                 Diag(PrevTagDecl->getLocation(),
15438                      diag::note_previous_definition);
15439                 Name = nullptr;
15440                 Previous.clear();
15441                 Invalid = true;
15442               }
15443             }
15444 
15445             // Okay, this is definition of a previously declared or referenced
15446             // tag. We're going to create a new Decl for it.
15447           }
15448 
15449           // Okay, we're going to make a redeclaration.  If this is some kind
15450           // of reference, make sure we build the redeclaration in the same DC
15451           // as the original, and ignore the current access specifier.
15452           if (TUK == TUK_Friend || TUK == TUK_Reference) {
15453             SearchDC = PrevTagDecl->getDeclContext();
15454             AS = AS_none;
15455           }
15456         }
15457         // If we get here we have (another) forward declaration or we
15458         // have a definition.  Just create a new decl.
15459 
15460       } else {
15461         // If we get here, this is a definition of a new tag type in a nested
15462         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
15463         // new decl/type.  We set PrevDecl to NULL so that the entities
15464         // have distinct types.
15465         Previous.clear();
15466       }
15467       // If we get here, we're going to create a new Decl. If PrevDecl
15468       // is non-NULL, it's a definition of the tag declared by
15469       // PrevDecl. If it's NULL, we have a new definition.
15470 
15471     // Otherwise, PrevDecl is not a tag, but was found with tag
15472     // lookup.  This is only actually possible in C++, where a few
15473     // things like templates still live in the tag namespace.
15474     } else {
15475       // Use a better diagnostic if an elaborated-type-specifier
15476       // found the wrong kind of type on the first
15477       // (non-redeclaration) lookup.
15478       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
15479           !Previous.isForRedeclaration()) {
15480         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15481         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
15482                                                        << Kind;
15483         Diag(PrevDecl->getLocation(), diag::note_declared_at);
15484         Invalid = true;
15485 
15486       // Otherwise, only diagnose if the declaration is in scope.
15487       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
15488                                 SS.isNotEmpty() || isMemberSpecialization)) {
15489         // do nothing
15490 
15491       // Diagnose implicit declarations introduced by elaborated types.
15492       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
15493         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15494         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
15495         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15496         Invalid = true;
15497 
15498       // Otherwise it's a declaration.  Call out a particularly common
15499       // case here.
15500       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15501         unsigned Kind = 0;
15502         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
15503         Diag(NameLoc, diag::err_tag_definition_of_typedef)
15504           << Name << Kind << TND->getUnderlyingType();
15505         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15506         Invalid = true;
15507 
15508       // Otherwise, diagnose.
15509       } else {
15510         // The tag name clashes with something else in the target scope,
15511         // issue an error and recover by making this tag be anonymous.
15512         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
15513         notePreviousDefinition(PrevDecl, NameLoc);
15514         Name = nullptr;
15515         Invalid = true;
15516       }
15517 
15518       // The existing declaration isn't relevant to us; we're in a
15519       // new scope, so clear out the previous declaration.
15520       Previous.clear();
15521     }
15522   }
15523 
15524 CreateNewDecl:
15525 
15526   TagDecl *PrevDecl = nullptr;
15527   if (Previous.isSingleResult())
15528     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
15529 
15530   // If there is an identifier, use the location of the identifier as the
15531   // location of the decl, otherwise use the location of the struct/union
15532   // keyword.
15533   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15534 
15535   // Otherwise, create a new declaration. If there is a previous
15536   // declaration of the same entity, the two will be linked via
15537   // PrevDecl.
15538   TagDecl *New;
15539 
15540   if (Kind == TTK_Enum) {
15541     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15542     // enum X { A, B, C } D;    D should chain to X.
15543     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
15544                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
15545                            ScopedEnumUsesClassTag, IsFixed);
15546 
15547     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
15548       StdAlignValT = cast<EnumDecl>(New);
15549 
15550     // If this is an undefined enum, warn.
15551     if (TUK != TUK_Definition && !Invalid) {
15552       TagDecl *Def;
15553       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
15554         // C++0x: 7.2p2: opaque-enum-declaration.
15555         // Conflicts are diagnosed above. Do nothing.
15556       }
15557       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
15558         Diag(Loc, diag::ext_forward_ref_enum_def)
15559           << New;
15560         Diag(Def->getLocation(), diag::note_previous_definition);
15561       } else {
15562         unsigned DiagID = diag::ext_forward_ref_enum;
15563         if (getLangOpts().MSVCCompat)
15564           DiagID = diag::ext_ms_forward_ref_enum;
15565         else if (getLangOpts().CPlusPlus)
15566           DiagID = diag::err_forward_ref_enum;
15567         Diag(Loc, DiagID);
15568       }
15569     }
15570 
15571     if (EnumUnderlying) {
15572       EnumDecl *ED = cast<EnumDecl>(New);
15573       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15574         ED->setIntegerTypeSourceInfo(TI);
15575       else
15576         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
15577       ED->setPromotionType(ED->getIntegerType());
15578       assert(ED->isComplete() && "enum with type should be complete");
15579     }
15580   } else {
15581     // struct/union/class
15582 
15583     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15584     // struct X { int A; } D;    D should chain to X.
15585     if (getLangOpts().CPlusPlus) {
15586       // FIXME: Look for a way to use RecordDecl for simple structs.
15587       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15588                                   cast_or_null<CXXRecordDecl>(PrevDecl));
15589 
15590       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
15591         StdBadAlloc = cast<CXXRecordDecl>(New);
15592     } else
15593       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15594                                cast_or_null<RecordDecl>(PrevDecl));
15595   }
15596 
15597   // C++11 [dcl.type]p3:
15598   //   A type-specifier-seq shall not define a class or enumeration [...].
15599   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
15600       TUK == TUK_Definition) {
15601     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
15602       << Context.getTagDeclType(New);
15603     Invalid = true;
15604   }
15605 
15606   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
15607       DC->getDeclKind() == Decl::Enum) {
15608     Diag(New->getLocation(), diag::err_type_defined_in_enum)
15609       << Context.getTagDeclType(New);
15610     Invalid = true;
15611   }
15612 
15613   // Maybe add qualifier info.
15614   if (SS.isNotEmpty()) {
15615     if (SS.isSet()) {
15616       // If this is either a declaration or a definition, check the
15617       // nested-name-specifier against the current context.
15618       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
15619           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
15620                                        isMemberSpecialization))
15621         Invalid = true;
15622 
15623       New->setQualifierInfo(SS.getWithLocInContext(Context));
15624       if (TemplateParameterLists.size() > 0) {
15625         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
15626       }
15627     }
15628     else
15629       Invalid = true;
15630   }
15631 
15632   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15633     // Add alignment attributes if necessary; these attributes are checked when
15634     // the ASTContext lays out the structure.
15635     //
15636     // It is important for implementing the correct semantics that this
15637     // happen here (in ActOnTag). The #pragma pack stack is
15638     // maintained as a result of parser callbacks which can occur at
15639     // many points during the parsing of a struct declaration (because
15640     // the #pragma tokens are effectively skipped over during the
15641     // parsing of the struct).
15642     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15643       AddAlignmentAttributesForRecord(RD);
15644       AddMsStructLayoutForRecord(RD);
15645     }
15646   }
15647 
15648   if (ModulePrivateLoc.isValid()) {
15649     if (isMemberSpecialization)
15650       Diag(New->getLocation(), diag::err_module_private_specialization)
15651         << 2
15652         << FixItHint::CreateRemoval(ModulePrivateLoc);
15653     // __module_private__ does not apply to local classes. However, we only
15654     // diagnose this as an error when the declaration specifiers are
15655     // freestanding. Here, we just ignore the __module_private__.
15656     else if (!SearchDC->isFunctionOrMethod())
15657       New->setModulePrivate();
15658   }
15659 
15660   // If this is a specialization of a member class (of a class template),
15661   // check the specialization.
15662   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
15663     Invalid = true;
15664 
15665   // If we're declaring or defining a tag in function prototype scope in C,
15666   // note that this type can only be used within the function and add it to
15667   // the list of decls to inject into the function definition scope.
15668   if ((Name || Kind == TTK_Enum) &&
15669       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
15670     if (getLangOpts().CPlusPlus) {
15671       // C++ [dcl.fct]p6:
15672       //   Types shall not be defined in return or parameter types.
15673       if (TUK == TUK_Definition && !IsTypeSpecifier) {
15674         Diag(Loc, diag::err_type_defined_in_param_type)
15675             << Name;
15676         Invalid = true;
15677       }
15678     } else if (!PrevDecl) {
15679       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
15680     }
15681   }
15682 
15683   if (Invalid)
15684     New->setInvalidDecl();
15685 
15686   // Set the lexical context. If the tag has a C++ scope specifier, the
15687   // lexical context will be different from the semantic context.
15688   New->setLexicalDeclContext(CurContext);
15689 
15690   // Mark this as a friend decl if applicable.
15691   // In Microsoft mode, a friend declaration also acts as a forward
15692   // declaration so we always pass true to setObjectOfFriendDecl to make
15693   // the tag name visible.
15694   if (TUK == TUK_Friend)
15695     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
15696 
15697   // Set the access specifier.
15698   if (!Invalid && SearchDC->isRecord())
15699     SetMemberAccessSpecifier(New, PrevDecl, AS);
15700 
15701   if (PrevDecl)
15702     CheckRedeclarationModuleOwnership(New, PrevDecl);
15703 
15704   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
15705     New->startDefinition();
15706 
15707   ProcessDeclAttributeList(S, New, Attrs);
15708   AddPragmaAttributes(S, New);
15709 
15710   // If this has an identifier, add it to the scope stack.
15711   if (TUK == TUK_Friend) {
15712     // We might be replacing an existing declaration in the lookup tables;
15713     // if so, borrow its access specifier.
15714     if (PrevDecl)
15715       New->setAccess(PrevDecl->getAccess());
15716 
15717     DeclContext *DC = New->getDeclContext()->getRedeclContext();
15718     DC->makeDeclVisibleInContext(New);
15719     if (Name) // can be null along some error paths
15720       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
15721         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
15722   } else if (Name) {
15723     S = getNonFieldDeclScope(S);
15724     PushOnScopeChains(New, S, true);
15725   } else {
15726     CurContext->addDecl(New);
15727   }
15728 
15729   // If this is the C FILE type, notify the AST context.
15730   if (IdentifierInfo *II = New->getIdentifier())
15731     if (!New->isInvalidDecl() &&
15732         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
15733         II->isStr("FILE"))
15734       Context.setFILEDecl(New);
15735 
15736   if (PrevDecl)
15737     mergeDeclAttributes(New, PrevDecl);
15738 
15739   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
15740     inferGslOwnerPointerAttribute(CXXRD);
15741 
15742   // If there's a #pragma GCC visibility in scope, set the visibility of this
15743   // record.
15744   AddPushedVisibilityAttribute(New);
15745 
15746   if (isMemberSpecialization && !New->isInvalidDecl())
15747     CompleteMemberSpecialization(New, Previous);
15748 
15749   OwnedDecl = true;
15750   // In C++, don't return an invalid declaration. We can't recover well from
15751   // the cases where we make the type anonymous.
15752   if (Invalid && getLangOpts().CPlusPlus) {
15753     if (New->isBeingDefined())
15754       if (auto RD = dyn_cast<RecordDecl>(New))
15755         RD->completeDefinition();
15756     return nullptr;
15757   } else if (SkipBody && SkipBody->ShouldSkip) {
15758     return SkipBody->Previous;
15759   } else {
15760     return New;
15761   }
15762 }
15763 
15764 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
15765   AdjustDeclIfTemplate(TagD);
15766   TagDecl *Tag = cast<TagDecl>(TagD);
15767 
15768   // Enter the tag context.
15769   PushDeclContext(S, Tag);
15770 
15771   ActOnDocumentableDecl(TagD);
15772 
15773   // If there's a #pragma GCC visibility in scope, set the visibility of this
15774   // record.
15775   AddPushedVisibilityAttribute(Tag);
15776 }
15777 
15778 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
15779                                     SkipBodyInfo &SkipBody) {
15780   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
15781     return false;
15782 
15783   // Make the previous decl visible.
15784   makeMergedDefinitionVisible(SkipBody.Previous);
15785   return true;
15786 }
15787 
15788 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
15789   assert(isa<ObjCContainerDecl>(IDecl) &&
15790          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
15791   DeclContext *OCD = cast<DeclContext>(IDecl);
15792   assert(getContainingDC(OCD) == CurContext &&
15793       "The next DeclContext should be lexically contained in the current one.");
15794   CurContext = OCD;
15795   return IDecl;
15796 }
15797 
15798 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
15799                                            SourceLocation FinalLoc,
15800                                            bool IsFinalSpelledSealed,
15801                                            SourceLocation LBraceLoc) {
15802   AdjustDeclIfTemplate(TagD);
15803   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
15804 
15805   FieldCollector->StartClass();
15806 
15807   if (!Record->getIdentifier())
15808     return;
15809 
15810   if (FinalLoc.isValid())
15811     Record->addAttr(FinalAttr::Create(
15812         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
15813         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
15814 
15815   // C++ [class]p2:
15816   //   [...] The class-name is also inserted into the scope of the
15817   //   class itself; this is known as the injected-class-name. For
15818   //   purposes of access checking, the injected-class-name is treated
15819   //   as if it were a public member name.
15820   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
15821       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
15822       Record->getLocation(), Record->getIdentifier(),
15823       /*PrevDecl=*/nullptr,
15824       /*DelayTypeCreation=*/true);
15825   Context.getTypeDeclType(InjectedClassName, Record);
15826   InjectedClassName->setImplicit();
15827   InjectedClassName->setAccess(AS_public);
15828   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
15829       InjectedClassName->setDescribedClassTemplate(Template);
15830   PushOnScopeChains(InjectedClassName, S);
15831   assert(InjectedClassName->isInjectedClassName() &&
15832          "Broken injected-class-name");
15833 }
15834 
15835 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
15836                                     SourceRange BraceRange) {
15837   AdjustDeclIfTemplate(TagD);
15838   TagDecl *Tag = cast<TagDecl>(TagD);
15839   Tag->setBraceRange(BraceRange);
15840 
15841   // Make sure we "complete" the definition even it is invalid.
15842   if (Tag->isBeingDefined()) {
15843     assert(Tag->isInvalidDecl() && "We should already have completed it");
15844     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15845       RD->completeDefinition();
15846   }
15847 
15848   if (isa<CXXRecordDecl>(Tag)) {
15849     FieldCollector->FinishClass();
15850   }
15851 
15852   // Exit this scope of this tag's definition.
15853   PopDeclContext();
15854 
15855   if (getCurLexicalContext()->isObjCContainer() &&
15856       Tag->getDeclContext()->isFileContext())
15857     Tag->setTopLevelDeclInObjCContainer();
15858 
15859   // Notify the consumer that we've defined a tag.
15860   if (!Tag->isInvalidDecl())
15861     Consumer.HandleTagDeclDefinition(Tag);
15862 }
15863 
15864 void Sema::ActOnObjCContainerFinishDefinition() {
15865   // Exit this scope of this interface definition.
15866   PopDeclContext();
15867 }
15868 
15869 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
15870   assert(DC == CurContext && "Mismatch of container contexts");
15871   OriginalLexicalContext = DC;
15872   ActOnObjCContainerFinishDefinition();
15873 }
15874 
15875 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
15876   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
15877   OriginalLexicalContext = nullptr;
15878 }
15879 
15880 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
15881   AdjustDeclIfTemplate(TagD);
15882   TagDecl *Tag = cast<TagDecl>(TagD);
15883   Tag->setInvalidDecl();
15884 
15885   // Make sure we "complete" the definition even it is invalid.
15886   if (Tag->isBeingDefined()) {
15887     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15888       RD->completeDefinition();
15889   }
15890 
15891   // We're undoing ActOnTagStartDefinition here, not
15892   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
15893   // the FieldCollector.
15894 
15895   PopDeclContext();
15896 }
15897 
15898 // Note that FieldName may be null for anonymous bitfields.
15899 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
15900                                 IdentifierInfo *FieldName,
15901                                 QualType FieldTy, bool IsMsStruct,
15902                                 Expr *BitWidth, bool *ZeroWidth) {
15903   // Default to true; that shouldn't confuse checks for emptiness
15904   if (ZeroWidth)
15905     *ZeroWidth = true;
15906 
15907   // C99 6.7.2.1p4 - verify the field type.
15908   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
15909   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
15910     // Handle incomplete types with specific error.
15911     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
15912       return ExprError();
15913     if (FieldName)
15914       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
15915         << FieldName << FieldTy << BitWidth->getSourceRange();
15916     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
15917       << FieldTy << BitWidth->getSourceRange();
15918   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
15919                                              UPPC_BitFieldWidth))
15920     return ExprError();
15921 
15922   // If the bit-width is type- or value-dependent, don't try to check
15923   // it now.
15924   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
15925     return BitWidth;
15926 
15927   llvm::APSInt Value;
15928   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
15929   if (ICE.isInvalid())
15930     return ICE;
15931   BitWidth = ICE.get();
15932 
15933   if (Value != 0 && ZeroWidth)
15934     *ZeroWidth = false;
15935 
15936   // Zero-width bitfield is ok for anonymous field.
15937   if (Value == 0 && FieldName)
15938     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
15939 
15940   if (Value.isSigned() && Value.isNegative()) {
15941     if (FieldName)
15942       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
15943                << FieldName << Value.toString(10);
15944     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
15945       << Value.toString(10);
15946   }
15947 
15948   if (!FieldTy->isDependentType()) {
15949     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
15950     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
15951     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
15952 
15953     // Over-wide bitfields are an error in C or when using the MSVC bitfield
15954     // ABI.
15955     bool CStdConstraintViolation =
15956         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
15957     bool MSBitfieldViolation =
15958         Value.ugt(TypeStorageSize) &&
15959         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
15960     if (CStdConstraintViolation || MSBitfieldViolation) {
15961       unsigned DiagWidth =
15962           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
15963       if (FieldName)
15964         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
15965                << FieldName << (unsigned)Value.getZExtValue()
15966                << !CStdConstraintViolation << DiagWidth;
15967 
15968       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
15969              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
15970              << DiagWidth;
15971     }
15972 
15973     // Warn on types where the user might conceivably expect to get all
15974     // specified bits as value bits: that's all integral types other than
15975     // 'bool'.
15976     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
15977       if (FieldName)
15978         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
15979             << FieldName << (unsigned)Value.getZExtValue()
15980             << (unsigned)TypeWidth;
15981       else
15982         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
15983             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
15984     }
15985   }
15986 
15987   return BitWidth;
15988 }
15989 
15990 /// ActOnField - Each field of a C struct/union is passed into this in order
15991 /// to create a FieldDecl object for it.
15992 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
15993                        Declarator &D, Expr *BitfieldWidth) {
15994   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
15995                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
15996                                /*InitStyle=*/ICIS_NoInit, AS_public);
15997   return Res;
15998 }
15999 
16000 /// HandleField - Analyze a field of a C struct or a C++ data member.
16001 ///
16002 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
16003                              SourceLocation DeclStart,
16004                              Declarator &D, Expr *BitWidth,
16005                              InClassInitStyle InitStyle,
16006                              AccessSpecifier AS) {
16007   if (D.isDecompositionDeclarator()) {
16008     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
16009     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
16010       << Decomp.getSourceRange();
16011     return nullptr;
16012   }
16013 
16014   IdentifierInfo *II = D.getIdentifier();
16015   SourceLocation Loc = DeclStart;
16016   if (II) Loc = D.getIdentifierLoc();
16017 
16018   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16019   QualType T = TInfo->getType();
16020   if (getLangOpts().CPlusPlus) {
16021     CheckExtraCXXDefaultArguments(D);
16022 
16023     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16024                                         UPPC_DataMemberType)) {
16025       D.setInvalidType();
16026       T = Context.IntTy;
16027       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
16028     }
16029   }
16030 
16031   DiagnoseFunctionSpecifiers(D.getDeclSpec());
16032 
16033   if (D.getDeclSpec().isInlineSpecified())
16034     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
16035         << getLangOpts().CPlusPlus17;
16036   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
16037     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
16038          diag::err_invalid_thread)
16039       << DeclSpec::getSpecifierName(TSCS);
16040 
16041   // Check to see if this name was declared as a member previously
16042   NamedDecl *PrevDecl = nullptr;
16043   LookupResult Previous(*this, II, Loc, LookupMemberName,
16044                         ForVisibleRedeclaration);
16045   LookupName(Previous, S);
16046   switch (Previous.getResultKind()) {
16047     case LookupResult::Found:
16048     case LookupResult::FoundUnresolvedValue:
16049       PrevDecl = Previous.getAsSingle<NamedDecl>();
16050       break;
16051 
16052     case LookupResult::FoundOverloaded:
16053       PrevDecl = Previous.getRepresentativeDecl();
16054       break;
16055 
16056     case LookupResult::NotFound:
16057     case LookupResult::NotFoundInCurrentInstantiation:
16058     case LookupResult::Ambiguous:
16059       break;
16060   }
16061   Previous.suppressDiagnostics();
16062 
16063   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16064     // Maybe we will complain about the shadowed template parameter.
16065     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16066     // Just pretend that we didn't see the previous declaration.
16067     PrevDecl = nullptr;
16068   }
16069 
16070   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
16071     PrevDecl = nullptr;
16072 
16073   bool Mutable
16074     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
16075   SourceLocation TSSL = D.getBeginLoc();
16076   FieldDecl *NewFD
16077     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
16078                      TSSL, AS, PrevDecl, &D);
16079 
16080   if (NewFD->isInvalidDecl())
16081     Record->setInvalidDecl();
16082 
16083   if (D.getDeclSpec().isModulePrivateSpecified())
16084     NewFD->setModulePrivate();
16085 
16086   if (NewFD->isInvalidDecl() && PrevDecl) {
16087     // Don't introduce NewFD into scope; there's already something
16088     // with the same name in the same scope.
16089   } else if (II) {
16090     PushOnScopeChains(NewFD, S);
16091   } else
16092     Record->addDecl(NewFD);
16093 
16094   return NewFD;
16095 }
16096 
16097 /// Build a new FieldDecl and check its well-formedness.
16098 ///
16099 /// This routine builds a new FieldDecl given the fields name, type,
16100 /// record, etc. \p PrevDecl should refer to any previous declaration
16101 /// with the same name and in the same scope as the field to be
16102 /// created.
16103 ///
16104 /// \returns a new FieldDecl.
16105 ///
16106 /// \todo The Declarator argument is a hack. It will be removed once
16107 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
16108                                 TypeSourceInfo *TInfo,
16109                                 RecordDecl *Record, SourceLocation Loc,
16110                                 bool Mutable, Expr *BitWidth,
16111                                 InClassInitStyle InitStyle,
16112                                 SourceLocation TSSL,
16113                                 AccessSpecifier AS, NamedDecl *PrevDecl,
16114                                 Declarator *D) {
16115   IdentifierInfo *II = Name.getAsIdentifierInfo();
16116   bool InvalidDecl = false;
16117   if (D) InvalidDecl = D->isInvalidType();
16118 
16119   // If we receive a broken type, recover by assuming 'int' and
16120   // marking this declaration as invalid.
16121   if (T.isNull()) {
16122     InvalidDecl = true;
16123     T = Context.IntTy;
16124   }
16125 
16126   QualType EltTy = Context.getBaseElementType(T);
16127   if (!EltTy->isDependentType()) {
16128     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
16129       // Fields of incomplete type force their record to be invalid.
16130       Record->setInvalidDecl();
16131       InvalidDecl = true;
16132     } else {
16133       NamedDecl *Def;
16134       EltTy->isIncompleteType(&Def);
16135       if (Def && Def->isInvalidDecl()) {
16136         Record->setInvalidDecl();
16137         InvalidDecl = true;
16138       }
16139     }
16140   }
16141 
16142   // TR 18037 does not allow fields to be declared with address space
16143   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
16144       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
16145     Diag(Loc, diag::err_field_with_address_space);
16146     Record->setInvalidDecl();
16147     InvalidDecl = true;
16148   }
16149 
16150   if (LangOpts.OpenCL) {
16151     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
16152     // used as structure or union field: image, sampler, event or block types.
16153     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
16154         T->isBlockPointerType()) {
16155       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
16156       Record->setInvalidDecl();
16157       InvalidDecl = true;
16158     }
16159     // OpenCL v1.2 s6.9.c: bitfields are not supported.
16160     if (BitWidth) {
16161       Diag(Loc, diag::err_opencl_bitfields);
16162       InvalidDecl = true;
16163     }
16164   }
16165 
16166   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
16167   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
16168       T.hasQualifiers()) {
16169     InvalidDecl = true;
16170     Diag(Loc, diag::err_anon_bitfield_qualifiers);
16171   }
16172 
16173   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16174   // than a variably modified type.
16175   if (!InvalidDecl && T->isVariablyModifiedType()) {
16176     bool SizeIsNegative;
16177     llvm::APSInt Oversized;
16178 
16179     TypeSourceInfo *FixedTInfo =
16180       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
16181                                                     SizeIsNegative,
16182                                                     Oversized);
16183     if (FixedTInfo) {
16184       Diag(Loc, diag::warn_illegal_constant_array_size);
16185       TInfo = FixedTInfo;
16186       T = FixedTInfo->getType();
16187     } else {
16188       if (SizeIsNegative)
16189         Diag(Loc, diag::err_typecheck_negative_array_size);
16190       else if (Oversized.getBoolValue())
16191         Diag(Loc, diag::err_array_too_large)
16192           << Oversized.toString(10);
16193       else
16194         Diag(Loc, diag::err_typecheck_field_variable_size);
16195       InvalidDecl = true;
16196     }
16197   }
16198 
16199   // Fields can not have abstract class types
16200   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
16201                                              diag::err_abstract_type_in_decl,
16202                                              AbstractFieldType))
16203     InvalidDecl = true;
16204 
16205   bool ZeroWidth = false;
16206   if (InvalidDecl)
16207     BitWidth = nullptr;
16208   // If this is declared as a bit-field, check the bit-field.
16209   if (BitWidth) {
16210     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
16211                               &ZeroWidth).get();
16212     if (!BitWidth) {
16213       InvalidDecl = true;
16214       BitWidth = nullptr;
16215       ZeroWidth = false;
16216     }
16217   }
16218 
16219   // Check that 'mutable' is consistent with the type of the declaration.
16220   if (!InvalidDecl && Mutable) {
16221     unsigned DiagID = 0;
16222     if (T->isReferenceType())
16223       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
16224                                         : diag::err_mutable_reference;
16225     else if (T.isConstQualified())
16226       DiagID = diag::err_mutable_const;
16227 
16228     if (DiagID) {
16229       SourceLocation ErrLoc = Loc;
16230       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
16231         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
16232       Diag(ErrLoc, DiagID);
16233       if (DiagID != diag::ext_mutable_reference) {
16234         Mutable = false;
16235         InvalidDecl = true;
16236       }
16237     }
16238   }
16239 
16240   // C++11 [class.union]p8 (DR1460):
16241   //   At most one variant member of a union may have a
16242   //   brace-or-equal-initializer.
16243   if (InitStyle != ICIS_NoInit)
16244     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
16245 
16246   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
16247                                        BitWidth, Mutable, InitStyle);
16248   if (InvalidDecl)
16249     NewFD->setInvalidDecl();
16250 
16251   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
16252     Diag(Loc, diag::err_duplicate_member) << II;
16253     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16254     NewFD->setInvalidDecl();
16255   }
16256 
16257   if (!InvalidDecl && getLangOpts().CPlusPlus) {
16258     if (Record->isUnion()) {
16259       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16260         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
16261         if (RDecl->getDefinition()) {
16262           // C++ [class.union]p1: An object of a class with a non-trivial
16263           // constructor, a non-trivial copy constructor, a non-trivial
16264           // destructor, or a non-trivial copy assignment operator
16265           // cannot be a member of a union, nor can an array of such
16266           // objects.
16267           if (CheckNontrivialField(NewFD))
16268             NewFD->setInvalidDecl();
16269         }
16270       }
16271 
16272       // C++ [class.union]p1: If a union contains a member of reference type,
16273       // the program is ill-formed, except when compiling with MSVC extensions
16274       // enabled.
16275       if (EltTy->isReferenceType()) {
16276         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
16277                                     diag::ext_union_member_of_reference_type :
16278                                     diag::err_union_member_of_reference_type)
16279           << NewFD->getDeclName() << EltTy;
16280         if (!getLangOpts().MicrosoftExt)
16281           NewFD->setInvalidDecl();
16282       }
16283     }
16284   }
16285 
16286   // FIXME: We need to pass in the attributes given an AST
16287   // representation, not a parser representation.
16288   if (D) {
16289     // FIXME: The current scope is almost... but not entirely... correct here.
16290     ProcessDeclAttributes(getCurScope(), NewFD, *D);
16291 
16292     if (NewFD->hasAttrs())
16293       CheckAlignasUnderalignment(NewFD);
16294   }
16295 
16296   // In auto-retain/release, infer strong retension for fields of
16297   // retainable type.
16298   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
16299     NewFD->setInvalidDecl();
16300 
16301   if (T.isObjCGCWeak())
16302     Diag(Loc, diag::warn_attribute_weak_on_field);
16303 
16304   NewFD->setAccess(AS);
16305   return NewFD;
16306 }
16307 
16308 bool Sema::CheckNontrivialField(FieldDecl *FD) {
16309   assert(FD);
16310   assert(getLangOpts().CPlusPlus && "valid check only for C++");
16311 
16312   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
16313     return false;
16314 
16315   QualType EltTy = Context.getBaseElementType(FD->getType());
16316   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16317     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
16318     if (RDecl->getDefinition()) {
16319       // We check for copy constructors before constructors
16320       // because otherwise we'll never get complaints about
16321       // copy constructors.
16322 
16323       CXXSpecialMember member = CXXInvalid;
16324       // We're required to check for any non-trivial constructors. Since the
16325       // implicit default constructor is suppressed if there are any
16326       // user-declared constructors, we just need to check that there is a
16327       // trivial default constructor and a trivial copy constructor. (We don't
16328       // worry about move constructors here, since this is a C++98 check.)
16329       if (RDecl->hasNonTrivialCopyConstructor())
16330         member = CXXCopyConstructor;
16331       else if (!RDecl->hasTrivialDefaultConstructor())
16332         member = CXXDefaultConstructor;
16333       else if (RDecl->hasNonTrivialCopyAssignment())
16334         member = CXXCopyAssignment;
16335       else if (RDecl->hasNonTrivialDestructor())
16336         member = CXXDestructor;
16337 
16338       if (member != CXXInvalid) {
16339         if (!getLangOpts().CPlusPlus11 &&
16340             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
16341           // Objective-C++ ARC: it is an error to have a non-trivial field of
16342           // a union. However, system headers in Objective-C programs
16343           // occasionally have Objective-C lifetime objects within unions,
16344           // and rather than cause the program to fail, we make those
16345           // members unavailable.
16346           SourceLocation Loc = FD->getLocation();
16347           if (getSourceManager().isInSystemHeader(Loc)) {
16348             if (!FD->hasAttr<UnavailableAttr>())
16349               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
16350                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
16351             return false;
16352           }
16353         }
16354 
16355         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
16356                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
16357                diag::err_illegal_union_or_anon_struct_member)
16358           << FD->getParent()->isUnion() << FD->getDeclName() << member;
16359         DiagnoseNontrivial(RDecl, member);
16360         return !getLangOpts().CPlusPlus11;
16361       }
16362     }
16363   }
16364 
16365   return false;
16366 }
16367 
16368 /// TranslateIvarVisibility - Translate visibility from a token ID to an
16369 ///  AST enum value.
16370 static ObjCIvarDecl::AccessControl
16371 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
16372   switch (ivarVisibility) {
16373   default: llvm_unreachable("Unknown visitibility kind");
16374   case tok::objc_private: return ObjCIvarDecl::Private;
16375   case tok::objc_public: return ObjCIvarDecl::Public;
16376   case tok::objc_protected: return ObjCIvarDecl::Protected;
16377   case tok::objc_package: return ObjCIvarDecl::Package;
16378   }
16379 }
16380 
16381 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
16382 /// in order to create an IvarDecl object for it.
16383 Decl *Sema::ActOnIvar(Scope *S,
16384                                 SourceLocation DeclStart,
16385                                 Declarator &D, Expr *BitfieldWidth,
16386                                 tok::ObjCKeywordKind Visibility) {
16387 
16388   IdentifierInfo *II = D.getIdentifier();
16389   Expr *BitWidth = (Expr*)BitfieldWidth;
16390   SourceLocation Loc = DeclStart;
16391   if (II) Loc = D.getIdentifierLoc();
16392 
16393   // FIXME: Unnamed fields can be handled in various different ways, for
16394   // example, unnamed unions inject all members into the struct namespace!
16395 
16396   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16397   QualType T = TInfo->getType();
16398 
16399   if (BitWidth) {
16400     // 6.7.2.1p3, 6.7.2.1p4
16401     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
16402     if (!BitWidth)
16403       D.setInvalidType();
16404   } else {
16405     // Not a bitfield.
16406 
16407     // validate II.
16408 
16409   }
16410   if (T->isReferenceType()) {
16411     Diag(Loc, diag::err_ivar_reference_type);
16412     D.setInvalidType();
16413   }
16414   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16415   // than a variably modified type.
16416   else if (T->isVariablyModifiedType()) {
16417     Diag(Loc, diag::err_typecheck_ivar_variable_size);
16418     D.setInvalidType();
16419   }
16420 
16421   // Get the visibility (access control) for this ivar.
16422   ObjCIvarDecl::AccessControl ac =
16423     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
16424                                         : ObjCIvarDecl::None;
16425   // Must set ivar's DeclContext to its enclosing interface.
16426   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
16427   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
16428     return nullptr;
16429   ObjCContainerDecl *EnclosingContext;
16430   if (ObjCImplementationDecl *IMPDecl =
16431       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16432     if (LangOpts.ObjCRuntime.isFragile()) {
16433     // Case of ivar declared in an implementation. Context is that of its class.
16434       EnclosingContext = IMPDecl->getClassInterface();
16435       assert(EnclosingContext && "Implementation has no class interface!");
16436     }
16437     else
16438       EnclosingContext = EnclosingDecl;
16439   } else {
16440     if (ObjCCategoryDecl *CDecl =
16441         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16442       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
16443         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
16444         return nullptr;
16445       }
16446     }
16447     EnclosingContext = EnclosingDecl;
16448   }
16449 
16450   // Construct the decl.
16451   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
16452                                              DeclStart, Loc, II, T,
16453                                              TInfo, ac, (Expr *)BitfieldWidth);
16454 
16455   if (II) {
16456     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
16457                                            ForVisibleRedeclaration);
16458     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
16459         && !isa<TagDecl>(PrevDecl)) {
16460       Diag(Loc, diag::err_duplicate_member) << II;
16461       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16462       NewID->setInvalidDecl();
16463     }
16464   }
16465 
16466   // Process attributes attached to the ivar.
16467   ProcessDeclAttributes(S, NewID, D);
16468 
16469   if (D.isInvalidType())
16470     NewID->setInvalidDecl();
16471 
16472   // In ARC, infer 'retaining' for ivars of retainable type.
16473   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
16474     NewID->setInvalidDecl();
16475 
16476   if (D.getDeclSpec().isModulePrivateSpecified())
16477     NewID->setModulePrivate();
16478 
16479   if (II) {
16480     // FIXME: When interfaces are DeclContexts, we'll need to add
16481     // these to the interface.
16482     S->AddDecl(NewID);
16483     IdResolver.AddDecl(NewID);
16484   }
16485 
16486   if (LangOpts.ObjCRuntime.isNonFragile() &&
16487       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
16488     Diag(Loc, diag::warn_ivars_in_interface);
16489 
16490   return NewID;
16491 }
16492 
16493 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
16494 /// class and class extensions. For every class \@interface and class
16495 /// extension \@interface, if the last ivar is a bitfield of any type,
16496 /// then add an implicit `char :0` ivar to the end of that interface.
16497 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
16498                              SmallVectorImpl<Decl *> &AllIvarDecls) {
16499   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
16500     return;
16501 
16502   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
16503   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
16504 
16505   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
16506     return;
16507   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
16508   if (!ID) {
16509     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
16510       if (!CD->IsClassExtension())
16511         return;
16512     }
16513     // No need to add this to end of @implementation.
16514     else
16515       return;
16516   }
16517   // All conditions are met. Add a new bitfield to the tail end of ivars.
16518   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
16519   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
16520 
16521   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
16522                               DeclLoc, DeclLoc, nullptr,
16523                               Context.CharTy,
16524                               Context.getTrivialTypeSourceInfo(Context.CharTy,
16525                                                                DeclLoc),
16526                               ObjCIvarDecl::Private, BW,
16527                               true);
16528   AllIvarDecls.push_back(Ivar);
16529 }
16530 
16531 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
16532                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
16533                        SourceLocation RBrac,
16534                        const ParsedAttributesView &Attrs) {
16535   assert(EnclosingDecl && "missing record or interface decl");
16536 
16537   // If this is an Objective-C @implementation or category and we have
16538   // new fields here we should reset the layout of the interface since
16539   // it will now change.
16540   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
16541     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
16542     switch (DC->getKind()) {
16543     default: break;
16544     case Decl::ObjCCategory:
16545       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
16546       break;
16547     case Decl::ObjCImplementation:
16548       Context.
16549         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
16550       break;
16551     }
16552   }
16553 
16554   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
16555   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
16556 
16557   // Start counting up the number of named members; make sure to include
16558   // members of anonymous structs and unions in the total.
16559   unsigned NumNamedMembers = 0;
16560   if (Record) {
16561     for (const auto *I : Record->decls()) {
16562       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
16563         if (IFD->getDeclName())
16564           ++NumNamedMembers;
16565     }
16566   }
16567 
16568   // Verify that all the fields are okay.
16569   SmallVector<FieldDecl*, 32> RecFields;
16570 
16571   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
16572        i != end; ++i) {
16573     FieldDecl *FD = cast<FieldDecl>(*i);
16574 
16575     // Get the type for the field.
16576     const Type *FDTy = FD->getType().getTypePtr();
16577 
16578     if (!FD->isAnonymousStructOrUnion()) {
16579       // Remember all fields written by the user.
16580       RecFields.push_back(FD);
16581     }
16582 
16583     // If the field is already invalid for some reason, don't emit more
16584     // diagnostics about it.
16585     if (FD->isInvalidDecl()) {
16586       EnclosingDecl->setInvalidDecl();
16587       continue;
16588     }
16589 
16590     // C99 6.7.2.1p2:
16591     //   A structure or union shall not contain a member with
16592     //   incomplete or function type (hence, a structure shall not
16593     //   contain an instance of itself, but may contain a pointer to
16594     //   an instance of itself), except that the last member of a
16595     //   structure with more than one named member may have incomplete
16596     //   array type; such a structure (and any union containing,
16597     //   possibly recursively, a member that is such a structure)
16598     //   shall not be a member of a structure or an element of an
16599     //   array.
16600     bool IsLastField = (i + 1 == Fields.end());
16601     if (FDTy->isFunctionType()) {
16602       // Field declared as a function.
16603       Diag(FD->getLocation(), diag::err_field_declared_as_function)
16604         << FD->getDeclName();
16605       FD->setInvalidDecl();
16606       EnclosingDecl->setInvalidDecl();
16607       continue;
16608     } else if (FDTy->isIncompleteArrayType() &&
16609                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
16610       if (Record) {
16611         // Flexible array member.
16612         // Microsoft and g++ is more permissive regarding flexible array.
16613         // It will accept flexible array in union and also
16614         // as the sole element of a struct/class.
16615         unsigned DiagID = 0;
16616         if (!Record->isUnion() && !IsLastField) {
16617           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
16618             << FD->getDeclName() << FD->getType() << Record->getTagKind();
16619           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
16620           FD->setInvalidDecl();
16621           EnclosingDecl->setInvalidDecl();
16622           continue;
16623         } else if (Record->isUnion())
16624           DiagID = getLangOpts().MicrosoftExt
16625                        ? diag::ext_flexible_array_union_ms
16626                        : getLangOpts().CPlusPlus
16627                              ? diag::ext_flexible_array_union_gnu
16628                              : diag::err_flexible_array_union;
16629         else if (NumNamedMembers < 1)
16630           DiagID = getLangOpts().MicrosoftExt
16631                        ? diag::ext_flexible_array_empty_aggregate_ms
16632                        : getLangOpts().CPlusPlus
16633                              ? diag::ext_flexible_array_empty_aggregate_gnu
16634                              : diag::err_flexible_array_empty_aggregate;
16635 
16636         if (DiagID)
16637           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
16638                                           << Record->getTagKind();
16639         // While the layout of types that contain virtual bases is not specified
16640         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
16641         // virtual bases after the derived members.  This would make a flexible
16642         // array member declared at the end of an object not adjacent to the end
16643         // of the type.
16644         if (CXXRecord && CXXRecord->getNumVBases() != 0)
16645           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
16646               << FD->getDeclName() << Record->getTagKind();
16647         if (!getLangOpts().C99)
16648           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
16649             << FD->getDeclName() << Record->getTagKind();
16650 
16651         // If the element type has a non-trivial destructor, we would not
16652         // implicitly destroy the elements, so disallow it for now.
16653         //
16654         // FIXME: GCC allows this. We should probably either implicitly delete
16655         // the destructor of the containing class, or just allow this.
16656         QualType BaseElem = Context.getBaseElementType(FD->getType());
16657         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
16658           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
16659             << FD->getDeclName() << FD->getType();
16660           FD->setInvalidDecl();
16661           EnclosingDecl->setInvalidDecl();
16662           continue;
16663         }
16664         // Okay, we have a legal flexible array member at the end of the struct.
16665         Record->setHasFlexibleArrayMember(true);
16666       } else {
16667         // In ObjCContainerDecl ivars with incomplete array type are accepted,
16668         // unless they are followed by another ivar. That check is done
16669         // elsewhere, after synthesized ivars are known.
16670       }
16671     } else if (!FDTy->isDependentType() &&
16672                RequireCompleteType(FD->getLocation(), FD->getType(),
16673                                    diag::err_field_incomplete)) {
16674       // Incomplete type
16675       FD->setInvalidDecl();
16676       EnclosingDecl->setInvalidDecl();
16677       continue;
16678     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
16679       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
16680         // A type which contains a flexible array member is considered to be a
16681         // flexible array member.
16682         Record->setHasFlexibleArrayMember(true);
16683         if (!Record->isUnion()) {
16684           // If this is a struct/class and this is not the last element, reject
16685           // it.  Note that GCC supports variable sized arrays in the middle of
16686           // structures.
16687           if (!IsLastField)
16688             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
16689               << FD->getDeclName() << FD->getType();
16690           else {
16691             // We support flexible arrays at the end of structs in
16692             // other structs as an extension.
16693             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
16694               << FD->getDeclName();
16695           }
16696         }
16697       }
16698       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
16699           RequireNonAbstractType(FD->getLocation(), FD->getType(),
16700                                  diag::err_abstract_type_in_decl,
16701                                  AbstractIvarType)) {
16702         // Ivars can not have abstract class types
16703         FD->setInvalidDecl();
16704       }
16705       if (Record && FDTTy->getDecl()->hasObjectMember())
16706         Record->setHasObjectMember(true);
16707       if (Record && FDTTy->getDecl()->hasVolatileMember())
16708         Record->setHasVolatileMember(true);
16709     } else if (FDTy->isObjCObjectType()) {
16710       /// A field cannot be an Objective-c object
16711       Diag(FD->getLocation(), diag::err_statically_allocated_object)
16712         << FixItHint::CreateInsertion(FD->getLocation(), "*");
16713       QualType T = Context.getObjCObjectPointerType(FD->getType());
16714       FD->setType(T);
16715     } else if (Record && Record->isUnion() &&
16716                FD->getType().hasNonTrivialObjCLifetime() &&
16717                getSourceManager().isInSystemHeader(FD->getLocation()) &&
16718                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
16719                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
16720                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
16721       // For backward compatibility, fields of C unions declared in system
16722       // headers that have non-trivial ObjC ownership qualifications are marked
16723       // as unavailable unless the qualifier is explicit and __strong. This can
16724       // break ABI compatibility between programs compiled with ARC and MRR, but
16725       // is a better option than rejecting programs using those unions under
16726       // ARC.
16727       FD->addAttr(UnavailableAttr::CreateImplicit(
16728           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
16729           FD->getLocation()));
16730     } else if (getLangOpts().ObjC &&
16731                getLangOpts().getGC() != LangOptions::NonGC &&
16732                Record && !Record->hasObjectMember()) {
16733       if (FD->getType()->isObjCObjectPointerType() ||
16734           FD->getType().isObjCGCStrong())
16735         Record->setHasObjectMember(true);
16736       else if (Context.getAsArrayType(FD->getType())) {
16737         QualType BaseType = Context.getBaseElementType(FD->getType());
16738         if (BaseType->isRecordType() &&
16739             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
16740           Record->setHasObjectMember(true);
16741         else if (BaseType->isObjCObjectPointerType() ||
16742                  BaseType.isObjCGCStrong())
16743                Record->setHasObjectMember(true);
16744       }
16745     }
16746 
16747     if (Record && !getLangOpts().CPlusPlus &&
16748         !shouldIgnoreForRecordTriviality(FD)) {
16749       QualType FT = FD->getType();
16750       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
16751         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
16752         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
16753             Record->isUnion())
16754           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
16755       }
16756       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
16757       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
16758         Record->setNonTrivialToPrimitiveCopy(true);
16759         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
16760           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
16761       }
16762       if (FT.isDestructedType()) {
16763         Record->setNonTrivialToPrimitiveDestroy(true);
16764         Record->setParamDestroyedInCallee(true);
16765         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
16766           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
16767       }
16768 
16769       if (const auto *RT = FT->getAs<RecordType>()) {
16770         if (RT->getDecl()->getArgPassingRestrictions() ==
16771             RecordDecl::APK_CanNeverPassInRegs)
16772           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16773       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
16774         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16775     }
16776 
16777     if (Record && FD->getType().isVolatileQualified())
16778       Record->setHasVolatileMember(true);
16779     // Keep track of the number of named members.
16780     if (FD->getIdentifier())
16781       ++NumNamedMembers;
16782   }
16783 
16784   // Okay, we successfully defined 'Record'.
16785   if (Record) {
16786     bool Completed = false;
16787     if (CXXRecord) {
16788       if (!CXXRecord->isInvalidDecl()) {
16789         // Set access bits correctly on the directly-declared conversions.
16790         for (CXXRecordDecl::conversion_iterator
16791                I = CXXRecord->conversion_begin(),
16792                E = CXXRecord->conversion_end(); I != E; ++I)
16793           I.setAccess((*I)->getAccess());
16794       }
16795 
16796       if (!CXXRecord->isDependentType()) {
16797         // Add any implicitly-declared members to this class.
16798         AddImplicitlyDeclaredMembersToClass(CXXRecord);
16799 
16800         if (!CXXRecord->isInvalidDecl()) {
16801           // If we have virtual base classes, we may end up finding multiple
16802           // final overriders for a given virtual function. Check for this
16803           // problem now.
16804           if (CXXRecord->getNumVBases()) {
16805             CXXFinalOverriderMap FinalOverriders;
16806             CXXRecord->getFinalOverriders(FinalOverriders);
16807 
16808             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
16809                                              MEnd = FinalOverriders.end();
16810                  M != MEnd; ++M) {
16811               for (OverridingMethods::iterator SO = M->second.begin(),
16812                                             SOEnd = M->second.end();
16813                    SO != SOEnd; ++SO) {
16814                 assert(SO->second.size() > 0 &&
16815                        "Virtual function without overriding functions?");
16816                 if (SO->second.size() == 1)
16817                   continue;
16818 
16819                 // C++ [class.virtual]p2:
16820                 //   In a derived class, if a virtual member function of a base
16821                 //   class subobject has more than one final overrider the
16822                 //   program is ill-formed.
16823                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
16824                   << (const NamedDecl *)M->first << Record;
16825                 Diag(M->first->getLocation(),
16826                      diag::note_overridden_virtual_function);
16827                 for (OverridingMethods::overriding_iterator
16828                           OM = SO->second.begin(),
16829                        OMEnd = SO->second.end();
16830                      OM != OMEnd; ++OM)
16831                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
16832                     << (const NamedDecl *)M->first << OM->Method->getParent();
16833 
16834                 Record->setInvalidDecl();
16835               }
16836             }
16837             CXXRecord->completeDefinition(&FinalOverriders);
16838             Completed = true;
16839           }
16840         }
16841       }
16842     }
16843 
16844     if (!Completed)
16845       Record->completeDefinition();
16846 
16847     // Handle attributes before checking the layout.
16848     ProcessDeclAttributeList(S, Record, Attrs);
16849 
16850     // We may have deferred checking for a deleted destructor. Check now.
16851     if (CXXRecord) {
16852       auto *Dtor = CXXRecord->getDestructor();
16853       if (Dtor && Dtor->isImplicit() &&
16854           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
16855         CXXRecord->setImplicitDestructorIsDeleted();
16856         SetDeclDeleted(Dtor, CXXRecord->getLocation());
16857       }
16858     }
16859 
16860     if (Record->hasAttrs()) {
16861       CheckAlignasUnderalignment(Record);
16862 
16863       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
16864         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
16865                                            IA->getRange(), IA->getBestCase(),
16866                                            IA->getInheritanceModel());
16867     }
16868 
16869     // Check if the structure/union declaration is a type that can have zero
16870     // size in C. For C this is a language extension, for C++ it may cause
16871     // compatibility problems.
16872     bool CheckForZeroSize;
16873     if (!getLangOpts().CPlusPlus) {
16874       CheckForZeroSize = true;
16875     } else {
16876       // For C++ filter out types that cannot be referenced in C code.
16877       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
16878       CheckForZeroSize =
16879           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
16880           !CXXRecord->isDependentType() &&
16881           CXXRecord->isCLike();
16882     }
16883     if (CheckForZeroSize) {
16884       bool ZeroSize = true;
16885       bool IsEmpty = true;
16886       unsigned NonBitFields = 0;
16887       for (RecordDecl::field_iterator I = Record->field_begin(),
16888                                       E = Record->field_end();
16889            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
16890         IsEmpty = false;
16891         if (I->isUnnamedBitfield()) {
16892           if (!I->isZeroLengthBitField(Context))
16893             ZeroSize = false;
16894         } else {
16895           ++NonBitFields;
16896           QualType FieldType = I->getType();
16897           if (FieldType->isIncompleteType() ||
16898               !Context.getTypeSizeInChars(FieldType).isZero())
16899             ZeroSize = false;
16900         }
16901       }
16902 
16903       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
16904       // allowed in C++, but warn if its declaration is inside
16905       // extern "C" block.
16906       if (ZeroSize) {
16907         Diag(RecLoc, getLangOpts().CPlusPlus ?
16908                          diag::warn_zero_size_struct_union_in_extern_c :
16909                          diag::warn_zero_size_struct_union_compat)
16910           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
16911       }
16912 
16913       // Structs without named members are extension in C (C99 6.7.2.1p7),
16914       // but are accepted by GCC.
16915       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
16916         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
16917                                diag::ext_no_named_members_in_struct_union)
16918           << Record->isUnion();
16919       }
16920     }
16921   } else {
16922     ObjCIvarDecl **ClsFields =
16923       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
16924     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
16925       ID->setEndOfDefinitionLoc(RBrac);
16926       // Add ivar's to class's DeclContext.
16927       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16928         ClsFields[i]->setLexicalDeclContext(ID);
16929         ID->addDecl(ClsFields[i]);
16930       }
16931       // Must enforce the rule that ivars in the base classes may not be
16932       // duplicates.
16933       if (ID->getSuperClass())
16934         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
16935     } else if (ObjCImplementationDecl *IMPDecl =
16936                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16937       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
16938       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
16939         // Ivar declared in @implementation never belongs to the implementation.
16940         // Only it is in implementation's lexical context.
16941         ClsFields[I]->setLexicalDeclContext(IMPDecl);
16942       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
16943       IMPDecl->setIvarLBraceLoc(LBrac);
16944       IMPDecl->setIvarRBraceLoc(RBrac);
16945     } else if (ObjCCategoryDecl *CDecl =
16946                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16947       // case of ivars in class extension; all other cases have been
16948       // reported as errors elsewhere.
16949       // FIXME. Class extension does not have a LocEnd field.
16950       // CDecl->setLocEnd(RBrac);
16951       // Add ivar's to class extension's DeclContext.
16952       // Diagnose redeclaration of private ivars.
16953       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
16954       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16955         if (IDecl) {
16956           if (const ObjCIvarDecl *ClsIvar =
16957               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
16958             Diag(ClsFields[i]->getLocation(),
16959                  diag::err_duplicate_ivar_declaration);
16960             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
16961             continue;
16962           }
16963           for (const auto *Ext : IDecl->known_extensions()) {
16964             if (const ObjCIvarDecl *ClsExtIvar
16965                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
16966               Diag(ClsFields[i]->getLocation(),
16967                    diag::err_duplicate_ivar_declaration);
16968               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
16969               continue;
16970             }
16971           }
16972         }
16973         ClsFields[i]->setLexicalDeclContext(CDecl);
16974         CDecl->addDecl(ClsFields[i]);
16975       }
16976       CDecl->setIvarLBraceLoc(LBrac);
16977       CDecl->setIvarRBraceLoc(RBrac);
16978     }
16979   }
16980 }
16981 
16982 /// Determine whether the given integral value is representable within
16983 /// the given type T.
16984 static bool isRepresentableIntegerValue(ASTContext &Context,
16985                                         llvm::APSInt &Value,
16986                                         QualType T) {
16987   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
16988          "Integral type required!");
16989   unsigned BitWidth = Context.getIntWidth(T);
16990 
16991   if (Value.isUnsigned() || Value.isNonNegative()) {
16992     if (T->isSignedIntegerOrEnumerationType())
16993       --BitWidth;
16994     return Value.getActiveBits() <= BitWidth;
16995   }
16996   return Value.getMinSignedBits() <= BitWidth;
16997 }
16998 
16999 // Given an integral type, return the next larger integral type
17000 // (or a NULL type of no such type exists).
17001 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
17002   // FIXME: Int128/UInt128 support, which also needs to be introduced into
17003   // enum checking below.
17004   assert((T->isIntegralType(Context) ||
17005          T->isEnumeralType()) && "Integral type required!");
17006   const unsigned NumTypes = 4;
17007   QualType SignedIntegralTypes[NumTypes] = {
17008     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
17009   };
17010   QualType UnsignedIntegralTypes[NumTypes] = {
17011     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
17012     Context.UnsignedLongLongTy
17013   };
17014 
17015   unsigned BitWidth = Context.getTypeSize(T);
17016   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
17017                                                         : UnsignedIntegralTypes;
17018   for (unsigned I = 0; I != NumTypes; ++I)
17019     if (Context.getTypeSize(Types[I]) > BitWidth)
17020       return Types[I];
17021 
17022   return QualType();
17023 }
17024 
17025 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
17026                                           EnumConstantDecl *LastEnumConst,
17027                                           SourceLocation IdLoc,
17028                                           IdentifierInfo *Id,
17029                                           Expr *Val) {
17030   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17031   llvm::APSInt EnumVal(IntWidth);
17032   QualType EltTy;
17033 
17034   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
17035     Val = nullptr;
17036 
17037   if (Val)
17038     Val = DefaultLvalueConversion(Val).get();
17039 
17040   if (Val) {
17041     if (Enum->isDependentType() || Val->isTypeDependent())
17042       EltTy = Context.DependentTy;
17043     else {
17044       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
17045         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
17046         // constant-expression in the enumerator-definition shall be a converted
17047         // constant expression of the underlying type.
17048         EltTy = Enum->getIntegerType();
17049         ExprResult Converted =
17050           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
17051                                            CCEK_Enumerator);
17052         if (Converted.isInvalid())
17053           Val = nullptr;
17054         else
17055           Val = Converted.get();
17056       } else if (!Val->isValueDependent() &&
17057                  !(Val = VerifyIntegerConstantExpression(Val,
17058                                                          &EnumVal).get())) {
17059         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
17060       } else {
17061         if (Enum->isComplete()) {
17062           EltTy = Enum->getIntegerType();
17063 
17064           // In Obj-C and Microsoft mode, require the enumeration value to be
17065           // representable in the underlying type of the enumeration. In C++11,
17066           // we perform a non-narrowing conversion as part of converted constant
17067           // expression checking.
17068           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17069             if (Context.getTargetInfo()
17070                     .getTriple()
17071                     .isWindowsMSVCEnvironment()) {
17072               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
17073             } else {
17074               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
17075             }
17076           }
17077 
17078           // Cast to the underlying type.
17079           Val = ImpCastExprToType(Val, EltTy,
17080                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
17081                                                          : CK_IntegralCast)
17082                     .get();
17083         } else if (getLangOpts().CPlusPlus) {
17084           // C++11 [dcl.enum]p5:
17085           //   If the underlying type is not fixed, the type of each enumerator
17086           //   is the type of its initializing value:
17087           //     - If an initializer is specified for an enumerator, the
17088           //       initializing value has the same type as the expression.
17089           EltTy = Val->getType();
17090         } else {
17091           // C99 6.7.2.2p2:
17092           //   The expression that defines the value of an enumeration constant
17093           //   shall be an integer constant expression that has a value
17094           //   representable as an int.
17095 
17096           // Complain if the value is not representable in an int.
17097           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
17098             Diag(IdLoc, diag::ext_enum_value_not_int)
17099               << EnumVal.toString(10) << Val->getSourceRange()
17100               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
17101           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
17102             // Force the type of the expression to 'int'.
17103             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
17104           }
17105           EltTy = Val->getType();
17106         }
17107       }
17108     }
17109   }
17110 
17111   if (!Val) {
17112     if (Enum->isDependentType())
17113       EltTy = Context.DependentTy;
17114     else if (!LastEnumConst) {
17115       // C++0x [dcl.enum]p5:
17116       //   If the underlying type is not fixed, the type of each enumerator
17117       //   is the type of its initializing value:
17118       //     - If no initializer is specified for the first enumerator, the
17119       //       initializing value has an unspecified integral type.
17120       //
17121       // GCC uses 'int' for its unspecified integral type, as does
17122       // C99 6.7.2.2p3.
17123       if (Enum->isFixed()) {
17124         EltTy = Enum->getIntegerType();
17125       }
17126       else {
17127         EltTy = Context.IntTy;
17128       }
17129     } else {
17130       // Assign the last value + 1.
17131       EnumVal = LastEnumConst->getInitVal();
17132       ++EnumVal;
17133       EltTy = LastEnumConst->getType();
17134 
17135       // Check for overflow on increment.
17136       if (EnumVal < LastEnumConst->getInitVal()) {
17137         // C++0x [dcl.enum]p5:
17138         //   If the underlying type is not fixed, the type of each enumerator
17139         //   is the type of its initializing value:
17140         //
17141         //     - Otherwise the type of the initializing value is the same as
17142         //       the type of the initializing value of the preceding enumerator
17143         //       unless the incremented value is not representable in that type,
17144         //       in which case the type is an unspecified integral type
17145         //       sufficient to contain the incremented value. If no such type
17146         //       exists, the program is ill-formed.
17147         QualType T = getNextLargerIntegralType(Context, EltTy);
17148         if (T.isNull() || Enum->isFixed()) {
17149           // There is no integral type larger enough to represent this
17150           // value. Complain, then allow the value to wrap around.
17151           EnumVal = LastEnumConst->getInitVal();
17152           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
17153           ++EnumVal;
17154           if (Enum->isFixed())
17155             // When the underlying type is fixed, this is ill-formed.
17156             Diag(IdLoc, diag::err_enumerator_wrapped)
17157               << EnumVal.toString(10)
17158               << EltTy;
17159           else
17160             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
17161               << EnumVal.toString(10);
17162         } else {
17163           EltTy = T;
17164         }
17165 
17166         // Retrieve the last enumerator's value, extent that type to the
17167         // type that is supposed to be large enough to represent the incremented
17168         // value, then increment.
17169         EnumVal = LastEnumConst->getInitVal();
17170         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17171         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
17172         ++EnumVal;
17173 
17174         // If we're not in C++, diagnose the overflow of enumerator values,
17175         // which in C99 means that the enumerator value is not representable in
17176         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
17177         // permits enumerator values that are representable in some larger
17178         // integral type.
17179         if (!getLangOpts().CPlusPlus && !T.isNull())
17180           Diag(IdLoc, diag::warn_enum_value_overflow);
17181       } else if (!getLangOpts().CPlusPlus &&
17182                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17183         // Enforce C99 6.7.2.2p2 even when we compute the next value.
17184         Diag(IdLoc, diag::ext_enum_value_not_int)
17185           << EnumVal.toString(10) << 1;
17186       }
17187     }
17188   }
17189 
17190   if (!EltTy->isDependentType()) {
17191     // Make the enumerator value match the signedness and size of the
17192     // enumerator's type.
17193     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
17194     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17195   }
17196 
17197   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
17198                                   Val, EnumVal);
17199 }
17200 
17201 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
17202                                                 SourceLocation IILoc) {
17203   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
17204       !getLangOpts().CPlusPlus)
17205     return SkipBodyInfo();
17206 
17207   // We have an anonymous enum definition. Look up the first enumerator to
17208   // determine if we should merge the definition with an existing one and
17209   // skip the body.
17210   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
17211                                          forRedeclarationInCurContext());
17212   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
17213   if (!PrevECD)
17214     return SkipBodyInfo();
17215 
17216   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
17217   NamedDecl *Hidden;
17218   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
17219     SkipBodyInfo Skip;
17220     Skip.Previous = Hidden;
17221     return Skip;
17222   }
17223 
17224   return SkipBodyInfo();
17225 }
17226 
17227 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
17228                               SourceLocation IdLoc, IdentifierInfo *Id,
17229                               const ParsedAttributesView &Attrs,
17230                               SourceLocation EqualLoc, Expr *Val) {
17231   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
17232   EnumConstantDecl *LastEnumConst =
17233     cast_or_null<EnumConstantDecl>(lastEnumConst);
17234 
17235   // The scope passed in may not be a decl scope.  Zip up the scope tree until
17236   // we find one that is.
17237   S = getNonFieldDeclScope(S);
17238 
17239   // Verify that there isn't already something declared with this name in this
17240   // scope.
17241   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
17242   LookupName(R, S);
17243   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
17244 
17245   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17246     // Maybe we will complain about the shadowed template parameter.
17247     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
17248     // Just pretend that we didn't see the previous declaration.
17249     PrevDecl = nullptr;
17250   }
17251 
17252   // C++ [class.mem]p15:
17253   // If T is the name of a class, then each of the following shall have a name
17254   // different from T:
17255   // - every enumerator of every member of class T that is an unscoped
17256   // enumerated type
17257   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
17258     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
17259                             DeclarationNameInfo(Id, IdLoc));
17260 
17261   EnumConstantDecl *New =
17262     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
17263   if (!New)
17264     return nullptr;
17265 
17266   if (PrevDecl) {
17267     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
17268       // Check for other kinds of shadowing not already handled.
17269       CheckShadow(New, PrevDecl, R);
17270     }
17271 
17272     // When in C++, we may get a TagDecl with the same name; in this case the
17273     // enum constant will 'hide' the tag.
17274     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
17275            "Received TagDecl when not in C++!");
17276     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
17277       if (isa<EnumConstantDecl>(PrevDecl))
17278         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
17279       else
17280         Diag(IdLoc, diag::err_redefinition) << Id;
17281       notePreviousDefinition(PrevDecl, IdLoc);
17282       return nullptr;
17283     }
17284   }
17285 
17286   // Process attributes.
17287   ProcessDeclAttributeList(S, New, Attrs);
17288   AddPragmaAttributes(S, New);
17289 
17290   // Register this decl in the current scope stack.
17291   New->setAccess(TheEnumDecl->getAccess());
17292   PushOnScopeChains(New, S);
17293 
17294   ActOnDocumentableDecl(New);
17295 
17296   return New;
17297 }
17298 
17299 // Returns true when the enum initial expression does not trigger the
17300 // duplicate enum warning.  A few common cases are exempted as follows:
17301 // Element2 = Element1
17302 // Element2 = Element1 + 1
17303 // Element2 = Element1 - 1
17304 // Where Element2 and Element1 are from the same enum.
17305 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
17306   Expr *InitExpr = ECD->getInitExpr();
17307   if (!InitExpr)
17308     return true;
17309   InitExpr = InitExpr->IgnoreImpCasts();
17310 
17311   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
17312     if (!BO->isAdditiveOp())
17313       return true;
17314     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
17315     if (!IL)
17316       return true;
17317     if (IL->getValue() != 1)
17318       return true;
17319 
17320     InitExpr = BO->getLHS();
17321   }
17322 
17323   // This checks if the elements are from the same enum.
17324   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
17325   if (!DRE)
17326     return true;
17327 
17328   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
17329   if (!EnumConstant)
17330     return true;
17331 
17332   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
17333       Enum)
17334     return true;
17335 
17336   return false;
17337 }
17338 
17339 // Emits a warning when an element is implicitly set a value that
17340 // a previous element has already been set to.
17341 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
17342                                         EnumDecl *Enum, QualType EnumType) {
17343   // Avoid anonymous enums
17344   if (!Enum->getIdentifier())
17345     return;
17346 
17347   // Only check for small enums.
17348   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
17349     return;
17350 
17351   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
17352     return;
17353 
17354   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
17355   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
17356 
17357   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
17358   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
17359 
17360   // Use int64_t as a key to avoid needing special handling for DenseMap keys.
17361   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
17362     llvm::APSInt Val = D->getInitVal();
17363     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
17364   };
17365 
17366   DuplicatesVector DupVector;
17367   ValueToVectorMap EnumMap;
17368 
17369   // Populate the EnumMap with all values represented by enum constants without
17370   // an initializer.
17371   for (auto *Element : Elements) {
17372     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
17373 
17374     // Null EnumConstantDecl means a previous diagnostic has been emitted for
17375     // this constant.  Skip this enum since it may be ill-formed.
17376     if (!ECD) {
17377       return;
17378     }
17379 
17380     // Constants with initalizers are handled in the next loop.
17381     if (ECD->getInitExpr())
17382       continue;
17383 
17384     // Duplicate values are handled in the next loop.
17385     EnumMap.insert({EnumConstantToKey(ECD), ECD});
17386   }
17387 
17388   if (EnumMap.size() == 0)
17389     return;
17390 
17391   // Create vectors for any values that has duplicates.
17392   for (auto *Element : Elements) {
17393     // The last loop returned if any constant was null.
17394     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
17395     if (!ValidDuplicateEnum(ECD, Enum))
17396       continue;
17397 
17398     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
17399     if (Iter == EnumMap.end())
17400       continue;
17401 
17402     DeclOrVector& Entry = Iter->second;
17403     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
17404       // Ensure constants are different.
17405       if (D == ECD)
17406         continue;
17407 
17408       // Create new vector and push values onto it.
17409       auto Vec = std::make_unique<ECDVector>();
17410       Vec->push_back(D);
17411       Vec->push_back(ECD);
17412 
17413       // Update entry to point to the duplicates vector.
17414       Entry = Vec.get();
17415 
17416       // Store the vector somewhere we can consult later for quick emission of
17417       // diagnostics.
17418       DupVector.emplace_back(std::move(Vec));
17419       continue;
17420     }
17421 
17422     ECDVector *Vec = Entry.get<ECDVector*>();
17423     // Make sure constants are not added more than once.
17424     if (*Vec->begin() == ECD)
17425       continue;
17426 
17427     Vec->push_back(ECD);
17428   }
17429 
17430   // Emit diagnostics.
17431   for (const auto &Vec : DupVector) {
17432     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
17433 
17434     // Emit warning for one enum constant.
17435     auto *FirstECD = Vec->front();
17436     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
17437       << FirstECD << FirstECD->getInitVal().toString(10)
17438       << FirstECD->getSourceRange();
17439 
17440     // Emit one note for each of the remaining enum constants with
17441     // the same value.
17442     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
17443       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
17444         << ECD << ECD->getInitVal().toString(10)
17445         << ECD->getSourceRange();
17446   }
17447 }
17448 
17449 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
17450                              bool AllowMask) const {
17451   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
17452   assert(ED->isCompleteDefinition() && "expected enum definition");
17453 
17454   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
17455   llvm::APInt &FlagBits = R.first->second;
17456 
17457   if (R.second) {
17458     for (auto *E : ED->enumerators()) {
17459       const auto &EVal = E->getInitVal();
17460       // Only single-bit enumerators introduce new flag values.
17461       if (EVal.isPowerOf2())
17462         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
17463     }
17464   }
17465 
17466   // A value is in a flag enum if either its bits are a subset of the enum's
17467   // flag bits (the first condition) or we are allowing masks and the same is
17468   // true of its complement (the second condition). When masks are allowed, we
17469   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
17470   //
17471   // While it's true that any value could be used as a mask, the assumption is
17472   // that a mask will have all of the insignificant bits set. Anything else is
17473   // likely a logic error.
17474   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
17475   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
17476 }
17477 
17478 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
17479                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
17480                          const ParsedAttributesView &Attrs) {
17481   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
17482   QualType EnumType = Context.getTypeDeclType(Enum);
17483 
17484   ProcessDeclAttributeList(S, Enum, Attrs);
17485 
17486   if (Enum->isDependentType()) {
17487     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17488       EnumConstantDecl *ECD =
17489         cast_or_null<EnumConstantDecl>(Elements[i]);
17490       if (!ECD) continue;
17491 
17492       ECD->setType(EnumType);
17493     }
17494 
17495     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
17496     return;
17497   }
17498 
17499   // TODO: If the result value doesn't fit in an int, it must be a long or long
17500   // long value.  ISO C does not support this, but GCC does as an extension,
17501   // emit a warning.
17502   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17503   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
17504   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
17505 
17506   // Verify that all the values are okay, compute the size of the values, and
17507   // reverse the list.
17508   unsigned NumNegativeBits = 0;
17509   unsigned NumPositiveBits = 0;
17510 
17511   // Keep track of whether all elements have type int.
17512   bool AllElementsInt = true;
17513 
17514   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17515     EnumConstantDecl *ECD =
17516       cast_or_null<EnumConstantDecl>(Elements[i]);
17517     if (!ECD) continue;  // Already issued a diagnostic.
17518 
17519     const llvm::APSInt &InitVal = ECD->getInitVal();
17520 
17521     // Keep track of the size of positive and negative values.
17522     if (InitVal.isUnsigned() || InitVal.isNonNegative())
17523       NumPositiveBits = std::max(NumPositiveBits,
17524                                  (unsigned)InitVal.getActiveBits());
17525     else
17526       NumNegativeBits = std::max(NumNegativeBits,
17527                                  (unsigned)InitVal.getMinSignedBits());
17528 
17529     // Keep track of whether every enum element has type int (very common).
17530     if (AllElementsInt)
17531       AllElementsInt = ECD->getType() == Context.IntTy;
17532   }
17533 
17534   // Figure out the type that should be used for this enum.
17535   QualType BestType;
17536   unsigned BestWidth;
17537 
17538   // C++0x N3000 [conv.prom]p3:
17539   //   An rvalue of an unscoped enumeration type whose underlying
17540   //   type is not fixed can be converted to an rvalue of the first
17541   //   of the following types that can represent all the values of
17542   //   the enumeration: int, unsigned int, long int, unsigned long
17543   //   int, long long int, or unsigned long long int.
17544   // C99 6.4.4.3p2:
17545   //   An identifier declared as an enumeration constant has type int.
17546   // The C99 rule is modified by a gcc extension
17547   QualType BestPromotionType;
17548 
17549   bool Packed = Enum->hasAttr<PackedAttr>();
17550   // -fshort-enums is the equivalent to specifying the packed attribute on all
17551   // enum definitions.
17552   if (LangOpts.ShortEnums)
17553     Packed = true;
17554 
17555   // If the enum already has a type because it is fixed or dictated by the
17556   // target, promote that type instead of analyzing the enumerators.
17557   if (Enum->isComplete()) {
17558     BestType = Enum->getIntegerType();
17559     if (BestType->isPromotableIntegerType())
17560       BestPromotionType = Context.getPromotedIntegerType(BestType);
17561     else
17562       BestPromotionType = BestType;
17563 
17564     BestWidth = Context.getIntWidth(BestType);
17565   }
17566   else if (NumNegativeBits) {
17567     // If there is a negative value, figure out the smallest integer type (of
17568     // int/long/longlong) that fits.
17569     // If it's packed, check also if it fits a char or a short.
17570     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
17571       BestType = Context.SignedCharTy;
17572       BestWidth = CharWidth;
17573     } else if (Packed && NumNegativeBits <= ShortWidth &&
17574                NumPositiveBits < ShortWidth) {
17575       BestType = Context.ShortTy;
17576       BestWidth = ShortWidth;
17577     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
17578       BestType = Context.IntTy;
17579       BestWidth = IntWidth;
17580     } else {
17581       BestWidth = Context.getTargetInfo().getLongWidth();
17582 
17583       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
17584         BestType = Context.LongTy;
17585       } else {
17586         BestWidth = Context.getTargetInfo().getLongLongWidth();
17587 
17588         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
17589           Diag(Enum->getLocation(), diag::ext_enum_too_large);
17590         BestType = Context.LongLongTy;
17591       }
17592     }
17593     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
17594   } else {
17595     // If there is no negative value, figure out the smallest type that fits
17596     // all of the enumerator values.
17597     // If it's packed, check also if it fits a char or a short.
17598     if (Packed && NumPositiveBits <= CharWidth) {
17599       BestType = Context.UnsignedCharTy;
17600       BestPromotionType = Context.IntTy;
17601       BestWidth = CharWidth;
17602     } else if (Packed && NumPositiveBits <= ShortWidth) {
17603       BestType = Context.UnsignedShortTy;
17604       BestPromotionType = Context.IntTy;
17605       BestWidth = ShortWidth;
17606     } else if (NumPositiveBits <= IntWidth) {
17607       BestType = Context.UnsignedIntTy;
17608       BestWidth = IntWidth;
17609       BestPromotionType
17610         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17611                            ? Context.UnsignedIntTy : Context.IntTy;
17612     } else if (NumPositiveBits <=
17613                (BestWidth = Context.getTargetInfo().getLongWidth())) {
17614       BestType = Context.UnsignedLongTy;
17615       BestPromotionType
17616         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17617                            ? Context.UnsignedLongTy : Context.LongTy;
17618     } else {
17619       BestWidth = Context.getTargetInfo().getLongLongWidth();
17620       assert(NumPositiveBits <= BestWidth &&
17621              "How could an initializer get larger than ULL?");
17622       BestType = Context.UnsignedLongLongTy;
17623       BestPromotionType
17624         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17625                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
17626     }
17627   }
17628 
17629   // Loop over all of the enumerator constants, changing their types to match
17630   // the type of the enum if needed.
17631   for (auto *D : Elements) {
17632     auto *ECD = cast_or_null<EnumConstantDecl>(D);
17633     if (!ECD) continue;  // Already issued a diagnostic.
17634 
17635     // Standard C says the enumerators have int type, but we allow, as an
17636     // extension, the enumerators to be larger than int size.  If each
17637     // enumerator value fits in an int, type it as an int, otherwise type it the
17638     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
17639     // that X has type 'int', not 'unsigned'.
17640 
17641     // Determine whether the value fits into an int.
17642     llvm::APSInt InitVal = ECD->getInitVal();
17643 
17644     // If it fits into an integer type, force it.  Otherwise force it to match
17645     // the enum decl type.
17646     QualType NewTy;
17647     unsigned NewWidth;
17648     bool NewSign;
17649     if (!getLangOpts().CPlusPlus &&
17650         !Enum->isFixed() &&
17651         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
17652       NewTy = Context.IntTy;
17653       NewWidth = IntWidth;
17654       NewSign = true;
17655     } else if (ECD->getType() == BestType) {
17656       // Already the right type!
17657       if (getLangOpts().CPlusPlus)
17658         // C++ [dcl.enum]p4: Following the closing brace of an
17659         // enum-specifier, each enumerator has the type of its
17660         // enumeration.
17661         ECD->setType(EnumType);
17662       continue;
17663     } else {
17664       NewTy = BestType;
17665       NewWidth = BestWidth;
17666       NewSign = BestType->isSignedIntegerOrEnumerationType();
17667     }
17668 
17669     // Adjust the APSInt value.
17670     InitVal = InitVal.extOrTrunc(NewWidth);
17671     InitVal.setIsSigned(NewSign);
17672     ECD->setInitVal(InitVal);
17673 
17674     // Adjust the Expr initializer and type.
17675     if (ECD->getInitExpr() &&
17676         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
17677       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
17678                                                 CK_IntegralCast,
17679                                                 ECD->getInitExpr(),
17680                                                 /*base paths*/ nullptr,
17681                                                 VK_RValue));
17682     if (getLangOpts().CPlusPlus)
17683       // C++ [dcl.enum]p4: Following the closing brace of an
17684       // enum-specifier, each enumerator has the type of its
17685       // enumeration.
17686       ECD->setType(EnumType);
17687     else
17688       ECD->setType(NewTy);
17689   }
17690 
17691   Enum->completeDefinition(BestType, BestPromotionType,
17692                            NumPositiveBits, NumNegativeBits);
17693 
17694   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
17695 
17696   if (Enum->isClosedFlag()) {
17697     for (Decl *D : Elements) {
17698       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
17699       if (!ECD) continue;  // Already issued a diagnostic.
17700 
17701       llvm::APSInt InitVal = ECD->getInitVal();
17702       if (InitVal != 0 && !InitVal.isPowerOf2() &&
17703           !IsValueInFlagEnum(Enum, InitVal, true))
17704         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
17705           << ECD << Enum;
17706     }
17707   }
17708 
17709   // Now that the enum type is defined, ensure it's not been underaligned.
17710   if (Enum->hasAttrs())
17711     CheckAlignasUnderalignment(Enum);
17712 }
17713 
17714 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
17715                                   SourceLocation StartLoc,
17716                                   SourceLocation EndLoc) {
17717   StringLiteral *AsmString = cast<StringLiteral>(expr);
17718 
17719   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
17720                                                    AsmString, StartLoc,
17721                                                    EndLoc);
17722   CurContext->addDecl(New);
17723   return New;
17724 }
17725 
17726 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
17727                                       IdentifierInfo* AliasName,
17728                                       SourceLocation PragmaLoc,
17729                                       SourceLocation NameLoc,
17730                                       SourceLocation AliasNameLoc) {
17731   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
17732                                          LookupOrdinaryName);
17733   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
17734                            AttributeCommonInfo::AS_Pragma);
17735   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
17736       Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
17737 
17738   // If a declaration that:
17739   // 1) declares a function or a variable
17740   // 2) has external linkage
17741   // already exists, add a label attribute to it.
17742   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17743     if (isDeclExternC(PrevDecl))
17744       PrevDecl->addAttr(Attr);
17745     else
17746       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
17747           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
17748   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
17749   } else
17750     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
17751 }
17752 
17753 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
17754                              SourceLocation PragmaLoc,
17755                              SourceLocation NameLoc) {
17756   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
17757 
17758   if (PrevDecl) {
17759     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
17760   } else {
17761     (void)WeakUndeclaredIdentifiers.insert(
17762       std::pair<IdentifierInfo*,WeakInfo>
17763         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
17764   }
17765 }
17766 
17767 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
17768                                 IdentifierInfo* AliasName,
17769                                 SourceLocation PragmaLoc,
17770                                 SourceLocation NameLoc,
17771                                 SourceLocation AliasNameLoc) {
17772   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
17773                                     LookupOrdinaryName);
17774   WeakInfo W = WeakInfo(Name, NameLoc);
17775 
17776   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17777     if (!PrevDecl->hasAttr<AliasAttr>())
17778       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
17779         DeclApplyPragmaWeak(TUScope, ND, W);
17780   } else {
17781     (void)WeakUndeclaredIdentifiers.insert(
17782       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
17783   }
17784 }
17785 
17786 Decl *Sema::getObjCDeclContext() const {
17787   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
17788 }
17789 
17790 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD) {
17791   // Templates are emitted when they're instantiated.
17792   if (FD->isDependentContext())
17793     return FunctionEmissionStatus::TemplateDiscarded;
17794 
17795   FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown;
17796   if (LangOpts.OpenMPIsDevice) {
17797     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
17798         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
17799     if (DevTy.hasValue()) {
17800       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
17801         OMPES = FunctionEmissionStatus::OMPDiscarded;
17802       else if (DeviceKnownEmittedFns.count(FD) > 0)
17803         OMPES = FunctionEmissionStatus::Emitted;
17804     }
17805   } else if (LangOpts.OpenMP) {
17806     // In OpenMP 4.5 all the functions are host functions.
17807     if (LangOpts.OpenMP <= 45) {
17808       OMPES = FunctionEmissionStatus::Emitted;
17809     } else {
17810       Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
17811           OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
17812       // In OpenMP 5.0 or above, DevTy may be changed later by
17813       // #pragma omp declare target to(*) device_type(*). Therefore DevTy
17814       // having no value does not imply host. The emission status will be
17815       // checked again at the end of compilation unit.
17816       if (DevTy.hasValue()) {
17817         if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
17818           OMPES = FunctionEmissionStatus::OMPDiscarded;
17819         } else if (DeviceKnownEmittedFns.count(FD) > 0) {
17820           OMPES = FunctionEmissionStatus::Emitted;
17821         }
17822       }
17823     }
17824   }
17825   if (OMPES == FunctionEmissionStatus::OMPDiscarded ||
17826       (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA))
17827     return OMPES;
17828 
17829   if (LangOpts.CUDA) {
17830     // When compiling for device, host functions are never emitted.  Similarly,
17831     // when compiling for host, device and global functions are never emitted.
17832     // (Technically, we do emit a host-side stub for global functions, but this
17833     // doesn't count for our purposes here.)
17834     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
17835     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
17836       return FunctionEmissionStatus::CUDADiscarded;
17837     if (!LangOpts.CUDAIsDevice &&
17838         (T == Sema::CFT_Device || T == Sema::CFT_Global))
17839       return FunctionEmissionStatus::CUDADiscarded;
17840 
17841     // Check whether this function is externally visible -- if so, it's
17842     // known-emitted.
17843     //
17844     // We have to check the GVA linkage of the function's *definition* -- if we
17845     // only have a declaration, we don't know whether or not the function will
17846     // be emitted, because (say) the definition could include "inline".
17847     FunctionDecl *Def = FD->getDefinition();
17848 
17849     if (Def &&
17850         !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def))
17851         && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted))
17852       return FunctionEmissionStatus::Emitted;
17853   }
17854 
17855   // Otherwise, the function is known-emitted if it's in our set of
17856   // known-emitted functions.
17857   return (DeviceKnownEmittedFns.count(FD) > 0)
17858              ? FunctionEmissionStatus::Emitted
17859              : FunctionEmissionStatus::Unknown;
17860 }
17861 
17862 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
17863   // Host-side references to a __global__ function refer to the stub, so the
17864   // function itself is never emitted and therefore should not be marked.
17865   // If we have host fn calls kernel fn calls host+device, the HD function
17866   // does not get instantiated on the host. We model this by omitting at the
17867   // call to the kernel from the callgraph. This ensures that, when compiling
17868   // for host, only HD functions actually called from the host get marked as
17869   // known-emitted.
17870   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
17871          IdentifyCUDATarget(Callee) == CFT_Global;
17872 }
17873