1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for declarations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/CommentDiagnostic.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/NonTrivialTypeVisitor.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/Basic/Builtins.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
32 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
33 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
34 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
35 #include "clang/Sema/CXXFieldCollector.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/DelayedDiagnostic.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaInternal.h"
44 #include "clang/Sema/Template.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/Triple.h"
47 #include <algorithm>
48 #include <cstring>
49 #include <functional>
50 
51 using namespace clang;
52 using namespace sema;
53 
54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
55   if (OwnedType) {
56     Decl *Group[2] = { OwnedType, Ptr };
57     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
58   }
59 
60   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
61 }
62 
63 namespace {
64 
65 class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
66  public:
67    TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
68                         bool AllowTemplates = false,
69                         bool AllowNonTemplates = true)
70        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
71          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
72      WantExpressionKeywords = false;
73      WantCXXNamedCasts = false;
74      WantRemainingKeywords = false;
75   }
76 
77   bool ValidateCandidate(const TypoCorrection &candidate) override {
78     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
79       if (!AllowInvalidDecl && ND->isInvalidDecl())
80         return false;
81 
82       if (getAsTypeTemplateDecl(ND))
83         return AllowTemplates;
84 
85       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
86       if (!IsType)
87         return false;
88 
89       if (AllowNonTemplates)
90         return true;
91 
92       // An injected-class-name of a class template (specialization) is valid
93       // as a template or as a non-template.
94       if (AllowTemplates) {
95         auto *RD = dyn_cast<CXXRecordDecl>(ND);
96         if (!RD || !RD->isInjectedClassName())
97           return false;
98         RD = cast<CXXRecordDecl>(RD->getDeclContext());
99         return RD->getDescribedClassTemplate() ||
100                isa<ClassTemplateSpecializationDecl>(RD);
101       }
102 
103       return false;
104     }
105 
106     return !WantClassName && candidate.isKeyword();
107   }
108 
109   std::unique_ptr<CorrectionCandidateCallback> clone() override {
110     return std::make_unique<TypeNameValidatorCCC>(*this);
111   }
112 
113  private:
114   bool AllowInvalidDecl;
115   bool WantClassName;
116   bool AllowTemplates;
117   bool AllowNonTemplates;
118 };
119 
120 } // end anonymous namespace
121 
122 /// Determine whether the token kind starts a simple-type-specifier.
123 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
124   switch (Kind) {
125   // FIXME: Take into account the current language when deciding whether a
126   // token kind is a valid type specifier
127   case tok::kw_short:
128   case tok::kw_long:
129   case tok::kw___int64:
130   case tok::kw___int128:
131   case tok::kw_signed:
132   case tok::kw_unsigned:
133   case tok::kw_void:
134   case tok::kw_char:
135   case tok::kw_int:
136   case tok::kw_half:
137   case tok::kw_float:
138   case tok::kw_double:
139   case tok::kw__Float16:
140   case tok::kw___float128:
141   case tok::kw_wchar_t:
142   case tok::kw_bool:
143   case tok::kw___underlying_type:
144   case tok::kw___auto_type:
145     return true;
146 
147   case tok::annot_typename:
148   case tok::kw_char16_t:
149   case tok::kw_char32_t:
150   case tok::kw_typeof:
151   case tok::annot_decltype:
152   case tok::kw_decltype:
153     return getLangOpts().CPlusPlus;
154 
155   case tok::kw_char8_t:
156     return getLangOpts().Char8;
157 
158   default:
159     break;
160   }
161 
162   return false;
163 }
164 
165 namespace {
166 enum class UnqualifiedTypeNameLookupResult {
167   NotFound,
168   FoundNonType,
169   FoundType
170 };
171 } // end anonymous namespace
172 
173 /// Tries to perform unqualified lookup of the type decls in bases for
174 /// dependent class.
175 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
176 /// type decl, \a FoundType if only type decls are found.
177 static UnqualifiedTypeNameLookupResult
178 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
179                                 SourceLocation NameLoc,
180                                 const CXXRecordDecl *RD) {
181   if (!RD->hasDefinition())
182     return UnqualifiedTypeNameLookupResult::NotFound;
183   // Look for type decls in base classes.
184   UnqualifiedTypeNameLookupResult FoundTypeDecl =
185       UnqualifiedTypeNameLookupResult::NotFound;
186   for (const auto &Base : RD->bases()) {
187     const CXXRecordDecl *BaseRD = nullptr;
188     if (auto *BaseTT = Base.getType()->getAs<TagType>())
189       BaseRD = BaseTT->getAsCXXRecordDecl();
190     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
191       // Look for type decls in dependent base classes that have known primary
192       // templates.
193       if (!TST || !TST->isDependentType())
194         continue;
195       auto *TD = TST->getTemplateName().getAsTemplateDecl();
196       if (!TD)
197         continue;
198       if (auto *BasePrimaryTemplate =
199           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
200         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
201           BaseRD = BasePrimaryTemplate;
202         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
203           if (const ClassTemplatePartialSpecializationDecl *PS =
204                   CTD->findPartialSpecialization(Base.getType()))
205             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
206               BaseRD = PS;
207         }
208       }
209     }
210     if (BaseRD) {
211       for (NamedDecl *ND : BaseRD->lookup(&II)) {
212         if (!isa<TypeDecl>(ND))
213           return UnqualifiedTypeNameLookupResult::FoundNonType;
214         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
215       }
216       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
217         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
218         case UnqualifiedTypeNameLookupResult::FoundNonType:
219           return UnqualifiedTypeNameLookupResult::FoundNonType;
220         case UnqualifiedTypeNameLookupResult::FoundType:
221           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
222           break;
223         case UnqualifiedTypeNameLookupResult::NotFound:
224           break;
225         }
226       }
227     }
228   }
229 
230   return FoundTypeDecl;
231 }
232 
233 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
234                                                       const IdentifierInfo &II,
235                                                       SourceLocation NameLoc) {
236   // Lookup in the parent class template context, if any.
237   const CXXRecordDecl *RD = nullptr;
238   UnqualifiedTypeNameLookupResult FoundTypeDecl =
239       UnqualifiedTypeNameLookupResult::NotFound;
240   for (DeclContext *DC = S.CurContext;
241        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
242        DC = DC->getParent()) {
243     // Look for type decls in dependent base classes that have known primary
244     // templates.
245     RD = dyn_cast<CXXRecordDecl>(DC);
246     if (RD && RD->getDescribedClassTemplate())
247       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
248   }
249   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
250     return nullptr;
251 
252   // We found some types in dependent base classes.  Recover as if the user
253   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
254   // lookup during template instantiation.
255   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
256 
257   ASTContext &Context = S.Context;
258   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
259                                           cast<Type>(Context.getRecordType(RD)));
260   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
261 
262   CXXScopeSpec SS;
263   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
264 
265   TypeLocBuilder Builder;
266   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
267   DepTL.setNameLoc(NameLoc);
268   DepTL.setElaboratedKeywordLoc(SourceLocation());
269   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
270   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
271 }
272 
273 /// If the identifier refers to a type name within this scope,
274 /// return the declaration of that type.
275 ///
276 /// This routine performs ordinary name lookup of the identifier II
277 /// within the given scope, with optional C++ scope specifier SS, to
278 /// determine whether the name refers to a type. If so, returns an
279 /// opaque pointer (actually a QualType) corresponding to that
280 /// type. Otherwise, returns NULL.
281 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
282                              Scope *S, CXXScopeSpec *SS,
283                              bool isClassName, bool HasTrailingDot,
284                              ParsedType ObjectTypePtr,
285                              bool IsCtorOrDtorName,
286                              bool WantNontrivialTypeSourceInfo,
287                              bool IsClassTemplateDeductionContext,
288                              IdentifierInfo **CorrectedII) {
289   // FIXME: Consider allowing this outside C++1z mode as an extension.
290   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
291                               getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
292                               !isClassName && !HasTrailingDot;
293 
294   // Determine where we will perform name lookup.
295   DeclContext *LookupCtx = nullptr;
296   if (ObjectTypePtr) {
297     QualType ObjectType = ObjectTypePtr.get();
298     if (ObjectType->isRecordType())
299       LookupCtx = computeDeclContext(ObjectType);
300   } else if (SS && SS->isNotEmpty()) {
301     LookupCtx = computeDeclContext(*SS, false);
302 
303     if (!LookupCtx) {
304       if (isDependentScopeSpecifier(*SS)) {
305         // C++ [temp.res]p3:
306         //   A qualified-id that refers to a type and in which the
307         //   nested-name-specifier depends on a template-parameter (14.6.2)
308         //   shall be prefixed by the keyword typename to indicate that the
309         //   qualified-id denotes a type, forming an
310         //   elaborated-type-specifier (7.1.5.3).
311         //
312         // We therefore do not perform any name lookup if the result would
313         // refer to a member of an unknown specialization.
314         if (!isClassName && !IsCtorOrDtorName)
315           return nullptr;
316 
317         // We know from the grammar that this name refers to a type,
318         // so build a dependent node to describe the type.
319         if (WantNontrivialTypeSourceInfo)
320           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
321 
322         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
323         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
324                                        II, NameLoc);
325         return ParsedType::make(T);
326       }
327 
328       return nullptr;
329     }
330 
331     if (!LookupCtx->isDependentContext() &&
332         RequireCompleteDeclContext(*SS, LookupCtx))
333       return nullptr;
334   }
335 
336   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
337   // lookup for class-names.
338   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
339                                       LookupOrdinaryName;
340   LookupResult Result(*this, &II, NameLoc, Kind);
341   if (LookupCtx) {
342     // Perform "qualified" name lookup into the declaration context we
343     // computed, which is either the type of the base of a member access
344     // expression or the declaration context associated with a prior
345     // nested-name-specifier.
346     LookupQualifiedName(Result, LookupCtx);
347 
348     if (ObjectTypePtr && Result.empty()) {
349       // C++ [basic.lookup.classref]p3:
350       //   If the unqualified-id is ~type-name, the type-name is looked up
351       //   in the context of the entire postfix-expression. If the type T of
352       //   the object expression is of a class type C, the type-name is also
353       //   looked up in the scope of class C. At least one of the lookups shall
354       //   find a name that refers to (possibly cv-qualified) T.
355       LookupName(Result, S);
356     }
357   } else {
358     // Perform unqualified name lookup.
359     LookupName(Result, S);
360 
361     // For unqualified lookup in a class template in MSVC mode, look into
362     // dependent base classes where the primary class template is known.
363     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
364       if (ParsedType TypeInBase =
365               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
366         return TypeInBase;
367     }
368   }
369 
370   NamedDecl *IIDecl = nullptr;
371   switch (Result.getResultKind()) {
372   case LookupResult::NotFound:
373   case LookupResult::NotFoundInCurrentInstantiation:
374     if (CorrectedII) {
375       TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
376                                AllowDeducedTemplate);
377       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
378                                               S, SS, CCC, CTK_ErrorRecovery);
379       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
380       TemplateTy Template;
381       bool MemberOfUnknownSpecialization;
382       UnqualifiedId TemplateName;
383       TemplateName.setIdentifier(NewII, NameLoc);
384       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
385       CXXScopeSpec NewSS, *NewSSPtr = SS;
386       if (SS && NNS) {
387         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
388         NewSSPtr = &NewSS;
389       }
390       if (Correction && (NNS || NewII != &II) &&
391           // Ignore a correction to a template type as the to-be-corrected
392           // identifier is not a template (typo correction for template names
393           // is handled elsewhere).
394           !(getLangOpts().CPlusPlus && NewSSPtr &&
395             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
396                            Template, MemberOfUnknownSpecialization))) {
397         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
398                                     isClassName, HasTrailingDot, ObjectTypePtr,
399                                     IsCtorOrDtorName,
400                                     WantNontrivialTypeSourceInfo,
401                                     IsClassTemplateDeductionContext);
402         if (Ty) {
403           diagnoseTypo(Correction,
404                        PDiag(diag::err_unknown_type_or_class_name_suggest)
405                          << Result.getLookupName() << isClassName);
406           if (SS && NNS)
407             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
408           *CorrectedII = NewII;
409           return Ty;
410         }
411       }
412     }
413     // If typo correction failed or was not performed, fall through
414     LLVM_FALLTHROUGH;
415   case LookupResult::FoundOverloaded:
416   case LookupResult::FoundUnresolvedValue:
417     Result.suppressDiagnostics();
418     return nullptr;
419 
420   case LookupResult::Ambiguous:
421     // Recover from type-hiding ambiguities by hiding the type.  We'll
422     // do the lookup again when looking for an object, and we can
423     // diagnose the error then.  If we don't do this, then the error
424     // about hiding the type will be immediately followed by an error
425     // that only makes sense if the identifier was treated like a type.
426     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
427       Result.suppressDiagnostics();
428       return nullptr;
429     }
430 
431     // Look to see if we have a type anywhere in the list of results.
432     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
433          Res != ResEnd; ++Res) {
434       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
435           (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
436         if (!IIDecl ||
437             (*Res)->getLocation().getRawEncoding() <
438               IIDecl->getLocation().getRawEncoding())
439           IIDecl = *Res;
440       }
441     }
442 
443     if (!IIDecl) {
444       // None of the entities we found is a type, so there is no way
445       // to even assume that the result is a type. In this case, don't
446       // complain about the ambiguity. The parser will either try to
447       // perform this lookup again (e.g., as an object name), which
448       // will produce the ambiguity, or will complain that it expected
449       // a type name.
450       Result.suppressDiagnostics();
451       return nullptr;
452     }
453 
454     // We found a type within the ambiguous lookup; diagnose the
455     // ambiguity and then return that type. This might be the right
456     // answer, or it might not be, but it suppresses any attempt to
457     // perform the name lookup again.
458     break;
459 
460   case LookupResult::Found:
461     IIDecl = Result.getFoundDecl();
462     break;
463   }
464 
465   assert(IIDecl && "Didn't find decl");
466 
467   QualType T;
468   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
469     // C++ [class.qual]p2: A lookup that would find the injected-class-name
470     // instead names the constructors of the class, except when naming a class.
471     // This is ill-formed when we're not actually forming a ctor or dtor name.
472     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
473     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
474     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
475         FoundRD->isInjectedClassName() &&
476         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
477       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
478           << &II << /*Type*/1;
479 
480     DiagnoseUseOfDecl(IIDecl, NameLoc);
481 
482     T = Context.getTypeDeclType(TD);
483     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
484   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
485     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
486     if (!HasTrailingDot)
487       T = Context.getObjCInterfaceType(IDecl);
488   } else if (AllowDeducedTemplate) {
489     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
490       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
491                                                        QualType(), false);
492   }
493 
494   if (T.isNull()) {
495     // If it's not plausibly a type, suppress diagnostics.
496     Result.suppressDiagnostics();
497     return nullptr;
498   }
499 
500   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
501   // constructor or destructor name (in such a case, the scope specifier
502   // will be attached to the enclosing Expr or Decl node).
503   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
504       !isa<ObjCInterfaceDecl>(IIDecl)) {
505     if (WantNontrivialTypeSourceInfo) {
506       // Construct a type with type-source information.
507       TypeLocBuilder Builder;
508       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
509 
510       T = getElaboratedType(ETK_None, *SS, T);
511       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
512       ElabTL.setElaboratedKeywordLoc(SourceLocation());
513       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
514       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
515     } else {
516       T = getElaboratedType(ETK_None, *SS, T);
517     }
518   }
519 
520   return ParsedType::make(T);
521 }
522 
523 // Builds a fake NNS for the given decl context.
524 static NestedNameSpecifier *
525 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
526   for (;; DC = DC->getLookupParent()) {
527     DC = DC->getPrimaryContext();
528     auto *ND = dyn_cast<NamespaceDecl>(DC);
529     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
530       return NestedNameSpecifier::Create(Context, nullptr, ND);
531     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
532       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
533                                          RD->getTypeForDecl());
534     else if (isa<TranslationUnitDecl>(DC))
535       return NestedNameSpecifier::GlobalSpecifier(Context);
536   }
537   llvm_unreachable("something isn't in TU scope?");
538 }
539 
540 /// Find the parent class with dependent bases of the innermost enclosing method
541 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
542 /// up allowing unqualified dependent type names at class-level, which MSVC
543 /// correctly rejects.
544 static const CXXRecordDecl *
545 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
546   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
547     DC = DC->getPrimaryContext();
548     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
549       if (MD->getParent()->hasAnyDependentBases())
550         return MD->getParent();
551   }
552   return nullptr;
553 }
554 
555 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
556                                           SourceLocation NameLoc,
557                                           bool IsTemplateTypeArg) {
558   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
559 
560   NestedNameSpecifier *NNS = nullptr;
561   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
562     // If we weren't able to parse a default template argument, delay lookup
563     // until instantiation time by making a non-dependent DependentTypeName. We
564     // pretend we saw a NestedNameSpecifier referring to the current scope, and
565     // lookup is retried.
566     // FIXME: This hurts our diagnostic quality, since we get errors like "no
567     // type named 'Foo' in 'current_namespace'" when the user didn't write any
568     // name specifiers.
569     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
570     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
571   } else if (const CXXRecordDecl *RD =
572                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
573     // Build a DependentNameType that will perform lookup into RD at
574     // instantiation time.
575     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
576                                       RD->getTypeForDecl());
577 
578     // Diagnose that this identifier was undeclared, and retry the lookup during
579     // template instantiation.
580     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
581                                                                       << RD;
582   } else {
583     // This is not a situation that we should recover from.
584     return ParsedType();
585   }
586 
587   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
588 
589   // Build type location information.  We synthesized the qualifier, so we have
590   // to build a fake NestedNameSpecifierLoc.
591   NestedNameSpecifierLocBuilder NNSLocBuilder;
592   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
593   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
594 
595   TypeLocBuilder Builder;
596   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
597   DepTL.setNameLoc(NameLoc);
598   DepTL.setElaboratedKeywordLoc(SourceLocation());
599   DepTL.setQualifierLoc(QualifierLoc);
600   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
601 }
602 
603 /// isTagName() - This method is called *for error recovery purposes only*
604 /// to determine if the specified name is a valid tag name ("struct foo").  If
605 /// so, this returns the TST for the tag corresponding to it (TST_enum,
606 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
607 /// cases in C where the user forgot to specify the tag.
608 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
609   // Do a tag name lookup in this scope.
610   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
611   LookupName(R, S, false);
612   R.suppressDiagnostics();
613   if (R.getResultKind() == LookupResult::Found)
614     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
615       switch (TD->getTagKind()) {
616       case TTK_Struct: return DeclSpec::TST_struct;
617       case TTK_Interface: return DeclSpec::TST_interface;
618       case TTK_Union:  return DeclSpec::TST_union;
619       case TTK_Class:  return DeclSpec::TST_class;
620       case TTK_Enum:   return DeclSpec::TST_enum;
621       }
622     }
623 
624   return DeclSpec::TST_unspecified;
625 }
626 
627 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
628 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
629 /// then downgrade the missing typename error to a warning.
630 /// This is needed for MSVC compatibility; Example:
631 /// @code
632 /// template<class T> class A {
633 /// public:
634 ///   typedef int TYPE;
635 /// };
636 /// template<class T> class B : public A<T> {
637 /// public:
638 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
639 /// };
640 /// @endcode
641 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
642   if (CurContext->isRecord()) {
643     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
644       return true;
645 
646     const Type *Ty = SS->getScopeRep()->getAsType();
647 
648     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
649     for (const auto &Base : RD->bases())
650       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
651         return true;
652     return S->isFunctionPrototypeScope();
653   }
654   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
655 }
656 
657 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
658                                    SourceLocation IILoc,
659                                    Scope *S,
660                                    CXXScopeSpec *SS,
661                                    ParsedType &SuggestedType,
662                                    bool IsTemplateName) {
663   // Don't report typename errors for editor placeholders.
664   if (II->isEditorPlaceholder())
665     return;
666   // We don't have anything to suggest (yet).
667   SuggestedType = nullptr;
668 
669   // There may have been a typo in the name of the type. Look up typo
670   // results, in case we have something that we can suggest.
671   TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
672                            /*AllowTemplates=*/IsTemplateName,
673                            /*AllowNonTemplates=*/!IsTemplateName);
674   if (TypoCorrection Corrected =
675           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
676                       CCC, CTK_ErrorRecovery)) {
677     // FIXME: Support error recovery for the template-name case.
678     bool CanRecover = !IsTemplateName;
679     if (Corrected.isKeyword()) {
680       // We corrected to a keyword.
681       diagnoseTypo(Corrected,
682                    PDiag(IsTemplateName ? diag::err_no_template_suggest
683                                         : diag::err_unknown_typename_suggest)
684                        << II);
685       II = Corrected.getCorrectionAsIdentifierInfo();
686     } else {
687       // We found a similarly-named type or interface; suggest that.
688       if (!SS || !SS->isSet()) {
689         diagnoseTypo(Corrected,
690                      PDiag(IsTemplateName ? diag::err_no_template_suggest
691                                           : diag::err_unknown_typename_suggest)
692                          << II, CanRecover);
693       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
694         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
695         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
696                                 II->getName().equals(CorrectedStr);
697         diagnoseTypo(Corrected,
698                      PDiag(IsTemplateName
699                                ? diag::err_no_member_template_suggest
700                                : diag::err_unknown_nested_typename_suggest)
701                          << II << DC << DroppedSpecifier << SS->getRange(),
702                      CanRecover);
703       } else {
704         llvm_unreachable("could not have corrected a typo here");
705       }
706 
707       if (!CanRecover)
708         return;
709 
710       CXXScopeSpec tmpSS;
711       if (Corrected.getCorrectionSpecifier())
712         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
713                           SourceRange(IILoc));
714       // FIXME: Support class template argument deduction here.
715       SuggestedType =
716           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
717                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
718                       /*IsCtorOrDtorName=*/false,
719                       /*WantNontrivialTypeSourceInfo=*/true);
720     }
721     return;
722   }
723 
724   if (getLangOpts().CPlusPlus && !IsTemplateName) {
725     // See if II is a class template that the user forgot to pass arguments to.
726     UnqualifiedId Name;
727     Name.setIdentifier(II, IILoc);
728     CXXScopeSpec EmptySS;
729     TemplateTy TemplateResult;
730     bool MemberOfUnknownSpecialization;
731     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
732                        Name, nullptr, true, TemplateResult,
733                        MemberOfUnknownSpecialization) == TNK_Type_template) {
734       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
735       return;
736     }
737   }
738 
739   // FIXME: Should we move the logic that tries to recover from a missing tag
740   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
741 
742   if (!SS || (!SS->isSet() && !SS->isInvalid()))
743     Diag(IILoc, IsTemplateName ? diag::err_no_template
744                                : diag::err_unknown_typename)
745         << II;
746   else if (DeclContext *DC = computeDeclContext(*SS, false))
747     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
748                                : diag::err_typename_nested_not_found)
749         << II << DC << SS->getRange();
750   else if (isDependentScopeSpecifier(*SS)) {
751     unsigned DiagID = diag::err_typename_missing;
752     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
753       DiagID = diag::ext_typename_missing;
754 
755     Diag(SS->getRange().getBegin(), DiagID)
756       << SS->getScopeRep() << II->getName()
757       << SourceRange(SS->getRange().getBegin(), IILoc)
758       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
759     SuggestedType = ActOnTypenameType(S, SourceLocation(),
760                                       *SS, *II, IILoc).get();
761   } else {
762     assert(SS && SS->isInvalid() &&
763            "Invalid scope specifier has already been diagnosed");
764   }
765 }
766 
767 /// Determine whether the given result set contains either a type name
768 /// or
769 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
770   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
771                        NextToken.is(tok::less);
772 
773   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
774     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
775       return true;
776 
777     if (CheckTemplate && isa<TemplateDecl>(*I))
778       return true;
779   }
780 
781   return false;
782 }
783 
784 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
785                                     Scope *S, CXXScopeSpec &SS,
786                                     IdentifierInfo *&Name,
787                                     SourceLocation NameLoc) {
788   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
789   SemaRef.LookupParsedName(R, S, &SS);
790   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
791     StringRef FixItTagName;
792     switch (Tag->getTagKind()) {
793       case TTK_Class:
794         FixItTagName = "class ";
795         break;
796 
797       case TTK_Enum:
798         FixItTagName = "enum ";
799         break;
800 
801       case TTK_Struct:
802         FixItTagName = "struct ";
803         break;
804 
805       case TTK_Interface:
806         FixItTagName = "__interface ";
807         break;
808 
809       case TTK_Union:
810         FixItTagName = "union ";
811         break;
812     }
813 
814     StringRef TagName = FixItTagName.drop_back();
815     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
816       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
817       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
818 
819     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
820          I != IEnd; ++I)
821       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
822         << Name << TagName;
823 
824     // Replace lookup results with just the tag decl.
825     Result.clear(Sema::LookupTagName);
826     SemaRef.LookupParsedName(Result, S, &SS);
827     return true;
828   }
829 
830   return false;
831 }
832 
833 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
834 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
835                                   QualType T, SourceLocation NameLoc) {
836   ASTContext &Context = S.Context;
837 
838   TypeLocBuilder Builder;
839   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
840 
841   T = S.getElaboratedType(ETK_None, SS, T);
842   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
843   ElabTL.setElaboratedKeywordLoc(SourceLocation());
844   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
845   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
846 }
847 
848 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
849                                             IdentifierInfo *&Name,
850                                             SourceLocation NameLoc,
851                                             const Token &NextToken,
852                                             CorrectionCandidateCallback *CCC) {
853   DeclarationNameInfo NameInfo(Name, NameLoc);
854   ObjCMethodDecl *CurMethod = getCurMethodDecl();
855 
856   assert(NextToken.isNot(tok::coloncolon) &&
857          "parse nested name specifiers before calling ClassifyName");
858   if (getLangOpts().CPlusPlus && SS.isSet() &&
859       isCurrentClassName(*Name, S, &SS)) {
860     // Per [class.qual]p2, this names the constructors of SS, not the
861     // injected-class-name. We don't have a classification for that.
862     // There's not much point caching this result, since the parser
863     // will reject it later.
864     return NameClassification::Unknown();
865   }
866 
867   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
868   LookupParsedName(Result, S, &SS, !CurMethod);
869 
870   if (SS.isInvalid())
871     return NameClassification::Error();
872 
873   // For unqualified lookup in a class template in MSVC mode, look into
874   // dependent base classes where the primary class template is known.
875   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
876     if (ParsedType TypeInBase =
877             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
878       return TypeInBase;
879   }
880 
881   // Perform lookup for Objective-C instance variables (including automatically
882   // synthesized instance variables), if we're in an Objective-C method.
883   // FIXME: This lookup really, really needs to be folded in to the normal
884   // unqualified lookup mechanism.
885   if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
886     DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
887     if (Ivar.isInvalid())
888       return NameClassification::Error();
889     if (Ivar.isUsable())
890       return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
891 
892     // We defer builtin creation until after ivar lookup inside ObjC methods.
893     if (Result.empty())
894       LookupBuiltin(Result);
895   }
896 
897   bool SecondTry = false;
898   bool IsFilteredTemplateName = false;
899 
900 Corrected:
901   switch (Result.getResultKind()) {
902   case LookupResult::NotFound:
903     // If an unqualified-id is followed by a '(', then we have a function
904     // call.
905     if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
906       // In C++, this is an ADL-only call.
907       // FIXME: Reference?
908       if (getLangOpts().CPlusPlus)
909         return NameClassification::UndeclaredNonType();
910 
911       // C90 6.3.2.2:
912       //   If the expression that precedes the parenthesized argument list in a
913       //   function call consists solely of an identifier, and if no
914       //   declaration is visible for this identifier, the identifier is
915       //   implicitly declared exactly as if, in the innermost block containing
916       //   the function call, the declaration
917       //
918       //     extern int identifier ();
919       //
920       //   appeared.
921       //
922       // We also allow this in C99 as an extension.
923       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
924         return NameClassification::NonType(D);
925     }
926 
927     if (getLangOpts().CPlusPlus2a && SS.isEmpty() && NextToken.is(tok::less)) {
928       // In C++20 onwards, this could be an ADL-only call to a function
929       // template, and we're required to assume that this is a template name.
930       //
931       // FIXME: Find a way to still do typo correction in this case.
932       TemplateName Template =
933           Context.getAssumedTemplateName(NameInfo.getName());
934       return NameClassification::UndeclaredTemplate(Template);
935     }
936 
937     // In C, we first see whether there is a tag type by the same name, in
938     // which case it's likely that the user just forgot to write "enum",
939     // "struct", or "union".
940     if (!getLangOpts().CPlusPlus && !SecondTry &&
941         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
942       break;
943     }
944 
945     // Perform typo correction to determine if there is another name that is
946     // close to this name.
947     if (!SecondTry && CCC) {
948       SecondTry = true;
949       if (TypoCorrection Corrected =
950               CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
951                           &SS, *CCC, CTK_ErrorRecovery)) {
952         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
953         unsigned QualifiedDiag = diag::err_no_member_suggest;
954 
955         NamedDecl *FirstDecl = Corrected.getFoundDecl();
956         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
957         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
958             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
959           UnqualifiedDiag = diag::err_no_template_suggest;
960           QualifiedDiag = diag::err_no_member_template_suggest;
961         } else if (UnderlyingFirstDecl &&
962                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
963                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
964                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
965           UnqualifiedDiag = diag::err_unknown_typename_suggest;
966           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
967         }
968 
969         if (SS.isEmpty()) {
970           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
971         } else {// FIXME: is this even reachable? Test it.
972           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
973           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
974                                   Name->getName().equals(CorrectedStr);
975           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
976                                     << Name << computeDeclContext(SS, false)
977                                     << DroppedSpecifier << SS.getRange());
978         }
979 
980         // Update the name, so that the caller has the new name.
981         Name = Corrected.getCorrectionAsIdentifierInfo();
982 
983         // Typo correction corrected to a keyword.
984         if (Corrected.isKeyword())
985           return Name;
986 
987         // Also update the LookupResult...
988         // FIXME: This should probably go away at some point
989         Result.clear();
990         Result.setLookupName(Corrected.getCorrection());
991         if (FirstDecl)
992           Result.addDecl(FirstDecl);
993 
994         // If we found an Objective-C instance variable, let
995         // LookupInObjCMethod build the appropriate expression to
996         // reference the ivar.
997         // FIXME: This is a gross hack.
998         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
999           DeclResult R =
1000               LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1001           if (R.isInvalid())
1002             return NameClassification::Error();
1003           if (R.isUsable())
1004             return NameClassification::NonType(Ivar);
1005         }
1006 
1007         goto Corrected;
1008       }
1009     }
1010 
1011     // We failed to correct; just fall through and let the parser deal with it.
1012     Result.suppressDiagnostics();
1013     return NameClassification::Unknown();
1014 
1015   case LookupResult::NotFoundInCurrentInstantiation: {
1016     // We performed name lookup into the current instantiation, and there were
1017     // dependent bases, so we treat this result the same way as any other
1018     // dependent nested-name-specifier.
1019 
1020     // C++ [temp.res]p2:
1021     //   A name used in a template declaration or definition and that is
1022     //   dependent on a template-parameter is assumed not to name a type
1023     //   unless the applicable name lookup finds a type name or the name is
1024     //   qualified by the keyword typename.
1025     //
1026     // FIXME: If the next token is '<', we might want to ask the parser to
1027     // perform some heroics to see if we actually have a
1028     // template-argument-list, which would indicate a missing 'template'
1029     // keyword here.
1030     return NameClassification::DependentNonType();
1031   }
1032 
1033   case LookupResult::Found:
1034   case LookupResult::FoundOverloaded:
1035   case LookupResult::FoundUnresolvedValue:
1036     break;
1037 
1038   case LookupResult::Ambiguous:
1039     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1040         hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1041                                       /*AllowDependent=*/false)) {
1042       // C++ [temp.local]p3:
1043       //   A lookup that finds an injected-class-name (10.2) can result in an
1044       //   ambiguity in certain cases (for example, if it is found in more than
1045       //   one base class). If all of the injected-class-names that are found
1046       //   refer to specializations of the same class template, and if the name
1047       //   is followed by a template-argument-list, the reference refers to the
1048       //   class template itself and not a specialization thereof, and is not
1049       //   ambiguous.
1050       //
1051       // This filtering can make an ambiguous result into an unambiguous one,
1052       // so try again after filtering out template names.
1053       FilterAcceptableTemplateNames(Result);
1054       if (!Result.isAmbiguous()) {
1055         IsFilteredTemplateName = true;
1056         break;
1057       }
1058     }
1059 
1060     // Diagnose the ambiguity and return an error.
1061     return NameClassification::Error();
1062   }
1063 
1064   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1065       (IsFilteredTemplateName ||
1066        hasAnyAcceptableTemplateNames(
1067            Result, /*AllowFunctionTemplates=*/true,
1068            /*AllowDependent=*/false,
1069            /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1070                getLangOpts().CPlusPlus2a))) {
1071     // C++ [temp.names]p3:
1072     //   After name lookup (3.4) finds that a name is a template-name or that
1073     //   an operator-function-id or a literal- operator-id refers to a set of
1074     //   overloaded functions any member of which is a function template if
1075     //   this is followed by a <, the < is always taken as the delimiter of a
1076     //   template-argument-list and never as the less-than operator.
1077     // C++2a [temp.names]p2:
1078     //   A name is also considered to refer to a template if it is an
1079     //   unqualified-id followed by a < and name lookup finds either one
1080     //   or more functions or finds nothing.
1081     if (!IsFilteredTemplateName)
1082       FilterAcceptableTemplateNames(Result);
1083 
1084     bool IsFunctionTemplate;
1085     bool IsVarTemplate;
1086     TemplateName Template;
1087     if (Result.end() - Result.begin() > 1) {
1088       IsFunctionTemplate = true;
1089       Template = Context.getOverloadedTemplateName(Result.begin(),
1090                                                    Result.end());
1091     } else if (!Result.empty()) {
1092       auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1093           *Result.begin(), /*AllowFunctionTemplates=*/true,
1094           /*AllowDependent=*/false));
1095       IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1096       IsVarTemplate = isa<VarTemplateDecl>(TD);
1097 
1098       if (SS.isNotEmpty())
1099         Template =
1100             Context.getQualifiedTemplateName(SS.getScopeRep(),
1101                                              /*TemplateKeyword=*/false, TD);
1102       else
1103         Template = TemplateName(TD);
1104     } else {
1105       // All results were non-template functions. This is a function template
1106       // name.
1107       IsFunctionTemplate = true;
1108       Template = Context.getAssumedTemplateName(NameInfo.getName());
1109     }
1110 
1111     if (IsFunctionTemplate) {
1112       // Function templates always go through overload resolution, at which
1113       // point we'll perform the various checks (e.g., accessibility) we need
1114       // to based on which function we selected.
1115       Result.suppressDiagnostics();
1116 
1117       return NameClassification::FunctionTemplate(Template);
1118     }
1119 
1120     return IsVarTemplate ? NameClassification::VarTemplate(Template)
1121                          : NameClassification::TypeTemplate(Template);
1122   }
1123 
1124   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1125   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1126     DiagnoseUseOfDecl(Type, NameLoc);
1127     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1128     QualType T = Context.getTypeDeclType(Type);
1129     if (SS.isNotEmpty())
1130       return buildNestedType(*this, SS, T, NameLoc);
1131     return ParsedType::make(T);
1132   }
1133 
1134   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1135   if (!Class) {
1136     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1137     if (ObjCCompatibleAliasDecl *Alias =
1138             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1139       Class = Alias->getClassInterface();
1140   }
1141 
1142   if (Class) {
1143     DiagnoseUseOfDecl(Class, NameLoc);
1144 
1145     if (NextToken.is(tok::period)) {
1146       // Interface. <something> is parsed as a property reference expression.
1147       // Just return "unknown" as a fall-through for now.
1148       Result.suppressDiagnostics();
1149       return NameClassification::Unknown();
1150     }
1151 
1152     QualType T = Context.getObjCInterfaceType(Class);
1153     return ParsedType::make(T);
1154   }
1155 
1156   if (isa<ConceptDecl>(FirstDecl))
1157     return NameClassification::Concept(
1158         TemplateName(cast<TemplateDecl>(FirstDecl)));
1159 
1160   // We can have a type template here if we're classifying a template argument.
1161   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1162       !isa<VarTemplateDecl>(FirstDecl))
1163     return NameClassification::TypeTemplate(
1164         TemplateName(cast<TemplateDecl>(FirstDecl)));
1165 
1166   // Check for a tag type hidden by a non-type decl in a few cases where it
1167   // seems likely a type is wanted instead of the non-type that was found.
1168   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1169   if ((NextToken.is(tok::identifier) ||
1170        (NextIsOp &&
1171         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1172       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1173     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1174     DiagnoseUseOfDecl(Type, NameLoc);
1175     QualType T = Context.getTypeDeclType(Type);
1176     if (SS.isNotEmpty())
1177       return buildNestedType(*this, SS, T, NameLoc);
1178     return ParsedType::make(T);
1179   }
1180 
1181   // FIXME: This is context-dependent. We need to defer building the member
1182   // expression until the classification is consumed.
1183   if (FirstDecl->isCXXClassMember())
1184     return NameClassification::ContextIndependentExpr(
1185         BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, nullptr,
1186                                         S));
1187 
1188   // If we already know which single declaration is referenced, just annotate
1189   // that declaration directly.
1190   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1191   if (Result.isSingleResult() && !ADL)
1192     return NameClassification::NonType(Result.getRepresentativeDecl());
1193 
1194   // Build an UnresolvedLookupExpr. Note that this doesn't depend on the
1195   // context in which we performed classification, so it's safe to do now.
1196   return NameClassification::ContextIndependentExpr(
1197       BuildDeclarationNameExpr(SS, Result, ADL));
1198 }
1199 
1200 ExprResult
1201 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1202                                              SourceLocation NameLoc) {
1203   assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1204   CXXScopeSpec SS;
1205   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1206   return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1207 }
1208 
1209 ExprResult
1210 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1211                                             IdentifierInfo *Name,
1212                                             SourceLocation NameLoc,
1213                                             bool IsAddressOfOperand) {
1214   DeclarationNameInfo NameInfo(Name, NameLoc);
1215   return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1216                                     NameInfo, IsAddressOfOperand,
1217                                     /*TemplateArgs=*/nullptr);
1218 }
1219 
1220 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1221                                               NamedDecl *Found,
1222                                               SourceLocation NameLoc,
1223                                               const Token &NextToken) {
1224   if (getCurMethodDecl() && SS.isEmpty())
1225     if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1226       return BuildIvarRefExpr(S, NameLoc, Ivar);
1227 
1228   // Reconstruct the lookup result.
1229   LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1230   Result.addDecl(Found);
1231   Result.resolveKind();
1232 
1233   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1234   return BuildDeclarationNameExpr(SS, Result, ADL);
1235 }
1236 
1237 Sema::TemplateNameKindForDiagnostics
1238 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1239   auto *TD = Name.getAsTemplateDecl();
1240   if (!TD)
1241     return TemplateNameKindForDiagnostics::DependentTemplate;
1242   if (isa<ClassTemplateDecl>(TD))
1243     return TemplateNameKindForDiagnostics::ClassTemplate;
1244   if (isa<FunctionTemplateDecl>(TD))
1245     return TemplateNameKindForDiagnostics::FunctionTemplate;
1246   if (isa<VarTemplateDecl>(TD))
1247     return TemplateNameKindForDiagnostics::VarTemplate;
1248   if (isa<TypeAliasTemplateDecl>(TD))
1249     return TemplateNameKindForDiagnostics::AliasTemplate;
1250   if (isa<TemplateTemplateParmDecl>(TD))
1251     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1252   if (isa<ConceptDecl>(TD))
1253     return TemplateNameKindForDiagnostics::Concept;
1254   return TemplateNameKindForDiagnostics::DependentTemplate;
1255 }
1256 
1257 // Determines the context to return to after temporarily entering a
1258 // context.  This depends in an unnecessarily complicated way on the
1259 // exact ordering of callbacks from the parser.
1260 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1261 
1262   // Functions defined inline within classes aren't parsed until we've
1263   // finished parsing the top-level class, so the top-level class is
1264   // the context we'll need to return to.
1265   // A Lambda call operator whose parent is a class must not be treated
1266   // as an inline member function.  A Lambda can be used legally
1267   // either as an in-class member initializer or a default argument.  These
1268   // are parsed once the class has been marked complete and so the containing
1269   // context would be the nested class (when the lambda is defined in one);
1270   // If the class is not complete, then the lambda is being used in an
1271   // ill-formed fashion (such as to specify the width of a bit-field, or
1272   // in an array-bound) - in which case we still want to return the
1273   // lexically containing DC (which could be a nested class).
1274   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1275     DC = DC->getLexicalParent();
1276 
1277     // A function not defined within a class will always return to its
1278     // lexical context.
1279     if (!isa<CXXRecordDecl>(DC))
1280       return DC;
1281 
1282     // A C++ inline method/friend is parsed *after* the topmost class
1283     // it was declared in is fully parsed ("complete");  the topmost
1284     // class is the context we need to return to.
1285     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1286       DC = RD;
1287 
1288     // Return the declaration context of the topmost class the inline method is
1289     // declared in.
1290     return DC;
1291   }
1292 
1293   return DC->getLexicalParent();
1294 }
1295 
1296 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1297   assert(getContainingDC(DC) == CurContext &&
1298       "The next DeclContext should be lexically contained in the current one.");
1299   CurContext = DC;
1300   S->setEntity(DC);
1301 }
1302 
1303 void Sema::PopDeclContext() {
1304   assert(CurContext && "DeclContext imbalance!");
1305 
1306   CurContext = getContainingDC(CurContext);
1307   assert(CurContext && "Popped translation unit!");
1308 }
1309 
1310 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1311                                                                     Decl *D) {
1312   // Unlike PushDeclContext, the context to which we return is not necessarily
1313   // the containing DC of TD, because the new context will be some pre-existing
1314   // TagDecl definition instead of a fresh one.
1315   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1316   CurContext = cast<TagDecl>(D)->getDefinition();
1317   assert(CurContext && "skipping definition of undefined tag");
1318   // Start lookups from the parent of the current context; we don't want to look
1319   // into the pre-existing complete definition.
1320   S->setEntity(CurContext->getLookupParent());
1321   return Result;
1322 }
1323 
1324 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1325   CurContext = static_cast<decltype(CurContext)>(Context);
1326 }
1327 
1328 /// EnterDeclaratorContext - Used when we must lookup names in the context
1329 /// of a declarator's nested name specifier.
1330 ///
1331 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1332   // C++0x [basic.lookup.unqual]p13:
1333   //   A name used in the definition of a static data member of class
1334   //   X (after the qualified-id of the static member) is looked up as
1335   //   if the name was used in a member function of X.
1336   // C++0x [basic.lookup.unqual]p14:
1337   //   If a variable member of a namespace is defined outside of the
1338   //   scope of its namespace then any name used in the definition of
1339   //   the variable member (after the declarator-id) is looked up as
1340   //   if the definition of the variable member occurred in its
1341   //   namespace.
1342   // Both of these imply that we should push a scope whose context
1343   // is the semantic context of the declaration.  We can't use
1344   // PushDeclContext here because that context is not necessarily
1345   // lexically contained in the current context.  Fortunately,
1346   // the containing scope should have the appropriate information.
1347 
1348   assert(!S->getEntity() && "scope already has entity");
1349 
1350 #ifndef NDEBUG
1351   Scope *Ancestor = S->getParent();
1352   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1353   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1354 #endif
1355 
1356   CurContext = DC;
1357   S->setEntity(DC);
1358 }
1359 
1360 void Sema::ExitDeclaratorContext(Scope *S) {
1361   assert(S->getEntity() == CurContext && "Context imbalance!");
1362 
1363   // Switch back to the lexical context.  The safety of this is
1364   // enforced by an assert in EnterDeclaratorContext.
1365   Scope *Ancestor = S->getParent();
1366   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1367   CurContext = Ancestor->getEntity();
1368 
1369   // We don't need to do anything with the scope, which is going to
1370   // disappear.
1371 }
1372 
1373 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1374   // We assume that the caller has already called
1375   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1376   FunctionDecl *FD = D->getAsFunction();
1377   if (!FD)
1378     return;
1379 
1380   // Same implementation as PushDeclContext, but enters the context
1381   // from the lexical parent, rather than the top-level class.
1382   assert(CurContext == FD->getLexicalParent() &&
1383     "The next DeclContext should be lexically contained in the current one.");
1384   CurContext = FD;
1385   S->setEntity(CurContext);
1386 
1387   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1388     ParmVarDecl *Param = FD->getParamDecl(P);
1389     // If the parameter has an identifier, then add it to the scope
1390     if (Param->getIdentifier()) {
1391       S->AddDecl(Param);
1392       IdResolver.AddDecl(Param);
1393     }
1394   }
1395 }
1396 
1397 void Sema::ActOnExitFunctionContext() {
1398   // Same implementation as PopDeclContext, but returns to the lexical parent,
1399   // rather than the top-level class.
1400   assert(CurContext && "DeclContext imbalance!");
1401   CurContext = CurContext->getLexicalParent();
1402   assert(CurContext && "Popped translation unit!");
1403 }
1404 
1405 /// Determine whether we allow overloading of the function
1406 /// PrevDecl with another declaration.
1407 ///
1408 /// This routine determines whether overloading is possible, not
1409 /// whether some new function is actually an overload. It will return
1410 /// true in C++ (where we can always provide overloads) or, as an
1411 /// extension, in C when the previous function is already an
1412 /// overloaded function declaration or has the "overloadable"
1413 /// attribute.
1414 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1415                                        ASTContext &Context,
1416                                        const FunctionDecl *New) {
1417   if (Context.getLangOpts().CPlusPlus)
1418     return true;
1419 
1420   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1421     return true;
1422 
1423   return Previous.getResultKind() == LookupResult::Found &&
1424          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1425           New->hasAttr<OverloadableAttr>());
1426 }
1427 
1428 /// Add this decl to the scope shadowed decl chains.
1429 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1430   // Move up the scope chain until we find the nearest enclosing
1431   // non-transparent context. The declaration will be introduced into this
1432   // scope.
1433   while (S->getEntity() && S->getEntity()->isTransparentContext())
1434     S = S->getParent();
1435 
1436   // Add scoped declarations into their context, so that they can be
1437   // found later. Declarations without a context won't be inserted
1438   // into any context.
1439   if (AddToContext)
1440     CurContext->addDecl(D);
1441 
1442   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1443   // are function-local declarations.
1444   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1445       !D->getDeclContext()->getRedeclContext()->Equals(
1446         D->getLexicalDeclContext()->getRedeclContext()) &&
1447       !D->getLexicalDeclContext()->isFunctionOrMethod())
1448     return;
1449 
1450   // Template instantiations should also not be pushed into scope.
1451   if (isa<FunctionDecl>(D) &&
1452       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1453     return;
1454 
1455   // If this replaces anything in the current scope,
1456   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1457                                IEnd = IdResolver.end();
1458   for (; I != IEnd; ++I) {
1459     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1460       S->RemoveDecl(*I);
1461       IdResolver.RemoveDecl(*I);
1462 
1463       // Should only need to replace one decl.
1464       break;
1465     }
1466   }
1467 
1468   S->AddDecl(D);
1469 
1470   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1471     // Implicitly-generated labels may end up getting generated in an order that
1472     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1473     // the label at the appropriate place in the identifier chain.
1474     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1475       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1476       if (IDC == CurContext) {
1477         if (!S->isDeclScope(*I))
1478           continue;
1479       } else if (IDC->Encloses(CurContext))
1480         break;
1481     }
1482 
1483     IdResolver.InsertDeclAfter(I, D);
1484   } else {
1485     IdResolver.AddDecl(D);
1486   }
1487 }
1488 
1489 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1490                          bool AllowInlineNamespace) {
1491   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1492 }
1493 
1494 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1495   DeclContext *TargetDC = DC->getPrimaryContext();
1496   do {
1497     if (DeclContext *ScopeDC = S->getEntity())
1498       if (ScopeDC->getPrimaryContext() == TargetDC)
1499         return S;
1500   } while ((S = S->getParent()));
1501 
1502   return nullptr;
1503 }
1504 
1505 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1506                                             DeclContext*,
1507                                             ASTContext&);
1508 
1509 /// Filters out lookup results that don't fall within the given scope
1510 /// as determined by isDeclInScope.
1511 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1512                                 bool ConsiderLinkage,
1513                                 bool AllowInlineNamespace) {
1514   LookupResult::Filter F = R.makeFilter();
1515   while (F.hasNext()) {
1516     NamedDecl *D = F.next();
1517 
1518     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1519       continue;
1520 
1521     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1522       continue;
1523 
1524     F.erase();
1525   }
1526 
1527   F.done();
1528 }
1529 
1530 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1531 /// have compatible owning modules.
1532 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1533   // FIXME: The Modules TS is not clear about how friend declarations are
1534   // to be treated. It's not meaningful to have different owning modules for
1535   // linkage in redeclarations of the same entity, so for now allow the
1536   // redeclaration and change the owning modules to match.
1537   if (New->getFriendObjectKind() &&
1538       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1539     New->setLocalOwningModule(Old->getOwningModule());
1540     makeMergedDefinitionVisible(New);
1541     return false;
1542   }
1543 
1544   Module *NewM = New->getOwningModule();
1545   Module *OldM = Old->getOwningModule();
1546 
1547   if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1548     NewM = NewM->Parent;
1549   if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1550     OldM = OldM->Parent;
1551 
1552   if (NewM == OldM)
1553     return false;
1554 
1555   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1556   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1557   if (NewIsModuleInterface || OldIsModuleInterface) {
1558     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1559     //   if a declaration of D [...] appears in the purview of a module, all
1560     //   other such declarations shall appear in the purview of the same module
1561     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1562       << New
1563       << NewIsModuleInterface
1564       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1565       << OldIsModuleInterface
1566       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1567     Diag(Old->getLocation(), diag::note_previous_declaration);
1568     New->setInvalidDecl();
1569     return true;
1570   }
1571 
1572   return false;
1573 }
1574 
1575 static bool isUsingDecl(NamedDecl *D) {
1576   return isa<UsingShadowDecl>(D) ||
1577          isa<UnresolvedUsingTypenameDecl>(D) ||
1578          isa<UnresolvedUsingValueDecl>(D);
1579 }
1580 
1581 /// Removes using shadow declarations from the lookup results.
1582 static void RemoveUsingDecls(LookupResult &R) {
1583   LookupResult::Filter F = R.makeFilter();
1584   while (F.hasNext())
1585     if (isUsingDecl(F.next()))
1586       F.erase();
1587 
1588   F.done();
1589 }
1590 
1591 /// Check for this common pattern:
1592 /// @code
1593 /// class S {
1594 ///   S(const S&); // DO NOT IMPLEMENT
1595 ///   void operator=(const S&); // DO NOT IMPLEMENT
1596 /// };
1597 /// @endcode
1598 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1599   // FIXME: Should check for private access too but access is set after we get
1600   // the decl here.
1601   if (D->doesThisDeclarationHaveABody())
1602     return false;
1603 
1604   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1605     return CD->isCopyConstructor();
1606   return D->isCopyAssignmentOperator();
1607 }
1608 
1609 // We need this to handle
1610 //
1611 // typedef struct {
1612 //   void *foo() { return 0; }
1613 // } A;
1614 //
1615 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1616 // for example. If 'A', foo will have external linkage. If we have '*A',
1617 // foo will have no linkage. Since we can't know until we get to the end
1618 // of the typedef, this function finds out if D might have non-external linkage.
1619 // Callers should verify at the end of the TU if it D has external linkage or
1620 // not.
1621 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1622   const DeclContext *DC = D->getDeclContext();
1623   while (!DC->isTranslationUnit()) {
1624     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1625       if (!RD->hasNameForLinkage())
1626         return true;
1627     }
1628     DC = DC->getParent();
1629   }
1630 
1631   return !D->isExternallyVisible();
1632 }
1633 
1634 // FIXME: This needs to be refactored; some other isInMainFile users want
1635 // these semantics.
1636 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1637   if (S.TUKind != TU_Complete)
1638     return false;
1639   return S.SourceMgr.isInMainFile(Loc);
1640 }
1641 
1642 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1643   assert(D);
1644 
1645   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1646     return false;
1647 
1648   // Ignore all entities declared within templates, and out-of-line definitions
1649   // of members of class templates.
1650   if (D->getDeclContext()->isDependentContext() ||
1651       D->getLexicalDeclContext()->isDependentContext())
1652     return false;
1653 
1654   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1655     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1656       return false;
1657     // A non-out-of-line declaration of a member specialization was implicitly
1658     // instantiated; it's the out-of-line declaration that we're interested in.
1659     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1660         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1661       return false;
1662 
1663     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1664       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1665         return false;
1666     } else {
1667       // 'static inline' functions are defined in headers; don't warn.
1668       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1669         return false;
1670     }
1671 
1672     if (FD->doesThisDeclarationHaveABody() &&
1673         Context.DeclMustBeEmitted(FD))
1674       return false;
1675   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1676     // Constants and utility variables are defined in headers with internal
1677     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1678     // like "inline".)
1679     if (!isMainFileLoc(*this, VD->getLocation()))
1680       return false;
1681 
1682     if (Context.DeclMustBeEmitted(VD))
1683       return false;
1684 
1685     if (VD->isStaticDataMember() &&
1686         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1687       return false;
1688     if (VD->isStaticDataMember() &&
1689         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1690         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1691       return false;
1692 
1693     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1694       return false;
1695   } else {
1696     return false;
1697   }
1698 
1699   // Only warn for unused decls internal to the translation unit.
1700   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1701   // for inline functions defined in the main source file, for instance.
1702   return mightHaveNonExternalLinkage(D);
1703 }
1704 
1705 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1706   if (!D)
1707     return;
1708 
1709   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1710     const FunctionDecl *First = FD->getFirstDecl();
1711     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1712       return; // First should already be in the vector.
1713   }
1714 
1715   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1716     const VarDecl *First = VD->getFirstDecl();
1717     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1718       return; // First should already be in the vector.
1719   }
1720 
1721   if (ShouldWarnIfUnusedFileScopedDecl(D))
1722     UnusedFileScopedDecls.push_back(D);
1723 }
1724 
1725 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1726   if (D->isInvalidDecl())
1727     return false;
1728 
1729   bool Referenced = false;
1730   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1731     // For a decomposition declaration, warn if none of the bindings are
1732     // referenced, instead of if the variable itself is referenced (which
1733     // it is, by the bindings' expressions).
1734     for (auto *BD : DD->bindings()) {
1735       if (BD->isReferenced()) {
1736         Referenced = true;
1737         break;
1738       }
1739     }
1740   } else if (!D->getDeclName()) {
1741     return false;
1742   } else if (D->isReferenced() || D->isUsed()) {
1743     Referenced = true;
1744   }
1745 
1746   if (Referenced || D->hasAttr<UnusedAttr>() ||
1747       D->hasAttr<ObjCPreciseLifetimeAttr>())
1748     return false;
1749 
1750   if (isa<LabelDecl>(D))
1751     return true;
1752 
1753   // Except for labels, we only care about unused decls that are local to
1754   // functions.
1755   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1756   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1757     // For dependent types, the diagnostic is deferred.
1758     WithinFunction =
1759         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1760   if (!WithinFunction)
1761     return false;
1762 
1763   if (isa<TypedefNameDecl>(D))
1764     return true;
1765 
1766   // White-list anything that isn't a local variable.
1767   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1768     return false;
1769 
1770   // Types of valid local variables should be complete, so this should succeed.
1771   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1772 
1773     // White-list anything with an __attribute__((unused)) type.
1774     const auto *Ty = VD->getType().getTypePtr();
1775 
1776     // Only look at the outermost level of typedef.
1777     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1778       if (TT->getDecl()->hasAttr<UnusedAttr>())
1779         return false;
1780     }
1781 
1782     // If we failed to complete the type for some reason, or if the type is
1783     // dependent, don't diagnose the variable.
1784     if (Ty->isIncompleteType() || Ty->isDependentType())
1785       return false;
1786 
1787     // Look at the element type to ensure that the warning behaviour is
1788     // consistent for both scalars and arrays.
1789     Ty = Ty->getBaseElementTypeUnsafe();
1790 
1791     if (const TagType *TT = Ty->getAs<TagType>()) {
1792       const TagDecl *Tag = TT->getDecl();
1793       if (Tag->hasAttr<UnusedAttr>())
1794         return false;
1795 
1796       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1797         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1798           return false;
1799 
1800         if (const Expr *Init = VD->getInit()) {
1801           if (const ExprWithCleanups *Cleanups =
1802                   dyn_cast<ExprWithCleanups>(Init))
1803             Init = Cleanups->getSubExpr();
1804           const CXXConstructExpr *Construct =
1805             dyn_cast<CXXConstructExpr>(Init);
1806           if (Construct && !Construct->isElidable()) {
1807             CXXConstructorDecl *CD = Construct->getConstructor();
1808             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1809                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1810               return false;
1811           }
1812 
1813           // Suppress the warning if we don't know how this is constructed, and
1814           // it could possibly be non-trivial constructor.
1815           if (Init->isTypeDependent())
1816             for (const CXXConstructorDecl *Ctor : RD->ctors())
1817               if (!Ctor->isTrivial())
1818                 return false;
1819         }
1820       }
1821     }
1822 
1823     // TODO: __attribute__((unused)) templates?
1824   }
1825 
1826   return true;
1827 }
1828 
1829 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1830                                      FixItHint &Hint) {
1831   if (isa<LabelDecl>(D)) {
1832     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1833         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1834         true);
1835     if (AfterColon.isInvalid())
1836       return;
1837     Hint = FixItHint::CreateRemoval(
1838         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1839   }
1840 }
1841 
1842 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1843   if (D->getTypeForDecl()->isDependentType())
1844     return;
1845 
1846   for (auto *TmpD : D->decls()) {
1847     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1848       DiagnoseUnusedDecl(T);
1849     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1850       DiagnoseUnusedNestedTypedefs(R);
1851   }
1852 }
1853 
1854 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1855 /// unless they are marked attr(unused).
1856 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1857   if (!ShouldDiagnoseUnusedDecl(D))
1858     return;
1859 
1860   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1861     // typedefs can be referenced later on, so the diagnostics are emitted
1862     // at end-of-translation-unit.
1863     UnusedLocalTypedefNameCandidates.insert(TD);
1864     return;
1865   }
1866 
1867   FixItHint Hint;
1868   GenerateFixForUnusedDecl(D, Context, Hint);
1869 
1870   unsigned DiagID;
1871   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1872     DiagID = diag::warn_unused_exception_param;
1873   else if (isa<LabelDecl>(D))
1874     DiagID = diag::warn_unused_label;
1875   else
1876     DiagID = diag::warn_unused_variable;
1877 
1878   Diag(D->getLocation(), DiagID) << D << Hint;
1879 }
1880 
1881 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1882   // Verify that we have no forward references left.  If so, there was a goto
1883   // or address of a label taken, but no definition of it.  Label fwd
1884   // definitions are indicated with a null substmt which is also not a resolved
1885   // MS inline assembly label name.
1886   bool Diagnose = false;
1887   if (L->isMSAsmLabel())
1888     Diagnose = !L->isResolvedMSAsmLabel();
1889   else
1890     Diagnose = L->getStmt() == nullptr;
1891   if (Diagnose)
1892     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1893 }
1894 
1895 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1896   S->mergeNRVOIntoParent();
1897 
1898   if (S->decl_empty()) return;
1899   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1900          "Scope shouldn't contain decls!");
1901 
1902   for (auto *TmpD : S->decls()) {
1903     assert(TmpD && "This decl didn't get pushed??");
1904 
1905     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1906     NamedDecl *D = cast<NamedDecl>(TmpD);
1907 
1908     // Diagnose unused variables in this scope.
1909     if (!S->hasUnrecoverableErrorOccurred()) {
1910       DiagnoseUnusedDecl(D);
1911       if (const auto *RD = dyn_cast<RecordDecl>(D))
1912         DiagnoseUnusedNestedTypedefs(RD);
1913     }
1914 
1915     if (!D->getDeclName()) continue;
1916 
1917     // If this was a forward reference to a label, verify it was defined.
1918     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1919       CheckPoppedLabel(LD, *this);
1920 
1921     // Remove this name from our lexical scope, and warn on it if we haven't
1922     // already.
1923     IdResolver.RemoveDecl(D);
1924     auto ShadowI = ShadowingDecls.find(D);
1925     if (ShadowI != ShadowingDecls.end()) {
1926       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1927         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1928             << D << FD << FD->getParent();
1929         Diag(FD->getLocation(), diag::note_previous_declaration);
1930       }
1931       ShadowingDecls.erase(ShadowI);
1932     }
1933   }
1934 }
1935 
1936 /// Look for an Objective-C class in the translation unit.
1937 ///
1938 /// \param Id The name of the Objective-C class we're looking for. If
1939 /// typo-correction fixes this name, the Id will be updated
1940 /// to the fixed name.
1941 ///
1942 /// \param IdLoc The location of the name in the translation unit.
1943 ///
1944 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1945 /// if there is no class with the given name.
1946 ///
1947 /// \returns The declaration of the named Objective-C class, or NULL if the
1948 /// class could not be found.
1949 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1950                                               SourceLocation IdLoc,
1951                                               bool DoTypoCorrection) {
1952   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1953   // creation from this context.
1954   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1955 
1956   if (!IDecl && DoTypoCorrection) {
1957     // Perform typo correction at the given location, but only if we
1958     // find an Objective-C class name.
1959     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
1960     if (TypoCorrection C =
1961             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
1962                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
1963       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1964       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1965       Id = IDecl->getIdentifier();
1966     }
1967   }
1968   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1969   // This routine must always return a class definition, if any.
1970   if (Def && Def->getDefinition())
1971       Def = Def->getDefinition();
1972   return Def;
1973 }
1974 
1975 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1976 /// from S, where a non-field would be declared. This routine copes
1977 /// with the difference between C and C++ scoping rules in structs and
1978 /// unions. For example, the following code is well-formed in C but
1979 /// ill-formed in C++:
1980 /// @code
1981 /// struct S6 {
1982 ///   enum { BAR } e;
1983 /// };
1984 ///
1985 /// void test_S6() {
1986 ///   struct S6 a;
1987 ///   a.e = BAR;
1988 /// }
1989 /// @endcode
1990 /// For the declaration of BAR, this routine will return a different
1991 /// scope. The scope S will be the scope of the unnamed enumeration
1992 /// within S6. In C++, this routine will return the scope associated
1993 /// with S6, because the enumeration's scope is a transparent
1994 /// context but structures can contain non-field names. In C, this
1995 /// routine will return the translation unit scope, since the
1996 /// enumeration's scope is a transparent context and structures cannot
1997 /// contain non-field names.
1998 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1999   while (((S->getFlags() & Scope::DeclScope) == 0) ||
2000          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2001          (S->isClassScope() && !getLangOpts().CPlusPlus))
2002     S = S->getParent();
2003   return S;
2004 }
2005 
2006 /// Looks up the declaration of "struct objc_super" and
2007 /// saves it for later use in building builtin declaration of
2008 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
2009 /// pre-existing declaration exists no action takes place.
2010 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
2011                                         IdentifierInfo *II) {
2012   if (!II->isStr("objc_msgSendSuper"))
2013     return;
2014   ASTContext &Context = ThisSema.Context;
2015 
2016   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
2017                       SourceLocation(), Sema::LookupTagName);
2018   ThisSema.LookupName(Result, S);
2019   if (Result.getResultKind() == LookupResult::Found)
2020     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
2021       Context.setObjCSuperType(Context.getTagDeclType(TD));
2022 }
2023 
2024 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2025                                ASTContext::GetBuiltinTypeError Error) {
2026   switch (Error) {
2027   case ASTContext::GE_None:
2028     return "";
2029   case ASTContext::GE_Missing_type:
2030     return BuiltinInfo.getHeaderName(ID);
2031   case ASTContext::GE_Missing_stdio:
2032     return "stdio.h";
2033   case ASTContext::GE_Missing_setjmp:
2034     return "setjmp.h";
2035   case ASTContext::GE_Missing_ucontext:
2036     return "ucontext.h";
2037   }
2038   llvm_unreachable("unhandled error kind");
2039 }
2040 
2041 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2042 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2043 /// if we're creating this built-in in anticipation of redeclaring the
2044 /// built-in.
2045 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2046                                      Scope *S, bool ForRedeclaration,
2047                                      SourceLocation Loc) {
2048   LookupPredefedObjCSuperType(*this, S, II);
2049 
2050   ASTContext::GetBuiltinTypeError Error;
2051   QualType R = Context.GetBuiltinType(ID, Error);
2052   if (Error) {
2053     if (!ForRedeclaration)
2054       return nullptr;
2055 
2056     // If we have a builtin without an associated type we should not emit a
2057     // warning when we were not able to find a type for it.
2058     if (Error == ASTContext::GE_Missing_type)
2059       return nullptr;
2060 
2061     // If we could not find a type for setjmp it is because the jmp_buf type was
2062     // not defined prior to the setjmp declaration.
2063     if (Error == ASTContext::GE_Missing_setjmp) {
2064       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2065           << Context.BuiltinInfo.getName(ID);
2066       return nullptr;
2067     }
2068 
2069     // Generally, we emit a warning that the declaration requires the
2070     // appropriate header.
2071     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2072         << getHeaderName(Context.BuiltinInfo, ID, Error)
2073         << Context.BuiltinInfo.getName(ID);
2074     return nullptr;
2075   }
2076 
2077   if (!ForRedeclaration &&
2078       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2079        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2080     Diag(Loc, diag::ext_implicit_lib_function_decl)
2081         << Context.BuiltinInfo.getName(ID) << R;
2082     if (Context.BuiltinInfo.getHeaderName(ID) &&
2083         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
2084       Diag(Loc, diag::note_include_header_or_declare)
2085           << Context.BuiltinInfo.getHeaderName(ID)
2086           << Context.BuiltinInfo.getName(ID);
2087   }
2088 
2089   if (R.isNull())
2090     return nullptr;
2091 
2092   DeclContext *Parent = Context.getTranslationUnitDecl();
2093   if (getLangOpts().CPlusPlus) {
2094     LinkageSpecDecl *CLinkageDecl =
2095         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
2096                                 LinkageSpecDecl::lang_c, false);
2097     CLinkageDecl->setImplicit();
2098     Parent->addDecl(CLinkageDecl);
2099     Parent = CLinkageDecl;
2100   }
2101 
2102   FunctionDecl *New = FunctionDecl::Create(Context,
2103                                            Parent,
2104                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
2105                                            SC_Extern,
2106                                            false,
2107                                            R->isFunctionProtoType());
2108   New->setImplicit();
2109 
2110   // Create Decl objects for each parameter, adding them to the
2111   // FunctionDecl.
2112   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
2113     SmallVector<ParmVarDecl*, 16> Params;
2114     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2115       ParmVarDecl *parm =
2116           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2117                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2118                               SC_None, nullptr);
2119       parm->setScopeInfo(0, i);
2120       Params.push_back(parm);
2121     }
2122     New->setParams(Params);
2123   }
2124 
2125   AddKnownFunctionAttributes(New);
2126   RegisterLocallyScopedExternCDecl(New, S);
2127 
2128   // TUScope is the translation-unit scope to insert this function into.
2129   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2130   // relate Scopes to DeclContexts, and probably eliminate CurContext
2131   // entirely, but we're not there yet.
2132   DeclContext *SavedContext = CurContext;
2133   CurContext = Parent;
2134   PushOnScopeChains(New, TUScope);
2135   CurContext = SavedContext;
2136   return New;
2137 }
2138 
2139 /// Typedef declarations don't have linkage, but they still denote the same
2140 /// entity if their types are the same.
2141 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2142 /// isSameEntity.
2143 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2144                                                      TypedefNameDecl *Decl,
2145                                                      LookupResult &Previous) {
2146   // This is only interesting when modules are enabled.
2147   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2148     return;
2149 
2150   // Empty sets are uninteresting.
2151   if (Previous.empty())
2152     return;
2153 
2154   LookupResult::Filter Filter = Previous.makeFilter();
2155   while (Filter.hasNext()) {
2156     NamedDecl *Old = Filter.next();
2157 
2158     // Non-hidden declarations are never ignored.
2159     if (S.isVisible(Old))
2160       continue;
2161 
2162     // Declarations of the same entity are not ignored, even if they have
2163     // different linkages.
2164     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2165       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2166                                 Decl->getUnderlyingType()))
2167         continue;
2168 
2169       // If both declarations give a tag declaration a typedef name for linkage
2170       // purposes, then they declare the same entity.
2171       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2172           Decl->getAnonDeclWithTypedefName())
2173         continue;
2174     }
2175 
2176     Filter.erase();
2177   }
2178 
2179   Filter.done();
2180 }
2181 
2182 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2183   QualType OldType;
2184   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2185     OldType = OldTypedef->getUnderlyingType();
2186   else
2187     OldType = Context.getTypeDeclType(Old);
2188   QualType NewType = New->getUnderlyingType();
2189 
2190   if (NewType->isVariablyModifiedType()) {
2191     // Must not redefine a typedef with a variably-modified type.
2192     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2193     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2194       << Kind << NewType;
2195     if (Old->getLocation().isValid())
2196       notePreviousDefinition(Old, New->getLocation());
2197     New->setInvalidDecl();
2198     return true;
2199   }
2200 
2201   if (OldType != NewType &&
2202       !OldType->isDependentType() &&
2203       !NewType->isDependentType() &&
2204       !Context.hasSameType(OldType, NewType)) {
2205     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2206     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2207       << Kind << NewType << OldType;
2208     if (Old->getLocation().isValid())
2209       notePreviousDefinition(Old, New->getLocation());
2210     New->setInvalidDecl();
2211     return true;
2212   }
2213   return false;
2214 }
2215 
2216 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2217 /// same name and scope as a previous declaration 'Old'.  Figure out
2218 /// how to resolve this situation, merging decls or emitting
2219 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2220 ///
2221 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2222                                 LookupResult &OldDecls) {
2223   // If the new decl is known invalid already, don't bother doing any
2224   // merging checks.
2225   if (New->isInvalidDecl()) return;
2226 
2227   // Allow multiple definitions for ObjC built-in typedefs.
2228   // FIXME: Verify the underlying types are equivalent!
2229   if (getLangOpts().ObjC) {
2230     const IdentifierInfo *TypeID = New->getIdentifier();
2231     switch (TypeID->getLength()) {
2232     default: break;
2233     case 2:
2234       {
2235         if (!TypeID->isStr("id"))
2236           break;
2237         QualType T = New->getUnderlyingType();
2238         if (!T->isPointerType())
2239           break;
2240         if (!T->isVoidPointerType()) {
2241           QualType PT = T->castAs<PointerType>()->getPointeeType();
2242           if (!PT->isStructureType())
2243             break;
2244         }
2245         Context.setObjCIdRedefinitionType(T);
2246         // Install the built-in type for 'id', ignoring the current definition.
2247         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2248         return;
2249       }
2250     case 5:
2251       if (!TypeID->isStr("Class"))
2252         break;
2253       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2254       // Install the built-in type for 'Class', ignoring the current definition.
2255       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2256       return;
2257     case 3:
2258       if (!TypeID->isStr("SEL"))
2259         break;
2260       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2261       // Install the built-in type for 'SEL', ignoring the current definition.
2262       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2263       return;
2264     }
2265     // Fall through - the typedef name was not a builtin type.
2266   }
2267 
2268   // Verify the old decl was also a type.
2269   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2270   if (!Old) {
2271     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2272       << New->getDeclName();
2273 
2274     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2275     if (OldD->getLocation().isValid())
2276       notePreviousDefinition(OldD, New->getLocation());
2277 
2278     return New->setInvalidDecl();
2279   }
2280 
2281   // If the old declaration is invalid, just give up here.
2282   if (Old->isInvalidDecl())
2283     return New->setInvalidDecl();
2284 
2285   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2286     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2287     auto *NewTag = New->getAnonDeclWithTypedefName();
2288     NamedDecl *Hidden = nullptr;
2289     if (OldTag && NewTag &&
2290         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2291         !hasVisibleDefinition(OldTag, &Hidden)) {
2292       // There is a definition of this tag, but it is not visible. Use it
2293       // instead of our tag.
2294       New->setTypeForDecl(OldTD->getTypeForDecl());
2295       if (OldTD->isModed())
2296         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2297                                     OldTD->getUnderlyingType());
2298       else
2299         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2300 
2301       // Make the old tag definition visible.
2302       makeMergedDefinitionVisible(Hidden);
2303 
2304       // If this was an unscoped enumeration, yank all of its enumerators
2305       // out of the scope.
2306       if (isa<EnumDecl>(NewTag)) {
2307         Scope *EnumScope = getNonFieldDeclScope(S);
2308         for (auto *D : NewTag->decls()) {
2309           auto *ED = cast<EnumConstantDecl>(D);
2310           assert(EnumScope->isDeclScope(ED));
2311           EnumScope->RemoveDecl(ED);
2312           IdResolver.RemoveDecl(ED);
2313           ED->getLexicalDeclContext()->removeDecl(ED);
2314         }
2315       }
2316     }
2317   }
2318 
2319   // If the typedef types are not identical, reject them in all languages and
2320   // with any extensions enabled.
2321   if (isIncompatibleTypedef(Old, New))
2322     return;
2323 
2324   // The types match.  Link up the redeclaration chain and merge attributes if
2325   // the old declaration was a typedef.
2326   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2327     New->setPreviousDecl(Typedef);
2328     mergeDeclAttributes(New, Old);
2329   }
2330 
2331   if (getLangOpts().MicrosoftExt)
2332     return;
2333 
2334   if (getLangOpts().CPlusPlus) {
2335     // C++ [dcl.typedef]p2:
2336     //   In a given non-class scope, a typedef specifier can be used to
2337     //   redefine the name of any type declared in that scope to refer
2338     //   to the type to which it already refers.
2339     if (!isa<CXXRecordDecl>(CurContext))
2340       return;
2341 
2342     // C++0x [dcl.typedef]p4:
2343     //   In a given class scope, a typedef specifier can be used to redefine
2344     //   any class-name declared in that scope that is not also a typedef-name
2345     //   to refer to the type to which it already refers.
2346     //
2347     // This wording came in via DR424, which was a correction to the
2348     // wording in DR56, which accidentally banned code like:
2349     //
2350     //   struct S {
2351     //     typedef struct A { } A;
2352     //   };
2353     //
2354     // in the C++03 standard. We implement the C++0x semantics, which
2355     // allow the above but disallow
2356     //
2357     //   struct S {
2358     //     typedef int I;
2359     //     typedef int I;
2360     //   };
2361     //
2362     // since that was the intent of DR56.
2363     if (!isa<TypedefNameDecl>(Old))
2364       return;
2365 
2366     Diag(New->getLocation(), diag::err_redefinition)
2367       << New->getDeclName();
2368     notePreviousDefinition(Old, New->getLocation());
2369     return New->setInvalidDecl();
2370   }
2371 
2372   // Modules always permit redefinition of typedefs, as does C11.
2373   if (getLangOpts().Modules || getLangOpts().C11)
2374     return;
2375 
2376   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2377   // is normally mapped to an error, but can be controlled with
2378   // -Wtypedef-redefinition.  If either the original or the redefinition is
2379   // in a system header, don't emit this for compatibility with GCC.
2380   if (getDiagnostics().getSuppressSystemWarnings() &&
2381       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2382       (Old->isImplicit() ||
2383        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2384        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2385     return;
2386 
2387   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2388     << New->getDeclName();
2389   notePreviousDefinition(Old, New->getLocation());
2390 }
2391 
2392 /// DeclhasAttr - returns true if decl Declaration already has the target
2393 /// attribute.
2394 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2395   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2396   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2397   for (const auto *i : D->attrs())
2398     if (i->getKind() == A->getKind()) {
2399       if (Ann) {
2400         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2401           return true;
2402         continue;
2403       }
2404       // FIXME: Don't hardcode this check
2405       if (OA && isa<OwnershipAttr>(i))
2406         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2407       return true;
2408     }
2409 
2410   return false;
2411 }
2412 
2413 static bool isAttributeTargetADefinition(Decl *D) {
2414   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2415     return VD->isThisDeclarationADefinition();
2416   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2417     return TD->isCompleteDefinition() || TD->isBeingDefined();
2418   return true;
2419 }
2420 
2421 /// Merge alignment attributes from \p Old to \p New, taking into account the
2422 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2423 ///
2424 /// \return \c true if any attributes were added to \p New.
2425 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2426   // Look for alignas attributes on Old, and pick out whichever attribute
2427   // specifies the strictest alignment requirement.
2428   AlignedAttr *OldAlignasAttr = nullptr;
2429   AlignedAttr *OldStrictestAlignAttr = nullptr;
2430   unsigned OldAlign = 0;
2431   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2432     // FIXME: We have no way of representing inherited dependent alignments
2433     // in a case like:
2434     //   template<int A, int B> struct alignas(A) X;
2435     //   template<int A, int B> struct alignas(B) X {};
2436     // For now, we just ignore any alignas attributes which are not on the
2437     // definition in such a case.
2438     if (I->isAlignmentDependent())
2439       return false;
2440 
2441     if (I->isAlignas())
2442       OldAlignasAttr = I;
2443 
2444     unsigned Align = I->getAlignment(S.Context);
2445     if (Align > OldAlign) {
2446       OldAlign = Align;
2447       OldStrictestAlignAttr = I;
2448     }
2449   }
2450 
2451   // Look for alignas attributes on New.
2452   AlignedAttr *NewAlignasAttr = nullptr;
2453   unsigned NewAlign = 0;
2454   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2455     if (I->isAlignmentDependent())
2456       return false;
2457 
2458     if (I->isAlignas())
2459       NewAlignasAttr = I;
2460 
2461     unsigned Align = I->getAlignment(S.Context);
2462     if (Align > NewAlign)
2463       NewAlign = Align;
2464   }
2465 
2466   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2467     // Both declarations have 'alignas' attributes. We require them to match.
2468     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2469     // fall short. (If two declarations both have alignas, they must both match
2470     // every definition, and so must match each other if there is a definition.)
2471 
2472     // If either declaration only contains 'alignas(0)' specifiers, then it
2473     // specifies the natural alignment for the type.
2474     if (OldAlign == 0 || NewAlign == 0) {
2475       QualType Ty;
2476       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2477         Ty = VD->getType();
2478       else
2479         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2480 
2481       if (OldAlign == 0)
2482         OldAlign = S.Context.getTypeAlign(Ty);
2483       if (NewAlign == 0)
2484         NewAlign = S.Context.getTypeAlign(Ty);
2485     }
2486 
2487     if (OldAlign != NewAlign) {
2488       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2489         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2490         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2491       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2492     }
2493   }
2494 
2495   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2496     // C++11 [dcl.align]p6:
2497     //   if any declaration of an entity has an alignment-specifier,
2498     //   every defining declaration of that entity shall specify an
2499     //   equivalent alignment.
2500     // C11 6.7.5/7:
2501     //   If the definition of an object does not have an alignment
2502     //   specifier, any other declaration of that object shall also
2503     //   have no alignment specifier.
2504     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2505       << OldAlignasAttr;
2506     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2507       << OldAlignasAttr;
2508   }
2509 
2510   bool AnyAdded = false;
2511 
2512   // Ensure we have an attribute representing the strictest alignment.
2513   if (OldAlign > NewAlign) {
2514     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2515     Clone->setInherited(true);
2516     New->addAttr(Clone);
2517     AnyAdded = true;
2518   }
2519 
2520   // Ensure we have an alignas attribute if the old declaration had one.
2521   if (OldAlignasAttr && !NewAlignasAttr &&
2522       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2523     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2524     Clone->setInherited(true);
2525     New->addAttr(Clone);
2526     AnyAdded = true;
2527   }
2528 
2529   return AnyAdded;
2530 }
2531 
2532 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2533                                const InheritableAttr *Attr,
2534                                Sema::AvailabilityMergeKind AMK) {
2535   // This function copies an attribute Attr from a previous declaration to the
2536   // new declaration D if the new declaration doesn't itself have that attribute
2537   // yet or if that attribute allows duplicates.
2538   // If you're adding a new attribute that requires logic different from
2539   // "use explicit attribute on decl if present, else use attribute from
2540   // previous decl", for example if the attribute needs to be consistent
2541   // between redeclarations, you need to call a custom merge function here.
2542   InheritableAttr *NewAttr = nullptr;
2543   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2544     NewAttr = S.mergeAvailabilityAttr(
2545         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2546         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2547         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2548         AA->getPriority());
2549   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2550     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2551   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2552     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2553   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2554     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2555   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2556     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2557   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2558     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2559                                 FA->getFirstArg());
2560   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2561     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2562   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2563     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2564   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2565     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2566                                        IA->getInheritanceModel());
2567   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2568     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2569                                       &S.Context.Idents.get(AA->getSpelling()));
2570   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2571            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2572             isa<CUDAGlobalAttr>(Attr))) {
2573     // CUDA target attributes are part of function signature for
2574     // overloading purposes and must not be merged.
2575     return false;
2576   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2577     NewAttr = S.mergeMinSizeAttr(D, *MA);
2578   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2579     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2580   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2581     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2582   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2583     NewAttr = S.mergeCommonAttr(D, *CommonA);
2584   else if (isa<AlignedAttr>(Attr))
2585     // AlignedAttrs are handled separately, because we need to handle all
2586     // such attributes on a declaration at the same time.
2587     NewAttr = nullptr;
2588   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2589            (AMK == Sema::AMK_Override ||
2590             AMK == Sema::AMK_ProtocolImplementation))
2591     NewAttr = nullptr;
2592   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2593     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid());
2594   else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
2595     NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
2596   else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
2597     NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
2598   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2599     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2600 
2601   if (NewAttr) {
2602     NewAttr->setInherited(true);
2603     D->addAttr(NewAttr);
2604     if (isa<MSInheritanceAttr>(NewAttr))
2605       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2606     return true;
2607   }
2608 
2609   return false;
2610 }
2611 
2612 static const NamedDecl *getDefinition(const Decl *D) {
2613   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2614     return TD->getDefinition();
2615   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2616     const VarDecl *Def = VD->getDefinition();
2617     if (Def)
2618       return Def;
2619     return VD->getActingDefinition();
2620   }
2621   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2622     return FD->getDefinition();
2623   return nullptr;
2624 }
2625 
2626 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2627   for (const auto *Attribute : D->attrs())
2628     if (Attribute->getKind() == Kind)
2629       return true;
2630   return false;
2631 }
2632 
2633 /// checkNewAttributesAfterDef - If we already have a definition, check that
2634 /// there are no new attributes in this declaration.
2635 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2636   if (!New->hasAttrs())
2637     return;
2638 
2639   const NamedDecl *Def = getDefinition(Old);
2640   if (!Def || Def == New)
2641     return;
2642 
2643   AttrVec &NewAttributes = New->getAttrs();
2644   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2645     const Attr *NewAttribute = NewAttributes[I];
2646 
2647     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2648       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2649         Sema::SkipBodyInfo SkipBody;
2650         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2651 
2652         // If we're skipping this definition, drop the "alias" attribute.
2653         if (SkipBody.ShouldSkip) {
2654           NewAttributes.erase(NewAttributes.begin() + I);
2655           --E;
2656           continue;
2657         }
2658       } else {
2659         VarDecl *VD = cast<VarDecl>(New);
2660         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2661                                 VarDecl::TentativeDefinition
2662                             ? diag::err_alias_after_tentative
2663                             : diag::err_redefinition;
2664         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2665         if (Diag == diag::err_redefinition)
2666           S.notePreviousDefinition(Def, VD->getLocation());
2667         else
2668           S.Diag(Def->getLocation(), diag::note_previous_definition);
2669         VD->setInvalidDecl();
2670       }
2671       ++I;
2672       continue;
2673     }
2674 
2675     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2676       // Tentative definitions are only interesting for the alias check above.
2677       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2678         ++I;
2679         continue;
2680       }
2681     }
2682 
2683     if (hasAttribute(Def, NewAttribute->getKind())) {
2684       ++I;
2685       continue; // regular attr merging will take care of validating this.
2686     }
2687 
2688     if (isa<C11NoReturnAttr>(NewAttribute)) {
2689       // C's _Noreturn is allowed to be added to a function after it is defined.
2690       ++I;
2691       continue;
2692     } else if (isa<UuidAttr>(NewAttribute)) {
2693       // msvc will allow a subsequent definition to add an uuid to a class
2694       ++I;
2695       continue;
2696     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2697       if (AA->isAlignas()) {
2698         // C++11 [dcl.align]p6:
2699         //   if any declaration of an entity has an alignment-specifier,
2700         //   every defining declaration of that entity shall specify an
2701         //   equivalent alignment.
2702         // C11 6.7.5/7:
2703         //   If the definition of an object does not have an alignment
2704         //   specifier, any other declaration of that object shall also
2705         //   have no alignment specifier.
2706         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2707           << AA;
2708         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2709           << AA;
2710         NewAttributes.erase(NewAttributes.begin() + I);
2711         --E;
2712         continue;
2713       }
2714     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2715                cast<VarDecl>(New)->isInline() &&
2716                !cast<VarDecl>(New)->isInlineSpecified()) {
2717       // Don't warn about applying selectany to implicitly inline variables.
2718       // Older compilers and language modes would require the use of selectany
2719       // to make such variables inline, and it would have no effect if we
2720       // honored it.
2721       ++I;
2722       continue;
2723     }
2724 
2725     S.Diag(NewAttribute->getLocation(),
2726            diag::warn_attribute_precede_definition);
2727     S.Diag(Def->getLocation(), diag::note_previous_definition);
2728     NewAttributes.erase(NewAttributes.begin() + I);
2729     --E;
2730   }
2731 }
2732 
2733 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2734                                      const ConstInitAttr *CIAttr,
2735                                      bool AttrBeforeInit) {
2736   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2737 
2738   // Figure out a good way to write this specifier on the old declaration.
2739   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2740   // enough of the attribute list spelling information to extract that without
2741   // heroics.
2742   std::string SuitableSpelling;
2743   if (S.getLangOpts().CPlusPlus2a)
2744     SuitableSpelling = std::string(
2745         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2746   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2747     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2748         InsertLoc, {tok::l_square, tok::l_square,
2749                     S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2750                     S.PP.getIdentifierInfo("require_constant_initialization"),
2751                     tok::r_square, tok::r_square}));
2752   if (SuitableSpelling.empty())
2753     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2754         InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2755                     S.PP.getIdentifierInfo("require_constant_initialization"),
2756                     tok::r_paren, tok::r_paren}));
2757   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus2a)
2758     SuitableSpelling = "constinit";
2759   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2760     SuitableSpelling = "[[clang::require_constant_initialization]]";
2761   if (SuitableSpelling.empty())
2762     SuitableSpelling = "__attribute__((require_constant_initialization))";
2763   SuitableSpelling += " ";
2764 
2765   if (AttrBeforeInit) {
2766     // extern constinit int a;
2767     // int a = 0; // error (missing 'constinit'), accepted as extension
2768     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
2769     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2770         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2771     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2772   } else {
2773     // int a = 0;
2774     // constinit extern int a; // error (missing 'constinit')
2775     S.Diag(CIAttr->getLocation(),
2776            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2777                                  : diag::warn_require_const_init_added_too_late)
2778         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2779     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2780         << CIAttr->isConstinit()
2781         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2782   }
2783 }
2784 
2785 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2786 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2787                                AvailabilityMergeKind AMK) {
2788   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2789     UsedAttr *NewAttr = OldAttr->clone(Context);
2790     NewAttr->setInherited(true);
2791     New->addAttr(NewAttr);
2792   }
2793 
2794   if (!Old->hasAttrs() && !New->hasAttrs())
2795     return;
2796 
2797   // [dcl.constinit]p1:
2798   //   If the [constinit] specifier is applied to any declaration of a
2799   //   variable, it shall be applied to the initializing declaration.
2800   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2801   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2802   if (bool(OldConstInit) != bool(NewConstInit)) {
2803     const auto *OldVD = cast<VarDecl>(Old);
2804     auto *NewVD = cast<VarDecl>(New);
2805 
2806     // Find the initializing declaration. Note that we might not have linked
2807     // the new declaration into the redeclaration chain yet.
2808     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2809     if (!InitDecl &&
2810         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2811       InitDecl = NewVD;
2812 
2813     if (InitDecl == NewVD) {
2814       // This is the initializing declaration. If it would inherit 'constinit',
2815       // that's ill-formed. (Note that we do not apply this to the attribute
2816       // form).
2817       if (OldConstInit && OldConstInit->isConstinit())
2818         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2819                                  /*AttrBeforeInit=*/true);
2820     } else if (NewConstInit) {
2821       // This is the first time we've been told that this declaration should
2822       // have a constant initializer. If we already saw the initializing
2823       // declaration, this is too late.
2824       if (InitDecl && InitDecl != NewVD) {
2825         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2826                                  /*AttrBeforeInit=*/false);
2827         NewVD->dropAttr<ConstInitAttr>();
2828       }
2829     }
2830   }
2831 
2832   // Attributes declared post-definition are currently ignored.
2833   checkNewAttributesAfterDef(*this, New, Old);
2834 
2835   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2836     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2837       if (!OldA->isEquivalent(NewA)) {
2838         // This redeclaration changes __asm__ label.
2839         Diag(New->getLocation(), diag::err_different_asm_label);
2840         Diag(OldA->getLocation(), diag::note_previous_declaration);
2841       }
2842     } else if (Old->isUsed()) {
2843       // This redeclaration adds an __asm__ label to a declaration that has
2844       // already been ODR-used.
2845       Diag(New->getLocation(), diag::err_late_asm_label_name)
2846         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2847     }
2848   }
2849 
2850   // Re-declaration cannot add abi_tag's.
2851   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2852     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2853       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2854         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2855                       NewTag) == OldAbiTagAttr->tags_end()) {
2856           Diag(NewAbiTagAttr->getLocation(),
2857                diag::err_new_abi_tag_on_redeclaration)
2858               << NewTag;
2859           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2860         }
2861       }
2862     } else {
2863       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2864       Diag(Old->getLocation(), diag::note_previous_declaration);
2865     }
2866   }
2867 
2868   // This redeclaration adds a section attribute.
2869   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2870     if (auto *VD = dyn_cast<VarDecl>(New)) {
2871       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2872         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2873         Diag(Old->getLocation(), diag::note_previous_declaration);
2874       }
2875     }
2876   }
2877 
2878   // Redeclaration adds code-seg attribute.
2879   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2880   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2881       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2882     Diag(New->getLocation(), diag::warn_mismatched_section)
2883          << 0 /*codeseg*/;
2884     Diag(Old->getLocation(), diag::note_previous_declaration);
2885   }
2886 
2887   if (!Old->hasAttrs())
2888     return;
2889 
2890   bool foundAny = New->hasAttrs();
2891 
2892   // Ensure that any moving of objects within the allocated map is done before
2893   // we process them.
2894   if (!foundAny) New->setAttrs(AttrVec());
2895 
2896   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2897     // Ignore deprecated/unavailable/availability attributes if requested.
2898     AvailabilityMergeKind LocalAMK = AMK_None;
2899     if (isa<DeprecatedAttr>(I) ||
2900         isa<UnavailableAttr>(I) ||
2901         isa<AvailabilityAttr>(I)) {
2902       switch (AMK) {
2903       case AMK_None:
2904         continue;
2905 
2906       case AMK_Redeclaration:
2907       case AMK_Override:
2908       case AMK_ProtocolImplementation:
2909         LocalAMK = AMK;
2910         break;
2911       }
2912     }
2913 
2914     // Already handled.
2915     if (isa<UsedAttr>(I))
2916       continue;
2917 
2918     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2919       foundAny = true;
2920   }
2921 
2922   if (mergeAlignedAttrs(*this, New, Old))
2923     foundAny = true;
2924 
2925   if (!foundAny) New->dropAttrs();
2926 }
2927 
2928 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2929 /// to the new one.
2930 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2931                                      const ParmVarDecl *oldDecl,
2932                                      Sema &S) {
2933   // C++11 [dcl.attr.depend]p2:
2934   //   The first declaration of a function shall specify the
2935   //   carries_dependency attribute for its declarator-id if any declaration
2936   //   of the function specifies the carries_dependency attribute.
2937   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2938   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2939     S.Diag(CDA->getLocation(),
2940            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2941     // Find the first declaration of the parameter.
2942     // FIXME: Should we build redeclaration chains for function parameters?
2943     const FunctionDecl *FirstFD =
2944       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2945     const ParmVarDecl *FirstVD =
2946       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2947     S.Diag(FirstVD->getLocation(),
2948            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2949   }
2950 
2951   if (!oldDecl->hasAttrs())
2952     return;
2953 
2954   bool foundAny = newDecl->hasAttrs();
2955 
2956   // Ensure that any moving of objects within the allocated map is
2957   // done before we process them.
2958   if (!foundAny) newDecl->setAttrs(AttrVec());
2959 
2960   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2961     if (!DeclHasAttr(newDecl, I)) {
2962       InheritableAttr *newAttr =
2963         cast<InheritableParamAttr>(I->clone(S.Context));
2964       newAttr->setInherited(true);
2965       newDecl->addAttr(newAttr);
2966       foundAny = true;
2967     }
2968   }
2969 
2970   if (!foundAny) newDecl->dropAttrs();
2971 }
2972 
2973 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2974                                 const ParmVarDecl *OldParam,
2975                                 Sema &S) {
2976   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2977     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2978       if (*Oldnullability != *Newnullability) {
2979         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2980           << DiagNullabilityKind(
2981                *Newnullability,
2982                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2983                 != 0))
2984           << DiagNullabilityKind(
2985                *Oldnullability,
2986                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2987                 != 0));
2988         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2989       }
2990     } else {
2991       QualType NewT = NewParam->getType();
2992       NewT = S.Context.getAttributedType(
2993                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2994                          NewT, NewT);
2995       NewParam->setType(NewT);
2996     }
2997   }
2998 }
2999 
3000 namespace {
3001 
3002 /// Used in MergeFunctionDecl to keep track of function parameters in
3003 /// C.
3004 struct GNUCompatibleParamWarning {
3005   ParmVarDecl *OldParm;
3006   ParmVarDecl *NewParm;
3007   QualType PromotedType;
3008 };
3009 
3010 } // end anonymous namespace
3011 
3012 // Determine whether the previous declaration was a definition, implicit
3013 // declaration, or a declaration.
3014 template <typename T>
3015 static std::pair<diag::kind, SourceLocation>
3016 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3017   diag::kind PrevDiag;
3018   SourceLocation OldLocation = Old->getLocation();
3019   if (Old->isThisDeclarationADefinition())
3020     PrevDiag = diag::note_previous_definition;
3021   else if (Old->isImplicit()) {
3022     PrevDiag = diag::note_previous_implicit_declaration;
3023     if (OldLocation.isInvalid())
3024       OldLocation = New->getLocation();
3025   } else
3026     PrevDiag = diag::note_previous_declaration;
3027   return std::make_pair(PrevDiag, OldLocation);
3028 }
3029 
3030 /// canRedefineFunction - checks if a function can be redefined. Currently,
3031 /// only extern inline functions can be redefined, and even then only in
3032 /// GNU89 mode.
3033 static bool canRedefineFunction(const FunctionDecl *FD,
3034                                 const LangOptions& LangOpts) {
3035   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3036           !LangOpts.CPlusPlus &&
3037           FD->isInlineSpecified() &&
3038           FD->getStorageClass() == SC_Extern);
3039 }
3040 
3041 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3042   const AttributedType *AT = T->getAs<AttributedType>();
3043   while (AT && !AT->isCallingConv())
3044     AT = AT->getModifiedType()->getAs<AttributedType>();
3045   return AT;
3046 }
3047 
3048 template <typename T>
3049 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3050   const DeclContext *DC = Old->getDeclContext();
3051   if (DC->isRecord())
3052     return false;
3053 
3054   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3055   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3056     return true;
3057   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3058     return true;
3059   return false;
3060 }
3061 
3062 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3063 static bool isExternC(VarTemplateDecl *) { return false; }
3064 
3065 /// Check whether a redeclaration of an entity introduced by a
3066 /// using-declaration is valid, given that we know it's not an overload
3067 /// (nor a hidden tag declaration).
3068 template<typename ExpectedDecl>
3069 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3070                                    ExpectedDecl *New) {
3071   // C++11 [basic.scope.declarative]p4:
3072   //   Given a set of declarations in a single declarative region, each of
3073   //   which specifies the same unqualified name,
3074   //   -- they shall all refer to the same entity, or all refer to functions
3075   //      and function templates; or
3076   //   -- exactly one declaration shall declare a class name or enumeration
3077   //      name that is not a typedef name and the other declarations shall all
3078   //      refer to the same variable or enumerator, or all refer to functions
3079   //      and function templates; in this case the class name or enumeration
3080   //      name is hidden (3.3.10).
3081 
3082   // C++11 [namespace.udecl]p14:
3083   //   If a function declaration in namespace scope or block scope has the
3084   //   same name and the same parameter-type-list as a function introduced
3085   //   by a using-declaration, and the declarations do not declare the same
3086   //   function, the program is ill-formed.
3087 
3088   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3089   if (Old &&
3090       !Old->getDeclContext()->getRedeclContext()->Equals(
3091           New->getDeclContext()->getRedeclContext()) &&
3092       !(isExternC(Old) && isExternC(New)))
3093     Old = nullptr;
3094 
3095   if (!Old) {
3096     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3097     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3098     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
3099     return true;
3100   }
3101   return false;
3102 }
3103 
3104 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3105                                             const FunctionDecl *B) {
3106   assert(A->getNumParams() == B->getNumParams());
3107 
3108   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3109     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3110     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3111     if (AttrA == AttrB)
3112       return true;
3113     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3114            AttrA->isDynamic() == AttrB->isDynamic();
3115   };
3116 
3117   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3118 }
3119 
3120 /// If necessary, adjust the semantic declaration context for a qualified
3121 /// declaration to name the correct inline namespace within the qualifier.
3122 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3123                                                DeclaratorDecl *OldD) {
3124   // The only case where we need to update the DeclContext is when
3125   // redeclaration lookup for a qualified name finds a declaration
3126   // in an inline namespace within the context named by the qualifier:
3127   //
3128   //   inline namespace N { int f(); }
3129   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3130   //
3131   // For unqualified declarations, the semantic context *can* change
3132   // along the redeclaration chain (for local extern declarations,
3133   // extern "C" declarations, and friend declarations in particular).
3134   if (!NewD->getQualifier())
3135     return;
3136 
3137   // NewD is probably already in the right context.
3138   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3139   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3140   if (NamedDC->Equals(SemaDC))
3141     return;
3142 
3143   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3144           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3145          "unexpected context for redeclaration");
3146 
3147   auto *LexDC = NewD->getLexicalDeclContext();
3148   auto FixSemaDC = [=](NamedDecl *D) {
3149     if (!D)
3150       return;
3151     D->setDeclContext(SemaDC);
3152     D->setLexicalDeclContext(LexDC);
3153   };
3154 
3155   FixSemaDC(NewD);
3156   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3157     FixSemaDC(FD->getDescribedFunctionTemplate());
3158   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3159     FixSemaDC(VD->getDescribedVarTemplate());
3160 }
3161 
3162 /// MergeFunctionDecl - We just parsed a function 'New' from
3163 /// declarator D which has the same name and scope as a previous
3164 /// declaration 'Old'.  Figure out how to resolve this situation,
3165 /// merging decls or emitting diagnostics as appropriate.
3166 ///
3167 /// In C++, New and Old must be declarations that are not
3168 /// overloaded. Use IsOverload to determine whether New and Old are
3169 /// overloaded, and to select the Old declaration that New should be
3170 /// merged with.
3171 ///
3172 /// Returns true if there was an error, false otherwise.
3173 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3174                              Scope *S, bool MergeTypeWithOld) {
3175   // Verify the old decl was also a function.
3176   FunctionDecl *Old = OldD->getAsFunction();
3177   if (!Old) {
3178     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3179       if (New->getFriendObjectKind()) {
3180         Diag(New->getLocation(), diag::err_using_decl_friend);
3181         Diag(Shadow->getTargetDecl()->getLocation(),
3182              diag::note_using_decl_target);
3183         Diag(Shadow->getUsingDecl()->getLocation(),
3184              diag::note_using_decl) << 0;
3185         return true;
3186       }
3187 
3188       // Check whether the two declarations might declare the same function.
3189       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3190         return true;
3191       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3192     } else {
3193       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3194         << New->getDeclName();
3195       notePreviousDefinition(OldD, New->getLocation());
3196       return true;
3197     }
3198   }
3199 
3200   // If the old declaration is invalid, just give up here.
3201   if (Old->isInvalidDecl())
3202     return true;
3203 
3204   // Disallow redeclaration of some builtins.
3205   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3206     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3207     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3208         << Old << Old->getType();
3209     return true;
3210   }
3211 
3212   diag::kind PrevDiag;
3213   SourceLocation OldLocation;
3214   std::tie(PrevDiag, OldLocation) =
3215       getNoteDiagForInvalidRedeclaration(Old, New);
3216 
3217   // Don't complain about this if we're in GNU89 mode and the old function
3218   // is an extern inline function.
3219   // Don't complain about specializations. They are not supposed to have
3220   // storage classes.
3221   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3222       New->getStorageClass() == SC_Static &&
3223       Old->hasExternalFormalLinkage() &&
3224       !New->getTemplateSpecializationInfo() &&
3225       !canRedefineFunction(Old, getLangOpts())) {
3226     if (getLangOpts().MicrosoftExt) {
3227       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3228       Diag(OldLocation, PrevDiag);
3229     } else {
3230       Diag(New->getLocation(), diag::err_static_non_static) << New;
3231       Diag(OldLocation, PrevDiag);
3232       return true;
3233     }
3234   }
3235 
3236   if (New->hasAttr<InternalLinkageAttr>() &&
3237       !Old->hasAttr<InternalLinkageAttr>()) {
3238     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3239         << New->getDeclName();
3240     notePreviousDefinition(Old, New->getLocation());
3241     New->dropAttr<InternalLinkageAttr>();
3242   }
3243 
3244   if (CheckRedeclarationModuleOwnership(New, Old))
3245     return true;
3246 
3247   if (!getLangOpts().CPlusPlus) {
3248     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3249     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3250       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3251         << New << OldOvl;
3252 
3253       // Try our best to find a decl that actually has the overloadable
3254       // attribute for the note. In most cases (e.g. programs with only one
3255       // broken declaration/definition), this won't matter.
3256       //
3257       // FIXME: We could do this if we juggled some extra state in
3258       // OverloadableAttr, rather than just removing it.
3259       const Decl *DiagOld = Old;
3260       if (OldOvl) {
3261         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3262           const auto *A = D->getAttr<OverloadableAttr>();
3263           return A && !A->isImplicit();
3264         });
3265         // If we've implicitly added *all* of the overloadable attrs to this
3266         // chain, emitting a "previous redecl" note is pointless.
3267         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3268       }
3269 
3270       if (DiagOld)
3271         Diag(DiagOld->getLocation(),
3272              diag::note_attribute_overloadable_prev_overload)
3273           << OldOvl;
3274 
3275       if (OldOvl)
3276         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3277       else
3278         New->dropAttr<OverloadableAttr>();
3279     }
3280   }
3281 
3282   // If a function is first declared with a calling convention, but is later
3283   // declared or defined without one, all following decls assume the calling
3284   // convention of the first.
3285   //
3286   // It's OK if a function is first declared without a calling convention,
3287   // but is later declared or defined with the default calling convention.
3288   //
3289   // To test if either decl has an explicit calling convention, we look for
3290   // AttributedType sugar nodes on the type as written.  If they are missing or
3291   // were canonicalized away, we assume the calling convention was implicit.
3292   //
3293   // Note also that we DO NOT return at this point, because we still have
3294   // other tests to run.
3295   QualType OldQType = Context.getCanonicalType(Old->getType());
3296   QualType NewQType = Context.getCanonicalType(New->getType());
3297   const FunctionType *OldType = cast<FunctionType>(OldQType);
3298   const FunctionType *NewType = cast<FunctionType>(NewQType);
3299   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3300   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3301   bool RequiresAdjustment = false;
3302 
3303   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3304     FunctionDecl *First = Old->getFirstDecl();
3305     const FunctionType *FT =
3306         First->getType().getCanonicalType()->castAs<FunctionType>();
3307     FunctionType::ExtInfo FI = FT->getExtInfo();
3308     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3309     if (!NewCCExplicit) {
3310       // Inherit the CC from the previous declaration if it was specified
3311       // there but not here.
3312       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3313       RequiresAdjustment = true;
3314     } else if (New->getBuiltinID()) {
3315       // Calling Conventions on a Builtin aren't really useful and setting a
3316       // default calling convention and cdecl'ing some builtin redeclarations is
3317       // common, so warn and ignore the calling convention on the redeclaration.
3318       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3319           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3320           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3321       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3322       RequiresAdjustment = true;
3323     } else {
3324       // Calling conventions aren't compatible, so complain.
3325       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3326       Diag(New->getLocation(), diag::err_cconv_change)
3327         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3328         << !FirstCCExplicit
3329         << (!FirstCCExplicit ? "" :
3330             FunctionType::getNameForCallConv(FI.getCC()));
3331 
3332       // Put the note on the first decl, since it is the one that matters.
3333       Diag(First->getLocation(), diag::note_previous_declaration);
3334       return true;
3335     }
3336   }
3337 
3338   // FIXME: diagnose the other way around?
3339   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3340     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3341     RequiresAdjustment = true;
3342   }
3343 
3344   // Merge regparm attribute.
3345   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3346       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3347     if (NewTypeInfo.getHasRegParm()) {
3348       Diag(New->getLocation(), diag::err_regparm_mismatch)
3349         << NewType->getRegParmType()
3350         << OldType->getRegParmType();
3351       Diag(OldLocation, diag::note_previous_declaration);
3352       return true;
3353     }
3354 
3355     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3356     RequiresAdjustment = true;
3357   }
3358 
3359   // Merge ns_returns_retained attribute.
3360   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3361     if (NewTypeInfo.getProducesResult()) {
3362       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3363           << "'ns_returns_retained'";
3364       Diag(OldLocation, diag::note_previous_declaration);
3365       return true;
3366     }
3367 
3368     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3369     RequiresAdjustment = true;
3370   }
3371 
3372   if (OldTypeInfo.getNoCallerSavedRegs() !=
3373       NewTypeInfo.getNoCallerSavedRegs()) {
3374     if (NewTypeInfo.getNoCallerSavedRegs()) {
3375       AnyX86NoCallerSavedRegistersAttr *Attr =
3376         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3377       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3378       Diag(OldLocation, diag::note_previous_declaration);
3379       return true;
3380     }
3381 
3382     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3383     RequiresAdjustment = true;
3384   }
3385 
3386   if (RequiresAdjustment) {
3387     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3388     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3389     New->setType(QualType(AdjustedType, 0));
3390     NewQType = Context.getCanonicalType(New->getType());
3391   }
3392 
3393   // If this redeclaration makes the function inline, we may need to add it to
3394   // UndefinedButUsed.
3395   if (!Old->isInlined() && New->isInlined() &&
3396       !New->hasAttr<GNUInlineAttr>() &&
3397       !getLangOpts().GNUInline &&
3398       Old->isUsed(false) &&
3399       !Old->isDefined() && !New->isThisDeclarationADefinition())
3400     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3401                                            SourceLocation()));
3402 
3403   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3404   // about it.
3405   if (New->hasAttr<GNUInlineAttr>() &&
3406       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3407     UndefinedButUsed.erase(Old->getCanonicalDecl());
3408   }
3409 
3410   // If pass_object_size params don't match up perfectly, this isn't a valid
3411   // redeclaration.
3412   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3413       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3414     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3415         << New->getDeclName();
3416     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3417     return true;
3418   }
3419 
3420   if (getLangOpts().CPlusPlus) {
3421     // C++1z [over.load]p2
3422     //   Certain function declarations cannot be overloaded:
3423     //     -- Function declarations that differ only in the return type,
3424     //        the exception specification, or both cannot be overloaded.
3425 
3426     // Check the exception specifications match. This may recompute the type of
3427     // both Old and New if it resolved exception specifications, so grab the
3428     // types again after this. Because this updates the type, we do this before
3429     // any of the other checks below, which may update the "de facto" NewQType
3430     // but do not necessarily update the type of New.
3431     if (CheckEquivalentExceptionSpec(Old, New))
3432       return true;
3433     OldQType = Context.getCanonicalType(Old->getType());
3434     NewQType = Context.getCanonicalType(New->getType());
3435 
3436     // Go back to the type source info to compare the declared return types,
3437     // per C++1y [dcl.type.auto]p13:
3438     //   Redeclarations or specializations of a function or function template
3439     //   with a declared return type that uses a placeholder type shall also
3440     //   use that placeholder, not a deduced type.
3441     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3442     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3443     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3444         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3445                                        OldDeclaredReturnType)) {
3446       QualType ResQT;
3447       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3448           OldDeclaredReturnType->isObjCObjectPointerType())
3449         // FIXME: This does the wrong thing for a deduced return type.
3450         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3451       if (ResQT.isNull()) {
3452         if (New->isCXXClassMember() && New->isOutOfLine())
3453           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3454               << New << New->getReturnTypeSourceRange();
3455         else
3456           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3457               << New->getReturnTypeSourceRange();
3458         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3459                                     << Old->getReturnTypeSourceRange();
3460         return true;
3461       }
3462       else
3463         NewQType = ResQT;
3464     }
3465 
3466     QualType OldReturnType = OldType->getReturnType();
3467     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3468     if (OldReturnType != NewReturnType) {
3469       // If this function has a deduced return type and has already been
3470       // defined, copy the deduced value from the old declaration.
3471       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3472       if (OldAT && OldAT->isDeduced()) {
3473         New->setType(
3474             SubstAutoType(New->getType(),
3475                           OldAT->isDependentType() ? Context.DependentTy
3476                                                    : OldAT->getDeducedType()));
3477         NewQType = Context.getCanonicalType(
3478             SubstAutoType(NewQType,
3479                           OldAT->isDependentType() ? Context.DependentTy
3480                                                    : OldAT->getDeducedType()));
3481       }
3482     }
3483 
3484     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3485     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3486     if (OldMethod && NewMethod) {
3487       // Preserve triviality.
3488       NewMethod->setTrivial(OldMethod->isTrivial());
3489 
3490       // MSVC allows explicit template specialization at class scope:
3491       // 2 CXXMethodDecls referring to the same function will be injected.
3492       // We don't want a redeclaration error.
3493       bool IsClassScopeExplicitSpecialization =
3494                               OldMethod->isFunctionTemplateSpecialization() &&
3495                               NewMethod->isFunctionTemplateSpecialization();
3496       bool isFriend = NewMethod->getFriendObjectKind();
3497 
3498       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3499           !IsClassScopeExplicitSpecialization) {
3500         //    -- Member function declarations with the same name and the
3501         //       same parameter types cannot be overloaded if any of them
3502         //       is a static member function declaration.
3503         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3504           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3505           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3506           return true;
3507         }
3508 
3509         // C++ [class.mem]p1:
3510         //   [...] A member shall not be declared twice in the
3511         //   member-specification, except that a nested class or member
3512         //   class template can be declared and then later defined.
3513         if (!inTemplateInstantiation()) {
3514           unsigned NewDiag;
3515           if (isa<CXXConstructorDecl>(OldMethod))
3516             NewDiag = diag::err_constructor_redeclared;
3517           else if (isa<CXXDestructorDecl>(NewMethod))
3518             NewDiag = diag::err_destructor_redeclared;
3519           else if (isa<CXXConversionDecl>(NewMethod))
3520             NewDiag = diag::err_conv_function_redeclared;
3521           else
3522             NewDiag = diag::err_member_redeclared;
3523 
3524           Diag(New->getLocation(), NewDiag);
3525         } else {
3526           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3527             << New << New->getType();
3528         }
3529         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3530         return true;
3531 
3532       // Complain if this is an explicit declaration of a special
3533       // member that was initially declared implicitly.
3534       //
3535       // As an exception, it's okay to befriend such methods in order
3536       // to permit the implicit constructor/destructor/operator calls.
3537       } else if (OldMethod->isImplicit()) {
3538         if (isFriend) {
3539           NewMethod->setImplicit();
3540         } else {
3541           Diag(NewMethod->getLocation(),
3542                diag::err_definition_of_implicitly_declared_member)
3543             << New << getSpecialMember(OldMethod);
3544           return true;
3545         }
3546       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3547         Diag(NewMethod->getLocation(),
3548              diag::err_definition_of_explicitly_defaulted_member)
3549           << getSpecialMember(OldMethod);
3550         return true;
3551       }
3552     }
3553 
3554     // C++11 [dcl.attr.noreturn]p1:
3555     //   The first declaration of a function shall specify the noreturn
3556     //   attribute if any declaration of that function specifies the noreturn
3557     //   attribute.
3558     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3559     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3560       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3561       Diag(Old->getFirstDecl()->getLocation(),
3562            diag::note_noreturn_missing_first_decl);
3563     }
3564 
3565     // C++11 [dcl.attr.depend]p2:
3566     //   The first declaration of a function shall specify the
3567     //   carries_dependency attribute for its declarator-id if any declaration
3568     //   of the function specifies the carries_dependency attribute.
3569     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3570     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3571       Diag(CDA->getLocation(),
3572            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3573       Diag(Old->getFirstDecl()->getLocation(),
3574            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3575     }
3576 
3577     // (C++98 8.3.5p3):
3578     //   All declarations for a function shall agree exactly in both the
3579     //   return type and the parameter-type-list.
3580     // We also want to respect all the extended bits except noreturn.
3581 
3582     // noreturn should now match unless the old type info didn't have it.
3583     QualType OldQTypeForComparison = OldQType;
3584     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3585       auto *OldType = OldQType->castAs<FunctionProtoType>();
3586       const FunctionType *OldTypeForComparison
3587         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3588       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3589       assert(OldQTypeForComparison.isCanonical());
3590     }
3591 
3592     if (haveIncompatibleLanguageLinkages(Old, New)) {
3593       // As a special case, retain the language linkage from previous
3594       // declarations of a friend function as an extension.
3595       //
3596       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3597       // and is useful because there's otherwise no way to specify language
3598       // linkage within class scope.
3599       //
3600       // Check cautiously as the friend object kind isn't yet complete.
3601       if (New->getFriendObjectKind() != Decl::FOK_None) {
3602         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3603         Diag(OldLocation, PrevDiag);
3604       } else {
3605         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3606         Diag(OldLocation, PrevDiag);
3607         return true;
3608       }
3609     }
3610 
3611     // If the function types are compatible, merge the declarations. Ignore the
3612     // exception specifier because it was already checked above in
3613     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3614     // about incompatible types under -fms-compatibility.
3615     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3616                                                          NewQType))
3617       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3618 
3619     // If the types are imprecise (due to dependent constructs in friends or
3620     // local extern declarations), it's OK if they differ. We'll check again
3621     // during instantiation.
3622     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3623       return false;
3624 
3625     // Fall through for conflicting redeclarations and redefinitions.
3626   }
3627 
3628   // C: Function types need to be compatible, not identical. This handles
3629   // duplicate function decls like "void f(int); void f(enum X);" properly.
3630   if (!getLangOpts().CPlusPlus &&
3631       Context.typesAreCompatible(OldQType, NewQType)) {
3632     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3633     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3634     const FunctionProtoType *OldProto = nullptr;
3635     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3636         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3637       // The old declaration provided a function prototype, but the
3638       // new declaration does not. Merge in the prototype.
3639       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3640       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3641       NewQType =
3642           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3643                                   OldProto->getExtProtoInfo());
3644       New->setType(NewQType);
3645       New->setHasInheritedPrototype();
3646 
3647       // Synthesize parameters with the same types.
3648       SmallVector<ParmVarDecl*, 16> Params;
3649       for (const auto &ParamType : OldProto->param_types()) {
3650         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3651                                                  SourceLocation(), nullptr,
3652                                                  ParamType, /*TInfo=*/nullptr,
3653                                                  SC_None, nullptr);
3654         Param->setScopeInfo(0, Params.size());
3655         Param->setImplicit();
3656         Params.push_back(Param);
3657       }
3658 
3659       New->setParams(Params);
3660     }
3661 
3662     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3663   }
3664 
3665   // Check if the function types are compatible when pointer size address
3666   // spaces are ignored.
3667   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3668     return false;
3669 
3670   // GNU C permits a K&R definition to follow a prototype declaration
3671   // if the declared types of the parameters in the K&R definition
3672   // match the types in the prototype declaration, even when the
3673   // promoted types of the parameters from the K&R definition differ
3674   // from the types in the prototype. GCC then keeps the types from
3675   // the prototype.
3676   //
3677   // If a variadic prototype is followed by a non-variadic K&R definition,
3678   // the K&R definition becomes variadic.  This is sort of an edge case, but
3679   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3680   // C99 6.9.1p8.
3681   if (!getLangOpts().CPlusPlus &&
3682       Old->hasPrototype() && !New->hasPrototype() &&
3683       New->getType()->getAs<FunctionProtoType>() &&
3684       Old->getNumParams() == New->getNumParams()) {
3685     SmallVector<QualType, 16> ArgTypes;
3686     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3687     const FunctionProtoType *OldProto
3688       = Old->getType()->getAs<FunctionProtoType>();
3689     const FunctionProtoType *NewProto
3690       = New->getType()->getAs<FunctionProtoType>();
3691 
3692     // Determine whether this is the GNU C extension.
3693     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3694                                                NewProto->getReturnType());
3695     bool LooseCompatible = !MergedReturn.isNull();
3696     for (unsigned Idx = 0, End = Old->getNumParams();
3697          LooseCompatible && Idx != End; ++Idx) {
3698       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3699       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3700       if (Context.typesAreCompatible(OldParm->getType(),
3701                                      NewProto->getParamType(Idx))) {
3702         ArgTypes.push_back(NewParm->getType());
3703       } else if (Context.typesAreCompatible(OldParm->getType(),
3704                                             NewParm->getType(),
3705                                             /*CompareUnqualified=*/true)) {
3706         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3707                                            NewProto->getParamType(Idx) };
3708         Warnings.push_back(Warn);
3709         ArgTypes.push_back(NewParm->getType());
3710       } else
3711         LooseCompatible = false;
3712     }
3713 
3714     if (LooseCompatible) {
3715       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3716         Diag(Warnings[Warn].NewParm->getLocation(),
3717              diag::ext_param_promoted_not_compatible_with_prototype)
3718           << Warnings[Warn].PromotedType
3719           << Warnings[Warn].OldParm->getType();
3720         if (Warnings[Warn].OldParm->getLocation().isValid())
3721           Diag(Warnings[Warn].OldParm->getLocation(),
3722                diag::note_previous_declaration);
3723       }
3724 
3725       if (MergeTypeWithOld)
3726         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3727                                              OldProto->getExtProtoInfo()));
3728       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3729     }
3730 
3731     // Fall through to diagnose conflicting types.
3732   }
3733 
3734   // A function that has already been declared has been redeclared or
3735   // defined with a different type; show an appropriate diagnostic.
3736 
3737   // If the previous declaration was an implicitly-generated builtin
3738   // declaration, then at the very least we should use a specialized note.
3739   unsigned BuiltinID;
3740   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3741     // If it's actually a library-defined builtin function like 'malloc'
3742     // or 'printf', just warn about the incompatible redeclaration.
3743     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3744       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3745       Diag(OldLocation, diag::note_previous_builtin_declaration)
3746         << Old << Old->getType();
3747 
3748       // If this is a global redeclaration, just forget hereafter
3749       // about the "builtin-ness" of the function.
3750       //
3751       // Doing this for local extern declarations is problematic.  If
3752       // the builtin declaration remains visible, a second invalid
3753       // local declaration will produce a hard error; if it doesn't
3754       // remain visible, a single bogus local redeclaration (which is
3755       // actually only a warning) could break all the downstream code.
3756       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3757         New->getIdentifier()->revertBuiltin();
3758 
3759       return false;
3760     }
3761 
3762     PrevDiag = diag::note_previous_builtin_declaration;
3763   }
3764 
3765   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3766   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3767   return true;
3768 }
3769 
3770 /// Completes the merge of two function declarations that are
3771 /// known to be compatible.
3772 ///
3773 /// This routine handles the merging of attributes and other
3774 /// properties of function declarations from the old declaration to
3775 /// the new declaration, once we know that New is in fact a
3776 /// redeclaration of Old.
3777 ///
3778 /// \returns false
3779 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3780                                         Scope *S, bool MergeTypeWithOld) {
3781   // Merge the attributes
3782   mergeDeclAttributes(New, Old);
3783 
3784   // Merge "pure" flag.
3785   if (Old->isPure())
3786     New->setPure();
3787 
3788   // Merge "used" flag.
3789   if (Old->getMostRecentDecl()->isUsed(false))
3790     New->setIsUsed();
3791 
3792   // Merge attributes from the parameters.  These can mismatch with K&R
3793   // declarations.
3794   if (New->getNumParams() == Old->getNumParams())
3795       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3796         ParmVarDecl *NewParam = New->getParamDecl(i);
3797         ParmVarDecl *OldParam = Old->getParamDecl(i);
3798         mergeParamDeclAttributes(NewParam, OldParam, *this);
3799         mergeParamDeclTypes(NewParam, OldParam, *this);
3800       }
3801 
3802   if (getLangOpts().CPlusPlus)
3803     return MergeCXXFunctionDecl(New, Old, S);
3804 
3805   // Merge the function types so the we get the composite types for the return
3806   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3807   // was visible.
3808   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3809   if (!Merged.isNull() && MergeTypeWithOld)
3810     New->setType(Merged);
3811 
3812   return false;
3813 }
3814 
3815 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3816                                 ObjCMethodDecl *oldMethod) {
3817   // Merge the attributes, including deprecated/unavailable
3818   AvailabilityMergeKind MergeKind =
3819     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3820       ? AMK_ProtocolImplementation
3821       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3822                                                        : AMK_Override;
3823 
3824   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3825 
3826   // Merge attributes from the parameters.
3827   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3828                                        oe = oldMethod->param_end();
3829   for (ObjCMethodDecl::param_iterator
3830          ni = newMethod->param_begin(), ne = newMethod->param_end();
3831        ni != ne && oi != oe; ++ni, ++oi)
3832     mergeParamDeclAttributes(*ni, *oi, *this);
3833 
3834   CheckObjCMethodOverride(newMethod, oldMethod);
3835 }
3836 
3837 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3838   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3839 
3840   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3841          ? diag::err_redefinition_different_type
3842          : diag::err_redeclaration_different_type)
3843     << New->getDeclName() << New->getType() << Old->getType();
3844 
3845   diag::kind PrevDiag;
3846   SourceLocation OldLocation;
3847   std::tie(PrevDiag, OldLocation)
3848     = getNoteDiagForInvalidRedeclaration(Old, New);
3849   S.Diag(OldLocation, PrevDiag);
3850   New->setInvalidDecl();
3851 }
3852 
3853 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3854 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3855 /// emitting diagnostics as appropriate.
3856 ///
3857 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3858 /// to here in AddInitializerToDecl. We can't check them before the initializer
3859 /// is attached.
3860 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3861                              bool MergeTypeWithOld) {
3862   if (New->isInvalidDecl() || Old->isInvalidDecl())
3863     return;
3864 
3865   QualType MergedT;
3866   if (getLangOpts().CPlusPlus) {
3867     if (New->getType()->isUndeducedType()) {
3868       // We don't know what the new type is until the initializer is attached.
3869       return;
3870     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3871       // These could still be something that needs exception specs checked.
3872       return MergeVarDeclExceptionSpecs(New, Old);
3873     }
3874     // C++ [basic.link]p10:
3875     //   [...] the types specified by all declarations referring to a given
3876     //   object or function shall be identical, except that declarations for an
3877     //   array object can specify array types that differ by the presence or
3878     //   absence of a major array bound (8.3.4).
3879     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3880       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3881       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3882 
3883       // We are merging a variable declaration New into Old. If it has an array
3884       // bound, and that bound differs from Old's bound, we should diagnose the
3885       // mismatch.
3886       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3887         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3888              PrevVD = PrevVD->getPreviousDecl()) {
3889           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3890           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3891             continue;
3892 
3893           if (!Context.hasSameType(NewArray, PrevVDTy))
3894             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3895         }
3896       }
3897 
3898       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3899         if (Context.hasSameType(OldArray->getElementType(),
3900                                 NewArray->getElementType()))
3901           MergedT = New->getType();
3902       }
3903       // FIXME: Check visibility. New is hidden but has a complete type. If New
3904       // has no array bound, it should not inherit one from Old, if Old is not
3905       // visible.
3906       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3907         if (Context.hasSameType(OldArray->getElementType(),
3908                                 NewArray->getElementType()))
3909           MergedT = Old->getType();
3910       }
3911     }
3912     else if (New->getType()->isObjCObjectPointerType() &&
3913                Old->getType()->isObjCObjectPointerType()) {
3914       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3915                                               Old->getType());
3916     }
3917   } else {
3918     // C 6.2.7p2:
3919     //   All declarations that refer to the same object or function shall have
3920     //   compatible type.
3921     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3922   }
3923   if (MergedT.isNull()) {
3924     // It's OK if we couldn't merge types if either type is dependent, for a
3925     // block-scope variable. In other cases (static data members of class
3926     // templates, variable templates, ...), we require the types to be
3927     // equivalent.
3928     // FIXME: The C++ standard doesn't say anything about this.
3929     if ((New->getType()->isDependentType() ||
3930          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3931       // If the old type was dependent, we can't merge with it, so the new type
3932       // becomes dependent for now. We'll reproduce the original type when we
3933       // instantiate the TypeSourceInfo for the variable.
3934       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3935         New->setType(Context.DependentTy);
3936       return;
3937     }
3938     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3939   }
3940 
3941   // Don't actually update the type on the new declaration if the old
3942   // declaration was an extern declaration in a different scope.
3943   if (MergeTypeWithOld)
3944     New->setType(MergedT);
3945 }
3946 
3947 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3948                                   LookupResult &Previous) {
3949   // C11 6.2.7p4:
3950   //   For an identifier with internal or external linkage declared
3951   //   in a scope in which a prior declaration of that identifier is
3952   //   visible, if the prior declaration specifies internal or
3953   //   external linkage, the type of the identifier at the later
3954   //   declaration becomes the composite type.
3955   //
3956   // If the variable isn't visible, we do not merge with its type.
3957   if (Previous.isShadowed())
3958     return false;
3959 
3960   if (S.getLangOpts().CPlusPlus) {
3961     // C++11 [dcl.array]p3:
3962     //   If there is a preceding declaration of the entity in the same
3963     //   scope in which the bound was specified, an omitted array bound
3964     //   is taken to be the same as in that earlier declaration.
3965     return NewVD->isPreviousDeclInSameBlockScope() ||
3966            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3967             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3968   } else {
3969     // If the old declaration was function-local, don't merge with its
3970     // type unless we're in the same function.
3971     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3972            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3973   }
3974 }
3975 
3976 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3977 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3978 /// situation, merging decls or emitting diagnostics as appropriate.
3979 ///
3980 /// Tentative definition rules (C99 6.9.2p2) are checked by
3981 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3982 /// definitions here, since the initializer hasn't been attached.
3983 ///
3984 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3985   // If the new decl is already invalid, don't do any other checking.
3986   if (New->isInvalidDecl())
3987     return;
3988 
3989   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3990     return;
3991 
3992   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3993 
3994   // Verify the old decl was also a variable or variable template.
3995   VarDecl *Old = nullptr;
3996   VarTemplateDecl *OldTemplate = nullptr;
3997   if (Previous.isSingleResult()) {
3998     if (NewTemplate) {
3999       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4000       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4001 
4002       if (auto *Shadow =
4003               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4004         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4005           return New->setInvalidDecl();
4006     } else {
4007       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4008 
4009       if (auto *Shadow =
4010               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4011         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4012           return New->setInvalidDecl();
4013     }
4014   }
4015   if (!Old) {
4016     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4017         << New->getDeclName();
4018     notePreviousDefinition(Previous.getRepresentativeDecl(),
4019                            New->getLocation());
4020     return New->setInvalidDecl();
4021   }
4022 
4023   // Ensure the template parameters are compatible.
4024   if (NewTemplate &&
4025       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4026                                       OldTemplate->getTemplateParameters(),
4027                                       /*Complain=*/true, TPL_TemplateMatch))
4028     return New->setInvalidDecl();
4029 
4030   // C++ [class.mem]p1:
4031   //   A member shall not be declared twice in the member-specification [...]
4032   //
4033   // Here, we need only consider static data members.
4034   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4035     Diag(New->getLocation(), diag::err_duplicate_member)
4036       << New->getIdentifier();
4037     Diag(Old->getLocation(), diag::note_previous_declaration);
4038     New->setInvalidDecl();
4039   }
4040 
4041   mergeDeclAttributes(New, Old);
4042   // Warn if an already-declared variable is made a weak_import in a subsequent
4043   // declaration
4044   if (New->hasAttr<WeakImportAttr>() &&
4045       Old->getStorageClass() == SC_None &&
4046       !Old->hasAttr<WeakImportAttr>()) {
4047     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4048     notePreviousDefinition(Old, New->getLocation());
4049     // Remove weak_import attribute on new declaration.
4050     New->dropAttr<WeakImportAttr>();
4051   }
4052 
4053   if (New->hasAttr<InternalLinkageAttr>() &&
4054       !Old->hasAttr<InternalLinkageAttr>()) {
4055     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
4056         << New->getDeclName();
4057     notePreviousDefinition(Old, New->getLocation());
4058     New->dropAttr<InternalLinkageAttr>();
4059   }
4060 
4061   // Merge the types.
4062   VarDecl *MostRecent = Old->getMostRecentDecl();
4063   if (MostRecent != Old) {
4064     MergeVarDeclTypes(New, MostRecent,
4065                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4066     if (New->isInvalidDecl())
4067       return;
4068   }
4069 
4070   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4071   if (New->isInvalidDecl())
4072     return;
4073 
4074   diag::kind PrevDiag;
4075   SourceLocation OldLocation;
4076   std::tie(PrevDiag, OldLocation) =
4077       getNoteDiagForInvalidRedeclaration(Old, New);
4078 
4079   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4080   if (New->getStorageClass() == SC_Static &&
4081       !New->isStaticDataMember() &&
4082       Old->hasExternalFormalLinkage()) {
4083     if (getLangOpts().MicrosoftExt) {
4084       Diag(New->getLocation(), diag::ext_static_non_static)
4085           << New->getDeclName();
4086       Diag(OldLocation, PrevDiag);
4087     } else {
4088       Diag(New->getLocation(), diag::err_static_non_static)
4089           << New->getDeclName();
4090       Diag(OldLocation, PrevDiag);
4091       return New->setInvalidDecl();
4092     }
4093   }
4094   // C99 6.2.2p4:
4095   //   For an identifier declared with the storage-class specifier
4096   //   extern in a scope in which a prior declaration of that
4097   //   identifier is visible,23) if the prior declaration specifies
4098   //   internal or external linkage, the linkage of the identifier at
4099   //   the later declaration is the same as the linkage specified at
4100   //   the prior declaration. If no prior declaration is visible, or
4101   //   if the prior declaration specifies no linkage, then the
4102   //   identifier has external linkage.
4103   if (New->hasExternalStorage() && Old->hasLinkage())
4104     /* Okay */;
4105   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4106            !New->isStaticDataMember() &&
4107            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4108     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4109     Diag(OldLocation, PrevDiag);
4110     return New->setInvalidDecl();
4111   }
4112 
4113   // Check if extern is followed by non-extern and vice-versa.
4114   if (New->hasExternalStorage() &&
4115       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4116     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4117     Diag(OldLocation, PrevDiag);
4118     return New->setInvalidDecl();
4119   }
4120   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4121       !New->hasExternalStorage()) {
4122     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4123     Diag(OldLocation, PrevDiag);
4124     return New->setInvalidDecl();
4125   }
4126 
4127   if (CheckRedeclarationModuleOwnership(New, Old))
4128     return;
4129 
4130   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4131 
4132   // FIXME: The test for external storage here seems wrong? We still
4133   // need to check for mismatches.
4134   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4135       // Don't complain about out-of-line definitions of static members.
4136       !(Old->getLexicalDeclContext()->isRecord() &&
4137         !New->getLexicalDeclContext()->isRecord())) {
4138     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4139     Diag(OldLocation, PrevDiag);
4140     return New->setInvalidDecl();
4141   }
4142 
4143   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4144     if (VarDecl *Def = Old->getDefinition()) {
4145       // C++1z [dcl.fcn.spec]p4:
4146       //   If the definition of a variable appears in a translation unit before
4147       //   its first declaration as inline, the program is ill-formed.
4148       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4149       Diag(Def->getLocation(), diag::note_previous_definition);
4150     }
4151   }
4152 
4153   // If this redeclaration makes the variable inline, we may need to add it to
4154   // UndefinedButUsed.
4155   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4156       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4157     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4158                                            SourceLocation()));
4159 
4160   if (New->getTLSKind() != Old->getTLSKind()) {
4161     if (!Old->getTLSKind()) {
4162       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4163       Diag(OldLocation, PrevDiag);
4164     } else if (!New->getTLSKind()) {
4165       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4166       Diag(OldLocation, PrevDiag);
4167     } else {
4168       // Do not allow redeclaration to change the variable between requiring
4169       // static and dynamic initialization.
4170       // FIXME: GCC allows this, but uses the TLS keyword on the first
4171       // declaration to determine the kind. Do we need to be compatible here?
4172       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4173         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4174       Diag(OldLocation, PrevDiag);
4175     }
4176   }
4177 
4178   // C++ doesn't have tentative definitions, so go right ahead and check here.
4179   if (getLangOpts().CPlusPlus &&
4180       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4181     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4182         Old->getCanonicalDecl()->isConstexpr()) {
4183       // This definition won't be a definition any more once it's been merged.
4184       Diag(New->getLocation(),
4185            diag::warn_deprecated_redundant_constexpr_static_def);
4186     } else if (VarDecl *Def = Old->getDefinition()) {
4187       if (checkVarDeclRedefinition(Def, New))
4188         return;
4189     }
4190   }
4191 
4192   if (haveIncompatibleLanguageLinkages(Old, New)) {
4193     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4194     Diag(OldLocation, PrevDiag);
4195     New->setInvalidDecl();
4196     return;
4197   }
4198 
4199   // Merge "used" flag.
4200   if (Old->getMostRecentDecl()->isUsed(false))
4201     New->setIsUsed();
4202 
4203   // Keep a chain of previous declarations.
4204   New->setPreviousDecl(Old);
4205   if (NewTemplate)
4206     NewTemplate->setPreviousDecl(OldTemplate);
4207   adjustDeclContextForDeclaratorDecl(New, Old);
4208 
4209   // Inherit access appropriately.
4210   New->setAccess(Old->getAccess());
4211   if (NewTemplate)
4212     NewTemplate->setAccess(New->getAccess());
4213 
4214   if (Old->isInline())
4215     New->setImplicitlyInline();
4216 }
4217 
4218 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4219   SourceManager &SrcMgr = getSourceManager();
4220   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4221   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4222   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4223   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4224   auto &HSI = PP.getHeaderSearchInfo();
4225   StringRef HdrFilename =
4226       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4227 
4228   auto noteFromModuleOrInclude = [&](Module *Mod,
4229                                      SourceLocation IncLoc) -> bool {
4230     // Redefinition errors with modules are common with non modular mapped
4231     // headers, example: a non-modular header H in module A that also gets
4232     // included directly in a TU. Pointing twice to the same header/definition
4233     // is confusing, try to get better diagnostics when modules is on.
4234     if (IncLoc.isValid()) {
4235       if (Mod) {
4236         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4237             << HdrFilename.str() << Mod->getFullModuleName();
4238         if (!Mod->DefinitionLoc.isInvalid())
4239           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4240               << Mod->getFullModuleName();
4241       } else {
4242         Diag(IncLoc, diag::note_redefinition_include_same_file)
4243             << HdrFilename.str();
4244       }
4245       return true;
4246     }
4247 
4248     return false;
4249   };
4250 
4251   // Is it the same file and same offset? Provide more information on why
4252   // this leads to a redefinition error.
4253   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4254     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4255     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4256     bool EmittedDiag =
4257         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4258     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4259 
4260     // If the header has no guards, emit a note suggesting one.
4261     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4262       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4263 
4264     if (EmittedDiag)
4265       return;
4266   }
4267 
4268   // Redefinition coming from different files or couldn't do better above.
4269   if (Old->getLocation().isValid())
4270     Diag(Old->getLocation(), diag::note_previous_definition);
4271 }
4272 
4273 /// We've just determined that \p Old and \p New both appear to be definitions
4274 /// of the same variable. Either diagnose or fix the problem.
4275 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4276   if (!hasVisibleDefinition(Old) &&
4277       (New->getFormalLinkage() == InternalLinkage ||
4278        New->isInline() ||
4279        New->getDescribedVarTemplate() ||
4280        New->getNumTemplateParameterLists() ||
4281        New->getDeclContext()->isDependentContext())) {
4282     // The previous definition is hidden, and multiple definitions are
4283     // permitted (in separate TUs). Demote this to a declaration.
4284     New->demoteThisDefinitionToDeclaration();
4285 
4286     // Make the canonical definition visible.
4287     if (auto *OldTD = Old->getDescribedVarTemplate())
4288       makeMergedDefinitionVisible(OldTD);
4289     makeMergedDefinitionVisible(Old);
4290     return false;
4291   } else {
4292     Diag(New->getLocation(), diag::err_redefinition) << New;
4293     notePreviousDefinition(Old, New->getLocation());
4294     New->setInvalidDecl();
4295     return true;
4296   }
4297 }
4298 
4299 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4300 /// no declarator (e.g. "struct foo;") is parsed.
4301 Decl *
4302 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4303                                  RecordDecl *&AnonRecord) {
4304   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4305                                     AnonRecord);
4306 }
4307 
4308 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4309 // disambiguate entities defined in different scopes.
4310 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4311 // compatibility.
4312 // We will pick our mangling number depending on which version of MSVC is being
4313 // targeted.
4314 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4315   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4316              ? S->getMSCurManglingNumber()
4317              : S->getMSLastManglingNumber();
4318 }
4319 
4320 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4321   if (!Context.getLangOpts().CPlusPlus)
4322     return;
4323 
4324   if (isa<CXXRecordDecl>(Tag->getParent())) {
4325     // If this tag is the direct child of a class, number it if
4326     // it is anonymous.
4327     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4328       return;
4329     MangleNumberingContext &MCtx =
4330         Context.getManglingNumberContext(Tag->getParent());
4331     Context.setManglingNumber(
4332         Tag, MCtx.getManglingNumber(
4333                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4334     return;
4335   }
4336 
4337   // If this tag isn't a direct child of a class, number it if it is local.
4338   MangleNumberingContext *MCtx;
4339   Decl *ManglingContextDecl;
4340   std::tie(MCtx, ManglingContextDecl) =
4341       getCurrentMangleNumberContext(Tag->getDeclContext());
4342   if (MCtx) {
4343     Context.setManglingNumber(
4344         Tag, MCtx->getManglingNumber(
4345                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4346   }
4347 }
4348 
4349 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4350                                         TypedefNameDecl *NewTD) {
4351   if (TagFromDeclSpec->isInvalidDecl())
4352     return;
4353 
4354   // Do nothing if the tag already has a name for linkage purposes.
4355   if (TagFromDeclSpec->hasNameForLinkage())
4356     return;
4357 
4358   // A well-formed anonymous tag must always be a TUK_Definition.
4359   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4360 
4361   // The type must match the tag exactly;  no qualifiers allowed.
4362   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4363                            Context.getTagDeclType(TagFromDeclSpec))) {
4364     if (getLangOpts().CPlusPlus)
4365       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4366     return;
4367   }
4368 
4369   // If we've already computed linkage for the anonymous tag, then
4370   // adding a typedef name for the anonymous decl can change that
4371   // linkage, which might be a serious problem.  Diagnose this as
4372   // unsupported and ignore the typedef name.  TODO: we should
4373   // pursue this as a language defect and establish a formal rule
4374   // for how to handle it.
4375   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4376     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4377 
4378     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4379     tagLoc = getLocForEndOfToken(tagLoc);
4380 
4381     llvm::SmallString<40> textToInsert;
4382     textToInsert += ' ';
4383     textToInsert += NewTD->getIdentifier()->getName();
4384     Diag(tagLoc, diag::note_typedef_changes_linkage)
4385         << FixItHint::CreateInsertion(tagLoc, textToInsert);
4386     return;
4387   }
4388 
4389   // Otherwise, set this is the anon-decl typedef for the tag.
4390   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4391 }
4392 
4393 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4394   switch (T) {
4395   case DeclSpec::TST_class:
4396     return 0;
4397   case DeclSpec::TST_struct:
4398     return 1;
4399   case DeclSpec::TST_interface:
4400     return 2;
4401   case DeclSpec::TST_union:
4402     return 3;
4403   case DeclSpec::TST_enum:
4404     return 4;
4405   default:
4406     llvm_unreachable("unexpected type specifier");
4407   }
4408 }
4409 
4410 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4411 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4412 /// parameters to cope with template friend declarations.
4413 Decl *
4414 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4415                                  MultiTemplateParamsArg TemplateParams,
4416                                  bool IsExplicitInstantiation,
4417                                  RecordDecl *&AnonRecord) {
4418   Decl *TagD = nullptr;
4419   TagDecl *Tag = nullptr;
4420   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4421       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4422       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4423       DS.getTypeSpecType() == DeclSpec::TST_union ||
4424       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4425     TagD = DS.getRepAsDecl();
4426 
4427     if (!TagD) // We probably had an error
4428       return nullptr;
4429 
4430     // Note that the above type specs guarantee that the
4431     // type rep is a Decl, whereas in many of the others
4432     // it's a Type.
4433     if (isa<TagDecl>(TagD))
4434       Tag = cast<TagDecl>(TagD);
4435     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4436       Tag = CTD->getTemplatedDecl();
4437   }
4438 
4439   if (Tag) {
4440     handleTagNumbering(Tag, S);
4441     Tag->setFreeStanding();
4442     if (Tag->isInvalidDecl())
4443       return Tag;
4444   }
4445 
4446   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4447     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4448     // or incomplete types shall not be restrict-qualified."
4449     if (TypeQuals & DeclSpec::TQ_restrict)
4450       Diag(DS.getRestrictSpecLoc(),
4451            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4452            << DS.getSourceRange();
4453   }
4454 
4455   if (DS.isInlineSpecified())
4456     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4457         << getLangOpts().CPlusPlus17;
4458 
4459   if (DS.hasConstexprSpecifier()) {
4460     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4461     // and definitions of functions and variables.
4462     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4463     // the declaration of a function or function template
4464     if (Tag)
4465       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4466           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4467           << DS.getConstexprSpecifier();
4468     else
4469       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4470           << DS.getConstexprSpecifier();
4471     // Don't emit warnings after this error.
4472     return TagD;
4473   }
4474 
4475   DiagnoseFunctionSpecifiers(DS);
4476 
4477   if (DS.isFriendSpecified()) {
4478     // If we're dealing with a decl but not a TagDecl, assume that
4479     // whatever routines created it handled the friendship aspect.
4480     if (TagD && !Tag)
4481       return nullptr;
4482     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4483   }
4484 
4485   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4486   bool IsExplicitSpecialization =
4487     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4488   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4489       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4490       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4491     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4492     // nested-name-specifier unless it is an explicit instantiation
4493     // or an explicit specialization.
4494     //
4495     // FIXME: We allow class template partial specializations here too, per the
4496     // obvious intent of DR1819.
4497     //
4498     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4499     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4500         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4501     return nullptr;
4502   }
4503 
4504   // Track whether this decl-specifier declares anything.
4505   bool DeclaresAnything = true;
4506 
4507   // Handle anonymous struct definitions.
4508   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4509     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4510         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4511       if (getLangOpts().CPlusPlus ||
4512           Record->getDeclContext()->isRecord()) {
4513         // If CurContext is a DeclContext that can contain statements,
4514         // RecursiveASTVisitor won't visit the decls that
4515         // BuildAnonymousStructOrUnion() will put into CurContext.
4516         // Also store them here so that they can be part of the
4517         // DeclStmt that gets created in this case.
4518         // FIXME: Also return the IndirectFieldDecls created by
4519         // BuildAnonymousStructOr union, for the same reason?
4520         if (CurContext->isFunctionOrMethod())
4521           AnonRecord = Record;
4522         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4523                                            Context.getPrintingPolicy());
4524       }
4525 
4526       DeclaresAnything = false;
4527     }
4528   }
4529 
4530   // C11 6.7.2.1p2:
4531   //   A struct-declaration that does not declare an anonymous structure or
4532   //   anonymous union shall contain a struct-declarator-list.
4533   //
4534   // This rule also existed in C89 and C99; the grammar for struct-declaration
4535   // did not permit a struct-declaration without a struct-declarator-list.
4536   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4537       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4538     // Check for Microsoft C extension: anonymous struct/union member.
4539     // Handle 2 kinds of anonymous struct/union:
4540     //   struct STRUCT;
4541     //   union UNION;
4542     // and
4543     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4544     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4545     if ((Tag && Tag->getDeclName()) ||
4546         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4547       RecordDecl *Record = nullptr;
4548       if (Tag)
4549         Record = dyn_cast<RecordDecl>(Tag);
4550       else if (const RecordType *RT =
4551                    DS.getRepAsType().get()->getAsStructureType())
4552         Record = RT->getDecl();
4553       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4554         Record = UT->getDecl();
4555 
4556       if (Record && getLangOpts().MicrosoftExt) {
4557         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4558             << Record->isUnion() << DS.getSourceRange();
4559         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4560       }
4561 
4562       DeclaresAnything = false;
4563     }
4564   }
4565 
4566   // Skip all the checks below if we have a type error.
4567   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4568       (TagD && TagD->isInvalidDecl()))
4569     return TagD;
4570 
4571   if (getLangOpts().CPlusPlus &&
4572       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4573     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4574       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4575           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4576         DeclaresAnything = false;
4577 
4578   if (!DS.isMissingDeclaratorOk()) {
4579     // Customize diagnostic for a typedef missing a name.
4580     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4581       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4582           << DS.getSourceRange();
4583     else
4584       DeclaresAnything = false;
4585   }
4586 
4587   if (DS.isModulePrivateSpecified() &&
4588       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4589     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4590       << Tag->getTagKind()
4591       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4592 
4593   ActOnDocumentableDecl(TagD);
4594 
4595   // C 6.7/2:
4596   //   A declaration [...] shall declare at least a declarator [...], a tag,
4597   //   or the members of an enumeration.
4598   // C++ [dcl.dcl]p3:
4599   //   [If there are no declarators], and except for the declaration of an
4600   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4601   //   names into the program, or shall redeclare a name introduced by a
4602   //   previous declaration.
4603   if (!DeclaresAnything) {
4604     // In C, we allow this as a (popular) extension / bug. Don't bother
4605     // producing further diagnostics for redundant qualifiers after this.
4606     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4607     return TagD;
4608   }
4609 
4610   // C++ [dcl.stc]p1:
4611   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4612   //   init-declarator-list of the declaration shall not be empty.
4613   // C++ [dcl.fct.spec]p1:
4614   //   If a cv-qualifier appears in a decl-specifier-seq, the
4615   //   init-declarator-list of the declaration shall not be empty.
4616   //
4617   // Spurious qualifiers here appear to be valid in C.
4618   unsigned DiagID = diag::warn_standalone_specifier;
4619   if (getLangOpts().CPlusPlus)
4620     DiagID = diag::ext_standalone_specifier;
4621 
4622   // Note that a linkage-specification sets a storage class, but
4623   // 'extern "C" struct foo;' is actually valid and not theoretically
4624   // useless.
4625   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4626     if (SCS == DeclSpec::SCS_mutable)
4627       // Since mutable is not a viable storage class specifier in C, there is
4628       // no reason to treat it as an extension. Instead, diagnose as an error.
4629       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4630     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4631       Diag(DS.getStorageClassSpecLoc(), DiagID)
4632         << DeclSpec::getSpecifierName(SCS);
4633   }
4634 
4635   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4636     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4637       << DeclSpec::getSpecifierName(TSCS);
4638   if (DS.getTypeQualifiers()) {
4639     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4640       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4641     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4642       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4643     // Restrict is covered above.
4644     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4645       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4646     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4647       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4648   }
4649 
4650   // Warn about ignored type attributes, for example:
4651   // __attribute__((aligned)) struct A;
4652   // Attributes should be placed after tag to apply to type declaration.
4653   if (!DS.getAttributes().empty()) {
4654     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4655     if (TypeSpecType == DeclSpec::TST_class ||
4656         TypeSpecType == DeclSpec::TST_struct ||
4657         TypeSpecType == DeclSpec::TST_interface ||
4658         TypeSpecType == DeclSpec::TST_union ||
4659         TypeSpecType == DeclSpec::TST_enum) {
4660       for (const ParsedAttr &AL : DS.getAttributes())
4661         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4662             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4663     }
4664   }
4665 
4666   return TagD;
4667 }
4668 
4669 /// We are trying to inject an anonymous member into the given scope;
4670 /// check if there's an existing declaration that can't be overloaded.
4671 ///
4672 /// \return true if this is a forbidden redeclaration
4673 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4674                                          Scope *S,
4675                                          DeclContext *Owner,
4676                                          DeclarationName Name,
4677                                          SourceLocation NameLoc,
4678                                          bool IsUnion) {
4679   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4680                  Sema::ForVisibleRedeclaration);
4681   if (!SemaRef.LookupName(R, S)) return false;
4682 
4683   // Pick a representative declaration.
4684   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4685   assert(PrevDecl && "Expected a non-null Decl");
4686 
4687   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4688     return false;
4689 
4690   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4691     << IsUnion << Name;
4692   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4693 
4694   return true;
4695 }
4696 
4697 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4698 /// anonymous struct or union AnonRecord into the owning context Owner
4699 /// and scope S. This routine will be invoked just after we realize
4700 /// that an unnamed union or struct is actually an anonymous union or
4701 /// struct, e.g.,
4702 ///
4703 /// @code
4704 /// union {
4705 ///   int i;
4706 ///   float f;
4707 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4708 ///    // f into the surrounding scope.x
4709 /// @endcode
4710 ///
4711 /// This routine is recursive, injecting the names of nested anonymous
4712 /// structs/unions into the owning context and scope as well.
4713 static bool
4714 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4715                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4716                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4717   bool Invalid = false;
4718 
4719   // Look every FieldDecl and IndirectFieldDecl with a name.
4720   for (auto *D : AnonRecord->decls()) {
4721     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4722         cast<NamedDecl>(D)->getDeclName()) {
4723       ValueDecl *VD = cast<ValueDecl>(D);
4724       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4725                                        VD->getLocation(),
4726                                        AnonRecord->isUnion())) {
4727         // C++ [class.union]p2:
4728         //   The names of the members of an anonymous union shall be
4729         //   distinct from the names of any other entity in the
4730         //   scope in which the anonymous union is declared.
4731         Invalid = true;
4732       } else {
4733         // C++ [class.union]p2:
4734         //   For the purpose of name lookup, after the anonymous union
4735         //   definition, the members of the anonymous union are
4736         //   considered to have been defined in the scope in which the
4737         //   anonymous union is declared.
4738         unsigned OldChainingSize = Chaining.size();
4739         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4740           Chaining.append(IF->chain_begin(), IF->chain_end());
4741         else
4742           Chaining.push_back(VD);
4743 
4744         assert(Chaining.size() >= 2);
4745         NamedDecl **NamedChain =
4746           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4747         for (unsigned i = 0; i < Chaining.size(); i++)
4748           NamedChain[i] = Chaining[i];
4749 
4750         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4751             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4752             VD->getType(), {NamedChain, Chaining.size()});
4753 
4754         for (const auto *Attr : VD->attrs())
4755           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4756 
4757         IndirectField->setAccess(AS);
4758         IndirectField->setImplicit();
4759         SemaRef.PushOnScopeChains(IndirectField, S);
4760 
4761         // That includes picking up the appropriate access specifier.
4762         if (AS != AS_none) IndirectField->setAccess(AS);
4763 
4764         Chaining.resize(OldChainingSize);
4765       }
4766     }
4767   }
4768 
4769   return Invalid;
4770 }
4771 
4772 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4773 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4774 /// illegal input values are mapped to SC_None.
4775 static StorageClass
4776 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4777   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4778   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4779          "Parser allowed 'typedef' as storage class VarDecl.");
4780   switch (StorageClassSpec) {
4781   case DeclSpec::SCS_unspecified:    return SC_None;
4782   case DeclSpec::SCS_extern:
4783     if (DS.isExternInLinkageSpec())
4784       return SC_None;
4785     return SC_Extern;
4786   case DeclSpec::SCS_static:         return SC_Static;
4787   case DeclSpec::SCS_auto:           return SC_Auto;
4788   case DeclSpec::SCS_register:       return SC_Register;
4789   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4790     // Illegal SCSs map to None: error reporting is up to the caller.
4791   case DeclSpec::SCS_mutable:        // Fall through.
4792   case DeclSpec::SCS_typedef:        return SC_None;
4793   }
4794   llvm_unreachable("unknown storage class specifier");
4795 }
4796 
4797 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4798   assert(Record->hasInClassInitializer());
4799 
4800   for (const auto *I : Record->decls()) {
4801     const auto *FD = dyn_cast<FieldDecl>(I);
4802     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4803       FD = IFD->getAnonField();
4804     if (FD && FD->hasInClassInitializer())
4805       return FD->getLocation();
4806   }
4807 
4808   llvm_unreachable("couldn't find in-class initializer");
4809 }
4810 
4811 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4812                                       SourceLocation DefaultInitLoc) {
4813   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4814     return;
4815 
4816   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4817   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4818 }
4819 
4820 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4821                                       CXXRecordDecl *AnonUnion) {
4822   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4823     return;
4824 
4825   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4826 }
4827 
4828 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4829 /// anonymous structure or union. Anonymous unions are a C++ feature
4830 /// (C++ [class.union]) and a C11 feature; anonymous structures
4831 /// are a C11 feature and GNU C++ extension.
4832 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4833                                         AccessSpecifier AS,
4834                                         RecordDecl *Record,
4835                                         const PrintingPolicy &Policy) {
4836   DeclContext *Owner = Record->getDeclContext();
4837 
4838   // Diagnose whether this anonymous struct/union is an extension.
4839   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4840     Diag(Record->getLocation(), diag::ext_anonymous_union);
4841   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4842     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4843   else if (!Record->isUnion() && !getLangOpts().C11)
4844     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4845 
4846   // C and C++ require different kinds of checks for anonymous
4847   // structs/unions.
4848   bool Invalid = false;
4849   if (getLangOpts().CPlusPlus) {
4850     const char *PrevSpec = nullptr;
4851     if (Record->isUnion()) {
4852       // C++ [class.union]p6:
4853       // C++17 [class.union.anon]p2:
4854       //   Anonymous unions declared in a named namespace or in the
4855       //   global namespace shall be declared static.
4856       unsigned DiagID;
4857       DeclContext *OwnerScope = Owner->getRedeclContext();
4858       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4859           (OwnerScope->isTranslationUnit() ||
4860            (OwnerScope->isNamespace() &&
4861             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
4862         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4863           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4864 
4865         // Recover by adding 'static'.
4866         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4867                                PrevSpec, DiagID, Policy);
4868       }
4869       // C++ [class.union]p6:
4870       //   A storage class is not allowed in a declaration of an
4871       //   anonymous union in a class scope.
4872       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4873                isa<RecordDecl>(Owner)) {
4874         Diag(DS.getStorageClassSpecLoc(),
4875              diag::err_anonymous_union_with_storage_spec)
4876           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4877 
4878         // Recover by removing the storage specifier.
4879         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4880                                SourceLocation(),
4881                                PrevSpec, DiagID, Context.getPrintingPolicy());
4882       }
4883     }
4884 
4885     // Ignore const/volatile/restrict qualifiers.
4886     if (DS.getTypeQualifiers()) {
4887       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4888         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4889           << Record->isUnion() << "const"
4890           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4891       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4892         Diag(DS.getVolatileSpecLoc(),
4893              diag::ext_anonymous_struct_union_qualified)
4894           << Record->isUnion() << "volatile"
4895           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4896       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4897         Diag(DS.getRestrictSpecLoc(),
4898              diag::ext_anonymous_struct_union_qualified)
4899           << Record->isUnion() << "restrict"
4900           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4901       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4902         Diag(DS.getAtomicSpecLoc(),
4903              diag::ext_anonymous_struct_union_qualified)
4904           << Record->isUnion() << "_Atomic"
4905           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4906       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4907         Diag(DS.getUnalignedSpecLoc(),
4908              diag::ext_anonymous_struct_union_qualified)
4909           << Record->isUnion() << "__unaligned"
4910           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4911 
4912       DS.ClearTypeQualifiers();
4913     }
4914 
4915     // C++ [class.union]p2:
4916     //   The member-specification of an anonymous union shall only
4917     //   define non-static data members. [Note: nested types and
4918     //   functions cannot be declared within an anonymous union. ]
4919     for (auto *Mem : Record->decls()) {
4920       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4921         // C++ [class.union]p3:
4922         //   An anonymous union shall not have private or protected
4923         //   members (clause 11).
4924         assert(FD->getAccess() != AS_none);
4925         if (FD->getAccess() != AS_public) {
4926           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4927             << Record->isUnion() << (FD->getAccess() == AS_protected);
4928           Invalid = true;
4929         }
4930 
4931         // C++ [class.union]p1
4932         //   An object of a class with a non-trivial constructor, a non-trivial
4933         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4934         //   assignment operator cannot be a member of a union, nor can an
4935         //   array of such objects.
4936         if (CheckNontrivialField(FD))
4937           Invalid = true;
4938       } else if (Mem->isImplicit()) {
4939         // Any implicit members are fine.
4940       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4941         // This is a type that showed up in an
4942         // elaborated-type-specifier inside the anonymous struct or
4943         // union, but which actually declares a type outside of the
4944         // anonymous struct or union. It's okay.
4945       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4946         if (!MemRecord->isAnonymousStructOrUnion() &&
4947             MemRecord->getDeclName()) {
4948           // Visual C++ allows type definition in anonymous struct or union.
4949           if (getLangOpts().MicrosoftExt)
4950             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4951               << Record->isUnion();
4952           else {
4953             // This is a nested type declaration.
4954             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4955               << Record->isUnion();
4956             Invalid = true;
4957           }
4958         } else {
4959           // This is an anonymous type definition within another anonymous type.
4960           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4961           // not part of standard C++.
4962           Diag(MemRecord->getLocation(),
4963                diag::ext_anonymous_record_with_anonymous_type)
4964             << Record->isUnion();
4965         }
4966       } else if (isa<AccessSpecDecl>(Mem)) {
4967         // Any access specifier is fine.
4968       } else if (isa<StaticAssertDecl>(Mem)) {
4969         // In C++1z, static_assert declarations are also fine.
4970       } else {
4971         // We have something that isn't a non-static data
4972         // member. Complain about it.
4973         unsigned DK = diag::err_anonymous_record_bad_member;
4974         if (isa<TypeDecl>(Mem))
4975           DK = diag::err_anonymous_record_with_type;
4976         else if (isa<FunctionDecl>(Mem))
4977           DK = diag::err_anonymous_record_with_function;
4978         else if (isa<VarDecl>(Mem))
4979           DK = diag::err_anonymous_record_with_static;
4980 
4981         // Visual C++ allows type definition in anonymous struct or union.
4982         if (getLangOpts().MicrosoftExt &&
4983             DK == diag::err_anonymous_record_with_type)
4984           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4985             << Record->isUnion();
4986         else {
4987           Diag(Mem->getLocation(), DK) << Record->isUnion();
4988           Invalid = true;
4989         }
4990       }
4991     }
4992 
4993     // C++11 [class.union]p8 (DR1460):
4994     //   At most one variant member of a union may have a
4995     //   brace-or-equal-initializer.
4996     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4997         Owner->isRecord())
4998       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4999                                 cast<CXXRecordDecl>(Record));
5000   }
5001 
5002   if (!Record->isUnion() && !Owner->isRecord()) {
5003     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5004       << getLangOpts().CPlusPlus;
5005     Invalid = true;
5006   }
5007 
5008   // C++ [dcl.dcl]p3:
5009   //   [If there are no declarators], and except for the declaration of an
5010   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5011   //   names into the program
5012   // C++ [class.mem]p2:
5013   //   each such member-declaration shall either declare at least one member
5014   //   name of the class or declare at least one unnamed bit-field
5015   //
5016   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5017   if (getLangOpts().CPlusPlus && Record->field_empty())
5018     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5019 
5020   // Mock up a declarator.
5021   Declarator Dc(DS, DeclaratorContext::MemberContext);
5022   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5023   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5024 
5025   // Create a declaration for this anonymous struct/union.
5026   NamedDecl *Anon = nullptr;
5027   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5028     Anon = FieldDecl::Create(
5029         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5030         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5031         /*BitWidth=*/nullptr, /*Mutable=*/false,
5032         /*InitStyle=*/ICIS_NoInit);
5033     Anon->setAccess(AS);
5034     ProcessDeclAttributes(S, Anon, Dc);
5035 
5036     if (getLangOpts().CPlusPlus)
5037       FieldCollector->Add(cast<FieldDecl>(Anon));
5038   } else {
5039     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5040     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5041     if (SCSpec == DeclSpec::SCS_mutable) {
5042       // mutable can only appear on non-static class members, so it's always
5043       // an error here
5044       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5045       Invalid = true;
5046       SC = SC_None;
5047     }
5048 
5049     assert(DS.getAttributes().empty() && "No attribute expected");
5050     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5051                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5052                            Context.getTypeDeclType(Record), TInfo, SC);
5053 
5054     // Default-initialize the implicit variable. This initialization will be
5055     // trivial in almost all cases, except if a union member has an in-class
5056     // initializer:
5057     //   union { int n = 0; };
5058     ActOnUninitializedDecl(Anon);
5059   }
5060   Anon->setImplicit();
5061 
5062   // Mark this as an anonymous struct/union type.
5063   Record->setAnonymousStructOrUnion(true);
5064 
5065   // Add the anonymous struct/union object to the current
5066   // context. We'll be referencing this object when we refer to one of
5067   // its members.
5068   Owner->addDecl(Anon);
5069 
5070   // Inject the members of the anonymous struct/union into the owning
5071   // context and into the identifier resolver chain for name lookup
5072   // purposes.
5073   SmallVector<NamedDecl*, 2> Chain;
5074   Chain.push_back(Anon);
5075 
5076   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5077     Invalid = true;
5078 
5079   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5080     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5081       MangleNumberingContext *MCtx;
5082       Decl *ManglingContextDecl;
5083       std::tie(MCtx, ManglingContextDecl) =
5084           getCurrentMangleNumberContext(NewVD->getDeclContext());
5085       if (MCtx) {
5086         Context.setManglingNumber(
5087             NewVD, MCtx->getManglingNumber(
5088                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5089         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5090       }
5091     }
5092   }
5093 
5094   if (Invalid)
5095     Anon->setInvalidDecl();
5096 
5097   return Anon;
5098 }
5099 
5100 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5101 /// Microsoft C anonymous structure.
5102 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5103 /// Example:
5104 ///
5105 /// struct A { int a; };
5106 /// struct B { struct A; int b; };
5107 ///
5108 /// void foo() {
5109 ///   B var;
5110 ///   var.a = 3;
5111 /// }
5112 ///
5113 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5114                                            RecordDecl *Record) {
5115   assert(Record && "expected a record!");
5116 
5117   // Mock up a declarator.
5118   Declarator Dc(DS, DeclaratorContext::TypeNameContext);
5119   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5120   assert(TInfo && "couldn't build declarator info for anonymous struct");
5121 
5122   auto *ParentDecl = cast<RecordDecl>(CurContext);
5123   QualType RecTy = Context.getTypeDeclType(Record);
5124 
5125   // Create a declaration for this anonymous struct.
5126   NamedDecl *Anon =
5127       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5128                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5129                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5130                         /*InitStyle=*/ICIS_NoInit);
5131   Anon->setImplicit();
5132 
5133   // Add the anonymous struct object to the current context.
5134   CurContext->addDecl(Anon);
5135 
5136   // Inject the members of the anonymous struct into the current
5137   // context and into the identifier resolver chain for name lookup
5138   // purposes.
5139   SmallVector<NamedDecl*, 2> Chain;
5140   Chain.push_back(Anon);
5141 
5142   RecordDecl *RecordDef = Record->getDefinition();
5143   if (RequireCompleteType(Anon->getLocation(), RecTy,
5144                           diag::err_field_incomplete) ||
5145       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5146                                           AS_none, Chain)) {
5147     Anon->setInvalidDecl();
5148     ParentDecl->setInvalidDecl();
5149   }
5150 
5151   return Anon;
5152 }
5153 
5154 /// GetNameForDeclarator - Determine the full declaration name for the
5155 /// given Declarator.
5156 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5157   return GetNameFromUnqualifiedId(D.getName());
5158 }
5159 
5160 /// Retrieves the declaration name from a parsed unqualified-id.
5161 DeclarationNameInfo
5162 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5163   DeclarationNameInfo NameInfo;
5164   NameInfo.setLoc(Name.StartLocation);
5165 
5166   switch (Name.getKind()) {
5167 
5168   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5169   case UnqualifiedIdKind::IK_Identifier:
5170     NameInfo.setName(Name.Identifier);
5171     return NameInfo;
5172 
5173   case UnqualifiedIdKind::IK_DeductionGuideName: {
5174     // C++ [temp.deduct.guide]p3:
5175     //   The simple-template-id shall name a class template specialization.
5176     //   The template-name shall be the same identifier as the template-name
5177     //   of the simple-template-id.
5178     // These together intend to imply that the template-name shall name a
5179     // class template.
5180     // FIXME: template<typename T> struct X {};
5181     //        template<typename T> using Y = X<T>;
5182     //        Y(int) -> Y<int>;
5183     //   satisfies these rules but does not name a class template.
5184     TemplateName TN = Name.TemplateName.get().get();
5185     auto *Template = TN.getAsTemplateDecl();
5186     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5187       Diag(Name.StartLocation,
5188            diag::err_deduction_guide_name_not_class_template)
5189         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5190       if (Template)
5191         Diag(Template->getLocation(), diag::note_template_decl_here);
5192       return DeclarationNameInfo();
5193     }
5194 
5195     NameInfo.setName(
5196         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5197     return NameInfo;
5198   }
5199 
5200   case UnqualifiedIdKind::IK_OperatorFunctionId:
5201     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5202                                            Name.OperatorFunctionId.Operator));
5203     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
5204       = Name.OperatorFunctionId.SymbolLocations[0];
5205     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
5206       = Name.EndLocation.getRawEncoding();
5207     return NameInfo;
5208 
5209   case UnqualifiedIdKind::IK_LiteralOperatorId:
5210     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5211                                                            Name.Identifier));
5212     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5213     return NameInfo;
5214 
5215   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5216     TypeSourceInfo *TInfo;
5217     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5218     if (Ty.isNull())
5219       return DeclarationNameInfo();
5220     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5221                                                Context.getCanonicalType(Ty)));
5222     NameInfo.setNamedTypeInfo(TInfo);
5223     return NameInfo;
5224   }
5225 
5226   case UnqualifiedIdKind::IK_ConstructorName: {
5227     TypeSourceInfo *TInfo;
5228     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5229     if (Ty.isNull())
5230       return DeclarationNameInfo();
5231     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5232                                               Context.getCanonicalType(Ty)));
5233     NameInfo.setNamedTypeInfo(TInfo);
5234     return NameInfo;
5235   }
5236 
5237   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5238     // In well-formed code, we can only have a constructor
5239     // template-id that refers to the current context, so go there
5240     // to find the actual type being constructed.
5241     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5242     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5243       return DeclarationNameInfo();
5244 
5245     // Determine the type of the class being constructed.
5246     QualType CurClassType = Context.getTypeDeclType(CurClass);
5247 
5248     // FIXME: Check two things: that the template-id names the same type as
5249     // CurClassType, and that the template-id does not occur when the name
5250     // was qualified.
5251 
5252     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5253                                     Context.getCanonicalType(CurClassType)));
5254     // FIXME: should we retrieve TypeSourceInfo?
5255     NameInfo.setNamedTypeInfo(nullptr);
5256     return NameInfo;
5257   }
5258 
5259   case UnqualifiedIdKind::IK_DestructorName: {
5260     TypeSourceInfo *TInfo;
5261     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5262     if (Ty.isNull())
5263       return DeclarationNameInfo();
5264     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5265                                               Context.getCanonicalType(Ty)));
5266     NameInfo.setNamedTypeInfo(TInfo);
5267     return NameInfo;
5268   }
5269 
5270   case UnqualifiedIdKind::IK_TemplateId: {
5271     TemplateName TName = Name.TemplateId->Template.get();
5272     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5273     return Context.getNameForTemplate(TName, TNameLoc);
5274   }
5275 
5276   } // switch (Name.getKind())
5277 
5278   llvm_unreachable("Unknown name kind");
5279 }
5280 
5281 static QualType getCoreType(QualType Ty) {
5282   do {
5283     if (Ty->isPointerType() || Ty->isReferenceType())
5284       Ty = Ty->getPointeeType();
5285     else if (Ty->isArrayType())
5286       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5287     else
5288       return Ty.withoutLocalFastQualifiers();
5289   } while (true);
5290 }
5291 
5292 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5293 /// and Definition have "nearly" matching parameters. This heuristic is
5294 /// used to improve diagnostics in the case where an out-of-line function
5295 /// definition doesn't match any declaration within the class or namespace.
5296 /// Also sets Params to the list of indices to the parameters that differ
5297 /// between the declaration and the definition. If hasSimilarParameters
5298 /// returns true and Params is empty, then all of the parameters match.
5299 static bool hasSimilarParameters(ASTContext &Context,
5300                                      FunctionDecl *Declaration,
5301                                      FunctionDecl *Definition,
5302                                      SmallVectorImpl<unsigned> &Params) {
5303   Params.clear();
5304   if (Declaration->param_size() != Definition->param_size())
5305     return false;
5306   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5307     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5308     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5309 
5310     // The parameter types are identical
5311     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5312       continue;
5313 
5314     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5315     QualType DefParamBaseTy = getCoreType(DefParamTy);
5316     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5317     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5318 
5319     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5320         (DeclTyName && DeclTyName == DefTyName))
5321       Params.push_back(Idx);
5322     else  // The two parameters aren't even close
5323       return false;
5324   }
5325 
5326   return true;
5327 }
5328 
5329 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5330 /// declarator needs to be rebuilt in the current instantiation.
5331 /// Any bits of declarator which appear before the name are valid for
5332 /// consideration here.  That's specifically the type in the decl spec
5333 /// and the base type in any member-pointer chunks.
5334 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5335                                                     DeclarationName Name) {
5336   // The types we specifically need to rebuild are:
5337   //   - typenames, typeofs, and decltypes
5338   //   - types which will become injected class names
5339   // Of course, we also need to rebuild any type referencing such a
5340   // type.  It's safest to just say "dependent", but we call out a
5341   // few cases here.
5342 
5343   DeclSpec &DS = D.getMutableDeclSpec();
5344   switch (DS.getTypeSpecType()) {
5345   case DeclSpec::TST_typename:
5346   case DeclSpec::TST_typeofType:
5347   case DeclSpec::TST_underlyingType:
5348   case DeclSpec::TST_atomic: {
5349     // Grab the type from the parser.
5350     TypeSourceInfo *TSI = nullptr;
5351     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5352     if (T.isNull() || !T->isDependentType()) break;
5353 
5354     // Make sure there's a type source info.  This isn't really much
5355     // of a waste; most dependent types should have type source info
5356     // attached already.
5357     if (!TSI)
5358       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5359 
5360     // Rebuild the type in the current instantiation.
5361     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5362     if (!TSI) return true;
5363 
5364     // Store the new type back in the decl spec.
5365     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5366     DS.UpdateTypeRep(LocType);
5367     break;
5368   }
5369 
5370   case DeclSpec::TST_decltype:
5371   case DeclSpec::TST_typeofExpr: {
5372     Expr *E = DS.getRepAsExpr();
5373     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5374     if (Result.isInvalid()) return true;
5375     DS.UpdateExprRep(Result.get());
5376     break;
5377   }
5378 
5379   default:
5380     // Nothing to do for these decl specs.
5381     break;
5382   }
5383 
5384   // It doesn't matter what order we do this in.
5385   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5386     DeclaratorChunk &Chunk = D.getTypeObject(I);
5387 
5388     // The only type information in the declarator which can come
5389     // before the declaration name is the base type of a member
5390     // pointer.
5391     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5392       continue;
5393 
5394     // Rebuild the scope specifier in-place.
5395     CXXScopeSpec &SS = Chunk.Mem.Scope();
5396     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5397       return true;
5398   }
5399 
5400   return false;
5401 }
5402 
5403 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5404   D.setFunctionDefinitionKind(FDK_Declaration);
5405   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5406 
5407   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5408       Dcl && Dcl->getDeclContext()->isFileContext())
5409     Dcl->setTopLevelDeclInObjCContainer();
5410 
5411   if (getLangOpts().OpenCL)
5412     setCurrentOpenCLExtensionForDecl(Dcl);
5413 
5414   return Dcl;
5415 }
5416 
5417 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5418 ///   If T is the name of a class, then each of the following shall have a
5419 ///   name different from T:
5420 ///     - every static data member of class T;
5421 ///     - every member function of class T
5422 ///     - every member of class T that is itself a type;
5423 /// \returns true if the declaration name violates these rules.
5424 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5425                                    DeclarationNameInfo NameInfo) {
5426   DeclarationName Name = NameInfo.getName();
5427 
5428   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5429   while (Record && Record->isAnonymousStructOrUnion())
5430     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5431   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5432     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5433     return true;
5434   }
5435 
5436   return false;
5437 }
5438 
5439 /// Diagnose a declaration whose declarator-id has the given
5440 /// nested-name-specifier.
5441 ///
5442 /// \param SS The nested-name-specifier of the declarator-id.
5443 ///
5444 /// \param DC The declaration context to which the nested-name-specifier
5445 /// resolves.
5446 ///
5447 /// \param Name The name of the entity being declared.
5448 ///
5449 /// \param Loc The location of the name of the entity being declared.
5450 ///
5451 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5452 /// we're declaring an explicit / partial specialization / instantiation.
5453 ///
5454 /// \returns true if we cannot safely recover from this error, false otherwise.
5455 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5456                                         DeclarationName Name,
5457                                         SourceLocation Loc, bool IsTemplateId) {
5458   DeclContext *Cur = CurContext;
5459   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5460     Cur = Cur->getParent();
5461 
5462   // If the user provided a superfluous scope specifier that refers back to the
5463   // class in which the entity is already declared, diagnose and ignore it.
5464   //
5465   // class X {
5466   //   void X::f();
5467   // };
5468   //
5469   // Note, it was once ill-formed to give redundant qualification in all
5470   // contexts, but that rule was removed by DR482.
5471   if (Cur->Equals(DC)) {
5472     if (Cur->isRecord()) {
5473       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5474                                       : diag::err_member_extra_qualification)
5475         << Name << FixItHint::CreateRemoval(SS.getRange());
5476       SS.clear();
5477     } else {
5478       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5479     }
5480     return false;
5481   }
5482 
5483   // Check whether the qualifying scope encloses the scope of the original
5484   // declaration. For a template-id, we perform the checks in
5485   // CheckTemplateSpecializationScope.
5486   if (!Cur->Encloses(DC) && !IsTemplateId) {
5487     if (Cur->isRecord())
5488       Diag(Loc, diag::err_member_qualification)
5489         << Name << SS.getRange();
5490     else if (isa<TranslationUnitDecl>(DC))
5491       Diag(Loc, diag::err_invalid_declarator_global_scope)
5492         << Name << SS.getRange();
5493     else if (isa<FunctionDecl>(Cur))
5494       Diag(Loc, diag::err_invalid_declarator_in_function)
5495         << Name << SS.getRange();
5496     else if (isa<BlockDecl>(Cur))
5497       Diag(Loc, diag::err_invalid_declarator_in_block)
5498         << Name << SS.getRange();
5499     else
5500       Diag(Loc, diag::err_invalid_declarator_scope)
5501       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5502 
5503     return true;
5504   }
5505 
5506   if (Cur->isRecord()) {
5507     // Cannot qualify members within a class.
5508     Diag(Loc, diag::err_member_qualification)
5509       << Name << SS.getRange();
5510     SS.clear();
5511 
5512     // C++ constructors and destructors with incorrect scopes can break
5513     // our AST invariants by having the wrong underlying types. If
5514     // that's the case, then drop this declaration entirely.
5515     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5516          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5517         !Context.hasSameType(Name.getCXXNameType(),
5518                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5519       return true;
5520 
5521     return false;
5522   }
5523 
5524   // C++11 [dcl.meaning]p1:
5525   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5526   //   not begin with a decltype-specifer"
5527   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5528   while (SpecLoc.getPrefix())
5529     SpecLoc = SpecLoc.getPrefix();
5530   if (dyn_cast_or_null<DecltypeType>(
5531         SpecLoc.getNestedNameSpecifier()->getAsType()))
5532     Diag(Loc, diag::err_decltype_in_declarator)
5533       << SpecLoc.getTypeLoc().getSourceRange();
5534 
5535   return false;
5536 }
5537 
5538 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5539                                   MultiTemplateParamsArg TemplateParamLists) {
5540   // TODO: consider using NameInfo for diagnostic.
5541   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5542   DeclarationName Name = NameInfo.getName();
5543 
5544   // All of these full declarators require an identifier.  If it doesn't have
5545   // one, the ParsedFreeStandingDeclSpec action should be used.
5546   if (D.isDecompositionDeclarator()) {
5547     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5548   } else if (!Name) {
5549     if (!D.isInvalidType())  // Reject this if we think it is valid.
5550       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5551           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5552     return nullptr;
5553   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5554     return nullptr;
5555 
5556   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5557   // we find one that is.
5558   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5559          (S->getFlags() & Scope::TemplateParamScope) != 0)
5560     S = S->getParent();
5561 
5562   DeclContext *DC = CurContext;
5563   if (D.getCXXScopeSpec().isInvalid())
5564     D.setInvalidType();
5565   else if (D.getCXXScopeSpec().isSet()) {
5566     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5567                                         UPPC_DeclarationQualifier))
5568       return nullptr;
5569 
5570     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5571     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5572     if (!DC || isa<EnumDecl>(DC)) {
5573       // If we could not compute the declaration context, it's because the
5574       // declaration context is dependent but does not refer to a class,
5575       // class template, or class template partial specialization. Complain
5576       // and return early, to avoid the coming semantic disaster.
5577       Diag(D.getIdentifierLoc(),
5578            diag::err_template_qualified_declarator_no_match)
5579         << D.getCXXScopeSpec().getScopeRep()
5580         << D.getCXXScopeSpec().getRange();
5581       return nullptr;
5582     }
5583     bool IsDependentContext = DC->isDependentContext();
5584 
5585     if (!IsDependentContext &&
5586         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5587       return nullptr;
5588 
5589     // If a class is incomplete, do not parse entities inside it.
5590     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5591       Diag(D.getIdentifierLoc(),
5592            diag::err_member_def_undefined_record)
5593         << Name << DC << D.getCXXScopeSpec().getRange();
5594       return nullptr;
5595     }
5596     if (!D.getDeclSpec().isFriendSpecified()) {
5597       if (diagnoseQualifiedDeclaration(
5598               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5599               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5600         if (DC->isRecord())
5601           return nullptr;
5602 
5603         D.setInvalidType();
5604       }
5605     }
5606 
5607     // Check whether we need to rebuild the type of the given
5608     // declaration in the current instantiation.
5609     if (EnteringContext && IsDependentContext &&
5610         TemplateParamLists.size() != 0) {
5611       ContextRAII SavedContext(*this, DC);
5612       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5613         D.setInvalidType();
5614     }
5615   }
5616 
5617   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5618   QualType R = TInfo->getType();
5619 
5620   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5621                                       UPPC_DeclarationType))
5622     D.setInvalidType();
5623 
5624   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5625                         forRedeclarationInCurContext());
5626 
5627   // See if this is a redefinition of a variable in the same scope.
5628   if (!D.getCXXScopeSpec().isSet()) {
5629     bool IsLinkageLookup = false;
5630     bool CreateBuiltins = false;
5631 
5632     // If the declaration we're planning to build will be a function
5633     // or object with linkage, then look for another declaration with
5634     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5635     //
5636     // If the declaration we're planning to build will be declared with
5637     // external linkage in the translation unit, create any builtin with
5638     // the same name.
5639     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5640       /* Do nothing*/;
5641     else if (CurContext->isFunctionOrMethod() &&
5642              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5643               R->isFunctionType())) {
5644       IsLinkageLookup = true;
5645       CreateBuiltins =
5646           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5647     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5648                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5649       CreateBuiltins = true;
5650 
5651     if (IsLinkageLookup) {
5652       Previous.clear(LookupRedeclarationWithLinkage);
5653       Previous.setRedeclarationKind(ForExternalRedeclaration);
5654     }
5655 
5656     LookupName(Previous, S, CreateBuiltins);
5657   } else { // Something like "int foo::x;"
5658     LookupQualifiedName(Previous, DC);
5659 
5660     // C++ [dcl.meaning]p1:
5661     //   When the declarator-id is qualified, the declaration shall refer to a
5662     //  previously declared member of the class or namespace to which the
5663     //  qualifier refers (or, in the case of a namespace, of an element of the
5664     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5665     //  thereof; [...]
5666     //
5667     // Note that we already checked the context above, and that we do not have
5668     // enough information to make sure that Previous contains the declaration
5669     // we want to match. For example, given:
5670     //
5671     //   class X {
5672     //     void f();
5673     //     void f(float);
5674     //   };
5675     //
5676     //   void X::f(int) { } // ill-formed
5677     //
5678     // In this case, Previous will point to the overload set
5679     // containing the two f's declared in X, but neither of them
5680     // matches.
5681 
5682     // C++ [dcl.meaning]p1:
5683     //   [...] the member shall not merely have been introduced by a
5684     //   using-declaration in the scope of the class or namespace nominated by
5685     //   the nested-name-specifier of the declarator-id.
5686     RemoveUsingDecls(Previous);
5687   }
5688 
5689   if (Previous.isSingleResult() &&
5690       Previous.getFoundDecl()->isTemplateParameter()) {
5691     // Maybe we will complain about the shadowed template parameter.
5692     if (!D.isInvalidType())
5693       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5694                                       Previous.getFoundDecl());
5695 
5696     // Just pretend that we didn't see the previous declaration.
5697     Previous.clear();
5698   }
5699 
5700   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5701     // Forget that the previous declaration is the injected-class-name.
5702     Previous.clear();
5703 
5704   // In C++, the previous declaration we find might be a tag type
5705   // (class or enum). In this case, the new declaration will hide the
5706   // tag type. Note that this applies to functions, function templates, and
5707   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5708   if (Previous.isSingleTagDecl() &&
5709       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5710       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5711     Previous.clear();
5712 
5713   // Check that there are no default arguments other than in the parameters
5714   // of a function declaration (C++ only).
5715   if (getLangOpts().CPlusPlus)
5716     CheckExtraCXXDefaultArguments(D);
5717 
5718   NamedDecl *New;
5719 
5720   bool AddToScope = true;
5721   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5722     if (TemplateParamLists.size()) {
5723       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5724       return nullptr;
5725     }
5726 
5727     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5728   } else if (R->isFunctionType()) {
5729     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5730                                   TemplateParamLists,
5731                                   AddToScope);
5732   } else {
5733     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5734                                   AddToScope);
5735   }
5736 
5737   if (!New)
5738     return nullptr;
5739 
5740   // If this has an identifier and is not a function template specialization,
5741   // add it to the scope stack.
5742   if (New->getDeclName() && AddToScope)
5743     PushOnScopeChains(New, S);
5744 
5745   if (isInOpenMPDeclareTargetContext())
5746     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5747 
5748   return New;
5749 }
5750 
5751 /// Helper method to turn variable array types into constant array
5752 /// types in certain situations which would otherwise be errors (for
5753 /// GCC compatibility).
5754 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5755                                                     ASTContext &Context,
5756                                                     bool &SizeIsNegative,
5757                                                     llvm::APSInt &Oversized) {
5758   // This method tries to turn a variable array into a constant
5759   // array even when the size isn't an ICE.  This is necessary
5760   // for compatibility with code that depends on gcc's buggy
5761   // constant expression folding, like struct {char x[(int)(char*)2];}
5762   SizeIsNegative = false;
5763   Oversized = 0;
5764 
5765   if (T->isDependentType())
5766     return QualType();
5767 
5768   QualifierCollector Qs;
5769   const Type *Ty = Qs.strip(T);
5770 
5771   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5772     QualType Pointee = PTy->getPointeeType();
5773     QualType FixedType =
5774         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5775                                             Oversized);
5776     if (FixedType.isNull()) return FixedType;
5777     FixedType = Context.getPointerType(FixedType);
5778     return Qs.apply(Context, FixedType);
5779   }
5780   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5781     QualType Inner = PTy->getInnerType();
5782     QualType FixedType =
5783         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5784                                             Oversized);
5785     if (FixedType.isNull()) return FixedType;
5786     FixedType = Context.getParenType(FixedType);
5787     return Qs.apply(Context, FixedType);
5788   }
5789 
5790   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5791   if (!VLATy)
5792     return QualType();
5793   // FIXME: We should probably handle this case
5794   if (VLATy->getElementType()->isVariablyModifiedType())
5795     return QualType();
5796 
5797   Expr::EvalResult Result;
5798   if (!VLATy->getSizeExpr() ||
5799       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5800     return QualType();
5801 
5802   llvm::APSInt Res = Result.Val.getInt();
5803 
5804   // Check whether the array size is negative.
5805   if (Res.isSigned() && Res.isNegative()) {
5806     SizeIsNegative = true;
5807     return QualType();
5808   }
5809 
5810   // Check whether the array is too large to be addressed.
5811   unsigned ActiveSizeBits
5812     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5813                                               Res);
5814   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5815     Oversized = Res;
5816     return QualType();
5817   }
5818 
5819   return Context.getConstantArrayType(
5820       VLATy->getElementType(), Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
5821 }
5822 
5823 static void
5824 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5825   SrcTL = SrcTL.getUnqualifiedLoc();
5826   DstTL = DstTL.getUnqualifiedLoc();
5827   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5828     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5829     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5830                                       DstPTL.getPointeeLoc());
5831     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5832     return;
5833   }
5834   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5835     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5836     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5837                                       DstPTL.getInnerLoc());
5838     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5839     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5840     return;
5841   }
5842   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5843   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5844   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5845   TypeLoc DstElemTL = DstATL.getElementLoc();
5846   DstElemTL.initializeFullCopy(SrcElemTL);
5847   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5848   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5849   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5850 }
5851 
5852 /// Helper method to turn variable array types into constant array
5853 /// types in certain situations which would otherwise be errors (for
5854 /// GCC compatibility).
5855 static TypeSourceInfo*
5856 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5857                                               ASTContext &Context,
5858                                               bool &SizeIsNegative,
5859                                               llvm::APSInt &Oversized) {
5860   QualType FixedTy
5861     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5862                                           SizeIsNegative, Oversized);
5863   if (FixedTy.isNull())
5864     return nullptr;
5865   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5866   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5867                                     FixedTInfo->getTypeLoc());
5868   return FixedTInfo;
5869 }
5870 
5871 /// Register the given locally-scoped extern "C" declaration so
5872 /// that it can be found later for redeclarations. We include any extern "C"
5873 /// declaration that is not visible in the translation unit here, not just
5874 /// function-scope declarations.
5875 void
5876 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5877   if (!getLangOpts().CPlusPlus &&
5878       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5879     // Don't need to track declarations in the TU in C.
5880     return;
5881 
5882   // Note that we have a locally-scoped external with this name.
5883   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5884 }
5885 
5886 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5887   // FIXME: We can have multiple results via __attribute__((overloadable)).
5888   auto Result = Context.getExternCContextDecl()->lookup(Name);
5889   return Result.empty() ? nullptr : *Result.begin();
5890 }
5891 
5892 /// Diagnose function specifiers on a declaration of an identifier that
5893 /// does not identify a function.
5894 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5895   // FIXME: We should probably indicate the identifier in question to avoid
5896   // confusion for constructs like "virtual int a(), b;"
5897   if (DS.isVirtualSpecified())
5898     Diag(DS.getVirtualSpecLoc(),
5899          diag::err_virtual_non_function);
5900 
5901   if (DS.hasExplicitSpecifier())
5902     Diag(DS.getExplicitSpecLoc(),
5903          diag::err_explicit_non_function);
5904 
5905   if (DS.isNoreturnSpecified())
5906     Diag(DS.getNoreturnSpecLoc(),
5907          diag::err_noreturn_non_function);
5908 }
5909 
5910 NamedDecl*
5911 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5912                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5913   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5914   if (D.getCXXScopeSpec().isSet()) {
5915     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5916       << D.getCXXScopeSpec().getRange();
5917     D.setInvalidType();
5918     // Pretend we didn't see the scope specifier.
5919     DC = CurContext;
5920     Previous.clear();
5921   }
5922 
5923   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5924 
5925   if (D.getDeclSpec().isInlineSpecified())
5926     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5927         << getLangOpts().CPlusPlus17;
5928   if (D.getDeclSpec().hasConstexprSpecifier())
5929     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5930         << 1 << D.getDeclSpec().getConstexprSpecifier();
5931 
5932   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
5933     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
5934       Diag(D.getName().StartLocation,
5935            diag::err_deduction_guide_invalid_specifier)
5936           << "typedef";
5937     else
5938       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5939           << D.getName().getSourceRange();
5940     return nullptr;
5941   }
5942 
5943   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5944   if (!NewTD) return nullptr;
5945 
5946   // Handle attributes prior to checking for duplicates in MergeVarDecl
5947   ProcessDeclAttributes(S, NewTD, D);
5948 
5949   CheckTypedefForVariablyModifiedType(S, NewTD);
5950 
5951   bool Redeclaration = D.isRedeclaration();
5952   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5953   D.setRedeclaration(Redeclaration);
5954   return ND;
5955 }
5956 
5957 void
5958 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5959   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5960   // then it shall have block scope.
5961   // Note that variably modified types must be fixed before merging the decl so
5962   // that redeclarations will match.
5963   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5964   QualType T = TInfo->getType();
5965   if (T->isVariablyModifiedType()) {
5966     setFunctionHasBranchProtectedScope();
5967 
5968     if (S->getFnParent() == nullptr) {
5969       bool SizeIsNegative;
5970       llvm::APSInt Oversized;
5971       TypeSourceInfo *FixedTInfo =
5972         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5973                                                       SizeIsNegative,
5974                                                       Oversized);
5975       if (FixedTInfo) {
5976         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5977         NewTD->setTypeSourceInfo(FixedTInfo);
5978       } else {
5979         if (SizeIsNegative)
5980           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5981         else if (T->isVariableArrayType())
5982           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5983         else if (Oversized.getBoolValue())
5984           Diag(NewTD->getLocation(), diag::err_array_too_large)
5985             << Oversized.toString(10);
5986         else
5987           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5988         NewTD->setInvalidDecl();
5989       }
5990     }
5991   }
5992 }
5993 
5994 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5995 /// declares a typedef-name, either using the 'typedef' type specifier or via
5996 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5997 NamedDecl*
5998 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5999                            LookupResult &Previous, bool &Redeclaration) {
6000 
6001   // Find the shadowed declaration before filtering for scope.
6002   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6003 
6004   // Merge the decl with the existing one if appropriate. If the decl is
6005   // in an outer scope, it isn't the same thing.
6006   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6007                        /*AllowInlineNamespace*/false);
6008   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6009   if (!Previous.empty()) {
6010     Redeclaration = true;
6011     MergeTypedefNameDecl(S, NewTD, Previous);
6012   } else {
6013     inferGslPointerAttribute(NewTD);
6014   }
6015 
6016   if (ShadowedDecl && !Redeclaration)
6017     CheckShadow(NewTD, ShadowedDecl, Previous);
6018 
6019   // If this is the C FILE type, notify the AST context.
6020   if (IdentifierInfo *II = NewTD->getIdentifier())
6021     if (!NewTD->isInvalidDecl() &&
6022         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6023       if (II->isStr("FILE"))
6024         Context.setFILEDecl(NewTD);
6025       else if (II->isStr("jmp_buf"))
6026         Context.setjmp_bufDecl(NewTD);
6027       else if (II->isStr("sigjmp_buf"))
6028         Context.setsigjmp_bufDecl(NewTD);
6029       else if (II->isStr("ucontext_t"))
6030         Context.setucontext_tDecl(NewTD);
6031     }
6032 
6033   return NewTD;
6034 }
6035 
6036 /// Determines whether the given declaration is an out-of-scope
6037 /// previous declaration.
6038 ///
6039 /// This routine should be invoked when name lookup has found a
6040 /// previous declaration (PrevDecl) that is not in the scope where a
6041 /// new declaration by the same name is being introduced. If the new
6042 /// declaration occurs in a local scope, previous declarations with
6043 /// linkage may still be considered previous declarations (C99
6044 /// 6.2.2p4-5, C++ [basic.link]p6).
6045 ///
6046 /// \param PrevDecl the previous declaration found by name
6047 /// lookup
6048 ///
6049 /// \param DC the context in which the new declaration is being
6050 /// declared.
6051 ///
6052 /// \returns true if PrevDecl is an out-of-scope previous declaration
6053 /// for a new delcaration with the same name.
6054 static bool
6055 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6056                                 ASTContext &Context) {
6057   if (!PrevDecl)
6058     return false;
6059 
6060   if (!PrevDecl->hasLinkage())
6061     return false;
6062 
6063   if (Context.getLangOpts().CPlusPlus) {
6064     // C++ [basic.link]p6:
6065     //   If there is a visible declaration of an entity with linkage
6066     //   having the same name and type, ignoring entities declared
6067     //   outside the innermost enclosing namespace scope, the block
6068     //   scope declaration declares that same entity and receives the
6069     //   linkage of the previous declaration.
6070     DeclContext *OuterContext = DC->getRedeclContext();
6071     if (!OuterContext->isFunctionOrMethod())
6072       // This rule only applies to block-scope declarations.
6073       return false;
6074 
6075     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6076     if (PrevOuterContext->isRecord())
6077       // We found a member function: ignore it.
6078       return false;
6079 
6080     // Find the innermost enclosing namespace for the new and
6081     // previous declarations.
6082     OuterContext = OuterContext->getEnclosingNamespaceContext();
6083     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6084 
6085     // The previous declaration is in a different namespace, so it
6086     // isn't the same function.
6087     if (!OuterContext->Equals(PrevOuterContext))
6088       return false;
6089   }
6090 
6091   return true;
6092 }
6093 
6094 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6095   CXXScopeSpec &SS = D.getCXXScopeSpec();
6096   if (!SS.isSet()) return;
6097   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6098 }
6099 
6100 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6101   QualType type = decl->getType();
6102   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6103   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6104     // Various kinds of declaration aren't allowed to be __autoreleasing.
6105     unsigned kind = -1U;
6106     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6107       if (var->hasAttr<BlocksAttr>())
6108         kind = 0; // __block
6109       else if (!var->hasLocalStorage())
6110         kind = 1; // global
6111     } else if (isa<ObjCIvarDecl>(decl)) {
6112       kind = 3; // ivar
6113     } else if (isa<FieldDecl>(decl)) {
6114       kind = 2; // field
6115     }
6116 
6117     if (kind != -1U) {
6118       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6119         << kind;
6120     }
6121   } else if (lifetime == Qualifiers::OCL_None) {
6122     // Try to infer lifetime.
6123     if (!type->isObjCLifetimeType())
6124       return false;
6125 
6126     lifetime = type->getObjCARCImplicitLifetime();
6127     type = Context.getLifetimeQualifiedType(type, lifetime);
6128     decl->setType(type);
6129   }
6130 
6131   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6132     // Thread-local variables cannot have lifetime.
6133     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6134         var->getTLSKind()) {
6135       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6136         << var->getType();
6137       return true;
6138     }
6139   }
6140 
6141   return false;
6142 }
6143 
6144 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6145   if (Decl->getType().hasAddressSpace())
6146     return;
6147   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6148     QualType Type = Var->getType();
6149     if (Type->isSamplerT() || Type->isVoidType())
6150       return;
6151     LangAS ImplAS = LangAS::opencl_private;
6152     if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) &&
6153         Var->hasGlobalStorage())
6154       ImplAS = LangAS::opencl_global;
6155     // If the original type from a decayed type is an array type and that array
6156     // type has no address space yet, deduce it now.
6157     if (auto DT = dyn_cast<DecayedType>(Type)) {
6158       auto OrigTy = DT->getOriginalType();
6159       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6160         // Add the address space to the original array type and then propagate
6161         // that to the element type through `getAsArrayType`.
6162         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6163         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6164         // Re-generate the decayed type.
6165         Type = Context.getDecayedType(OrigTy);
6166       }
6167     }
6168     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6169     // Apply any qualifiers (including address space) from the array type to
6170     // the element type. This implements C99 6.7.3p8: "If the specification of
6171     // an array type includes any type qualifiers, the element type is so
6172     // qualified, not the array type."
6173     if (Type->isArrayType())
6174       Type = QualType(Context.getAsArrayType(Type), 0);
6175     Decl->setType(Type);
6176   }
6177 }
6178 
6179 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6180   // Ensure that an auto decl is deduced otherwise the checks below might cache
6181   // the wrong linkage.
6182   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6183 
6184   // 'weak' only applies to declarations with external linkage.
6185   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6186     if (!ND.isExternallyVisible()) {
6187       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6188       ND.dropAttr<WeakAttr>();
6189     }
6190   }
6191   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6192     if (ND.isExternallyVisible()) {
6193       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6194       ND.dropAttr<WeakRefAttr>();
6195       ND.dropAttr<AliasAttr>();
6196     }
6197   }
6198 
6199   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6200     if (VD->hasInit()) {
6201       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6202         assert(VD->isThisDeclarationADefinition() &&
6203                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6204         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6205         VD->dropAttr<AliasAttr>();
6206       }
6207     }
6208   }
6209 
6210   // 'selectany' only applies to externally visible variable declarations.
6211   // It does not apply to functions.
6212   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6213     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6214       S.Diag(Attr->getLocation(),
6215              diag::err_attribute_selectany_non_extern_data);
6216       ND.dropAttr<SelectAnyAttr>();
6217     }
6218   }
6219 
6220   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6221     auto *VD = dyn_cast<VarDecl>(&ND);
6222     bool IsAnonymousNS = false;
6223     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6224     if (VD) {
6225       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6226       while (NS && !IsAnonymousNS) {
6227         IsAnonymousNS = NS->isAnonymousNamespace();
6228         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6229       }
6230     }
6231     // dll attributes require external linkage. Static locals may have external
6232     // linkage but still cannot be explicitly imported or exported.
6233     // In Microsoft mode, a variable defined in anonymous namespace must have
6234     // external linkage in order to be exported.
6235     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6236     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6237         (!AnonNSInMicrosoftMode &&
6238          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6239       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6240         << &ND << Attr;
6241       ND.setInvalidDecl();
6242     }
6243   }
6244 
6245   // Virtual functions cannot be marked as 'notail'.
6246   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
6247     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
6248       if (MD->isVirtual()) {
6249         S.Diag(ND.getLocation(),
6250                diag::err_invalid_attribute_on_virtual_function)
6251             << Attr;
6252         ND.dropAttr<NotTailCalledAttr>();
6253       }
6254 
6255   // Check the attributes on the function type, if any.
6256   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6257     // Don't declare this variable in the second operand of the for-statement;
6258     // GCC miscompiles that by ending its lifetime before evaluating the
6259     // third operand. See gcc.gnu.org/PR86769.
6260     AttributedTypeLoc ATL;
6261     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6262          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6263          TL = ATL.getModifiedLoc()) {
6264       // The [[lifetimebound]] attribute can be applied to the implicit object
6265       // parameter of a non-static member function (other than a ctor or dtor)
6266       // by applying it to the function type.
6267       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6268         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6269         if (!MD || MD->isStatic()) {
6270           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6271               << !MD << A->getRange();
6272         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6273           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6274               << isa<CXXDestructorDecl>(MD) << A->getRange();
6275         }
6276       }
6277     }
6278   }
6279 }
6280 
6281 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6282                                            NamedDecl *NewDecl,
6283                                            bool IsSpecialization,
6284                                            bool IsDefinition) {
6285   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6286     return;
6287 
6288   bool IsTemplate = false;
6289   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6290     OldDecl = OldTD->getTemplatedDecl();
6291     IsTemplate = true;
6292     if (!IsSpecialization)
6293       IsDefinition = false;
6294   }
6295   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6296     NewDecl = NewTD->getTemplatedDecl();
6297     IsTemplate = true;
6298   }
6299 
6300   if (!OldDecl || !NewDecl)
6301     return;
6302 
6303   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6304   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6305   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6306   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6307 
6308   // dllimport and dllexport are inheritable attributes so we have to exclude
6309   // inherited attribute instances.
6310   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6311                     (NewExportAttr && !NewExportAttr->isInherited());
6312 
6313   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6314   // the only exception being explicit specializations.
6315   // Implicitly generated declarations are also excluded for now because there
6316   // is no other way to switch these to use dllimport or dllexport.
6317   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6318 
6319   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6320     // Allow with a warning for free functions and global variables.
6321     bool JustWarn = false;
6322     if (!OldDecl->isCXXClassMember()) {
6323       auto *VD = dyn_cast<VarDecl>(OldDecl);
6324       if (VD && !VD->getDescribedVarTemplate())
6325         JustWarn = true;
6326       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6327       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6328         JustWarn = true;
6329     }
6330 
6331     // We cannot change a declaration that's been used because IR has already
6332     // been emitted. Dllimported functions will still work though (modulo
6333     // address equality) as they can use the thunk.
6334     if (OldDecl->isUsed())
6335       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6336         JustWarn = false;
6337 
6338     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6339                                : diag::err_attribute_dll_redeclaration;
6340     S.Diag(NewDecl->getLocation(), DiagID)
6341         << NewDecl
6342         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6343     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6344     if (!JustWarn) {
6345       NewDecl->setInvalidDecl();
6346       return;
6347     }
6348   }
6349 
6350   // A redeclaration is not allowed to drop a dllimport attribute, the only
6351   // exceptions being inline function definitions (except for function
6352   // templates), local extern declarations, qualified friend declarations or
6353   // special MSVC extension: in the last case, the declaration is treated as if
6354   // it were marked dllexport.
6355   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6356   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6357   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6358     // Ignore static data because out-of-line definitions are diagnosed
6359     // separately.
6360     IsStaticDataMember = VD->isStaticDataMember();
6361     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6362                    VarDecl::DeclarationOnly;
6363   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6364     IsInline = FD->isInlined();
6365     IsQualifiedFriend = FD->getQualifier() &&
6366                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6367   }
6368 
6369   if (OldImportAttr && !HasNewAttr &&
6370       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6371       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6372     if (IsMicrosoft && IsDefinition) {
6373       S.Diag(NewDecl->getLocation(),
6374              diag::warn_redeclaration_without_import_attribute)
6375           << NewDecl;
6376       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6377       NewDecl->dropAttr<DLLImportAttr>();
6378       NewDecl->addAttr(
6379           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6380     } else {
6381       S.Diag(NewDecl->getLocation(),
6382              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6383           << NewDecl << OldImportAttr;
6384       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6385       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6386       OldDecl->dropAttr<DLLImportAttr>();
6387       NewDecl->dropAttr<DLLImportAttr>();
6388     }
6389   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6390     // In MinGW, seeing a function declared inline drops the dllimport
6391     // attribute.
6392     OldDecl->dropAttr<DLLImportAttr>();
6393     NewDecl->dropAttr<DLLImportAttr>();
6394     S.Diag(NewDecl->getLocation(),
6395            diag::warn_dllimport_dropped_from_inline_function)
6396         << NewDecl << OldImportAttr;
6397   }
6398 
6399   // A specialization of a class template member function is processed here
6400   // since it's a redeclaration. If the parent class is dllexport, the
6401   // specialization inherits that attribute. This doesn't happen automatically
6402   // since the parent class isn't instantiated until later.
6403   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6404     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6405         !NewImportAttr && !NewExportAttr) {
6406       if (const DLLExportAttr *ParentExportAttr =
6407               MD->getParent()->getAttr<DLLExportAttr>()) {
6408         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6409         NewAttr->setInherited(true);
6410         NewDecl->addAttr(NewAttr);
6411       }
6412     }
6413   }
6414 }
6415 
6416 /// Given that we are within the definition of the given function,
6417 /// will that definition behave like C99's 'inline', where the
6418 /// definition is discarded except for optimization purposes?
6419 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6420   // Try to avoid calling GetGVALinkageForFunction.
6421 
6422   // All cases of this require the 'inline' keyword.
6423   if (!FD->isInlined()) return false;
6424 
6425   // This is only possible in C++ with the gnu_inline attribute.
6426   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6427     return false;
6428 
6429   // Okay, go ahead and call the relatively-more-expensive function.
6430   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6431 }
6432 
6433 /// Determine whether a variable is extern "C" prior to attaching
6434 /// an initializer. We can't just call isExternC() here, because that
6435 /// will also compute and cache whether the declaration is externally
6436 /// visible, which might change when we attach the initializer.
6437 ///
6438 /// This can only be used if the declaration is known to not be a
6439 /// redeclaration of an internal linkage declaration.
6440 ///
6441 /// For instance:
6442 ///
6443 ///   auto x = []{};
6444 ///
6445 /// Attaching the initializer here makes this declaration not externally
6446 /// visible, because its type has internal linkage.
6447 ///
6448 /// FIXME: This is a hack.
6449 template<typename T>
6450 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6451   if (S.getLangOpts().CPlusPlus) {
6452     // In C++, the overloadable attribute negates the effects of extern "C".
6453     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6454       return false;
6455 
6456     // So do CUDA's host/device attributes.
6457     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6458                                  D->template hasAttr<CUDAHostAttr>()))
6459       return false;
6460   }
6461   return D->isExternC();
6462 }
6463 
6464 static bool shouldConsiderLinkage(const VarDecl *VD) {
6465   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6466   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6467       isa<OMPDeclareMapperDecl>(DC))
6468     return VD->hasExternalStorage();
6469   if (DC->isFileContext())
6470     return true;
6471   if (DC->isRecord())
6472     return false;
6473   if (isa<RequiresExprBodyDecl>(DC))
6474     return false;
6475   llvm_unreachable("Unexpected context");
6476 }
6477 
6478 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6479   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6480   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6481       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6482     return true;
6483   if (DC->isRecord())
6484     return false;
6485   llvm_unreachable("Unexpected context");
6486 }
6487 
6488 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6489                           ParsedAttr::Kind Kind) {
6490   // Check decl attributes on the DeclSpec.
6491   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6492     return true;
6493 
6494   // Walk the declarator structure, checking decl attributes that were in a type
6495   // position to the decl itself.
6496   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6497     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6498       return true;
6499   }
6500 
6501   // Finally, check attributes on the decl itself.
6502   return PD.getAttributes().hasAttribute(Kind);
6503 }
6504 
6505 /// Adjust the \c DeclContext for a function or variable that might be a
6506 /// function-local external declaration.
6507 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6508   if (!DC->isFunctionOrMethod())
6509     return false;
6510 
6511   // If this is a local extern function or variable declared within a function
6512   // template, don't add it into the enclosing namespace scope until it is
6513   // instantiated; it might have a dependent type right now.
6514   if (DC->isDependentContext())
6515     return true;
6516 
6517   // C++11 [basic.link]p7:
6518   //   When a block scope declaration of an entity with linkage is not found to
6519   //   refer to some other declaration, then that entity is a member of the
6520   //   innermost enclosing namespace.
6521   //
6522   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6523   // semantically-enclosing namespace, not a lexically-enclosing one.
6524   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6525     DC = DC->getParent();
6526   return true;
6527 }
6528 
6529 /// Returns true if given declaration has external C language linkage.
6530 static bool isDeclExternC(const Decl *D) {
6531   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6532     return FD->isExternC();
6533   if (const auto *VD = dyn_cast<VarDecl>(D))
6534     return VD->isExternC();
6535 
6536   llvm_unreachable("Unknown type of decl!");
6537 }
6538 /// Returns true if there hasn't been any invalid type diagnosed.
6539 static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D,
6540                                 DeclContext *DC, QualType R) {
6541   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6542   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6543   // argument.
6544   if (R->isImageType() || R->isPipeType()) {
6545     Se.Diag(D.getIdentifierLoc(),
6546             diag::err_opencl_type_can_only_be_used_as_function_parameter)
6547         << R;
6548     D.setInvalidType();
6549     return false;
6550   }
6551 
6552   // OpenCL v1.2 s6.9.r:
6553   // The event type cannot be used to declare a program scope variable.
6554   // OpenCL v2.0 s6.9.q:
6555   // The clk_event_t and reserve_id_t types cannot be declared in program
6556   // scope.
6557   if (NULL == S->getParent()) {
6558     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6559       Se.Diag(D.getIdentifierLoc(),
6560               diag::err_invalid_type_for_program_scope_var)
6561           << R;
6562       D.setInvalidType();
6563       return false;
6564     }
6565   }
6566 
6567   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6568   QualType NR = R;
6569   while (NR->isPointerType()) {
6570     if (NR->isFunctionPointerType()) {
6571       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6572       D.setInvalidType();
6573       return false;
6574     }
6575     NR = NR->getPointeeType();
6576   }
6577 
6578   if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6579     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6580     // half array type (unless the cl_khr_fp16 extension is enabled).
6581     if (Se.Context.getBaseElementType(R)->isHalfType()) {
6582       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6583       D.setInvalidType();
6584       return false;
6585     }
6586   }
6587 
6588   // OpenCL v1.2 s6.9.r:
6589   // The event type cannot be used with the __local, __constant and __global
6590   // address space qualifiers.
6591   if (R->isEventT()) {
6592     if (R.getAddressSpace() != LangAS::opencl_private) {
6593       Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6594       D.setInvalidType();
6595       return false;
6596     }
6597   }
6598 
6599   // C++ for OpenCL does not allow the thread_local storage qualifier.
6600   // OpenCL C does not support thread_local either, and
6601   // also reject all other thread storage class specifiers.
6602   DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6603   if (TSC != TSCS_unspecified) {
6604     bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus;
6605     Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6606             diag::err_opencl_unknown_type_specifier)
6607         << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString()
6608         << DeclSpec::getSpecifierName(TSC) << 1;
6609     D.setInvalidType();
6610     return false;
6611   }
6612 
6613   if (R->isSamplerT()) {
6614     // OpenCL v1.2 s6.9.b p4:
6615     // The sampler type cannot be used with the __local and __global address
6616     // space qualifiers.
6617     if (R.getAddressSpace() == LangAS::opencl_local ||
6618         R.getAddressSpace() == LangAS::opencl_global) {
6619       Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6620       D.setInvalidType();
6621     }
6622 
6623     // OpenCL v1.2 s6.12.14.1:
6624     // A global sampler must be declared with either the constant address
6625     // space qualifier or with the const qualifier.
6626     if (DC->isTranslationUnit() &&
6627         !(R.getAddressSpace() == LangAS::opencl_constant ||
6628           R.isConstQualified())) {
6629       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6630       D.setInvalidType();
6631     }
6632     if (D.isInvalidType())
6633       return false;
6634   }
6635   return true;
6636 }
6637 
6638 NamedDecl *Sema::ActOnVariableDeclarator(
6639     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6640     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6641     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6642   QualType R = TInfo->getType();
6643   DeclarationName Name = GetNameForDeclarator(D).getName();
6644 
6645   IdentifierInfo *II = Name.getAsIdentifierInfo();
6646 
6647   if (D.isDecompositionDeclarator()) {
6648     // Take the name of the first declarator as our name for diagnostic
6649     // purposes.
6650     auto &Decomp = D.getDecompositionDeclarator();
6651     if (!Decomp.bindings().empty()) {
6652       II = Decomp.bindings()[0].Name;
6653       Name = II;
6654     }
6655   } else if (!II) {
6656     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6657     return nullptr;
6658   }
6659 
6660 
6661   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6662   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6663 
6664   // dllimport globals without explicit storage class are treated as extern. We
6665   // have to change the storage class this early to get the right DeclContext.
6666   if (SC == SC_None && !DC->isRecord() &&
6667       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6668       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6669     SC = SC_Extern;
6670 
6671   DeclContext *OriginalDC = DC;
6672   bool IsLocalExternDecl = SC == SC_Extern &&
6673                            adjustContextForLocalExternDecl(DC);
6674 
6675   if (SCSpec == DeclSpec::SCS_mutable) {
6676     // mutable can only appear on non-static class members, so it's always
6677     // an error here
6678     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6679     D.setInvalidType();
6680     SC = SC_None;
6681   }
6682 
6683   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6684       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6685                               D.getDeclSpec().getStorageClassSpecLoc())) {
6686     // In C++11, the 'register' storage class specifier is deprecated.
6687     // Suppress the warning in system macros, it's used in macros in some
6688     // popular C system headers, such as in glibc's htonl() macro.
6689     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6690          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6691                                    : diag::warn_deprecated_register)
6692       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6693   }
6694 
6695   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6696 
6697   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6698     // C99 6.9p2: The storage-class specifiers auto and register shall not
6699     // appear in the declaration specifiers in an external declaration.
6700     // Global Register+Asm is a GNU extension we support.
6701     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6702       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6703       D.setInvalidType();
6704     }
6705   }
6706 
6707   bool IsMemberSpecialization = false;
6708   bool IsVariableTemplateSpecialization = false;
6709   bool IsPartialSpecialization = false;
6710   bool IsVariableTemplate = false;
6711   VarDecl *NewVD = nullptr;
6712   VarTemplateDecl *NewTemplate = nullptr;
6713   TemplateParameterList *TemplateParams = nullptr;
6714   if (!getLangOpts().CPlusPlus) {
6715     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6716                             II, R, TInfo, SC);
6717 
6718     if (R->getContainedDeducedType())
6719       ParsingInitForAutoVars.insert(NewVD);
6720 
6721     if (D.isInvalidType())
6722       NewVD->setInvalidDecl();
6723 
6724     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
6725         NewVD->hasLocalStorage())
6726       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
6727                             NTCUC_AutoVar, NTCUK_Destruct);
6728   } else {
6729     bool Invalid = false;
6730 
6731     if (DC->isRecord() && !CurContext->isRecord()) {
6732       // This is an out-of-line definition of a static data member.
6733       switch (SC) {
6734       case SC_None:
6735         break;
6736       case SC_Static:
6737         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6738              diag::err_static_out_of_line)
6739           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6740         break;
6741       case SC_Auto:
6742       case SC_Register:
6743       case SC_Extern:
6744         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6745         // to names of variables declared in a block or to function parameters.
6746         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6747         // of class members
6748 
6749         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6750              diag::err_storage_class_for_static_member)
6751           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6752         break;
6753       case SC_PrivateExtern:
6754         llvm_unreachable("C storage class in c++!");
6755       }
6756     }
6757 
6758     if (SC == SC_Static && CurContext->isRecord()) {
6759       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6760         if (RD->isLocalClass())
6761           Diag(D.getIdentifierLoc(),
6762                diag::err_static_data_member_not_allowed_in_local_class)
6763             << Name << RD->getDeclName();
6764 
6765         // C++98 [class.union]p1: If a union contains a static data member,
6766         // the program is ill-formed. C++11 drops this restriction.
6767         if (RD->isUnion())
6768           Diag(D.getIdentifierLoc(),
6769                getLangOpts().CPlusPlus11
6770                  ? diag::warn_cxx98_compat_static_data_member_in_union
6771                  : diag::ext_static_data_member_in_union) << Name;
6772         // We conservatively disallow static data members in anonymous structs.
6773         else if (!RD->getDeclName())
6774           Diag(D.getIdentifierLoc(),
6775                diag::err_static_data_member_not_allowed_in_anon_struct)
6776             << Name << RD->isUnion();
6777       }
6778     }
6779 
6780     // Match up the template parameter lists with the scope specifier, then
6781     // determine whether we have a template or a template specialization.
6782     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6783         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6784         D.getCXXScopeSpec(),
6785         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6786             ? D.getName().TemplateId
6787             : nullptr,
6788         TemplateParamLists,
6789         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6790 
6791     if (TemplateParams) {
6792       if (!TemplateParams->size() &&
6793           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6794         // There is an extraneous 'template<>' for this variable. Complain
6795         // about it, but allow the declaration of the variable.
6796         Diag(TemplateParams->getTemplateLoc(),
6797              diag::err_template_variable_noparams)
6798           << II
6799           << SourceRange(TemplateParams->getTemplateLoc(),
6800                          TemplateParams->getRAngleLoc());
6801         TemplateParams = nullptr;
6802       } else {
6803         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6804           // This is an explicit specialization or a partial specialization.
6805           // FIXME: Check that we can declare a specialization here.
6806           IsVariableTemplateSpecialization = true;
6807           IsPartialSpecialization = TemplateParams->size() > 0;
6808         } else { // if (TemplateParams->size() > 0)
6809           // This is a template declaration.
6810           IsVariableTemplate = true;
6811 
6812           // Check that we can declare a template here.
6813           if (CheckTemplateDeclScope(S, TemplateParams))
6814             return nullptr;
6815 
6816           // Only C++1y supports variable templates (N3651).
6817           Diag(D.getIdentifierLoc(),
6818                getLangOpts().CPlusPlus14
6819                    ? diag::warn_cxx11_compat_variable_template
6820                    : diag::ext_variable_template);
6821         }
6822       }
6823     } else {
6824       assert((Invalid ||
6825               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
6826              "should have a 'template<>' for this decl");
6827     }
6828 
6829     if (IsVariableTemplateSpecialization) {
6830       SourceLocation TemplateKWLoc =
6831           TemplateParamLists.size() > 0
6832               ? TemplateParamLists[0]->getTemplateLoc()
6833               : SourceLocation();
6834       DeclResult Res = ActOnVarTemplateSpecialization(
6835           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6836           IsPartialSpecialization);
6837       if (Res.isInvalid())
6838         return nullptr;
6839       NewVD = cast<VarDecl>(Res.get());
6840       AddToScope = false;
6841     } else if (D.isDecompositionDeclarator()) {
6842       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
6843                                         D.getIdentifierLoc(), R, TInfo, SC,
6844                                         Bindings);
6845     } else
6846       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
6847                               D.getIdentifierLoc(), II, R, TInfo, SC);
6848 
6849     // If this is supposed to be a variable template, create it as such.
6850     if (IsVariableTemplate) {
6851       NewTemplate =
6852           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6853                                   TemplateParams, NewVD);
6854       NewVD->setDescribedVarTemplate(NewTemplate);
6855     }
6856 
6857     // If this decl has an auto type in need of deduction, make a note of the
6858     // Decl so we can diagnose uses of it in its own initializer.
6859     if (R->getContainedDeducedType())
6860       ParsingInitForAutoVars.insert(NewVD);
6861 
6862     if (D.isInvalidType() || Invalid) {
6863       NewVD->setInvalidDecl();
6864       if (NewTemplate)
6865         NewTemplate->setInvalidDecl();
6866     }
6867 
6868     SetNestedNameSpecifier(*this, NewVD, D);
6869 
6870     // If we have any template parameter lists that don't directly belong to
6871     // the variable (matching the scope specifier), store them.
6872     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6873     if (TemplateParamLists.size() > VDTemplateParamLists)
6874       NewVD->setTemplateParameterListsInfo(
6875           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6876   }
6877 
6878   if (D.getDeclSpec().isInlineSpecified()) {
6879     if (!getLangOpts().CPlusPlus) {
6880       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6881           << 0;
6882     } else if (CurContext->isFunctionOrMethod()) {
6883       // 'inline' is not allowed on block scope variable declaration.
6884       Diag(D.getDeclSpec().getInlineSpecLoc(),
6885            diag::err_inline_declaration_block_scope) << Name
6886         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6887     } else {
6888       Diag(D.getDeclSpec().getInlineSpecLoc(),
6889            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
6890                                      : diag::ext_inline_variable);
6891       NewVD->setInlineSpecified();
6892     }
6893   }
6894 
6895   // Set the lexical context. If the declarator has a C++ scope specifier, the
6896   // lexical context will be different from the semantic context.
6897   NewVD->setLexicalDeclContext(CurContext);
6898   if (NewTemplate)
6899     NewTemplate->setLexicalDeclContext(CurContext);
6900 
6901   if (IsLocalExternDecl) {
6902     if (D.isDecompositionDeclarator())
6903       for (auto *B : Bindings)
6904         B->setLocalExternDecl();
6905     else
6906       NewVD->setLocalExternDecl();
6907   }
6908 
6909   bool EmitTLSUnsupportedError = false;
6910   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6911     // C++11 [dcl.stc]p4:
6912     //   When thread_local is applied to a variable of block scope the
6913     //   storage-class-specifier static is implied if it does not appear
6914     //   explicitly.
6915     // Core issue: 'static' is not implied if the variable is declared
6916     //   'extern'.
6917     if (NewVD->hasLocalStorage() &&
6918         (SCSpec != DeclSpec::SCS_unspecified ||
6919          TSCS != DeclSpec::TSCS_thread_local ||
6920          !DC->isFunctionOrMethod()))
6921       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6922            diag::err_thread_non_global)
6923         << DeclSpec::getSpecifierName(TSCS);
6924     else if (!Context.getTargetInfo().isTLSSupported()) {
6925       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6926         // Postpone error emission until we've collected attributes required to
6927         // figure out whether it's a host or device variable and whether the
6928         // error should be ignored.
6929         EmitTLSUnsupportedError = true;
6930         // We still need to mark the variable as TLS so it shows up in AST with
6931         // proper storage class for other tools to use even if we're not going
6932         // to emit any code for it.
6933         NewVD->setTSCSpec(TSCS);
6934       } else
6935         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6936              diag::err_thread_unsupported);
6937     } else
6938       NewVD->setTSCSpec(TSCS);
6939   }
6940 
6941   switch (D.getDeclSpec().getConstexprSpecifier()) {
6942   case CSK_unspecified:
6943     break;
6944 
6945   case CSK_consteval:
6946     Diag(D.getDeclSpec().getConstexprSpecLoc(),
6947         diag::err_constexpr_wrong_decl_kind)
6948       << D.getDeclSpec().getConstexprSpecifier();
6949     LLVM_FALLTHROUGH;
6950 
6951   case CSK_constexpr:
6952     NewVD->setConstexpr(true);
6953     // C++1z [dcl.spec.constexpr]p1:
6954     //   A static data member declared with the constexpr specifier is
6955     //   implicitly an inline variable.
6956     if (NewVD->isStaticDataMember() &&
6957         (getLangOpts().CPlusPlus17 ||
6958          Context.getTargetInfo().getCXXABI().isMicrosoft()))
6959       NewVD->setImplicitlyInline();
6960     break;
6961 
6962   case CSK_constinit:
6963     if (!NewVD->hasGlobalStorage())
6964       Diag(D.getDeclSpec().getConstexprSpecLoc(),
6965            diag::err_constinit_local_variable);
6966     else
6967       NewVD->addAttr(ConstInitAttr::Create(
6968           Context, D.getDeclSpec().getConstexprSpecLoc(),
6969           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
6970     break;
6971   }
6972 
6973   // C99 6.7.4p3
6974   //   An inline definition of a function with external linkage shall
6975   //   not contain a definition of a modifiable object with static or
6976   //   thread storage duration...
6977   // We only apply this when the function is required to be defined
6978   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6979   // that a local variable with thread storage duration still has to
6980   // be marked 'static'.  Also note that it's possible to get these
6981   // semantics in C++ using __attribute__((gnu_inline)).
6982   if (SC == SC_Static && S->getFnParent() != nullptr &&
6983       !NewVD->getType().isConstQualified()) {
6984     FunctionDecl *CurFD = getCurFunctionDecl();
6985     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6986       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6987            diag::warn_static_local_in_extern_inline);
6988       MaybeSuggestAddingStaticToDecl(CurFD);
6989     }
6990   }
6991 
6992   if (D.getDeclSpec().isModulePrivateSpecified()) {
6993     if (IsVariableTemplateSpecialization)
6994       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6995           << (IsPartialSpecialization ? 1 : 0)
6996           << FixItHint::CreateRemoval(
6997                  D.getDeclSpec().getModulePrivateSpecLoc());
6998     else if (IsMemberSpecialization)
6999       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7000         << 2
7001         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7002     else if (NewVD->hasLocalStorage())
7003       Diag(NewVD->getLocation(), diag::err_module_private_local)
7004         << 0 << NewVD->getDeclName()
7005         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7006         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7007     else {
7008       NewVD->setModulePrivate();
7009       if (NewTemplate)
7010         NewTemplate->setModulePrivate();
7011       for (auto *B : Bindings)
7012         B->setModulePrivate();
7013     }
7014   }
7015 
7016   if (getLangOpts().OpenCL) {
7017 
7018     deduceOpenCLAddressSpace(NewVD);
7019 
7020     diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType());
7021   }
7022 
7023   // Handle attributes prior to checking for duplicates in MergeVarDecl
7024   ProcessDeclAttributes(S, NewVD, D);
7025 
7026   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
7027     if (EmitTLSUnsupportedError &&
7028         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7029          (getLangOpts().OpenMPIsDevice &&
7030           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7031       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7032            diag::err_thread_unsupported);
7033     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7034     // storage [duration]."
7035     if (SC == SC_None && S->getFnParent() != nullptr &&
7036         (NewVD->hasAttr<CUDASharedAttr>() ||
7037          NewVD->hasAttr<CUDAConstantAttr>())) {
7038       NewVD->setStorageClass(SC_Static);
7039     }
7040   }
7041 
7042   // Ensure that dllimport globals without explicit storage class are treated as
7043   // extern. The storage class is set above using parsed attributes. Now we can
7044   // check the VarDecl itself.
7045   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7046          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7047          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7048 
7049   // In auto-retain/release, infer strong retension for variables of
7050   // retainable type.
7051   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7052     NewVD->setInvalidDecl();
7053 
7054   // Handle GNU asm-label extension (encoded as an attribute).
7055   if (Expr *E = (Expr*)D.getAsmLabel()) {
7056     // The parser guarantees this is a string.
7057     StringLiteral *SE = cast<StringLiteral>(E);
7058     StringRef Label = SE->getString();
7059     if (S->getFnParent() != nullptr) {
7060       switch (SC) {
7061       case SC_None:
7062       case SC_Auto:
7063         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7064         break;
7065       case SC_Register:
7066         // Local Named register
7067         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7068             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7069           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7070         break;
7071       case SC_Static:
7072       case SC_Extern:
7073       case SC_PrivateExtern:
7074         break;
7075       }
7076     } else if (SC == SC_Register) {
7077       // Global Named register
7078       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7079         const auto &TI = Context.getTargetInfo();
7080         bool HasSizeMismatch;
7081 
7082         if (!TI.isValidGCCRegisterName(Label))
7083           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7084         else if (!TI.validateGlobalRegisterVariable(Label,
7085                                                     Context.getTypeSize(R),
7086                                                     HasSizeMismatch))
7087           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7088         else if (HasSizeMismatch)
7089           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7090       }
7091 
7092       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7093         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7094         NewVD->setInvalidDecl(true);
7095       }
7096     }
7097 
7098     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7099                                         /*IsLiteralLabel=*/true,
7100                                         SE->getStrTokenLoc(0)));
7101   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7102     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7103       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7104     if (I != ExtnameUndeclaredIdentifiers.end()) {
7105       if (isDeclExternC(NewVD)) {
7106         NewVD->addAttr(I->second);
7107         ExtnameUndeclaredIdentifiers.erase(I);
7108       } else
7109         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7110             << /*Variable*/1 << NewVD;
7111     }
7112   }
7113 
7114   // Find the shadowed declaration before filtering for scope.
7115   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7116                                 ? getShadowedDeclaration(NewVD, Previous)
7117                                 : nullptr;
7118 
7119   // Don't consider existing declarations that are in a different
7120   // scope and are out-of-semantic-context declarations (if the new
7121   // declaration has linkage).
7122   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7123                        D.getCXXScopeSpec().isNotEmpty() ||
7124                        IsMemberSpecialization ||
7125                        IsVariableTemplateSpecialization);
7126 
7127   // Check whether the previous declaration is in the same block scope. This
7128   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7129   if (getLangOpts().CPlusPlus &&
7130       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7131     NewVD->setPreviousDeclInSameBlockScope(
7132         Previous.isSingleResult() && !Previous.isShadowed() &&
7133         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7134 
7135   if (!getLangOpts().CPlusPlus) {
7136     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7137   } else {
7138     // If this is an explicit specialization of a static data member, check it.
7139     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7140         CheckMemberSpecialization(NewVD, Previous))
7141       NewVD->setInvalidDecl();
7142 
7143     // Merge the decl with the existing one if appropriate.
7144     if (!Previous.empty()) {
7145       if (Previous.isSingleResult() &&
7146           isa<FieldDecl>(Previous.getFoundDecl()) &&
7147           D.getCXXScopeSpec().isSet()) {
7148         // The user tried to define a non-static data member
7149         // out-of-line (C++ [dcl.meaning]p1).
7150         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7151           << D.getCXXScopeSpec().getRange();
7152         Previous.clear();
7153         NewVD->setInvalidDecl();
7154       }
7155     } else if (D.getCXXScopeSpec().isSet()) {
7156       // No previous declaration in the qualifying scope.
7157       Diag(D.getIdentifierLoc(), diag::err_no_member)
7158         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7159         << D.getCXXScopeSpec().getRange();
7160       NewVD->setInvalidDecl();
7161     }
7162 
7163     if (!IsVariableTemplateSpecialization)
7164       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7165 
7166     if (NewTemplate) {
7167       VarTemplateDecl *PrevVarTemplate =
7168           NewVD->getPreviousDecl()
7169               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7170               : nullptr;
7171 
7172       // Check the template parameter list of this declaration, possibly
7173       // merging in the template parameter list from the previous variable
7174       // template declaration.
7175       if (CheckTemplateParameterList(
7176               TemplateParams,
7177               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7178                               : nullptr,
7179               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7180                DC->isDependentContext())
7181                   ? TPC_ClassTemplateMember
7182                   : TPC_VarTemplate))
7183         NewVD->setInvalidDecl();
7184 
7185       // If we are providing an explicit specialization of a static variable
7186       // template, make a note of that.
7187       if (PrevVarTemplate &&
7188           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7189         PrevVarTemplate->setMemberSpecialization();
7190     }
7191   }
7192 
7193   // Diagnose shadowed variables iff this isn't a redeclaration.
7194   if (ShadowedDecl && !D.isRedeclaration())
7195     CheckShadow(NewVD, ShadowedDecl, Previous);
7196 
7197   ProcessPragmaWeak(S, NewVD);
7198 
7199   // If this is the first declaration of an extern C variable, update
7200   // the map of such variables.
7201   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7202       isIncompleteDeclExternC(*this, NewVD))
7203     RegisterLocallyScopedExternCDecl(NewVD, S);
7204 
7205   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7206     MangleNumberingContext *MCtx;
7207     Decl *ManglingContextDecl;
7208     std::tie(MCtx, ManglingContextDecl) =
7209         getCurrentMangleNumberContext(NewVD->getDeclContext());
7210     if (MCtx) {
7211       Context.setManglingNumber(
7212           NewVD, MCtx->getManglingNumber(
7213                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7214       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7215     }
7216   }
7217 
7218   // Special handling of variable named 'main'.
7219   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7220       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7221       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7222 
7223     // C++ [basic.start.main]p3
7224     // A program that declares a variable main at global scope is ill-formed.
7225     if (getLangOpts().CPlusPlus)
7226       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7227 
7228     // In C, and external-linkage variable named main results in undefined
7229     // behavior.
7230     else if (NewVD->hasExternalFormalLinkage())
7231       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7232   }
7233 
7234   if (D.isRedeclaration() && !Previous.empty()) {
7235     NamedDecl *Prev = Previous.getRepresentativeDecl();
7236     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7237                                    D.isFunctionDefinition());
7238   }
7239 
7240   if (NewTemplate) {
7241     if (NewVD->isInvalidDecl())
7242       NewTemplate->setInvalidDecl();
7243     ActOnDocumentableDecl(NewTemplate);
7244     return NewTemplate;
7245   }
7246 
7247   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7248     CompleteMemberSpecialization(NewVD, Previous);
7249 
7250   return NewVD;
7251 }
7252 
7253 /// Enum describing the %select options in diag::warn_decl_shadow.
7254 enum ShadowedDeclKind {
7255   SDK_Local,
7256   SDK_Global,
7257   SDK_StaticMember,
7258   SDK_Field,
7259   SDK_Typedef,
7260   SDK_Using
7261 };
7262 
7263 /// Determine what kind of declaration we're shadowing.
7264 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7265                                                 const DeclContext *OldDC) {
7266   if (isa<TypeAliasDecl>(ShadowedDecl))
7267     return SDK_Using;
7268   else if (isa<TypedefDecl>(ShadowedDecl))
7269     return SDK_Typedef;
7270   else if (isa<RecordDecl>(OldDC))
7271     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7272 
7273   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7274 }
7275 
7276 /// Return the location of the capture if the given lambda captures the given
7277 /// variable \p VD, or an invalid source location otherwise.
7278 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7279                                          const VarDecl *VD) {
7280   for (const Capture &Capture : LSI->Captures) {
7281     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7282       return Capture.getLocation();
7283   }
7284   return SourceLocation();
7285 }
7286 
7287 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7288                                      const LookupResult &R) {
7289   // Only diagnose if we're shadowing an unambiguous field or variable.
7290   if (R.getResultKind() != LookupResult::Found)
7291     return false;
7292 
7293   // Return false if warning is ignored.
7294   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7295 }
7296 
7297 /// Return the declaration shadowed by the given variable \p D, or null
7298 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7299 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7300                                         const LookupResult &R) {
7301   if (!shouldWarnIfShadowedDecl(Diags, R))
7302     return nullptr;
7303 
7304   // Don't diagnose declarations at file scope.
7305   if (D->hasGlobalStorage())
7306     return nullptr;
7307 
7308   NamedDecl *ShadowedDecl = R.getFoundDecl();
7309   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
7310              ? ShadowedDecl
7311              : nullptr;
7312 }
7313 
7314 /// Return the declaration shadowed by the given typedef \p D, or null
7315 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7316 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7317                                         const LookupResult &R) {
7318   // Don't warn if typedef declaration is part of a class
7319   if (D->getDeclContext()->isRecord())
7320     return nullptr;
7321 
7322   if (!shouldWarnIfShadowedDecl(Diags, R))
7323     return nullptr;
7324 
7325   NamedDecl *ShadowedDecl = R.getFoundDecl();
7326   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7327 }
7328 
7329 /// Diagnose variable or built-in function shadowing.  Implements
7330 /// -Wshadow.
7331 ///
7332 /// This method is called whenever a VarDecl is added to a "useful"
7333 /// scope.
7334 ///
7335 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7336 /// \param R the lookup of the name
7337 ///
7338 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7339                        const LookupResult &R) {
7340   DeclContext *NewDC = D->getDeclContext();
7341 
7342   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7343     // Fields are not shadowed by variables in C++ static methods.
7344     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7345       if (MD->isStatic())
7346         return;
7347 
7348     // Fields shadowed by constructor parameters are a special case. Usually
7349     // the constructor initializes the field with the parameter.
7350     if (isa<CXXConstructorDecl>(NewDC))
7351       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7352         // Remember that this was shadowed so we can either warn about its
7353         // modification or its existence depending on warning settings.
7354         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7355         return;
7356       }
7357   }
7358 
7359   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7360     if (shadowedVar->isExternC()) {
7361       // For shadowing external vars, make sure that we point to the global
7362       // declaration, not a locally scoped extern declaration.
7363       for (auto I : shadowedVar->redecls())
7364         if (I->isFileVarDecl()) {
7365           ShadowedDecl = I;
7366           break;
7367         }
7368     }
7369 
7370   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7371 
7372   unsigned WarningDiag = diag::warn_decl_shadow;
7373   SourceLocation CaptureLoc;
7374   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7375       isa<CXXMethodDecl>(NewDC)) {
7376     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7377       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7378         if (RD->getLambdaCaptureDefault() == LCD_None) {
7379           // Try to avoid warnings for lambdas with an explicit capture list.
7380           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7381           // Warn only when the lambda captures the shadowed decl explicitly.
7382           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7383           if (CaptureLoc.isInvalid())
7384             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7385         } else {
7386           // Remember that this was shadowed so we can avoid the warning if the
7387           // shadowed decl isn't captured and the warning settings allow it.
7388           cast<LambdaScopeInfo>(getCurFunction())
7389               ->ShadowingDecls.push_back(
7390                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7391           return;
7392         }
7393       }
7394 
7395       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7396         // A variable can't shadow a local variable in an enclosing scope, if
7397         // they are separated by a non-capturing declaration context.
7398         for (DeclContext *ParentDC = NewDC;
7399              ParentDC && !ParentDC->Equals(OldDC);
7400              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7401           // Only block literals, captured statements, and lambda expressions
7402           // can capture; other scopes don't.
7403           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7404               !isLambdaCallOperator(ParentDC)) {
7405             return;
7406           }
7407         }
7408       }
7409     }
7410   }
7411 
7412   // Only warn about certain kinds of shadowing for class members.
7413   if (NewDC && NewDC->isRecord()) {
7414     // In particular, don't warn about shadowing non-class members.
7415     if (!OldDC->isRecord())
7416       return;
7417 
7418     // TODO: should we warn about static data members shadowing
7419     // static data members from base classes?
7420 
7421     // TODO: don't diagnose for inaccessible shadowed members.
7422     // This is hard to do perfectly because we might friend the
7423     // shadowing context, but that's just a false negative.
7424   }
7425 
7426 
7427   DeclarationName Name = R.getLookupName();
7428 
7429   // Emit warning and note.
7430   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7431     return;
7432   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7433   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7434   if (!CaptureLoc.isInvalid())
7435     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7436         << Name << /*explicitly*/ 1;
7437   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7438 }
7439 
7440 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7441 /// when these variables are captured by the lambda.
7442 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7443   for (const auto &Shadow : LSI->ShadowingDecls) {
7444     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7445     // Try to avoid the warning when the shadowed decl isn't captured.
7446     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7447     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7448     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7449                                        ? diag::warn_decl_shadow_uncaptured_local
7450                                        : diag::warn_decl_shadow)
7451         << Shadow.VD->getDeclName()
7452         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7453     if (!CaptureLoc.isInvalid())
7454       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7455           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7456     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7457   }
7458 }
7459 
7460 /// Check -Wshadow without the advantage of a previous lookup.
7461 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7462   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7463     return;
7464 
7465   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7466                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7467   LookupName(R, S);
7468   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7469     CheckShadow(D, ShadowedDecl, R);
7470 }
7471 
7472 /// Check if 'E', which is an expression that is about to be modified, refers
7473 /// to a constructor parameter that shadows a field.
7474 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7475   // Quickly ignore expressions that can't be shadowing ctor parameters.
7476   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7477     return;
7478   E = E->IgnoreParenImpCasts();
7479   auto *DRE = dyn_cast<DeclRefExpr>(E);
7480   if (!DRE)
7481     return;
7482   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7483   auto I = ShadowingDecls.find(D);
7484   if (I == ShadowingDecls.end())
7485     return;
7486   const NamedDecl *ShadowedDecl = I->second;
7487   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7488   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7489   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7490   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7491 
7492   // Avoid issuing multiple warnings about the same decl.
7493   ShadowingDecls.erase(I);
7494 }
7495 
7496 /// Check for conflict between this global or extern "C" declaration and
7497 /// previous global or extern "C" declarations. This is only used in C++.
7498 template<typename T>
7499 static bool checkGlobalOrExternCConflict(
7500     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7501   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7502   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7503 
7504   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7505     // The common case: this global doesn't conflict with any extern "C"
7506     // declaration.
7507     return false;
7508   }
7509 
7510   if (Prev) {
7511     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7512       // Both the old and new declarations have C language linkage. This is a
7513       // redeclaration.
7514       Previous.clear();
7515       Previous.addDecl(Prev);
7516       return true;
7517     }
7518 
7519     // This is a global, non-extern "C" declaration, and there is a previous
7520     // non-global extern "C" declaration. Diagnose if this is a variable
7521     // declaration.
7522     if (!isa<VarDecl>(ND))
7523       return false;
7524   } else {
7525     // The declaration is extern "C". Check for any declaration in the
7526     // translation unit which might conflict.
7527     if (IsGlobal) {
7528       // We have already performed the lookup into the translation unit.
7529       IsGlobal = false;
7530       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7531            I != E; ++I) {
7532         if (isa<VarDecl>(*I)) {
7533           Prev = *I;
7534           break;
7535         }
7536       }
7537     } else {
7538       DeclContext::lookup_result R =
7539           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7540       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7541            I != E; ++I) {
7542         if (isa<VarDecl>(*I)) {
7543           Prev = *I;
7544           break;
7545         }
7546         // FIXME: If we have any other entity with this name in global scope,
7547         // the declaration is ill-formed, but that is a defect: it breaks the
7548         // 'stat' hack, for instance. Only variables can have mangled name
7549         // clashes with extern "C" declarations, so only they deserve a
7550         // diagnostic.
7551       }
7552     }
7553 
7554     if (!Prev)
7555       return false;
7556   }
7557 
7558   // Use the first declaration's location to ensure we point at something which
7559   // is lexically inside an extern "C" linkage-spec.
7560   assert(Prev && "should have found a previous declaration to diagnose");
7561   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7562     Prev = FD->getFirstDecl();
7563   else
7564     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7565 
7566   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7567     << IsGlobal << ND;
7568   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7569     << IsGlobal;
7570   return false;
7571 }
7572 
7573 /// Apply special rules for handling extern "C" declarations. Returns \c true
7574 /// if we have found that this is a redeclaration of some prior entity.
7575 ///
7576 /// Per C++ [dcl.link]p6:
7577 ///   Two declarations [for a function or variable] with C language linkage
7578 ///   with the same name that appear in different scopes refer to the same
7579 ///   [entity]. An entity with C language linkage shall not be declared with
7580 ///   the same name as an entity in global scope.
7581 template<typename T>
7582 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7583                                                   LookupResult &Previous) {
7584   if (!S.getLangOpts().CPlusPlus) {
7585     // In C, when declaring a global variable, look for a corresponding 'extern'
7586     // variable declared in function scope. We don't need this in C++, because
7587     // we find local extern decls in the surrounding file-scope DeclContext.
7588     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7589       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7590         Previous.clear();
7591         Previous.addDecl(Prev);
7592         return true;
7593       }
7594     }
7595     return false;
7596   }
7597 
7598   // A declaration in the translation unit can conflict with an extern "C"
7599   // declaration.
7600   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7601     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7602 
7603   // An extern "C" declaration can conflict with a declaration in the
7604   // translation unit or can be a redeclaration of an extern "C" declaration
7605   // in another scope.
7606   if (isIncompleteDeclExternC(S,ND))
7607     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7608 
7609   // Neither global nor extern "C": nothing to do.
7610   return false;
7611 }
7612 
7613 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7614   // If the decl is already known invalid, don't check it.
7615   if (NewVD->isInvalidDecl())
7616     return;
7617 
7618   QualType T = NewVD->getType();
7619 
7620   // Defer checking an 'auto' type until its initializer is attached.
7621   if (T->isUndeducedType())
7622     return;
7623 
7624   if (NewVD->hasAttrs())
7625     CheckAlignasUnderalignment(NewVD);
7626 
7627   if (T->isObjCObjectType()) {
7628     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7629       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7630     T = Context.getObjCObjectPointerType(T);
7631     NewVD->setType(T);
7632   }
7633 
7634   // Emit an error if an address space was applied to decl with local storage.
7635   // This includes arrays of objects with address space qualifiers, but not
7636   // automatic variables that point to other address spaces.
7637   // ISO/IEC TR 18037 S5.1.2
7638   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7639       T.getAddressSpace() != LangAS::Default) {
7640     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7641     NewVD->setInvalidDecl();
7642     return;
7643   }
7644 
7645   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7646   // scope.
7647   if (getLangOpts().OpenCLVersion == 120 &&
7648       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7649       NewVD->isStaticLocal()) {
7650     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7651     NewVD->setInvalidDecl();
7652     return;
7653   }
7654 
7655   if (getLangOpts().OpenCL) {
7656     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7657     if (NewVD->hasAttr<BlocksAttr>()) {
7658       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7659       return;
7660     }
7661 
7662     if (T->isBlockPointerType()) {
7663       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7664       // can't use 'extern' storage class.
7665       if (!T.isConstQualified()) {
7666         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7667             << 0 /*const*/;
7668         NewVD->setInvalidDecl();
7669         return;
7670       }
7671       if (NewVD->hasExternalStorage()) {
7672         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7673         NewVD->setInvalidDecl();
7674         return;
7675       }
7676     }
7677     // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7678     // __constant address space.
7679     // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7680     // variables inside a function can also be declared in the global
7681     // address space.
7682     // C++ for OpenCL inherits rule from OpenCL C v2.0.
7683     // FIXME: Adding local AS in C++ for OpenCL might make sense.
7684     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7685         NewVD->hasExternalStorage()) {
7686       if (!T->isSamplerT() &&
7687           !(T.getAddressSpace() == LangAS::opencl_constant ||
7688             (T.getAddressSpace() == LangAS::opencl_global &&
7689              (getLangOpts().OpenCLVersion == 200 ||
7690               getLangOpts().OpenCLCPlusPlus)))) {
7691         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7692         if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7693           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7694               << Scope << "global or constant";
7695         else
7696           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7697               << Scope << "constant";
7698         NewVD->setInvalidDecl();
7699         return;
7700       }
7701     } else {
7702       if (T.getAddressSpace() == LangAS::opencl_global) {
7703         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7704             << 1 /*is any function*/ << "global";
7705         NewVD->setInvalidDecl();
7706         return;
7707       }
7708       if (T.getAddressSpace() == LangAS::opencl_constant ||
7709           T.getAddressSpace() == LangAS::opencl_local) {
7710         FunctionDecl *FD = getCurFunctionDecl();
7711         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7712         // in functions.
7713         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7714           if (T.getAddressSpace() == LangAS::opencl_constant)
7715             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7716                 << 0 /*non-kernel only*/ << "constant";
7717           else
7718             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7719                 << 0 /*non-kernel only*/ << "local";
7720           NewVD->setInvalidDecl();
7721           return;
7722         }
7723         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7724         // in the outermost scope of a kernel function.
7725         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7726           if (!getCurScope()->isFunctionScope()) {
7727             if (T.getAddressSpace() == LangAS::opencl_constant)
7728               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7729                   << "constant";
7730             else
7731               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7732                   << "local";
7733             NewVD->setInvalidDecl();
7734             return;
7735           }
7736         }
7737       } else if (T.getAddressSpace() != LangAS::opencl_private &&
7738                  // If we are parsing a template we didn't deduce an addr
7739                  // space yet.
7740                  T.getAddressSpace() != LangAS::Default) {
7741         // Do not allow other address spaces on automatic variable.
7742         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7743         NewVD->setInvalidDecl();
7744         return;
7745       }
7746     }
7747   }
7748 
7749   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7750       && !NewVD->hasAttr<BlocksAttr>()) {
7751     if (getLangOpts().getGC() != LangOptions::NonGC)
7752       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7753     else {
7754       assert(!getLangOpts().ObjCAutoRefCount);
7755       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7756     }
7757   }
7758 
7759   bool isVM = T->isVariablyModifiedType();
7760   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7761       NewVD->hasAttr<BlocksAttr>())
7762     setFunctionHasBranchProtectedScope();
7763 
7764   if ((isVM && NewVD->hasLinkage()) ||
7765       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7766     bool SizeIsNegative;
7767     llvm::APSInt Oversized;
7768     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7769         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7770     QualType FixedT;
7771     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
7772       FixedT = FixedTInfo->getType();
7773     else if (FixedTInfo) {
7774       // Type and type-as-written are canonically different. We need to fix up
7775       // both types separately.
7776       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7777                                                    Oversized);
7778     }
7779     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7780       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7781       // FIXME: This won't give the correct result for
7782       // int a[10][n];
7783       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7784 
7785       if (NewVD->isFileVarDecl())
7786         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7787         << SizeRange;
7788       else if (NewVD->isStaticLocal())
7789         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7790         << SizeRange;
7791       else
7792         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7793         << SizeRange;
7794       NewVD->setInvalidDecl();
7795       return;
7796     }
7797 
7798     if (!FixedTInfo) {
7799       if (NewVD->isFileVarDecl())
7800         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7801       else
7802         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7803       NewVD->setInvalidDecl();
7804       return;
7805     }
7806 
7807     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7808     NewVD->setType(FixedT);
7809     NewVD->setTypeSourceInfo(FixedTInfo);
7810   }
7811 
7812   if (T->isVoidType()) {
7813     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7814     //                    of objects and functions.
7815     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7816       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7817         << T;
7818       NewVD->setInvalidDecl();
7819       return;
7820     }
7821   }
7822 
7823   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7824     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7825     NewVD->setInvalidDecl();
7826     return;
7827   }
7828 
7829   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7830     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7831     NewVD->setInvalidDecl();
7832     return;
7833   }
7834 
7835   if (NewVD->isConstexpr() && !T->isDependentType() &&
7836       RequireLiteralType(NewVD->getLocation(), T,
7837                          diag::err_constexpr_var_non_literal)) {
7838     NewVD->setInvalidDecl();
7839     return;
7840   }
7841 }
7842 
7843 /// Perform semantic checking on a newly-created variable
7844 /// declaration.
7845 ///
7846 /// This routine performs all of the type-checking required for a
7847 /// variable declaration once it has been built. It is used both to
7848 /// check variables after they have been parsed and their declarators
7849 /// have been translated into a declaration, and to check variables
7850 /// that have been instantiated from a template.
7851 ///
7852 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7853 ///
7854 /// Returns true if the variable declaration is a redeclaration.
7855 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7856   CheckVariableDeclarationType(NewVD);
7857 
7858   // If the decl is already known invalid, don't check it.
7859   if (NewVD->isInvalidDecl())
7860     return false;
7861 
7862   // If we did not find anything by this name, look for a non-visible
7863   // extern "C" declaration with the same name.
7864   if (Previous.empty() &&
7865       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7866     Previous.setShadowed();
7867 
7868   if (!Previous.empty()) {
7869     MergeVarDecl(NewVD, Previous);
7870     return true;
7871   }
7872   return false;
7873 }
7874 
7875 namespace {
7876 struct FindOverriddenMethod {
7877   Sema *S;
7878   CXXMethodDecl *Method;
7879 
7880   /// Member lookup function that determines whether a given C++
7881   /// method overrides a method in a base class, to be used with
7882   /// CXXRecordDecl::lookupInBases().
7883   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7884     RecordDecl *BaseRecord =
7885         Specifier->getType()->castAs<RecordType>()->getDecl();
7886 
7887     DeclarationName Name = Method->getDeclName();
7888 
7889     // FIXME: Do we care about other names here too?
7890     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7891       // We really want to find the base class destructor here.
7892       QualType T = S->Context.getTypeDeclType(BaseRecord);
7893       CanQualType CT = S->Context.getCanonicalType(T);
7894 
7895       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7896     }
7897 
7898     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7899          Path.Decls = Path.Decls.slice(1)) {
7900       NamedDecl *D = Path.Decls.front();
7901       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7902         if (MD->isVirtual() &&
7903             !S->IsOverload(
7904                 Method, MD, /*UseMemberUsingDeclRules=*/false,
7905                 /*ConsiderCudaAttrs=*/true,
7906                 // C++2a [class.virtual]p2 does not consider requires clauses
7907                 // when overriding.
7908                 /*ConsiderRequiresClauses=*/false))
7909           return true;
7910       }
7911     }
7912 
7913     return false;
7914   }
7915 };
7916 
7917 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7918 } // end anonymous namespace
7919 
7920 /// Report an error regarding overriding, along with any relevant
7921 /// overridden methods.
7922 ///
7923 /// \param DiagID the primary error to report.
7924 /// \param MD the overriding method.
7925 /// \param OEK which overrides to include as notes.
7926 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7927                             OverrideErrorKind OEK = OEK_All) {
7928   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7929   for (const CXXMethodDecl *O : MD->overridden_methods()) {
7930     // This check (& the OEK parameter) could be replaced by a predicate, but
7931     // without lambdas that would be overkill. This is still nicer than writing
7932     // out the diag loop 3 times.
7933     if ((OEK == OEK_All) ||
7934         (OEK == OEK_NonDeleted && !O->isDeleted()) ||
7935         (OEK == OEK_Deleted && O->isDeleted()))
7936       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7937   }
7938 }
7939 
7940 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7941 /// and if so, check that it's a valid override and remember it.
7942 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7943   // Look for methods in base classes that this method might override.
7944   CXXBasePaths Paths;
7945   FindOverriddenMethod FOM;
7946   FOM.Method = MD;
7947   FOM.S = this;
7948   bool hasDeletedOverridenMethods = false;
7949   bool hasNonDeletedOverridenMethods = false;
7950   bool AddedAny = false;
7951   if (DC->lookupInBases(FOM, Paths)) {
7952     for (auto *I : Paths.found_decls()) {
7953       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7954         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7955         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7956             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7957             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7958             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7959           hasDeletedOverridenMethods |= OldMD->isDeleted();
7960           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7961           AddedAny = true;
7962         }
7963       }
7964     }
7965   }
7966 
7967   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7968     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7969   }
7970   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7971     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7972   }
7973 
7974   return AddedAny;
7975 }
7976 
7977 namespace {
7978   // Struct for holding all of the extra arguments needed by
7979   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7980   struct ActOnFDArgs {
7981     Scope *S;
7982     Declarator &D;
7983     MultiTemplateParamsArg TemplateParamLists;
7984     bool AddToScope;
7985   };
7986 } // end anonymous namespace
7987 
7988 namespace {
7989 
7990 // Callback to only accept typo corrections that have a non-zero edit distance.
7991 // Also only accept corrections that have the same parent decl.
7992 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
7993  public:
7994   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7995                             CXXRecordDecl *Parent)
7996       : Context(Context), OriginalFD(TypoFD),
7997         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7998 
7999   bool ValidateCandidate(const TypoCorrection &candidate) override {
8000     if (candidate.getEditDistance() == 0)
8001       return false;
8002 
8003     SmallVector<unsigned, 1> MismatchedParams;
8004     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8005                                           CDeclEnd = candidate.end();
8006          CDecl != CDeclEnd; ++CDecl) {
8007       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8008 
8009       if (FD && !FD->hasBody() &&
8010           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8011         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8012           CXXRecordDecl *Parent = MD->getParent();
8013           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8014             return true;
8015         } else if (!ExpectedParent) {
8016           return true;
8017         }
8018       }
8019     }
8020 
8021     return false;
8022   }
8023 
8024   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8025     return std::make_unique<DifferentNameValidatorCCC>(*this);
8026   }
8027 
8028  private:
8029   ASTContext &Context;
8030   FunctionDecl *OriginalFD;
8031   CXXRecordDecl *ExpectedParent;
8032 };
8033 
8034 } // end anonymous namespace
8035 
8036 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8037   TypoCorrectedFunctionDefinitions.insert(F);
8038 }
8039 
8040 /// Generate diagnostics for an invalid function redeclaration.
8041 ///
8042 /// This routine handles generating the diagnostic messages for an invalid
8043 /// function redeclaration, including finding possible similar declarations
8044 /// or performing typo correction if there are no previous declarations with
8045 /// the same name.
8046 ///
8047 /// Returns a NamedDecl iff typo correction was performed and substituting in
8048 /// the new declaration name does not cause new errors.
8049 static NamedDecl *DiagnoseInvalidRedeclaration(
8050     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8051     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8052   DeclarationName Name = NewFD->getDeclName();
8053   DeclContext *NewDC = NewFD->getDeclContext();
8054   SmallVector<unsigned, 1> MismatchedParams;
8055   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8056   TypoCorrection Correction;
8057   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8058   unsigned DiagMsg =
8059     IsLocalFriend ? diag::err_no_matching_local_friend :
8060     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8061     diag::err_member_decl_does_not_match;
8062   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8063                     IsLocalFriend ? Sema::LookupLocalFriendName
8064                                   : Sema::LookupOrdinaryName,
8065                     Sema::ForVisibleRedeclaration);
8066 
8067   NewFD->setInvalidDecl();
8068   if (IsLocalFriend)
8069     SemaRef.LookupName(Prev, S);
8070   else
8071     SemaRef.LookupQualifiedName(Prev, NewDC);
8072   assert(!Prev.isAmbiguous() &&
8073          "Cannot have an ambiguity in previous-declaration lookup");
8074   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8075   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8076                                 MD ? MD->getParent() : nullptr);
8077   if (!Prev.empty()) {
8078     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8079          Func != FuncEnd; ++Func) {
8080       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8081       if (FD &&
8082           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8083         // Add 1 to the index so that 0 can mean the mismatch didn't
8084         // involve a parameter
8085         unsigned ParamNum =
8086             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8087         NearMatches.push_back(std::make_pair(FD, ParamNum));
8088       }
8089     }
8090   // If the qualified name lookup yielded nothing, try typo correction
8091   } else if ((Correction = SemaRef.CorrectTypo(
8092                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8093                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8094                   IsLocalFriend ? nullptr : NewDC))) {
8095     // Set up everything for the call to ActOnFunctionDeclarator
8096     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8097                               ExtraArgs.D.getIdentifierLoc());
8098     Previous.clear();
8099     Previous.setLookupName(Correction.getCorrection());
8100     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8101                                     CDeclEnd = Correction.end();
8102          CDecl != CDeclEnd; ++CDecl) {
8103       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8104       if (FD && !FD->hasBody() &&
8105           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8106         Previous.addDecl(FD);
8107       }
8108     }
8109     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8110 
8111     NamedDecl *Result;
8112     // Retry building the function declaration with the new previous
8113     // declarations, and with errors suppressed.
8114     {
8115       // Trap errors.
8116       Sema::SFINAETrap Trap(SemaRef);
8117 
8118       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8119       // pieces need to verify the typo-corrected C++ declaration and hopefully
8120       // eliminate the need for the parameter pack ExtraArgs.
8121       Result = SemaRef.ActOnFunctionDeclarator(
8122           ExtraArgs.S, ExtraArgs.D,
8123           Correction.getCorrectionDecl()->getDeclContext(),
8124           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8125           ExtraArgs.AddToScope);
8126 
8127       if (Trap.hasErrorOccurred())
8128         Result = nullptr;
8129     }
8130 
8131     if (Result) {
8132       // Determine which correction we picked.
8133       Decl *Canonical = Result->getCanonicalDecl();
8134       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8135            I != E; ++I)
8136         if ((*I)->getCanonicalDecl() == Canonical)
8137           Correction.setCorrectionDecl(*I);
8138 
8139       // Let Sema know about the correction.
8140       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8141       SemaRef.diagnoseTypo(
8142           Correction,
8143           SemaRef.PDiag(IsLocalFriend
8144                           ? diag::err_no_matching_local_friend_suggest
8145                           : diag::err_member_decl_does_not_match_suggest)
8146             << Name << NewDC << IsDefinition);
8147       return Result;
8148     }
8149 
8150     // Pretend the typo correction never occurred
8151     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8152                               ExtraArgs.D.getIdentifierLoc());
8153     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8154     Previous.clear();
8155     Previous.setLookupName(Name);
8156   }
8157 
8158   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8159       << Name << NewDC << IsDefinition << NewFD->getLocation();
8160 
8161   bool NewFDisConst = false;
8162   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8163     NewFDisConst = NewMD->isConst();
8164 
8165   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8166        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8167        NearMatch != NearMatchEnd; ++NearMatch) {
8168     FunctionDecl *FD = NearMatch->first;
8169     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8170     bool FDisConst = MD && MD->isConst();
8171     bool IsMember = MD || !IsLocalFriend;
8172 
8173     // FIXME: These notes are poorly worded for the local friend case.
8174     if (unsigned Idx = NearMatch->second) {
8175       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8176       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8177       if (Loc.isInvalid()) Loc = FD->getLocation();
8178       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8179                                  : diag::note_local_decl_close_param_match)
8180         << Idx << FDParam->getType()
8181         << NewFD->getParamDecl(Idx - 1)->getType();
8182     } else if (FDisConst != NewFDisConst) {
8183       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8184           << NewFDisConst << FD->getSourceRange().getEnd();
8185     } else
8186       SemaRef.Diag(FD->getLocation(),
8187                    IsMember ? diag::note_member_def_close_match
8188                             : diag::note_local_decl_close_match);
8189   }
8190   return nullptr;
8191 }
8192 
8193 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8194   switch (D.getDeclSpec().getStorageClassSpec()) {
8195   default: llvm_unreachable("Unknown storage class!");
8196   case DeclSpec::SCS_auto:
8197   case DeclSpec::SCS_register:
8198   case DeclSpec::SCS_mutable:
8199     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8200                  diag::err_typecheck_sclass_func);
8201     D.getMutableDeclSpec().ClearStorageClassSpecs();
8202     D.setInvalidType();
8203     break;
8204   case DeclSpec::SCS_unspecified: break;
8205   case DeclSpec::SCS_extern:
8206     if (D.getDeclSpec().isExternInLinkageSpec())
8207       return SC_None;
8208     return SC_Extern;
8209   case DeclSpec::SCS_static: {
8210     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8211       // C99 6.7.1p5:
8212       //   The declaration of an identifier for a function that has
8213       //   block scope shall have no explicit storage-class specifier
8214       //   other than extern
8215       // See also (C++ [dcl.stc]p4).
8216       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8217                    diag::err_static_block_func);
8218       break;
8219     } else
8220       return SC_Static;
8221   }
8222   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8223   }
8224 
8225   // No explicit storage class has already been returned
8226   return SC_None;
8227 }
8228 
8229 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8230                                            DeclContext *DC, QualType &R,
8231                                            TypeSourceInfo *TInfo,
8232                                            StorageClass SC,
8233                                            bool &IsVirtualOkay) {
8234   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8235   DeclarationName Name = NameInfo.getName();
8236 
8237   FunctionDecl *NewFD = nullptr;
8238   bool isInline = D.getDeclSpec().isInlineSpecified();
8239 
8240   if (!SemaRef.getLangOpts().CPlusPlus) {
8241     // Determine whether the function was written with a
8242     // prototype. This true when:
8243     //   - there is a prototype in the declarator, or
8244     //   - the type R of the function is some kind of typedef or other non-
8245     //     attributed reference to a type name (which eventually refers to a
8246     //     function type).
8247     bool HasPrototype =
8248       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8249       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8250 
8251     NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8252                                  R, TInfo, SC, isInline, HasPrototype,
8253                                  CSK_unspecified,
8254                                  /*TrailingRequiresClause=*/nullptr);
8255     if (D.isInvalidType())
8256       NewFD->setInvalidDecl();
8257 
8258     return NewFD;
8259   }
8260 
8261   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8262 
8263   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8264   if (ConstexprKind == CSK_constinit) {
8265     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8266                  diag::err_constexpr_wrong_decl_kind)
8267         << ConstexprKind;
8268     ConstexprKind = CSK_unspecified;
8269     D.getMutableDeclSpec().ClearConstexprSpec();
8270   }
8271   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8272 
8273   // Check that the return type is not an abstract class type.
8274   // For record types, this is done by the AbstractClassUsageDiagnoser once
8275   // the class has been completely parsed.
8276   if (!DC->isRecord() &&
8277       SemaRef.RequireNonAbstractType(
8278           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8279           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8280     D.setInvalidType();
8281 
8282   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8283     // This is a C++ constructor declaration.
8284     assert(DC->isRecord() &&
8285            "Constructors can only be declared in a member context");
8286 
8287     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8288     return CXXConstructorDecl::Create(
8289         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8290         TInfo, ExplicitSpecifier, isInline,
8291         /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(),
8292         TrailingRequiresClause);
8293 
8294   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8295     // This is a C++ destructor declaration.
8296     if (DC->isRecord()) {
8297       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8298       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8299       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8300           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8301           isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8302           TrailingRequiresClause);
8303 
8304       // If the destructor needs an implicit exception specification, set it
8305       // now. FIXME: It'd be nice to be able to create the right type to start
8306       // with, but the type needs to reference the destructor declaration.
8307       if (SemaRef.getLangOpts().CPlusPlus11)
8308         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8309 
8310       IsVirtualOkay = true;
8311       return NewDD;
8312 
8313     } else {
8314       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8315       D.setInvalidType();
8316 
8317       // Create a FunctionDecl to satisfy the function definition parsing
8318       // code path.
8319       return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8320                                   D.getIdentifierLoc(), Name, R, TInfo, SC,
8321                                   isInline,
8322                                   /*hasPrototype=*/true, ConstexprKind,
8323                                   TrailingRequiresClause);
8324     }
8325 
8326   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8327     if (!DC->isRecord()) {
8328       SemaRef.Diag(D.getIdentifierLoc(),
8329            diag::err_conv_function_not_member);
8330       return nullptr;
8331     }
8332 
8333     SemaRef.CheckConversionDeclarator(D, R, SC);
8334     if (D.isInvalidType())
8335       return nullptr;
8336 
8337     IsVirtualOkay = true;
8338     return CXXConversionDecl::Create(
8339         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8340         TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(),
8341         TrailingRequiresClause);
8342 
8343   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8344     if (TrailingRequiresClause)
8345       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8346                    diag::err_trailing_requires_clause_on_deduction_guide)
8347           << TrailingRequiresClause->getSourceRange();
8348     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8349 
8350     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8351                                          ExplicitSpecifier, NameInfo, R, TInfo,
8352                                          D.getEndLoc());
8353   } else if (DC->isRecord()) {
8354     // If the name of the function is the same as the name of the record,
8355     // then this must be an invalid constructor that has a return type.
8356     // (The parser checks for a return type and makes the declarator a
8357     // constructor if it has no return type).
8358     if (Name.getAsIdentifierInfo() &&
8359         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8360       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8361         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8362         << SourceRange(D.getIdentifierLoc());
8363       return nullptr;
8364     }
8365 
8366     // This is a C++ method declaration.
8367     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8368         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8369         TInfo, SC, isInline, ConstexprKind, SourceLocation(),
8370         TrailingRequiresClause);
8371     IsVirtualOkay = !Ret->isStatic();
8372     return Ret;
8373   } else {
8374     bool isFriend =
8375         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8376     if (!isFriend && SemaRef.CurContext->isRecord())
8377       return nullptr;
8378 
8379     // Determine whether the function was written with a
8380     // prototype. This true when:
8381     //   - we're in C++ (where every function has a prototype),
8382     return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8383                                 R, TInfo, SC, isInline, true /*HasPrototype*/,
8384                                 ConstexprKind, TrailingRequiresClause);
8385   }
8386 }
8387 
8388 enum OpenCLParamType {
8389   ValidKernelParam,
8390   PtrPtrKernelParam,
8391   PtrKernelParam,
8392   InvalidAddrSpacePtrKernelParam,
8393   InvalidKernelParam,
8394   RecordKernelParam
8395 };
8396 
8397 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8398   // Size dependent types are just typedefs to normal integer types
8399   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8400   // integers other than by their names.
8401   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8402 
8403   // Remove typedefs one by one until we reach a typedef
8404   // for a size dependent type.
8405   QualType DesugaredTy = Ty;
8406   do {
8407     ArrayRef<StringRef> Names(SizeTypeNames);
8408     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8409     if (Names.end() != Match)
8410       return true;
8411 
8412     Ty = DesugaredTy;
8413     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8414   } while (DesugaredTy != Ty);
8415 
8416   return false;
8417 }
8418 
8419 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8420   if (PT->isPointerType()) {
8421     QualType PointeeType = PT->getPointeeType();
8422     if (PointeeType->isPointerType())
8423       return PtrPtrKernelParam;
8424     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8425         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8426         PointeeType.getAddressSpace() == LangAS::Default)
8427       return InvalidAddrSpacePtrKernelParam;
8428     return PtrKernelParam;
8429   }
8430 
8431   // OpenCL v1.2 s6.9.k:
8432   // Arguments to kernel functions in a program cannot be declared with the
8433   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8434   // uintptr_t or a struct and/or union that contain fields declared to be one
8435   // of these built-in scalar types.
8436   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8437     return InvalidKernelParam;
8438 
8439   if (PT->isImageType())
8440     return PtrKernelParam;
8441 
8442   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8443     return InvalidKernelParam;
8444 
8445   // OpenCL extension spec v1.2 s9.5:
8446   // This extension adds support for half scalar and vector types as built-in
8447   // types that can be used for arithmetic operations, conversions etc.
8448   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8449     return InvalidKernelParam;
8450 
8451   if (PT->isRecordType())
8452     return RecordKernelParam;
8453 
8454   // Look into an array argument to check if it has a forbidden type.
8455   if (PT->isArrayType()) {
8456     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8457     // Call ourself to check an underlying type of an array. Since the
8458     // getPointeeOrArrayElementType returns an innermost type which is not an
8459     // array, this recursive call only happens once.
8460     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8461   }
8462 
8463   return ValidKernelParam;
8464 }
8465 
8466 static void checkIsValidOpenCLKernelParameter(
8467   Sema &S,
8468   Declarator &D,
8469   ParmVarDecl *Param,
8470   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8471   QualType PT = Param->getType();
8472 
8473   // Cache the valid types we encounter to avoid rechecking structs that are
8474   // used again
8475   if (ValidTypes.count(PT.getTypePtr()))
8476     return;
8477 
8478   switch (getOpenCLKernelParameterType(S, PT)) {
8479   case PtrPtrKernelParam:
8480     // OpenCL v1.2 s6.9.a:
8481     // A kernel function argument cannot be declared as a
8482     // pointer to a pointer type.
8483     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8484     D.setInvalidType();
8485     return;
8486 
8487   case InvalidAddrSpacePtrKernelParam:
8488     // OpenCL v1.0 s6.5:
8489     // __kernel function arguments declared to be a pointer of a type can point
8490     // to one of the following address spaces only : __global, __local or
8491     // __constant.
8492     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8493     D.setInvalidType();
8494     return;
8495 
8496     // OpenCL v1.2 s6.9.k:
8497     // Arguments to kernel functions in a program cannot be declared with the
8498     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8499     // uintptr_t or a struct and/or union that contain fields declared to be
8500     // one of these built-in scalar types.
8501 
8502   case InvalidKernelParam:
8503     // OpenCL v1.2 s6.8 n:
8504     // A kernel function argument cannot be declared
8505     // of event_t type.
8506     // Do not diagnose half type since it is diagnosed as invalid argument
8507     // type for any function elsewhere.
8508     if (!PT->isHalfType()) {
8509       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8510 
8511       // Explain what typedefs are involved.
8512       const TypedefType *Typedef = nullptr;
8513       while ((Typedef = PT->getAs<TypedefType>())) {
8514         SourceLocation Loc = Typedef->getDecl()->getLocation();
8515         // SourceLocation may be invalid for a built-in type.
8516         if (Loc.isValid())
8517           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8518         PT = Typedef->desugar();
8519       }
8520     }
8521 
8522     D.setInvalidType();
8523     return;
8524 
8525   case PtrKernelParam:
8526   case ValidKernelParam:
8527     ValidTypes.insert(PT.getTypePtr());
8528     return;
8529 
8530   case RecordKernelParam:
8531     break;
8532   }
8533 
8534   // Track nested structs we will inspect
8535   SmallVector<const Decl *, 4> VisitStack;
8536 
8537   // Track where we are in the nested structs. Items will migrate from
8538   // VisitStack to HistoryStack as we do the DFS for bad field.
8539   SmallVector<const FieldDecl *, 4> HistoryStack;
8540   HistoryStack.push_back(nullptr);
8541 
8542   // At this point we already handled everything except of a RecordType or
8543   // an ArrayType of a RecordType.
8544   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8545   const RecordType *RecTy =
8546       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8547   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8548 
8549   VisitStack.push_back(RecTy->getDecl());
8550   assert(VisitStack.back() && "First decl null?");
8551 
8552   do {
8553     const Decl *Next = VisitStack.pop_back_val();
8554     if (!Next) {
8555       assert(!HistoryStack.empty());
8556       // Found a marker, we have gone up a level
8557       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8558         ValidTypes.insert(Hist->getType().getTypePtr());
8559 
8560       continue;
8561     }
8562 
8563     // Adds everything except the original parameter declaration (which is not a
8564     // field itself) to the history stack.
8565     const RecordDecl *RD;
8566     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8567       HistoryStack.push_back(Field);
8568 
8569       QualType FieldTy = Field->getType();
8570       // Other field types (known to be valid or invalid) are handled while we
8571       // walk around RecordDecl::fields().
8572       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8573              "Unexpected type.");
8574       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8575 
8576       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8577     } else {
8578       RD = cast<RecordDecl>(Next);
8579     }
8580 
8581     // Add a null marker so we know when we've gone back up a level
8582     VisitStack.push_back(nullptr);
8583 
8584     for (const auto *FD : RD->fields()) {
8585       QualType QT = FD->getType();
8586 
8587       if (ValidTypes.count(QT.getTypePtr()))
8588         continue;
8589 
8590       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8591       if (ParamType == ValidKernelParam)
8592         continue;
8593 
8594       if (ParamType == RecordKernelParam) {
8595         VisitStack.push_back(FD);
8596         continue;
8597       }
8598 
8599       // OpenCL v1.2 s6.9.p:
8600       // Arguments to kernel functions that are declared to be a struct or union
8601       // do not allow OpenCL objects to be passed as elements of the struct or
8602       // union.
8603       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8604           ParamType == InvalidAddrSpacePtrKernelParam) {
8605         S.Diag(Param->getLocation(),
8606                diag::err_record_with_pointers_kernel_param)
8607           << PT->isUnionType()
8608           << PT;
8609       } else {
8610         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8611       }
8612 
8613       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8614           << OrigRecDecl->getDeclName();
8615 
8616       // We have an error, now let's go back up through history and show where
8617       // the offending field came from
8618       for (ArrayRef<const FieldDecl *>::const_iterator
8619                I = HistoryStack.begin() + 1,
8620                E = HistoryStack.end();
8621            I != E; ++I) {
8622         const FieldDecl *OuterField = *I;
8623         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8624           << OuterField->getType();
8625       }
8626 
8627       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8628         << QT->isPointerType()
8629         << QT;
8630       D.setInvalidType();
8631       return;
8632     }
8633   } while (!VisitStack.empty());
8634 }
8635 
8636 /// Find the DeclContext in which a tag is implicitly declared if we see an
8637 /// elaborated type specifier in the specified context, and lookup finds
8638 /// nothing.
8639 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8640   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8641     DC = DC->getParent();
8642   return DC;
8643 }
8644 
8645 /// Find the Scope in which a tag is implicitly declared if we see an
8646 /// elaborated type specifier in the specified context, and lookup finds
8647 /// nothing.
8648 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8649   while (S->isClassScope() ||
8650          (LangOpts.CPlusPlus &&
8651           S->isFunctionPrototypeScope()) ||
8652          ((S->getFlags() & Scope::DeclScope) == 0) ||
8653          (S->getEntity() && S->getEntity()->isTransparentContext()))
8654     S = S->getParent();
8655   return S;
8656 }
8657 
8658 NamedDecl*
8659 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8660                               TypeSourceInfo *TInfo, LookupResult &Previous,
8661                               MultiTemplateParamsArg TemplateParamListsRef,
8662                               bool &AddToScope) {
8663   QualType R = TInfo->getType();
8664 
8665   assert(R->isFunctionType());
8666   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
8667   for (TemplateParameterList *TPL : TemplateParamListsRef)
8668     TemplateParamLists.push_back(TPL);
8669   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
8670     if (!TemplateParamLists.empty() &&
8671         Invented->getDepth() == TemplateParamLists.back()->getDepth())
8672       TemplateParamLists.back() = Invented;
8673     else
8674       TemplateParamLists.push_back(Invented);
8675   }
8676 
8677   // TODO: consider using NameInfo for diagnostic.
8678   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8679   DeclarationName Name = NameInfo.getName();
8680   StorageClass SC = getFunctionStorageClass(*this, D);
8681 
8682   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8683     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8684          diag::err_invalid_thread)
8685       << DeclSpec::getSpecifierName(TSCS);
8686 
8687   if (D.isFirstDeclarationOfMember())
8688     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8689                            D.getIdentifierLoc());
8690 
8691   bool isFriend = false;
8692   FunctionTemplateDecl *FunctionTemplate = nullptr;
8693   bool isMemberSpecialization = false;
8694   bool isFunctionTemplateSpecialization = false;
8695 
8696   bool isDependentClassScopeExplicitSpecialization = false;
8697   bool HasExplicitTemplateArgs = false;
8698   TemplateArgumentListInfo TemplateArgs;
8699 
8700   bool isVirtualOkay = false;
8701 
8702   DeclContext *OriginalDC = DC;
8703   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8704 
8705   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8706                                               isVirtualOkay);
8707   if (!NewFD) return nullptr;
8708 
8709   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8710     NewFD->setTopLevelDeclInObjCContainer();
8711 
8712   // Set the lexical context. If this is a function-scope declaration, or has a
8713   // C++ scope specifier, or is the object of a friend declaration, the lexical
8714   // context will be different from the semantic context.
8715   NewFD->setLexicalDeclContext(CurContext);
8716 
8717   if (IsLocalExternDecl)
8718     NewFD->setLocalExternDecl();
8719 
8720   if (getLangOpts().CPlusPlus) {
8721     bool isInline = D.getDeclSpec().isInlineSpecified();
8722     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8723     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
8724     isFriend = D.getDeclSpec().isFriendSpecified();
8725     if (isFriend && !isInline && D.isFunctionDefinition()) {
8726       // C++ [class.friend]p5
8727       //   A function can be defined in a friend declaration of a
8728       //   class . . . . Such a function is implicitly inline.
8729       NewFD->setImplicitlyInline();
8730     }
8731 
8732     // If this is a method defined in an __interface, and is not a constructor
8733     // or an overloaded operator, then set the pure flag (isVirtual will already
8734     // return true).
8735     if (const CXXRecordDecl *Parent =
8736           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8737       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8738         NewFD->setPure(true);
8739 
8740       // C++ [class.union]p2
8741       //   A union can have member functions, but not virtual functions.
8742       if (isVirtual && Parent->isUnion())
8743         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8744     }
8745 
8746     SetNestedNameSpecifier(*this, NewFD, D);
8747     isMemberSpecialization = false;
8748     isFunctionTemplateSpecialization = false;
8749     if (D.isInvalidType())
8750       NewFD->setInvalidDecl();
8751 
8752     // Match up the template parameter lists with the scope specifier, then
8753     // determine whether we have a template or a template specialization.
8754     bool Invalid = false;
8755     TemplateParameterList *TemplateParams =
8756         MatchTemplateParametersToScopeSpecifier(
8757             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8758             D.getCXXScopeSpec(),
8759             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8760                 ? D.getName().TemplateId
8761                 : nullptr,
8762             TemplateParamLists, isFriend, isMemberSpecialization,
8763             Invalid);
8764     if (TemplateParams) {
8765       if (TemplateParams->size() > 0) {
8766         // This is a function template
8767 
8768         // Check that we can declare a template here.
8769         if (CheckTemplateDeclScope(S, TemplateParams))
8770           NewFD->setInvalidDecl();
8771 
8772         // A destructor cannot be a template.
8773         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8774           Diag(NewFD->getLocation(), diag::err_destructor_template);
8775           NewFD->setInvalidDecl();
8776         }
8777 
8778         // If we're adding a template to a dependent context, we may need to
8779         // rebuilding some of the types used within the template parameter list,
8780         // now that we know what the current instantiation is.
8781         if (DC->isDependentContext()) {
8782           ContextRAII SavedContext(*this, DC);
8783           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8784             Invalid = true;
8785         }
8786 
8787         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8788                                                         NewFD->getLocation(),
8789                                                         Name, TemplateParams,
8790                                                         NewFD);
8791         FunctionTemplate->setLexicalDeclContext(CurContext);
8792         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8793 
8794         // For source fidelity, store the other template param lists.
8795         if (TemplateParamLists.size() > 1) {
8796           NewFD->setTemplateParameterListsInfo(Context,
8797               ArrayRef<TemplateParameterList *>(TemplateParamLists)
8798                   .drop_back(1));
8799         }
8800       } else {
8801         // This is a function template specialization.
8802         isFunctionTemplateSpecialization = true;
8803         // For source fidelity, store all the template param lists.
8804         if (TemplateParamLists.size() > 0)
8805           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8806 
8807         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8808         if (isFriend) {
8809           // We want to remove the "template<>", found here.
8810           SourceRange RemoveRange = TemplateParams->getSourceRange();
8811 
8812           // If we remove the template<> and the name is not a
8813           // template-id, we're actually silently creating a problem:
8814           // the friend declaration will refer to an untemplated decl,
8815           // and clearly the user wants a template specialization.  So
8816           // we need to insert '<>' after the name.
8817           SourceLocation InsertLoc;
8818           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8819             InsertLoc = D.getName().getSourceRange().getEnd();
8820             InsertLoc = getLocForEndOfToken(InsertLoc);
8821           }
8822 
8823           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8824             << Name << RemoveRange
8825             << FixItHint::CreateRemoval(RemoveRange)
8826             << FixItHint::CreateInsertion(InsertLoc, "<>");
8827         }
8828       }
8829     } else {
8830       // All template param lists were matched against the scope specifier:
8831       // this is NOT (an explicit specialization of) a template.
8832       if (TemplateParamLists.size() > 0)
8833         // For source fidelity, store all the template param lists.
8834         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8835     }
8836 
8837     if (Invalid) {
8838       NewFD->setInvalidDecl();
8839       if (FunctionTemplate)
8840         FunctionTemplate->setInvalidDecl();
8841     }
8842 
8843     // C++ [dcl.fct.spec]p5:
8844     //   The virtual specifier shall only be used in declarations of
8845     //   nonstatic class member functions that appear within a
8846     //   member-specification of a class declaration; see 10.3.
8847     //
8848     if (isVirtual && !NewFD->isInvalidDecl()) {
8849       if (!isVirtualOkay) {
8850         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8851              diag::err_virtual_non_function);
8852       } else if (!CurContext->isRecord()) {
8853         // 'virtual' was specified outside of the class.
8854         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8855              diag::err_virtual_out_of_class)
8856           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8857       } else if (NewFD->getDescribedFunctionTemplate()) {
8858         // C++ [temp.mem]p3:
8859         //  A member function template shall not be virtual.
8860         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8861              diag::err_virtual_member_function_template)
8862           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8863       } else {
8864         // Okay: Add virtual to the method.
8865         NewFD->setVirtualAsWritten(true);
8866       }
8867 
8868       if (getLangOpts().CPlusPlus14 &&
8869           NewFD->getReturnType()->isUndeducedType())
8870         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8871     }
8872 
8873     if (getLangOpts().CPlusPlus14 &&
8874         (NewFD->isDependentContext() ||
8875          (isFriend && CurContext->isDependentContext())) &&
8876         NewFD->getReturnType()->isUndeducedType()) {
8877       // If the function template is referenced directly (for instance, as a
8878       // member of the current instantiation), pretend it has a dependent type.
8879       // This is not really justified by the standard, but is the only sane
8880       // thing to do.
8881       // FIXME: For a friend function, we have not marked the function as being
8882       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8883       const FunctionProtoType *FPT =
8884           NewFD->getType()->castAs<FunctionProtoType>();
8885       QualType Result =
8886           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8887       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8888                                              FPT->getExtProtoInfo()));
8889     }
8890 
8891     // C++ [dcl.fct.spec]p3:
8892     //  The inline specifier shall not appear on a block scope function
8893     //  declaration.
8894     if (isInline && !NewFD->isInvalidDecl()) {
8895       if (CurContext->isFunctionOrMethod()) {
8896         // 'inline' is not allowed on block scope function declaration.
8897         Diag(D.getDeclSpec().getInlineSpecLoc(),
8898              diag::err_inline_declaration_block_scope) << Name
8899           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8900       }
8901     }
8902 
8903     // C++ [dcl.fct.spec]p6:
8904     //  The explicit specifier shall be used only in the declaration of a
8905     //  constructor or conversion function within its class definition;
8906     //  see 12.3.1 and 12.3.2.
8907     if (hasExplicit && !NewFD->isInvalidDecl() &&
8908         !isa<CXXDeductionGuideDecl>(NewFD)) {
8909       if (!CurContext->isRecord()) {
8910         // 'explicit' was specified outside of the class.
8911         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8912              diag::err_explicit_out_of_class)
8913             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
8914       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8915                  !isa<CXXConversionDecl>(NewFD)) {
8916         // 'explicit' was specified on a function that wasn't a constructor
8917         // or conversion function.
8918         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8919              diag::err_explicit_non_ctor_or_conv_function)
8920             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
8921       }
8922     }
8923 
8924     if (ConstexprSpecKind ConstexprKind =
8925             D.getDeclSpec().getConstexprSpecifier()) {
8926       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8927       // are implicitly inline.
8928       NewFD->setImplicitlyInline();
8929 
8930       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8931       // be either constructors or to return a literal type. Therefore,
8932       // destructors cannot be declared constexpr.
8933       if (isa<CXXDestructorDecl>(NewFD) && !getLangOpts().CPlusPlus2a) {
8934         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
8935             << ConstexprKind;
8936       }
8937     }
8938 
8939     // If __module_private__ was specified, mark the function accordingly.
8940     if (D.getDeclSpec().isModulePrivateSpecified()) {
8941       if (isFunctionTemplateSpecialization) {
8942         SourceLocation ModulePrivateLoc
8943           = D.getDeclSpec().getModulePrivateSpecLoc();
8944         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8945           << 0
8946           << FixItHint::CreateRemoval(ModulePrivateLoc);
8947       } else {
8948         NewFD->setModulePrivate();
8949         if (FunctionTemplate)
8950           FunctionTemplate->setModulePrivate();
8951       }
8952     }
8953 
8954     if (isFriend) {
8955       if (FunctionTemplate) {
8956         FunctionTemplate->setObjectOfFriendDecl();
8957         FunctionTemplate->setAccess(AS_public);
8958       }
8959       NewFD->setObjectOfFriendDecl();
8960       NewFD->setAccess(AS_public);
8961     }
8962 
8963     // If a function is defined as defaulted or deleted, mark it as such now.
8964     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8965     // definition kind to FDK_Definition.
8966     switch (D.getFunctionDefinitionKind()) {
8967       case FDK_Declaration:
8968       case FDK_Definition:
8969         break;
8970 
8971       case FDK_Defaulted:
8972         NewFD->setDefaulted();
8973         break;
8974 
8975       case FDK_Deleted:
8976         NewFD->setDeletedAsWritten();
8977         break;
8978     }
8979 
8980     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8981         D.isFunctionDefinition()) {
8982       // C++ [class.mfct]p2:
8983       //   A member function may be defined (8.4) in its class definition, in
8984       //   which case it is an inline member function (7.1.2)
8985       NewFD->setImplicitlyInline();
8986     }
8987 
8988     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8989         !CurContext->isRecord()) {
8990       // C++ [class.static]p1:
8991       //   A data or function member of a class may be declared static
8992       //   in a class definition, in which case it is a static member of
8993       //   the class.
8994 
8995       // Complain about the 'static' specifier if it's on an out-of-line
8996       // member function definition.
8997 
8998       // MSVC permits the use of a 'static' storage specifier on an out-of-line
8999       // member function template declaration and class member template
9000       // declaration (MSVC versions before 2015), warn about this.
9001       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9002            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9003              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9004            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9005            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9006         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9007     }
9008 
9009     // C++11 [except.spec]p15:
9010     //   A deallocation function with no exception-specification is treated
9011     //   as if it were specified with noexcept(true).
9012     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9013     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9014          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9015         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9016       NewFD->setType(Context.getFunctionType(
9017           FPT->getReturnType(), FPT->getParamTypes(),
9018           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9019   }
9020 
9021   // Filter out previous declarations that don't match the scope.
9022   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9023                        D.getCXXScopeSpec().isNotEmpty() ||
9024                        isMemberSpecialization ||
9025                        isFunctionTemplateSpecialization);
9026 
9027   // Handle GNU asm-label extension (encoded as an attribute).
9028   if (Expr *E = (Expr*) D.getAsmLabel()) {
9029     // The parser guarantees this is a string.
9030     StringLiteral *SE = cast<StringLiteral>(E);
9031     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9032                                         /*IsLiteralLabel=*/true,
9033                                         SE->getStrTokenLoc(0)));
9034   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9035     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9036       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9037     if (I != ExtnameUndeclaredIdentifiers.end()) {
9038       if (isDeclExternC(NewFD)) {
9039         NewFD->addAttr(I->second);
9040         ExtnameUndeclaredIdentifiers.erase(I);
9041       } else
9042         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9043             << /*Variable*/0 << NewFD;
9044     }
9045   }
9046 
9047   // Copy the parameter declarations from the declarator D to the function
9048   // declaration NewFD, if they are available.  First scavenge them into Params.
9049   SmallVector<ParmVarDecl*, 16> Params;
9050   unsigned FTIIdx;
9051   if (D.isFunctionDeclarator(FTIIdx)) {
9052     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9053 
9054     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9055     // function that takes no arguments, not a function that takes a
9056     // single void argument.
9057     // We let through "const void" here because Sema::GetTypeForDeclarator
9058     // already checks for that case.
9059     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9060       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9061         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9062         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9063         Param->setDeclContext(NewFD);
9064         Params.push_back(Param);
9065 
9066         if (Param->isInvalidDecl())
9067           NewFD->setInvalidDecl();
9068       }
9069     }
9070 
9071     if (!getLangOpts().CPlusPlus) {
9072       // In C, find all the tag declarations from the prototype and move them
9073       // into the function DeclContext. Remove them from the surrounding tag
9074       // injection context of the function, which is typically but not always
9075       // the TU.
9076       DeclContext *PrototypeTagContext =
9077           getTagInjectionContext(NewFD->getLexicalDeclContext());
9078       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9079         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9080 
9081         // We don't want to reparent enumerators. Look at their parent enum
9082         // instead.
9083         if (!TD) {
9084           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9085             TD = cast<EnumDecl>(ECD->getDeclContext());
9086         }
9087         if (!TD)
9088           continue;
9089         DeclContext *TagDC = TD->getLexicalDeclContext();
9090         if (!TagDC->containsDecl(TD))
9091           continue;
9092         TagDC->removeDecl(TD);
9093         TD->setDeclContext(NewFD);
9094         NewFD->addDecl(TD);
9095 
9096         // Preserve the lexical DeclContext if it is not the surrounding tag
9097         // injection context of the FD. In this example, the semantic context of
9098         // E will be f and the lexical context will be S, while both the
9099         // semantic and lexical contexts of S will be f:
9100         //   void f(struct S { enum E { a } f; } s);
9101         if (TagDC != PrototypeTagContext)
9102           TD->setLexicalDeclContext(TagDC);
9103       }
9104     }
9105   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9106     // When we're declaring a function with a typedef, typeof, etc as in the
9107     // following example, we'll need to synthesize (unnamed)
9108     // parameters for use in the declaration.
9109     //
9110     // @code
9111     // typedef void fn(int);
9112     // fn f;
9113     // @endcode
9114 
9115     // Synthesize a parameter for each argument type.
9116     for (const auto &AI : FT->param_types()) {
9117       ParmVarDecl *Param =
9118           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9119       Param->setScopeInfo(0, Params.size());
9120       Params.push_back(Param);
9121     }
9122   } else {
9123     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9124            "Should not need args for typedef of non-prototype fn");
9125   }
9126 
9127   // Finally, we know we have the right number of parameters, install them.
9128   NewFD->setParams(Params);
9129 
9130   if (D.getDeclSpec().isNoreturnSpecified())
9131     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9132                                            D.getDeclSpec().getNoreturnSpecLoc(),
9133                                            AttributeCommonInfo::AS_Keyword));
9134 
9135   // Functions returning a variably modified type violate C99 6.7.5.2p2
9136   // because all functions have linkage.
9137   if (!NewFD->isInvalidDecl() &&
9138       NewFD->getReturnType()->isVariablyModifiedType()) {
9139     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9140     NewFD->setInvalidDecl();
9141   }
9142 
9143   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9144   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9145       !NewFD->hasAttr<SectionAttr>())
9146     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9147         Context, PragmaClangTextSection.SectionName,
9148         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9149 
9150   // Apply an implicit SectionAttr if #pragma code_seg is active.
9151   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9152       !NewFD->hasAttr<SectionAttr>()) {
9153     NewFD->addAttr(SectionAttr::CreateImplicit(
9154         Context, CodeSegStack.CurrentValue->getString(),
9155         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9156         SectionAttr::Declspec_allocate));
9157     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9158                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9159                          ASTContext::PSF_Read,
9160                      NewFD))
9161       NewFD->dropAttr<SectionAttr>();
9162   }
9163 
9164   // Apply an implicit CodeSegAttr from class declspec or
9165   // apply an implicit SectionAttr from #pragma code_seg if active.
9166   if (!NewFD->hasAttr<CodeSegAttr>()) {
9167     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9168                                                                  D.isFunctionDefinition())) {
9169       NewFD->addAttr(SAttr);
9170     }
9171   }
9172 
9173   // Handle attributes.
9174   ProcessDeclAttributes(S, NewFD, D);
9175 
9176   if (getLangOpts().OpenCL) {
9177     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9178     // type declaration will generate a compilation error.
9179     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9180     if (AddressSpace != LangAS::Default) {
9181       Diag(NewFD->getLocation(),
9182            diag::err_opencl_return_value_with_address_space);
9183       NewFD->setInvalidDecl();
9184     }
9185   }
9186 
9187   if (!getLangOpts().CPlusPlus) {
9188     // Perform semantic checking on the function declaration.
9189     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9190       CheckMain(NewFD, D.getDeclSpec());
9191 
9192     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9193       CheckMSVCRTEntryPoint(NewFD);
9194 
9195     if (!NewFD->isInvalidDecl())
9196       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9197                                                   isMemberSpecialization));
9198     else if (!Previous.empty())
9199       // Recover gracefully from an invalid redeclaration.
9200       D.setRedeclaration(true);
9201     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9202             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9203            "previous declaration set still overloaded");
9204 
9205     // Diagnose no-prototype function declarations with calling conventions that
9206     // don't support variadic calls. Only do this in C and do it after merging
9207     // possibly prototyped redeclarations.
9208     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9209     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9210       CallingConv CC = FT->getExtInfo().getCC();
9211       if (!supportsVariadicCall(CC)) {
9212         // Windows system headers sometimes accidentally use stdcall without
9213         // (void) parameters, so we relax this to a warning.
9214         int DiagID =
9215             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9216         Diag(NewFD->getLocation(), DiagID)
9217             << FunctionType::getNameForCallConv(CC);
9218       }
9219     }
9220 
9221    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9222        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9223      checkNonTrivialCUnion(NewFD->getReturnType(),
9224                            NewFD->getReturnTypeSourceRange().getBegin(),
9225                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9226   } else {
9227     // C++11 [replacement.functions]p3:
9228     //  The program's definitions shall not be specified as inline.
9229     //
9230     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9231     //
9232     // Suppress the diagnostic if the function is __attribute__((used)), since
9233     // that forces an external definition to be emitted.
9234     if (D.getDeclSpec().isInlineSpecified() &&
9235         NewFD->isReplaceableGlobalAllocationFunction() &&
9236         !NewFD->hasAttr<UsedAttr>())
9237       Diag(D.getDeclSpec().getInlineSpecLoc(),
9238            diag::ext_operator_new_delete_declared_inline)
9239         << NewFD->getDeclName();
9240 
9241     // If the declarator is a template-id, translate the parser's template
9242     // argument list into our AST format.
9243     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9244       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9245       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9246       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9247       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9248                                          TemplateId->NumArgs);
9249       translateTemplateArguments(TemplateArgsPtr,
9250                                  TemplateArgs);
9251 
9252       HasExplicitTemplateArgs = true;
9253 
9254       if (NewFD->isInvalidDecl()) {
9255         HasExplicitTemplateArgs = false;
9256       } else if (FunctionTemplate) {
9257         // Function template with explicit template arguments.
9258         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9259           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9260 
9261         HasExplicitTemplateArgs = false;
9262       } else {
9263         assert((isFunctionTemplateSpecialization ||
9264                 D.getDeclSpec().isFriendSpecified()) &&
9265                "should have a 'template<>' for this decl");
9266         // "friend void foo<>(int);" is an implicit specialization decl.
9267         isFunctionTemplateSpecialization = true;
9268       }
9269     } else if (isFriend && isFunctionTemplateSpecialization) {
9270       // This combination is only possible in a recovery case;  the user
9271       // wrote something like:
9272       //   template <> friend void foo(int);
9273       // which we're recovering from as if the user had written:
9274       //   friend void foo<>(int);
9275       // Go ahead and fake up a template id.
9276       HasExplicitTemplateArgs = true;
9277       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9278       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9279     }
9280 
9281     // We do not add HD attributes to specializations here because
9282     // they may have different constexpr-ness compared to their
9283     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9284     // may end up with different effective targets. Instead, a
9285     // specialization inherits its target attributes from its template
9286     // in the CheckFunctionTemplateSpecialization() call below.
9287     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9288       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9289 
9290     // If it's a friend (and only if it's a friend), it's possible
9291     // that either the specialized function type or the specialized
9292     // template is dependent, and therefore matching will fail.  In
9293     // this case, don't check the specialization yet.
9294     bool InstantiationDependent = false;
9295     if (isFunctionTemplateSpecialization && isFriend &&
9296         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9297          TemplateSpecializationType::anyDependentTemplateArguments(
9298             TemplateArgs,
9299             InstantiationDependent))) {
9300       assert(HasExplicitTemplateArgs &&
9301              "friend function specialization without template args");
9302       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9303                                                        Previous))
9304         NewFD->setInvalidDecl();
9305     } else if (isFunctionTemplateSpecialization) {
9306       if (CurContext->isDependentContext() && CurContext->isRecord()
9307           && !isFriend) {
9308         isDependentClassScopeExplicitSpecialization = true;
9309       } else if (!NewFD->isInvalidDecl() &&
9310                  CheckFunctionTemplateSpecialization(
9311                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9312                      Previous))
9313         NewFD->setInvalidDecl();
9314 
9315       // C++ [dcl.stc]p1:
9316       //   A storage-class-specifier shall not be specified in an explicit
9317       //   specialization (14.7.3)
9318       FunctionTemplateSpecializationInfo *Info =
9319           NewFD->getTemplateSpecializationInfo();
9320       if (Info && SC != SC_None) {
9321         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9322           Diag(NewFD->getLocation(),
9323                diag::err_explicit_specialization_inconsistent_storage_class)
9324             << SC
9325             << FixItHint::CreateRemoval(
9326                                       D.getDeclSpec().getStorageClassSpecLoc());
9327 
9328         else
9329           Diag(NewFD->getLocation(),
9330                diag::ext_explicit_specialization_storage_class)
9331             << FixItHint::CreateRemoval(
9332                                       D.getDeclSpec().getStorageClassSpecLoc());
9333       }
9334     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9335       if (CheckMemberSpecialization(NewFD, Previous))
9336           NewFD->setInvalidDecl();
9337     }
9338 
9339     // Perform semantic checking on the function declaration.
9340     if (!isDependentClassScopeExplicitSpecialization) {
9341       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9342         CheckMain(NewFD, D.getDeclSpec());
9343 
9344       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9345         CheckMSVCRTEntryPoint(NewFD);
9346 
9347       if (!NewFD->isInvalidDecl())
9348         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9349                                                     isMemberSpecialization));
9350       else if (!Previous.empty())
9351         // Recover gracefully from an invalid redeclaration.
9352         D.setRedeclaration(true);
9353     }
9354 
9355     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9356             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9357            "previous declaration set still overloaded");
9358 
9359     NamedDecl *PrincipalDecl = (FunctionTemplate
9360                                 ? cast<NamedDecl>(FunctionTemplate)
9361                                 : NewFD);
9362 
9363     if (isFriend && NewFD->getPreviousDecl()) {
9364       AccessSpecifier Access = AS_public;
9365       if (!NewFD->isInvalidDecl())
9366         Access = NewFD->getPreviousDecl()->getAccess();
9367 
9368       NewFD->setAccess(Access);
9369       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9370     }
9371 
9372     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9373         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9374       PrincipalDecl->setNonMemberOperator();
9375 
9376     // If we have a function template, check the template parameter
9377     // list. This will check and merge default template arguments.
9378     if (FunctionTemplate) {
9379       FunctionTemplateDecl *PrevTemplate =
9380                                      FunctionTemplate->getPreviousDecl();
9381       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9382                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9383                                     : nullptr,
9384                             D.getDeclSpec().isFriendSpecified()
9385                               ? (D.isFunctionDefinition()
9386                                    ? TPC_FriendFunctionTemplateDefinition
9387                                    : TPC_FriendFunctionTemplate)
9388                               : (D.getCXXScopeSpec().isSet() &&
9389                                  DC && DC->isRecord() &&
9390                                  DC->isDependentContext())
9391                                   ? TPC_ClassTemplateMember
9392                                   : TPC_FunctionTemplate);
9393     }
9394 
9395     if (NewFD->isInvalidDecl()) {
9396       // Ignore all the rest of this.
9397     } else if (!D.isRedeclaration()) {
9398       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9399                                        AddToScope };
9400       // Fake up an access specifier if it's supposed to be a class member.
9401       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9402         NewFD->setAccess(AS_public);
9403 
9404       // Qualified decls generally require a previous declaration.
9405       if (D.getCXXScopeSpec().isSet()) {
9406         // ...with the major exception of templated-scope or
9407         // dependent-scope friend declarations.
9408 
9409         // TODO: we currently also suppress this check in dependent
9410         // contexts because (1) the parameter depth will be off when
9411         // matching friend templates and (2) we might actually be
9412         // selecting a friend based on a dependent factor.  But there
9413         // are situations where these conditions don't apply and we
9414         // can actually do this check immediately.
9415         //
9416         // Unless the scope is dependent, it's always an error if qualified
9417         // redeclaration lookup found nothing at all. Diagnose that now;
9418         // nothing will diagnose that error later.
9419         if (isFriend &&
9420             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9421              (!Previous.empty() && CurContext->isDependentContext()))) {
9422           // ignore these
9423         } else {
9424           // The user tried to provide an out-of-line definition for a
9425           // function that is a member of a class or namespace, but there
9426           // was no such member function declared (C++ [class.mfct]p2,
9427           // C++ [namespace.memdef]p2). For example:
9428           //
9429           // class X {
9430           //   void f() const;
9431           // };
9432           //
9433           // void X::f() { } // ill-formed
9434           //
9435           // Complain about this problem, and attempt to suggest close
9436           // matches (e.g., those that differ only in cv-qualifiers and
9437           // whether the parameter types are references).
9438 
9439           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9440                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9441             AddToScope = ExtraArgs.AddToScope;
9442             return Result;
9443           }
9444         }
9445 
9446         // Unqualified local friend declarations are required to resolve
9447         // to something.
9448       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9449         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9450                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9451           AddToScope = ExtraArgs.AddToScope;
9452           return Result;
9453         }
9454       }
9455     } else if (!D.isFunctionDefinition() &&
9456                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9457                !isFriend && !isFunctionTemplateSpecialization &&
9458                !isMemberSpecialization) {
9459       // An out-of-line member function declaration must also be a
9460       // definition (C++ [class.mfct]p2).
9461       // Note that this is not the case for explicit specializations of
9462       // function templates or member functions of class templates, per
9463       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9464       // extension for compatibility with old SWIG code which likes to
9465       // generate them.
9466       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9467         << D.getCXXScopeSpec().getRange();
9468     }
9469   }
9470 
9471   ProcessPragmaWeak(S, NewFD);
9472   checkAttributesAfterMerging(*this, *NewFD);
9473 
9474   AddKnownFunctionAttributes(NewFD);
9475 
9476   if (NewFD->hasAttr<OverloadableAttr>() &&
9477       !NewFD->getType()->getAs<FunctionProtoType>()) {
9478     Diag(NewFD->getLocation(),
9479          diag::err_attribute_overloadable_no_prototype)
9480       << NewFD;
9481 
9482     // Turn this into a variadic function with no parameters.
9483     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9484     FunctionProtoType::ExtProtoInfo EPI(
9485         Context.getDefaultCallingConvention(true, false));
9486     EPI.Variadic = true;
9487     EPI.ExtInfo = FT->getExtInfo();
9488 
9489     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9490     NewFD->setType(R);
9491   }
9492 
9493   // If there's a #pragma GCC visibility in scope, and this isn't a class
9494   // member, set the visibility of this function.
9495   if (!DC->isRecord() && NewFD->isExternallyVisible())
9496     AddPushedVisibilityAttribute(NewFD);
9497 
9498   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9499   // marking the function.
9500   AddCFAuditedAttribute(NewFD);
9501 
9502   // If this is a function definition, check if we have to apply optnone due to
9503   // a pragma.
9504   if(D.isFunctionDefinition())
9505     AddRangeBasedOptnone(NewFD);
9506 
9507   // If this is the first declaration of an extern C variable, update
9508   // the map of such variables.
9509   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9510       isIncompleteDeclExternC(*this, NewFD))
9511     RegisterLocallyScopedExternCDecl(NewFD, S);
9512 
9513   // Set this FunctionDecl's range up to the right paren.
9514   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9515 
9516   if (D.isRedeclaration() && !Previous.empty()) {
9517     NamedDecl *Prev = Previous.getRepresentativeDecl();
9518     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9519                                    isMemberSpecialization ||
9520                                        isFunctionTemplateSpecialization,
9521                                    D.isFunctionDefinition());
9522   }
9523 
9524   if (getLangOpts().CUDA) {
9525     IdentifierInfo *II = NewFD->getIdentifier();
9526     if (II && II->isStr(getCudaConfigureFuncName()) &&
9527         !NewFD->isInvalidDecl() &&
9528         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9529       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9530         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9531             << getCudaConfigureFuncName();
9532       Context.setcudaConfigureCallDecl(NewFD);
9533     }
9534 
9535     // Variadic functions, other than a *declaration* of printf, are not allowed
9536     // in device-side CUDA code, unless someone passed
9537     // -fcuda-allow-variadic-functions.
9538     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9539         (NewFD->hasAttr<CUDADeviceAttr>() ||
9540          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9541         !(II && II->isStr("printf") && NewFD->isExternC() &&
9542           !D.isFunctionDefinition())) {
9543       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9544     }
9545   }
9546 
9547   MarkUnusedFileScopedDecl(NewFD);
9548 
9549 
9550 
9551   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9552     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9553     if ((getLangOpts().OpenCLVersion >= 120)
9554         && (SC == SC_Static)) {
9555       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9556       D.setInvalidType();
9557     }
9558 
9559     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9560     if (!NewFD->getReturnType()->isVoidType()) {
9561       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9562       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9563           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9564                                 : FixItHint());
9565       D.setInvalidType();
9566     }
9567 
9568     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9569     for (auto Param : NewFD->parameters())
9570       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9571 
9572     if (getLangOpts().OpenCLCPlusPlus) {
9573       if (DC->isRecord()) {
9574         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9575         D.setInvalidType();
9576       }
9577       if (FunctionTemplate) {
9578         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9579         D.setInvalidType();
9580       }
9581     }
9582   }
9583 
9584   if (getLangOpts().CPlusPlus) {
9585     if (FunctionTemplate) {
9586       if (NewFD->isInvalidDecl())
9587         FunctionTemplate->setInvalidDecl();
9588       return FunctionTemplate;
9589     }
9590 
9591     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9592       CompleteMemberSpecialization(NewFD, Previous);
9593   }
9594 
9595   for (const ParmVarDecl *Param : NewFD->parameters()) {
9596     QualType PT = Param->getType();
9597 
9598     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9599     // types.
9600     if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
9601       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9602         QualType ElemTy = PipeTy->getElementType();
9603           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9604             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9605             D.setInvalidType();
9606           }
9607       }
9608     }
9609   }
9610 
9611   // Here we have an function template explicit specialization at class scope.
9612   // The actual specialization will be postponed to template instatiation
9613   // time via the ClassScopeFunctionSpecializationDecl node.
9614   if (isDependentClassScopeExplicitSpecialization) {
9615     ClassScopeFunctionSpecializationDecl *NewSpec =
9616                          ClassScopeFunctionSpecializationDecl::Create(
9617                                 Context, CurContext, NewFD->getLocation(),
9618                                 cast<CXXMethodDecl>(NewFD),
9619                                 HasExplicitTemplateArgs, TemplateArgs);
9620     CurContext->addDecl(NewSpec);
9621     AddToScope = false;
9622   }
9623 
9624   // Diagnose availability attributes. Availability cannot be used on functions
9625   // that are run during load/unload.
9626   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9627     if (NewFD->hasAttr<ConstructorAttr>()) {
9628       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9629           << 1;
9630       NewFD->dropAttr<AvailabilityAttr>();
9631     }
9632     if (NewFD->hasAttr<DestructorAttr>()) {
9633       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9634           << 2;
9635       NewFD->dropAttr<AvailabilityAttr>();
9636     }
9637   }
9638 
9639   // Diagnose no_builtin attribute on function declaration that are not a
9640   // definition.
9641   // FIXME: We should really be doing this in
9642   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
9643   // the FunctionDecl and at this point of the code
9644   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
9645   // because Sema::ActOnStartOfFunctionDef has not been called yet.
9646   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
9647     switch (D.getFunctionDefinitionKind()) {
9648     case FDK_Defaulted:
9649     case FDK_Deleted:
9650       Diag(NBA->getLocation(),
9651            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
9652           << NBA->getSpelling();
9653       break;
9654     case FDK_Declaration:
9655       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
9656           << NBA->getSpelling();
9657       break;
9658     case FDK_Definition:
9659       break;
9660     }
9661 
9662   return NewFD;
9663 }
9664 
9665 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
9666 /// when __declspec(code_seg) "is applied to a class, all member functions of
9667 /// the class and nested classes -- this includes compiler-generated special
9668 /// member functions -- are put in the specified segment."
9669 /// The actual behavior is a little more complicated. The Microsoft compiler
9670 /// won't check outer classes if there is an active value from #pragma code_seg.
9671 /// The CodeSeg is always applied from the direct parent but only from outer
9672 /// classes when the #pragma code_seg stack is empty. See:
9673 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9674 /// available since MS has removed the page.
9675 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9676   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9677   if (!Method)
9678     return nullptr;
9679   const CXXRecordDecl *Parent = Method->getParent();
9680   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9681     Attr *NewAttr = SAttr->clone(S.getASTContext());
9682     NewAttr->setImplicit(true);
9683     return NewAttr;
9684   }
9685 
9686   // The Microsoft compiler won't check outer classes for the CodeSeg
9687   // when the #pragma code_seg stack is active.
9688   if (S.CodeSegStack.CurrentValue)
9689    return nullptr;
9690 
9691   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9692     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9693       Attr *NewAttr = SAttr->clone(S.getASTContext());
9694       NewAttr->setImplicit(true);
9695       return NewAttr;
9696     }
9697   }
9698   return nullptr;
9699 }
9700 
9701 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9702 /// containing class. Otherwise it will return implicit SectionAttr if the
9703 /// function is a definition and there is an active value on CodeSegStack
9704 /// (from the current #pragma code-seg value).
9705 ///
9706 /// \param FD Function being declared.
9707 /// \param IsDefinition Whether it is a definition or just a declarartion.
9708 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
9709 ///          nullptr if no attribute should be added.
9710 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9711                                                        bool IsDefinition) {
9712   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9713     return A;
9714   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9715       CodeSegStack.CurrentValue)
9716     return SectionAttr::CreateImplicit(
9717         getASTContext(), CodeSegStack.CurrentValue->getString(),
9718         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9719         SectionAttr::Declspec_allocate);
9720   return nullptr;
9721 }
9722 
9723 /// Determines if we can perform a correct type check for \p D as a
9724 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
9725 /// best-effort check.
9726 ///
9727 /// \param NewD The new declaration.
9728 /// \param OldD The old declaration.
9729 /// \param NewT The portion of the type of the new declaration to check.
9730 /// \param OldT The portion of the type of the old declaration to check.
9731 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
9732                                           QualType NewT, QualType OldT) {
9733   if (!NewD->getLexicalDeclContext()->isDependentContext())
9734     return true;
9735 
9736   // For dependently-typed local extern declarations and friends, we can't
9737   // perform a correct type check in general until instantiation:
9738   //
9739   //   int f();
9740   //   template<typename T> void g() { T f(); }
9741   //
9742   // (valid if g() is only instantiated with T = int).
9743   if (NewT->isDependentType() &&
9744       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
9745     return false;
9746 
9747   // Similarly, if the previous declaration was a dependent local extern
9748   // declaration, we don't really know its type yet.
9749   if (OldT->isDependentType() && OldD->isLocalExternDecl())
9750     return false;
9751 
9752   return true;
9753 }
9754 
9755 /// Checks if the new declaration declared in dependent context must be
9756 /// put in the same redeclaration chain as the specified declaration.
9757 ///
9758 /// \param D Declaration that is checked.
9759 /// \param PrevDecl Previous declaration found with proper lookup method for the
9760 ///                 same declaration name.
9761 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9762 ///          belongs to.
9763 ///
9764 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9765   if (!D->getLexicalDeclContext()->isDependentContext())
9766     return true;
9767 
9768   // Don't chain dependent friend function definitions until instantiation, to
9769   // permit cases like
9770   //
9771   //   void func();
9772   //   template<typename T> class C1 { friend void func() {} };
9773   //   template<typename T> class C2 { friend void func() {} };
9774   //
9775   // ... which is valid if only one of C1 and C2 is ever instantiated.
9776   //
9777   // FIXME: This need only apply to function definitions. For now, we proxy
9778   // this by checking for a file-scope function. We do not want this to apply
9779   // to friend declarations nominating member functions, because that gets in
9780   // the way of access checks.
9781   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
9782     return false;
9783 
9784   auto *VD = dyn_cast<ValueDecl>(D);
9785   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
9786   return !VD || !PrevVD ||
9787          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
9788                                         PrevVD->getType());
9789 }
9790 
9791 /// Check the target attribute of the function for MultiVersion
9792 /// validity.
9793 ///
9794 /// Returns true if there was an error, false otherwise.
9795 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9796   const auto *TA = FD->getAttr<TargetAttr>();
9797   assert(TA && "MultiVersion Candidate requires a target attribute");
9798   ParsedTargetAttr ParseInfo = TA->parse();
9799   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9800   enum ErrType { Feature = 0, Architecture = 1 };
9801 
9802   if (!ParseInfo.Architecture.empty() &&
9803       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
9804     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9805         << Architecture << ParseInfo.Architecture;
9806     return true;
9807   }
9808 
9809   for (const auto &Feat : ParseInfo.Features) {
9810     auto BareFeat = StringRef{Feat}.substr(1);
9811     if (Feat[0] == '-') {
9812       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9813           << Feature << ("no-" + BareFeat).str();
9814       return true;
9815     }
9816 
9817     if (!TargetInfo.validateCpuSupports(BareFeat) ||
9818         !TargetInfo.isValidFeatureName(BareFeat)) {
9819       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9820           << Feature << BareFeat;
9821       return true;
9822     }
9823   }
9824   return false;
9825 }
9826 
9827 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD,
9828                                          MultiVersionKind MVType) {
9829   for (const Attr *A : FD->attrs()) {
9830     switch (A->getKind()) {
9831     case attr::CPUDispatch:
9832     case attr::CPUSpecific:
9833       if (MVType != MultiVersionKind::CPUDispatch &&
9834           MVType != MultiVersionKind::CPUSpecific)
9835         return true;
9836       break;
9837     case attr::Target:
9838       if (MVType != MultiVersionKind::Target)
9839         return true;
9840       break;
9841     default:
9842       return true;
9843     }
9844   }
9845   return false;
9846 }
9847 
9848 bool Sema::areMultiversionVariantFunctionsCompatible(
9849     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
9850     const PartialDiagnostic &NoProtoDiagID,
9851     const PartialDiagnosticAt &NoteCausedDiagIDAt,
9852     const PartialDiagnosticAt &NoSupportDiagIDAt,
9853     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
9854     bool ConstexprSupported, bool CLinkageMayDiffer) {
9855   enum DoesntSupport {
9856     FuncTemplates = 0,
9857     VirtFuncs = 1,
9858     DeducedReturn = 2,
9859     Constructors = 3,
9860     Destructors = 4,
9861     DeletedFuncs = 5,
9862     DefaultedFuncs = 6,
9863     ConstexprFuncs = 7,
9864     ConstevalFuncs = 8,
9865   };
9866   enum Different {
9867     CallingConv = 0,
9868     ReturnType = 1,
9869     ConstexprSpec = 2,
9870     InlineSpec = 3,
9871     StorageClass = 4,
9872     Linkage = 5,
9873   };
9874 
9875   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
9876       !OldFD->getType()->getAs<FunctionProtoType>()) {
9877     Diag(OldFD->getLocation(), NoProtoDiagID);
9878     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
9879     return true;
9880   }
9881 
9882   if (NoProtoDiagID.getDiagID() != 0 &&
9883       !NewFD->getType()->getAs<FunctionProtoType>())
9884     return Diag(NewFD->getLocation(), NoProtoDiagID);
9885 
9886   if (!TemplatesSupported &&
9887       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9888     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9889            << FuncTemplates;
9890 
9891   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
9892     if (NewCXXFD->isVirtual())
9893       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9894              << VirtFuncs;
9895 
9896     if (isa<CXXConstructorDecl>(NewCXXFD))
9897       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9898              << Constructors;
9899 
9900     if (isa<CXXDestructorDecl>(NewCXXFD))
9901       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9902              << Destructors;
9903   }
9904 
9905   if (NewFD->isDeleted())
9906     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9907            << DeletedFuncs;
9908 
9909   if (NewFD->isDefaulted())
9910     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9911            << DefaultedFuncs;
9912 
9913   if (!ConstexprSupported && NewFD->isConstexpr())
9914     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9915            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
9916 
9917   QualType NewQType = Context.getCanonicalType(NewFD->getType());
9918   const auto *NewType = cast<FunctionType>(NewQType);
9919   QualType NewReturnType = NewType->getReturnType();
9920 
9921   if (NewReturnType->isUndeducedType())
9922     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9923            << DeducedReturn;
9924 
9925   // Ensure the return type is identical.
9926   if (OldFD) {
9927     QualType OldQType = Context.getCanonicalType(OldFD->getType());
9928     const auto *OldType = cast<FunctionType>(OldQType);
9929     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
9930     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
9931 
9932     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
9933       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
9934 
9935     QualType OldReturnType = OldType->getReturnType();
9936 
9937     if (OldReturnType != NewReturnType)
9938       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
9939 
9940     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
9941       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
9942 
9943     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
9944       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
9945 
9946     if (OldFD->getStorageClass() != NewFD->getStorageClass())
9947       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass;
9948 
9949     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
9950       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
9951 
9952     if (CheckEquivalentExceptionSpec(
9953             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
9954             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
9955       return true;
9956   }
9957   return false;
9958 }
9959 
9960 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
9961                                              const FunctionDecl *NewFD,
9962                                              bool CausesMV,
9963                                              MultiVersionKind MVType) {
9964   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9965     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9966     if (OldFD)
9967       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9968     return true;
9969   }
9970 
9971   bool IsCPUSpecificCPUDispatchMVType =
9972       MVType == MultiVersionKind::CPUDispatch ||
9973       MVType == MultiVersionKind::CPUSpecific;
9974 
9975   // For now, disallow all other attributes.  These should be opt-in, but
9976   // an analysis of all of them is a future FIXME.
9977   if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) {
9978     S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
9979         << IsCPUSpecificCPUDispatchMVType;
9980     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9981     return true;
9982   }
9983 
9984   if (HasNonMultiVersionAttributes(NewFD, MVType))
9985     return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
9986            << IsCPUSpecificCPUDispatchMVType;
9987 
9988   // Only allow transition to MultiVersion if it hasn't been used.
9989   if (OldFD && CausesMV && OldFD->isUsed(false))
9990     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
9991 
9992   return S.areMultiversionVariantFunctionsCompatible(
9993       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
9994       PartialDiagnosticAt(NewFD->getLocation(),
9995                           S.PDiag(diag::note_multiversioning_caused_here)),
9996       PartialDiagnosticAt(NewFD->getLocation(),
9997                           S.PDiag(diag::err_multiversion_doesnt_support)
9998                               << IsCPUSpecificCPUDispatchMVType),
9999       PartialDiagnosticAt(NewFD->getLocation(),
10000                           S.PDiag(diag::err_multiversion_diff)),
10001       /*TemplatesSupported=*/false,
10002       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
10003       /*CLinkageMayDiffer=*/false);
10004 }
10005 
10006 /// Check the validity of a multiversion function declaration that is the
10007 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10008 ///
10009 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10010 ///
10011 /// Returns true if there was an error, false otherwise.
10012 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10013                                            MultiVersionKind MVType,
10014                                            const TargetAttr *TA) {
10015   assert(MVType != MultiVersionKind::None &&
10016          "Function lacks multiversion attribute");
10017 
10018   // Target only causes MV if it is default, otherwise this is a normal
10019   // function.
10020   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
10021     return false;
10022 
10023   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10024     FD->setInvalidDecl();
10025     return true;
10026   }
10027 
10028   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
10029     FD->setInvalidDecl();
10030     return true;
10031   }
10032 
10033   FD->setIsMultiVersion();
10034   return false;
10035 }
10036 
10037 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10038   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10039     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10040       return true;
10041   }
10042 
10043   return false;
10044 }
10045 
10046 static bool CheckTargetCausesMultiVersioning(
10047     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10048     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10049     LookupResult &Previous) {
10050   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10051   ParsedTargetAttr NewParsed = NewTA->parse();
10052   // Sort order doesn't matter, it just needs to be consistent.
10053   llvm::sort(NewParsed.Features);
10054 
10055   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10056   // to change, this is a simple redeclaration.
10057   if (!NewTA->isDefaultVersion() &&
10058       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10059     return false;
10060 
10061   // Otherwise, this decl causes MultiVersioning.
10062   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10063     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10064     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10065     NewFD->setInvalidDecl();
10066     return true;
10067   }
10068 
10069   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10070                                        MultiVersionKind::Target)) {
10071     NewFD->setInvalidDecl();
10072     return true;
10073   }
10074 
10075   if (CheckMultiVersionValue(S, NewFD)) {
10076     NewFD->setInvalidDecl();
10077     return true;
10078   }
10079 
10080   // If this is 'default', permit the forward declaration.
10081   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10082     Redeclaration = true;
10083     OldDecl = OldFD;
10084     OldFD->setIsMultiVersion();
10085     NewFD->setIsMultiVersion();
10086     return false;
10087   }
10088 
10089   if (CheckMultiVersionValue(S, OldFD)) {
10090     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10091     NewFD->setInvalidDecl();
10092     return true;
10093   }
10094 
10095   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10096 
10097   if (OldParsed == NewParsed) {
10098     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10099     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10100     NewFD->setInvalidDecl();
10101     return true;
10102   }
10103 
10104   for (const auto *FD : OldFD->redecls()) {
10105     const auto *CurTA = FD->getAttr<TargetAttr>();
10106     // We allow forward declarations before ANY multiversioning attributes, but
10107     // nothing after the fact.
10108     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10109         (!CurTA || CurTA->isInherited())) {
10110       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10111           << 0;
10112       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10113       NewFD->setInvalidDecl();
10114       return true;
10115     }
10116   }
10117 
10118   OldFD->setIsMultiVersion();
10119   NewFD->setIsMultiVersion();
10120   Redeclaration = false;
10121   MergeTypeWithPrevious = false;
10122   OldDecl = nullptr;
10123   Previous.clear();
10124   return false;
10125 }
10126 
10127 /// Check the validity of a new function declaration being added to an existing
10128 /// multiversioned declaration collection.
10129 static bool CheckMultiVersionAdditionalDecl(
10130     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10131     MultiVersionKind NewMVType, const TargetAttr *NewTA,
10132     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10133     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10134     LookupResult &Previous) {
10135 
10136   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10137   // Disallow mixing of multiversioning types.
10138   if ((OldMVType == MultiVersionKind::Target &&
10139        NewMVType != MultiVersionKind::Target) ||
10140       (NewMVType == MultiVersionKind::Target &&
10141        OldMVType != MultiVersionKind::Target)) {
10142     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10143     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10144     NewFD->setInvalidDecl();
10145     return true;
10146   }
10147 
10148   ParsedTargetAttr NewParsed;
10149   if (NewTA) {
10150     NewParsed = NewTA->parse();
10151     llvm::sort(NewParsed.Features);
10152   }
10153 
10154   bool UseMemberUsingDeclRules =
10155       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10156 
10157   // Next, check ALL non-overloads to see if this is a redeclaration of a
10158   // previous member of the MultiVersion set.
10159   for (NamedDecl *ND : Previous) {
10160     FunctionDecl *CurFD = ND->getAsFunction();
10161     if (!CurFD)
10162       continue;
10163     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10164       continue;
10165 
10166     if (NewMVType == MultiVersionKind::Target) {
10167       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10168       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10169         NewFD->setIsMultiVersion();
10170         Redeclaration = true;
10171         OldDecl = ND;
10172         return false;
10173       }
10174 
10175       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10176       if (CurParsed == NewParsed) {
10177         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10178         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10179         NewFD->setInvalidDecl();
10180         return true;
10181       }
10182     } else {
10183       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10184       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10185       // Handle CPUDispatch/CPUSpecific versions.
10186       // Only 1 CPUDispatch function is allowed, this will make it go through
10187       // the redeclaration errors.
10188       if (NewMVType == MultiVersionKind::CPUDispatch &&
10189           CurFD->hasAttr<CPUDispatchAttr>()) {
10190         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10191             std::equal(
10192                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10193                 NewCPUDisp->cpus_begin(),
10194                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10195                   return Cur->getName() == New->getName();
10196                 })) {
10197           NewFD->setIsMultiVersion();
10198           Redeclaration = true;
10199           OldDecl = ND;
10200           return false;
10201         }
10202 
10203         // If the declarations don't match, this is an error condition.
10204         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10205         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10206         NewFD->setInvalidDecl();
10207         return true;
10208       }
10209       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10210 
10211         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10212             std::equal(
10213                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10214                 NewCPUSpec->cpus_begin(),
10215                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10216                   return Cur->getName() == New->getName();
10217                 })) {
10218           NewFD->setIsMultiVersion();
10219           Redeclaration = true;
10220           OldDecl = ND;
10221           return false;
10222         }
10223 
10224         // Only 1 version of CPUSpecific is allowed for each CPU.
10225         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10226           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10227             if (CurII == NewII) {
10228               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10229                   << NewII;
10230               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10231               NewFD->setInvalidDecl();
10232               return true;
10233             }
10234           }
10235         }
10236       }
10237       // If the two decls aren't the same MVType, there is no possible error
10238       // condition.
10239     }
10240   }
10241 
10242   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10243   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10244   // handled in the attribute adding step.
10245   if (NewMVType == MultiVersionKind::Target &&
10246       CheckMultiVersionValue(S, NewFD)) {
10247     NewFD->setInvalidDecl();
10248     return true;
10249   }
10250 
10251   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10252                                        !OldFD->isMultiVersion(), NewMVType)) {
10253     NewFD->setInvalidDecl();
10254     return true;
10255   }
10256 
10257   // Permit forward declarations in the case where these two are compatible.
10258   if (!OldFD->isMultiVersion()) {
10259     OldFD->setIsMultiVersion();
10260     NewFD->setIsMultiVersion();
10261     Redeclaration = true;
10262     OldDecl = OldFD;
10263     return false;
10264   }
10265 
10266   NewFD->setIsMultiVersion();
10267   Redeclaration = false;
10268   MergeTypeWithPrevious = false;
10269   OldDecl = nullptr;
10270   Previous.clear();
10271   return false;
10272 }
10273 
10274 
10275 /// Check the validity of a mulitversion function declaration.
10276 /// Also sets the multiversion'ness' of the function itself.
10277 ///
10278 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10279 ///
10280 /// Returns true if there was an error, false otherwise.
10281 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10282                                       bool &Redeclaration, NamedDecl *&OldDecl,
10283                                       bool &MergeTypeWithPrevious,
10284                                       LookupResult &Previous) {
10285   const auto *NewTA = NewFD->getAttr<TargetAttr>();
10286   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10287   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10288 
10289   // Mixing Multiversioning types is prohibited.
10290   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
10291       (NewCPUDisp && NewCPUSpec)) {
10292     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10293     NewFD->setInvalidDecl();
10294     return true;
10295   }
10296 
10297   MultiVersionKind  MVType = NewFD->getMultiVersionKind();
10298 
10299   // Main isn't allowed to become a multiversion function, however it IS
10300   // permitted to have 'main' be marked with the 'target' optimization hint.
10301   if (NewFD->isMain()) {
10302     if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10303         MVType == MultiVersionKind::CPUDispatch ||
10304         MVType == MultiVersionKind::CPUSpecific) {
10305       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10306       NewFD->setInvalidDecl();
10307       return true;
10308     }
10309     return false;
10310   }
10311 
10312   if (!OldDecl || !OldDecl->getAsFunction() ||
10313       OldDecl->getDeclContext()->getRedeclContext() !=
10314           NewFD->getDeclContext()->getRedeclContext()) {
10315     // If there's no previous declaration, AND this isn't attempting to cause
10316     // multiversioning, this isn't an error condition.
10317     if (MVType == MultiVersionKind::None)
10318       return false;
10319     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10320   }
10321 
10322   FunctionDecl *OldFD = OldDecl->getAsFunction();
10323 
10324   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10325     return false;
10326 
10327   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10328     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10329         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10330     NewFD->setInvalidDecl();
10331     return true;
10332   }
10333 
10334   // Handle the target potentially causes multiversioning case.
10335   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10336     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10337                                             Redeclaration, OldDecl,
10338                                             MergeTypeWithPrevious, Previous);
10339 
10340   // At this point, we have a multiversion function decl (in OldFD) AND an
10341   // appropriate attribute in the current function decl.  Resolve that these are
10342   // still compatible with previous declarations.
10343   return CheckMultiVersionAdditionalDecl(
10344       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10345       OldDecl, MergeTypeWithPrevious, Previous);
10346 }
10347 
10348 /// Perform semantic checking of a new function declaration.
10349 ///
10350 /// Performs semantic analysis of the new function declaration
10351 /// NewFD. This routine performs all semantic checking that does not
10352 /// require the actual declarator involved in the declaration, and is
10353 /// used both for the declaration of functions as they are parsed
10354 /// (called via ActOnDeclarator) and for the declaration of functions
10355 /// that have been instantiated via C++ template instantiation (called
10356 /// via InstantiateDecl).
10357 ///
10358 /// \param IsMemberSpecialization whether this new function declaration is
10359 /// a member specialization (that replaces any definition provided by the
10360 /// previous declaration).
10361 ///
10362 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10363 ///
10364 /// \returns true if the function declaration is a redeclaration.
10365 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10366                                     LookupResult &Previous,
10367                                     bool IsMemberSpecialization) {
10368   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10369          "Variably modified return types are not handled here");
10370 
10371   // Determine whether the type of this function should be merged with
10372   // a previous visible declaration. This never happens for functions in C++,
10373   // and always happens in C if the previous declaration was visible.
10374   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10375                                !Previous.isShadowed();
10376 
10377   bool Redeclaration = false;
10378   NamedDecl *OldDecl = nullptr;
10379   bool MayNeedOverloadableChecks = false;
10380 
10381   // Merge or overload the declaration with an existing declaration of
10382   // the same name, if appropriate.
10383   if (!Previous.empty()) {
10384     // Determine whether NewFD is an overload of PrevDecl or
10385     // a declaration that requires merging. If it's an overload,
10386     // there's no more work to do here; we'll just add the new
10387     // function to the scope.
10388     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10389       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10390       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10391         Redeclaration = true;
10392         OldDecl = Candidate;
10393       }
10394     } else {
10395       MayNeedOverloadableChecks = true;
10396       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10397                             /*NewIsUsingDecl*/ false)) {
10398       case Ovl_Match:
10399         Redeclaration = true;
10400         break;
10401 
10402       case Ovl_NonFunction:
10403         Redeclaration = true;
10404         break;
10405 
10406       case Ovl_Overload:
10407         Redeclaration = false;
10408         break;
10409       }
10410     }
10411   }
10412 
10413   // Check for a previous extern "C" declaration with this name.
10414   if (!Redeclaration &&
10415       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10416     if (!Previous.empty()) {
10417       // This is an extern "C" declaration with the same name as a previous
10418       // declaration, and thus redeclares that entity...
10419       Redeclaration = true;
10420       OldDecl = Previous.getFoundDecl();
10421       MergeTypeWithPrevious = false;
10422 
10423       // ... except in the presence of __attribute__((overloadable)).
10424       if (OldDecl->hasAttr<OverloadableAttr>() ||
10425           NewFD->hasAttr<OverloadableAttr>()) {
10426         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10427           MayNeedOverloadableChecks = true;
10428           Redeclaration = false;
10429           OldDecl = nullptr;
10430         }
10431       }
10432     }
10433   }
10434 
10435   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10436                                 MergeTypeWithPrevious, Previous))
10437     return Redeclaration;
10438 
10439   // C++11 [dcl.constexpr]p8:
10440   //   A constexpr specifier for a non-static member function that is not
10441   //   a constructor declares that member function to be const.
10442   //
10443   // This needs to be delayed until we know whether this is an out-of-line
10444   // definition of a static member function.
10445   //
10446   // This rule is not present in C++1y, so we produce a backwards
10447   // compatibility warning whenever it happens in C++11.
10448   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10449   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10450       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10451       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10452     CXXMethodDecl *OldMD = nullptr;
10453     if (OldDecl)
10454       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10455     if (!OldMD || !OldMD->isStatic()) {
10456       const FunctionProtoType *FPT =
10457         MD->getType()->castAs<FunctionProtoType>();
10458       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10459       EPI.TypeQuals.addConst();
10460       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10461                                           FPT->getParamTypes(), EPI));
10462 
10463       // Warn that we did this, if we're not performing template instantiation.
10464       // In that case, we'll have warned already when the template was defined.
10465       if (!inTemplateInstantiation()) {
10466         SourceLocation AddConstLoc;
10467         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10468                 .IgnoreParens().getAs<FunctionTypeLoc>())
10469           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10470 
10471         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10472           << FixItHint::CreateInsertion(AddConstLoc, " const");
10473       }
10474     }
10475   }
10476 
10477   if (Redeclaration) {
10478     // NewFD and OldDecl represent declarations that need to be
10479     // merged.
10480     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10481       NewFD->setInvalidDecl();
10482       return Redeclaration;
10483     }
10484 
10485     Previous.clear();
10486     Previous.addDecl(OldDecl);
10487 
10488     if (FunctionTemplateDecl *OldTemplateDecl =
10489             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10490       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10491       FunctionTemplateDecl *NewTemplateDecl
10492         = NewFD->getDescribedFunctionTemplate();
10493       assert(NewTemplateDecl && "Template/non-template mismatch");
10494 
10495       // The call to MergeFunctionDecl above may have created some state in
10496       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10497       // can add it as a redeclaration.
10498       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10499 
10500       NewFD->setPreviousDeclaration(OldFD);
10501       adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10502       if (NewFD->isCXXClassMember()) {
10503         NewFD->setAccess(OldTemplateDecl->getAccess());
10504         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10505       }
10506 
10507       // If this is an explicit specialization of a member that is a function
10508       // template, mark it as a member specialization.
10509       if (IsMemberSpecialization &&
10510           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10511         NewTemplateDecl->setMemberSpecialization();
10512         assert(OldTemplateDecl->isMemberSpecialization());
10513         // Explicit specializations of a member template do not inherit deleted
10514         // status from the parent member template that they are specializing.
10515         if (OldFD->isDeleted()) {
10516           // FIXME: This assert will not hold in the presence of modules.
10517           assert(OldFD->getCanonicalDecl() == OldFD);
10518           // FIXME: We need an update record for this AST mutation.
10519           OldFD->setDeletedAsWritten(false);
10520         }
10521       }
10522 
10523     } else {
10524       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10525         auto *OldFD = cast<FunctionDecl>(OldDecl);
10526         // This needs to happen first so that 'inline' propagates.
10527         NewFD->setPreviousDeclaration(OldFD);
10528         adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10529         if (NewFD->isCXXClassMember())
10530           NewFD->setAccess(OldFD->getAccess());
10531       }
10532     }
10533   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10534              !NewFD->getAttr<OverloadableAttr>()) {
10535     assert((Previous.empty() ||
10536             llvm::any_of(Previous,
10537                          [](const NamedDecl *ND) {
10538                            return ND->hasAttr<OverloadableAttr>();
10539                          })) &&
10540            "Non-redecls shouldn't happen without overloadable present");
10541 
10542     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10543       const auto *FD = dyn_cast<FunctionDecl>(ND);
10544       return FD && !FD->hasAttr<OverloadableAttr>();
10545     });
10546 
10547     if (OtherUnmarkedIter != Previous.end()) {
10548       Diag(NewFD->getLocation(),
10549            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10550       Diag((*OtherUnmarkedIter)->getLocation(),
10551            diag::note_attribute_overloadable_prev_overload)
10552           << false;
10553 
10554       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10555     }
10556   }
10557 
10558   // Semantic checking for this function declaration (in isolation).
10559 
10560   if (getLangOpts().CPlusPlus) {
10561     // C++-specific checks.
10562     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10563       CheckConstructor(Constructor);
10564     } else if (CXXDestructorDecl *Destructor =
10565                 dyn_cast<CXXDestructorDecl>(NewFD)) {
10566       CXXRecordDecl *Record = Destructor->getParent();
10567       QualType ClassType = Context.getTypeDeclType(Record);
10568 
10569       // FIXME: Shouldn't we be able to perform this check even when the class
10570       // type is dependent? Both gcc and edg can handle that.
10571       if (!ClassType->isDependentType()) {
10572         DeclarationName Name
10573           = Context.DeclarationNames.getCXXDestructorName(
10574                                         Context.getCanonicalType(ClassType));
10575         if (NewFD->getDeclName() != Name) {
10576           Diag(NewFD->getLocation(), diag::err_destructor_name);
10577           NewFD->setInvalidDecl();
10578           return Redeclaration;
10579         }
10580       }
10581     } else if (CXXConversionDecl *Conversion
10582                = dyn_cast<CXXConversionDecl>(NewFD)) {
10583       ActOnConversionDeclarator(Conversion);
10584     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10585       if (auto *TD = Guide->getDescribedFunctionTemplate())
10586         CheckDeductionGuideTemplate(TD);
10587 
10588       // A deduction guide is not on the list of entities that can be
10589       // explicitly specialized.
10590       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10591         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10592             << /*explicit specialization*/ 1;
10593     }
10594 
10595     // Find any virtual functions that this function overrides.
10596     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10597       if (!Method->isFunctionTemplateSpecialization() &&
10598           !Method->getDescribedFunctionTemplate() &&
10599           Method->isCanonicalDecl()) {
10600         if (AddOverriddenMethods(Method->getParent(), Method)) {
10601           // If the function was marked as "static", we have a problem.
10602           if (NewFD->getStorageClass() == SC_Static) {
10603             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
10604           }
10605         }
10606       }
10607       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
10608         // C++2a [class.virtual]p6
10609         // A virtual method shall not have a requires-clause.
10610         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
10611              diag::err_constrained_virtual_method);
10612 
10613       if (Method->isStatic())
10614         checkThisInStaticMemberFunctionType(Method);
10615     }
10616 
10617     // Extra checking for C++ overloaded operators (C++ [over.oper]).
10618     if (NewFD->isOverloadedOperator() &&
10619         CheckOverloadedOperatorDeclaration(NewFD)) {
10620       NewFD->setInvalidDecl();
10621       return Redeclaration;
10622     }
10623 
10624     // Extra checking for C++0x literal operators (C++0x [over.literal]).
10625     if (NewFD->getLiteralIdentifier() &&
10626         CheckLiteralOperatorDeclaration(NewFD)) {
10627       NewFD->setInvalidDecl();
10628       return Redeclaration;
10629     }
10630 
10631     // In C++, check default arguments now that we have merged decls. Unless
10632     // the lexical context is the class, because in this case this is done
10633     // during delayed parsing anyway.
10634     if (!CurContext->isRecord())
10635       CheckCXXDefaultArguments(NewFD);
10636 
10637     // If this function declares a builtin function, check the type of this
10638     // declaration against the expected type for the builtin.
10639     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10640       ASTContext::GetBuiltinTypeError Error;
10641       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
10642       QualType T = Context.GetBuiltinType(BuiltinID, Error);
10643       // If the type of the builtin differs only in its exception
10644       // specification, that's OK.
10645       // FIXME: If the types do differ in this way, it would be better to
10646       // retain the 'noexcept' form of the type.
10647       if (!T.isNull() &&
10648           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10649                                                             NewFD->getType()))
10650         // The type of this function differs from the type of the builtin,
10651         // so forget about the builtin entirely.
10652         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10653     }
10654 
10655     // If this function is declared as being extern "C", then check to see if
10656     // the function returns a UDT (class, struct, or union type) that is not C
10657     // compatible, and if it does, warn the user.
10658     // But, issue any diagnostic on the first declaration only.
10659     if (Previous.empty() && NewFD->isExternC()) {
10660       QualType R = NewFD->getReturnType();
10661       if (R->isIncompleteType() && !R->isVoidType())
10662         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10663             << NewFD << R;
10664       else if (!R.isPODType(Context) && !R->isVoidType() &&
10665                !R->isObjCObjectPointerType())
10666         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10667     }
10668 
10669     // C++1z [dcl.fct]p6:
10670     //   [...] whether the function has a non-throwing exception-specification
10671     //   [is] part of the function type
10672     //
10673     // This results in an ABI break between C++14 and C++17 for functions whose
10674     // declared type includes an exception-specification in a parameter or
10675     // return type. (Exception specifications on the function itself are OK in
10676     // most cases, and exception specifications are not permitted in most other
10677     // contexts where they could make it into a mangling.)
10678     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10679       auto HasNoexcept = [&](QualType T) -> bool {
10680         // Strip off declarator chunks that could be between us and a function
10681         // type. We don't need to look far, exception specifications are very
10682         // restricted prior to C++17.
10683         if (auto *RT = T->getAs<ReferenceType>())
10684           T = RT->getPointeeType();
10685         else if (T->isAnyPointerType())
10686           T = T->getPointeeType();
10687         else if (auto *MPT = T->getAs<MemberPointerType>())
10688           T = MPT->getPointeeType();
10689         if (auto *FPT = T->getAs<FunctionProtoType>())
10690           if (FPT->isNothrow())
10691             return true;
10692         return false;
10693       };
10694 
10695       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10696       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10697       for (QualType T : FPT->param_types())
10698         AnyNoexcept |= HasNoexcept(T);
10699       if (AnyNoexcept)
10700         Diag(NewFD->getLocation(),
10701              diag::warn_cxx17_compat_exception_spec_in_signature)
10702             << NewFD;
10703     }
10704 
10705     if (!Redeclaration && LangOpts.CUDA)
10706       checkCUDATargetOverload(NewFD, Previous);
10707   }
10708   return Redeclaration;
10709 }
10710 
10711 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10712   // C++11 [basic.start.main]p3:
10713   //   A program that [...] declares main to be inline, static or
10714   //   constexpr is ill-formed.
10715   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
10716   //   appear in a declaration of main.
10717   // static main is not an error under C99, but we should warn about it.
10718   // We accept _Noreturn main as an extension.
10719   if (FD->getStorageClass() == SC_Static)
10720     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10721          ? diag::err_static_main : diag::warn_static_main)
10722       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10723   if (FD->isInlineSpecified())
10724     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10725       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10726   if (DS.isNoreturnSpecified()) {
10727     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10728     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10729     Diag(NoreturnLoc, diag::ext_noreturn_main);
10730     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10731       << FixItHint::CreateRemoval(NoreturnRange);
10732   }
10733   if (FD->isConstexpr()) {
10734     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10735         << FD->isConsteval()
10736         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10737     FD->setConstexprKind(CSK_unspecified);
10738   }
10739 
10740   if (getLangOpts().OpenCL) {
10741     Diag(FD->getLocation(), diag::err_opencl_no_main)
10742         << FD->hasAttr<OpenCLKernelAttr>();
10743     FD->setInvalidDecl();
10744     return;
10745   }
10746 
10747   QualType T = FD->getType();
10748   assert(T->isFunctionType() && "function decl is not of function type");
10749   const FunctionType* FT = T->castAs<FunctionType>();
10750 
10751   // Set default calling convention for main()
10752   if (FT->getCallConv() != CC_C) {
10753     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10754     FD->setType(QualType(FT, 0));
10755     T = Context.getCanonicalType(FD->getType());
10756   }
10757 
10758   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10759     // In C with GNU extensions we allow main() to have non-integer return
10760     // type, but we should warn about the extension, and we disable the
10761     // implicit-return-zero rule.
10762 
10763     // GCC in C mode accepts qualified 'int'.
10764     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
10765       FD->setHasImplicitReturnZero(true);
10766     else {
10767       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
10768       SourceRange RTRange = FD->getReturnTypeSourceRange();
10769       if (RTRange.isValid())
10770         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
10771             << FixItHint::CreateReplacement(RTRange, "int");
10772     }
10773   } else {
10774     // In C and C++, main magically returns 0 if you fall off the end;
10775     // set the flag which tells us that.
10776     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
10777 
10778     // All the standards say that main() should return 'int'.
10779     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
10780       FD->setHasImplicitReturnZero(true);
10781     else {
10782       // Otherwise, this is just a flat-out error.
10783       SourceRange RTRange = FD->getReturnTypeSourceRange();
10784       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
10785           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
10786                                 : FixItHint());
10787       FD->setInvalidDecl(true);
10788     }
10789   }
10790 
10791   // Treat protoless main() as nullary.
10792   if (isa<FunctionNoProtoType>(FT)) return;
10793 
10794   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
10795   unsigned nparams = FTP->getNumParams();
10796   assert(FD->getNumParams() == nparams);
10797 
10798   bool HasExtraParameters = (nparams > 3);
10799 
10800   if (FTP->isVariadic()) {
10801     Diag(FD->getLocation(), diag::ext_variadic_main);
10802     // FIXME: if we had information about the location of the ellipsis, we
10803     // could add a FixIt hint to remove it as a parameter.
10804   }
10805 
10806   // Darwin passes an undocumented fourth argument of type char**.  If
10807   // other platforms start sprouting these, the logic below will start
10808   // getting shifty.
10809   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
10810     HasExtraParameters = false;
10811 
10812   if (HasExtraParameters) {
10813     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
10814     FD->setInvalidDecl(true);
10815     nparams = 3;
10816   }
10817 
10818   // FIXME: a lot of the following diagnostics would be improved
10819   // if we had some location information about types.
10820 
10821   QualType CharPP =
10822     Context.getPointerType(Context.getPointerType(Context.CharTy));
10823   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
10824 
10825   for (unsigned i = 0; i < nparams; ++i) {
10826     QualType AT = FTP->getParamType(i);
10827 
10828     bool mismatch = true;
10829 
10830     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
10831       mismatch = false;
10832     else if (Expected[i] == CharPP) {
10833       // As an extension, the following forms are okay:
10834       //   char const **
10835       //   char const * const *
10836       //   char * const *
10837 
10838       QualifierCollector qs;
10839       const PointerType* PT;
10840       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
10841           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
10842           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
10843                               Context.CharTy)) {
10844         qs.removeConst();
10845         mismatch = !qs.empty();
10846       }
10847     }
10848 
10849     if (mismatch) {
10850       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
10851       // TODO: suggest replacing given type with expected type
10852       FD->setInvalidDecl(true);
10853     }
10854   }
10855 
10856   if (nparams == 1 && !FD->isInvalidDecl()) {
10857     Diag(FD->getLocation(), diag::warn_main_one_arg);
10858   }
10859 
10860   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10861     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10862     FD->setInvalidDecl();
10863   }
10864 }
10865 
10866 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
10867   QualType T = FD->getType();
10868   assert(T->isFunctionType() && "function decl is not of function type");
10869   const FunctionType *FT = T->castAs<FunctionType>();
10870 
10871   // Set an implicit return of 'zero' if the function can return some integral,
10872   // enumeration, pointer or nullptr type.
10873   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
10874       FT->getReturnType()->isAnyPointerType() ||
10875       FT->getReturnType()->isNullPtrType())
10876     // DllMain is exempt because a return value of zero means it failed.
10877     if (FD->getName() != "DllMain")
10878       FD->setHasImplicitReturnZero(true);
10879 
10880   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10881     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10882     FD->setInvalidDecl();
10883   }
10884 }
10885 
10886 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
10887   // FIXME: Need strict checking.  In C89, we need to check for
10888   // any assignment, increment, decrement, function-calls, or
10889   // commas outside of a sizeof.  In C99, it's the same list,
10890   // except that the aforementioned are allowed in unevaluated
10891   // expressions.  Everything else falls under the
10892   // "may accept other forms of constant expressions" exception.
10893   // (We never end up here for C++, so the constant expression
10894   // rules there don't matter.)
10895   const Expr *Culprit;
10896   if (Init->isConstantInitializer(Context, false, &Culprit))
10897     return false;
10898   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
10899     << Culprit->getSourceRange();
10900   return true;
10901 }
10902 
10903 namespace {
10904   // Visits an initialization expression to see if OrigDecl is evaluated in
10905   // its own initialization and throws a warning if it does.
10906   class SelfReferenceChecker
10907       : public EvaluatedExprVisitor<SelfReferenceChecker> {
10908     Sema &S;
10909     Decl *OrigDecl;
10910     bool isRecordType;
10911     bool isPODType;
10912     bool isReferenceType;
10913 
10914     bool isInitList;
10915     llvm::SmallVector<unsigned, 4> InitFieldIndex;
10916 
10917   public:
10918     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
10919 
10920     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
10921                                                     S(S), OrigDecl(OrigDecl) {
10922       isPODType = false;
10923       isRecordType = false;
10924       isReferenceType = false;
10925       isInitList = false;
10926       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
10927         isPODType = VD->getType().isPODType(S.Context);
10928         isRecordType = VD->getType()->isRecordType();
10929         isReferenceType = VD->getType()->isReferenceType();
10930       }
10931     }
10932 
10933     // For most expressions, just call the visitor.  For initializer lists,
10934     // track the index of the field being initialized since fields are
10935     // initialized in order allowing use of previously initialized fields.
10936     void CheckExpr(Expr *E) {
10937       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
10938       if (!InitList) {
10939         Visit(E);
10940         return;
10941       }
10942 
10943       // Track and increment the index here.
10944       isInitList = true;
10945       InitFieldIndex.push_back(0);
10946       for (auto Child : InitList->children()) {
10947         CheckExpr(cast<Expr>(Child));
10948         ++InitFieldIndex.back();
10949       }
10950       InitFieldIndex.pop_back();
10951     }
10952 
10953     // Returns true if MemberExpr is checked and no further checking is needed.
10954     // Returns false if additional checking is required.
10955     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
10956       llvm::SmallVector<FieldDecl*, 4> Fields;
10957       Expr *Base = E;
10958       bool ReferenceField = false;
10959 
10960       // Get the field members used.
10961       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10962         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
10963         if (!FD)
10964           return false;
10965         Fields.push_back(FD);
10966         if (FD->getType()->isReferenceType())
10967           ReferenceField = true;
10968         Base = ME->getBase()->IgnoreParenImpCasts();
10969       }
10970 
10971       // Keep checking only if the base Decl is the same.
10972       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
10973       if (!DRE || DRE->getDecl() != OrigDecl)
10974         return false;
10975 
10976       // A reference field can be bound to an unininitialized field.
10977       if (CheckReference && !ReferenceField)
10978         return true;
10979 
10980       // Convert FieldDecls to their index number.
10981       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
10982       for (const FieldDecl *I : llvm::reverse(Fields))
10983         UsedFieldIndex.push_back(I->getFieldIndex());
10984 
10985       // See if a warning is needed by checking the first difference in index
10986       // numbers.  If field being used has index less than the field being
10987       // initialized, then the use is safe.
10988       for (auto UsedIter = UsedFieldIndex.begin(),
10989                 UsedEnd = UsedFieldIndex.end(),
10990                 OrigIter = InitFieldIndex.begin(),
10991                 OrigEnd = InitFieldIndex.end();
10992            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
10993         if (*UsedIter < *OrigIter)
10994           return true;
10995         if (*UsedIter > *OrigIter)
10996           break;
10997       }
10998 
10999       // TODO: Add a different warning which will print the field names.
11000       HandleDeclRefExpr(DRE);
11001       return true;
11002     }
11003 
11004     // For most expressions, the cast is directly above the DeclRefExpr.
11005     // For conditional operators, the cast can be outside the conditional
11006     // operator if both expressions are DeclRefExpr's.
11007     void HandleValue(Expr *E) {
11008       E = E->IgnoreParens();
11009       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11010         HandleDeclRefExpr(DRE);
11011         return;
11012       }
11013 
11014       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11015         Visit(CO->getCond());
11016         HandleValue(CO->getTrueExpr());
11017         HandleValue(CO->getFalseExpr());
11018         return;
11019       }
11020 
11021       if (BinaryConditionalOperator *BCO =
11022               dyn_cast<BinaryConditionalOperator>(E)) {
11023         Visit(BCO->getCond());
11024         HandleValue(BCO->getFalseExpr());
11025         return;
11026       }
11027 
11028       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11029         HandleValue(OVE->getSourceExpr());
11030         return;
11031       }
11032 
11033       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11034         if (BO->getOpcode() == BO_Comma) {
11035           Visit(BO->getLHS());
11036           HandleValue(BO->getRHS());
11037           return;
11038         }
11039       }
11040 
11041       if (isa<MemberExpr>(E)) {
11042         if (isInitList) {
11043           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11044                                       false /*CheckReference*/))
11045             return;
11046         }
11047 
11048         Expr *Base = E->IgnoreParenImpCasts();
11049         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11050           // Check for static member variables and don't warn on them.
11051           if (!isa<FieldDecl>(ME->getMemberDecl()))
11052             return;
11053           Base = ME->getBase()->IgnoreParenImpCasts();
11054         }
11055         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11056           HandleDeclRefExpr(DRE);
11057         return;
11058       }
11059 
11060       Visit(E);
11061     }
11062 
11063     // Reference types not handled in HandleValue are handled here since all
11064     // uses of references are bad, not just r-value uses.
11065     void VisitDeclRefExpr(DeclRefExpr *E) {
11066       if (isReferenceType)
11067         HandleDeclRefExpr(E);
11068     }
11069 
11070     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11071       if (E->getCastKind() == CK_LValueToRValue) {
11072         HandleValue(E->getSubExpr());
11073         return;
11074       }
11075 
11076       Inherited::VisitImplicitCastExpr(E);
11077     }
11078 
11079     void VisitMemberExpr(MemberExpr *E) {
11080       if (isInitList) {
11081         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11082           return;
11083       }
11084 
11085       // Don't warn on arrays since they can be treated as pointers.
11086       if (E->getType()->canDecayToPointerType()) return;
11087 
11088       // Warn when a non-static method call is followed by non-static member
11089       // field accesses, which is followed by a DeclRefExpr.
11090       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11091       bool Warn = (MD && !MD->isStatic());
11092       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11093       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11094         if (!isa<FieldDecl>(ME->getMemberDecl()))
11095           Warn = false;
11096         Base = ME->getBase()->IgnoreParenImpCasts();
11097       }
11098 
11099       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11100         if (Warn)
11101           HandleDeclRefExpr(DRE);
11102         return;
11103       }
11104 
11105       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11106       // Visit that expression.
11107       Visit(Base);
11108     }
11109 
11110     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11111       Expr *Callee = E->getCallee();
11112 
11113       if (isa<UnresolvedLookupExpr>(Callee))
11114         return Inherited::VisitCXXOperatorCallExpr(E);
11115 
11116       Visit(Callee);
11117       for (auto Arg: E->arguments())
11118         HandleValue(Arg->IgnoreParenImpCasts());
11119     }
11120 
11121     void VisitUnaryOperator(UnaryOperator *E) {
11122       // For POD record types, addresses of its own members are well-defined.
11123       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11124           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11125         if (!isPODType)
11126           HandleValue(E->getSubExpr());
11127         return;
11128       }
11129 
11130       if (E->isIncrementDecrementOp()) {
11131         HandleValue(E->getSubExpr());
11132         return;
11133       }
11134 
11135       Inherited::VisitUnaryOperator(E);
11136     }
11137 
11138     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11139 
11140     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11141       if (E->getConstructor()->isCopyConstructor()) {
11142         Expr *ArgExpr = E->getArg(0);
11143         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11144           if (ILE->getNumInits() == 1)
11145             ArgExpr = ILE->getInit(0);
11146         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11147           if (ICE->getCastKind() == CK_NoOp)
11148             ArgExpr = ICE->getSubExpr();
11149         HandleValue(ArgExpr);
11150         return;
11151       }
11152       Inherited::VisitCXXConstructExpr(E);
11153     }
11154 
11155     void VisitCallExpr(CallExpr *E) {
11156       // Treat std::move as a use.
11157       if (E->isCallToStdMove()) {
11158         HandleValue(E->getArg(0));
11159         return;
11160       }
11161 
11162       Inherited::VisitCallExpr(E);
11163     }
11164 
11165     void VisitBinaryOperator(BinaryOperator *E) {
11166       if (E->isCompoundAssignmentOp()) {
11167         HandleValue(E->getLHS());
11168         Visit(E->getRHS());
11169         return;
11170       }
11171 
11172       Inherited::VisitBinaryOperator(E);
11173     }
11174 
11175     // A custom visitor for BinaryConditionalOperator is needed because the
11176     // regular visitor would check the condition and true expression separately
11177     // but both point to the same place giving duplicate diagnostics.
11178     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11179       Visit(E->getCond());
11180       Visit(E->getFalseExpr());
11181     }
11182 
11183     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11184       Decl* ReferenceDecl = DRE->getDecl();
11185       if (OrigDecl != ReferenceDecl) return;
11186       unsigned diag;
11187       if (isReferenceType) {
11188         diag = diag::warn_uninit_self_reference_in_reference_init;
11189       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11190         diag = diag::warn_static_self_reference_in_init;
11191       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11192                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11193                  DRE->getDecl()->getType()->isRecordType()) {
11194         diag = diag::warn_uninit_self_reference_in_init;
11195       } else {
11196         // Local variables will be handled by the CFG analysis.
11197         return;
11198       }
11199 
11200       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11201                             S.PDiag(diag)
11202                                 << DRE->getDecl() << OrigDecl->getLocation()
11203                                 << DRE->getSourceRange());
11204     }
11205   };
11206 
11207   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11208   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11209                                  bool DirectInit) {
11210     // Parameters arguments are occassionially constructed with itself,
11211     // for instance, in recursive functions.  Skip them.
11212     if (isa<ParmVarDecl>(OrigDecl))
11213       return;
11214 
11215     E = E->IgnoreParens();
11216 
11217     // Skip checking T a = a where T is not a record or reference type.
11218     // Doing so is a way to silence uninitialized warnings.
11219     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11220       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11221         if (ICE->getCastKind() == CK_LValueToRValue)
11222           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11223             if (DRE->getDecl() == OrigDecl)
11224               return;
11225 
11226     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11227   }
11228 } // end anonymous namespace
11229 
11230 namespace {
11231   // Simple wrapper to add the name of a variable or (if no variable is
11232   // available) a DeclarationName into a diagnostic.
11233   struct VarDeclOrName {
11234     VarDecl *VDecl;
11235     DeclarationName Name;
11236 
11237     friend const Sema::SemaDiagnosticBuilder &
11238     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11239       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11240     }
11241   };
11242 } // end anonymous namespace
11243 
11244 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11245                                             DeclarationName Name, QualType Type,
11246                                             TypeSourceInfo *TSI,
11247                                             SourceRange Range, bool DirectInit,
11248                                             Expr *Init) {
11249   bool IsInitCapture = !VDecl;
11250   assert((!VDecl || !VDecl->isInitCapture()) &&
11251          "init captures are expected to be deduced prior to initialization");
11252 
11253   VarDeclOrName VN{VDecl, Name};
11254 
11255   DeducedType *Deduced = Type->getContainedDeducedType();
11256   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11257 
11258   // C++11 [dcl.spec.auto]p3
11259   if (!Init) {
11260     assert(VDecl && "no init for init capture deduction?");
11261 
11262     // Except for class argument deduction, and then for an initializing
11263     // declaration only, i.e. no static at class scope or extern.
11264     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11265         VDecl->hasExternalStorage() ||
11266         VDecl->isStaticDataMember()) {
11267       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11268         << VDecl->getDeclName() << Type;
11269       return QualType();
11270     }
11271   }
11272 
11273   ArrayRef<Expr*> DeduceInits;
11274   if (Init)
11275     DeduceInits = Init;
11276 
11277   if (DirectInit) {
11278     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11279       DeduceInits = PL->exprs();
11280   }
11281 
11282   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11283     assert(VDecl && "non-auto type for init capture deduction?");
11284     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11285     InitializationKind Kind = InitializationKind::CreateForInit(
11286         VDecl->getLocation(), DirectInit, Init);
11287     // FIXME: Initialization should not be taking a mutable list of inits.
11288     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11289     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11290                                                        InitsCopy);
11291   }
11292 
11293   if (DirectInit) {
11294     if (auto *IL = dyn_cast<InitListExpr>(Init))
11295       DeduceInits = IL->inits();
11296   }
11297 
11298   // Deduction only works if we have exactly one source expression.
11299   if (DeduceInits.empty()) {
11300     // It isn't possible to write this directly, but it is possible to
11301     // end up in this situation with "auto x(some_pack...);"
11302     Diag(Init->getBeginLoc(), IsInitCapture
11303                                   ? diag::err_init_capture_no_expression
11304                                   : diag::err_auto_var_init_no_expression)
11305         << VN << Type << Range;
11306     return QualType();
11307   }
11308 
11309   if (DeduceInits.size() > 1) {
11310     Diag(DeduceInits[1]->getBeginLoc(),
11311          IsInitCapture ? diag::err_init_capture_multiple_expressions
11312                        : diag::err_auto_var_init_multiple_expressions)
11313         << VN << Type << Range;
11314     return QualType();
11315   }
11316 
11317   Expr *DeduceInit = DeduceInits[0];
11318   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11319     Diag(Init->getBeginLoc(), IsInitCapture
11320                                   ? diag::err_init_capture_paren_braces
11321                                   : diag::err_auto_var_init_paren_braces)
11322         << isa<InitListExpr>(Init) << VN << Type << Range;
11323     return QualType();
11324   }
11325 
11326   // Expressions default to 'id' when we're in a debugger.
11327   bool DefaultedAnyToId = false;
11328   if (getLangOpts().DebuggerCastResultToId &&
11329       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11330     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11331     if (Result.isInvalid()) {
11332       return QualType();
11333     }
11334     Init = Result.get();
11335     DefaultedAnyToId = true;
11336   }
11337 
11338   // C++ [dcl.decomp]p1:
11339   //   If the assignment-expression [...] has array type A and no ref-qualifier
11340   //   is present, e has type cv A
11341   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11342       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11343       DeduceInit->getType()->isConstantArrayType())
11344     return Context.getQualifiedType(DeduceInit->getType(),
11345                                     Type.getQualifiers());
11346 
11347   QualType DeducedType;
11348   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11349     if (!IsInitCapture)
11350       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11351     else if (isa<InitListExpr>(Init))
11352       Diag(Range.getBegin(),
11353            diag::err_init_capture_deduction_failure_from_init_list)
11354           << VN
11355           << (DeduceInit->getType().isNull() ? TSI->getType()
11356                                              : DeduceInit->getType())
11357           << DeduceInit->getSourceRange();
11358     else
11359       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11360           << VN << TSI->getType()
11361           << (DeduceInit->getType().isNull() ? TSI->getType()
11362                                              : DeduceInit->getType())
11363           << DeduceInit->getSourceRange();
11364   }
11365 
11366   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11367   // 'id' instead of a specific object type prevents most of our usual
11368   // checks.
11369   // We only want to warn outside of template instantiations, though:
11370   // inside a template, the 'id' could have come from a parameter.
11371   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11372       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11373     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11374     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11375   }
11376 
11377   return DeducedType;
11378 }
11379 
11380 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11381                                          Expr *Init) {
11382   QualType DeducedType = deduceVarTypeFromInitializer(
11383       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11384       VDecl->getSourceRange(), DirectInit, Init);
11385   if (DeducedType.isNull()) {
11386     VDecl->setInvalidDecl();
11387     return true;
11388   }
11389 
11390   VDecl->setType(DeducedType);
11391   assert(VDecl->isLinkageValid());
11392 
11393   // In ARC, infer lifetime.
11394   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11395     VDecl->setInvalidDecl();
11396 
11397   if (getLangOpts().OpenCL)
11398     deduceOpenCLAddressSpace(VDecl);
11399 
11400   // If this is a redeclaration, check that the type we just deduced matches
11401   // the previously declared type.
11402   if (VarDecl *Old = VDecl->getPreviousDecl()) {
11403     // We never need to merge the type, because we cannot form an incomplete
11404     // array of auto, nor deduce such a type.
11405     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11406   }
11407 
11408   // Check the deduced type is valid for a variable declaration.
11409   CheckVariableDeclarationType(VDecl);
11410   return VDecl->isInvalidDecl();
11411 }
11412 
11413 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11414                                               SourceLocation Loc) {
11415   if (auto *CE = dyn_cast<ConstantExpr>(Init))
11416     Init = CE->getSubExpr();
11417 
11418   QualType InitType = Init->getType();
11419   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11420           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
11421          "shouldn't be called if type doesn't have a non-trivial C struct");
11422   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11423     for (auto I : ILE->inits()) {
11424       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11425           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11426         continue;
11427       SourceLocation SL = I->getExprLoc();
11428       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11429     }
11430     return;
11431   }
11432 
11433   if (isa<ImplicitValueInitExpr>(Init)) {
11434     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11435       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11436                             NTCUK_Init);
11437   } else {
11438     // Assume all other explicit initializers involving copying some existing
11439     // object.
11440     // TODO: ignore any explicit initializers where we can guarantee
11441     // copy-elision.
11442     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11443       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11444   }
11445 }
11446 
11447 namespace {
11448 
11449 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11450   // Ignore unavailable fields. A field can be marked as unavailable explicitly
11451   // in the source code or implicitly by the compiler if it is in a union
11452   // defined in a system header and has non-trivial ObjC ownership
11453   // qualifications. We don't want those fields to participate in determining
11454   // whether the containing union is non-trivial.
11455   return FD->hasAttr<UnavailableAttr>();
11456 }
11457 
11458 struct DiagNonTrivalCUnionDefaultInitializeVisitor
11459     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11460                                     void> {
11461   using Super =
11462       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11463                                     void>;
11464 
11465   DiagNonTrivalCUnionDefaultInitializeVisitor(
11466       QualType OrigTy, SourceLocation OrigLoc,
11467       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11468       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11469 
11470   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11471                      const FieldDecl *FD, bool InNonTrivialUnion) {
11472     if (const auto *AT = S.Context.getAsArrayType(QT))
11473       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11474                                      InNonTrivialUnion);
11475     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11476   }
11477 
11478   void visitARCStrong(QualType QT, const FieldDecl *FD,
11479                       bool InNonTrivialUnion) {
11480     if (InNonTrivialUnion)
11481       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11482           << 1 << 0 << QT << FD->getName();
11483   }
11484 
11485   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11486     if (InNonTrivialUnion)
11487       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11488           << 1 << 0 << QT << FD->getName();
11489   }
11490 
11491   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11492     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11493     if (RD->isUnion()) {
11494       if (OrigLoc.isValid()) {
11495         bool IsUnion = false;
11496         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11497           IsUnion = OrigRD->isUnion();
11498         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11499             << 0 << OrigTy << IsUnion << UseContext;
11500         // Reset OrigLoc so that this diagnostic is emitted only once.
11501         OrigLoc = SourceLocation();
11502       }
11503       InNonTrivialUnion = true;
11504     }
11505 
11506     if (InNonTrivialUnion)
11507       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11508           << 0 << 0 << QT.getUnqualifiedType() << "";
11509 
11510     for (const FieldDecl *FD : RD->fields())
11511       if (!shouldIgnoreForRecordTriviality(FD))
11512         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11513   }
11514 
11515   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11516 
11517   // The non-trivial C union type or the struct/union type that contains a
11518   // non-trivial C union.
11519   QualType OrigTy;
11520   SourceLocation OrigLoc;
11521   Sema::NonTrivialCUnionContext UseContext;
11522   Sema &S;
11523 };
11524 
11525 struct DiagNonTrivalCUnionDestructedTypeVisitor
11526     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
11527   using Super =
11528       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
11529 
11530   DiagNonTrivalCUnionDestructedTypeVisitor(
11531       QualType OrigTy, SourceLocation OrigLoc,
11532       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11533       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11534 
11535   void visitWithKind(QualType::DestructionKind DK, QualType QT,
11536                      const FieldDecl *FD, bool InNonTrivialUnion) {
11537     if (const auto *AT = S.Context.getAsArrayType(QT))
11538       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11539                                      InNonTrivialUnion);
11540     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
11541   }
11542 
11543   void visitARCStrong(QualType QT, const FieldDecl *FD,
11544                       bool InNonTrivialUnion) {
11545     if (InNonTrivialUnion)
11546       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11547           << 1 << 1 << QT << FD->getName();
11548   }
11549 
11550   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11551     if (InNonTrivialUnion)
11552       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11553           << 1 << 1 << QT << FD->getName();
11554   }
11555 
11556   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11557     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11558     if (RD->isUnion()) {
11559       if (OrigLoc.isValid()) {
11560         bool IsUnion = false;
11561         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11562           IsUnion = OrigRD->isUnion();
11563         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11564             << 1 << OrigTy << IsUnion << UseContext;
11565         // Reset OrigLoc so that this diagnostic is emitted only once.
11566         OrigLoc = SourceLocation();
11567       }
11568       InNonTrivialUnion = true;
11569     }
11570 
11571     if (InNonTrivialUnion)
11572       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11573           << 0 << 1 << QT.getUnqualifiedType() << "";
11574 
11575     for (const FieldDecl *FD : RD->fields())
11576       if (!shouldIgnoreForRecordTriviality(FD))
11577         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11578   }
11579 
11580   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11581   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
11582                           bool InNonTrivialUnion) {}
11583 
11584   // The non-trivial C union type or the struct/union type that contains a
11585   // non-trivial C union.
11586   QualType OrigTy;
11587   SourceLocation OrigLoc;
11588   Sema::NonTrivialCUnionContext UseContext;
11589   Sema &S;
11590 };
11591 
11592 struct DiagNonTrivalCUnionCopyVisitor
11593     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
11594   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
11595 
11596   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
11597                                  Sema::NonTrivialCUnionContext UseContext,
11598                                  Sema &S)
11599       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11600 
11601   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
11602                      const FieldDecl *FD, bool InNonTrivialUnion) {
11603     if (const auto *AT = S.Context.getAsArrayType(QT))
11604       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11605                                      InNonTrivialUnion);
11606     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
11607   }
11608 
11609   void visitARCStrong(QualType QT, const FieldDecl *FD,
11610                       bool InNonTrivialUnion) {
11611     if (InNonTrivialUnion)
11612       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11613           << 1 << 2 << QT << FD->getName();
11614   }
11615 
11616   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11617     if (InNonTrivialUnion)
11618       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11619           << 1 << 2 << QT << FD->getName();
11620   }
11621 
11622   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11623     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11624     if (RD->isUnion()) {
11625       if (OrigLoc.isValid()) {
11626         bool IsUnion = false;
11627         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11628           IsUnion = OrigRD->isUnion();
11629         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11630             << 2 << OrigTy << IsUnion << UseContext;
11631         // Reset OrigLoc so that this diagnostic is emitted only once.
11632         OrigLoc = SourceLocation();
11633       }
11634       InNonTrivialUnion = true;
11635     }
11636 
11637     if (InNonTrivialUnion)
11638       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11639           << 0 << 2 << QT.getUnqualifiedType() << "";
11640 
11641     for (const FieldDecl *FD : RD->fields())
11642       if (!shouldIgnoreForRecordTriviality(FD))
11643         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11644   }
11645 
11646   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
11647                 const FieldDecl *FD, bool InNonTrivialUnion) {}
11648   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11649   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
11650                             bool InNonTrivialUnion) {}
11651 
11652   // The non-trivial C union type or the struct/union type that contains a
11653   // non-trivial C union.
11654   QualType OrigTy;
11655   SourceLocation OrigLoc;
11656   Sema::NonTrivialCUnionContext UseContext;
11657   Sema &S;
11658 };
11659 
11660 } // namespace
11661 
11662 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
11663                                  NonTrivialCUnionContext UseContext,
11664                                  unsigned NonTrivialKind) {
11665   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11666           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
11667           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
11668          "shouldn't be called if type doesn't have a non-trivial C union");
11669 
11670   if ((NonTrivialKind & NTCUK_Init) &&
11671       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11672     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
11673         .visit(QT, nullptr, false);
11674   if ((NonTrivialKind & NTCUK_Destruct) &&
11675       QT.hasNonTrivialToPrimitiveDestructCUnion())
11676     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
11677         .visit(QT, nullptr, false);
11678   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
11679     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
11680         .visit(QT, nullptr, false);
11681 }
11682 
11683 /// AddInitializerToDecl - Adds the initializer Init to the
11684 /// declaration dcl. If DirectInit is true, this is C++ direct
11685 /// initialization rather than copy initialization.
11686 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
11687   // If there is no declaration, there was an error parsing it.  Just ignore
11688   // the initializer.
11689   if (!RealDecl || RealDecl->isInvalidDecl()) {
11690     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
11691     return;
11692   }
11693 
11694   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
11695     // Pure-specifiers are handled in ActOnPureSpecifier.
11696     Diag(Method->getLocation(), diag::err_member_function_initialization)
11697       << Method->getDeclName() << Init->getSourceRange();
11698     Method->setInvalidDecl();
11699     return;
11700   }
11701 
11702   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
11703   if (!VDecl) {
11704     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
11705     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
11706     RealDecl->setInvalidDecl();
11707     return;
11708   }
11709 
11710   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
11711   if (VDecl->getType()->isUndeducedType()) {
11712     // Attempt typo correction early so that the type of the init expression can
11713     // be deduced based on the chosen correction if the original init contains a
11714     // TypoExpr.
11715     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
11716     if (!Res.isUsable()) {
11717       RealDecl->setInvalidDecl();
11718       return;
11719     }
11720     Init = Res.get();
11721 
11722     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
11723       return;
11724   }
11725 
11726   // dllimport cannot be used on variable definitions.
11727   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
11728     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
11729     VDecl->setInvalidDecl();
11730     return;
11731   }
11732 
11733   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
11734     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
11735     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
11736     VDecl->setInvalidDecl();
11737     return;
11738   }
11739 
11740   if (!VDecl->getType()->isDependentType()) {
11741     // A definition must end up with a complete type, which means it must be
11742     // complete with the restriction that an array type might be completed by
11743     // the initializer; note that later code assumes this restriction.
11744     QualType BaseDeclType = VDecl->getType();
11745     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
11746       BaseDeclType = Array->getElementType();
11747     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
11748                             diag::err_typecheck_decl_incomplete_type)) {
11749       RealDecl->setInvalidDecl();
11750       return;
11751     }
11752 
11753     // The variable can not have an abstract class type.
11754     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
11755                                diag::err_abstract_type_in_decl,
11756                                AbstractVariableType))
11757       VDecl->setInvalidDecl();
11758   }
11759 
11760   // If adding the initializer will turn this declaration into a definition,
11761   // and we already have a definition for this variable, diagnose or otherwise
11762   // handle the situation.
11763   VarDecl *Def;
11764   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
11765       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
11766       !VDecl->isThisDeclarationADemotedDefinition() &&
11767       checkVarDeclRedefinition(Def, VDecl))
11768     return;
11769 
11770   if (getLangOpts().CPlusPlus) {
11771     // C++ [class.static.data]p4
11772     //   If a static data member is of const integral or const
11773     //   enumeration type, its declaration in the class definition can
11774     //   specify a constant-initializer which shall be an integral
11775     //   constant expression (5.19). In that case, the member can appear
11776     //   in integral constant expressions. The member shall still be
11777     //   defined in a namespace scope if it is used in the program and the
11778     //   namespace scope definition shall not contain an initializer.
11779     //
11780     // We already performed a redefinition check above, but for static
11781     // data members we also need to check whether there was an in-class
11782     // declaration with an initializer.
11783     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
11784       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
11785           << VDecl->getDeclName();
11786       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
11787            diag::note_previous_initializer)
11788           << 0;
11789       return;
11790     }
11791 
11792     if (VDecl->hasLocalStorage())
11793       setFunctionHasBranchProtectedScope();
11794 
11795     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
11796       VDecl->setInvalidDecl();
11797       return;
11798     }
11799   }
11800 
11801   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
11802   // a kernel function cannot be initialized."
11803   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
11804     Diag(VDecl->getLocation(), diag::err_local_cant_init);
11805     VDecl->setInvalidDecl();
11806     return;
11807   }
11808 
11809   // Get the decls type and save a reference for later, since
11810   // CheckInitializerTypes may change it.
11811   QualType DclT = VDecl->getType(), SavT = DclT;
11812 
11813   // Expressions default to 'id' when we're in a debugger
11814   // and we are assigning it to a variable of Objective-C pointer type.
11815   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
11816       Init->getType() == Context.UnknownAnyTy) {
11817     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11818     if (Result.isInvalid()) {
11819       VDecl->setInvalidDecl();
11820       return;
11821     }
11822     Init = Result.get();
11823   }
11824 
11825   // Perform the initialization.
11826   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
11827   if (!VDecl->isInvalidDecl()) {
11828     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11829     InitializationKind Kind = InitializationKind::CreateForInit(
11830         VDecl->getLocation(), DirectInit, Init);
11831 
11832     MultiExprArg Args = Init;
11833     if (CXXDirectInit)
11834       Args = MultiExprArg(CXXDirectInit->getExprs(),
11835                           CXXDirectInit->getNumExprs());
11836 
11837     // Try to correct any TypoExprs in the initialization arguments.
11838     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
11839       ExprResult Res = CorrectDelayedTyposInExpr(
11840           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
11841             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
11842             return Init.Failed() ? ExprError() : E;
11843           });
11844       if (Res.isInvalid()) {
11845         VDecl->setInvalidDecl();
11846       } else if (Res.get() != Args[Idx]) {
11847         Args[Idx] = Res.get();
11848       }
11849     }
11850     if (VDecl->isInvalidDecl())
11851       return;
11852 
11853     InitializationSequence InitSeq(*this, Entity, Kind, Args,
11854                                    /*TopLevelOfInitList=*/false,
11855                                    /*TreatUnavailableAsInvalid=*/false);
11856     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
11857     if (Result.isInvalid()) {
11858       VDecl->setInvalidDecl();
11859       return;
11860     }
11861 
11862     Init = Result.getAs<Expr>();
11863   }
11864 
11865   // Check for self-references within variable initializers.
11866   // Variables declared within a function/method body (except for references)
11867   // are handled by a dataflow analysis.
11868   // This is undefined behavior in C++, but valid in C.
11869   if (getLangOpts().CPlusPlus) {
11870     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
11871         VDecl->getType()->isReferenceType()) {
11872       CheckSelfReference(*this, RealDecl, Init, DirectInit);
11873     }
11874   }
11875 
11876   // If the type changed, it means we had an incomplete type that was
11877   // completed by the initializer. For example:
11878   //   int ary[] = { 1, 3, 5 };
11879   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
11880   if (!VDecl->isInvalidDecl() && (DclT != SavT))
11881     VDecl->setType(DclT);
11882 
11883   if (!VDecl->isInvalidDecl()) {
11884     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
11885 
11886     if (VDecl->hasAttr<BlocksAttr>())
11887       checkRetainCycles(VDecl, Init);
11888 
11889     // It is safe to assign a weak reference into a strong variable.
11890     // Although this code can still have problems:
11891     //   id x = self.weakProp;
11892     //   id y = self.weakProp;
11893     // we do not warn to warn spuriously when 'x' and 'y' are on separate
11894     // paths through the function. This should be revisited if
11895     // -Wrepeated-use-of-weak is made flow-sensitive.
11896     if (FunctionScopeInfo *FSI = getCurFunction())
11897       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
11898            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
11899           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11900                            Init->getBeginLoc()))
11901         FSI->markSafeWeakUse(Init);
11902   }
11903 
11904   // The initialization is usually a full-expression.
11905   //
11906   // FIXME: If this is a braced initialization of an aggregate, it is not
11907   // an expression, and each individual field initializer is a separate
11908   // full-expression. For instance, in:
11909   //
11910   //   struct Temp { ~Temp(); };
11911   //   struct S { S(Temp); };
11912   //   struct T { S a, b; } t = { Temp(), Temp() }
11913   //
11914   // we should destroy the first Temp before constructing the second.
11915   ExprResult Result =
11916       ActOnFinishFullExpr(Init, VDecl->getLocation(),
11917                           /*DiscardedValue*/ false, VDecl->isConstexpr());
11918   if (Result.isInvalid()) {
11919     VDecl->setInvalidDecl();
11920     return;
11921   }
11922   Init = Result.get();
11923 
11924   // Attach the initializer to the decl.
11925   VDecl->setInit(Init);
11926 
11927   if (VDecl->isLocalVarDecl()) {
11928     // Don't check the initializer if the declaration is malformed.
11929     if (VDecl->isInvalidDecl()) {
11930       // do nothing
11931 
11932     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
11933     // This is true even in C++ for OpenCL.
11934     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
11935       CheckForConstantInitializer(Init, DclT);
11936 
11937     // Otherwise, C++ does not restrict the initializer.
11938     } else if (getLangOpts().CPlusPlus) {
11939       // do nothing
11940 
11941     // C99 6.7.8p4: All the expressions in an initializer for an object that has
11942     // static storage duration shall be constant expressions or string literals.
11943     } else if (VDecl->getStorageClass() == SC_Static) {
11944       CheckForConstantInitializer(Init, DclT);
11945 
11946     // C89 is stricter than C99 for aggregate initializers.
11947     // C89 6.5.7p3: All the expressions [...] in an initializer list
11948     // for an object that has aggregate or union type shall be
11949     // constant expressions.
11950     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
11951                isa<InitListExpr>(Init)) {
11952       const Expr *Culprit;
11953       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
11954         Diag(Culprit->getExprLoc(),
11955              diag::ext_aggregate_init_not_constant)
11956           << Culprit->getSourceRange();
11957       }
11958     }
11959 
11960     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
11961       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
11962         if (VDecl->hasLocalStorage())
11963           BE->getBlockDecl()->setCanAvoidCopyToHeap();
11964   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
11965              VDecl->getLexicalDeclContext()->isRecord()) {
11966     // This is an in-class initialization for a static data member, e.g.,
11967     //
11968     // struct S {
11969     //   static const int value = 17;
11970     // };
11971 
11972     // C++ [class.mem]p4:
11973     //   A member-declarator can contain a constant-initializer only
11974     //   if it declares a static member (9.4) of const integral or
11975     //   const enumeration type, see 9.4.2.
11976     //
11977     // C++11 [class.static.data]p3:
11978     //   If a non-volatile non-inline const static data member is of integral
11979     //   or enumeration type, its declaration in the class definition can
11980     //   specify a brace-or-equal-initializer in which every initializer-clause
11981     //   that is an assignment-expression is a constant expression. A static
11982     //   data member of literal type can be declared in the class definition
11983     //   with the constexpr specifier; if so, its declaration shall specify a
11984     //   brace-or-equal-initializer in which every initializer-clause that is
11985     //   an assignment-expression is a constant expression.
11986 
11987     // Do nothing on dependent types.
11988     if (DclT->isDependentType()) {
11989 
11990     // Allow any 'static constexpr' members, whether or not they are of literal
11991     // type. We separately check that every constexpr variable is of literal
11992     // type.
11993     } else if (VDecl->isConstexpr()) {
11994 
11995     // Require constness.
11996     } else if (!DclT.isConstQualified()) {
11997       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
11998         << Init->getSourceRange();
11999       VDecl->setInvalidDecl();
12000 
12001     // We allow integer constant expressions in all cases.
12002     } else if (DclT->isIntegralOrEnumerationType()) {
12003       // Check whether the expression is a constant expression.
12004       SourceLocation Loc;
12005       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12006         // In C++11, a non-constexpr const static data member with an
12007         // in-class initializer cannot be volatile.
12008         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12009       else if (Init->isValueDependent())
12010         ; // Nothing to check.
12011       else if (Init->isIntegerConstantExpr(Context, &Loc))
12012         ; // Ok, it's an ICE!
12013       else if (Init->getType()->isScopedEnumeralType() &&
12014                Init->isCXX11ConstantExpr(Context))
12015         ; // Ok, it is a scoped-enum constant expression.
12016       else if (Init->isEvaluatable(Context)) {
12017         // If we can constant fold the initializer through heroics, accept it,
12018         // but report this as a use of an extension for -pedantic.
12019         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12020           << Init->getSourceRange();
12021       } else {
12022         // Otherwise, this is some crazy unknown case.  Report the issue at the
12023         // location provided by the isIntegerConstantExpr failed check.
12024         Diag(Loc, diag::err_in_class_initializer_non_constant)
12025           << Init->getSourceRange();
12026         VDecl->setInvalidDecl();
12027       }
12028 
12029     // We allow foldable floating-point constants as an extension.
12030     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12031       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12032       // it anyway and provide a fixit to add the 'constexpr'.
12033       if (getLangOpts().CPlusPlus11) {
12034         Diag(VDecl->getLocation(),
12035              diag::ext_in_class_initializer_float_type_cxx11)
12036             << DclT << Init->getSourceRange();
12037         Diag(VDecl->getBeginLoc(),
12038              diag::note_in_class_initializer_float_type_cxx11)
12039             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12040       } else {
12041         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12042           << DclT << Init->getSourceRange();
12043 
12044         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12045           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12046             << Init->getSourceRange();
12047           VDecl->setInvalidDecl();
12048         }
12049       }
12050 
12051     // Suggest adding 'constexpr' in C++11 for literal types.
12052     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12053       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12054           << DclT << Init->getSourceRange()
12055           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12056       VDecl->setConstexpr(true);
12057 
12058     } else {
12059       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12060         << DclT << Init->getSourceRange();
12061       VDecl->setInvalidDecl();
12062     }
12063   } else if (VDecl->isFileVarDecl()) {
12064     // In C, extern is typically used to avoid tentative definitions when
12065     // declaring variables in headers, but adding an intializer makes it a
12066     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12067     // In C++, extern is often used to give implictly static const variables
12068     // external linkage, so don't warn in that case. If selectany is present,
12069     // this might be header code intended for C and C++ inclusion, so apply the
12070     // C++ rules.
12071     if (VDecl->getStorageClass() == SC_Extern &&
12072         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12073          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12074         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12075         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12076       Diag(VDecl->getLocation(), diag::warn_extern_init);
12077 
12078     // In Microsoft C++ mode, a const variable defined in namespace scope has
12079     // external linkage by default if the variable is declared with
12080     // __declspec(dllexport).
12081     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12082         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12083         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12084       VDecl->setStorageClass(SC_Extern);
12085 
12086     // C99 6.7.8p4. All file scoped initializers need to be constant.
12087     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12088       CheckForConstantInitializer(Init, DclT);
12089   }
12090 
12091   QualType InitType = Init->getType();
12092   if (!InitType.isNull() &&
12093       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12094        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12095     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12096 
12097   // We will represent direct-initialization similarly to copy-initialization:
12098   //    int x(1);  -as-> int x = 1;
12099   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12100   //
12101   // Clients that want to distinguish between the two forms, can check for
12102   // direct initializer using VarDecl::getInitStyle().
12103   // A major benefit is that clients that don't particularly care about which
12104   // exactly form was it (like the CodeGen) can handle both cases without
12105   // special case code.
12106 
12107   // C++ 8.5p11:
12108   // The form of initialization (using parentheses or '=') is generally
12109   // insignificant, but does matter when the entity being initialized has a
12110   // class type.
12111   if (CXXDirectInit) {
12112     assert(DirectInit && "Call-style initializer must be direct init.");
12113     VDecl->setInitStyle(VarDecl::CallInit);
12114   } else if (DirectInit) {
12115     // This must be list-initialization. No other way is direct-initialization.
12116     VDecl->setInitStyle(VarDecl::ListInit);
12117   }
12118 
12119   CheckCompleteVariableDeclaration(VDecl);
12120 }
12121 
12122 /// ActOnInitializerError - Given that there was an error parsing an
12123 /// initializer for the given declaration, try to return to some form
12124 /// of sanity.
12125 void Sema::ActOnInitializerError(Decl *D) {
12126   // Our main concern here is re-establishing invariants like "a
12127   // variable's type is either dependent or complete".
12128   if (!D || D->isInvalidDecl()) return;
12129 
12130   VarDecl *VD = dyn_cast<VarDecl>(D);
12131   if (!VD) return;
12132 
12133   // Bindings are not usable if we can't make sense of the initializer.
12134   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12135     for (auto *BD : DD->bindings())
12136       BD->setInvalidDecl();
12137 
12138   // Auto types are meaningless if we can't make sense of the initializer.
12139   if (ParsingInitForAutoVars.count(D)) {
12140     D->setInvalidDecl();
12141     return;
12142   }
12143 
12144   QualType Ty = VD->getType();
12145   if (Ty->isDependentType()) return;
12146 
12147   // Require a complete type.
12148   if (RequireCompleteType(VD->getLocation(),
12149                           Context.getBaseElementType(Ty),
12150                           diag::err_typecheck_decl_incomplete_type)) {
12151     VD->setInvalidDecl();
12152     return;
12153   }
12154 
12155   // Require a non-abstract type.
12156   if (RequireNonAbstractType(VD->getLocation(), Ty,
12157                              diag::err_abstract_type_in_decl,
12158                              AbstractVariableType)) {
12159     VD->setInvalidDecl();
12160     return;
12161   }
12162 
12163   // Don't bother complaining about constructors or destructors,
12164   // though.
12165 }
12166 
12167 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12168   // If there is no declaration, there was an error parsing it. Just ignore it.
12169   if (!RealDecl)
12170     return;
12171 
12172   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12173     QualType Type = Var->getType();
12174 
12175     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12176     if (isa<DecompositionDecl>(RealDecl)) {
12177       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12178       Var->setInvalidDecl();
12179       return;
12180     }
12181 
12182     if (Type->isUndeducedType() &&
12183         DeduceVariableDeclarationType(Var, false, nullptr))
12184       return;
12185 
12186     // C++11 [class.static.data]p3: A static data member can be declared with
12187     // the constexpr specifier; if so, its declaration shall specify
12188     // a brace-or-equal-initializer.
12189     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12190     // the definition of a variable [...] or the declaration of a static data
12191     // member.
12192     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12193         !Var->isThisDeclarationADemotedDefinition()) {
12194       if (Var->isStaticDataMember()) {
12195         // C++1z removes the relevant rule; the in-class declaration is always
12196         // a definition there.
12197         if (!getLangOpts().CPlusPlus17 &&
12198             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12199           Diag(Var->getLocation(),
12200                diag::err_constexpr_static_mem_var_requires_init)
12201             << Var->getDeclName();
12202           Var->setInvalidDecl();
12203           return;
12204         }
12205       } else {
12206         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12207         Var->setInvalidDecl();
12208         return;
12209       }
12210     }
12211 
12212     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12213     // be initialized.
12214     if (!Var->isInvalidDecl() &&
12215         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12216         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12217       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12218       Var->setInvalidDecl();
12219       return;
12220     }
12221 
12222     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12223     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12224         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12225       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12226                             NTCUC_DefaultInitializedObject, NTCUK_Init);
12227 
12228 
12229     switch (DefKind) {
12230     case VarDecl::Definition:
12231       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12232         break;
12233 
12234       // We have an out-of-line definition of a static data member
12235       // that has an in-class initializer, so we type-check this like
12236       // a declaration.
12237       //
12238       LLVM_FALLTHROUGH;
12239 
12240     case VarDecl::DeclarationOnly:
12241       // It's only a declaration.
12242 
12243       // Block scope. C99 6.7p7: If an identifier for an object is
12244       // declared with no linkage (C99 6.2.2p6), the type for the
12245       // object shall be complete.
12246       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12247           !Var->hasLinkage() && !Var->isInvalidDecl() &&
12248           RequireCompleteType(Var->getLocation(), Type,
12249                               diag::err_typecheck_decl_incomplete_type))
12250         Var->setInvalidDecl();
12251 
12252       // Make sure that the type is not abstract.
12253       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12254           RequireNonAbstractType(Var->getLocation(), Type,
12255                                  diag::err_abstract_type_in_decl,
12256                                  AbstractVariableType))
12257         Var->setInvalidDecl();
12258       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12259           Var->getStorageClass() == SC_PrivateExtern) {
12260         Diag(Var->getLocation(), diag::warn_private_extern);
12261         Diag(Var->getLocation(), diag::note_private_extern);
12262       }
12263 
12264       if (Context.getTargetInfo().allowDebugInfoForExternalVar() &&
12265           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12266         ExternalDeclarations.push_back(Var);
12267 
12268       return;
12269 
12270     case VarDecl::TentativeDefinition:
12271       // File scope. C99 6.9.2p2: A declaration of an identifier for an
12272       // object that has file scope without an initializer, and without a
12273       // storage-class specifier or with the storage-class specifier "static",
12274       // constitutes a tentative definition. Note: A tentative definition with
12275       // external linkage is valid (C99 6.2.2p5).
12276       if (!Var->isInvalidDecl()) {
12277         if (const IncompleteArrayType *ArrayT
12278                                     = Context.getAsIncompleteArrayType(Type)) {
12279           if (RequireCompleteType(Var->getLocation(),
12280                                   ArrayT->getElementType(),
12281                                   diag::err_illegal_decl_array_incomplete_type))
12282             Var->setInvalidDecl();
12283         } else if (Var->getStorageClass() == SC_Static) {
12284           // C99 6.9.2p3: If the declaration of an identifier for an object is
12285           // a tentative definition and has internal linkage (C99 6.2.2p3), the
12286           // declared type shall not be an incomplete type.
12287           // NOTE: code such as the following
12288           //     static struct s;
12289           //     struct s { int a; };
12290           // is accepted by gcc. Hence here we issue a warning instead of
12291           // an error and we do not invalidate the static declaration.
12292           // NOTE: to avoid multiple warnings, only check the first declaration.
12293           if (Var->isFirstDecl())
12294             RequireCompleteType(Var->getLocation(), Type,
12295                                 diag::ext_typecheck_decl_incomplete_type);
12296         }
12297       }
12298 
12299       // Record the tentative definition; we're done.
12300       if (!Var->isInvalidDecl())
12301         TentativeDefinitions.push_back(Var);
12302       return;
12303     }
12304 
12305     // Provide a specific diagnostic for uninitialized variable
12306     // definitions with incomplete array type.
12307     if (Type->isIncompleteArrayType()) {
12308       Diag(Var->getLocation(),
12309            diag::err_typecheck_incomplete_array_needs_initializer);
12310       Var->setInvalidDecl();
12311       return;
12312     }
12313 
12314     // Provide a specific diagnostic for uninitialized variable
12315     // definitions with reference type.
12316     if (Type->isReferenceType()) {
12317       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12318         << Var->getDeclName()
12319         << SourceRange(Var->getLocation(), Var->getLocation());
12320       Var->setInvalidDecl();
12321       return;
12322     }
12323 
12324     // Do not attempt to type-check the default initializer for a
12325     // variable with dependent type.
12326     if (Type->isDependentType())
12327       return;
12328 
12329     if (Var->isInvalidDecl())
12330       return;
12331 
12332     if (!Var->hasAttr<AliasAttr>()) {
12333       if (RequireCompleteType(Var->getLocation(),
12334                               Context.getBaseElementType(Type),
12335                               diag::err_typecheck_decl_incomplete_type)) {
12336         Var->setInvalidDecl();
12337         return;
12338       }
12339     } else {
12340       return;
12341     }
12342 
12343     // The variable can not have an abstract class type.
12344     if (RequireNonAbstractType(Var->getLocation(), Type,
12345                                diag::err_abstract_type_in_decl,
12346                                AbstractVariableType)) {
12347       Var->setInvalidDecl();
12348       return;
12349     }
12350 
12351     // Check for jumps past the implicit initializer.  C++0x
12352     // clarifies that this applies to a "variable with automatic
12353     // storage duration", not a "local variable".
12354     // C++11 [stmt.dcl]p3
12355     //   A program that jumps from a point where a variable with automatic
12356     //   storage duration is not in scope to a point where it is in scope is
12357     //   ill-formed unless the variable has scalar type, class type with a
12358     //   trivial default constructor and a trivial destructor, a cv-qualified
12359     //   version of one of these types, or an array of one of the preceding
12360     //   types and is declared without an initializer.
12361     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12362       if (const RecordType *Record
12363             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12364         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12365         // Mark the function (if we're in one) for further checking even if the
12366         // looser rules of C++11 do not require such checks, so that we can
12367         // diagnose incompatibilities with C++98.
12368         if (!CXXRecord->isPOD())
12369           setFunctionHasBranchProtectedScope();
12370       }
12371     }
12372     // In OpenCL, we can't initialize objects in the __local address space,
12373     // even implicitly, so don't synthesize an implicit initializer.
12374     if (getLangOpts().OpenCL &&
12375         Var->getType().getAddressSpace() == LangAS::opencl_local)
12376       return;
12377     // C++03 [dcl.init]p9:
12378     //   If no initializer is specified for an object, and the
12379     //   object is of (possibly cv-qualified) non-POD class type (or
12380     //   array thereof), the object shall be default-initialized; if
12381     //   the object is of const-qualified type, the underlying class
12382     //   type shall have a user-declared default
12383     //   constructor. Otherwise, if no initializer is specified for
12384     //   a non- static object, the object and its subobjects, if
12385     //   any, have an indeterminate initial value); if the object
12386     //   or any of its subobjects are of const-qualified type, the
12387     //   program is ill-formed.
12388     // C++0x [dcl.init]p11:
12389     //   If no initializer is specified for an object, the object is
12390     //   default-initialized; [...].
12391     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12392     InitializationKind Kind
12393       = InitializationKind::CreateDefault(Var->getLocation());
12394 
12395     InitializationSequence InitSeq(*this, Entity, Kind, None);
12396     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12397     if (Init.isInvalid())
12398       Var->setInvalidDecl();
12399     else if (Init.get()) {
12400       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12401       // This is important for template substitution.
12402       Var->setInitStyle(VarDecl::CallInit);
12403     }
12404 
12405     CheckCompleteVariableDeclaration(Var);
12406   }
12407 }
12408 
12409 void Sema::ActOnCXXForRangeDecl(Decl *D) {
12410   // If there is no declaration, there was an error parsing it. Ignore it.
12411   if (!D)
12412     return;
12413 
12414   VarDecl *VD = dyn_cast<VarDecl>(D);
12415   if (!VD) {
12416     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12417     D->setInvalidDecl();
12418     return;
12419   }
12420 
12421   VD->setCXXForRangeDecl(true);
12422 
12423   // for-range-declaration cannot be given a storage class specifier.
12424   int Error = -1;
12425   switch (VD->getStorageClass()) {
12426   case SC_None:
12427     break;
12428   case SC_Extern:
12429     Error = 0;
12430     break;
12431   case SC_Static:
12432     Error = 1;
12433     break;
12434   case SC_PrivateExtern:
12435     Error = 2;
12436     break;
12437   case SC_Auto:
12438     Error = 3;
12439     break;
12440   case SC_Register:
12441     Error = 4;
12442     break;
12443   }
12444   if (Error != -1) {
12445     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12446       << VD->getDeclName() << Error;
12447     D->setInvalidDecl();
12448   }
12449 }
12450 
12451 StmtResult
12452 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
12453                                  IdentifierInfo *Ident,
12454                                  ParsedAttributes &Attrs,
12455                                  SourceLocation AttrEnd) {
12456   // C++1y [stmt.iter]p1:
12457   //   A range-based for statement of the form
12458   //      for ( for-range-identifier : for-range-initializer ) statement
12459   //   is equivalent to
12460   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
12461   DeclSpec DS(Attrs.getPool().getFactory());
12462 
12463   const char *PrevSpec;
12464   unsigned DiagID;
12465   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
12466                      getPrintingPolicy());
12467 
12468   Declarator D(DS, DeclaratorContext::ForContext);
12469   D.SetIdentifier(Ident, IdentLoc);
12470   D.takeAttributes(Attrs, AttrEnd);
12471 
12472   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
12473                 IdentLoc);
12474   Decl *Var = ActOnDeclarator(S, D);
12475   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
12476   FinalizeDeclaration(Var);
12477   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
12478                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
12479 }
12480 
12481 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
12482   if (var->isInvalidDecl()) return;
12483 
12484   if (getLangOpts().OpenCL) {
12485     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
12486     // initialiser
12487     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
12488         !var->hasInit()) {
12489       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
12490           << 1 /*Init*/;
12491       var->setInvalidDecl();
12492       return;
12493     }
12494   }
12495 
12496   // In Objective-C, don't allow jumps past the implicit initialization of a
12497   // local retaining variable.
12498   if (getLangOpts().ObjC &&
12499       var->hasLocalStorage()) {
12500     switch (var->getType().getObjCLifetime()) {
12501     case Qualifiers::OCL_None:
12502     case Qualifiers::OCL_ExplicitNone:
12503     case Qualifiers::OCL_Autoreleasing:
12504       break;
12505 
12506     case Qualifiers::OCL_Weak:
12507     case Qualifiers::OCL_Strong:
12508       setFunctionHasBranchProtectedScope();
12509       break;
12510     }
12511   }
12512 
12513   if (var->hasLocalStorage() &&
12514       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
12515     setFunctionHasBranchProtectedScope();
12516 
12517   // Warn about externally-visible variables being defined without a
12518   // prior declaration.  We only want to do this for global
12519   // declarations, but we also specifically need to avoid doing it for
12520   // class members because the linkage of an anonymous class can
12521   // change if it's later given a typedef name.
12522   if (var->isThisDeclarationADefinition() &&
12523       var->getDeclContext()->getRedeclContext()->isFileContext() &&
12524       var->isExternallyVisible() && var->hasLinkage() &&
12525       !var->isInline() && !var->getDescribedVarTemplate() &&
12526       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
12527       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
12528                                   var->getLocation())) {
12529     // Find a previous declaration that's not a definition.
12530     VarDecl *prev = var->getPreviousDecl();
12531     while (prev && prev->isThisDeclarationADefinition())
12532       prev = prev->getPreviousDecl();
12533 
12534     if (!prev) {
12535       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
12536       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
12537           << /* variable */ 0;
12538     }
12539   }
12540 
12541   // Cache the result of checking for constant initialization.
12542   Optional<bool> CacheHasConstInit;
12543   const Expr *CacheCulprit = nullptr;
12544   auto checkConstInit = [&]() mutable {
12545     if (!CacheHasConstInit)
12546       CacheHasConstInit = var->getInit()->isConstantInitializer(
12547             Context, var->getType()->isReferenceType(), &CacheCulprit);
12548     return *CacheHasConstInit;
12549   };
12550 
12551   if (var->getTLSKind() == VarDecl::TLS_Static) {
12552     if (var->getType().isDestructedType()) {
12553       // GNU C++98 edits for __thread, [basic.start.term]p3:
12554       //   The type of an object with thread storage duration shall not
12555       //   have a non-trivial destructor.
12556       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
12557       if (getLangOpts().CPlusPlus11)
12558         Diag(var->getLocation(), diag::note_use_thread_local);
12559     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
12560       if (!checkConstInit()) {
12561         // GNU C++98 edits for __thread, [basic.start.init]p4:
12562         //   An object of thread storage duration shall not require dynamic
12563         //   initialization.
12564         // FIXME: Need strict checking here.
12565         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
12566           << CacheCulprit->getSourceRange();
12567         if (getLangOpts().CPlusPlus11)
12568           Diag(var->getLocation(), diag::note_use_thread_local);
12569       }
12570     }
12571   }
12572 
12573   // Apply section attributes and pragmas to global variables.
12574   bool GlobalStorage = var->hasGlobalStorage();
12575   if (GlobalStorage && var->isThisDeclarationADefinition() &&
12576       !inTemplateInstantiation()) {
12577     PragmaStack<StringLiteral *> *Stack = nullptr;
12578     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
12579     if (var->getType().isConstQualified())
12580       Stack = &ConstSegStack;
12581     else if (!var->getInit()) {
12582       Stack = &BSSSegStack;
12583       SectionFlags |= ASTContext::PSF_Write;
12584     } else {
12585       Stack = &DataSegStack;
12586       SectionFlags |= ASTContext::PSF_Write;
12587     }
12588     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>())
12589       var->addAttr(SectionAttr::CreateImplicit(
12590           Context, Stack->CurrentValue->getString(),
12591           Stack->CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
12592           SectionAttr::Declspec_allocate));
12593     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
12594       if (UnifySection(SA->getName(), SectionFlags, var))
12595         var->dropAttr<SectionAttr>();
12596 
12597     // Apply the init_seg attribute if this has an initializer.  If the
12598     // initializer turns out to not be dynamic, we'll end up ignoring this
12599     // attribute.
12600     if (CurInitSeg && var->getInit())
12601       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
12602                                                CurInitSegLoc,
12603                                                AttributeCommonInfo::AS_Pragma));
12604   }
12605 
12606   // All the following checks are C++ only.
12607   if (!getLangOpts().CPlusPlus) {
12608       // If this variable must be emitted, add it as an initializer for the
12609       // current module.
12610      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12611        Context.addModuleInitializer(ModuleScopes.back().Module, var);
12612      return;
12613   }
12614 
12615   if (auto *DD = dyn_cast<DecompositionDecl>(var))
12616     CheckCompleteDecompositionDeclaration(DD);
12617 
12618   QualType type = var->getType();
12619   if (type->isDependentType()) return;
12620 
12621   if (var->hasAttr<BlocksAttr>())
12622     getCurFunction()->addByrefBlockVar(var);
12623 
12624   Expr *Init = var->getInit();
12625   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
12626   QualType baseType = Context.getBaseElementType(type);
12627 
12628   if (Init && !Init->isValueDependent()) {
12629     if (var->isConstexpr()) {
12630       SmallVector<PartialDiagnosticAt, 8> Notes;
12631       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
12632         SourceLocation DiagLoc = var->getLocation();
12633         // If the note doesn't add any useful information other than a source
12634         // location, fold it into the primary diagnostic.
12635         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12636               diag::note_invalid_subexpr_in_const_expr) {
12637           DiagLoc = Notes[0].first;
12638           Notes.clear();
12639         }
12640         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
12641           << var << Init->getSourceRange();
12642         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
12643           Diag(Notes[I].first, Notes[I].second);
12644       }
12645     } else if (var->mightBeUsableInConstantExpressions(Context)) {
12646       // Check whether the initializer of a const variable of integral or
12647       // enumeration type is an ICE now, since we can't tell whether it was
12648       // initialized by a constant expression if we check later.
12649       var->checkInitIsICE();
12650     }
12651 
12652     // Don't emit further diagnostics about constexpr globals since they
12653     // were just diagnosed.
12654     if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) {
12655       // FIXME: Need strict checking in C++03 here.
12656       bool DiagErr = getLangOpts().CPlusPlus11
12657           ? !var->checkInitIsICE() : !checkConstInit();
12658       if (DiagErr) {
12659         auto *Attr = var->getAttr<ConstInitAttr>();
12660         Diag(var->getLocation(), diag::err_require_constant_init_failed)
12661           << Init->getSourceRange();
12662         Diag(Attr->getLocation(),
12663              diag::note_declared_required_constant_init_here)
12664             << Attr->getRange() << Attr->isConstinit();
12665         if (getLangOpts().CPlusPlus11) {
12666           APValue Value;
12667           SmallVector<PartialDiagnosticAt, 8> Notes;
12668           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
12669           for (auto &it : Notes)
12670             Diag(it.first, it.second);
12671         } else {
12672           Diag(CacheCulprit->getExprLoc(),
12673                diag::note_invalid_subexpr_in_const_expr)
12674               << CacheCulprit->getSourceRange();
12675         }
12676       }
12677     }
12678     else if (!var->isConstexpr() && IsGlobal &&
12679              !getDiagnostics().isIgnored(diag::warn_global_constructor,
12680                                     var->getLocation())) {
12681       // Warn about globals which don't have a constant initializer.  Don't
12682       // warn about globals with a non-trivial destructor because we already
12683       // warned about them.
12684       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
12685       if (!(RD && !RD->hasTrivialDestructor())) {
12686         if (!checkConstInit())
12687           Diag(var->getLocation(), diag::warn_global_constructor)
12688             << Init->getSourceRange();
12689       }
12690     }
12691   }
12692 
12693   // Require the destructor.
12694   if (const RecordType *recordType = baseType->getAs<RecordType>())
12695     FinalizeVarWithDestructor(var, recordType);
12696 
12697   // If this variable must be emitted, add it as an initializer for the current
12698   // module.
12699   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12700     Context.addModuleInitializer(ModuleScopes.back().Module, var);
12701 }
12702 
12703 /// Determines if a variable's alignment is dependent.
12704 static bool hasDependentAlignment(VarDecl *VD) {
12705   if (VD->getType()->isDependentType())
12706     return true;
12707   for (auto *I : VD->specific_attrs<AlignedAttr>())
12708     if (I->isAlignmentDependent())
12709       return true;
12710   return false;
12711 }
12712 
12713 /// Check if VD needs to be dllexport/dllimport due to being in a
12714 /// dllexport/import function.
12715 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
12716   assert(VD->isStaticLocal());
12717 
12718   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12719 
12720   // Find outermost function when VD is in lambda function.
12721   while (FD && !getDLLAttr(FD) &&
12722          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
12723          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
12724     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
12725   }
12726 
12727   if (!FD)
12728     return;
12729 
12730   // Static locals inherit dll attributes from their function.
12731   if (Attr *A = getDLLAttr(FD)) {
12732     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
12733     NewAttr->setInherited(true);
12734     VD->addAttr(NewAttr);
12735   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
12736     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
12737     NewAttr->setInherited(true);
12738     VD->addAttr(NewAttr);
12739 
12740     // Export this function to enforce exporting this static variable even
12741     // if it is not used in this compilation unit.
12742     if (!FD->hasAttr<DLLExportAttr>())
12743       FD->addAttr(NewAttr);
12744 
12745   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
12746     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
12747     NewAttr->setInherited(true);
12748     VD->addAttr(NewAttr);
12749   }
12750 }
12751 
12752 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
12753 /// any semantic actions necessary after any initializer has been attached.
12754 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
12755   // Note that we are no longer parsing the initializer for this declaration.
12756   ParsingInitForAutoVars.erase(ThisDecl);
12757 
12758   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
12759   if (!VD)
12760     return;
12761 
12762   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
12763   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
12764       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
12765     if (PragmaClangBSSSection.Valid)
12766       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
12767           Context, PragmaClangBSSSection.SectionName,
12768           PragmaClangBSSSection.PragmaLocation,
12769           AttributeCommonInfo::AS_Pragma));
12770     if (PragmaClangDataSection.Valid)
12771       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
12772           Context, PragmaClangDataSection.SectionName,
12773           PragmaClangDataSection.PragmaLocation,
12774           AttributeCommonInfo::AS_Pragma));
12775     if (PragmaClangRodataSection.Valid)
12776       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
12777           Context, PragmaClangRodataSection.SectionName,
12778           PragmaClangRodataSection.PragmaLocation,
12779           AttributeCommonInfo::AS_Pragma));
12780     if (PragmaClangRelroSection.Valid)
12781       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
12782           Context, PragmaClangRelroSection.SectionName,
12783           PragmaClangRelroSection.PragmaLocation,
12784           AttributeCommonInfo::AS_Pragma));
12785   }
12786 
12787   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
12788     for (auto *BD : DD->bindings()) {
12789       FinalizeDeclaration(BD);
12790     }
12791   }
12792 
12793   checkAttributesAfterMerging(*this, *VD);
12794 
12795   // Perform TLS alignment check here after attributes attached to the variable
12796   // which may affect the alignment have been processed. Only perform the check
12797   // if the target has a maximum TLS alignment (zero means no constraints).
12798   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
12799     // Protect the check so that it's not performed on dependent types and
12800     // dependent alignments (we can't determine the alignment in that case).
12801     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
12802         !VD->isInvalidDecl()) {
12803       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
12804       if (Context.getDeclAlign(VD) > MaxAlignChars) {
12805         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
12806           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
12807           << (unsigned)MaxAlignChars.getQuantity();
12808       }
12809     }
12810   }
12811 
12812   if (VD->isStaticLocal()) {
12813     CheckStaticLocalForDllExport(VD);
12814 
12815     if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
12816       // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
12817       // function, only __shared__ variables or variables without any device
12818       // memory qualifiers may be declared with static storage class.
12819       // Note: It is unclear how a function-scope non-const static variable
12820       // without device memory qualifier is implemented, therefore only static
12821       // const variable without device memory qualifier is allowed.
12822       [&]() {
12823         if (!getLangOpts().CUDA)
12824           return;
12825         if (VD->hasAttr<CUDASharedAttr>())
12826           return;
12827         if (VD->getType().isConstQualified() &&
12828             !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
12829           return;
12830         if (CUDADiagIfDeviceCode(VD->getLocation(),
12831                                  diag::err_device_static_local_var)
12832             << CurrentCUDATarget())
12833           VD->setInvalidDecl();
12834       }();
12835     }
12836   }
12837 
12838   // Perform check for initializers of device-side global variables.
12839   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
12840   // 7.5). We must also apply the same checks to all __shared__
12841   // variables whether they are local or not. CUDA also allows
12842   // constant initializers for __constant__ and __device__ variables.
12843   if (getLangOpts().CUDA)
12844     checkAllowedCUDAInitializer(VD);
12845 
12846   // Grab the dllimport or dllexport attribute off of the VarDecl.
12847   const InheritableAttr *DLLAttr = getDLLAttr(VD);
12848 
12849   // Imported static data members cannot be defined out-of-line.
12850   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
12851     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
12852         VD->isThisDeclarationADefinition()) {
12853       // We allow definitions of dllimport class template static data members
12854       // with a warning.
12855       CXXRecordDecl *Context =
12856         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
12857       bool IsClassTemplateMember =
12858           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
12859           Context->getDescribedClassTemplate();
12860 
12861       Diag(VD->getLocation(),
12862            IsClassTemplateMember
12863                ? diag::warn_attribute_dllimport_static_field_definition
12864                : diag::err_attribute_dllimport_static_field_definition);
12865       Diag(IA->getLocation(), diag::note_attribute);
12866       if (!IsClassTemplateMember)
12867         VD->setInvalidDecl();
12868     }
12869   }
12870 
12871   // dllimport/dllexport variables cannot be thread local, their TLS index
12872   // isn't exported with the variable.
12873   if (DLLAttr && VD->getTLSKind()) {
12874     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12875     if (F && getDLLAttr(F)) {
12876       assert(VD->isStaticLocal());
12877       // But if this is a static local in a dlimport/dllexport function, the
12878       // function will never be inlined, which means the var would never be
12879       // imported, so having it marked import/export is safe.
12880     } else {
12881       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
12882                                                                     << DLLAttr;
12883       VD->setInvalidDecl();
12884     }
12885   }
12886 
12887   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
12888     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
12889       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
12890       VD->dropAttr<UsedAttr>();
12891     }
12892   }
12893 
12894   const DeclContext *DC = VD->getDeclContext();
12895   // If there's a #pragma GCC visibility in scope, and this isn't a class
12896   // member, set the visibility of this variable.
12897   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
12898     AddPushedVisibilityAttribute(VD);
12899 
12900   // FIXME: Warn on unused var template partial specializations.
12901   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
12902     MarkUnusedFileScopedDecl(VD);
12903 
12904   // Now we have parsed the initializer and can update the table of magic
12905   // tag values.
12906   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
12907       !VD->getType()->isIntegralOrEnumerationType())
12908     return;
12909 
12910   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
12911     const Expr *MagicValueExpr = VD->getInit();
12912     if (!MagicValueExpr) {
12913       continue;
12914     }
12915     llvm::APSInt MagicValueInt;
12916     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
12917       Diag(I->getRange().getBegin(),
12918            diag::err_type_tag_for_datatype_not_ice)
12919         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12920       continue;
12921     }
12922     if (MagicValueInt.getActiveBits() > 64) {
12923       Diag(I->getRange().getBegin(),
12924            diag::err_type_tag_for_datatype_too_large)
12925         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12926       continue;
12927     }
12928     uint64_t MagicValue = MagicValueInt.getZExtValue();
12929     RegisterTypeTagForDatatype(I->getArgumentKind(),
12930                                MagicValue,
12931                                I->getMatchingCType(),
12932                                I->getLayoutCompatible(),
12933                                I->getMustBeNull());
12934   }
12935 }
12936 
12937 static bool hasDeducedAuto(DeclaratorDecl *DD) {
12938   auto *VD = dyn_cast<VarDecl>(DD);
12939   return VD && !VD->getType()->hasAutoForTrailingReturnType();
12940 }
12941 
12942 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
12943                                                    ArrayRef<Decl *> Group) {
12944   SmallVector<Decl*, 8> Decls;
12945 
12946   if (DS.isTypeSpecOwned())
12947     Decls.push_back(DS.getRepAsDecl());
12948 
12949   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
12950   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
12951   bool DiagnosedMultipleDecomps = false;
12952   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
12953   bool DiagnosedNonDeducedAuto = false;
12954 
12955   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12956     if (Decl *D = Group[i]) {
12957       // For declarators, there are some additional syntactic-ish checks we need
12958       // to perform.
12959       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
12960         if (!FirstDeclaratorInGroup)
12961           FirstDeclaratorInGroup = DD;
12962         if (!FirstDecompDeclaratorInGroup)
12963           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
12964         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
12965             !hasDeducedAuto(DD))
12966           FirstNonDeducedAutoInGroup = DD;
12967 
12968         if (FirstDeclaratorInGroup != DD) {
12969           // A decomposition declaration cannot be combined with any other
12970           // declaration in the same group.
12971           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
12972             Diag(FirstDecompDeclaratorInGroup->getLocation(),
12973                  diag::err_decomp_decl_not_alone)
12974                 << FirstDeclaratorInGroup->getSourceRange()
12975                 << DD->getSourceRange();
12976             DiagnosedMultipleDecomps = true;
12977           }
12978 
12979           // A declarator that uses 'auto' in any way other than to declare a
12980           // variable with a deduced type cannot be combined with any other
12981           // declarator in the same group.
12982           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
12983             Diag(FirstNonDeducedAutoInGroup->getLocation(),
12984                  diag::err_auto_non_deduced_not_alone)
12985                 << FirstNonDeducedAutoInGroup->getType()
12986                        ->hasAutoForTrailingReturnType()
12987                 << FirstDeclaratorInGroup->getSourceRange()
12988                 << DD->getSourceRange();
12989             DiagnosedNonDeducedAuto = true;
12990           }
12991         }
12992       }
12993 
12994       Decls.push_back(D);
12995     }
12996   }
12997 
12998   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
12999     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13000       handleTagNumbering(Tag, S);
13001       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13002           getLangOpts().CPlusPlus)
13003         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13004     }
13005   }
13006 
13007   return BuildDeclaratorGroup(Decls);
13008 }
13009 
13010 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
13011 /// group, performing any necessary semantic checking.
13012 Sema::DeclGroupPtrTy
13013 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13014   // C++14 [dcl.spec.auto]p7: (DR1347)
13015   //   If the type that replaces the placeholder type is not the same in each
13016   //   deduction, the program is ill-formed.
13017   if (Group.size() > 1) {
13018     QualType Deduced;
13019     VarDecl *DeducedDecl = nullptr;
13020     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13021       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13022       if (!D || D->isInvalidDecl())
13023         break;
13024       DeducedType *DT = D->getType()->getContainedDeducedType();
13025       if (!DT || DT->getDeducedType().isNull())
13026         continue;
13027       if (Deduced.isNull()) {
13028         Deduced = DT->getDeducedType();
13029         DeducedDecl = D;
13030       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13031         auto *AT = dyn_cast<AutoType>(DT);
13032         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13033              diag::err_auto_different_deductions)
13034           << (AT ? (unsigned)AT->getKeyword() : 3)
13035           << Deduced << DeducedDecl->getDeclName()
13036           << DT->getDeducedType() << D->getDeclName()
13037           << DeducedDecl->getInit()->getSourceRange()
13038           << D->getInit()->getSourceRange();
13039         D->setInvalidDecl();
13040         break;
13041       }
13042     }
13043   }
13044 
13045   ActOnDocumentableDecls(Group);
13046 
13047   return DeclGroupPtrTy::make(
13048       DeclGroupRef::Create(Context, Group.data(), Group.size()));
13049 }
13050 
13051 void Sema::ActOnDocumentableDecl(Decl *D) {
13052   ActOnDocumentableDecls(D);
13053 }
13054 
13055 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13056   // Don't parse the comment if Doxygen diagnostics are ignored.
13057   if (Group.empty() || !Group[0])
13058     return;
13059 
13060   if (Diags.isIgnored(diag::warn_doc_param_not_found,
13061                       Group[0]->getLocation()) &&
13062       Diags.isIgnored(diag::warn_unknown_comment_command_name,
13063                       Group[0]->getLocation()))
13064     return;
13065 
13066   if (Group.size() >= 2) {
13067     // This is a decl group.  Normally it will contain only declarations
13068     // produced from declarator list.  But in case we have any definitions or
13069     // additional declaration references:
13070     //   'typedef struct S {} S;'
13071     //   'typedef struct S *S;'
13072     //   'struct S *pS;'
13073     // FinalizeDeclaratorGroup adds these as separate declarations.
13074     Decl *MaybeTagDecl = Group[0];
13075     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13076       Group = Group.slice(1);
13077     }
13078   }
13079 
13080   // FIMXE: We assume every Decl in the group is in the same file.
13081   // This is false when preprocessor constructs the group from decls in
13082   // different files (e. g. macros or #include).
13083   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13084 }
13085 
13086 /// Common checks for a parameter-declaration that should apply to both function
13087 /// parameters and non-type template parameters.
13088 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13089   // Check that there are no default arguments inside the type of this
13090   // parameter.
13091   if (getLangOpts().CPlusPlus)
13092     CheckExtraCXXDefaultArguments(D);
13093 
13094   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13095   if (D.getCXXScopeSpec().isSet()) {
13096     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13097       << D.getCXXScopeSpec().getRange();
13098   }
13099 
13100   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13101   // simple identifier except [...irrelevant cases...].
13102   switch (D.getName().getKind()) {
13103   case UnqualifiedIdKind::IK_Identifier:
13104     break;
13105 
13106   case UnqualifiedIdKind::IK_OperatorFunctionId:
13107   case UnqualifiedIdKind::IK_ConversionFunctionId:
13108   case UnqualifiedIdKind::IK_LiteralOperatorId:
13109   case UnqualifiedIdKind::IK_ConstructorName:
13110   case UnqualifiedIdKind::IK_DestructorName:
13111   case UnqualifiedIdKind::IK_ImplicitSelfParam:
13112   case UnqualifiedIdKind::IK_DeductionGuideName:
13113     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13114       << GetNameForDeclarator(D).getName();
13115     break;
13116 
13117   case UnqualifiedIdKind::IK_TemplateId:
13118   case UnqualifiedIdKind::IK_ConstructorTemplateId:
13119     // GetNameForDeclarator would not produce a useful name in this case.
13120     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13121     break;
13122   }
13123 }
13124 
13125 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13126 /// to introduce parameters into function prototype scope.
13127 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13128   const DeclSpec &DS = D.getDeclSpec();
13129 
13130   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13131 
13132   // C++03 [dcl.stc]p2 also permits 'auto'.
13133   StorageClass SC = SC_None;
13134   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13135     SC = SC_Register;
13136     // In C++11, the 'register' storage class specifier is deprecated.
13137     // In C++17, it is not allowed, but we tolerate it as an extension.
13138     if (getLangOpts().CPlusPlus11) {
13139       Diag(DS.getStorageClassSpecLoc(),
13140            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13141                                      : diag::warn_deprecated_register)
13142         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13143     }
13144   } else if (getLangOpts().CPlusPlus &&
13145              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13146     SC = SC_Auto;
13147   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13148     Diag(DS.getStorageClassSpecLoc(),
13149          diag::err_invalid_storage_class_in_func_decl);
13150     D.getMutableDeclSpec().ClearStorageClassSpecs();
13151   }
13152 
13153   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13154     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13155       << DeclSpec::getSpecifierName(TSCS);
13156   if (DS.isInlineSpecified())
13157     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13158         << getLangOpts().CPlusPlus17;
13159   if (DS.hasConstexprSpecifier())
13160     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13161         << 0 << D.getDeclSpec().getConstexprSpecifier();
13162 
13163   DiagnoseFunctionSpecifiers(DS);
13164 
13165   CheckFunctionOrTemplateParamDeclarator(S, D);
13166 
13167   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13168   QualType parmDeclType = TInfo->getType();
13169 
13170   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13171   IdentifierInfo *II = D.getIdentifier();
13172   if (II) {
13173     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13174                    ForVisibleRedeclaration);
13175     LookupName(R, S);
13176     if (R.isSingleResult()) {
13177       NamedDecl *PrevDecl = R.getFoundDecl();
13178       if (PrevDecl->isTemplateParameter()) {
13179         // Maybe we will complain about the shadowed template parameter.
13180         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13181         // Just pretend that we didn't see the previous declaration.
13182         PrevDecl = nullptr;
13183       } else if (S->isDeclScope(PrevDecl)) {
13184         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13185         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13186 
13187         // Recover by removing the name
13188         II = nullptr;
13189         D.SetIdentifier(nullptr, D.getIdentifierLoc());
13190         D.setInvalidType(true);
13191       }
13192     }
13193   }
13194 
13195   // Temporarily put parameter variables in the translation unit, not
13196   // the enclosing context.  This prevents them from accidentally
13197   // looking like class members in C++.
13198   ParmVarDecl *New =
13199       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13200                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13201 
13202   if (D.isInvalidType())
13203     New->setInvalidDecl();
13204 
13205   assert(S->isFunctionPrototypeScope());
13206   assert(S->getFunctionPrototypeDepth() >= 1);
13207   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13208                     S->getNextFunctionPrototypeIndex());
13209 
13210   // Add the parameter declaration into this scope.
13211   S->AddDecl(New);
13212   if (II)
13213     IdResolver.AddDecl(New);
13214 
13215   ProcessDeclAttributes(S, New, D);
13216 
13217   if (D.getDeclSpec().isModulePrivateSpecified())
13218     Diag(New->getLocation(), diag::err_module_private_local)
13219       << 1 << New->getDeclName()
13220       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13221       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13222 
13223   if (New->hasAttr<BlocksAttr>()) {
13224     Diag(New->getLocation(), diag::err_block_on_nonlocal);
13225   }
13226 
13227   if (getLangOpts().OpenCL)
13228     deduceOpenCLAddressSpace(New);
13229 
13230   return New;
13231 }
13232 
13233 /// Synthesizes a variable for a parameter arising from a
13234 /// typedef.
13235 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13236                                               SourceLocation Loc,
13237                                               QualType T) {
13238   /* FIXME: setting StartLoc == Loc.
13239      Would it be worth to modify callers so as to provide proper source
13240      location for the unnamed parameters, embedding the parameter's type? */
13241   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13242                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
13243                                            SC_None, nullptr);
13244   Param->setImplicit();
13245   return Param;
13246 }
13247 
13248 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13249   // Don't diagnose unused-parameter errors in template instantiations; we
13250   // will already have done so in the template itself.
13251   if (inTemplateInstantiation())
13252     return;
13253 
13254   for (const ParmVarDecl *Parameter : Parameters) {
13255     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13256         !Parameter->hasAttr<UnusedAttr>()) {
13257       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13258         << Parameter->getDeclName();
13259     }
13260   }
13261 }
13262 
13263 void Sema::DiagnoseSizeOfParametersAndReturnValue(
13264     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13265   if (LangOpts.NumLargeByValueCopy == 0) // No check.
13266     return;
13267 
13268   // Warn if the return value is pass-by-value and larger than the specified
13269   // threshold.
13270   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13271     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13272     if (Size > LangOpts.NumLargeByValueCopy)
13273       Diag(D->getLocation(), diag::warn_return_value_size)
13274           << D->getDeclName() << Size;
13275   }
13276 
13277   // Warn if any parameter is pass-by-value and larger than the specified
13278   // threshold.
13279   for (const ParmVarDecl *Parameter : Parameters) {
13280     QualType T = Parameter->getType();
13281     if (T->isDependentType() || !T.isPODType(Context))
13282       continue;
13283     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13284     if (Size > LangOpts.NumLargeByValueCopy)
13285       Diag(Parameter->getLocation(), diag::warn_parameter_size)
13286           << Parameter->getDeclName() << Size;
13287   }
13288 }
13289 
13290 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13291                                   SourceLocation NameLoc, IdentifierInfo *Name,
13292                                   QualType T, TypeSourceInfo *TSInfo,
13293                                   StorageClass SC) {
13294   // In ARC, infer a lifetime qualifier for appropriate parameter types.
13295   if (getLangOpts().ObjCAutoRefCount &&
13296       T.getObjCLifetime() == Qualifiers::OCL_None &&
13297       T->isObjCLifetimeType()) {
13298 
13299     Qualifiers::ObjCLifetime lifetime;
13300 
13301     // Special cases for arrays:
13302     //   - if it's const, use __unsafe_unretained
13303     //   - otherwise, it's an error
13304     if (T->isArrayType()) {
13305       if (!T.isConstQualified()) {
13306         if (DelayedDiagnostics.shouldDelayDiagnostics())
13307           DelayedDiagnostics.add(
13308               sema::DelayedDiagnostic::makeForbiddenType(
13309               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13310         else
13311           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13312               << TSInfo->getTypeLoc().getSourceRange();
13313       }
13314       lifetime = Qualifiers::OCL_ExplicitNone;
13315     } else {
13316       lifetime = T->getObjCARCImplicitLifetime();
13317     }
13318     T = Context.getLifetimeQualifiedType(T, lifetime);
13319   }
13320 
13321   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13322                                          Context.getAdjustedParameterType(T),
13323                                          TSInfo, SC, nullptr);
13324 
13325   // Make a note if we created a new pack in the scope of a lambda, so that
13326   // we know that references to that pack must also be expanded within the
13327   // lambda scope.
13328   if (New->isParameterPack())
13329     if (auto *LSI = getEnclosingLambda())
13330       LSI->LocalPacks.push_back(New);
13331 
13332   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13333       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13334     checkNonTrivialCUnion(New->getType(), New->getLocation(),
13335                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13336 
13337   // Parameters can not be abstract class types.
13338   // For record types, this is done by the AbstractClassUsageDiagnoser once
13339   // the class has been completely parsed.
13340   if (!CurContext->isRecord() &&
13341       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13342                              AbstractParamType))
13343     New->setInvalidDecl();
13344 
13345   // Parameter declarators cannot be interface types. All ObjC objects are
13346   // passed by reference.
13347   if (T->isObjCObjectType()) {
13348     SourceLocation TypeEndLoc =
13349         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13350     Diag(NameLoc,
13351          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13352       << FixItHint::CreateInsertion(TypeEndLoc, "*");
13353     T = Context.getObjCObjectPointerType(T);
13354     New->setType(T);
13355   }
13356 
13357   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13358   // duration shall not be qualified by an address-space qualifier."
13359   // Since all parameters have automatic store duration, they can not have
13360   // an address space.
13361   if (T.getAddressSpace() != LangAS::Default &&
13362       // OpenCL allows function arguments declared to be an array of a type
13363       // to be qualified with an address space.
13364       !(getLangOpts().OpenCL &&
13365         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13366     Diag(NameLoc, diag::err_arg_with_address_space);
13367     New->setInvalidDecl();
13368   }
13369 
13370   return New;
13371 }
13372 
13373 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
13374                                            SourceLocation LocAfterDecls) {
13375   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
13376 
13377   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
13378   // for a K&R function.
13379   if (!FTI.hasPrototype) {
13380     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
13381       --i;
13382       if (FTI.Params[i].Param == nullptr) {
13383         SmallString<256> Code;
13384         llvm::raw_svector_ostream(Code)
13385             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
13386         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
13387             << FTI.Params[i].Ident
13388             << FixItHint::CreateInsertion(LocAfterDecls, Code);
13389 
13390         // Implicitly declare the argument as type 'int' for lack of a better
13391         // type.
13392         AttributeFactory attrs;
13393         DeclSpec DS(attrs);
13394         const char* PrevSpec; // unused
13395         unsigned DiagID; // unused
13396         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
13397                            DiagID, Context.getPrintingPolicy());
13398         // Use the identifier location for the type source range.
13399         DS.SetRangeStart(FTI.Params[i].IdentLoc);
13400         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
13401         Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
13402         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
13403         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
13404       }
13405     }
13406   }
13407 }
13408 
13409 Decl *
13410 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
13411                               MultiTemplateParamsArg TemplateParameterLists,
13412                               SkipBodyInfo *SkipBody) {
13413   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
13414   assert(D.isFunctionDeclarator() && "Not a function declarator!");
13415   Scope *ParentScope = FnBodyScope->getParent();
13416 
13417   D.setFunctionDefinitionKind(FDK_Definition);
13418   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
13419   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
13420 }
13421 
13422 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
13423   Consumer.HandleInlineFunctionDefinition(D);
13424 }
13425 
13426 static bool
13427 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
13428                                 const FunctionDecl *&PossiblePrototype) {
13429   // Don't warn about invalid declarations.
13430   if (FD->isInvalidDecl())
13431     return false;
13432 
13433   // Or declarations that aren't global.
13434   if (!FD->isGlobal())
13435     return false;
13436 
13437   // Don't warn about C++ member functions.
13438   if (isa<CXXMethodDecl>(FD))
13439     return false;
13440 
13441   // Don't warn about 'main'.
13442   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
13443     if (IdentifierInfo *II = FD->getIdentifier())
13444       if (II->isStr("main"))
13445         return false;
13446 
13447   // Don't warn about inline functions.
13448   if (FD->isInlined())
13449     return false;
13450 
13451   // Don't warn about function templates.
13452   if (FD->getDescribedFunctionTemplate())
13453     return false;
13454 
13455   // Don't warn about function template specializations.
13456   if (FD->isFunctionTemplateSpecialization())
13457     return false;
13458 
13459   // Don't warn for OpenCL kernels.
13460   if (FD->hasAttr<OpenCLKernelAttr>())
13461     return false;
13462 
13463   // Don't warn on explicitly deleted functions.
13464   if (FD->isDeleted())
13465     return false;
13466 
13467   for (const FunctionDecl *Prev = FD->getPreviousDecl();
13468        Prev; Prev = Prev->getPreviousDecl()) {
13469     // Ignore any declarations that occur in function or method
13470     // scope, because they aren't visible from the header.
13471     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
13472       continue;
13473 
13474     PossiblePrototype = Prev;
13475     return Prev->getType()->isFunctionNoProtoType();
13476   }
13477 
13478   return true;
13479 }
13480 
13481 void
13482 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
13483                                    const FunctionDecl *EffectiveDefinition,
13484                                    SkipBodyInfo *SkipBody) {
13485   const FunctionDecl *Definition = EffectiveDefinition;
13486   if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
13487     // If this is a friend function defined in a class template, it does not
13488     // have a body until it is used, nevertheless it is a definition, see
13489     // [temp.inst]p2:
13490     //
13491     // ... for the purpose of determining whether an instantiated redeclaration
13492     // is valid according to [basic.def.odr] and [class.mem], a declaration that
13493     // corresponds to a definition in the template is considered to be a
13494     // definition.
13495     //
13496     // The following code must produce redefinition error:
13497     //
13498     //     template<typename T> struct C20 { friend void func_20() {} };
13499     //     C20<int> c20i;
13500     //     void func_20() {}
13501     //
13502     for (auto I : FD->redecls()) {
13503       if (I != FD && !I->isInvalidDecl() &&
13504           I->getFriendObjectKind() != Decl::FOK_None) {
13505         if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
13506           if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
13507             // A merged copy of the same function, instantiated as a member of
13508             // the same class, is OK.
13509             if (declaresSameEntity(OrigFD, Original) &&
13510                 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
13511                                    cast<Decl>(FD->getLexicalDeclContext())))
13512               continue;
13513           }
13514 
13515           if (Original->isThisDeclarationADefinition()) {
13516             Definition = I;
13517             break;
13518           }
13519         }
13520       }
13521     }
13522   }
13523 
13524   if (!Definition)
13525     // Similar to friend functions a friend function template may be a
13526     // definition and do not have a body if it is instantiated in a class
13527     // template.
13528     if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
13529       for (auto I : FTD->redecls()) {
13530         auto D = cast<FunctionTemplateDecl>(I);
13531         if (D != FTD) {
13532           assert(!D->isThisDeclarationADefinition() &&
13533                  "More than one definition in redeclaration chain");
13534           if (D->getFriendObjectKind() != Decl::FOK_None)
13535             if (FunctionTemplateDecl *FT =
13536                                        D->getInstantiatedFromMemberTemplate()) {
13537               if (FT->isThisDeclarationADefinition()) {
13538                 Definition = D->getTemplatedDecl();
13539                 break;
13540               }
13541             }
13542         }
13543       }
13544     }
13545 
13546   if (!Definition)
13547     return;
13548 
13549   if (canRedefineFunction(Definition, getLangOpts()))
13550     return;
13551 
13552   // Don't emit an error when this is redefinition of a typo-corrected
13553   // definition.
13554   if (TypoCorrectedFunctionDefinitions.count(Definition))
13555     return;
13556 
13557   // If we don't have a visible definition of the function, and it's inline or
13558   // a template, skip the new definition.
13559   if (SkipBody && !hasVisibleDefinition(Definition) &&
13560       (Definition->getFormalLinkage() == InternalLinkage ||
13561        Definition->isInlined() ||
13562        Definition->getDescribedFunctionTemplate() ||
13563        Definition->getNumTemplateParameterLists())) {
13564     SkipBody->ShouldSkip = true;
13565     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
13566     if (auto *TD = Definition->getDescribedFunctionTemplate())
13567       makeMergedDefinitionVisible(TD);
13568     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
13569     return;
13570   }
13571 
13572   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
13573       Definition->getStorageClass() == SC_Extern)
13574     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
13575         << FD->getDeclName() << getLangOpts().CPlusPlus;
13576   else
13577     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
13578 
13579   Diag(Definition->getLocation(), diag::note_previous_definition);
13580   FD->setInvalidDecl();
13581 }
13582 
13583 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
13584                                    Sema &S) {
13585   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
13586 
13587   LambdaScopeInfo *LSI = S.PushLambdaScope();
13588   LSI->CallOperator = CallOperator;
13589   LSI->Lambda = LambdaClass;
13590   LSI->ReturnType = CallOperator->getReturnType();
13591   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
13592 
13593   if (LCD == LCD_None)
13594     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
13595   else if (LCD == LCD_ByCopy)
13596     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
13597   else if (LCD == LCD_ByRef)
13598     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
13599   DeclarationNameInfo DNI = CallOperator->getNameInfo();
13600 
13601   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
13602   LSI->Mutable = !CallOperator->isConst();
13603 
13604   // Add the captures to the LSI so they can be noted as already
13605   // captured within tryCaptureVar.
13606   auto I = LambdaClass->field_begin();
13607   for (const auto &C : LambdaClass->captures()) {
13608     if (C.capturesVariable()) {
13609       VarDecl *VD = C.getCapturedVar();
13610       if (VD->isInitCapture())
13611         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
13612       QualType CaptureType = VD->getType();
13613       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
13614       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
13615           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
13616           /*EllipsisLoc*/C.isPackExpansion()
13617                          ? C.getEllipsisLoc() : SourceLocation(),
13618           CaptureType, /*Invalid*/false);
13619 
13620     } else if (C.capturesThis()) {
13621       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
13622                           C.getCaptureKind() == LCK_StarThis);
13623     } else {
13624       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
13625                              I->getType());
13626     }
13627     ++I;
13628   }
13629 }
13630 
13631 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
13632                                     SkipBodyInfo *SkipBody) {
13633   if (!D) {
13634     // Parsing the function declaration failed in some way. Push on a fake scope
13635     // anyway so we can try to parse the function body.
13636     PushFunctionScope();
13637     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13638     return D;
13639   }
13640 
13641   FunctionDecl *FD = nullptr;
13642 
13643   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
13644     FD = FunTmpl->getTemplatedDecl();
13645   else
13646     FD = cast<FunctionDecl>(D);
13647 
13648   // Do not push if it is a lambda because one is already pushed when building
13649   // the lambda in ActOnStartOfLambdaDefinition().
13650   if (!isLambdaCallOperator(FD))
13651     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13652 
13653   // Check for defining attributes before the check for redefinition.
13654   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
13655     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
13656     FD->dropAttr<AliasAttr>();
13657     FD->setInvalidDecl();
13658   }
13659   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
13660     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
13661     FD->dropAttr<IFuncAttr>();
13662     FD->setInvalidDecl();
13663   }
13664 
13665   // See if this is a redefinition. If 'will have body' is already set, then
13666   // these checks were already performed when it was set.
13667   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
13668     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
13669 
13670     // If we're skipping the body, we're done. Don't enter the scope.
13671     if (SkipBody && SkipBody->ShouldSkip)
13672       return D;
13673   }
13674 
13675   // Mark this function as "will have a body eventually".  This lets users to
13676   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
13677   // this function.
13678   FD->setWillHaveBody();
13679 
13680   // If we are instantiating a generic lambda call operator, push
13681   // a LambdaScopeInfo onto the function stack.  But use the information
13682   // that's already been calculated (ActOnLambdaExpr) to prime the current
13683   // LambdaScopeInfo.
13684   // When the template operator is being specialized, the LambdaScopeInfo,
13685   // has to be properly restored so that tryCaptureVariable doesn't try
13686   // and capture any new variables. In addition when calculating potential
13687   // captures during transformation of nested lambdas, it is necessary to
13688   // have the LSI properly restored.
13689   if (isGenericLambdaCallOperatorSpecialization(FD)) {
13690     assert(inTemplateInstantiation() &&
13691            "There should be an active template instantiation on the stack "
13692            "when instantiating a generic lambda!");
13693     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
13694   } else {
13695     // Enter a new function scope
13696     PushFunctionScope();
13697   }
13698 
13699   // Builtin functions cannot be defined.
13700   if (unsigned BuiltinID = FD->getBuiltinID()) {
13701     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
13702         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
13703       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
13704       FD->setInvalidDecl();
13705     }
13706   }
13707 
13708   // The return type of a function definition must be complete
13709   // (C99 6.9.1p3, C++ [dcl.fct]p6).
13710   QualType ResultType = FD->getReturnType();
13711   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
13712       !FD->isInvalidDecl() &&
13713       RequireCompleteType(FD->getLocation(), ResultType,
13714                           diag::err_func_def_incomplete_result))
13715     FD->setInvalidDecl();
13716 
13717   if (FnBodyScope)
13718     PushDeclContext(FnBodyScope, FD);
13719 
13720   // Check the validity of our function parameters
13721   CheckParmsForFunctionDef(FD->parameters(),
13722                            /*CheckParameterNames=*/true);
13723 
13724   // Add non-parameter declarations already in the function to the current
13725   // scope.
13726   if (FnBodyScope) {
13727     for (Decl *NPD : FD->decls()) {
13728       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
13729       if (!NonParmDecl)
13730         continue;
13731       assert(!isa<ParmVarDecl>(NonParmDecl) &&
13732              "parameters should not be in newly created FD yet");
13733 
13734       // If the decl has a name, make it accessible in the current scope.
13735       if (NonParmDecl->getDeclName())
13736         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
13737 
13738       // Similarly, dive into enums and fish their constants out, making them
13739       // accessible in this scope.
13740       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
13741         for (auto *EI : ED->enumerators())
13742           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
13743       }
13744     }
13745   }
13746 
13747   // Introduce our parameters into the function scope
13748   for (auto Param : FD->parameters()) {
13749     Param->setOwningFunction(FD);
13750 
13751     // If this has an identifier, add it to the scope stack.
13752     if (Param->getIdentifier() && FnBodyScope) {
13753       CheckShadow(FnBodyScope, Param);
13754 
13755       PushOnScopeChains(Param, FnBodyScope);
13756     }
13757   }
13758 
13759   // Ensure that the function's exception specification is instantiated.
13760   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
13761     ResolveExceptionSpec(D->getLocation(), FPT);
13762 
13763   // dllimport cannot be applied to non-inline function definitions.
13764   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
13765       !FD->isTemplateInstantiation()) {
13766     assert(!FD->hasAttr<DLLExportAttr>());
13767     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
13768     FD->setInvalidDecl();
13769     return D;
13770   }
13771   // We want to attach documentation to original Decl (which might be
13772   // a function template).
13773   ActOnDocumentableDecl(D);
13774   if (getCurLexicalContext()->isObjCContainer() &&
13775       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
13776       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
13777     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
13778 
13779   return D;
13780 }
13781 
13782 /// Given the set of return statements within a function body,
13783 /// compute the variables that are subject to the named return value
13784 /// optimization.
13785 ///
13786 /// Each of the variables that is subject to the named return value
13787 /// optimization will be marked as NRVO variables in the AST, and any
13788 /// return statement that has a marked NRVO variable as its NRVO candidate can
13789 /// use the named return value optimization.
13790 ///
13791 /// This function applies a very simplistic algorithm for NRVO: if every return
13792 /// statement in the scope of a variable has the same NRVO candidate, that
13793 /// candidate is an NRVO variable.
13794 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
13795   ReturnStmt **Returns = Scope->Returns.data();
13796 
13797   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
13798     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
13799       if (!NRVOCandidate->isNRVOVariable())
13800         Returns[I]->setNRVOCandidate(nullptr);
13801     }
13802   }
13803 }
13804 
13805 bool Sema::canDelayFunctionBody(const Declarator &D) {
13806   // We can't delay parsing the body of a constexpr function template (yet).
13807   if (D.getDeclSpec().hasConstexprSpecifier())
13808     return false;
13809 
13810   // We can't delay parsing the body of a function template with a deduced
13811   // return type (yet).
13812   if (D.getDeclSpec().hasAutoTypeSpec()) {
13813     // If the placeholder introduces a non-deduced trailing return type,
13814     // we can still delay parsing it.
13815     if (D.getNumTypeObjects()) {
13816       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
13817       if (Outer.Kind == DeclaratorChunk::Function &&
13818           Outer.Fun.hasTrailingReturnType()) {
13819         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
13820         return Ty.isNull() || !Ty->isUndeducedType();
13821       }
13822     }
13823     return false;
13824   }
13825 
13826   return true;
13827 }
13828 
13829 bool Sema::canSkipFunctionBody(Decl *D) {
13830   // We cannot skip the body of a function (or function template) which is
13831   // constexpr, since we may need to evaluate its body in order to parse the
13832   // rest of the file.
13833   // We cannot skip the body of a function with an undeduced return type,
13834   // because any callers of that function need to know the type.
13835   if (const FunctionDecl *FD = D->getAsFunction()) {
13836     if (FD->isConstexpr())
13837       return false;
13838     // We can't simply call Type::isUndeducedType here, because inside template
13839     // auto can be deduced to a dependent type, which is not considered
13840     // "undeduced".
13841     if (FD->getReturnType()->getContainedDeducedType())
13842       return false;
13843   }
13844   return Consumer.shouldSkipFunctionBody(D);
13845 }
13846 
13847 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
13848   if (!Decl)
13849     return nullptr;
13850   if (FunctionDecl *FD = Decl->getAsFunction())
13851     FD->setHasSkippedBody();
13852   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
13853     MD->setHasSkippedBody();
13854   return Decl;
13855 }
13856 
13857 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
13858   return ActOnFinishFunctionBody(D, BodyArg, false);
13859 }
13860 
13861 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
13862 /// body.
13863 class ExitFunctionBodyRAII {
13864 public:
13865   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
13866   ~ExitFunctionBodyRAII() {
13867     if (!IsLambda)
13868       S.PopExpressionEvaluationContext();
13869   }
13870 
13871 private:
13872   Sema &S;
13873   bool IsLambda = false;
13874 };
13875 
13876 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
13877   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
13878 
13879   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
13880     if (EscapeInfo.count(BD))
13881       return EscapeInfo[BD];
13882 
13883     bool R = false;
13884     const BlockDecl *CurBD = BD;
13885 
13886     do {
13887       R = !CurBD->doesNotEscape();
13888       if (R)
13889         break;
13890       CurBD = CurBD->getParent()->getInnermostBlockDecl();
13891     } while (CurBD);
13892 
13893     return EscapeInfo[BD] = R;
13894   };
13895 
13896   // If the location where 'self' is implicitly retained is inside a escaping
13897   // block, emit a diagnostic.
13898   for (const std::pair<SourceLocation, const BlockDecl *> &P :
13899        S.ImplicitlyRetainedSelfLocs)
13900     if (IsOrNestedInEscapingBlock(P.second))
13901       S.Diag(P.first, diag::warn_implicitly_retains_self)
13902           << FixItHint::CreateInsertion(P.first, "self->");
13903 }
13904 
13905 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
13906                                     bool IsInstantiation) {
13907   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
13908 
13909   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13910   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
13911 
13912   if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
13913     CheckCompletedCoroutineBody(FD, Body);
13914 
13915   // Do not call PopExpressionEvaluationContext() if it is a lambda because one
13916   // is already popped when finishing the lambda in BuildLambdaExpr(). This is
13917   // meant to pop the context added in ActOnStartOfFunctionDef().
13918   ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
13919 
13920   if (FD) {
13921     FD->setBody(Body);
13922     FD->setWillHaveBody(false);
13923 
13924     if (getLangOpts().CPlusPlus14) {
13925       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
13926           FD->getReturnType()->isUndeducedType()) {
13927         // If the function has a deduced result type but contains no 'return'
13928         // statements, the result type as written must be exactly 'auto', and
13929         // the deduced result type is 'void'.
13930         if (!FD->getReturnType()->getAs<AutoType>()) {
13931           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
13932               << FD->getReturnType();
13933           FD->setInvalidDecl();
13934         } else {
13935           // Substitute 'void' for the 'auto' in the type.
13936           TypeLoc ResultType = getReturnTypeLoc(FD);
13937           Context.adjustDeducedFunctionResultType(
13938               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
13939         }
13940       }
13941     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
13942       // In C++11, we don't use 'auto' deduction rules for lambda call
13943       // operators because we don't support return type deduction.
13944       auto *LSI = getCurLambda();
13945       if (LSI->HasImplicitReturnType) {
13946         deduceClosureReturnType(*LSI);
13947 
13948         // C++11 [expr.prim.lambda]p4:
13949         //   [...] if there are no return statements in the compound-statement
13950         //   [the deduced type is] the type void
13951         QualType RetType =
13952             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
13953 
13954         // Update the return type to the deduced type.
13955         const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
13956         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
13957                                             Proto->getExtProtoInfo()));
13958       }
13959     }
13960 
13961     // If the function implicitly returns zero (like 'main') or is naked,
13962     // don't complain about missing return statements.
13963     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
13964       WP.disableCheckFallThrough();
13965 
13966     // MSVC permits the use of pure specifier (=0) on function definition,
13967     // defined at class scope, warn about this non-standard construct.
13968     if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
13969       Diag(FD->getLocation(), diag::ext_pure_function_definition);
13970 
13971     if (!FD->isInvalidDecl()) {
13972       // Don't diagnose unused parameters of defaulted or deleted functions.
13973       if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
13974         DiagnoseUnusedParameters(FD->parameters());
13975       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
13976                                              FD->getReturnType(), FD);
13977 
13978       // If this is a structor, we need a vtable.
13979       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
13980         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
13981       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
13982         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
13983 
13984       // Try to apply the named return value optimization. We have to check
13985       // if we can do this here because lambdas keep return statements around
13986       // to deduce an implicit return type.
13987       if (FD->getReturnType()->isRecordType() &&
13988           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
13989         computeNRVO(Body, getCurFunction());
13990     }
13991 
13992     // GNU warning -Wmissing-prototypes:
13993     //   Warn if a global function is defined without a previous
13994     //   prototype declaration. This warning is issued even if the
13995     //   definition itself provides a prototype. The aim is to detect
13996     //   global functions that fail to be declared in header files.
13997     const FunctionDecl *PossiblePrototype = nullptr;
13998     if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
13999       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14000 
14001       if (PossiblePrototype) {
14002         // We found a declaration that is not a prototype,
14003         // but that could be a zero-parameter prototype
14004         if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14005           TypeLoc TL = TI->getTypeLoc();
14006           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14007             Diag(PossiblePrototype->getLocation(),
14008                  diag::note_declaration_not_a_prototype)
14009                 << (FD->getNumParams() != 0)
14010                 << (FD->getNumParams() == 0
14011                         ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
14012                         : FixItHint{});
14013         }
14014       } else {
14015         Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14016             << /* function */ 1
14017             << (FD->getStorageClass() == SC_None
14018                     ? FixItHint::CreateInsertion(FD->getTypeSpecStartLoc(),
14019                                                  "static ")
14020                     : FixItHint{});
14021       }
14022 
14023       // GNU warning -Wstrict-prototypes
14024       //   Warn if K&R function is defined without a previous declaration.
14025       //   This warning is issued only if the definition itself does not provide
14026       //   a prototype. Only K&R definitions do not provide a prototype.
14027       //   An empty list in a function declarator that is part of a definition
14028       //   of that function specifies that the function has no parameters
14029       //   (C99 6.7.5.3p14)
14030       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
14031           !LangOpts.CPlusPlus) {
14032         TypeSourceInfo *TI = FD->getTypeSourceInfo();
14033         TypeLoc TL = TI->getTypeLoc();
14034         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
14035         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14036       }
14037     }
14038 
14039     // Warn on CPUDispatch with an actual body.
14040     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14041       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14042         if (!CmpndBody->body_empty())
14043           Diag(CmpndBody->body_front()->getBeginLoc(),
14044                diag::warn_dispatch_body_ignored);
14045 
14046     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14047       const CXXMethodDecl *KeyFunction;
14048       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14049           MD->isVirtual() &&
14050           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14051           MD == KeyFunction->getCanonicalDecl()) {
14052         // Update the key-function state if necessary for this ABI.
14053         if (FD->isInlined() &&
14054             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14055           Context.setNonKeyFunction(MD);
14056 
14057           // If the newly-chosen key function is already defined, then we
14058           // need to mark the vtable as used retroactively.
14059           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14060           const FunctionDecl *Definition;
14061           if (KeyFunction && KeyFunction->isDefined(Definition))
14062             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14063         } else {
14064           // We just defined they key function; mark the vtable as used.
14065           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14066         }
14067       }
14068     }
14069 
14070     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
14071            "Function parsing confused");
14072   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14073     assert(MD == getCurMethodDecl() && "Method parsing confused");
14074     MD->setBody(Body);
14075     if (!MD->isInvalidDecl()) {
14076       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14077                                              MD->getReturnType(), MD);
14078 
14079       if (Body)
14080         computeNRVO(Body, getCurFunction());
14081     }
14082     if (getCurFunction()->ObjCShouldCallSuper) {
14083       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14084           << MD->getSelector().getAsString();
14085       getCurFunction()->ObjCShouldCallSuper = false;
14086     }
14087     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
14088       const ObjCMethodDecl *InitMethod = nullptr;
14089       bool isDesignated =
14090           MD->isDesignatedInitializerForTheInterface(&InitMethod);
14091       assert(isDesignated && InitMethod);
14092       (void)isDesignated;
14093 
14094       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14095         auto IFace = MD->getClassInterface();
14096         if (!IFace)
14097           return false;
14098         auto SuperD = IFace->getSuperClass();
14099         if (!SuperD)
14100           return false;
14101         return SuperD->getIdentifier() ==
14102             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14103       };
14104       // Don't issue this warning for unavailable inits or direct subclasses
14105       // of NSObject.
14106       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14107         Diag(MD->getLocation(),
14108              diag::warn_objc_designated_init_missing_super_call);
14109         Diag(InitMethod->getLocation(),
14110              diag::note_objc_designated_init_marked_here);
14111       }
14112       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
14113     }
14114     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
14115       // Don't issue this warning for unavaialable inits.
14116       if (!MD->isUnavailable())
14117         Diag(MD->getLocation(),
14118              diag::warn_objc_secondary_init_missing_init_call);
14119       getCurFunction()->ObjCWarnForNoInitDelegation = false;
14120     }
14121 
14122     diagnoseImplicitlyRetainedSelf(*this);
14123   } else {
14124     // Parsing the function declaration failed in some way. Pop the fake scope
14125     // we pushed on.
14126     PopFunctionScopeInfo(ActivePolicy, dcl);
14127     return nullptr;
14128   }
14129 
14130   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
14131     DiagnoseUnguardedAvailabilityViolations(dcl);
14132 
14133   assert(!getCurFunction()->ObjCShouldCallSuper &&
14134          "This should only be set for ObjC methods, which should have been "
14135          "handled in the block above.");
14136 
14137   // Verify and clean out per-function state.
14138   if (Body && (!FD || !FD->isDefaulted())) {
14139     // C++ constructors that have function-try-blocks can't have return
14140     // statements in the handlers of that block. (C++ [except.handle]p14)
14141     // Verify this.
14142     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14143       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14144 
14145     // Verify that gotos and switch cases don't jump into scopes illegally.
14146     if (getCurFunction()->NeedsScopeChecking() &&
14147         !PP.isCodeCompletionEnabled())
14148       DiagnoseInvalidJumps(Body);
14149 
14150     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14151       if (!Destructor->getParent()->isDependentType())
14152         CheckDestructor(Destructor);
14153 
14154       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14155                                              Destructor->getParent());
14156     }
14157 
14158     // If any errors have occurred, clear out any temporaries that may have
14159     // been leftover. This ensures that these temporaries won't be picked up for
14160     // deletion in some later function.
14161     if (getDiagnostics().hasErrorOccurred() ||
14162         getDiagnostics().getSuppressAllDiagnostics()) {
14163       DiscardCleanupsInEvaluationContext();
14164     }
14165     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
14166         !isa<FunctionTemplateDecl>(dcl)) {
14167       // Since the body is valid, issue any analysis-based warnings that are
14168       // enabled.
14169       ActivePolicy = &WP;
14170     }
14171 
14172     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14173         !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14174       FD->setInvalidDecl();
14175 
14176     if (FD && FD->hasAttr<NakedAttr>()) {
14177       for (const Stmt *S : Body->children()) {
14178         // Allow local register variables without initializer as they don't
14179         // require prologue.
14180         bool RegisterVariables = false;
14181         if (auto *DS = dyn_cast<DeclStmt>(S)) {
14182           for (const auto *Decl : DS->decls()) {
14183             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14184               RegisterVariables =
14185                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14186               if (!RegisterVariables)
14187                 break;
14188             }
14189           }
14190         }
14191         if (RegisterVariables)
14192           continue;
14193         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14194           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14195           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14196           FD->setInvalidDecl();
14197           break;
14198         }
14199       }
14200     }
14201 
14202     assert(ExprCleanupObjects.size() ==
14203                ExprEvalContexts.back().NumCleanupObjects &&
14204            "Leftover temporaries in function");
14205     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
14206     assert(MaybeODRUseExprs.empty() &&
14207            "Leftover expressions for odr-use checking");
14208   }
14209 
14210   if (!IsInstantiation)
14211     PopDeclContext();
14212 
14213   PopFunctionScopeInfo(ActivePolicy, dcl);
14214   // If any errors have occurred, clear out any temporaries that may have
14215   // been leftover. This ensures that these temporaries won't be picked up for
14216   // deletion in some later function.
14217   if (getDiagnostics().hasErrorOccurred()) {
14218     DiscardCleanupsInEvaluationContext();
14219   }
14220 
14221   return dcl;
14222 }
14223 
14224 /// When we finish delayed parsing of an attribute, we must attach it to the
14225 /// relevant Decl.
14226 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14227                                        ParsedAttributes &Attrs) {
14228   // Always attach attributes to the underlying decl.
14229   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14230     D = TD->getTemplatedDecl();
14231   ProcessDeclAttributeList(S, D, Attrs);
14232 
14233   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14234     if (Method->isStatic())
14235       checkThisInStaticMemberFunctionAttributes(Method);
14236 }
14237 
14238 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14239 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
14240 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14241                                           IdentifierInfo &II, Scope *S) {
14242   // Find the scope in which the identifier is injected and the corresponding
14243   // DeclContext.
14244   // FIXME: C89 does not say what happens if there is no enclosing block scope.
14245   // In that case, we inject the declaration into the translation unit scope
14246   // instead.
14247   Scope *BlockScope = S;
14248   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14249     BlockScope = BlockScope->getParent();
14250 
14251   Scope *ContextScope = BlockScope;
14252   while (!ContextScope->getEntity())
14253     ContextScope = ContextScope->getParent();
14254   ContextRAII SavedContext(*this, ContextScope->getEntity());
14255 
14256   // Before we produce a declaration for an implicitly defined
14257   // function, see whether there was a locally-scoped declaration of
14258   // this name as a function or variable. If so, use that
14259   // (non-visible) declaration, and complain about it.
14260   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14261   if (ExternCPrev) {
14262     // We still need to inject the function into the enclosing block scope so
14263     // that later (non-call) uses can see it.
14264     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14265 
14266     // C89 footnote 38:
14267     //   If in fact it is not defined as having type "function returning int",
14268     //   the behavior is undefined.
14269     if (!isa<FunctionDecl>(ExternCPrev) ||
14270         !Context.typesAreCompatible(
14271             cast<FunctionDecl>(ExternCPrev)->getType(),
14272             Context.getFunctionNoProtoType(Context.IntTy))) {
14273       Diag(Loc, diag::ext_use_out_of_scope_declaration)
14274           << ExternCPrev << !getLangOpts().C99;
14275       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14276       return ExternCPrev;
14277     }
14278   }
14279 
14280   // Extension in C99.  Legal in C90, but warn about it.
14281   unsigned diag_id;
14282   if (II.getName().startswith("__builtin_"))
14283     diag_id = diag::warn_builtin_unknown;
14284   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14285   else if (getLangOpts().OpenCL)
14286     diag_id = diag::err_opencl_implicit_function_decl;
14287   else if (getLangOpts().C99)
14288     diag_id = diag::ext_implicit_function_decl;
14289   else
14290     diag_id = diag::warn_implicit_function_decl;
14291   Diag(Loc, diag_id) << &II;
14292 
14293   // If we found a prior declaration of this function, don't bother building
14294   // another one. We've already pushed that one into scope, so there's nothing
14295   // more to do.
14296   if (ExternCPrev)
14297     return ExternCPrev;
14298 
14299   // Because typo correction is expensive, only do it if the implicit
14300   // function declaration is going to be treated as an error.
14301   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
14302     TypoCorrection Corrected;
14303     DeclFilterCCC<FunctionDecl> CCC{};
14304     if (S && (Corrected =
14305                   CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
14306                               S, nullptr, CCC, CTK_NonError)))
14307       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
14308                    /*ErrorRecovery*/false);
14309   }
14310 
14311   // Set a Declarator for the implicit definition: int foo();
14312   const char *Dummy;
14313   AttributeFactory attrFactory;
14314   DeclSpec DS(attrFactory);
14315   unsigned DiagID;
14316   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
14317                                   Context.getPrintingPolicy());
14318   (void)Error; // Silence warning.
14319   assert(!Error && "Error setting up implicit decl!");
14320   SourceLocation NoLoc;
14321   Declarator D(DS, DeclaratorContext::BlockContext);
14322   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
14323                                              /*IsAmbiguous=*/false,
14324                                              /*LParenLoc=*/NoLoc,
14325                                              /*Params=*/nullptr,
14326                                              /*NumParams=*/0,
14327                                              /*EllipsisLoc=*/NoLoc,
14328                                              /*RParenLoc=*/NoLoc,
14329                                              /*RefQualifierIsLvalueRef=*/true,
14330                                              /*RefQualifierLoc=*/NoLoc,
14331                                              /*MutableLoc=*/NoLoc, EST_None,
14332                                              /*ESpecRange=*/SourceRange(),
14333                                              /*Exceptions=*/nullptr,
14334                                              /*ExceptionRanges=*/nullptr,
14335                                              /*NumExceptions=*/0,
14336                                              /*NoexceptExpr=*/nullptr,
14337                                              /*ExceptionSpecTokens=*/nullptr,
14338                                              /*DeclsInPrototype=*/None, Loc,
14339                                              Loc, D),
14340                 std::move(DS.getAttributes()), SourceLocation());
14341   D.SetIdentifier(&II, Loc);
14342 
14343   // Insert this function into the enclosing block scope.
14344   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
14345   FD->setImplicit();
14346 
14347   AddKnownFunctionAttributes(FD);
14348 
14349   return FD;
14350 }
14351 
14352 /// Adds any function attributes that we know a priori based on
14353 /// the declaration of this function.
14354 ///
14355 /// These attributes can apply both to implicitly-declared builtins
14356 /// (like __builtin___printf_chk) or to library-declared functions
14357 /// like NSLog or printf.
14358 ///
14359 /// We need to check for duplicate attributes both here and where user-written
14360 /// attributes are applied to declarations.
14361 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
14362   if (FD->isInvalidDecl())
14363     return;
14364 
14365   // If this is a built-in function, map its builtin attributes to
14366   // actual attributes.
14367   if (unsigned BuiltinID = FD->getBuiltinID()) {
14368     // Handle printf-formatting attributes.
14369     unsigned FormatIdx;
14370     bool HasVAListArg;
14371     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
14372       if (!FD->hasAttr<FormatAttr>()) {
14373         const char *fmt = "printf";
14374         unsigned int NumParams = FD->getNumParams();
14375         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
14376             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
14377           fmt = "NSString";
14378         FD->addAttr(FormatAttr::CreateImplicit(Context,
14379                                                &Context.Idents.get(fmt),
14380                                                FormatIdx+1,
14381                                                HasVAListArg ? 0 : FormatIdx+2,
14382                                                FD->getLocation()));
14383       }
14384     }
14385     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
14386                                              HasVAListArg)) {
14387      if (!FD->hasAttr<FormatAttr>())
14388        FD->addAttr(FormatAttr::CreateImplicit(Context,
14389                                               &Context.Idents.get("scanf"),
14390                                               FormatIdx+1,
14391                                               HasVAListArg ? 0 : FormatIdx+2,
14392                                               FD->getLocation()));
14393     }
14394 
14395     // Handle automatically recognized callbacks.
14396     SmallVector<int, 4> Encoding;
14397     if (!FD->hasAttr<CallbackAttr>() &&
14398         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
14399       FD->addAttr(CallbackAttr::CreateImplicit(
14400           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
14401 
14402     // Mark const if we don't care about errno and that is the only thing
14403     // preventing the function from being const. This allows IRgen to use LLVM
14404     // intrinsics for such functions.
14405     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
14406         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
14407       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14408 
14409     // We make "fma" on some platforms const because we know it does not set
14410     // errno in those environments even though it could set errno based on the
14411     // C standard.
14412     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
14413     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
14414         !FD->hasAttr<ConstAttr>()) {
14415       switch (BuiltinID) {
14416       case Builtin::BI__builtin_fma:
14417       case Builtin::BI__builtin_fmaf:
14418       case Builtin::BI__builtin_fmal:
14419       case Builtin::BIfma:
14420       case Builtin::BIfmaf:
14421       case Builtin::BIfmal:
14422         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14423         break;
14424       default:
14425         break;
14426       }
14427     }
14428 
14429     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
14430         !FD->hasAttr<ReturnsTwiceAttr>())
14431       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
14432                                          FD->getLocation()));
14433     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
14434       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14435     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
14436       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
14437     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
14438       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14439     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
14440         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
14441       // Add the appropriate attribute, depending on the CUDA compilation mode
14442       // and which target the builtin belongs to. For example, during host
14443       // compilation, aux builtins are __device__, while the rest are __host__.
14444       if (getLangOpts().CUDAIsDevice !=
14445           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
14446         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
14447       else
14448         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
14449     }
14450   }
14451 
14452   // If C++ exceptions are enabled but we are told extern "C" functions cannot
14453   // throw, add an implicit nothrow attribute to any extern "C" function we come
14454   // across.
14455   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
14456       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
14457     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
14458     if (!FPT || FPT->getExceptionSpecType() == EST_None)
14459       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14460   }
14461 
14462   IdentifierInfo *Name = FD->getIdentifier();
14463   if (!Name)
14464     return;
14465   if ((!getLangOpts().CPlusPlus &&
14466        FD->getDeclContext()->isTranslationUnit()) ||
14467       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
14468        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
14469        LinkageSpecDecl::lang_c)) {
14470     // Okay: this could be a libc/libm/Objective-C function we know
14471     // about.
14472   } else
14473     return;
14474 
14475   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
14476     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
14477     // target-specific builtins, perhaps?
14478     if (!FD->hasAttr<FormatAttr>())
14479       FD->addAttr(FormatAttr::CreateImplicit(Context,
14480                                              &Context.Idents.get("printf"), 2,
14481                                              Name->isStr("vasprintf") ? 0 : 3,
14482                                              FD->getLocation()));
14483   }
14484 
14485   if (Name->isStr("__CFStringMakeConstantString")) {
14486     // We already have a __builtin___CFStringMakeConstantString,
14487     // but builds that use -fno-constant-cfstrings don't go through that.
14488     if (!FD->hasAttr<FormatArgAttr>())
14489       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
14490                                                 FD->getLocation()));
14491   }
14492 }
14493 
14494 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
14495                                     TypeSourceInfo *TInfo) {
14496   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
14497   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
14498 
14499   if (!TInfo) {
14500     assert(D.isInvalidType() && "no declarator info for valid type");
14501     TInfo = Context.getTrivialTypeSourceInfo(T);
14502   }
14503 
14504   // Scope manipulation handled by caller.
14505   TypedefDecl *NewTD =
14506       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
14507                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
14508 
14509   // Bail out immediately if we have an invalid declaration.
14510   if (D.isInvalidType()) {
14511     NewTD->setInvalidDecl();
14512     return NewTD;
14513   }
14514 
14515   if (D.getDeclSpec().isModulePrivateSpecified()) {
14516     if (CurContext->isFunctionOrMethod())
14517       Diag(NewTD->getLocation(), diag::err_module_private_local)
14518         << 2 << NewTD->getDeclName()
14519         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14520         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
14521     else
14522       NewTD->setModulePrivate();
14523   }
14524 
14525   // C++ [dcl.typedef]p8:
14526   //   If the typedef declaration defines an unnamed class (or
14527   //   enum), the first typedef-name declared by the declaration
14528   //   to be that class type (or enum type) is used to denote the
14529   //   class type (or enum type) for linkage purposes only.
14530   // We need to check whether the type was declared in the declaration.
14531   switch (D.getDeclSpec().getTypeSpecType()) {
14532   case TST_enum:
14533   case TST_struct:
14534   case TST_interface:
14535   case TST_union:
14536   case TST_class: {
14537     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
14538     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
14539     break;
14540   }
14541 
14542   default:
14543     break;
14544   }
14545 
14546   return NewTD;
14547 }
14548 
14549 /// Check that this is a valid underlying type for an enum declaration.
14550 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
14551   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
14552   QualType T = TI->getType();
14553 
14554   if (T->isDependentType())
14555     return false;
14556 
14557   if (const BuiltinType *BT = T->getAs<BuiltinType>())
14558     if (BT->isInteger())
14559       return false;
14560 
14561   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
14562   return true;
14563 }
14564 
14565 /// Check whether this is a valid redeclaration of a previous enumeration.
14566 /// \return true if the redeclaration was invalid.
14567 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
14568                                   QualType EnumUnderlyingTy, bool IsFixed,
14569                                   const EnumDecl *Prev) {
14570   if (IsScoped != Prev->isScoped()) {
14571     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
14572       << Prev->isScoped();
14573     Diag(Prev->getLocation(), diag::note_previous_declaration);
14574     return true;
14575   }
14576 
14577   if (IsFixed && Prev->isFixed()) {
14578     if (!EnumUnderlyingTy->isDependentType() &&
14579         !Prev->getIntegerType()->isDependentType() &&
14580         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
14581                                         Prev->getIntegerType())) {
14582       // TODO: Highlight the underlying type of the redeclaration.
14583       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
14584         << EnumUnderlyingTy << Prev->getIntegerType();
14585       Diag(Prev->getLocation(), diag::note_previous_declaration)
14586           << Prev->getIntegerTypeRange();
14587       return true;
14588     }
14589   } else if (IsFixed != Prev->isFixed()) {
14590     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
14591       << Prev->isFixed();
14592     Diag(Prev->getLocation(), diag::note_previous_declaration);
14593     return true;
14594   }
14595 
14596   return false;
14597 }
14598 
14599 /// Get diagnostic %select index for tag kind for
14600 /// redeclaration diagnostic message.
14601 /// WARNING: Indexes apply to particular diagnostics only!
14602 ///
14603 /// \returns diagnostic %select index.
14604 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
14605   switch (Tag) {
14606   case TTK_Struct: return 0;
14607   case TTK_Interface: return 1;
14608   case TTK_Class:  return 2;
14609   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
14610   }
14611 }
14612 
14613 /// Determine if tag kind is a class-key compatible with
14614 /// class for redeclaration (class, struct, or __interface).
14615 ///
14616 /// \returns true iff the tag kind is compatible.
14617 static bool isClassCompatTagKind(TagTypeKind Tag)
14618 {
14619   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
14620 }
14621 
14622 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
14623                                              TagTypeKind TTK) {
14624   if (isa<TypedefDecl>(PrevDecl))
14625     return NTK_Typedef;
14626   else if (isa<TypeAliasDecl>(PrevDecl))
14627     return NTK_TypeAlias;
14628   else if (isa<ClassTemplateDecl>(PrevDecl))
14629     return NTK_Template;
14630   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
14631     return NTK_TypeAliasTemplate;
14632   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
14633     return NTK_TemplateTemplateArgument;
14634   switch (TTK) {
14635   case TTK_Struct:
14636   case TTK_Interface:
14637   case TTK_Class:
14638     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
14639   case TTK_Union:
14640     return NTK_NonUnion;
14641   case TTK_Enum:
14642     return NTK_NonEnum;
14643   }
14644   llvm_unreachable("invalid TTK");
14645 }
14646 
14647 /// Determine whether a tag with a given kind is acceptable
14648 /// as a redeclaration of the given tag declaration.
14649 ///
14650 /// \returns true if the new tag kind is acceptable, false otherwise.
14651 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
14652                                         TagTypeKind NewTag, bool isDefinition,
14653                                         SourceLocation NewTagLoc,
14654                                         const IdentifierInfo *Name) {
14655   // C++ [dcl.type.elab]p3:
14656   //   The class-key or enum keyword present in the
14657   //   elaborated-type-specifier shall agree in kind with the
14658   //   declaration to which the name in the elaborated-type-specifier
14659   //   refers. This rule also applies to the form of
14660   //   elaborated-type-specifier that declares a class-name or
14661   //   friend class since it can be construed as referring to the
14662   //   definition of the class. Thus, in any
14663   //   elaborated-type-specifier, the enum keyword shall be used to
14664   //   refer to an enumeration (7.2), the union class-key shall be
14665   //   used to refer to a union (clause 9), and either the class or
14666   //   struct class-key shall be used to refer to a class (clause 9)
14667   //   declared using the class or struct class-key.
14668   TagTypeKind OldTag = Previous->getTagKind();
14669   if (OldTag != NewTag &&
14670       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
14671     return false;
14672 
14673   // Tags are compatible, but we might still want to warn on mismatched tags.
14674   // Non-class tags can't be mismatched at this point.
14675   if (!isClassCompatTagKind(NewTag))
14676     return true;
14677 
14678   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
14679   // by our warning analysis. We don't want to warn about mismatches with (eg)
14680   // declarations in system headers that are designed to be specialized, but if
14681   // a user asks us to warn, we should warn if their code contains mismatched
14682   // declarations.
14683   auto IsIgnoredLoc = [&](SourceLocation Loc) {
14684     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
14685                                       Loc);
14686   };
14687   if (IsIgnoredLoc(NewTagLoc))
14688     return true;
14689 
14690   auto IsIgnored = [&](const TagDecl *Tag) {
14691     return IsIgnoredLoc(Tag->getLocation());
14692   };
14693   while (IsIgnored(Previous)) {
14694     Previous = Previous->getPreviousDecl();
14695     if (!Previous)
14696       return true;
14697     OldTag = Previous->getTagKind();
14698   }
14699 
14700   bool isTemplate = false;
14701   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
14702     isTemplate = Record->getDescribedClassTemplate();
14703 
14704   if (inTemplateInstantiation()) {
14705     if (OldTag != NewTag) {
14706       // In a template instantiation, do not offer fix-its for tag mismatches
14707       // since they usually mess up the template instead of fixing the problem.
14708       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14709         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14710         << getRedeclDiagFromTagKind(OldTag);
14711       // FIXME: Note previous location?
14712     }
14713     return true;
14714   }
14715 
14716   if (isDefinition) {
14717     // On definitions, check all previous tags and issue a fix-it for each
14718     // one that doesn't match the current tag.
14719     if (Previous->getDefinition()) {
14720       // Don't suggest fix-its for redefinitions.
14721       return true;
14722     }
14723 
14724     bool previousMismatch = false;
14725     for (const TagDecl *I : Previous->redecls()) {
14726       if (I->getTagKind() != NewTag) {
14727         // Ignore previous declarations for which the warning was disabled.
14728         if (IsIgnored(I))
14729           continue;
14730 
14731         if (!previousMismatch) {
14732           previousMismatch = true;
14733           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
14734             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14735             << getRedeclDiagFromTagKind(I->getTagKind());
14736         }
14737         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
14738           << getRedeclDiagFromTagKind(NewTag)
14739           << FixItHint::CreateReplacement(I->getInnerLocStart(),
14740                TypeWithKeyword::getTagTypeKindName(NewTag));
14741       }
14742     }
14743     return true;
14744   }
14745 
14746   // Identify the prevailing tag kind: this is the kind of the definition (if
14747   // there is a non-ignored definition), or otherwise the kind of the prior
14748   // (non-ignored) declaration.
14749   const TagDecl *PrevDef = Previous->getDefinition();
14750   if (PrevDef && IsIgnored(PrevDef))
14751     PrevDef = nullptr;
14752   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
14753   if (Redecl->getTagKind() != NewTag) {
14754     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14755       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14756       << getRedeclDiagFromTagKind(OldTag);
14757     Diag(Redecl->getLocation(), diag::note_previous_use);
14758 
14759     // If there is a previous definition, suggest a fix-it.
14760     if (PrevDef) {
14761       Diag(NewTagLoc, diag::note_struct_class_suggestion)
14762         << getRedeclDiagFromTagKind(Redecl->getTagKind())
14763         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
14764              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
14765     }
14766   }
14767 
14768   return true;
14769 }
14770 
14771 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
14772 /// from an outer enclosing namespace or file scope inside a friend declaration.
14773 /// This should provide the commented out code in the following snippet:
14774 ///   namespace N {
14775 ///     struct X;
14776 ///     namespace M {
14777 ///       struct Y { friend struct /*N::*/ X; };
14778 ///     }
14779 ///   }
14780 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
14781                                          SourceLocation NameLoc) {
14782   // While the decl is in a namespace, do repeated lookup of that name and see
14783   // if we get the same namespace back.  If we do not, continue until
14784   // translation unit scope, at which point we have a fully qualified NNS.
14785   SmallVector<IdentifierInfo *, 4> Namespaces;
14786   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14787   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
14788     // This tag should be declared in a namespace, which can only be enclosed by
14789     // other namespaces.  Bail if there's an anonymous namespace in the chain.
14790     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
14791     if (!Namespace || Namespace->isAnonymousNamespace())
14792       return FixItHint();
14793     IdentifierInfo *II = Namespace->getIdentifier();
14794     Namespaces.push_back(II);
14795     NamedDecl *Lookup = SemaRef.LookupSingleName(
14796         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
14797     if (Lookup == Namespace)
14798       break;
14799   }
14800 
14801   // Once we have all the namespaces, reverse them to go outermost first, and
14802   // build an NNS.
14803   SmallString<64> Insertion;
14804   llvm::raw_svector_ostream OS(Insertion);
14805   if (DC->isTranslationUnit())
14806     OS << "::";
14807   std::reverse(Namespaces.begin(), Namespaces.end());
14808   for (auto *II : Namespaces)
14809     OS << II->getName() << "::";
14810   return FixItHint::CreateInsertion(NameLoc, Insertion);
14811 }
14812 
14813 /// Determine whether a tag originally declared in context \p OldDC can
14814 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
14815 /// found a declaration in \p OldDC as a previous decl, perhaps through a
14816 /// using-declaration).
14817 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
14818                                          DeclContext *NewDC) {
14819   OldDC = OldDC->getRedeclContext();
14820   NewDC = NewDC->getRedeclContext();
14821 
14822   if (OldDC->Equals(NewDC))
14823     return true;
14824 
14825   // In MSVC mode, we allow a redeclaration if the contexts are related (either
14826   // encloses the other).
14827   if (S.getLangOpts().MSVCCompat &&
14828       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
14829     return true;
14830 
14831   return false;
14832 }
14833 
14834 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
14835 /// former case, Name will be non-null.  In the later case, Name will be null.
14836 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
14837 /// reference/declaration/definition of a tag.
14838 ///
14839 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
14840 /// trailing-type-specifier) other than one in an alias-declaration.
14841 ///
14842 /// \param SkipBody If non-null, will be set to indicate if the caller should
14843 /// skip the definition of this tag and treat it as if it were a declaration.
14844 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
14845                      SourceLocation KWLoc, CXXScopeSpec &SS,
14846                      IdentifierInfo *Name, SourceLocation NameLoc,
14847                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
14848                      SourceLocation ModulePrivateLoc,
14849                      MultiTemplateParamsArg TemplateParameterLists,
14850                      bool &OwnedDecl, bool &IsDependent,
14851                      SourceLocation ScopedEnumKWLoc,
14852                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
14853                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
14854                      SkipBodyInfo *SkipBody) {
14855   // If this is not a definition, it must have a name.
14856   IdentifierInfo *OrigName = Name;
14857   assert((Name != nullptr || TUK == TUK_Definition) &&
14858          "Nameless record must be a definition!");
14859   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
14860 
14861   OwnedDecl = false;
14862   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14863   bool ScopedEnum = ScopedEnumKWLoc.isValid();
14864 
14865   // FIXME: Check member specializations more carefully.
14866   bool isMemberSpecialization = false;
14867   bool Invalid = false;
14868 
14869   // We only need to do this matching if we have template parameters
14870   // or a scope specifier, which also conveniently avoids this work
14871   // for non-C++ cases.
14872   if (TemplateParameterLists.size() > 0 ||
14873       (SS.isNotEmpty() && TUK != TUK_Reference)) {
14874     if (TemplateParameterList *TemplateParams =
14875             MatchTemplateParametersToScopeSpecifier(
14876                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
14877                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
14878       if (Kind == TTK_Enum) {
14879         Diag(KWLoc, diag::err_enum_template);
14880         return nullptr;
14881       }
14882 
14883       if (TemplateParams->size() > 0) {
14884         // This is a declaration or definition of a class template (which may
14885         // be a member of another template).
14886 
14887         if (Invalid)
14888           return nullptr;
14889 
14890         OwnedDecl = false;
14891         DeclResult Result = CheckClassTemplate(
14892             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
14893             AS, ModulePrivateLoc,
14894             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
14895             TemplateParameterLists.data(), SkipBody);
14896         return Result.get();
14897       } else {
14898         // The "template<>" header is extraneous.
14899         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14900           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14901         isMemberSpecialization = true;
14902       }
14903     }
14904   }
14905 
14906   // Figure out the underlying type if this a enum declaration. We need to do
14907   // this early, because it's needed to detect if this is an incompatible
14908   // redeclaration.
14909   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
14910   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
14911 
14912   if (Kind == TTK_Enum) {
14913     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
14914       // No underlying type explicitly specified, or we failed to parse the
14915       // type, default to int.
14916       EnumUnderlying = Context.IntTy.getTypePtr();
14917     } else if (UnderlyingType.get()) {
14918       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
14919       // integral type; any cv-qualification is ignored.
14920       TypeSourceInfo *TI = nullptr;
14921       GetTypeFromParser(UnderlyingType.get(), &TI);
14922       EnumUnderlying = TI;
14923 
14924       if (CheckEnumUnderlyingType(TI))
14925         // Recover by falling back to int.
14926         EnumUnderlying = Context.IntTy.getTypePtr();
14927 
14928       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
14929                                           UPPC_FixedUnderlyingType))
14930         EnumUnderlying = Context.IntTy.getTypePtr();
14931 
14932     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
14933       // For MSVC ABI compatibility, unfixed enums must use an underlying type
14934       // of 'int'. However, if this is an unfixed forward declaration, don't set
14935       // the underlying type unless the user enables -fms-compatibility. This
14936       // makes unfixed forward declared enums incomplete and is more conforming.
14937       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
14938         EnumUnderlying = Context.IntTy.getTypePtr();
14939     }
14940   }
14941 
14942   DeclContext *SearchDC = CurContext;
14943   DeclContext *DC = CurContext;
14944   bool isStdBadAlloc = false;
14945   bool isStdAlignValT = false;
14946 
14947   RedeclarationKind Redecl = forRedeclarationInCurContext();
14948   if (TUK == TUK_Friend || TUK == TUK_Reference)
14949     Redecl = NotForRedeclaration;
14950 
14951   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
14952   /// implemented asks for structural equivalence checking, the returned decl
14953   /// here is passed back to the parser, allowing the tag body to be parsed.
14954   auto createTagFromNewDecl = [&]() -> TagDecl * {
14955     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
14956     // If there is an identifier, use the location of the identifier as the
14957     // location of the decl, otherwise use the location of the struct/union
14958     // keyword.
14959     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14960     TagDecl *New = nullptr;
14961 
14962     if (Kind == TTK_Enum) {
14963       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
14964                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
14965       // If this is an undefined enum, bail.
14966       if (TUK != TUK_Definition && !Invalid)
14967         return nullptr;
14968       if (EnumUnderlying) {
14969         EnumDecl *ED = cast<EnumDecl>(New);
14970         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
14971           ED->setIntegerTypeSourceInfo(TI);
14972         else
14973           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
14974         ED->setPromotionType(ED->getIntegerType());
14975       }
14976     } else { // struct/union
14977       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14978                                nullptr);
14979     }
14980 
14981     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14982       // Add alignment attributes if necessary; these attributes are checked
14983       // when the ASTContext lays out the structure.
14984       //
14985       // It is important for implementing the correct semantics that this
14986       // happen here (in ActOnTag). The #pragma pack stack is
14987       // maintained as a result of parser callbacks which can occur at
14988       // many points during the parsing of a struct declaration (because
14989       // the #pragma tokens are effectively skipped over during the
14990       // parsing of the struct).
14991       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
14992         AddAlignmentAttributesForRecord(RD);
14993         AddMsStructLayoutForRecord(RD);
14994       }
14995     }
14996     New->setLexicalDeclContext(CurContext);
14997     return New;
14998   };
14999 
15000   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
15001   if (Name && SS.isNotEmpty()) {
15002     // We have a nested-name tag ('struct foo::bar').
15003 
15004     // Check for invalid 'foo::'.
15005     if (SS.isInvalid()) {
15006       Name = nullptr;
15007       goto CreateNewDecl;
15008     }
15009 
15010     // If this is a friend or a reference to a class in a dependent
15011     // context, don't try to make a decl for it.
15012     if (TUK == TUK_Friend || TUK == TUK_Reference) {
15013       DC = computeDeclContext(SS, false);
15014       if (!DC) {
15015         IsDependent = true;
15016         return nullptr;
15017       }
15018     } else {
15019       DC = computeDeclContext(SS, true);
15020       if (!DC) {
15021         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
15022           << SS.getRange();
15023         return nullptr;
15024       }
15025     }
15026 
15027     if (RequireCompleteDeclContext(SS, DC))
15028       return nullptr;
15029 
15030     SearchDC = DC;
15031     // Look-up name inside 'foo::'.
15032     LookupQualifiedName(Previous, DC);
15033 
15034     if (Previous.isAmbiguous())
15035       return nullptr;
15036 
15037     if (Previous.empty()) {
15038       // Name lookup did not find anything. However, if the
15039       // nested-name-specifier refers to the current instantiation,
15040       // and that current instantiation has any dependent base
15041       // classes, we might find something at instantiation time: treat
15042       // this as a dependent elaborated-type-specifier.
15043       // But this only makes any sense for reference-like lookups.
15044       if (Previous.wasNotFoundInCurrentInstantiation() &&
15045           (TUK == TUK_Reference || TUK == TUK_Friend)) {
15046         IsDependent = true;
15047         return nullptr;
15048       }
15049 
15050       // A tag 'foo::bar' must already exist.
15051       Diag(NameLoc, diag::err_not_tag_in_scope)
15052         << Kind << Name << DC << SS.getRange();
15053       Name = nullptr;
15054       Invalid = true;
15055       goto CreateNewDecl;
15056     }
15057   } else if (Name) {
15058     // C++14 [class.mem]p14:
15059     //   If T is the name of a class, then each of the following shall have a
15060     //   name different from T:
15061     //    -- every member of class T that is itself a type
15062     if (TUK != TUK_Reference && TUK != TUK_Friend &&
15063         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15064       return nullptr;
15065 
15066     // If this is a named struct, check to see if there was a previous forward
15067     // declaration or definition.
15068     // FIXME: We're looking into outer scopes here, even when we
15069     // shouldn't be. Doing so can result in ambiguities that we
15070     // shouldn't be diagnosing.
15071     LookupName(Previous, S);
15072 
15073     // When declaring or defining a tag, ignore ambiguities introduced
15074     // by types using'ed into this scope.
15075     if (Previous.isAmbiguous() &&
15076         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
15077       LookupResult::Filter F = Previous.makeFilter();
15078       while (F.hasNext()) {
15079         NamedDecl *ND = F.next();
15080         if (!ND->getDeclContext()->getRedeclContext()->Equals(
15081                 SearchDC->getRedeclContext()))
15082           F.erase();
15083       }
15084       F.done();
15085     }
15086 
15087     // C++11 [namespace.memdef]p3:
15088     //   If the name in a friend declaration is neither qualified nor
15089     //   a template-id and the declaration is a function or an
15090     //   elaborated-type-specifier, the lookup to determine whether
15091     //   the entity has been previously declared shall not consider
15092     //   any scopes outside the innermost enclosing namespace.
15093     //
15094     // MSVC doesn't implement the above rule for types, so a friend tag
15095     // declaration may be a redeclaration of a type declared in an enclosing
15096     // scope.  They do implement this rule for friend functions.
15097     //
15098     // Does it matter that this should be by scope instead of by
15099     // semantic context?
15100     if (!Previous.empty() && TUK == TUK_Friend) {
15101       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
15102       LookupResult::Filter F = Previous.makeFilter();
15103       bool FriendSawTagOutsideEnclosingNamespace = false;
15104       while (F.hasNext()) {
15105         NamedDecl *ND = F.next();
15106         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15107         if (DC->isFileContext() &&
15108             !EnclosingNS->Encloses(ND->getDeclContext())) {
15109           if (getLangOpts().MSVCCompat)
15110             FriendSawTagOutsideEnclosingNamespace = true;
15111           else
15112             F.erase();
15113         }
15114       }
15115       F.done();
15116 
15117       // Diagnose this MSVC extension in the easy case where lookup would have
15118       // unambiguously found something outside the enclosing namespace.
15119       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
15120         NamedDecl *ND = Previous.getFoundDecl();
15121         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
15122             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
15123       }
15124     }
15125 
15126     // Note:  there used to be some attempt at recovery here.
15127     if (Previous.isAmbiguous())
15128       return nullptr;
15129 
15130     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
15131       // FIXME: This makes sure that we ignore the contexts associated
15132       // with C structs, unions, and enums when looking for a matching
15133       // tag declaration or definition. See the similar lookup tweak
15134       // in Sema::LookupName; is there a better way to deal with this?
15135       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
15136         SearchDC = SearchDC->getParent();
15137     }
15138   }
15139 
15140   if (Previous.isSingleResult() &&
15141       Previous.getFoundDecl()->isTemplateParameter()) {
15142     // Maybe we will complain about the shadowed template parameter.
15143     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
15144     // Just pretend that we didn't see the previous declaration.
15145     Previous.clear();
15146   }
15147 
15148   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
15149       DC->Equals(getStdNamespace())) {
15150     if (Name->isStr("bad_alloc")) {
15151       // This is a declaration of or a reference to "std::bad_alloc".
15152       isStdBadAlloc = true;
15153 
15154       // If std::bad_alloc has been implicitly declared (but made invisible to
15155       // name lookup), fill in this implicit declaration as the previous
15156       // declaration, so that the declarations get chained appropriately.
15157       if (Previous.empty() && StdBadAlloc)
15158         Previous.addDecl(getStdBadAlloc());
15159     } else if (Name->isStr("align_val_t")) {
15160       isStdAlignValT = true;
15161       if (Previous.empty() && StdAlignValT)
15162         Previous.addDecl(getStdAlignValT());
15163     }
15164   }
15165 
15166   // If we didn't find a previous declaration, and this is a reference
15167   // (or friend reference), move to the correct scope.  In C++, we
15168   // also need to do a redeclaration lookup there, just in case
15169   // there's a shadow friend decl.
15170   if (Name && Previous.empty() &&
15171       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
15172     if (Invalid) goto CreateNewDecl;
15173     assert(SS.isEmpty());
15174 
15175     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
15176       // C++ [basic.scope.pdecl]p5:
15177       //   -- for an elaborated-type-specifier of the form
15178       //
15179       //          class-key identifier
15180       //
15181       //      if the elaborated-type-specifier is used in the
15182       //      decl-specifier-seq or parameter-declaration-clause of a
15183       //      function defined in namespace scope, the identifier is
15184       //      declared as a class-name in the namespace that contains
15185       //      the declaration; otherwise, except as a friend
15186       //      declaration, the identifier is declared in the smallest
15187       //      non-class, non-function-prototype scope that contains the
15188       //      declaration.
15189       //
15190       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
15191       // C structs and unions.
15192       //
15193       // It is an error in C++ to declare (rather than define) an enum
15194       // type, including via an elaborated type specifier.  We'll
15195       // diagnose that later; for now, declare the enum in the same
15196       // scope as we would have picked for any other tag type.
15197       //
15198       // GNU C also supports this behavior as part of its incomplete
15199       // enum types extension, while GNU C++ does not.
15200       //
15201       // Find the context where we'll be declaring the tag.
15202       // FIXME: We would like to maintain the current DeclContext as the
15203       // lexical context,
15204       SearchDC = getTagInjectionContext(SearchDC);
15205 
15206       // Find the scope where we'll be declaring the tag.
15207       S = getTagInjectionScope(S, getLangOpts());
15208     } else {
15209       assert(TUK == TUK_Friend);
15210       // C++ [namespace.memdef]p3:
15211       //   If a friend declaration in a non-local class first declares a
15212       //   class or function, the friend class or function is a member of
15213       //   the innermost enclosing namespace.
15214       SearchDC = SearchDC->getEnclosingNamespaceContext();
15215     }
15216 
15217     // In C++, we need to do a redeclaration lookup to properly
15218     // diagnose some problems.
15219     // FIXME: redeclaration lookup is also used (with and without C++) to find a
15220     // hidden declaration so that we don't get ambiguity errors when using a
15221     // type declared by an elaborated-type-specifier.  In C that is not correct
15222     // and we should instead merge compatible types found by lookup.
15223     if (getLangOpts().CPlusPlus) {
15224       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15225       LookupQualifiedName(Previous, SearchDC);
15226     } else {
15227       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15228       LookupName(Previous, S);
15229     }
15230   }
15231 
15232   // If we have a known previous declaration to use, then use it.
15233   if (Previous.empty() && SkipBody && SkipBody->Previous)
15234     Previous.addDecl(SkipBody->Previous);
15235 
15236   if (!Previous.empty()) {
15237     NamedDecl *PrevDecl = Previous.getFoundDecl();
15238     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
15239 
15240     // It's okay to have a tag decl in the same scope as a typedef
15241     // which hides a tag decl in the same scope.  Finding this
15242     // insanity with a redeclaration lookup can only actually happen
15243     // in C++.
15244     //
15245     // This is also okay for elaborated-type-specifiers, which is
15246     // technically forbidden by the current standard but which is
15247     // okay according to the likely resolution of an open issue;
15248     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
15249     if (getLangOpts().CPlusPlus) {
15250       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15251         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
15252           TagDecl *Tag = TT->getDecl();
15253           if (Tag->getDeclName() == Name &&
15254               Tag->getDeclContext()->getRedeclContext()
15255                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
15256             PrevDecl = Tag;
15257             Previous.clear();
15258             Previous.addDecl(Tag);
15259             Previous.resolveKind();
15260           }
15261         }
15262       }
15263     }
15264 
15265     // If this is a redeclaration of a using shadow declaration, it must
15266     // declare a tag in the same context. In MSVC mode, we allow a
15267     // redefinition if either context is within the other.
15268     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
15269       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
15270       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
15271           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
15272           !(OldTag && isAcceptableTagRedeclContext(
15273                           *this, OldTag->getDeclContext(), SearchDC))) {
15274         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
15275         Diag(Shadow->getTargetDecl()->getLocation(),
15276              diag::note_using_decl_target);
15277         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
15278             << 0;
15279         // Recover by ignoring the old declaration.
15280         Previous.clear();
15281         goto CreateNewDecl;
15282       }
15283     }
15284 
15285     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
15286       // If this is a use of a previous tag, or if the tag is already declared
15287       // in the same scope (so that the definition/declaration completes or
15288       // rementions the tag), reuse the decl.
15289       if (TUK == TUK_Reference || TUK == TUK_Friend ||
15290           isDeclInScope(DirectPrevDecl, SearchDC, S,
15291                         SS.isNotEmpty() || isMemberSpecialization)) {
15292         // Make sure that this wasn't declared as an enum and now used as a
15293         // struct or something similar.
15294         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
15295                                           TUK == TUK_Definition, KWLoc,
15296                                           Name)) {
15297           bool SafeToContinue
15298             = (PrevTagDecl->getTagKind() != TTK_Enum &&
15299                Kind != TTK_Enum);
15300           if (SafeToContinue)
15301             Diag(KWLoc, diag::err_use_with_wrong_tag)
15302               << Name
15303               << FixItHint::CreateReplacement(SourceRange(KWLoc),
15304                                               PrevTagDecl->getKindName());
15305           else
15306             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
15307           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
15308 
15309           if (SafeToContinue)
15310             Kind = PrevTagDecl->getTagKind();
15311           else {
15312             // Recover by making this an anonymous redefinition.
15313             Name = nullptr;
15314             Previous.clear();
15315             Invalid = true;
15316           }
15317         }
15318 
15319         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
15320           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
15321 
15322           // If this is an elaborated-type-specifier for a scoped enumeration,
15323           // the 'class' keyword is not necessary and not permitted.
15324           if (TUK == TUK_Reference || TUK == TUK_Friend) {
15325             if (ScopedEnum)
15326               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
15327                 << PrevEnum->isScoped()
15328                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
15329             return PrevTagDecl;
15330           }
15331 
15332           QualType EnumUnderlyingTy;
15333           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15334             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
15335           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
15336             EnumUnderlyingTy = QualType(T, 0);
15337 
15338           // All conflicts with previous declarations are recovered by
15339           // returning the previous declaration, unless this is a definition,
15340           // in which case we want the caller to bail out.
15341           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
15342                                      ScopedEnum, EnumUnderlyingTy,
15343                                      IsFixed, PrevEnum))
15344             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
15345         }
15346 
15347         // C++11 [class.mem]p1:
15348         //   A member shall not be declared twice in the member-specification,
15349         //   except that a nested class or member class template can be declared
15350         //   and then later defined.
15351         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
15352             S->isDeclScope(PrevDecl)) {
15353           Diag(NameLoc, diag::ext_member_redeclared);
15354           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
15355         }
15356 
15357         if (!Invalid) {
15358           // If this is a use, just return the declaration we found, unless
15359           // we have attributes.
15360           if (TUK == TUK_Reference || TUK == TUK_Friend) {
15361             if (!Attrs.empty()) {
15362               // FIXME: Diagnose these attributes. For now, we create a new
15363               // declaration to hold them.
15364             } else if (TUK == TUK_Reference &&
15365                        (PrevTagDecl->getFriendObjectKind() ==
15366                             Decl::FOK_Undeclared ||
15367                         PrevDecl->getOwningModule() != getCurrentModule()) &&
15368                        SS.isEmpty()) {
15369               // This declaration is a reference to an existing entity, but
15370               // has different visibility from that entity: it either makes
15371               // a friend visible or it makes a type visible in a new module.
15372               // In either case, create a new declaration. We only do this if
15373               // the declaration would have meant the same thing if no prior
15374               // declaration were found, that is, if it was found in the same
15375               // scope where we would have injected a declaration.
15376               if (!getTagInjectionContext(CurContext)->getRedeclContext()
15377                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
15378                 return PrevTagDecl;
15379               // This is in the injected scope, create a new declaration in
15380               // that scope.
15381               S = getTagInjectionScope(S, getLangOpts());
15382             } else {
15383               return PrevTagDecl;
15384             }
15385           }
15386 
15387           // Diagnose attempts to redefine a tag.
15388           if (TUK == TUK_Definition) {
15389             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
15390               // If we're defining a specialization and the previous definition
15391               // is from an implicit instantiation, don't emit an error
15392               // here; we'll catch this in the general case below.
15393               bool IsExplicitSpecializationAfterInstantiation = false;
15394               if (isMemberSpecialization) {
15395                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
15396                   IsExplicitSpecializationAfterInstantiation =
15397                     RD->getTemplateSpecializationKind() !=
15398                     TSK_ExplicitSpecialization;
15399                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
15400                   IsExplicitSpecializationAfterInstantiation =
15401                     ED->getTemplateSpecializationKind() !=
15402                     TSK_ExplicitSpecialization;
15403               }
15404 
15405               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
15406               // not keep more that one definition around (merge them). However,
15407               // ensure the decl passes the structural compatibility check in
15408               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
15409               NamedDecl *Hidden = nullptr;
15410               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
15411                 // There is a definition of this tag, but it is not visible. We
15412                 // explicitly make use of C++'s one definition rule here, and
15413                 // assume that this definition is identical to the hidden one
15414                 // we already have. Make the existing definition visible and
15415                 // use it in place of this one.
15416                 if (!getLangOpts().CPlusPlus) {
15417                   // Postpone making the old definition visible until after we
15418                   // complete parsing the new one and do the structural
15419                   // comparison.
15420                   SkipBody->CheckSameAsPrevious = true;
15421                   SkipBody->New = createTagFromNewDecl();
15422                   SkipBody->Previous = Def;
15423                   return Def;
15424                 } else {
15425                   SkipBody->ShouldSkip = true;
15426                   SkipBody->Previous = Def;
15427                   makeMergedDefinitionVisible(Hidden);
15428                   // Carry on and handle it like a normal definition. We'll
15429                   // skip starting the definitiion later.
15430                 }
15431               } else if (!IsExplicitSpecializationAfterInstantiation) {
15432                 // A redeclaration in function prototype scope in C isn't
15433                 // visible elsewhere, so merely issue a warning.
15434                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
15435                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
15436                 else
15437                   Diag(NameLoc, diag::err_redefinition) << Name;
15438                 notePreviousDefinition(Def,
15439                                        NameLoc.isValid() ? NameLoc : KWLoc);
15440                 // If this is a redefinition, recover by making this
15441                 // struct be anonymous, which will make any later
15442                 // references get the previous definition.
15443                 Name = nullptr;
15444                 Previous.clear();
15445                 Invalid = true;
15446               }
15447             } else {
15448               // If the type is currently being defined, complain
15449               // about a nested redefinition.
15450               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
15451               if (TD->isBeingDefined()) {
15452                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
15453                 Diag(PrevTagDecl->getLocation(),
15454                      diag::note_previous_definition);
15455                 Name = nullptr;
15456                 Previous.clear();
15457                 Invalid = true;
15458               }
15459             }
15460 
15461             // Okay, this is definition of a previously declared or referenced
15462             // tag. We're going to create a new Decl for it.
15463           }
15464 
15465           // Okay, we're going to make a redeclaration.  If this is some kind
15466           // of reference, make sure we build the redeclaration in the same DC
15467           // as the original, and ignore the current access specifier.
15468           if (TUK == TUK_Friend || TUK == TUK_Reference) {
15469             SearchDC = PrevTagDecl->getDeclContext();
15470             AS = AS_none;
15471           }
15472         }
15473         // If we get here we have (another) forward declaration or we
15474         // have a definition.  Just create a new decl.
15475 
15476       } else {
15477         // If we get here, this is a definition of a new tag type in a nested
15478         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
15479         // new decl/type.  We set PrevDecl to NULL so that the entities
15480         // have distinct types.
15481         Previous.clear();
15482       }
15483       // If we get here, we're going to create a new Decl. If PrevDecl
15484       // is non-NULL, it's a definition of the tag declared by
15485       // PrevDecl. If it's NULL, we have a new definition.
15486 
15487     // Otherwise, PrevDecl is not a tag, but was found with tag
15488     // lookup.  This is only actually possible in C++, where a few
15489     // things like templates still live in the tag namespace.
15490     } else {
15491       // Use a better diagnostic if an elaborated-type-specifier
15492       // found the wrong kind of type on the first
15493       // (non-redeclaration) lookup.
15494       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
15495           !Previous.isForRedeclaration()) {
15496         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15497         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
15498                                                        << Kind;
15499         Diag(PrevDecl->getLocation(), diag::note_declared_at);
15500         Invalid = true;
15501 
15502       // Otherwise, only diagnose if the declaration is in scope.
15503       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
15504                                 SS.isNotEmpty() || isMemberSpecialization)) {
15505         // do nothing
15506 
15507       // Diagnose implicit declarations introduced by elaborated types.
15508       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
15509         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15510         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
15511         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15512         Invalid = true;
15513 
15514       // Otherwise it's a declaration.  Call out a particularly common
15515       // case here.
15516       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15517         unsigned Kind = 0;
15518         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
15519         Diag(NameLoc, diag::err_tag_definition_of_typedef)
15520           << Name << Kind << TND->getUnderlyingType();
15521         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15522         Invalid = true;
15523 
15524       // Otherwise, diagnose.
15525       } else {
15526         // The tag name clashes with something else in the target scope,
15527         // issue an error and recover by making this tag be anonymous.
15528         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
15529         notePreviousDefinition(PrevDecl, NameLoc);
15530         Name = nullptr;
15531         Invalid = true;
15532       }
15533 
15534       // The existing declaration isn't relevant to us; we're in a
15535       // new scope, so clear out the previous declaration.
15536       Previous.clear();
15537     }
15538   }
15539 
15540 CreateNewDecl:
15541 
15542   TagDecl *PrevDecl = nullptr;
15543   if (Previous.isSingleResult())
15544     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
15545 
15546   // If there is an identifier, use the location of the identifier as the
15547   // location of the decl, otherwise use the location of the struct/union
15548   // keyword.
15549   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15550 
15551   // Otherwise, create a new declaration. If there is a previous
15552   // declaration of the same entity, the two will be linked via
15553   // PrevDecl.
15554   TagDecl *New;
15555 
15556   if (Kind == TTK_Enum) {
15557     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15558     // enum X { A, B, C } D;    D should chain to X.
15559     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
15560                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
15561                            ScopedEnumUsesClassTag, IsFixed);
15562 
15563     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
15564       StdAlignValT = cast<EnumDecl>(New);
15565 
15566     // If this is an undefined enum, warn.
15567     if (TUK != TUK_Definition && !Invalid) {
15568       TagDecl *Def;
15569       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
15570         // C++0x: 7.2p2: opaque-enum-declaration.
15571         // Conflicts are diagnosed above. Do nothing.
15572       }
15573       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
15574         Diag(Loc, diag::ext_forward_ref_enum_def)
15575           << New;
15576         Diag(Def->getLocation(), diag::note_previous_definition);
15577       } else {
15578         unsigned DiagID = diag::ext_forward_ref_enum;
15579         if (getLangOpts().MSVCCompat)
15580           DiagID = diag::ext_ms_forward_ref_enum;
15581         else if (getLangOpts().CPlusPlus)
15582           DiagID = diag::err_forward_ref_enum;
15583         Diag(Loc, DiagID);
15584       }
15585     }
15586 
15587     if (EnumUnderlying) {
15588       EnumDecl *ED = cast<EnumDecl>(New);
15589       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15590         ED->setIntegerTypeSourceInfo(TI);
15591       else
15592         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
15593       ED->setPromotionType(ED->getIntegerType());
15594       assert(ED->isComplete() && "enum with type should be complete");
15595     }
15596   } else {
15597     // struct/union/class
15598 
15599     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15600     // struct X { int A; } D;    D should chain to X.
15601     if (getLangOpts().CPlusPlus) {
15602       // FIXME: Look for a way to use RecordDecl for simple structs.
15603       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15604                                   cast_or_null<CXXRecordDecl>(PrevDecl));
15605 
15606       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
15607         StdBadAlloc = cast<CXXRecordDecl>(New);
15608     } else
15609       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15610                                cast_or_null<RecordDecl>(PrevDecl));
15611   }
15612 
15613   // C++11 [dcl.type]p3:
15614   //   A type-specifier-seq shall not define a class or enumeration [...].
15615   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
15616       TUK == TUK_Definition) {
15617     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
15618       << Context.getTagDeclType(New);
15619     Invalid = true;
15620   }
15621 
15622   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
15623       DC->getDeclKind() == Decl::Enum) {
15624     Diag(New->getLocation(), diag::err_type_defined_in_enum)
15625       << Context.getTagDeclType(New);
15626     Invalid = true;
15627   }
15628 
15629   // Maybe add qualifier info.
15630   if (SS.isNotEmpty()) {
15631     if (SS.isSet()) {
15632       // If this is either a declaration or a definition, check the
15633       // nested-name-specifier against the current context.
15634       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
15635           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
15636                                        isMemberSpecialization))
15637         Invalid = true;
15638 
15639       New->setQualifierInfo(SS.getWithLocInContext(Context));
15640       if (TemplateParameterLists.size() > 0) {
15641         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
15642       }
15643     }
15644     else
15645       Invalid = true;
15646   }
15647 
15648   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15649     // Add alignment attributes if necessary; these attributes are checked when
15650     // the ASTContext lays out the structure.
15651     //
15652     // It is important for implementing the correct semantics that this
15653     // happen here (in ActOnTag). The #pragma pack stack is
15654     // maintained as a result of parser callbacks which can occur at
15655     // many points during the parsing of a struct declaration (because
15656     // the #pragma tokens are effectively skipped over during the
15657     // parsing of the struct).
15658     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15659       AddAlignmentAttributesForRecord(RD);
15660       AddMsStructLayoutForRecord(RD);
15661     }
15662   }
15663 
15664   if (ModulePrivateLoc.isValid()) {
15665     if (isMemberSpecialization)
15666       Diag(New->getLocation(), diag::err_module_private_specialization)
15667         << 2
15668         << FixItHint::CreateRemoval(ModulePrivateLoc);
15669     // __module_private__ does not apply to local classes. However, we only
15670     // diagnose this as an error when the declaration specifiers are
15671     // freestanding. Here, we just ignore the __module_private__.
15672     else if (!SearchDC->isFunctionOrMethod())
15673       New->setModulePrivate();
15674   }
15675 
15676   // If this is a specialization of a member class (of a class template),
15677   // check the specialization.
15678   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
15679     Invalid = true;
15680 
15681   // If we're declaring or defining a tag in function prototype scope in C,
15682   // note that this type can only be used within the function and add it to
15683   // the list of decls to inject into the function definition scope.
15684   if ((Name || Kind == TTK_Enum) &&
15685       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
15686     if (getLangOpts().CPlusPlus) {
15687       // C++ [dcl.fct]p6:
15688       //   Types shall not be defined in return or parameter types.
15689       if (TUK == TUK_Definition && !IsTypeSpecifier) {
15690         Diag(Loc, diag::err_type_defined_in_param_type)
15691             << Name;
15692         Invalid = true;
15693       }
15694     } else if (!PrevDecl) {
15695       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
15696     }
15697   }
15698 
15699   if (Invalid)
15700     New->setInvalidDecl();
15701 
15702   // Set the lexical context. If the tag has a C++ scope specifier, the
15703   // lexical context will be different from the semantic context.
15704   New->setLexicalDeclContext(CurContext);
15705 
15706   // Mark this as a friend decl if applicable.
15707   // In Microsoft mode, a friend declaration also acts as a forward
15708   // declaration so we always pass true to setObjectOfFriendDecl to make
15709   // the tag name visible.
15710   if (TUK == TUK_Friend)
15711     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
15712 
15713   // Set the access specifier.
15714   if (!Invalid && SearchDC->isRecord())
15715     SetMemberAccessSpecifier(New, PrevDecl, AS);
15716 
15717   if (PrevDecl)
15718     CheckRedeclarationModuleOwnership(New, PrevDecl);
15719 
15720   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
15721     New->startDefinition();
15722 
15723   ProcessDeclAttributeList(S, New, Attrs);
15724   AddPragmaAttributes(S, New);
15725 
15726   // If this has an identifier, add it to the scope stack.
15727   if (TUK == TUK_Friend) {
15728     // We might be replacing an existing declaration in the lookup tables;
15729     // if so, borrow its access specifier.
15730     if (PrevDecl)
15731       New->setAccess(PrevDecl->getAccess());
15732 
15733     DeclContext *DC = New->getDeclContext()->getRedeclContext();
15734     DC->makeDeclVisibleInContext(New);
15735     if (Name) // can be null along some error paths
15736       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
15737         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
15738   } else if (Name) {
15739     S = getNonFieldDeclScope(S);
15740     PushOnScopeChains(New, S, true);
15741   } else {
15742     CurContext->addDecl(New);
15743   }
15744 
15745   // If this is the C FILE type, notify the AST context.
15746   if (IdentifierInfo *II = New->getIdentifier())
15747     if (!New->isInvalidDecl() &&
15748         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
15749         II->isStr("FILE"))
15750       Context.setFILEDecl(New);
15751 
15752   if (PrevDecl)
15753     mergeDeclAttributes(New, PrevDecl);
15754 
15755   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
15756     inferGslOwnerPointerAttribute(CXXRD);
15757 
15758   // If there's a #pragma GCC visibility in scope, set the visibility of this
15759   // record.
15760   AddPushedVisibilityAttribute(New);
15761 
15762   if (isMemberSpecialization && !New->isInvalidDecl())
15763     CompleteMemberSpecialization(New, Previous);
15764 
15765   OwnedDecl = true;
15766   // In C++, don't return an invalid declaration. We can't recover well from
15767   // the cases where we make the type anonymous.
15768   if (Invalid && getLangOpts().CPlusPlus) {
15769     if (New->isBeingDefined())
15770       if (auto RD = dyn_cast<RecordDecl>(New))
15771         RD->completeDefinition();
15772     return nullptr;
15773   } else if (SkipBody && SkipBody->ShouldSkip) {
15774     return SkipBody->Previous;
15775   } else {
15776     return New;
15777   }
15778 }
15779 
15780 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
15781   AdjustDeclIfTemplate(TagD);
15782   TagDecl *Tag = cast<TagDecl>(TagD);
15783 
15784   // Enter the tag context.
15785   PushDeclContext(S, Tag);
15786 
15787   ActOnDocumentableDecl(TagD);
15788 
15789   // If there's a #pragma GCC visibility in scope, set the visibility of this
15790   // record.
15791   AddPushedVisibilityAttribute(Tag);
15792 }
15793 
15794 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
15795                                     SkipBodyInfo &SkipBody) {
15796   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
15797     return false;
15798 
15799   // Make the previous decl visible.
15800   makeMergedDefinitionVisible(SkipBody.Previous);
15801   return true;
15802 }
15803 
15804 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
15805   assert(isa<ObjCContainerDecl>(IDecl) &&
15806          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
15807   DeclContext *OCD = cast<DeclContext>(IDecl);
15808   assert(getContainingDC(OCD) == CurContext &&
15809       "The next DeclContext should be lexically contained in the current one.");
15810   CurContext = OCD;
15811   return IDecl;
15812 }
15813 
15814 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
15815                                            SourceLocation FinalLoc,
15816                                            bool IsFinalSpelledSealed,
15817                                            SourceLocation LBraceLoc) {
15818   AdjustDeclIfTemplate(TagD);
15819   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
15820 
15821   FieldCollector->StartClass();
15822 
15823   if (!Record->getIdentifier())
15824     return;
15825 
15826   if (FinalLoc.isValid())
15827     Record->addAttr(FinalAttr::Create(
15828         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
15829         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
15830 
15831   // C++ [class]p2:
15832   //   [...] The class-name is also inserted into the scope of the
15833   //   class itself; this is known as the injected-class-name. For
15834   //   purposes of access checking, the injected-class-name is treated
15835   //   as if it were a public member name.
15836   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
15837       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
15838       Record->getLocation(), Record->getIdentifier(),
15839       /*PrevDecl=*/nullptr,
15840       /*DelayTypeCreation=*/true);
15841   Context.getTypeDeclType(InjectedClassName, Record);
15842   InjectedClassName->setImplicit();
15843   InjectedClassName->setAccess(AS_public);
15844   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
15845       InjectedClassName->setDescribedClassTemplate(Template);
15846   PushOnScopeChains(InjectedClassName, S);
15847   assert(InjectedClassName->isInjectedClassName() &&
15848          "Broken injected-class-name");
15849 }
15850 
15851 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
15852                                     SourceRange BraceRange) {
15853   AdjustDeclIfTemplate(TagD);
15854   TagDecl *Tag = cast<TagDecl>(TagD);
15855   Tag->setBraceRange(BraceRange);
15856 
15857   // Make sure we "complete" the definition even it is invalid.
15858   if (Tag->isBeingDefined()) {
15859     assert(Tag->isInvalidDecl() && "We should already have completed it");
15860     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15861       RD->completeDefinition();
15862   }
15863 
15864   if (isa<CXXRecordDecl>(Tag)) {
15865     FieldCollector->FinishClass();
15866   }
15867 
15868   // Exit this scope of this tag's definition.
15869   PopDeclContext();
15870 
15871   if (getCurLexicalContext()->isObjCContainer() &&
15872       Tag->getDeclContext()->isFileContext())
15873     Tag->setTopLevelDeclInObjCContainer();
15874 
15875   // Notify the consumer that we've defined a tag.
15876   if (!Tag->isInvalidDecl())
15877     Consumer.HandleTagDeclDefinition(Tag);
15878 }
15879 
15880 void Sema::ActOnObjCContainerFinishDefinition() {
15881   // Exit this scope of this interface definition.
15882   PopDeclContext();
15883 }
15884 
15885 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
15886   assert(DC == CurContext && "Mismatch of container contexts");
15887   OriginalLexicalContext = DC;
15888   ActOnObjCContainerFinishDefinition();
15889 }
15890 
15891 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
15892   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
15893   OriginalLexicalContext = nullptr;
15894 }
15895 
15896 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
15897   AdjustDeclIfTemplate(TagD);
15898   TagDecl *Tag = cast<TagDecl>(TagD);
15899   Tag->setInvalidDecl();
15900 
15901   // Make sure we "complete" the definition even it is invalid.
15902   if (Tag->isBeingDefined()) {
15903     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15904       RD->completeDefinition();
15905   }
15906 
15907   // We're undoing ActOnTagStartDefinition here, not
15908   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
15909   // the FieldCollector.
15910 
15911   PopDeclContext();
15912 }
15913 
15914 // Note that FieldName may be null for anonymous bitfields.
15915 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
15916                                 IdentifierInfo *FieldName,
15917                                 QualType FieldTy, bool IsMsStruct,
15918                                 Expr *BitWidth, bool *ZeroWidth) {
15919   // Default to true; that shouldn't confuse checks for emptiness
15920   if (ZeroWidth)
15921     *ZeroWidth = true;
15922 
15923   // C99 6.7.2.1p4 - verify the field type.
15924   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
15925   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
15926     // Handle incomplete types with specific error.
15927     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
15928       return ExprError();
15929     if (FieldName)
15930       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
15931         << FieldName << FieldTy << BitWidth->getSourceRange();
15932     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
15933       << FieldTy << BitWidth->getSourceRange();
15934   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
15935                                              UPPC_BitFieldWidth))
15936     return ExprError();
15937 
15938   // If the bit-width is type- or value-dependent, don't try to check
15939   // it now.
15940   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
15941     return BitWidth;
15942 
15943   llvm::APSInt Value;
15944   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
15945   if (ICE.isInvalid())
15946     return ICE;
15947   BitWidth = ICE.get();
15948 
15949   if (Value != 0 && ZeroWidth)
15950     *ZeroWidth = false;
15951 
15952   // Zero-width bitfield is ok for anonymous field.
15953   if (Value == 0 && FieldName)
15954     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
15955 
15956   if (Value.isSigned() && Value.isNegative()) {
15957     if (FieldName)
15958       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
15959                << FieldName << Value.toString(10);
15960     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
15961       << Value.toString(10);
15962   }
15963 
15964   if (!FieldTy->isDependentType()) {
15965     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
15966     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
15967     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
15968 
15969     // Over-wide bitfields are an error in C or when using the MSVC bitfield
15970     // ABI.
15971     bool CStdConstraintViolation =
15972         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
15973     bool MSBitfieldViolation =
15974         Value.ugt(TypeStorageSize) &&
15975         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
15976     if (CStdConstraintViolation || MSBitfieldViolation) {
15977       unsigned DiagWidth =
15978           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
15979       if (FieldName)
15980         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
15981                << FieldName << (unsigned)Value.getZExtValue()
15982                << !CStdConstraintViolation << DiagWidth;
15983 
15984       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
15985              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
15986              << DiagWidth;
15987     }
15988 
15989     // Warn on types where the user might conceivably expect to get all
15990     // specified bits as value bits: that's all integral types other than
15991     // 'bool'.
15992     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
15993       if (FieldName)
15994         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
15995             << FieldName << (unsigned)Value.getZExtValue()
15996             << (unsigned)TypeWidth;
15997       else
15998         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
15999             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
16000     }
16001   }
16002 
16003   return BitWidth;
16004 }
16005 
16006 /// ActOnField - Each field of a C struct/union is passed into this in order
16007 /// to create a FieldDecl object for it.
16008 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
16009                        Declarator &D, Expr *BitfieldWidth) {
16010   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
16011                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
16012                                /*InitStyle=*/ICIS_NoInit, AS_public);
16013   return Res;
16014 }
16015 
16016 /// HandleField - Analyze a field of a C struct or a C++ data member.
16017 ///
16018 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
16019                              SourceLocation DeclStart,
16020                              Declarator &D, Expr *BitWidth,
16021                              InClassInitStyle InitStyle,
16022                              AccessSpecifier AS) {
16023   if (D.isDecompositionDeclarator()) {
16024     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
16025     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
16026       << Decomp.getSourceRange();
16027     return nullptr;
16028   }
16029 
16030   IdentifierInfo *II = D.getIdentifier();
16031   SourceLocation Loc = DeclStart;
16032   if (II) Loc = D.getIdentifierLoc();
16033 
16034   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16035   QualType T = TInfo->getType();
16036   if (getLangOpts().CPlusPlus) {
16037     CheckExtraCXXDefaultArguments(D);
16038 
16039     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16040                                         UPPC_DataMemberType)) {
16041       D.setInvalidType();
16042       T = Context.IntTy;
16043       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
16044     }
16045   }
16046 
16047   DiagnoseFunctionSpecifiers(D.getDeclSpec());
16048 
16049   if (D.getDeclSpec().isInlineSpecified())
16050     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
16051         << getLangOpts().CPlusPlus17;
16052   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
16053     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
16054          diag::err_invalid_thread)
16055       << DeclSpec::getSpecifierName(TSCS);
16056 
16057   // Check to see if this name was declared as a member previously
16058   NamedDecl *PrevDecl = nullptr;
16059   LookupResult Previous(*this, II, Loc, LookupMemberName,
16060                         ForVisibleRedeclaration);
16061   LookupName(Previous, S);
16062   switch (Previous.getResultKind()) {
16063     case LookupResult::Found:
16064     case LookupResult::FoundUnresolvedValue:
16065       PrevDecl = Previous.getAsSingle<NamedDecl>();
16066       break;
16067 
16068     case LookupResult::FoundOverloaded:
16069       PrevDecl = Previous.getRepresentativeDecl();
16070       break;
16071 
16072     case LookupResult::NotFound:
16073     case LookupResult::NotFoundInCurrentInstantiation:
16074     case LookupResult::Ambiguous:
16075       break;
16076   }
16077   Previous.suppressDiagnostics();
16078 
16079   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16080     // Maybe we will complain about the shadowed template parameter.
16081     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16082     // Just pretend that we didn't see the previous declaration.
16083     PrevDecl = nullptr;
16084   }
16085 
16086   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
16087     PrevDecl = nullptr;
16088 
16089   bool Mutable
16090     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
16091   SourceLocation TSSL = D.getBeginLoc();
16092   FieldDecl *NewFD
16093     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
16094                      TSSL, AS, PrevDecl, &D);
16095 
16096   if (NewFD->isInvalidDecl())
16097     Record->setInvalidDecl();
16098 
16099   if (D.getDeclSpec().isModulePrivateSpecified())
16100     NewFD->setModulePrivate();
16101 
16102   if (NewFD->isInvalidDecl() && PrevDecl) {
16103     // Don't introduce NewFD into scope; there's already something
16104     // with the same name in the same scope.
16105   } else if (II) {
16106     PushOnScopeChains(NewFD, S);
16107   } else
16108     Record->addDecl(NewFD);
16109 
16110   return NewFD;
16111 }
16112 
16113 /// Build a new FieldDecl and check its well-formedness.
16114 ///
16115 /// This routine builds a new FieldDecl given the fields name, type,
16116 /// record, etc. \p PrevDecl should refer to any previous declaration
16117 /// with the same name and in the same scope as the field to be
16118 /// created.
16119 ///
16120 /// \returns a new FieldDecl.
16121 ///
16122 /// \todo The Declarator argument is a hack. It will be removed once
16123 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
16124                                 TypeSourceInfo *TInfo,
16125                                 RecordDecl *Record, SourceLocation Loc,
16126                                 bool Mutable, Expr *BitWidth,
16127                                 InClassInitStyle InitStyle,
16128                                 SourceLocation TSSL,
16129                                 AccessSpecifier AS, NamedDecl *PrevDecl,
16130                                 Declarator *D) {
16131   IdentifierInfo *II = Name.getAsIdentifierInfo();
16132   bool InvalidDecl = false;
16133   if (D) InvalidDecl = D->isInvalidType();
16134 
16135   // If we receive a broken type, recover by assuming 'int' and
16136   // marking this declaration as invalid.
16137   if (T.isNull()) {
16138     InvalidDecl = true;
16139     T = Context.IntTy;
16140   }
16141 
16142   QualType EltTy = Context.getBaseElementType(T);
16143   if (!EltTy->isDependentType()) {
16144     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
16145       // Fields of incomplete type force their record to be invalid.
16146       Record->setInvalidDecl();
16147       InvalidDecl = true;
16148     } else {
16149       NamedDecl *Def;
16150       EltTy->isIncompleteType(&Def);
16151       if (Def && Def->isInvalidDecl()) {
16152         Record->setInvalidDecl();
16153         InvalidDecl = true;
16154       }
16155     }
16156   }
16157 
16158   // TR 18037 does not allow fields to be declared with address space
16159   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
16160       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
16161     Diag(Loc, diag::err_field_with_address_space);
16162     Record->setInvalidDecl();
16163     InvalidDecl = true;
16164   }
16165 
16166   if (LangOpts.OpenCL) {
16167     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
16168     // used as structure or union field: image, sampler, event or block types.
16169     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
16170         T->isBlockPointerType()) {
16171       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
16172       Record->setInvalidDecl();
16173       InvalidDecl = true;
16174     }
16175     // OpenCL v1.2 s6.9.c: bitfields are not supported.
16176     if (BitWidth) {
16177       Diag(Loc, diag::err_opencl_bitfields);
16178       InvalidDecl = true;
16179     }
16180   }
16181 
16182   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
16183   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
16184       T.hasQualifiers()) {
16185     InvalidDecl = true;
16186     Diag(Loc, diag::err_anon_bitfield_qualifiers);
16187   }
16188 
16189   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16190   // than a variably modified type.
16191   if (!InvalidDecl && T->isVariablyModifiedType()) {
16192     bool SizeIsNegative;
16193     llvm::APSInt Oversized;
16194 
16195     TypeSourceInfo *FixedTInfo =
16196       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
16197                                                     SizeIsNegative,
16198                                                     Oversized);
16199     if (FixedTInfo) {
16200       Diag(Loc, diag::warn_illegal_constant_array_size);
16201       TInfo = FixedTInfo;
16202       T = FixedTInfo->getType();
16203     } else {
16204       if (SizeIsNegative)
16205         Diag(Loc, diag::err_typecheck_negative_array_size);
16206       else if (Oversized.getBoolValue())
16207         Diag(Loc, diag::err_array_too_large)
16208           << Oversized.toString(10);
16209       else
16210         Diag(Loc, diag::err_typecheck_field_variable_size);
16211       InvalidDecl = true;
16212     }
16213   }
16214 
16215   // Fields can not have abstract class types
16216   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
16217                                              diag::err_abstract_type_in_decl,
16218                                              AbstractFieldType))
16219     InvalidDecl = true;
16220 
16221   bool ZeroWidth = false;
16222   if (InvalidDecl)
16223     BitWidth = nullptr;
16224   // If this is declared as a bit-field, check the bit-field.
16225   if (BitWidth) {
16226     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
16227                               &ZeroWidth).get();
16228     if (!BitWidth) {
16229       InvalidDecl = true;
16230       BitWidth = nullptr;
16231       ZeroWidth = false;
16232     }
16233   }
16234 
16235   // Check that 'mutable' is consistent with the type of the declaration.
16236   if (!InvalidDecl && Mutable) {
16237     unsigned DiagID = 0;
16238     if (T->isReferenceType())
16239       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
16240                                         : diag::err_mutable_reference;
16241     else if (T.isConstQualified())
16242       DiagID = diag::err_mutable_const;
16243 
16244     if (DiagID) {
16245       SourceLocation ErrLoc = Loc;
16246       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
16247         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
16248       Diag(ErrLoc, DiagID);
16249       if (DiagID != diag::ext_mutable_reference) {
16250         Mutable = false;
16251         InvalidDecl = true;
16252       }
16253     }
16254   }
16255 
16256   // C++11 [class.union]p8 (DR1460):
16257   //   At most one variant member of a union may have a
16258   //   brace-or-equal-initializer.
16259   if (InitStyle != ICIS_NoInit)
16260     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
16261 
16262   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
16263                                        BitWidth, Mutable, InitStyle);
16264   if (InvalidDecl)
16265     NewFD->setInvalidDecl();
16266 
16267   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
16268     Diag(Loc, diag::err_duplicate_member) << II;
16269     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16270     NewFD->setInvalidDecl();
16271   }
16272 
16273   if (!InvalidDecl && getLangOpts().CPlusPlus) {
16274     if (Record->isUnion()) {
16275       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16276         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
16277         if (RDecl->getDefinition()) {
16278           // C++ [class.union]p1: An object of a class with a non-trivial
16279           // constructor, a non-trivial copy constructor, a non-trivial
16280           // destructor, or a non-trivial copy assignment operator
16281           // cannot be a member of a union, nor can an array of such
16282           // objects.
16283           if (CheckNontrivialField(NewFD))
16284             NewFD->setInvalidDecl();
16285         }
16286       }
16287 
16288       // C++ [class.union]p1: If a union contains a member of reference type,
16289       // the program is ill-formed, except when compiling with MSVC extensions
16290       // enabled.
16291       if (EltTy->isReferenceType()) {
16292         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
16293                                     diag::ext_union_member_of_reference_type :
16294                                     diag::err_union_member_of_reference_type)
16295           << NewFD->getDeclName() << EltTy;
16296         if (!getLangOpts().MicrosoftExt)
16297           NewFD->setInvalidDecl();
16298       }
16299     }
16300   }
16301 
16302   // FIXME: We need to pass in the attributes given an AST
16303   // representation, not a parser representation.
16304   if (D) {
16305     // FIXME: The current scope is almost... but not entirely... correct here.
16306     ProcessDeclAttributes(getCurScope(), NewFD, *D);
16307 
16308     if (NewFD->hasAttrs())
16309       CheckAlignasUnderalignment(NewFD);
16310   }
16311 
16312   // In auto-retain/release, infer strong retension for fields of
16313   // retainable type.
16314   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
16315     NewFD->setInvalidDecl();
16316 
16317   if (T.isObjCGCWeak())
16318     Diag(Loc, diag::warn_attribute_weak_on_field);
16319 
16320   NewFD->setAccess(AS);
16321   return NewFD;
16322 }
16323 
16324 bool Sema::CheckNontrivialField(FieldDecl *FD) {
16325   assert(FD);
16326   assert(getLangOpts().CPlusPlus && "valid check only for C++");
16327 
16328   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
16329     return false;
16330 
16331   QualType EltTy = Context.getBaseElementType(FD->getType());
16332   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16333     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
16334     if (RDecl->getDefinition()) {
16335       // We check for copy constructors before constructors
16336       // because otherwise we'll never get complaints about
16337       // copy constructors.
16338 
16339       CXXSpecialMember member = CXXInvalid;
16340       // We're required to check for any non-trivial constructors. Since the
16341       // implicit default constructor is suppressed if there are any
16342       // user-declared constructors, we just need to check that there is a
16343       // trivial default constructor and a trivial copy constructor. (We don't
16344       // worry about move constructors here, since this is a C++98 check.)
16345       if (RDecl->hasNonTrivialCopyConstructor())
16346         member = CXXCopyConstructor;
16347       else if (!RDecl->hasTrivialDefaultConstructor())
16348         member = CXXDefaultConstructor;
16349       else if (RDecl->hasNonTrivialCopyAssignment())
16350         member = CXXCopyAssignment;
16351       else if (RDecl->hasNonTrivialDestructor())
16352         member = CXXDestructor;
16353 
16354       if (member != CXXInvalid) {
16355         if (!getLangOpts().CPlusPlus11 &&
16356             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
16357           // Objective-C++ ARC: it is an error to have a non-trivial field of
16358           // a union. However, system headers in Objective-C programs
16359           // occasionally have Objective-C lifetime objects within unions,
16360           // and rather than cause the program to fail, we make those
16361           // members unavailable.
16362           SourceLocation Loc = FD->getLocation();
16363           if (getSourceManager().isInSystemHeader(Loc)) {
16364             if (!FD->hasAttr<UnavailableAttr>())
16365               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
16366                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
16367             return false;
16368           }
16369         }
16370 
16371         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
16372                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
16373                diag::err_illegal_union_or_anon_struct_member)
16374           << FD->getParent()->isUnion() << FD->getDeclName() << member;
16375         DiagnoseNontrivial(RDecl, member);
16376         return !getLangOpts().CPlusPlus11;
16377       }
16378     }
16379   }
16380 
16381   return false;
16382 }
16383 
16384 /// TranslateIvarVisibility - Translate visibility from a token ID to an
16385 ///  AST enum value.
16386 static ObjCIvarDecl::AccessControl
16387 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
16388   switch (ivarVisibility) {
16389   default: llvm_unreachable("Unknown visitibility kind");
16390   case tok::objc_private: return ObjCIvarDecl::Private;
16391   case tok::objc_public: return ObjCIvarDecl::Public;
16392   case tok::objc_protected: return ObjCIvarDecl::Protected;
16393   case tok::objc_package: return ObjCIvarDecl::Package;
16394   }
16395 }
16396 
16397 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
16398 /// in order to create an IvarDecl object for it.
16399 Decl *Sema::ActOnIvar(Scope *S,
16400                                 SourceLocation DeclStart,
16401                                 Declarator &D, Expr *BitfieldWidth,
16402                                 tok::ObjCKeywordKind Visibility) {
16403 
16404   IdentifierInfo *II = D.getIdentifier();
16405   Expr *BitWidth = (Expr*)BitfieldWidth;
16406   SourceLocation Loc = DeclStart;
16407   if (II) Loc = D.getIdentifierLoc();
16408 
16409   // FIXME: Unnamed fields can be handled in various different ways, for
16410   // example, unnamed unions inject all members into the struct namespace!
16411 
16412   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16413   QualType T = TInfo->getType();
16414 
16415   if (BitWidth) {
16416     // 6.7.2.1p3, 6.7.2.1p4
16417     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
16418     if (!BitWidth)
16419       D.setInvalidType();
16420   } else {
16421     // Not a bitfield.
16422 
16423     // validate II.
16424 
16425   }
16426   if (T->isReferenceType()) {
16427     Diag(Loc, diag::err_ivar_reference_type);
16428     D.setInvalidType();
16429   }
16430   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16431   // than a variably modified type.
16432   else if (T->isVariablyModifiedType()) {
16433     Diag(Loc, diag::err_typecheck_ivar_variable_size);
16434     D.setInvalidType();
16435   }
16436 
16437   // Get the visibility (access control) for this ivar.
16438   ObjCIvarDecl::AccessControl ac =
16439     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
16440                                         : ObjCIvarDecl::None;
16441   // Must set ivar's DeclContext to its enclosing interface.
16442   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
16443   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
16444     return nullptr;
16445   ObjCContainerDecl *EnclosingContext;
16446   if (ObjCImplementationDecl *IMPDecl =
16447       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16448     if (LangOpts.ObjCRuntime.isFragile()) {
16449     // Case of ivar declared in an implementation. Context is that of its class.
16450       EnclosingContext = IMPDecl->getClassInterface();
16451       assert(EnclosingContext && "Implementation has no class interface!");
16452     }
16453     else
16454       EnclosingContext = EnclosingDecl;
16455   } else {
16456     if (ObjCCategoryDecl *CDecl =
16457         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16458       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
16459         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
16460         return nullptr;
16461       }
16462     }
16463     EnclosingContext = EnclosingDecl;
16464   }
16465 
16466   // Construct the decl.
16467   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
16468                                              DeclStart, Loc, II, T,
16469                                              TInfo, ac, (Expr *)BitfieldWidth);
16470 
16471   if (II) {
16472     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
16473                                            ForVisibleRedeclaration);
16474     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
16475         && !isa<TagDecl>(PrevDecl)) {
16476       Diag(Loc, diag::err_duplicate_member) << II;
16477       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16478       NewID->setInvalidDecl();
16479     }
16480   }
16481 
16482   // Process attributes attached to the ivar.
16483   ProcessDeclAttributes(S, NewID, D);
16484 
16485   if (D.isInvalidType())
16486     NewID->setInvalidDecl();
16487 
16488   // In ARC, infer 'retaining' for ivars of retainable type.
16489   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
16490     NewID->setInvalidDecl();
16491 
16492   if (D.getDeclSpec().isModulePrivateSpecified())
16493     NewID->setModulePrivate();
16494 
16495   if (II) {
16496     // FIXME: When interfaces are DeclContexts, we'll need to add
16497     // these to the interface.
16498     S->AddDecl(NewID);
16499     IdResolver.AddDecl(NewID);
16500   }
16501 
16502   if (LangOpts.ObjCRuntime.isNonFragile() &&
16503       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
16504     Diag(Loc, diag::warn_ivars_in_interface);
16505 
16506   return NewID;
16507 }
16508 
16509 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
16510 /// class and class extensions. For every class \@interface and class
16511 /// extension \@interface, if the last ivar is a bitfield of any type,
16512 /// then add an implicit `char :0` ivar to the end of that interface.
16513 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
16514                              SmallVectorImpl<Decl *> &AllIvarDecls) {
16515   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
16516     return;
16517 
16518   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
16519   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
16520 
16521   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
16522     return;
16523   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
16524   if (!ID) {
16525     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
16526       if (!CD->IsClassExtension())
16527         return;
16528     }
16529     // No need to add this to end of @implementation.
16530     else
16531       return;
16532   }
16533   // All conditions are met. Add a new bitfield to the tail end of ivars.
16534   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
16535   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
16536 
16537   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
16538                               DeclLoc, DeclLoc, nullptr,
16539                               Context.CharTy,
16540                               Context.getTrivialTypeSourceInfo(Context.CharTy,
16541                                                                DeclLoc),
16542                               ObjCIvarDecl::Private, BW,
16543                               true);
16544   AllIvarDecls.push_back(Ivar);
16545 }
16546 
16547 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
16548                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
16549                        SourceLocation RBrac,
16550                        const ParsedAttributesView &Attrs) {
16551   assert(EnclosingDecl && "missing record or interface decl");
16552 
16553   // If this is an Objective-C @implementation or category and we have
16554   // new fields here we should reset the layout of the interface since
16555   // it will now change.
16556   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
16557     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
16558     switch (DC->getKind()) {
16559     default: break;
16560     case Decl::ObjCCategory:
16561       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
16562       break;
16563     case Decl::ObjCImplementation:
16564       Context.
16565         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
16566       break;
16567     }
16568   }
16569 
16570   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
16571   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
16572 
16573   // Start counting up the number of named members; make sure to include
16574   // members of anonymous structs and unions in the total.
16575   unsigned NumNamedMembers = 0;
16576   if (Record) {
16577     for (const auto *I : Record->decls()) {
16578       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
16579         if (IFD->getDeclName())
16580           ++NumNamedMembers;
16581     }
16582   }
16583 
16584   // Verify that all the fields are okay.
16585   SmallVector<FieldDecl*, 32> RecFields;
16586 
16587   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
16588        i != end; ++i) {
16589     FieldDecl *FD = cast<FieldDecl>(*i);
16590 
16591     // Get the type for the field.
16592     const Type *FDTy = FD->getType().getTypePtr();
16593 
16594     if (!FD->isAnonymousStructOrUnion()) {
16595       // Remember all fields written by the user.
16596       RecFields.push_back(FD);
16597     }
16598 
16599     // If the field is already invalid for some reason, don't emit more
16600     // diagnostics about it.
16601     if (FD->isInvalidDecl()) {
16602       EnclosingDecl->setInvalidDecl();
16603       continue;
16604     }
16605 
16606     // C99 6.7.2.1p2:
16607     //   A structure or union shall not contain a member with
16608     //   incomplete or function type (hence, a structure shall not
16609     //   contain an instance of itself, but may contain a pointer to
16610     //   an instance of itself), except that the last member of a
16611     //   structure with more than one named member may have incomplete
16612     //   array type; such a structure (and any union containing,
16613     //   possibly recursively, a member that is such a structure)
16614     //   shall not be a member of a structure or an element of an
16615     //   array.
16616     bool IsLastField = (i + 1 == Fields.end());
16617     if (FDTy->isFunctionType()) {
16618       // Field declared as a function.
16619       Diag(FD->getLocation(), diag::err_field_declared_as_function)
16620         << FD->getDeclName();
16621       FD->setInvalidDecl();
16622       EnclosingDecl->setInvalidDecl();
16623       continue;
16624     } else if (FDTy->isIncompleteArrayType() &&
16625                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
16626       if (Record) {
16627         // Flexible array member.
16628         // Microsoft and g++ is more permissive regarding flexible array.
16629         // It will accept flexible array in union and also
16630         // as the sole element of a struct/class.
16631         unsigned DiagID = 0;
16632         if (!Record->isUnion() && !IsLastField) {
16633           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
16634             << FD->getDeclName() << FD->getType() << Record->getTagKind();
16635           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
16636           FD->setInvalidDecl();
16637           EnclosingDecl->setInvalidDecl();
16638           continue;
16639         } else if (Record->isUnion())
16640           DiagID = getLangOpts().MicrosoftExt
16641                        ? diag::ext_flexible_array_union_ms
16642                        : getLangOpts().CPlusPlus
16643                              ? diag::ext_flexible_array_union_gnu
16644                              : diag::err_flexible_array_union;
16645         else if (NumNamedMembers < 1)
16646           DiagID = getLangOpts().MicrosoftExt
16647                        ? diag::ext_flexible_array_empty_aggregate_ms
16648                        : getLangOpts().CPlusPlus
16649                              ? diag::ext_flexible_array_empty_aggregate_gnu
16650                              : diag::err_flexible_array_empty_aggregate;
16651 
16652         if (DiagID)
16653           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
16654                                           << Record->getTagKind();
16655         // While the layout of types that contain virtual bases is not specified
16656         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
16657         // virtual bases after the derived members.  This would make a flexible
16658         // array member declared at the end of an object not adjacent to the end
16659         // of the type.
16660         if (CXXRecord && CXXRecord->getNumVBases() != 0)
16661           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
16662               << FD->getDeclName() << Record->getTagKind();
16663         if (!getLangOpts().C99)
16664           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
16665             << FD->getDeclName() << Record->getTagKind();
16666 
16667         // If the element type has a non-trivial destructor, we would not
16668         // implicitly destroy the elements, so disallow it for now.
16669         //
16670         // FIXME: GCC allows this. We should probably either implicitly delete
16671         // the destructor of the containing class, or just allow this.
16672         QualType BaseElem = Context.getBaseElementType(FD->getType());
16673         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
16674           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
16675             << FD->getDeclName() << FD->getType();
16676           FD->setInvalidDecl();
16677           EnclosingDecl->setInvalidDecl();
16678           continue;
16679         }
16680         // Okay, we have a legal flexible array member at the end of the struct.
16681         Record->setHasFlexibleArrayMember(true);
16682       } else {
16683         // In ObjCContainerDecl ivars with incomplete array type are accepted,
16684         // unless they are followed by another ivar. That check is done
16685         // elsewhere, after synthesized ivars are known.
16686       }
16687     } else if (!FDTy->isDependentType() &&
16688                RequireCompleteType(FD->getLocation(), FD->getType(),
16689                                    diag::err_field_incomplete)) {
16690       // Incomplete type
16691       FD->setInvalidDecl();
16692       EnclosingDecl->setInvalidDecl();
16693       continue;
16694     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
16695       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
16696         // A type which contains a flexible array member is considered to be a
16697         // flexible array member.
16698         Record->setHasFlexibleArrayMember(true);
16699         if (!Record->isUnion()) {
16700           // If this is a struct/class and this is not the last element, reject
16701           // it.  Note that GCC supports variable sized arrays in the middle of
16702           // structures.
16703           if (!IsLastField)
16704             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
16705               << FD->getDeclName() << FD->getType();
16706           else {
16707             // We support flexible arrays at the end of structs in
16708             // other structs as an extension.
16709             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
16710               << FD->getDeclName();
16711           }
16712         }
16713       }
16714       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
16715           RequireNonAbstractType(FD->getLocation(), FD->getType(),
16716                                  diag::err_abstract_type_in_decl,
16717                                  AbstractIvarType)) {
16718         // Ivars can not have abstract class types
16719         FD->setInvalidDecl();
16720       }
16721       if (Record && FDTTy->getDecl()->hasObjectMember())
16722         Record->setHasObjectMember(true);
16723       if (Record && FDTTy->getDecl()->hasVolatileMember())
16724         Record->setHasVolatileMember(true);
16725     } else if (FDTy->isObjCObjectType()) {
16726       /// A field cannot be an Objective-c object
16727       Diag(FD->getLocation(), diag::err_statically_allocated_object)
16728         << FixItHint::CreateInsertion(FD->getLocation(), "*");
16729       QualType T = Context.getObjCObjectPointerType(FD->getType());
16730       FD->setType(T);
16731     } else if (Record && Record->isUnion() &&
16732                FD->getType().hasNonTrivialObjCLifetime() &&
16733                getSourceManager().isInSystemHeader(FD->getLocation()) &&
16734                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
16735                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
16736                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
16737       // For backward compatibility, fields of C unions declared in system
16738       // headers that have non-trivial ObjC ownership qualifications are marked
16739       // as unavailable unless the qualifier is explicit and __strong. This can
16740       // break ABI compatibility between programs compiled with ARC and MRR, but
16741       // is a better option than rejecting programs using those unions under
16742       // ARC.
16743       FD->addAttr(UnavailableAttr::CreateImplicit(
16744           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
16745           FD->getLocation()));
16746     } else if (getLangOpts().ObjC &&
16747                getLangOpts().getGC() != LangOptions::NonGC &&
16748                Record && !Record->hasObjectMember()) {
16749       if (FD->getType()->isObjCObjectPointerType() ||
16750           FD->getType().isObjCGCStrong())
16751         Record->setHasObjectMember(true);
16752       else if (Context.getAsArrayType(FD->getType())) {
16753         QualType BaseType = Context.getBaseElementType(FD->getType());
16754         if (BaseType->isRecordType() &&
16755             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
16756           Record->setHasObjectMember(true);
16757         else if (BaseType->isObjCObjectPointerType() ||
16758                  BaseType.isObjCGCStrong())
16759                Record->setHasObjectMember(true);
16760       }
16761     }
16762 
16763     if (Record && !getLangOpts().CPlusPlus &&
16764         !shouldIgnoreForRecordTriviality(FD)) {
16765       QualType FT = FD->getType();
16766       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
16767         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
16768         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
16769             Record->isUnion())
16770           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
16771       }
16772       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
16773       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
16774         Record->setNonTrivialToPrimitiveCopy(true);
16775         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
16776           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
16777       }
16778       if (FT.isDestructedType()) {
16779         Record->setNonTrivialToPrimitiveDestroy(true);
16780         Record->setParamDestroyedInCallee(true);
16781         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
16782           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
16783       }
16784 
16785       if (const auto *RT = FT->getAs<RecordType>()) {
16786         if (RT->getDecl()->getArgPassingRestrictions() ==
16787             RecordDecl::APK_CanNeverPassInRegs)
16788           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16789       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
16790         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16791     }
16792 
16793     if (Record && FD->getType().isVolatileQualified())
16794       Record->setHasVolatileMember(true);
16795     // Keep track of the number of named members.
16796     if (FD->getIdentifier())
16797       ++NumNamedMembers;
16798   }
16799 
16800   // Okay, we successfully defined 'Record'.
16801   if (Record) {
16802     bool Completed = false;
16803     if (CXXRecord) {
16804       if (!CXXRecord->isInvalidDecl()) {
16805         // Set access bits correctly on the directly-declared conversions.
16806         for (CXXRecordDecl::conversion_iterator
16807                I = CXXRecord->conversion_begin(),
16808                E = CXXRecord->conversion_end(); I != E; ++I)
16809           I.setAccess((*I)->getAccess());
16810       }
16811 
16812       if (!CXXRecord->isDependentType()) {
16813         // Add any implicitly-declared members to this class.
16814         AddImplicitlyDeclaredMembersToClass(CXXRecord);
16815 
16816         if (!CXXRecord->isInvalidDecl()) {
16817           // If we have virtual base classes, we may end up finding multiple
16818           // final overriders for a given virtual function. Check for this
16819           // problem now.
16820           if (CXXRecord->getNumVBases()) {
16821             CXXFinalOverriderMap FinalOverriders;
16822             CXXRecord->getFinalOverriders(FinalOverriders);
16823 
16824             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
16825                                              MEnd = FinalOverriders.end();
16826                  M != MEnd; ++M) {
16827               for (OverridingMethods::iterator SO = M->second.begin(),
16828                                             SOEnd = M->second.end();
16829                    SO != SOEnd; ++SO) {
16830                 assert(SO->second.size() > 0 &&
16831                        "Virtual function without overriding functions?");
16832                 if (SO->second.size() == 1)
16833                   continue;
16834 
16835                 // C++ [class.virtual]p2:
16836                 //   In a derived class, if a virtual member function of a base
16837                 //   class subobject has more than one final overrider the
16838                 //   program is ill-formed.
16839                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
16840                   << (const NamedDecl *)M->first << Record;
16841                 Diag(M->first->getLocation(),
16842                      diag::note_overridden_virtual_function);
16843                 for (OverridingMethods::overriding_iterator
16844                           OM = SO->second.begin(),
16845                        OMEnd = SO->second.end();
16846                      OM != OMEnd; ++OM)
16847                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
16848                     << (const NamedDecl *)M->first << OM->Method->getParent();
16849 
16850                 Record->setInvalidDecl();
16851               }
16852             }
16853             CXXRecord->completeDefinition(&FinalOverriders);
16854             Completed = true;
16855           }
16856         }
16857       }
16858     }
16859 
16860     if (!Completed)
16861       Record->completeDefinition();
16862 
16863     // Handle attributes before checking the layout.
16864     ProcessDeclAttributeList(S, Record, Attrs);
16865 
16866     // We may have deferred checking for a deleted destructor. Check now.
16867     if (CXXRecord) {
16868       auto *Dtor = CXXRecord->getDestructor();
16869       if (Dtor && Dtor->isImplicit() &&
16870           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
16871         CXXRecord->setImplicitDestructorIsDeleted();
16872         SetDeclDeleted(Dtor, CXXRecord->getLocation());
16873       }
16874     }
16875 
16876     if (Record->hasAttrs()) {
16877       CheckAlignasUnderalignment(Record);
16878 
16879       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
16880         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
16881                                            IA->getRange(), IA->getBestCase(),
16882                                            IA->getInheritanceModel());
16883     }
16884 
16885     // Check if the structure/union declaration is a type that can have zero
16886     // size in C. For C this is a language extension, for C++ it may cause
16887     // compatibility problems.
16888     bool CheckForZeroSize;
16889     if (!getLangOpts().CPlusPlus) {
16890       CheckForZeroSize = true;
16891     } else {
16892       // For C++ filter out types that cannot be referenced in C code.
16893       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
16894       CheckForZeroSize =
16895           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
16896           !CXXRecord->isDependentType() &&
16897           CXXRecord->isCLike();
16898     }
16899     if (CheckForZeroSize) {
16900       bool ZeroSize = true;
16901       bool IsEmpty = true;
16902       unsigned NonBitFields = 0;
16903       for (RecordDecl::field_iterator I = Record->field_begin(),
16904                                       E = Record->field_end();
16905            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
16906         IsEmpty = false;
16907         if (I->isUnnamedBitfield()) {
16908           if (!I->isZeroLengthBitField(Context))
16909             ZeroSize = false;
16910         } else {
16911           ++NonBitFields;
16912           QualType FieldType = I->getType();
16913           if (FieldType->isIncompleteType() ||
16914               !Context.getTypeSizeInChars(FieldType).isZero())
16915             ZeroSize = false;
16916         }
16917       }
16918 
16919       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
16920       // allowed in C++, but warn if its declaration is inside
16921       // extern "C" block.
16922       if (ZeroSize) {
16923         Diag(RecLoc, getLangOpts().CPlusPlus ?
16924                          diag::warn_zero_size_struct_union_in_extern_c :
16925                          diag::warn_zero_size_struct_union_compat)
16926           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
16927       }
16928 
16929       // Structs without named members are extension in C (C99 6.7.2.1p7),
16930       // but are accepted by GCC.
16931       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
16932         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
16933                                diag::ext_no_named_members_in_struct_union)
16934           << Record->isUnion();
16935       }
16936     }
16937   } else {
16938     ObjCIvarDecl **ClsFields =
16939       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
16940     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
16941       ID->setEndOfDefinitionLoc(RBrac);
16942       // Add ivar's to class's DeclContext.
16943       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16944         ClsFields[i]->setLexicalDeclContext(ID);
16945         ID->addDecl(ClsFields[i]);
16946       }
16947       // Must enforce the rule that ivars in the base classes may not be
16948       // duplicates.
16949       if (ID->getSuperClass())
16950         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
16951     } else if (ObjCImplementationDecl *IMPDecl =
16952                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16953       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
16954       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
16955         // Ivar declared in @implementation never belongs to the implementation.
16956         // Only it is in implementation's lexical context.
16957         ClsFields[I]->setLexicalDeclContext(IMPDecl);
16958       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
16959       IMPDecl->setIvarLBraceLoc(LBrac);
16960       IMPDecl->setIvarRBraceLoc(RBrac);
16961     } else if (ObjCCategoryDecl *CDecl =
16962                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16963       // case of ivars in class extension; all other cases have been
16964       // reported as errors elsewhere.
16965       // FIXME. Class extension does not have a LocEnd field.
16966       // CDecl->setLocEnd(RBrac);
16967       // Add ivar's to class extension's DeclContext.
16968       // Diagnose redeclaration of private ivars.
16969       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
16970       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16971         if (IDecl) {
16972           if (const ObjCIvarDecl *ClsIvar =
16973               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
16974             Diag(ClsFields[i]->getLocation(),
16975                  diag::err_duplicate_ivar_declaration);
16976             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
16977             continue;
16978           }
16979           for (const auto *Ext : IDecl->known_extensions()) {
16980             if (const ObjCIvarDecl *ClsExtIvar
16981                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
16982               Diag(ClsFields[i]->getLocation(),
16983                    diag::err_duplicate_ivar_declaration);
16984               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
16985               continue;
16986             }
16987           }
16988         }
16989         ClsFields[i]->setLexicalDeclContext(CDecl);
16990         CDecl->addDecl(ClsFields[i]);
16991       }
16992       CDecl->setIvarLBraceLoc(LBrac);
16993       CDecl->setIvarRBraceLoc(RBrac);
16994     }
16995   }
16996 }
16997 
16998 /// Determine whether the given integral value is representable within
16999 /// the given type T.
17000 static bool isRepresentableIntegerValue(ASTContext &Context,
17001                                         llvm::APSInt &Value,
17002                                         QualType T) {
17003   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
17004          "Integral type required!");
17005   unsigned BitWidth = Context.getIntWidth(T);
17006 
17007   if (Value.isUnsigned() || Value.isNonNegative()) {
17008     if (T->isSignedIntegerOrEnumerationType())
17009       --BitWidth;
17010     return Value.getActiveBits() <= BitWidth;
17011   }
17012   return Value.getMinSignedBits() <= BitWidth;
17013 }
17014 
17015 // Given an integral type, return the next larger integral type
17016 // (or a NULL type of no such type exists).
17017 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
17018   // FIXME: Int128/UInt128 support, which also needs to be introduced into
17019   // enum checking below.
17020   assert((T->isIntegralType(Context) ||
17021          T->isEnumeralType()) && "Integral type required!");
17022   const unsigned NumTypes = 4;
17023   QualType SignedIntegralTypes[NumTypes] = {
17024     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
17025   };
17026   QualType UnsignedIntegralTypes[NumTypes] = {
17027     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
17028     Context.UnsignedLongLongTy
17029   };
17030 
17031   unsigned BitWidth = Context.getTypeSize(T);
17032   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
17033                                                         : UnsignedIntegralTypes;
17034   for (unsigned I = 0; I != NumTypes; ++I)
17035     if (Context.getTypeSize(Types[I]) > BitWidth)
17036       return Types[I];
17037 
17038   return QualType();
17039 }
17040 
17041 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
17042                                           EnumConstantDecl *LastEnumConst,
17043                                           SourceLocation IdLoc,
17044                                           IdentifierInfo *Id,
17045                                           Expr *Val) {
17046   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17047   llvm::APSInt EnumVal(IntWidth);
17048   QualType EltTy;
17049 
17050   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
17051     Val = nullptr;
17052 
17053   if (Val)
17054     Val = DefaultLvalueConversion(Val).get();
17055 
17056   if (Val) {
17057     if (Enum->isDependentType() || Val->isTypeDependent())
17058       EltTy = Context.DependentTy;
17059     else {
17060       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
17061         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
17062         // constant-expression in the enumerator-definition shall be a converted
17063         // constant expression of the underlying type.
17064         EltTy = Enum->getIntegerType();
17065         ExprResult Converted =
17066           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
17067                                            CCEK_Enumerator);
17068         if (Converted.isInvalid())
17069           Val = nullptr;
17070         else
17071           Val = Converted.get();
17072       } else if (!Val->isValueDependent() &&
17073                  !(Val = VerifyIntegerConstantExpression(Val,
17074                                                          &EnumVal).get())) {
17075         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
17076       } else {
17077         if (Enum->isComplete()) {
17078           EltTy = Enum->getIntegerType();
17079 
17080           // In Obj-C and Microsoft mode, require the enumeration value to be
17081           // representable in the underlying type of the enumeration. In C++11,
17082           // we perform a non-narrowing conversion as part of converted constant
17083           // expression checking.
17084           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17085             if (Context.getTargetInfo()
17086                     .getTriple()
17087                     .isWindowsMSVCEnvironment()) {
17088               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
17089             } else {
17090               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
17091             }
17092           }
17093 
17094           // Cast to the underlying type.
17095           Val = ImpCastExprToType(Val, EltTy,
17096                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
17097                                                          : CK_IntegralCast)
17098                     .get();
17099         } else if (getLangOpts().CPlusPlus) {
17100           // C++11 [dcl.enum]p5:
17101           //   If the underlying type is not fixed, the type of each enumerator
17102           //   is the type of its initializing value:
17103           //     - If an initializer is specified for an enumerator, the
17104           //       initializing value has the same type as the expression.
17105           EltTy = Val->getType();
17106         } else {
17107           // C99 6.7.2.2p2:
17108           //   The expression that defines the value of an enumeration constant
17109           //   shall be an integer constant expression that has a value
17110           //   representable as an int.
17111 
17112           // Complain if the value is not representable in an int.
17113           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
17114             Diag(IdLoc, diag::ext_enum_value_not_int)
17115               << EnumVal.toString(10) << Val->getSourceRange()
17116               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
17117           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
17118             // Force the type of the expression to 'int'.
17119             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
17120           }
17121           EltTy = Val->getType();
17122         }
17123       }
17124     }
17125   }
17126 
17127   if (!Val) {
17128     if (Enum->isDependentType())
17129       EltTy = Context.DependentTy;
17130     else if (!LastEnumConst) {
17131       // C++0x [dcl.enum]p5:
17132       //   If the underlying type is not fixed, the type of each enumerator
17133       //   is the type of its initializing value:
17134       //     - If no initializer is specified for the first enumerator, the
17135       //       initializing value has an unspecified integral type.
17136       //
17137       // GCC uses 'int' for its unspecified integral type, as does
17138       // C99 6.7.2.2p3.
17139       if (Enum->isFixed()) {
17140         EltTy = Enum->getIntegerType();
17141       }
17142       else {
17143         EltTy = Context.IntTy;
17144       }
17145     } else {
17146       // Assign the last value + 1.
17147       EnumVal = LastEnumConst->getInitVal();
17148       ++EnumVal;
17149       EltTy = LastEnumConst->getType();
17150 
17151       // Check for overflow on increment.
17152       if (EnumVal < LastEnumConst->getInitVal()) {
17153         // C++0x [dcl.enum]p5:
17154         //   If the underlying type is not fixed, the type of each enumerator
17155         //   is the type of its initializing value:
17156         //
17157         //     - Otherwise the type of the initializing value is the same as
17158         //       the type of the initializing value of the preceding enumerator
17159         //       unless the incremented value is not representable in that type,
17160         //       in which case the type is an unspecified integral type
17161         //       sufficient to contain the incremented value. If no such type
17162         //       exists, the program is ill-formed.
17163         QualType T = getNextLargerIntegralType(Context, EltTy);
17164         if (T.isNull() || Enum->isFixed()) {
17165           // There is no integral type larger enough to represent this
17166           // value. Complain, then allow the value to wrap around.
17167           EnumVal = LastEnumConst->getInitVal();
17168           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
17169           ++EnumVal;
17170           if (Enum->isFixed())
17171             // When the underlying type is fixed, this is ill-formed.
17172             Diag(IdLoc, diag::err_enumerator_wrapped)
17173               << EnumVal.toString(10)
17174               << EltTy;
17175           else
17176             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
17177               << EnumVal.toString(10);
17178         } else {
17179           EltTy = T;
17180         }
17181 
17182         // Retrieve the last enumerator's value, extent that type to the
17183         // type that is supposed to be large enough to represent the incremented
17184         // value, then increment.
17185         EnumVal = LastEnumConst->getInitVal();
17186         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17187         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
17188         ++EnumVal;
17189 
17190         // If we're not in C++, diagnose the overflow of enumerator values,
17191         // which in C99 means that the enumerator value is not representable in
17192         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
17193         // permits enumerator values that are representable in some larger
17194         // integral type.
17195         if (!getLangOpts().CPlusPlus && !T.isNull())
17196           Diag(IdLoc, diag::warn_enum_value_overflow);
17197       } else if (!getLangOpts().CPlusPlus &&
17198                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17199         // Enforce C99 6.7.2.2p2 even when we compute the next value.
17200         Diag(IdLoc, diag::ext_enum_value_not_int)
17201           << EnumVal.toString(10) << 1;
17202       }
17203     }
17204   }
17205 
17206   if (!EltTy->isDependentType()) {
17207     // Make the enumerator value match the signedness and size of the
17208     // enumerator's type.
17209     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
17210     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17211   }
17212 
17213   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
17214                                   Val, EnumVal);
17215 }
17216 
17217 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
17218                                                 SourceLocation IILoc) {
17219   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
17220       !getLangOpts().CPlusPlus)
17221     return SkipBodyInfo();
17222 
17223   // We have an anonymous enum definition. Look up the first enumerator to
17224   // determine if we should merge the definition with an existing one and
17225   // skip the body.
17226   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
17227                                          forRedeclarationInCurContext());
17228   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
17229   if (!PrevECD)
17230     return SkipBodyInfo();
17231 
17232   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
17233   NamedDecl *Hidden;
17234   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
17235     SkipBodyInfo Skip;
17236     Skip.Previous = Hidden;
17237     return Skip;
17238   }
17239 
17240   return SkipBodyInfo();
17241 }
17242 
17243 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
17244                               SourceLocation IdLoc, IdentifierInfo *Id,
17245                               const ParsedAttributesView &Attrs,
17246                               SourceLocation EqualLoc, Expr *Val) {
17247   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
17248   EnumConstantDecl *LastEnumConst =
17249     cast_or_null<EnumConstantDecl>(lastEnumConst);
17250 
17251   // The scope passed in may not be a decl scope.  Zip up the scope tree until
17252   // we find one that is.
17253   S = getNonFieldDeclScope(S);
17254 
17255   // Verify that there isn't already something declared with this name in this
17256   // scope.
17257   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
17258   LookupName(R, S);
17259   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
17260 
17261   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17262     // Maybe we will complain about the shadowed template parameter.
17263     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
17264     // Just pretend that we didn't see the previous declaration.
17265     PrevDecl = nullptr;
17266   }
17267 
17268   // C++ [class.mem]p15:
17269   // If T is the name of a class, then each of the following shall have a name
17270   // different from T:
17271   // - every enumerator of every member of class T that is an unscoped
17272   // enumerated type
17273   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
17274     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
17275                             DeclarationNameInfo(Id, IdLoc));
17276 
17277   EnumConstantDecl *New =
17278     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
17279   if (!New)
17280     return nullptr;
17281 
17282   if (PrevDecl) {
17283     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
17284       // Check for other kinds of shadowing not already handled.
17285       CheckShadow(New, PrevDecl, R);
17286     }
17287 
17288     // When in C++, we may get a TagDecl with the same name; in this case the
17289     // enum constant will 'hide' the tag.
17290     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
17291            "Received TagDecl when not in C++!");
17292     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
17293       if (isa<EnumConstantDecl>(PrevDecl))
17294         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
17295       else
17296         Diag(IdLoc, diag::err_redefinition) << Id;
17297       notePreviousDefinition(PrevDecl, IdLoc);
17298       return nullptr;
17299     }
17300   }
17301 
17302   // Process attributes.
17303   ProcessDeclAttributeList(S, New, Attrs);
17304   AddPragmaAttributes(S, New);
17305 
17306   // Register this decl in the current scope stack.
17307   New->setAccess(TheEnumDecl->getAccess());
17308   PushOnScopeChains(New, S);
17309 
17310   ActOnDocumentableDecl(New);
17311 
17312   return New;
17313 }
17314 
17315 // Returns true when the enum initial expression does not trigger the
17316 // duplicate enum warning.  A few common cases are exempted as follows:
17317 // Element2 = Element1
17318 // Element2 = Element1 + 1
17319 // Element2 = Element1 - 1
17320 // Where Element2 and Element1 are from the same enum.
17321 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
17322   Expr *InitExpr = ECD->getInitExpr();
17323   if (!InitExpr)
17324     return true;
17325   InitExpr = InitExpr->IgnoreImpCasts();
17326 
17327   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
17328     if (!BO->isAdditiveOp())
17329       return true;
17330     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
17331     if (!IL)
17332       return true;
17333     if (IL->getValue() != 1)
17334       return true;
17335 
17336     InitExpr = BO->getLHS();
17337   }
17338 
17339   // This checks if the elements are from the same enum.
17340   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
17341   if (!DRE)
17342     return true;
17343 
17344   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
17345   if (!EnumConstant)
17346     return true;
17347 
17348   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
17349       Enum)
17350     return true;
17351 
17352   return false;
17353 }
17354 
17355 // Emits a warning when an element is implicitly set a value that
17356 // a previous element has already been set to.
17357 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
17358                                         EnumDecl *Enum, QualType EnumType) {
17359   // Avoid anonymous enums
17360   if (!Enum->getIdentifier())
17361     return;
17362 
17363   // Only check for small enums.
17364   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
17365     return;
17366 
17367   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
17368     return;
17369 
17370   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
17371   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
17372 
17373   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
17374   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
17375 
17376   // Use int64_t as a key to avoid needing special handling for DenseMap keys.
17377   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
17378     llvm::APSInt Val = D->getInitVal();
17379     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
17380   };
17381 
17382   DuplicatesVector DupVector;
17383   ValueToVectorMap EnumMap;
17384 
17385   // Populate the EnumMap with all values represented by enum constants without
17386   // an initializer.
17387   for (auto *Element : Elements) {
17388     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
17389 
17390     // Null EnumConstantDecl means a previous diagnostic has been emitted for
17391     // this constant.  Skip this enum since it may be ill-formed.
17392     if (!ECD) {
17393       return;
17394     }
17395 
17396     // Constants with initalizers are handled in the next loop.
17397     if (ECD->getInitExpr())
17398       continue;
17399 
17400     // Duplicate values are handled in the next loop.
17401     EnumMap.insert({EnumConstantToKey(ECD), ECD});
17402   }
17403 
17404   if (EnumMap.size() == 0)
17405     return;
17406 
17407   // Create vectors for any values that has duplicates.
17408   for (auto *Element : Elements) {
17409     // The last loop returned if any constant was null.
17410     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
17411     if (!ValidDuplicateEnum(ECD, Enum))
17412       continue;
17413 
17414     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
17415     if (Iter == EnumMap.end())
17416       continue;
17417 
17418     DeclOrVector& Entry = Iter->second;
17419     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
17420       // Ensure constants are different.
17421       if (D == ECD)
17422         continue;
17423 
17424       // Create new vector and push values onto it.
17425       auto Vec = std::make_unique<ECDVector>();
17426       Vec->push_back(D);
17427       Vec->push_back(ECD);
17428 
17429       // Update entry to point to the duplicates vector.
17430       Entry = Vec.get();
17431 
17432       // Store the vector somewhere we can consult later for quick emission of
17433       // diagnostics.
17434       DupVector.emplace_back(std::move(Vec));
17435       continue;
17436     }
17437 
17438     ECDVector *Vec = Entry.get<ECDVector*>();
17439     // Make sure constants are not added more than once.
17440     if (*Vec->begin() == ECD)
17441       continue;
17442 
17443     Vec->push_back(ECD);
17444   }
17445 
17446   // Emit diagnostics.
17447   for (const auto &Vec : DupVector) {
17448     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
17449 
17450     // Emit warning for one enum constant.
17451     auto *FirstECD = Vec->front();
17452     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
17453       << FirstECD << FirstECD->getInitVal().toString(10)
17454       << FirstECD->getSourceRange();
17455 
17456     // Emit one note for each of the remaining enum constants with
17457     // the same value.
17458     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
17459       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
17460         << ECD << ECD->getInitVal().toString(10)
17461         << ECD->getSourceRange();
17462   }
17463 }
17464 
17465 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
17466                              bool AllowMask) const {
17467   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
17468   assert(ED->isCompleteDefinition() && "expected enum definition");
17469 
17470   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
17471   llvm::APInt &FlagBits = R.first->second;
17472 
17473   if (R.second) {
17474     for (auto *E : ED->enumerators()) {
17475       const auto &EVal = E->getInitVal();
17476       // Only single-bit enumerators introduce new flag values.
17477       if (EVal.isPowerOf2())
17478         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
17479     }
17480   }
17481 
17482   // A value is in a flag enum if either its bits are a subset of the enum's
17483   // flag bits (the first condition) or we are allowing masks and the same is
17484   // true of its complement (the second condition). When masks are allowed, we
17485   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
17486   //
17487   // While it's true that any value could be used as a mask, the assumption is
17488   // that a mask will have all of the insignificant bits set. Anything else is
17489   // likely a logic error.
17490   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
17491   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
17492 }
17493 
17494 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
17495                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
17496                          const ParsedAttributesView &Attrs) {
17497   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
17498   QualType EnumType = Context.getTypeDeclType(Enum);
17499 
17500   ProcessDeclAttributeList(S, Enum, Attrs);
17501 
17502   if (Enum->isDependentType()) {
17503     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17504       EnumConstantDecl *ECD =
17505         cast_or_null<EnumConstantDecl>(Elements[i]);
17506       if (!ECD) continue;
17507 
17508       ECD->setType(EnumType);
17509     }
17510 
17511     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
17512     return;
17513   }
17514 
17515   // TODO: If the result value doesn't fit in an int, it must be a long or long
17516   // long value.  ISO C does not support this, but GCC does as an extension,
17517   // emit a warning.
17518   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17519   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
17520   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
17521 
17522   // Verify that all the values are okay, compute the size of the values, and
17523   // reverse the list.
17524   unsigned NumNegativeBits = 0;
17525   unsigned NumPositiveBits = 0;
17526 
17527   // Keep track of whether all elements have type int.
17528   bool AllElementsInt = true;
17529 
17530   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17531     EnumConstantDecl *ECD =
17532       cast_or_null<EnumConstantDecl>(Elements[i]);
17533     if (!ECD) continue;  // Already issued a diagnostic.
17534 
17535     const llvm::APSInt &InitVal = ECD->getInitVal();
17536 
17537     // Keep track of the size of positive and negative values.
17538     if (InitVal.isUnsigned() || InitVal.isNonNegative())
17539       NumPositiveBits = std::max(NumPositiveBits,
17540                                  (unsigned)InitVal.getActiveBits());
17541     else
17542       NumNegativeBits = std::max(NumNegativeBits,
17543                                  (unsigned)InitVal.getMinSignedBits());
17544 
17545     // Keep track of whether every enum element has type int (very common).
17546     if (AllElementsInt)
17547       AllElementsInt = ECD->getType() == Context.IntTy;
17548   }
17549 
17550   // Figure out the type that should be used for this enum.
17551   QualType BestType;
17552   unsigned BestWidth;
17553 
17554   // C++0x N3000 [conv.prom]p3:
17555   //   An rvalue of an unscoped enumeration type whose underlying
17556   //   type is not fixed can be converted to an rvalue of the first
17557   //   of the following types that can represent all the values of
17558   //   the enumeration: int, unsigned int, long int, unsigned long
17559   //   int, long long int, or unsigned long long int.
17560   // C99 6.4.4.3p2:
17561   //   An identifier declared as an enumeration constant has type int.
17562   // The C99 rule is modified by a gcc extension
17563   QualType BestPromotionType;
17564 
17565   bool Packed = Enum->hasAttr<PackedAttr>();
17566   // -fshort-enums is the equivalent to specifying the packed attribute on all
17567   // enum definitions.
17568   if (LangOpts.ShortEnums)
17569     Packed = true;
17570 
17571   // If the enum already has a type because it is fixed or dictated by the
17572   // target, promote that type instead of analyzing the enumerators.
17573   if (Enum->isComplete()) {
17574     BestType = Enum->getIntegerType();
17575     if (BestType->isPromotableIntegerType())
17576       BestPromotionType = Context.getPromotedIntegerType(BestType);
17577     else
17578       BestPromotionType = BestType;
17579 
17580     BestWidth = Context.getIntWidth(BestType);
17581   }
17582   else if (NumNegativeBits) {
17583     // If there is a negative value, figure out the smallest integer type (of
17584     // int/long/longlong) that fits.
17585     // If it's packed, check also if it fits a char or a short.
17586     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
17587       BestType = Context.SignedCharTy;
17588       BestWidth = CharWidth;
17589     } else if (Packed && NumNegativeBits <= ShortWidth &&
17590                NumPositiveBits < ShortWidth) {
17591       BestType = Context.ShortTy;
17592       BestWidth = ShortWidth;
17593     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
17594       BestType = Context.IntTy;
17595       BestWidth = IntWidth;
17596     } else {
17597       BestWidth = Context.getTargetInfo().getLongWidth();
17598 
17599       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
17600         BestType = Context.LongTy;
17601       } else {
17602         BestWidth = Context.getTargetInfo().getLongLongWidth();
17603 
17604         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
17605           Diag(Enum->getLocation(), diag::ext_enum_too_large);
17606         BestType = Context.LongLongTy;
17607       }
17608     }
17609     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
17610   } else {
17611     // If there is no negative value, figure out the smallest type that fits
17612     // all of the enumerator values.
17613     // If it's packed, check also if it fits a char or a short.
17614     if (Packed && NumPositiveBits <= CharWidth) {
17615       BestType = Context.UnsignedCharTy;
17616       BestPromotionType = Context.IntTy;
17617       BestWidth = CharWidth;
17618     } else if (Packed && NumPositiveBits <= ShortWidth) {
17619       BestType = Context.UnsignedShortTy;
17620       BestPromotionType = Context.IntTy;
17621       BestWidth = ShortWidth;
17622     } else if (NumPositiveBits <= IntWidth) {
17623       BestType = Context.UnsignedIntTy;
17624       BestWidth = IntWidth;
17625       BestPromotionType
17626         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17627                            ? Context.UnsignedIntTy : Context.IntTy;
17628     } else if (NumPositiveBits <=
17629                (BestWidth = Context.getTargetInfo().getLongWidth())) {
17630       BestType = Context.UnsignedLongTy;
17631       BestPromotionType
17632         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17633                            ? Context.UnsignedLongTy : Context.LongTy;
17634     } else {
17635       BestWidth = Context.getTargetInfo().getLongLongWidth();
17636       assert(NumPositiveBits <= BestWidth &&
17637              "How could an initializer get larger than ULL?");
17638       BestType = Context.UnsignedLongLongTy;
17639       BestPromotionType
17640         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17641                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
17642     }
17643   }
17644 
17645   // Loop over all of the enumerator constants, changing their types to match
17646   // the type of the enum if needed.
17647   for (auto *D : Elements) {
17648     auto *ECD = cast_or_null<EnumConstantDecl>(D);
17649     if (!ECD) continue;  // Already issued a diagnostic.
17650 
17651     // Standard C says the enumerators have int type, but we allow, as an
17652     // extension, the enumerators to be larger than int size.  If each
17653     // enumerator value fits in an int, type it as an int, otherwise type it the
17654     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
17655     // that X has type 'int', not 'unsigned'.
17656 
17657     // Determine whether the value fits into an int.
17658     llvm::APSInt InitVal = ECD->getInitVal();
17659 
17660     // If it fits into an integer type, force it.  Otherwise force it to match
17661     // the enum decl type.
17662     QualType NewTy;
17663     unsigned NewWidth;
17664     bool NewSign;
17665     if (!getLangOpts().CPlusPlus &&
17666         !Enum->isFixed() &&
17667         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
17668       NewTy = Context.IntTy;
17669       NewWidth = IntWidth;
17670       NewSign = true;
17671     } else if (ECD->getType() == BestType) {
17672       // Already the right type!
17673       if (getLangOpts().CPlusPlus)
17674         // C++ [dcl.enum]p4: Following the closing brace of an
17675         // enum-specifier, each enumerator has the type of its
17676         // enumeration.
17677         ECD->setType(EnumType);
17678       continue;
17679     } else {
17680       NewTy = BestType;
17681       NewWidth = BestWidth;
17682       NewSign = BestType->isSignedIntegerOrEnumerationType();
17683     }
17684 
17685     // Adjust the APSInt value.
17686     InitVal = InitVal.extOrTrunc(NewWidth);
17687     InitVal.setIsSigned(NewSign);
17688     ECD->setInitVal(InitVal);
17689 
17690     // Adjust the Expr initializer and type.
17691     if (ECD->getInitExpr() &&
17692         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
17693       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
17694                                                 CK_IntegralCast,
17695                                                 ECD->getInitExpr(),
17696                                                 /*base paths*/ nullptr,
17697                                                 VK_RValue));
17698     if (getLangOpts().CPlusPlus)
17699       // C++ [dcl.enum]p4: Following the closing brace of an
17700       // enum-specifier, each enumerator has the type of its
17701       // enumeration.
17702       ECD->setType(EnumType);
17703     else
17704       ECD->setType(NewTy);
17705   }
17706 
17707   Enum->completeDefinition(BestType, BestPromotionType,
17708                            NumPositiveBits, NumNegativeBits);
17709 
17710   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
17711 
17712   if (Enum->isClosedFlag()) {
17713     for (Decl *D : Elements) {
17714       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
17715       if (!ECD) continue;  // Already issued a diagnostic.
17716 
17717       llvm::APSInt InitVal = ECD->getInitVal();
17718       if (InitVal != 0 && !InitVal.isPowerOf2() &&
17719           !IsValueInFlagEnum(Enum, InitVal, true))
17720         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
17721           << ECD << Enum;
17722     }
17723   }
17724 
17725   // Now that the enum type is defined, ensure it's not been underaligned.
17726   if (Enum->hasAttrs())
17727     CheckAlignasUnderalignment(Enum);
17728 }
17729 
17730 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
17731                                   SourceLocation StartLoc,
17732                                   SourceLocation EndLoc) {
17733   StringLiteral *AsmString = cast<StringLiteral>(expr);
17734 
17735   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
17736                                                    AsmString, StartLoc,
17737                                                    EndLoc);
17738   CurContext->addDecl(New);
17739   return New;
17740 }
17741 
17742 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
17743                                       IdentifierInfo* AliasName,
17744                                       SourceLocation PragmaLoc,
17745                                       SourceLocation NameLoc,
17746                                       SourceLocation AliasNameLoc) {
17747   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
17748                                          LookupOrdinaryName);
17749   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
17750                            AttributeCommonInfo::AS_Pragma);
17751   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
17752       Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
17753 
17754   // If a declaration that:
17755   // 1) declares a function or a variable
17756   // 2) has external linkage
17757   // already exists, add a label attribute to it.
17758   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17759     if (isDeclExternC(PrevDecl))
17760       PrevDecl->addAttr(Attr);
17761     else
17762       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
17763           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
17764   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
17765   } else
17766     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
17767 }
17768 
17769 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
17770                              SourceLocation PragmaLoc,
17771                              SourceLocation NameLoc) {
17772   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
17773 
17774   if (PrevDecl) {
17775     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
17776   } else {
17777     (void)WeakUndeclaredIdentifiers.insert(
17778       std::pair<IdentifierInfo*,WeakInfo>
17779         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
17780   }
17781 }
17782 
17783 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
17784                                 IdentifierInfo* AliasName,
17785                                 SourceLocation PragmaLoc,
17786                                 SourceLocation NameLoc,
17787                                 SourceLocation AliasNameLoc) {
17788   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
17789                                     LookupOrdinaryName);
17790   WeakInfo W = WeakInfo(Name, NameLoc);
17791 
17792   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17793     if (!PrevDecl->hasAttr<AliasAttr>())
17794       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
17795         DeclApplyPragmaWeak(TUScope, ND, W);
17796   } else {
17797     (void)WeakUndeclaredIdentifiers.insert(
17798       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
17799   }
17800 }
17801 
17802 Decl *Sema::getObjCDeclContext() const {
17803   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
17804 }
17805 
17806 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD) {
17807   // Templates are emitted when they're instantiated.
17808   if (FD->isDependentContext())
17809     return FunctionEmissionStatus::TemplateDiscarded;
17810 
17811   FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown;
17812   if (LangOpts.OpenMPIsDevice) {
17813     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
17814         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
17815     if (DevTy.hasValue()) {
17816       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
17817         OMPES = FunctionEmissionStatus::OMPDiscarded;
17818       else if (DeviceKnownEmittedFns.count(FD) > 0)
17819         OMPES = FunctionEmissionStatus::Emitted;
17820     }
17821   } else if (LangOpts.OpenMP) {
17822     // In OpenMP 4.5 all the functions are host functions.
17823     if (LangOpts.OpenMP <= 45) {
17824       OMPES = FunctionEmissionStatus::Emitted;
17825     } else {
17826       Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
17827           OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
17828       // In OpenMP 5.0 or above, DevTy may be changed later by
17829       // #pragma omp declare target to(*) device_type(*). Therefore DevTy
17830       // having no value does not imply host. The emission status will be
17831       // checked again at the end of compilation unit.
17832       if (DevTy.hasValue()) {
17833         if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
17834           OMPES = FunctionEmissionStatus::OMPDiscarded;
17835         } else if (DeviceKnownEmittedFns.count(FD) > 0) {
17836           OMPES = FunctionEmissionStatus::Emitted;
17837         }
17838       }
17839     }
17840   }
17841   if (OMPES == FunctionEmissionStatus::OMPDiscarded ||
17842       (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA))
17843     return OMPES;
17844 
17845   if (LangOpts.CUDA) {
17846     // When compiling for device, host functions are never emitted.  Similarly,
17847     // when compiling for host, device and global functions are never emitted.
17848     // (Technically, we do emit a host-side stub for global functions, but this
17849     // doesn't count for our purposes here.)
17850     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
17851     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
17852       return FunctionEmissionStatus::CUDADiscarded;
17853     if (!LangOpts.CUDAIsDevice &&
17854         (T == Sema::CFT_Device || T == Sema::CFT_Global))
17855       return FunctionEmissionStatus::CUDADiscarded;
17856 
17857     // Check whether this function is externally visible -- if so, it's
17858     // known-emitted.
17859     //
17860     // We have to check the GVA linkage of the function's *definition* -- if we
17861     // only have a declaration, we don't know whether or not the function will
17862     // be emitted, because (say) the definition could include "inline".
17863     FunctionDecl *Def = FD->getDefinition();
17864 
17865     if (Def &&
17866         !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def))
17867         && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted))
17868       return FunctionEmissionStatus::Emitted;
17869   }
17870 
17871   // Otherwise, the function is known-emitted if it's in our set of
17872   // known-emitted functions.
17873   return (DeviceKnownEmittedFns.count(FD) > 0)
17874              ? FunctionEmissionStatus::Emitted
17875              : FunctionEmissionStatus::Unknown;
17876 }
17877 
17878 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
17879   // Host-side references to a __global__ function refer to the stub, so the
17880   // function itself is never emitted and therefore should not be marked.
17881   // If we have host fn calls kernel fn calls host+device, the HD function
17882   // does not get instantiated on the host. We model this by omitting at the
17883   // call to the kernel from the callgraph. This ensures that, when compiling
17884   // for host, only HD functions actually called from the host get marked as
17885   // known-emitted.
17886   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
17887          IdentifyCUDATarget(Callee) == CFT_Global;
17888 }
17889