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
849 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
850                    SourceLocation NameLoc, const Token &NextToken,
851                    bool IsAddressOfOperand, CorrectionCandidateCallback *CCC) {
852   DeclarationNameInfo NameInfo(Name, NameLoc);
853   ObjCMethodDecl *CurMethod = getCurMethodDecl();
854 
855   if (NextToken.is(tok::coloncolon)) {
856     NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
857     BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
858   } else if (getLangOpts().CPlusPlus && SS.isSet() &&
859              isCurrentClassName(*Name, S, &SS)) {
860     // Per [class.qual]p2, this names the constructors of SS, not the
861     // injected-class-name. We don't have a classification for that.
862     // There's not much point caching this result, since the parser
863     // will reject it later.
864     return NameClassification::Unknown();
865   }
866 
867   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
868   LookupParsedName(Result, S, &SS, !CurMethod);
869 
870   // For unqualified lookup in a class template in MSVC mode, look into
871   // dependent base classes where the primary class template is known.
872   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
873     if (ParsedType TypeInBase =
874             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
875       return TypeInBase;
876   }
877 
878   // Perform lookup for Objective-C instance variables (including automatically
879   // synthesized instance variables), if we're in an Objective-C method.
880   // FIXME: This lookup really, really needs to be folded in to the normal
881   // unqualified lookup mechanism.
882   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
883     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
884     if (E.get() || E.isInvalid())
885       return E;
886   }
887 
888   bool SecondTry = false;
889   bool IsFilteredTemplateName = false;
890 
891 Corrected:
892   switch (Result.getResultKind()) {
893   case LookupResult::NotFound:
894     // If an unqualified-id is followed by a '(', then we have a function
895     // call.
896     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
897       // In C++, this is an ADL-only call.
898       // FIXME: Reference?
899       if (getLangOpts().CPlusPlus)
900         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
901 
902       // C90 6.3.2.2:
903       //   If the expression that precedes the parenthesized argument list in a
904       //   function call consists solely of an identifier, and if no
905       //   declaration is visible for this identifier, the identifier is
906       //   implicitly declared exactly as if, in the innermost block containing
907       //   the function call, the declaration
908       //
909       //     extern int identifier ();
910       //
911       //   appeared.
912       //
913       // We also allow this in C99 as an extension.
914       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
915         Result.addDecl(D);
916         Result.resolveKind();
917         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
918       }
919     }
920 
921     if (getLangOpts().CPlusPlus2a && !SS.isSet() && NextToken.is(tok::less)) {
922       // In C++20 onwards, this could be an ADL-only call to a function
923       // template, and we're required to assume that this is a template name.
924       //
925       // FIXME: Find a way to still do typo correction in this case.
926       TemplateName Template =
927           Context.getAssumedTemplateName(NameInfo.getName());
928       return NameClassification::UndeclaredTemplate(Template);
929     }
930 
931     // In C, we first see whether there is a tag type by the same name, in
932     // which case it's likely that the user just forgot to write "enum",
933     // "struct", or "union".
934     if (!getLangOpts().CPlusPlus && !SecondTry &&
935         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
936       break;
937     }
938 
939     // Perform typo correction to determine if there is another name that is
940     // close to this name.
941     if (!SecondTry && CCC) {
942       SecondTry = true;
943       if (TypoCorrection Corrected =
944               CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
945                           &SS, *CCC, CTK_ErrorRecovery)) {
946         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
947         unsigned QualifiedDiag = diag::err_no_member_suggest;
948 
949         NamedDecl *FirstDecl = Corrected.getFoundDecl();
950         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
951         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
952             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
953           UnqualifiedDiag = diag::err_no_template_suggest;
954           QualifiedDiag = diag::err_no_member_template_suggest;
955         } else if (UnderlyingFirstDecl &&
956                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
957                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
958                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
959           UnqualifiedDiag = diag::err_unknown_typename_suggest;
960           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
961         }
962 
963         if (SS.isEmpty()) {
964           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
965         } else {// FIXME: is this even reachable? Test it.
966           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
967           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
968                                   Name->getName().equals(CorrectedStr);
969           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
970                                     << Name << computeDeclContext(SS, false)
971                                     << DroppedSpecifier << SS.getRange());
972         }
973 
974         // Update the name, so that the caller has the new name.
975         Name = Corrected.getCorrectionAsIdentifierInfo();
976 
977         // Typo correction corrected to a keyword.
978         if (Corrected.isKeyword())
979           return Name;
980 
981         // Also update the LookupResult...
982         // FIXME: This should probably go away at some point
983         Result.clear();
984         Result.setLookupName(Corrected.getCorrection());
985         if (FirstDecl)
986           Result.addDecl(FirstDecl);
987 
988         // If we found an Objective-C instance variable, let
989         // LookupInObjCMethod build the appropriate expression to
990         // reference the ivar.
991         // FIXME: This is a gross hack.
992         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
993           Result.clear();
994           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
995           return E;
996         }
997 
998         goto Corrected;
999       }
1000     }
1001 
1002     // We failed to correct; just fall through and let the parser deal with it.
1003     Result.suppressDiagnostics();
1004     return NameClassification::Unknown();
1005 
1006   case LookupResult::NotFoundInCurrentInstantiation: {
1007     // We performed name lookup into the current instantiation, and there were
1008     // dependent bases, so we treat this result the same way as any other
1009     // dependent nested-name-specifier.
1010 
1011     // C++ [temp.res]p2:
1012     //   A name used in a template declaration or definition and that is
1013     //   dependent on a template-parameter is assumed not to name a type
1014     //   unless the applicable name lookup finds a type name or the name is
1015     //   qualified by the keyword typename.
1016     //
1017     // FIXME: If the next token is '<', we might want to ask the parser to
1018     // perform some heroics to see if we actually have a
1019     // template-argument-list, which would indicate a missing 'template'
1020     // keyword here.
1021     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1022                                       NameInfo, IsAddressOfOperand,
1023                                       /*TemplateArgs=*/nullptr);
1024   }
1025 
1026   case LookupResult::Found:
1027   case LookupResult::FoundOverloaded:
1028   case LookupResult::FoundUnresolvedValue:
1029     break;
1030 
1031   case LookupResult::Ambiguous:
1032     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1033         hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1034                                       /*AllowDependent=*/false)) {
1035       // C++ [temp.local]p3:
1036       //   A lookup that finds an injected-class-name (10.2) can result in an
1037       //   ambiguity in certain cases (for example, if it is found in more than
1038       //   one base class). If all of the injected-class-names that are found
1039       //   refer to specializations of the same class template, and if the name
1040       //   is followed by a template-argument-list, the reference refers to the
1041       //   class template itself and not a specialization thereof, and is not
1042       //   ambiguous.
1043       //
1044       // This filtering can make an ambiguous result into an unambiguous one,
1045       // so try again after filtering out template names.
1046       FilterAcceptableTemplateNames(Result);
1047       if (!Result.isAmbiguous()) {
1048         IsFilteredTemplateName = true;
1049         break;
1050       }
1051     }
1052 
1053     // Diagnose the ambiguity and return an error.
1054     return NameClassification::Error();
1055   }
1056 
1057   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1058       (IsFilteredTemplateName ||
1059        hasAnyAcceptableTemplateNames(
1060            Result, /*AllowFunctionTemplates=*/true,
1061            /*AllowDependent=*/false,
1062            /*AllowNonTemplateFunctions*/ !SS.isSet() &&
1063                getLangOpts().CPlusPlus2a))) {
1064     // C++ [temp.names]p3:
1065     //   After name lookup (3.4) finds that a name is a template-name or that
1066     //   an operator-function-id or a literal- operator-id refers to a set of
1067     //   overloaded functions any member of which is a function template if
1068     //   this is followed by a <, the < is always taken as the delimiter of a
1069     //   template-argument-list and never as the less-than operator.
1070     // C++2a [temp.names]p2:
1071     //   A name is also considered to refer to a template if it is an
1072     //   unqualified-id followed by a < and name lookup finds either one
1073     //   or more functions or finds nothing.
1074     if (!IsFilteredTemplateName)
1075       FilterAcceptableTemplateNames(Result);
1076 
1077     bool IsFunctionTemplate;
1078     bool IsVarTemplate;
1079     TemplateName Template;
1080     if (Result.end() - Result.begin() > 1) {
1081       IsFunctionTemplate = true;
1082       Template = Context.getOverloadedTemplateName(Result.begin(),
1083                                                    Result.end());
1084     } else if (!Result.empty()) {
1085       auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1086           *Result.begin(), /*AllowFunctionTemplates=*/true,
1087           /*AllowDependent=*/false));
1088       IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1089       IsVarTemplate = isa<VarTemplateDecl>(TD);
1090 
1091       if (SS.isSet() && !SS.isInvalid())
1092         Template =
1093             Context.getQualifiedTemplateName(SS.getScopeRep(),
1094                                              /*TemplateKeyword=*/false, TD);
1095       else
1096         Template = TemplateName(TD);
1097     } else {
1098       // All results were non-template functions. This is a function template
1099       // name.
1100       IsFunctionTemplate = true;
1101       Template = Context.getAssumedTemplateName(NameInfo.getName());
1102     }
1103 
1104     if (IsFunctionTemplate) {
1105       // Function templates always go through overload resolution, at which
1106       // point we'll perform the various checks (e.g., accessibility) we need
1107       // to based on which function we selected.
1108       Result.suppressDiagnostics();
1109 
1110       return NameClassification::FunctionTemplate(Template);
1111     }
1112 
1113     return IsVarTemplate ? NameClassification::VarTemplate(Template)
1114                          : NameClassification::TypeTemplate(Template);
1115   }
1116 
1117   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1118   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1119     DiagnoseUseOfDecl(Type, NameLoc);
1120     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1121     QualType T = Context.getTypeDeclType(Type);
1122     if (SS.isNotEmpty())
1123       return buildNestedType(*this, SS, T, NameLoc);
1124     return ParsedType::make(T);
1125   }
1126 
1127   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1128   if (!Class) {
1129     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1130     if (ObjCCompatibleAliasDecl *Alias =
1131             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1132       Class = Alias->getClassInterface();
1133   }
1134 
1135   if (Class) {
1136     DiagnoseUseOfDecl(Class, NameLoc);
1137 
1138     if (NextToken.is(tok::period)) {
1139       // Interface. <something> is parsed as a property reference expression.
1140       // Just return "unknown" as a fall-through for now.
1141       Result.suppressDiagnostics();
1142       return NameClassification::Unknown();
1143     }
1144 
1145     QualType T = Context.getObjCInterfaceType(Class);
1146     return ParsedType::make(T);
1147   }
1148 
1149   // We can have a type template here if we're classifying a template argument.
1150   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1151       !isa<VarTemplateDecl>(FirstDecl))
1152     return NameClassification::TypeTemplate(
1153         TemplateName(cast<TemplateDecl>(FirstDecl)));
1154 
1155   // Check for a tag type hidden by a non-type decl in a few cases where it
1156   // seems likely a type is wanted instead of the non-type that was found.
1157   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1158   if ((NextToken.is(tok::identifier) ||
1159        (NextIsOp &&
1160         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1161       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1162     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1163     DiagnoseUseOfDecl(Type, NameLoc);
1164     QualType T = Context.getTypeDeclType(Type);
1165     if (SS.isNotEmpty())
1166       return buildNestedType(*this, SS, T, NameLoc);
1167     return ParsedType::make(T);
1168   }
1169 
1170   if (FirstDecl->isCXXClassMember())
1171     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1172                                            nullptr, S);
1173 
1174   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1175   return BuildDeclarationNameExpr(SS, Result, ADL);
1176 }
1177 
1178 Sema::TemplateNameKindForDiagnostics
1179 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1180   auto *TD = Name.getAsTemplateDecl();
1181   if (!TD)
1182     return TemplateNameKindForDiagnostics::DependentTemplate;
1183   if (isa<ClassTemplateDecl>(TD))
1184     return TemplateNameKindForDiagnostics::ClassTemplate;
1185   if (isa<FunctionTemplateDecl>(TD))
1186     return TemplateNameKindForDiagnostics::FunctionTemplate;
1187   if (isa<VarTemplateDecl>(TD))
1188     return TemplateNameKindForDiagnostics::VarTemplate;
1189   if (isa<TypeAliasTemplateDecl>(TD))
1190     return TemplateNameKindForDiagnostics::AliasTemplate;
1191   if (isa<TemplateTemplateParmDecl>(TD))
1192     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1193   if (isa<ConceptDecl>(TD))
1194     return TemplateNameKindForDiagnostics::Concept;
1195   return TemplateNameKindForDiagnostics::DependentTemplate;
1196 }
1197 
1198 // Determines the context to return to after temporarily entering a
1199 // context.  This depends in an unnecessarily complicated way on the
1200 // exact ordering of callbacks from the parser.
1201 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1202 
1203   // Functions defined inline within classes aren't parsed until we've
1204   // finished parsing the top-level class, so the top-level class is
1205   // the context we'll need to return to.
1206   // A Lambda call operator whose parent is a class must not be treated
1207   // as an inline member function.  A Lambda can be used legally
1208   // either as an in-class member initializer or a default argument.  These
1209   // are parsed once the class has been marked complete and so the containing
1210   // context would be the nested class (when the lambda is defined in one);
1211   // If the class is not complete, then the lambda is being used in an
1212   // ill-formed fashion (such as to specify the width of a bit-field, or
1213   // in an array-bound) - in which case we still want to return the
1214   // lexically containing DC (which could be a nested class).
1215   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1216     DC = DC->getLexicalParent();
1217 
1218     // A function not defined within a class will always return to its
1219     // lexical context.
1220     if (!isa<CXXRecordDecl>(DC))
1221       return DC;
1222 
1223     // A C++ inline method/friend is parsed *after* the topmost class
1224     // it was declared in is fully parsed ("complete");  the topmost
1225     // class is the context we need to return to.
1226     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1227       DC = RD;
1228 
1229     // Return the declaration context of the topmost class the inline method is
1230     // declared in.
1231     return DC;
1232   }
1233 
1234   return DC->getLexicalParent();
1235 }
1236 
1237 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1238   assert(getContainingDC(DC) == CurContext &&
1239       "The next DeclContext should be lexically contained in the current one.");
1240   CurContext = DC;
1241   S->setEntity(DC);
1242 }
1243 
1244 void Sema::PopDeclContext() {
1245   assert(CurContext && "DeclContext imbalance!");
1246 
1247   CurContext = getContainingDC(CurContext);
1248   assert(CurContext && "Popped translation unit!");
1249 }
1250 
1251 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1252                                                                     Decl *D) {
1253   // Unlike PushDeclContext, the context to which we return is not necessarily
1254   // the containing DC of TD, because the new context will be some pre-existing
1255   // TagDecl definition instead of a fresh one.
1256   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1257   CurContext = cast<TagDecl>(D)->getDefinition();
1258   assert(CurContext && "skipping definition of undefined tag");
1259   // Start lookups from the parent of the current context; we don't want to look
1260   // into the pre-existing complete definition.
1261   S->setEntity(CurContext->getLookupParent());
1262   return Result;
1263 }
1264 
1265 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1266   CurContext = static_cast<decltype(CurContext)>(Context);
1267 }
1268 
1269 /// EnterDeclaratorContext - Used when we must lookup names in the context
1270 /// of a declarator's nested name specifier.
1271 ///
1272 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1273   // C++0x [basic.lookup.unqual]p13:
1274   //   A name used in the definition of a static data member of class
1275   //   X (after the qualified-id of the static member) is looked up as
1276   //   if the name was used in a member function of X.
1277   // C++0x [basic.lookup.unqual]p14:
1278   //   If a variable member of a namespace is defined outside of the
1279   //   scope of its namespace then any name used in the definition of
1280   //   the variable member (after the declarator-id) is looked up as
1281   //   if the definition of the variable member occurred in its
1282   //   namespace.
1283   // Both of these imply that we should push a scope whose context
1284   // is the semantic context of the declaration.  We can't use
1285   // PushDeclContext here because that context is not necessarily
1286   // lexically contained in the current context.  Fortunately,
1287   // the containing scope should have the appropriate information.
1288 
1289   assert(!S->getEntity() && "scope already has entity");
1290 
1291 #ifndef NDEBUG
1292   Scope *Ancestor = S->getParent();
1293   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1294   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1295 #endif
1296 
1297   CurContext = DC;
1298   S->setEntity(DC);
1299 }
1300 
1301 void Sema::ExitDeclaratorContext(Scope *S) {
1302   assert(S->getEntity() == CurContext && "Context imbalance!");
1303 
1304   // Switch back to the lexical context.  The safety of this is
1305   // enforced by an assert in EnterDeclaratorContext.
1306   Scope *Ancestor = S->getParent();
1307   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1308   CurContext = Ancestor->getEntity();
1309 
1310   // We don't need to do anything with the scope, which is going to
1311   // disappear.
1312 }
1313 
1314 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1315   // We assume that the caller has already called
1316   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1317   FunctionDecl *FD = D->getAsFunction();
1318   if (!FD)
1319     return;
1320 
1321   // Same implementation as PushDeclContext, but enters the context
1322   // from the lexical parent, rather than the top-level class.
1323   assert(CurContext == FD->getLexicalParent() &&
1324     "The next DeclContext should be lexically contained in the current one.");
1325   CurContext = FD;
1326   S->setEntity(CurContext);
1327 
1328   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1329     ParmVarDecl *Param = FD->getParamDecl(P);
1330     // If the parameter has an identifier, then add it to the scope
1331     if (Param->getIdentifier()) {
1332       S->AddDecl(Param);
1333       IdResolver.AddDecl(Param);
1334     }
1335   }
1336 }
1337 
1338 void Sema::ActOnExitFunctionContext() {
1339   // Same implementation as PopDeclContext, but returns to the lexical parent,
1340   // rather than the top-level class.
1341   assert(CurContext && "DeclContext imbalance!");
1342   CurContext = CurContext->getLexicalParent();
1343   assert(CurContext && "Popped translation unit!");
1344 }
1345 
1346 /// Determine whether we allow overloading of the function
1347 /// PrevDecl with another declaration.
1348 ///
1349 /// This routine determines whether overloading is possible, not
1350 /// whether some new function is actually an overload. It will return
1351 /// true in C++ (where we can always provide overloads) or, as an
1352 /// extension, in C when the previous function is already an
1353 /// overloaded function declaration or has the "overloadable"
1354 /// attribute.
1355 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1356                                        ASTContext &Context,
1357                                        const FunctionDecl *New) {
1358   if (Context.getLangOpts().CPlusPlus)
1359     return true;
1360 
1361   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1362     return true;
1363 
1364   return Previous.getResultKind() == LookupResult::Found &&
1365          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1366           New->hasAttr<OverloadableAttr>());
1367 }
1368 
1369 /// Add this decl to the scope shadowed decl chains.
1370 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1371   // Move up the scope chain until we find the nearest enclosing
1372   // non-transparent context. The declaration will be introduced into this
1373   // scope.
1374   while (S->getEntity() && S->getEntity()->isTransparentContext())
1375     S = S->getParent();
1376 
1377   // Add scoped declarations into their context, so that they can be
1378   // found later. Declarations without a context won't be inserted
1379   // into any context.
1380   if (AddToContext)
1381     CurContext->addDecl(D);
1382 
1383   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1384   // are function-local declarations.
1385   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1386       !D->getDeclContext()->getRedeclContext()->Equals(
1387         D->getLexicalDeclContext()->getRedeclContext()) &&
1388       !D->getLexicalDeclContext()->isFunctionOrMethod())
1389     return;
1390 
1391   // Template instantiations should also not be pushed into scope.
1392   if (isa<FunctionDecl>(D) &&
1393       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1394     return;
1395 
1396   // If this replaces anything in the current scope,
1397   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1398                                IEnd = IdResolver.end();
1399   for (; I != IEnd; ++I) {
1400     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1401       S->RemoveDecl(*I);
1402       IdResolver.RemoveDecl(*I);
1403 
1404       // Should only need to replace one decl.
1405       break;
1406     }
1407   }
1408 
1409   S->AddDecl(D);
1410 
1411   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1412     // Implicitly-generated labels may end up getting generated in an order that
1413     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1414     // the label at the appropriate place in the identifier chain.
1415     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1416       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1417       if (IDC == CurContext) {
1418         if (!S->isDeclScope(*I))
1419           continue;
1420       } else if (IDC->Encloses(CurContext))
1421         break;
1422     }
1423 
1424     IdResolver.InsertDeclAfter(I, D);
1425   } else {
1426     IdResolver.AddDecl(D);
1427   }
1428 }
1429 
1430 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1431                          bool AllowInlineNamespace) {
1432   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1433 }
1434 
1435 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1436   DeclContext *TargetDC = DC->getPrimaryContext();
1437   do {
1438     if (DeclContext *ScopeDC = S->getEntity())
1439       if (ScopeDC->getPrimaryContext() == TargetDC)
1440         return S;
1441   } while ((S = S->getParent()));
1442 
1443   return nullptr;
1444 }
1445 
1446 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1447                                             DeclContext*,
1448                                             ASTContext&);
1449 
1450 /// Filters out lookup results that don't fall within the given scope
1451 /// as determined by isDeclInScope.
1452 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1453                                 bool ConsiderLinkage,
1454                                 bool AllowInlineNamespace) {
1455   LookupResult::Filter F = R.makeFilter();
1456   while (F.hasNext()) {
1457     NamedDecl *D = F.next();
1458 
1459     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1460       continue;
1461 
1462     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1463       continue;
1464 
1465     F.erase();
1466   }
1467 
1468   F.done();
1469 }
1470 
1471 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1472 /// have compatible owning modules.
1473 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1474   // FIXME: The Modules TS is not clear about how friend declarations are
1475   // to be treated. It's not meaningful to have different owning modules for
1476   // linkage in redeclarations of the same entity, so for now allow the
1477   // redeclaration and change the owning modules to match.
1478   if (New->getFriendObjectKind() &&
1479       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1480     New->setLocalOwningModule(Old->getOwningModule());
1481     makeMergedDefinitionVisible(New);
1482     return false;
1483   }
1484 
1485   Module *NewM = New->getOwningModule();
1486   Module *OldM = Old->getOwningModule();
1487 
1488   if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1489     NewM = NewM->Parent;
1490   if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1491     OldM = OldM->Parent;
1492 
1493   if (NewM == OldM)
1494     return false;
1495 
1496   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1497   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1498   if (NewIsModuleInterface || OldIsModuleInterface) {
1499     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1500     //   if a declaration of D [...] appears in the purview of a module, all
1501     //   other such declarations shall appear in the purview of the same module
1502     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1503       << New
1504       << NewIsModuleInterface
1505       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1506       << OldIsModuleInterface
1507       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1508     Diag(Old->getLocation(), diag::note_previous_declaration);
1509     New->setInvalidDecl();
1510     return true;
1511   }
1512 
1513   return false;
1514 }
1515 
1516 static bool isUsingDecl(NamedDecl *D) {
1517   return isa<UsingShadowDecl>(D) ||
1518          isa<UnresolvedUsingTypenameDecl>(D) ||
1519          isa<UnresolvedUsingValueDecl>(D);
1520 }
1521 
1522 /// Removes using shadow declarations from the lookup results.
1523 static void RemoveUsingDecls(LookupResult &R) {
1524   LookupResult::Filter F = R.makeFilter();
1525   while (F.hasNext())
1526     if (isUsingDecl(F.next()))
1527       F.erase();
1528 
1529   F.done();
1530 }
1531 
1532 /// Check for this common pattern:
1533 /// @code
1534 /// class S {
1535 ///   S(const S&); // DO NOT IMPLEMENT
1536 ///   void operator=(const S&); // DO NOT IMPLEMENT
1537 /// };
1538 /// @endcode
1539 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1540   // FIXME: Should check for private access too but access is set after we get
1541   // the decl here.
1542   if (D->doesThisDeclarationHaveABody())
1543     return false;
1544 
1545   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1546     return CD->isCopyConstructor();
1547   return D->isCopyAssignmentOperator();
1548 }
1549 
1550 // We need this to handle
1551 //
1552 // typedef struct {
1553 //   void *foo() { return 0; }
1554 // } A;
1555 //
1556 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1557 // for example. If 'A', foo will have external linkage. If we have '*A',
1558 // foo will have no linkage. Since we can't know until we get to the end
1559 // of the typedef, this function finds out if D might have non-external linkage.
1560 // Callers should verify at the end of the TU if it D has external linkage or
1561 // not.
1562 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1563   const DeclContext *DC = D->getDeclContext();
1564   while (!DC->isTranslationUnit()) {
1565     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1566       if (!RD->hasNameForLinkage())
1567         return true;
1568     }
1569     DC = DC->getParent();
1570   }
1571 
1572   return !D->isExternallyVisible();
1573 }
1574 
1575 // FIXME: This needs to be refactored; some other isInMainFile users want
1576 // these semantics.
1577 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1578   if (S.TUKind != TU_Complete)
1579     return false;
1580   return S.SourceMgr.isInMainFile(Loc);
1581 }
1582 
1583 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1584   assert(D);
1585 
1586   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1587     return false;
1588 
1589   // Ignore all entities declared within templates, and out-of-line definitions
1590   // of members of class templates.
1591   if (D->getDeclContext()->isDependentContext() ||
1592       D->getLexicalDeclContext()->isDependentContext())
1593     return false;
1594 
1595   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1596     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1597       return false;
1598     // A non-out-of-line declaration of a member specialization was implicitly
1599     // instantiated; it's the out-of-line declaration that we're interested in.
1600     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1601         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1602       return false;
1603 
1604     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1605       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1606         return false;
1607     } else {
1608       // 'static inline' functions are defined in headers; don't warn.
1609       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1610         return false;
1611     }
1612 
1613     if (FD->doesThisDeclarationHaveABody() &&
1614         Context.DeclMustBeEmitted(FD))
1615       return false;
1616   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1617     // Constants and utility variables are defined in headers with internal
1618     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1619     // like "inline".)
1620     if (!isMainFileLoc(*this, VD->getLocation()))
1621       return false;
1622 
1623     if (Context.DeclMustBeEmitted(VD))
1624       return false;
1625 
1626     if (VD->isStaticDataMember() &&
1627         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1628       return false;
1629     if (VD->isStaticDataMember() &&
1630         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1631         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1632       return false;
1633 
1634     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1635       return false;
1636   } else {
1637     return false;
1638   }
1639 
1640   // Only warn for unused decls internal to the translation unit.
1641   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1642   // for inline functions defined in the main source file, for instance.
1643   return mightHaveNonExternalLinkage(D);
1644 }
1645 
1646 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1647   if (!D)
1648     return;
1649 
1650   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1651     const FunctionDecl *First = FD->getFirstDecl();
1652     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1653       return; // First should already be in the vector.
1654   }
1655 
1656   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1657     const VarDecl *First = VD->getFirstDecl();
1658     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1659       return; // First should already be in the vector.
1660   }
1661 
1662   if (ShouldWarnIfUnusedFileScopedDecl(D))
1663     UnusedFileScopedDecls.push_back(D);
1664 }
1665 
1666 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1667   if (D->isInvalidDecl())
1668     return false;
1669 
1670   bool Referenced = false;
1671   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1672     // For a decomposition declaration, warn if none of the bindings are
1673     // referenced, instead of if the variable itself is referenced (which
1674     // it is, by the bindings' expressions).
1675     for (auto *BD : DD->bindings()) {
1676       if (BD->isReferenced()) {
1677         Referenced = true;
1678         break;
1679       }
1680     }
1681   } else if (!D->getDeclName()) {
1682     return false;
1683   } else if (D->isReferenced() || D->isUsed()) {
1684     Referenced = true;
1685   }
1686 
1687   if (Referenced || D->hasAttr<UnusedAttr>() ||
1688       D->hasAttr<ObjCPreciseLifetimeAttr>())
1689     return false;
1690 
1691   if (isa<LabelDecl>(D))
1692     return true;
1693 
1694   // Except for labels, we only care about unused decls that are local to
1695   // functions.
1696   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1697   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1698     // For dependent types, the diagnostic is deferred.
1699     WithinFunction =
1700         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1701   if (!WithinFunction)
1702     return false;
1703 
1704   if (isa<TypedefNameDecl>(D))
1705     return true;
1706 
1707   // White-list anything that isn't a local variable.
1708   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1709     return false;
1710 
1711   // Types of valid local variables should be complete, so this should succeed.
1712   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1713 
1714     // White-list anything with an __attribute__((unused)) type.
1715     const auto *Ty = VD->getType().getTypePtr();
1716 
1717     // Only look at the outermost level of typedef.
1718     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1719       if (TT->getDecl()->hasAttr<UnusedAttr>())
1720         return false;
1721     }
1722 
1723     // If we failed to complete the type for some reason, or if the type is
1724     // dependent, don't diagnose the variable.
1725     if (Ty->isIncompleteType() || Ty->isDependentType())
1726       return false;
1727 
1728     // Look at the element type to ensure that the warning behaviour is
1729     // consistent for both scalars and arrays.
1730     Ty = Ty->getBaseElementTypeUnsafe();
1731 
1732     if (const TagType *TT = Ty->getAs<TagType>()) {
1733       const TagDecl *Tag = TT->getDecl();
1734       if (Tag->hasAttr<UnusedAttr>())
1735         return false;
1736 
1737       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1738         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1739           return false;
1740 
1741         if (const Expr *Init = VD->getInit()) {
1742           if (const ExprWithCleanups *Cleanups =
1743                   dyn_cast<ExprWithCleanups>(Init))
1744             Init = Cleanups->getSubExpr();
1745           const CXXConstructExpr *Construct =
1746             dyn_cast<CXXConstructExpr>(Init);
1747           if (Construct && !Construct->isElidable()) {
1748             CXXConstructorDecl *CD = Construct->getConstructor();
1749             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1750                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1751               return false;
1752           }
1753         }
1754       }
1755     }
1756 
1757     // TODO: __attribute__((unused)) templates?
1758   }
1759 
1760   return true;
1761 }
1762 
1763 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1764                                      FixItHint &Hint) {
1765   if (isa<LabelDecl>(D)) {
1766     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1767         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1768         true);
1769     if (AfterColon.isInvalid())
1770       return;
1771     Hint = FixItHint::CreateRemoval(
1772         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1773   }
1774 }
1775 
1776 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1777   if (D->getTypeForDecl()->isDependentType())
1778     return;
1779 
1780   for (auto *TmpD : D->decls()) {
1781     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1782       DiagnoseUnusedDecl(T);
1783     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1784       DiagnoseUnusedNestedTypedefs(R);
1785   }
1786 }
1787 
1788 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1789 /// unless they are marked attr(unused).
1790 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1791   if (!ShouldDiagnoseUnusedDecl(D))
1792     return;
1793 
1794   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1795     // typedefs can be referenced later on, so the diagnostics are emitted
1796     // at end-of-translation-unit.
1797     UnusedLocalTypedefNameCandidates.insert(TD);
1798     return;
1799   }
1800 
1801   FixItHint Hint;
1802   GenerateFixForUnusedDecl(D, Context, Hint);
1803 
1804   unsigned DiagID;
1805   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1806     DiagID = diag::warn_unused_exception_param;
1807   else if (isa<LabelDecl>(D))
1808     DiagID = diag::warn_unused_label;
1809   else
1810     DiagID = diag::warn_unused_variable;
1811 
1812   Diag(D->getLocation(), DiagID) << D << Hint;
1813 }
1814 
1815 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1816   // Verify that we have no forward references left.  If so, there was a goto
1817   // or address of a label taken, but no definition of it.  Label fwd
1818   // definitions are indicated with a null substmt which is also not a resolved
1819   // MS inline assembly label name.
1820   bool Diagnose = false;
1821   if (L->isMSAsmLabel())
1822     Diagnose = !L->isResolvedMSAsmLabel();
1823   else
1824     Diagnose = L->getStmt() == nullptr;
1825   if (Diagnose)
1826     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1827 }
1828 
1829 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1830   S->mergeNRVOIntoParent();
1831 
1832   if (S->decl_empty()) return;
1833   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1834          "Scope shouldn't contain decls!");
1835 
1836   for (auto *TmpD : S->decls()) {
1837     assert(TmpD && "This decl didn't get pushed??");
1838 
1839     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1840     NamedDecl *D = cast<NamedDecl>(TmpD);
1841 
1842     // Diagnose unused variables in this scope.
1843     if (!S->hasUnrecoverableErrorOccurred()) {
1844       DiagnoseUnusedDecl(D);
1845       if (const auto *RD = dyn_cast<RecordDecl>(D))
1846         DiagnoseUnusedNestedTypedefs(RD);
1847     }
1848 
1849     if (!D->getDeclName()) continue;
1850 
1851     // If this was a forward reference to a label, verify it was defined.
1852     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1853       CheckPoppedLabel(LD, *this);
1854 
1855     // Remove this name from our lexical scope, and warn on it if we haven't
1856     // already.
1857     IdResolver.RemoveDecl(D);
1858     auto ShadowI = ShadowingDecls.find(D);
1859     if (ShadowI != ShadowingDecls.end()) {
1860       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1861         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1862             << D << FD << FD->getParent();
1863         Diag(FD->getLocation(), diag::note_previous_declaration);
1864       }
1865       ShadowingDecls.erase(ShadowI);
1866     }
1867   }
1868 }
1869 
1870 /// Look for an Objective-C class in the translation unit.
1871 ///
1872 /// \param Id The name of the Objective-C class we're looking for. If
1873 /// typo-correction fixes this name, the Id will be updated
1874 /// to the fixed name.
1875 ///
1876 /// \param IdLoc The location of the name in the translation unit.
1877 ///
1878 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1879 /// if there is no class with the given name.
1880 ///
1881 /// \returns The declaration of the named Objective-C class, or NULL if the
1882 /// class could not be found.
1883 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1884                                               SourceLocation IdLoc,
1885                                               bool DoTypoCorrection) {
1886   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1887   // creation from this context.
1888   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1889 
1890   if (!IDecl && DoTypoCorrection) {
1891     // Perform typo correction at the given location, but only if we
1892     // find an Objective-C class name.
1893     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
1894     if (TypoCorrection C =
1895             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
1896                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
1897       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1898       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1899       Id = IDecl->getIdentifier();
1900     }
1901   }
1902   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1903   // This routine must always return a class definition, if any.
1904   if (Def && Def->getDefinition())
1905       Def = Def->getDefinition();
1906   return Def;
1907 }
1908 
1909 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1910 /// from S, where a non-field would be declared. This routine copes
1911 /// with the difference between C and C++ scoping rules in structs and
1912 /// unions. For example, the following code is well-formed in C but
1913 /// ill-formed in C++:
1914 /// @code
1915 /// struct S6 {
1916 ///   enum { BAR } e;
1917 /// };
1918 ///
1919 /// void test_S6() {
1920 ///   struct S6 a;
1921 ///   a.e = BAR;
1922 /// }
1923 /// @endcode
1924 /// For the declaration of BAR, this routine will return a different
1925 /// scope. The scope S will be the scope of the unnamed enumeration
1926 /// within S6. In C++, this routine will return the scope associated
1927 /// with S6, because the enumeration's scope is a transparent
1928 /// context but structures can contain non-field names. In C, this
1929 /// routine will return the translation unit scope, since the
1930 /// enumeration's scope is a transparent context and structures cannot
1931 /// contain non-field names.
1932 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1933   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1934          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1935          (S->isClassScope() && !getLangOpts().CPlusPlus))
1936     S = S->getParent();
1937   return S;
1938 }
1939 
1940 /// Looks up the declaration of "struct objc_super" and
1941 /// saves it for later use in building builtin declaration of
1942 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1943 /// pre-existing declaration exists no action takes place.
1944 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1945                                         IdentifierInfo *II) {
1946   if (!II->isStr("objc_msgSendSuper"))
1947     return;
1948   ASTContext &Context = ThisSema.Context;
1949 
1950   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1951                       SourceLocation(), Sema::LookupTagName);
1952   ThisSema.LookupName(Result, S);
1953   if (Result.getResultKind() == LookupResult::Found)
1954     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1955       Context.setObjCSuperType(Context.getTagDeclType(TD));
1956 }
1957 
1958 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
1959                                ASTContext::GetBuiltinTypeError Error) {
1960   switch (Error) {
1961   case ASTContext::GE_None:
1962     return "";
1963   case ASTContext::GE_Missing_type:
1964     return BuiltinInfo.getHeaderName(ID);
1965   case ASTContext::GE_Missing_stdio:
1966     return "stdio.h";
1967   case ASTContext::GE_Missing_setjmp:
1968     return "setjmp.h";
1969   case ASTContext::GE_Missing_ucontext:
1970     return "ucontext.h";
1971   }
1972   llvm_unreachable("unhandled error kind");
1973 }
1974 
1975 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1976 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1977 /// if we're creating this built-in in anticipation of redeclaring the
1978 /// built-in.
1979 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1980                                      Scope *S, bool ForRedeclaration,
1981                                      SourceLocation Loc) {
1982   LookupPredefedObjCSuperType(*this, S, II);
1983 
1984   ASTContext::GetBuiltinTypeError Error;
1985   QualType R = Context.GetBuiltinType(ID, Error);
1986   if (Error) {
1987     if (!ForRedeclaration)
1988       return nullptr;
1989 
1990     // If we have a builtin without an associated type we should not emit a
1991     // warning when we were not able to find a type for it.
1992     if (Error == ASTContext::GE_Missing_type)
1993       return nullptr;
1994 
1995     // If we could not find a type for setjmp it is because the jmp_buf type was
1996     // not defined prior to the setjmp declaration.
1997     if (Error == ASTContext::GE_Missing_setjmp) {
1998       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
1999           << Context.BuiltinInfo.getName(ID);
2000       return nullptr;
2001     }
2002 
2003     // Generally, we emit a warning that the declaration requires the
2004     // appropriate header.
2005     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2006         << getHeaderName(Context.BuiltinInfo, ID, Error)
2007         << Context.BuiltinInfo.getName(ID);
2008     return nullptr;
2009   }
2010 
2011   if (!ForRedeclaration &&
2012       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2013        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2014     Diag(Loc, diag::ext_implicit_lib_function_decl)
2015         << Context.BuiltinInfo.getName(ID) << R;
2016     if (Context.BuiltinInfo.getHeaderName(ID) &&
2017         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
2018       Diag(Loc, diag::note_include_header_or_declare)
2019           << Context.BuiltinInfo.getHeaderName(ID)
2020           << Context.BuiltinInfo.getName(ID);
2021   }
2022 
2023   if (R.isNull())
2024     return nullptr;
2025 
2026   DeclContext *Parent = Context.getTranslationUnitDecl();
2027   if (getLangOpts().CPlusPlus) {
2028     LinkageSpecDecl *CLinkageDecl =
2029         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
2030                                 LinkageSpecDecl::lang_c, false);
2031     CLinkageDecl->setImplicit();
2032     Parent->addDecl(CLinkageDecl);
2033     Parent = CLinkageDecl;
2034   }
2035 
2036   FunctionDecl *New = FunctionDecl::Create(Context,
2037                                            Parent,
2038                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
2039                                            SC_Extern,
2040                                            false,
2041                                            R->isFunctionProtoType());
2042   New->setImplicit();
2043 
2044   // Create Decl objects for each parameter, adding them to the
2045   // FunctionDecl.
2046   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
2047     SmallVector<ParmVarDecl*, 16> Params;
2048     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2049       ParmVarDecl *parm =
2050           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2051                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2052                               SC_None, nullptr);
2053       parm->setScopeInfo(0, i);
2054       Params.push_back(parm);
2055     }
2056     New->setParams(Params);
2057   }
2058 
2059   AddKnownFunctionAttributes(New);
2060   RegisterLocallyScopedExternCDecl(New, S);
2061 
2062   // TUScope is the translation-unit scope to insert this function into.
2063   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2064   // relate Scopes to DeclContexts, and probably eliminate CurContext
2065   // entirely, but we're not there yet.
2066   DeclContext *SavedContext = CurContext;
2067   CurContext = Parent;
2068   PushOnScopeChains(New, TUScope);
2069   CurContext = SavedContext;
2070   return New;
2071 }
2072 
2073 /// Typedef declarations don't have linkage, but they still denote the same
2074 /// entity if their types are the same.
2075 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2076 /// isSameEntity.
2077 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2078                                                      TypedefNameDecl *Decl,
2079                                                      LookupResult &Previous) {
2080   // This is only interesting when modules are enabled.
2081   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2082     return;
2083 
2084   // Empty sets are uninteresting.
2085   if (Previous.empty())
2086     return;
2087 
2088   LookupResult::Filter Filter = Previous.makeFilter();
2089   while (Filter.hasNext()) {
2090     NamedDecl *Old = Filter.next();
2091 
2092     // Non-hidden declarations are never ignored.
2093     if (S.isVisible(Old))
2094       continue;
2095 
2096     // Declarations of the same entity are not ignored, even if they have
2097     // different linkages.
2098     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2099       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2100                                 Decl->getUnderlyingType()))
2101         continue;
2102 
2103       // If both declarations give a tag declaration a typedef name for linkage
2104       // purposes, then they declare the same entity.
2105       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2106           Decl->getAnonDeclWithTypedefName())
2107         continue;
2108     }
2109 
2110     Filter.erase();
2111   }
2112 
2113   Filter.done();
2114 }
2115 
2116 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2117   QualType OldType;
2118   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2119     OldType = OldTypedef->getUnderlyingType();
2120   else
2121     OldType = Context.getTypeDeclType(Old);
2122   QualType NewType = New->getUnderlyingType();
2123 
2124   if (NewType->isVariablyModifiedType()) {
2125     // Must not redefine a typedef with a variably-modified type.
2126     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2127     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2128       << Kind << NewType;
2129     if (Old->getLocation().isValid())
2130       notePreviousDefinition(Old, New->getLocation());
2131     New->setInvalidDecl();
2132     return true;
2133   }
2134 
2135   if (OldType != NewType &&
2136       !OldType->isDependentType() &&
2137       !NewType->isDependentType() &&
2138       !Context.hasSameType(OldType, NewType)) {
2139     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2140     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2141       << Kind << NewType << OldType;
2142     if (Old->getLocation().isValid())
2143       notePreviousDefinition(Old, New->getLocation());
2144     New->setInvalidDecl();
2145     return true;
2146   }
2147   return false;
2148 }
2149 
2150 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2151 /// same name and scope as a previous declaration 'Old'.  Figure out
2152 /// how to resolve this situation, merging decls or emitting
2153 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2154 ///
2155 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2156                                 LookupResult &OldDecls) {
2157   // If the new decl is known invalid already, don't bother doing any
2158   // merging checks.
2159   if (New->isInvalidDecl()) return;
2160 
2161   // Allow multiple definitions for ObjC built-in typedefs.
2162   // FIXME: Verify the underlying types are equivalent!
2163   if (getLangOpts().ObjC) {
2164     const IdentifierInfo *TypeID = New->getIdentifier();
2165     switch (TypeID->getLength()) {
2166     default: break;
2167     case 2:
2168       {
2169         if (!TypeID->isStr("id"))
2170           break;
2171         QualType T = New->getUnderlyingType();
2172         if (!T->isPointerType())
2173           break;
2174         if (!T->isVoidPointerType()) {
2175           QualType PT = T->getAs<PointerType>()->getPointeeType();
2176           if (!PT->isStructureType())
2177             break;
2178         }
2179         Context.setObjCIdRedefinitionType(T);
2180         // Install the built-in type for 'id', ignoring the current definition.
2181         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2182         return;
2183       }
2184     case 5:
2185       if (!TypeID->isStr("Class"))
2186         break;
2187       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2188       // Install the built-in type for 'Class', ignoring the current definition.
2189       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2190       return;
2191     case 3:
2192       if (!TypeID->isStr("SEL"))
2193         break;
2194       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2195       // Install the built-in type for 'SEL', ignoring the current definition.
2196       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2197       return;
2198     }
2199     // Fall through - the typedef name was not a builtin type.
2200   }
2201 
2202   // Verify the old decl was also a type.
2203   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2204   if (!Old) {
2205     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2206       << New->getDeclName();
2207 
2208     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2209     if (OldD->getLocation().isValid())
2210       notePreviousDefinition(OldD, New->getLocation());
2211 
2212     return New->setInvalidDecl();
2213   }
2214 
2215   // If the old declaration is invalid, just give up here.
2216   if (Old->isInvalidDecl())
2217     return New->setInvalidDecl();
2218 
2219   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2220     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2221     auto *NewTag = New->getAnonDeclWithTypedefName();
2222     NamedDecl *Hidden = nullptr;
2223     if (OldTag && NewTag &&
2224         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2225         !hasVisibleDefinition(OldTag, &Hidden)) {
2226       // There is a definition of this tag, but it is not visible. Use it
2227       // instead of our tag.
2228       New->setTypeForDecl(OldTD->getTypeForDecl());
2229       if (OldTD->isModed())
2230         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2231                                     OldTD->getUnderlyingType());
2232       else
2233         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2234 
2235       // Make the old tag definition visible.
2236       makeMergedDefinitionVisible(Hidden);
2237 
2238       // If this was an unscoped enumeration, yank all of its enumerators
2239       // out of the scope.
2240       if (isa<EnumDecl>(NewTag)) {
2241         Scope *EnumScope = getNonFieldDeclScope(S);
2242         for (auto *D : NewTag->decls()) {
2243           auto *ED = cast<EnumConstantDecl>(D);
2244           assert(EnumScope->isDeclScope(ED));
2245           EnumScope->RemoveDecl(ED);
2246           IdResolver.RemoveDecl(ED);
2247           ED->getLexicalDeclContext()->removeDecl(ED);
2248         }
2249       }
2250     }
2251   }
2252 
2253   // If the typedef types are not identical, reject them in all languages and
2254   // with any extensions enabled.
2255   if (isIncompatibleTypedef(Old, New))
2256     return;
2257 
2258   // The types match.  Link up the redeclaration chain and merge attributes if
2259   // the old declaration was a typedef.
2260   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2261     New->setPreviousDecl(Typedef);
2262     mergeDeclAttributes(New, Old);
2263   }
2264 
2265   if (getLangOpts().MicrosoftExt)
2266     return;
2267 
2268   if (getLangOpts().CPlusPlus) {
2269     // C++ [dcl.typedef]p2:
2270     //   In a given non-class scope, a typedef specifier can be used to
2271     //   redefine the name of any type declared in that scope to refer
2272     //   to the type to which it already refers.
2273     if (!isa<CXXRecordDecl>(CurContext))
2274       return;
2275 
2276     // C++0x [dcl.typedef]p4:
2277     //   In a given class scope, a typedef specifier can be used to redefine
2278     //   any class-name declared in that scope that is not also a typedef-name
2279     //   to refer to the type to which it already refers.
2280     //
2281     // This wording came in via DR424, which was a correction to the
2282     // wording in DR56, which accidentally banned code like:
2283     //
2284     //   struct S {
2285     //     typedef struct A { } A;
2286     //   };
2287     //
2288     // in the C++03 standard. We implement the C++0x semantics, which
2289     // allow the above but disallow
2290     //
2291     //   struct S {
2292     //     typedef int I;
2293     //     typedef int I;
2294     //   };
2295     //
2296     // since that was the intent of DR56.
2297     if (!isa<TypedefNameDecl>(Old))
2298       return;
2299 
2300     Diag(New->getLocation(), diag::err_redefinition)
2301       << New->getDeclName();
2302     notePreviousDefinition(Old, New->getLocation());
2303     return New->setInvalidDecl();
2304   }
2305 
2306   // Modules always permit redefinition of typedefs, as does C11.
2307   if (getLangOpts().Modules || getLangOpts().C11)
2308     return;
2309 
2310   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2311   // is normally mapped to an error, but can be controlled with
2312   // -Wtypedef-redefinition.  If either the original or the redefinition is
2313   // in a system header, don't emit this for compatibility with GCC.
2314   if (getDiagnostics().getSuppressSystemWarnings() &&
2315       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2316       (Old->isImplicit() ||
2317        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2318        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2319     return;
2320 
2321   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2322     << New->getDeclName();
2323   notePreviousDefinition(Old, New->getLocation());
2324 }
2325 
2326 /// DeclhasAttr - returns true if decl Declaration already has the target
2327 /// attribute.
2328 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2329   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2330   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2331   for (const auto *i : D->attrs())
2332     if (i->getKind() == A->getKind()) {
2333       if (Ann) {
2334         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2335           return true;
2336         continue;
2337       }
2338       // FIXME: Don't hardcode this check
2339       if (OA && isa<OwnershipAttr>(i))
2340         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2341       return true;
2342     }
2343 
2344   return false;
2345 }
2346 
2347 static bool isAttributeTargetADefinition(Decl *D) {
2348   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2349     return VD->isThisDeclarationADefinition();
2350   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2351     return TD->isCompleteDefinition() || TD->isBeingDefined();
2352   return true;
2353 }
2354 
2355 /// Merge alignment attributes from \p Old to \p New, taking into account the
2356 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2357 ///
2358 /// \return \c true if any attributes were added to \p New.
2359 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2360   // Look for alignas attributes on Old, and pick out whichever attribute
2361   // specifies the strictest alignment requirement.
2362   AlignedAttr *OldAlignasAttr = nullptr;
2363   AlignedAttr *OldStrictestAlignAttr = nullptr;
2364   unsigned OldAlign = 0;
2365   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2366     // FIXME: We have no way of representing inherited dependent alignments
2367     // in a case like:
2368     //   template<int A, int B> struct alignas(A) X;
2369     //   template<int A, int B> struct alignas(B) X {};
2370     // For now, we just ignore any alignas attributes which are not on the
2371     // definition in such a case.
2372     if (I->isAlignmentDependent())
2373       return false;
2374 
2375     if (I->isAlignas())
2376       OldAlignasAttr = I;
2377 
2378     unsigned Align = I->getAlignment(S.Context);
2379     if (Align > OldAlign) {
2380       OldAlign = Align;
2381       OldStrictestAlignAttr = I;
2382     }
2383   }
2384 
2385   // Look for alignas attributes on New.
2386   AlignedAttr *NewAlignasAttr = nullptr;
2387   unsigned NewAlign = 0;
2388   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2389     if (I->isAlignmentDependent())
2390       return false;
2391 
2392     if (I->isAlignas())
2393       NewAlignasAttr = I;
2394 
2395     unsigned Align = I->getAlignment(S.Context);
2396     if (Align > NewAlign)
2397       NewAlign = Align;
2398   }
2399 
2400   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2401     // Both declarations have 'alignas' attributes. We require them to match.
2402     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2403     // fall short. (If two declarations both have alignas, they must both match
2404     // every definition, and so must match each other if there is a definition.)
2405 
2406     // If either declaration only contains 'alignas(0)' specifiers, then it
2407     // specifies the natural alignment for the type.
2408     if (OldAlign == 0 || NewAlign == 0) {
2409       QualType Ty;
2410       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2411         Ty = VD->getType();
2412       else
2413         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2414 
2415       if (OldAlign == 0)
2416         OldAlign = S.Context.getTypeAlign(Ty);
2417       if (NewAlign == 0)
2418         NewAlign = S.Context.getTypeAlign(Ty);
2419     }
2420 
2421     if (OldAlign != NewAlign) {
2422       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2423         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2424         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2425       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2426     }
2427   }
2428 
2429   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2430     // C++11 [dcl.align]p6:
2431     //   if any declaration of an entity has an alignment-specifier,
2432     //   every defining declaration of that entity shall specify an
2433     //   equivalent alignment.
2434     // C11 6.7.5/7:
2435     //   If the definition of an object does not have an alignment
2436     //   specifier, any other declaration of that object shall also
2437     //   have no alignment specifier.
2438     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2439       << OldAlignasAttr;
2440     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2441       << OldAlignasAttr;
2442   }
2443 
2444   bool AnyAdded = false;
2445 
2446   // Ensure we have an attribute representing the strictest alignment.
2447   if (OldAlign > NewAlign) {
2448     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2449     Clone->setInherited(true);
2450     New->addAttr(Clone);
2451     AnyAdded = true;
2452   }
2453 
2454   // Ensure we have an alignas attribute if the old declaration had one.
2455   if (OldAlignasAttr && !NewAlignasAttr &&
2456       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2457     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2458     Clone->setInherited(true);
2459     New->addAttr(Clone);
2460     AnyAdded = true;
2461   }
2462 
2463   return AnyAdded;
2464 }
2465 
2466 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2467                                const InheritableAttr *Attr,
2468                                Sema::AvailabilityMergeKind AMK) {
2469   // This function copies an attribute Attr from a previous declaration to the
2470   // new declaration D if the new declaration doesn't itself have that attribute
2471   // yet or if that attribute allows duplicates.
2472   // If you're adding a new attribute that requires logic different from
2473   // "use explicit attribute on decl if present, else use attribute from
2474   // previous decl", for example if the attribute needs to be consistent
2475   // between redeclarations, you need to call a custom merge function here.
2476   InheritableAttr *NewAttr = nullptr;
2477   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2478     NewAttr = S.mergeAvailabilityAttr(
2479         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2480         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2481         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2482         AA->getPriority());
2483   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2484     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2485   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2486     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2487   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2488     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2489   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2490     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2491   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2492     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2493                                 FA->getFirstArg());
2494   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2495     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2496   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2497     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2498   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2499     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2500                                        IA->getSemanticSpelling());
2501   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2502     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2503                                       &S.Context.Idents.get(AA->getSpelling()));
2504   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2505            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2506             isa<CUDAGlobalAttr>(Attr))) {
2507     // CUDA target attributes are part of function signature for
2508     // overloading purposes and must not be merged.
2509     return false;
2510   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2511     NewAttr = S.mergeMinSizeAttr(D, *MA);
2512   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2513     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2514   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2515     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2516   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2517     NewAttr = S.mergeCommonAttr(D, *CommonA);
2518   else if (isa<AlignedAttr>(Attr))
2519     // AlignedAttrs are handled separately, because we need to handle all
2520     // such attributes on a declaration at the same time.
2521     NewAttr = nullptr;
2522   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2523            (AMK == Sema::AMK_Override ||
2524             AMK == Sema::AMK_ProtocolImplementation))
2525     NewAttr = nullptr;
2526   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2527     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid());
2528   else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
2529     NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
2530   else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
2531     NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
2532   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2533     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2534 
2535   if (NewAttr) {
2536     NewAttr->setInherited(true);
2537     D->addAttr(NewAttr);
2538     if (isa<MSInheritanceAttr>(NewAttr))
2539       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2540     return true;
2541   }
2542 
2543   return false;
2544 }
2545 
2546 static const NamedDecl *getDefinition(const Decl *D) {
2547   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2548     return TD->getDefinition();
2549   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2550     const VarDecl *Def = VD->getDefinition();
2551     if (Def)
2552       return Def;
2553     return VD->getActingDefinition();
2554   }
2555   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2556     return FD->getDefinition();
2557   return nullptr;
2558 }
2559 
2560 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2561   for (const auto *Attribute : D->attrs())
2562     if (Attribute->getKind() == Kind)
2563       return true;
2564   return false;
2565 }
2566 
2567 /// checkNewAttributesAfterDef - If we already have a definition, check that
2568 /// there are no new attributes in this declaration.
2569 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2570   if (!New->hasAttrs())
2571     return;
2572 
2573   const NamedDecl *Def = getDefinition(Old);
2574   if (!Def || Def == New)
2575     return;
2576 
2577   AttrVec &NewAttributes = New->getAttrs();
2578   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2579     const Attr *NewAttribute = NewAttributes[I];
2580 
2581     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2582       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2583         Sema::SkipBodyInfo SkipBody;
2584         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2585 
2586         // If we're skipping this definition, drop the "alias" attribute.
2587         if (SkipBody.ShouldSkip) {
2588           NewAttributes.erase(NewAttributes.begin() + I);
2589           --E;
2590           continue;
2591         }
2592       } else {
2593         VarDecl *VD = cast<VarDecl>(New);
2594         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2595                                 VarDecl::TentativeDefinition
2596                             ? diag::err_alias_after_tentative
2597                             : diag::err_redefinition;
2598         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2599         if (Diag == diag::err_redefinition)
2600           S.notePreviousDefinition(Def, VD->getLocation());
2601         else
2602           S.Diag(Def->getLocation(), diag::note_previous_definition);
2603         VD->setInvalidDecl();
2604       }
2605       ++I;
2606       continue;
2607     }
2608 
2609     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2610       // Tentative definitions are only interesting for the alias check above.
2611       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2612         ++I;
2613         continue;
2614       }
2615     }
2616 
2617     if (hasAttribute(Def, NewAttribute->getKind())) {
2618       ++I;
2619       continue; // regular attr merging will take care of validating this.
2620     }
2621 
2622     if (isa<C11NoReturnAttr>(NewAttribute)) {
2623       // C's _Noreturn is allowed to be added to a function after it is defined.
2624       ++I;
2625       continue;
2626     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2627       if (AA->isAlignas()) {
2628         // C++11 [dcl.align]p6:
2629         //   if any declaration of an entity has an alignment-specifier,
2630         //   every defining declaration of that entity shall specify an
2631         //   equivalent alignment.
2632         // C11 6.7.5/7:
2633         //   If the definition of an object does not have an alignment
2634         //   specifier, any other declaration of that object shall also
2635         //   have no alignment specifier.
2636         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2637           << AA;
2638         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2639           << AA;
2640         NewAttributes.erase(NewAttributes.begin() + I);
2641         --E;
2642         continue;
2643       }
2644     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2645                cast<VarDecl>(New)->isInline() &&
2646                !cast<VarDecl>(New)->isInlineSpecified()) {
2647       // Don't warn about applying selectany to implicitly inline variables.
2648       // Older compilers and language modes would require the use of selectany
2649       // to make such variables inline, and it would have no effect if we
2650       // honored it.
2651       ++I;
2652       continue;
2653     }
2654 
2655     S.Diag(NewAttribute->getLocation(),
2656            diag::warn_attribute_precede_definition);
2657     S.Diag(Def->getLocation(), diag::note_previous_definition);
2658     NewAttributes.erase(NewAttributes.begin() + I);
2659     --E;
2660   }
2661 }
2662 
2663 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2664                                      const ConstInitAttr *CIAttr,
2665                                      bool AttrBeforeInit) {
2666   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2667 
2668   // Figure out a good way to write this specifier on the old declaration.
2669   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2670   // enough of the attribute list spelling information to extract that without
2671   // heroics.
2672   std::string SuitableSpelling;
2673   if (S.getLangOpts().CPlusPlus2a)
2674     SuitableSpelling =
2675         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit});
2676   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2677     SuitableSpelling = S.PP.getLastMacroWithSpelling(
2678         InsertLoc,
2679         {tok::l_square, tok::l_square, S.PP.getIdentifierInfo("clang"),
2680          tok::coloncolon,
2681          S.PP.getIdentifierInfo("require_constant_initialization"),
2682          tok::r_square, tok::r_square});
2683   if (SuitableSpelling.empty())
2684     SuitableSpelling = S.PP.getLastMacroWithSpelling(
2685         InsertLoc,
2686         {tok::kw___attribute, tok::l_paren, tok::r_paren,
2687          S.PP.getIdentifierInfo("require_constant_initialization"),
2688          tok::r_paren, tok::r_paren});
2689   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus2a)
2690     SuitableSpelling = "constinit";
2691   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2692     SuitableSpelling = "[[clang::require_constant_initialization]]";
2693   if (SuitableSpelling.empty())
2694     SuitableSpelling = "__attribute__((require_constant_initialization))";
2695   SuitableSpelling += " ";
2696 
2697   if (AttrBeforeInit) {
2698     // extern constinit int a;
2699     // int a = 0; // error (missing 'constinit'), accepted as extension
2700     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
2701     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2702         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2703     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2704   } else {
2705     // int a = 0;
2706     // constinit extern int a; // error (missing 'constinit')
2707     S.Diag(CIAttr->getLocation(),
2708            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2709                                  : diag::warn_require_const_init_added_too_late)
2710         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2711     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2712         << CIAttr->isConstinit()
2713         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2714   }
2715 }
2716 
2717 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2718 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2719                                AvailabilityMergeKind AMK) {
2720   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2721     UsedAttr *NewAttr = OldAttr->clone(Context);
2722     NewAttr->setInherited(true);
2723     New->addAttr(NewAttr);
2724   }
2725 
2726   if (!Old->hasAttrs() && !New->hasAttrs())
2727     return;
2728 
2729   // [dcl.constinit]p1:
2730   //   If the [constinit] specifier is applied to any declaration of a
2731   //   variable, it shall be applied to the initializing declaration.
2732   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2733   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2734   if (bool(OldConstInit) != bool(NewConstInit)) {
2735     const auto *OldVD = cast<VarDecl>(Old);
2736     auto *NewVD = cast<VarDecl>(New);
2737 
2738     // Find the initializing declaration. Note that we might not have linked
2739     // the new declaration into the redeclaration chain yet.
2740     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2741     if (!InitDecl &&
2742         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2743       InitDecl = NewVD;
2744 
2745     if (InitDecl == NewVD) {
2746       // This is the initializing declaration. If it would inherit 'constinit',
2747       // that's ill-formed. (Note that we do not apply this to the attribute
2748       // form).
2749       if (OldConstInit && OldConstInit->isConstinit())
2750         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2751                                  /*AttrBeforeInit=*/true);
2752     } else if (NewConstInit) {
2753       // This is the first time we've been told that this declaration should
2754       // have a constant initializer. If we already saw the initializing
2755       // declaration, this is too late.
2756       if (InitDecl && InitDecl != NewVD) {
2757         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2758                                  /*AttrBeforeInit=*/false);
2759         NewVD->dropAttr<ConstInitAttr>();
2760       }
2761     }
2762   }
2763 
2764   // Attributes declared post-definition are currently ignored.
2765   checkNewAttributesAfterDef(*this, New, Old);
2766 
2767   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2768     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2769       if (!OldA->isEquivalent(NewA)) {
2770         // This redeclaration changes __asm__ label.
2771         Diag(New->getLocation(), diag::err_different_asm_label);
2772         Diag(OldA->getLocation(), diag::note_previous_declaration);
2773       }
2774     } else if (Old->isUsed()) {
2775       // This redeclaration adds an __asm__ label to a declaration that has
2776       // already been ODR-used.
2777       Diag(New->getLocation(), diag::err_late_asm_label_name)
2778         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2779     }
2780   }
2781 
2782   // Re-declaration cannot add abi_tag's.
2783   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2784     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2785       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2786         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2787                       NewTag) == OldAbiTagAttr->tags_end()) {
2788           Diag(NewAbiTagAttr->getLocation(),
2789                diag::err_new_abi_tag_on_redeclaration)
2790               << NewTag;
2791           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2792         }
2793       }
2794     } else {
2795       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2796       Diag(Old->getLocation(), diag::note_previous_declaration);
2797     }
2798   }
2799 
2800   // This redeclaration adds a section attribute.
2801   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2802     if (auto *VD = dyn_cast<VarDecl>(New)) {
2803       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2804         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2805         Diag(Old->getLocation(), diag::note_previous_declaration);
2806       }
2807     }
2808   }
2809 
2810   // Redeclaration adds code-seg attribute.
2811   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2812   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2813       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2814     Diag(New->getLocation(), diag::warn_mismatched_section)
2815          << 0 /*codeseg*/;
2816     Diag(Old->getLocation(), diag::note_previous_declaration);
2817   }
2818 
2819   if (!Old->hasAttrs())
2820     return;
2821 
2822   bool foundAny = New->hasAttrs();
2823 
2824   // Ensure that any moving of objects within the allocated map is done before
2825   // we process them.
2826   if (!foundAny) New->setAttrs(AttrVec());
2827 
2828   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2829     // Ignore deprecated/unavailable/availability attributes if requested.
2830     AvailabilityMergeKind LocalAMK = AMK_None;
2831     if (isa<DeprecatedAttr>(I) ||
2832         isa<UnavailableAttr>(I) ||
2833         isa<AvailabilityAttr>(I)) {
2834       switch (AMK) {
2835       case AMK_None:
2836         continue;
2837 
2838       case AMK_Redeclaration:
2839       case AMK_Override:
2840       case AMK_ProtocolImplementation:
2841         LocalAMK = AMK;
2842         break;
2843       }
2844     }
2845 
2846     // Already handled.
2847     if (isa<UsedAttr>(I))
2848       continue;
2849 
2850     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2851       foundAny = true;
2852   }
2853 
2854   if (mergeAlignedAttrs(*this, New, Old))
2855     foundAny = true;
2856 
2857   if (!foundAny) New->dropAttrs();
2858 }
2859 
2860 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2861 /// to the new one.
2862 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2863                                      const ParmVarDecl *oldDecl,
2864                                      Sema &S) {
2865   // C++11 [dcl.attr.depend]p2:
2866   //   The first declaration of a function shall specify the
2867   //   carries_dependency attribute for its declarator-id if any declaration
2868   //   of the function specifies the carries_dependency attribute.
2869   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2870   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2871     S.Diag(CDA->getLocation(),
2872            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2873     // Find the first declaration of the parameter.
2874     // FIXME: Should we build redeclaration chains for function parameters?
2875     const FunctionDecl *FirstFD =
2876       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2877     const ParmVarDecl *FirstVD =
2878       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2879     S.Diag(FirstVD->getLocation(),
2880            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2881   }
2882 
2883   if (!oldDecl->hasAttrs())
2884     return;
2885 
2886   bool foundAny = newDecl->hasAttrs();
2887 
2888   // Ensure that any moving of objects within the allocated map is
2889   // done before we process them.
2890   if (!foundAny) newDecl->setAttrs(AttrVec());
2891 
2892   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2893     if (!DeclHasAttr(newDecl, I)) {
2894       InheritableAttr *newAttr =
2895         cast<InheritableParamAttr>(I->clone(S.Context));
2896       newAttr->setInherited(true);
2897       newDecl->addAttr(newAttr);
2898       foundAny = true;
2899     }
2900   }
2901 
2902   if (!foundAny) newDecl->dropAttrs();
2903 }
2904 
2905 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2906                                 const ParmVarDecl *OldParam,
2907                                 Sema &S) {
2908   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2909     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2910       if (*Oldnullability != *Newnullability) {
2911         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2912           << DiagNullabilityKind(
2913                *Newnullability,
2914                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2915                 != 0))
2916           << DiagNullabilityKind(
2917                *Oldnullability,
2918                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2919                 != 0));
2920         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2921       }
2922     } else {
2923       QualType NewT = NewParam->getType();
2924       NewT = S.Context.getAttributedType(
2925                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2926                          NewT, NewT);
2927       NewParam->setType(NewT);
2928     }
2929   }
2930 }
2931 
2932 namespace {
2933 
2934 /// Used in MergeFunctionDecl to keep track of function parameters in
2935 /// C.
2936 struct GNUCompatibleParamWarning {
2937   ParmVarDecl *OldParm;
2938   ParmVarDecl *NewParm;
2939   QualType PromotedType;
2940 };
2941 
2942 } // end anonymous namespace
2943 
2944 /// getSpecialMember - get the special member enum for a method.
2945 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2946   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2947     if (Ctor->isDefaultConstructor())
2948       return Sema::CXXDefaultConstructor;
2949 
2950     if (Ctor->isCopyConstructor())
2951       return Sema::CXXCopyConstructor;
2952 
2953     if (Ctor->isMoveConstructor())
2954       return Sema::CXXMoveConstructor;
2955   } else if (isa<CXXDestructorDecl>(MD)) {
2956     return Sema::CXXDestructor;
2957   } else if (MD->isCopyAssignmentOperator()) {
2958     return Sema::CXXCopyAssignment;
2959   } else if (MD->isMoveAssignmentOperator()) {
2960     return Sema::CXXMoveAssignment;
2961   }
2962 
2963   return Sema::CXXInvalid;
2964 }
2965 
2966 // Determine whether the previous declaration was a definition, implicit
2967 // declaration, or a declaration.
2968 template <typename T>
2969 static std::pair<diag::kind, SourceLocation>
2970 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2971   diag::kind PrevDiag;
2972   SourceLocation OldLocation = Old->getLocation();
2973   if (Old->isThisDeclarationADefinition())
2974     PrevDiag = diag::note_previous_definition;
2975   else if (Old->isImplicit()) {
2976     PrevDiag = diag::note_previous_implicit_declaration;
2977     if (OldLocation.isInvalid())
2978       OldLocation = New->getLocation();
2979   } else
2980     PrevDiag = diag::note_previous_declaration;
2981   return std::make_pair(PrevDiag, OldLocation);
2982 }
2983 
2984 /// canRedefineFunction - checks if a function can be redefined. Currently,
2985 /// only extern inline functions can be redefined, and even then only in
2986 /// GNU89 mode.
2987 static bool canRedefineFunction(const FunctionDecl *FD,
2988                                 const LangOptions& LangOpts) {
2989   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2990           !LangOpts.CPlusPlus &&
2991           FD->isInlineSpecified() &&
2992           FD->getStorageClass() == SC_Extern);
2993 }
2994 
2995 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2996   const AttributedType *AT = T->getAs<AttributedType>();
2997   while (AT && !AT->isCallingConv())
2998     AT = AT->getModifiedType()->getAs<AttributedType>();
2999   return AT;
3000 }
3001 
3002 template <typename T>
3003 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3004   const DeclContext *DC = Old->getDeclContext();
3005   if (DC->isRecord())
3006     return false;
3007 
3008   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3009   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3010     return true;
3011   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3012     return true;
3013   return false;
3014 }
3015 
3016 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3017 static bool isExternC(VarTemplateDecl *) { return false; }
3018 
3019 /// Check whether a redeclaration of an entity introduced by a
3020 /// using-declaration is valid, given that we know it's not an overload
3021 /// (nor a hidden tag declaration).
3022 template<typename ExpectedDecl>
3023 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3024                                    ExpectedDecl *New) {
3025   // C++11 [basic.scope.declarative]p4:
3026   //   Given a set of declarations in a single declarative region, each of
3027   //   which specifies the same unqualified name,
3028   //   -- they shall all refer to the same entity, or all refer to functions
3029   //      and function templates; or
3030   //   -- exactly one declaration shall declare a class name or enumeration
3031   //      name that is not a typedef name and the other declarations shall all
3032   //      refer to the same variable or enumerator, or all refer to functions
3033   //      and function templates; in this case the class name or enumeration
3034   //      name is hidden (3.3.10).
3035 
3036   // C++11 [namespace.udecl]p14:
3037   //   If a function declaration in namespace scope or block scope has the
3038   //   same name and the same parameter-type-list as a function introduced
3039   //   by a using-declaration, and the declarations do not declare the same
3040   //   function, the program is ill-formed.
3041 
3042   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3043   if (Old &&
3044       !Old->getDeclContext()->getRedeclContext()->Equals(
3045           New->getDeclContext()->getRedeclContext()) &&
3046       !(isExternC(Old) && isExternC(New)))
3047     Old = nullptr;
3048 
3049   if (!Old) {
3050     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3051     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3052     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
3053     return true;
3054   }
3055   return false;
3056 }
3057 
3058 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3059                                             const FunctionDecl *B) {
3060   assert(A->getNumParams() == B->getNumParams());
3061 
3062   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3063     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3064     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3065     if (AttrA == AttrB)
3066       return true;
3067     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3068            AttrA->isDynamic() == AttrB->isDynamic();
3069   };
3070 
3071   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3072 }
3073 
3074 /// If necessary, adjust the semantic declaration context for a qualified
3075 /// declaration to name the correct inline namespace within the qualifier.
3076 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3077                                                DeclaratorDecl *OldD) {
3078   // The only case where we need to update the DeclContext is when
3079   // redeclaration lookup for a qualified name finds a declaration
3080   // in an inline namespace within the context named by the qualifier:
3081   //
3082   //   inline namespace N { int f(); }
3083   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3084   //
3085   // For unqualified declarations, the semantic context *can* change
3086   // along the redeclaration chain (for local extern declarations,
3087   // extern "C" declarations, and friend declarations in particular).
3088   if (!NewD->getQualifier())
3089     return;
3090 
3091   // NewD is probably already in the right context.
3092   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3093   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3094   if (NamedDC->Equals(SemaDC))
3095     return;
3096 
3097   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3098           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3099          "unexpected context for redeclaration");
3100 
3101   auto *LexDC = NewD->getLexicalDeclContext();
3102   auto FixSemaDC = [=](NamedDecl *D) {
3103     if (!D)
3104       return;
3105     D->setDeclContext(SemaDC);
3106     D->setLexicalDeclContext(LexDC);
3107   };
3108 
3109   FixSemaDC(NewD);
3110   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3111     FixSemaDC(FD->getDescribedFunctionTemplate());
3112   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3113     FixSemaDC(VD->getDescribedVarTemplate());
3114 }
3115 
3116 /// MergeFunctionDecl - We just parsed a function 'New' from
3117 /// declarator D which has the same name and scope as a previous
3118 /// declaration 'Old'.  Figure out how to resolve this situation,
3119 /// merging decls or emitting diagnostics as appropriate.
3120 ///
3121 /// In C++, New and Old must be declarations that are not
3122 /// overloaded. Use IsOverload to determine whether New and Old are
3123 /// overloaded, and to select the Old declaration that New should be
3124 /// merged with.
3125 ///
3126 /// Returns true if there was an error, false otherwise.
3127 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3128                              Scope *S, bool MergeTypeWithOld) {
3129   // Verify the old decl was also a function.
3130   FunctionDecl *Old = OldD->getAsFunction();
3131   if (!Old) {
3132     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3133       if (New->getFriendObjectKind()) {
3134         Diag(New->getLocation(), diag::err_using_decl_friend);
3135         Diag(Shadow->getTargetDecl()->getLocation(),
3136              diag::note_using_decl_target);
3137         Diag(Shadow->getUsingDecl()->getLocation(),
3138              diag::note_using_decl) << 0;
3139         return true;
3140       }
3141 
3142       // Check whether the two declarations might declare the same function.
3143       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3144         return true;
3145       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3146     } else {
3147       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3148         << New->getDeclName();
3149       notePreviousDefinition(OldD, New->getLocation());
3150       return true;
3151     }
3152   }
3153 
3154   // If the old declaration is invalid, just give up here.
3155   if (Old->isInvalidDecl())
3156     return true;
3157 
3158   // Disallow redeclaration of some builtins.
3159   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3160     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3161     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3162         << Old << Old->getType();
3163     return true;
3164   }
3165 
3166   diag::kind PrevDiag;
3167   SourceLocation OldLocation;
3168   std::tie(PrevDiag, OldLocation) =
3169       getNoteDiagForInvalidRedeclaration(Old, New);
3170 
3171   // Don't complain about this if we're in GNU89 mode and the old function
3172   // is an extern inline function.
3173   // Don't complain about specializations. They are not supposed to have
3174   // storage classes.
3175   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3176       New->getStorageClass() == SC_Static &&
3177       Old->hasExternalFormalLinkage() &&
3178       !New->getTemplateSpecializationInfo() &&
3179       !canRedefineFunction(Old, getLangOpts())) {
3180     if (getLangOpts().MicrosoftExt) {
3181       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3182       Diag(OldLocation, PrevDiag);
3183     } else {
3184       Diag(New->getLocation(), diag::err_static_non_static) << New;
3185       Diag(OldLocation, PrevDiag);
3186       return true;
3187     }
3188   }
3189 
3190   if (New->hasAttr<InternalLinkageAttr>() &&
3191       !Old->hasAttr<InternalLinkageAttr>()) {
3192     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3193         << New->getDeclName();
3194     notePreviousDefinition(Old, New->getLocation());
3195     New->dropAttr<InternalLinkageAttr>();
3196   }
3197 
3198   if (CheckRedeclarationModuleOwnership(New, Old))
3199     return true;
3200 
3201   if (!getLangOpts().CPlusPlus) {
3202     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3203     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3204       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3205         << New << OldOvl;
3206 
3207       // Try our best to find a decl that actually has the overloadable
3208       // attribute for the note. In most cases (e.g. programs with only one
3209       // broken declaration/definition), this won't matter.
3210       //
3211       // FIXME: We could do this if we juggled some extra state in
3212       // OverloadableAttr, rather than just removing it.
3213       const Decl *DiagOld = Old;
3214       if (OldOvl) {
3215         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3216           const auto *A = D->getAttr<OverloadableAttr>();
3217           return A && !A->isImplicit();
3218         });
3219         // If we've implicitly added *all* of the overloadable attrs to this
3220         // chain, emitting a "previous redecl" note is pointless.
3221         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3222       }
3223 
3224       if (DiagOld)
3225         Diag(DiagOld->getLocation(),
3226              diag::note_attribute_overloadable_prev_overload)
3227           << OldOvl;
3228 
3229       if (OldOvl)
3230         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3231       else
3232         New->dropAttr<OverloadableAttr>();
3233     }
3234   }
3235 
3236   // If a function is first declared with a calling convention, but is later
3237   // declared or defined without one, all following decls assume the calling
3238   // convention of the first.
3239   //
3240   // It's OK if a function is first declared without a calling convention,
3241   // but is later declared or defined with the default calling convention.
3242   //
3243   // To test if either decl has an explicit calling convention, we look for
3244   // AttributedType sugar nodes on the type as written.  If they are missing or
3245   // were canonicalized away, we assume the calling convention was implicit.
3246   //
3247   // Note also that we DO NOT return at this point, because we still have
3248   // other tests to run.
3249   QualType OldQType = Context.getCanonicalType(Old->getType());
3250   QualType NewQType = Context.getCanonicalType(New->getType());
3251   const FunctionType *OldType = cast<FunctionType>(OldQType);
3252   const FunctionType *NewType = cast<FunctionType>(NewQType);
3253   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3254   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3255   bool RequiresAdjustment = false;
3256 
3257   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3258     FunctionDecl *First = Old->getFirstDecl();
3259     const FunctionType *FT =
3260         First->getType().getCanonicalType()->castAs<FunctionType>();
3261     FunctionType::ExtInfo FI = FT->getExtInfo();
3262     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3263     if (!NewCCExplicit) {
3264       // Inherit the CC from the previous declaration if it was specified
3265       // there but not here.
3266       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3267       RequiresAdjustment = true;
3268     } else if (New->getBuiltinID()) {
3269       // Calling Conventions on a Builtin aren't really useful and setting a
3270       // default calling convention and cdecl'ing some builtin redeclarations is
3271       // common, so warn and ignore the calling convention on the redeclaration.
3272       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3273           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3274           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3275       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3276       RequiresAdjustment = true;
3277     } else {
3278       // Calling conventions aren't compatible, so complain.
3279       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3280       Diag(New->getLocation(), diag::err_cconv_change)
3281         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3282         << !FirstCCExplicit
3283         << (!FirstCCExplicit ? "" :
3284             FunctionType::getNameForCallConv(FI.getCC()));
3285 
3286       // Put the note on the first decl, since it is the one that matters.
3287       Diag(First->getLocation(), diag::note_previous_declaration);
3288       return true;
3289     }
3290   }
3291 
3292   // FIXME: diagnose the other way around?
3293   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3294     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3295     RequiresAdjustment = true;
3296   }
3297 
3298   // Merge regparm attribute.
3299   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3300       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3301     if (NewTypeInfo.getHasRegParm()) {
3302       Diag(New->getLocation(), diag::err_regparm_mismatch)
3303         << NewType->getRegParmType()
3304         << OldType->getRegParmType();
3305       Diag(OldLocation, diag::note_previous_declaration);
3306       return true;
3307     }
3308 
3309     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3310     RequiresAdjustment = true;
3311   }
3312 
3313   // Merge ns_returns_retained attribute.
3314   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3315     if (NewTypeInfo.getProducesResult()) {
3316       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3317           << "'ns_returns_retained'";
3318       Diag(OldLocation, diag::note_previous_declaration);
3319       return true;
3320     }
3321 
3322     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3323     RequiresAdjustment = true;
3324   }
3325 
3326   if (OldTypeInfo.getNoCallerSavedRegs() !=
3327       NewTypeInfo.getNoCallerSavedRegs()) {
3328     if (NewTypeInfo.getNoCallerSavedRegs()) {
3329       AnyX86NoCallerSavedRegistersAttr *Attr =
3330         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3331       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3332       Diag(OldLocation, diag::note_previous_declaration);
3333       return true;
3334     }
3335 
3336     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3337     RequiresAdjustment = true;
3338   }
3339 
3340   if (RequiresAdjustment) {
3341     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3342     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3343     New->setType(QualType(AdjustedType, 0));
3344     NewQType = Context.getCanonicalType(New->getType());
3345   }
3346 
3347   // If this redeclaration makes the function inline, we may need to add it to
3348   // UndefinedButUsed.
3349   if (!Old->isInlined() && New->isInlined() &&
3350       !New->hasAttr<GNUInlineAttr>() &&
3351       !getLangOpts().GNUInline &&
3352       Old->isUsed(false) &&
3353       !Old->isDefined() && !New->isThisDeclarationADefinition())
3354     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3355                                            SourceLocation()));
3356 
3357   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3358   // about it.
3359   if (New->hasAttr<GNUInlineAttr>() &&
3360       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3361     UndefinedButUsed.erase(Old->getCanonicalDecl());
3362   }
3363 
3364   // If pass_object_size params don't match up perfectly, this isn't a valid
3365   // redeclaration.
3366   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3367       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3368     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3369         << New->getDeclName();
3370     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3371     return true;
3372   }
3373 
3374   if (getLangOpts().CPlusPlus) {
3375     // C++1z [over.load]p2
3376     //   Certain function declarations cannot be overloaded:
3377     //     -- Function declarations that differ only in the return type,
3378     //        the exception specification, or both cannot be overloaded.
3379 
3380     // Check the exception specifications match. This may recompute the type of
3381     // both Old and New if it resolved exception specifications, so grab the
3382     // types again after this. Because this updates the type, we do this before
3383     // any of the other checks below, which may update the "de facto" NewQType
3384     // but do not necessarily update the type of New.
3385     if (CheckEquivalentExceptionSpec(Old, New))
3386       return true;
3387     OldQType = Context.getCanonicalType(Old->getType());
3388     NewQType = Context.getCanonicalType(New->getType());
3389 
3390     // Go back to the type source info to compare the declared return types,
3391     // per C++1y [dcl.type.auto]p13:
3392     //   Redeclarations or specializations of a function or function template
3393     //   with a declared return type that uses a placeholder type shall also
3394     //   use that placeholder, not a deduced type.
3395     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3396     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3397     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3398         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3399                                        OldDeclaredReturnType)) {
3400       QualType ResQT;
3401       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3402           OldDeclaredReturnType->isObjCObjectPointerType())
3403         // FIXME: This does the wrong thing for a deduced return type.
3404         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3405       if (ResQT.isNull()) {
3406         if (New->isCXXClassMember() && New->isOutOfLine())
3407           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3408               << New << New->getReturnTypeSourceRange();
3409         else
3410           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3411               << New->getReturnTypeSourceRange();
3412         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3413                                     << Old->getReturnTypeSourceRange();
3414         return true;
3415       }
3416       else
3417         NewQType = ResQT;
3418     }
3419 
3420     QualType OldReturnType = OldType->getReturnType();
3421     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3422     if (OldReturnType != NewReturnType) {
3423       // If this function has a deduced return type and has already been
3424       // defined, copy the deduced value from the old declaration.
3425       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3426       if (OldAT && OldAT->isDeduced()) {
3427         New->setType(
3428             SubstAutoType(New->getType(),
3429                           OldAT->isDependentType() ? Context.DependentTy
3430                                                    : OldAT->getDeducedType()));
3431         NewQType = Context.getCanonicalType(
3432             SubstAutoType(NewQType,
3433                           OldAT->isDependentType() ? Context.DependentTy
3434                                                    : OldAT->getDeducedType()));
3435       }
3436     }
3437 
3438     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3439     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3440     if (OldMethod && NewMethod) {
3441       // Preserve triviality.
3442       NewMethod->setTrivial(OldMethod->isTrivial());
3443 
3444       // MSVC allows explicit template specialization at class scope:
3445       // 2 CXXMethodDecls referring to the same function will be injected.
3446       // We don't want a redeclaration error.
3447       bool IsClassScopeExplicitSpecialization =
3448                               OldMethod->isFunctionTemplateSpecialization() &&
3449                               NewMethod->isFunctionTemplateSpecialization();
3450       bool isFriend = NewMethod->getFriendObjectKind();
3451 
3452       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3453           !IsClassScopeExplicitSpecialization) {
3454         //    -- Member function declarations with the same name and the
3455         //       same parameter types cannot be overloaded if any of them
3456         //       is a static member function declaration.
3457         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3458           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3459           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3460           return true;
3461         }
3462 
3463         // C++ [class.mem]p1:
3464         //   [...] A member shall not be declared twice in the
3465         //   member-specification, except that a nested class or member
3466         //   class template can be declared and then later defined.
3467         if (!inTemplateInstantiation()) {
3468           unsigned NewDiag;
3469           if (isa<CXXConstructorDecl>(OldMethod))
3470             NewDiag = diag::err_constructor_redeclared;
3471           else if (isa<CXXDestructorDecl>(NewMethod))
3472             NewDiag = diag::err_destructor_redeclared;
3473           else if (isa<CXXConversionDecl>(NewMethod))
3474             NewDiag = diag::err_conv_function_redeclared;
3475           else
3476             NewDiag = diag::err_member_redeclared;
3477 
3478           Diag(New->getLocation(), NewDiag);
3479         } else {
3480           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3481             << New << New->getType();
3482         }
3483         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3484         return true;
3485 
3486       // Complain if this is an explicit declaration of a special
3487       // member that was initially declared implicitly.
3488       //
3489       // As an exception, it's okay to befriend such methods in order
3490       // to permit the implicit constructor/destructor/operator calls.
3491       } else if (OldMethod->isImplicit()) {
3492         if (isFriend) {
3493           NewMethod->setImplicit();
3494         } else {
3495           Diag(NewMethod->getLocation(),
3496                diag::err_definition_of_implicitly_declared_member)
3497             << New << getSpecialMember(OldMethod);
3498           return true;
3499         }
3500       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3501         Diag(NewMethod->getLocation(),
3502              diag::err_definition_of_explicitly_defaulted_member)
3503           << getSpecialMember(OldMethod);
3504         return true;
3505       }
3506     }
3507 
3508     // C++11 [dcl.attr.noreturn]p1:
3509     //   The first declaration of a function shall specify the noreturn
3510     //   attribute if any declaration of that function specifies the noreturn
3511     //   attribute.
3512     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3513     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3514       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3515       Diag(Old->getFirstDecl()->getLocation(),
3516            diag::note_noreturn_missing_first_decl);
3517     }
3518 
3519     // C++11 [dcl.attr.depend]p2:
3520     //   The first declaration of a function shall specify the
3521     //   carries_dependency attribute for its declarator-id if any declaration
3522     //   of the function specifies the carries_dependency attribute.
3523     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3524     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3525       Diag(CDA->getLocation(),
3526            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3527       Diag(Old->getFirstDecl()->getLocation(),
3528            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3529     }
3530 
3531     // (C++98 8.3.5p3):
3532     //   All declarations for a function shall agree exactly in both the
3533     //   return type and the parameter-type-list.
3534     // We also want to respect all the extended bits except noreturn.
3535 
3536     // noreturn should now match unless the old type info didn't have it.
3537     QualType OldQTypeForComparison = OldQType;
3538     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3539       auto *OldType = OldQType->castAs<FunctionProtoType>();
3540       const FunctionType *OldTypeForComparison
3541         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3542       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3543       assert(OldQTypeForComparison.isCanonical());
3544     }
3545 
3546     if (haveIncompatibleLanguageLinkages(Old, New)) {
3547       // As a special case, retain the language linkage from previous
3548       // declarations of a friend function as an extension.
3549       //
3550       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3551       // and is useful because there's otherwise no way to specify language
3552       // linkage within class scope.
3553       //
3554       // Check cautiously as the friend object kind isn't yet complete.
3555       if (New->getFriendObjectKind() != Decl::FOK_None) {
3556         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3557         Diag(OldLocation, PrevDiag);
3558       } else {
3559         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3560         Diag(OldLocation, PrevDiag);
3561         return true;
3562       }
3563     }
3564 
3565     // If the function types are compatible, merge the declarations. Ignore the
3566     // exception specifier because it was already checked above in
3567     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3568     // about incompatible types under -fms-compatibility.
3569     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3570                                                          NewQType))
3571       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3572 
3573     // If the types are imprecise (due to dependent constructs in friends or
3574     // local extern declarations), it's OK if they differ. We'll check again
3575     // during instantiation.
3576     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3577       return false;
3578 
3579     // Fall through for conflicting redeclarations and redefinitions.
3580   }
3581 
3582   // C: Function types need to be compatible, not identical. This handles
3583   // duplicate function decls like "void f(int); void f(enum X);" properly.
3584   if (!getLangOpts().CPlusPlus &&
3585       Context.typesAreCompatible(OldQType, NewQType)) {
3586     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3587     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3588     const FunctionProtoType *OldProto = nullptr;
3589     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3590         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3591       // The old declaration provided a function prototype, but the
3592       // new declaration does not. Merge in the prototype.
3593       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3594       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3595       NewQType =
3596           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3597                                   OldProto->getExtProtoInfo());
3598       New->setType(NewQType);
3599       New->setHasInheritedPrototype();
3600 
3601       // Synthesize parameters with the same types.
3602       SmallVector<ParmVarDecl*, 16> Params;
3603       for (const auto &ParamType : OldProto->param_types()) {
3604         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3605                                                  SourceLocation(), nullptr,
3606                                                  ParamType, /*TInfo=*/nullptr,
3607                                                  SC_None, nullptr);
3608         Param->setScopeInfo(0, Params.size());
3609         Param->setImplicit();
3610         Params.push_back(Param);
3611       }
3612 
3613       New->setParams(Params);
3614     }
3615 
3616     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3617   }
3618 
3619   // GNU C permits a K&R definition to follow a prototype declaration
3620   // if the declared types of the parameters in the K&R definition
3621   // match the types in the prototype declaration, even when the
3622   // promoted types of the parameters from the K&R definition differ
3623   // from the types in the prototype. GCC then keeps the types from
3624   // the prototype.
3625   //
3626   // If a variadic prototype is followed by a non-variadic K&R definition,
3627   // the K&R definition becomes variadic.  This is sort of an edge case, but
3628   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3629   // C99 6.9.1p8.
3630   if (!getLangOpts().CPlusPlus &&
3631       Old->hasPrototype() && !New->hasPrototype() &&
3632       New->getType()->getAs<FunctionProtoType>() &&
3633       Old->getNumParams() == New->getNumParams()) {
3634     SmallVector<QualType, 16> ArgTypes;
3635     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3636     const FunctionProtoType *OldProto
3637       = Old->getType()->getAs<FunctionProtoType>();
3638     const FunctionProtoType *NewProto
3639       = New->getType()->getAs<FunctionProtoType>();
3640 
3641     // Determine whether this is the GNU C extension.
3642     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3643                                                NewProto->getReturnType());
3644     bool LooseCompatible = !MergedReturn.isNull();
3645     for (unsigned Idx = 0, End = Old->getNumParams();
3646          LooseCompatible && Idx != End; ++Idx) {
3647       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3648       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3649       if (Context.typesAreCompatible(OldParm->getType(),
3650                                      NewProto->getParamType(Idx))) {
3651         ArgTypes.push_back(NewParm->getType());
3652       } else if (Context.typesAreCompatible(OldParm->getType(),
3653                                             NewParm->getType(),
3654                                             /*CompareUnqualified=*/true)) {
3655         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3656                                            NewProto->getParamType(Idx) };
3657         Warnings.push_back(Warn);
3658         ArgTypes.push_back(NewParm->getType());
3659       } else
3660         LooseCompatible = false;
3661     }
3662 
3663     if (LooseCompatible) {
3664       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3665         Diag(Warnings[Warn].NewParm->getLocation(),
3666              diag::ext_param_promoted_not_compatible_with_prototype)
3667           << Warnings[Warn].PromotedType
3668           << Warnings[Warn].OldParm->getType();
3669         if (Warnings[Warn].OldParm->getLocation().isValid())
3670           Diag(Warnings[Warn].OldParm->getLocation(),
3671                diag::note_previous_declaration);
3672       }
3673 
3674       if (MergeTypeWithOld)
3675         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3676                                              OldProto->getExtProtoInfo()));
3677       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3678     }
3679 
3680     // Fall through to diagnose conflicting types.
3681   }
3682 
3683   // A function that has already been declared has been redeclared or
3684   // defined with a different type; show an appropriate diagnostic.
3685 
3686   // If the previous declaration was an implicitly-generated builtin
3687   // declaration, then at the very least we should use a specialized note.
3688   unsigned BuiltinID;
3689   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3690     // If it's actually a library-defined builtin function like 'malloc'
3691     // or 'printf', just warn about the incompatible redeclaration.
3692     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3693       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3694       Diag(OldLocation, diag::note_previous_builtin_declaration)
3695         << Old << Old->getType();
3696 
3697       // If this is a global redeclaration, just forget hereafter
3698       // about the "builtin-ness" of the function.
3699       //
3700       // Doing this for local extern declarations is problematic.  If
3701       // the builtin declaration remains visible, a second invalid
3702       // local declaration will produce a hard error; if it doesn't
3703       // remain visible, a single bogus local redeclaration (which is
3704       // actually only a warning) could break all the downstream code.
3705       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3706         New->getIdentifier()->revertBuiltin();
3707 
3708       return false;
3709     }
3710 
3711     PrevDiag = diag::note_previous_builtin_declaration;
3712   }
3713 
3714   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3715   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3716   return true;
3717 }
3718 
3719 /// Completes the merge of two function declarations that are
3720 /// known to be compatible.
3721 ///
3722 /// This routine handles the merging of attributes and other
3723 /// properties of function declarations from the old declaration to
3724 /// the new declaration, once we know that New is in fact a
3725 /// redeclaration of Old.
3726 ///
3727 /// \returns false
3728 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3729                                         Scope *S, bool MergeTypeWithOld) {
3730   // Merge the attributes
3731   mergeDeclAttributes(New, Old);
3732 
3733   // Merge "pure" flag.
3734   if (Old->isPure())
3735     New->setPure();
3736 
3737   // Merge "used" flag.
3738   if (Old->getMostRecentDecl()->isUsed(false))
3739     New->setIsUsed();
3740 
3741   // Merge attributes from the parameters.  These can mismatch with K&R
3742   // declarations.
3743   if (New->getNumParams() == Old->getNumParams())
3744       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3745         ParmVarDecl *NewParam = New->getParamDecl(i);
3746         ParmVarDecl *OldParam = Old->getParamDecl(i);
3747         mergeParamDeclAttributes(NewParam, OldParam, *this);
3748         mergeParamDeclTypes(NewParam, OldParam, *this);
3749       }
3750 
3751   if (getLangOpts().CPlusPlus)
3752     return MergeCXXFunctionDecl(New, Old, S);
3753 
3754   // Merge the function types so the we get the composite types for the return
3755   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3756   // was visible.
3757   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3758   if (!Merged.isNull() && MergeTypeWithOld)
3759     New->setType(Merged);
3760 
3761   return false;
3762 }
3763 
3764 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3765                                 ObjCMethodDecl *oldMethod) {
3766   // Merge the attributes, including deprecated/unavailable
3767   AvailabilityMergeKind MergeKind =
3768     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3769       ? AMK_ProtocolImplementation
3770       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3771                                                        : AMK_Override;
3772 
3773   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3774 
3775   // Merge attributes from the parameters.
3776   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3777                                        oe = oldMethod->param_end();
3778   for (ObjCMethodDecl::param_iterator
3779          ni = newMethod->param_begin(), ne = newMethod->param_end();
3780        ni != ne && oi != oe; ++ni, ++oi)
3781     mergeParamDeclAttributes(*ni, *oi, *this);
3782 
3783   CheckObjCMethodOverride(newMethod, oldMethod);
3784 }
3785 
3786 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3787   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3788 
3789   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3790          ? diag::err_redefinition_different_type
3791          : diag::err_redeclaration_different_type)
3792     << New->getDeclName() << New->getType() << Old->getType();
3793 
3794   diag::kind PrevDiag;
3795   SourceLocation OldLocation;
3796   std::tie(PrevDiag, OldLocation)
3797     = getNoteDiagForInvalidRedeclaration(Old, New);
3798   S.Diag(OldLocation, PrevDiag);
3799   New->setInvalidDecl();
3800 }
3801 
3802 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3803 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3804 /// emitting diagnostics as appropriate.
3805 ///
3806 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3807 /// to here in AddInitializerToDecl. We can't check them before the initializer
3808 /// is attached.
3809 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3810                              bool MergeTypeWithOld) {
3811   if (New->isInvalidDecl() || Old->isInvalidDecl())
3812     return;
3813 
3814   QualType MergedT;
3815   if (getLangOpts().CPlusPlus) {
3816     if (New->getType()->isUndeducedType()) {
3817       // We don't know what the new type is until the initializer is attached.
3818       return;
3819     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3820       // These could still be something that needs exception specs checked.
3821       return MergeVarDeclExceptionSpecs(New, Old);
3822     }
3823     // C++ [basic.link]p10:
3824     //   [...] the types specified by all declarations referring to a given
3825     //   object or function shall be identical, except that declarations for an
3826     //   array object can specify array types that differ by the presence or
3827     //   absence of a major array bound (8.3.4).
3828     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3829       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3830       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3831 
3832       // We are merging a variable declaration New into Old. If it has an array
3833       // bound, and that bound differs from Old's bound, we should diagnose the
3834       // mismatch.
3835       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3836         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3837              PrevVD = PrevVD->getPreviousDecl()) {
3838           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3839           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3840             continue;
3841 
3842           if (!Context.hasSameType(NewArray, PrevVDTy))
3843             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3844         }
3845       }
3846 
3847       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3848         if (Context.hasSameType(OldArray->getElementType(),
3849                                 NewArray->getElementType()))
3850           MergedT = New->getType();
3851       }
3852       // FIXME: Check visibility. New is hidden but has a complete type. If New
3853       // has no array bound, it should not inherit one from Old, if Old is not
3854       // visible.
3855       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3856         if (Context.hasSameType(OldArray->getElementType(),
3857                                 NewArray->getElementType()))
3858           MergedT = Old->getType();
3859       }
3860     }
3861     else if (New->getType()->isObjCObjectPointerType() &&
3862                Old->getType()->isObjCObjectPointerType()) {
3863       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3864                                               Old->getType());
3865     }
3866   } else {
3867     // C 6.2.7p2:
3868     //   All declarations that refer to the same object or function shall have
3869     //   compatible type.
3870     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3871   }
3872   if (MergedT.isNull()) {
3873     // It's OK if we couldn't merge types if either type is dependent, for a
3874     // block-scope variable. In other cases (static data members of class
3875     // templates, variable templates, ...), we require the types to be
3876     // equivalent.
3877     // FIXME: The C++ standard doesn't say anything about this.
3878     if ((New->getType()->isDependentType() ||
3879          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3880       // If the old type was dependent, we can't merge with it, so the new type
3881       // becomes dependent for now. We'll reproduce the original type when we
3882       // instantiate the TypeSourceInfo for the variable.
3883       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3884         New->setType(Context.DependentTy);
3885       return;
3886     }
3887     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3888   }
3889 
3890   // Don't actually update the type on the new declaration if the old
3891   // declaration was an extern declaration in a different scope.
3892   if (MergeTypeWithOld)
3893     New->setType(MergedT);
3894 }
3895 
3896 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3897                                   LookupResult &Previous) {
3898   // C11 6.2.7p4:
3899   //   For an identifier with internal or external linkage declared
3900   //   in a scope in which a prior declaration of that identifier is
3901   //   visible, if the prior declaration specifies internal or
3902   //   external linkage, the type of the identifier at the later
3903   //   declaration becomes the composite type.
3904   //
3905   // If the variable isn't visible, we do not merge with its type.
3906   if (Previous.isShadowed())
3907     return false;
3908 
3909   if (S.getLangOpts().CPlusPlus) {
3910     // C++11 [dcl.array]p3:
3911     //   If there is a preceding declaration of the entity in the same
3912     //   scope in which the bound was specified, an omitted array bound
3913     //   is taken to be the same as in that earlier declaration.
3914     return NewVD->isPreviousDeclInSameBlockScope() ||
3915            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3916             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3917   } else {
3918     // If the old declaration was function-local, don't merge with its
3919     // type unless we're in the same function.
3920     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3921            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3922   }
3923 }
3924 
3925 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3926 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3927 /// situation, merging decls or emitting diagnostics as appropriate.
3928 ///
3929 /// Tentative definition rules (C99 6.9.2p2) are checked by
3930 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3931 /// definitions here, since the initializer hasn't been attached.
3932 ///
3933 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3934   // If the new decl is already invalid, don't do any other checking.
3935   if (New->isInvalidDecl())
3936     return;
3937 
3938   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3939     return;
3940 
3941   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3942 
3943   // Verify the old decl was also a variable or variable template.
3944   VarDecl *Old = nullptr;
3945   VarTemplateDecl *OldTemplate = nullptr;
3946   if (Previous.isSingleResult()) {
3947     if (NewTemplate) {
3948       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3949       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3950 
3951       if (auto *Shadow =
3952               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3953         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3954           return New->setInvalidDecl();
3955     } else {
3956       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3957 
3958       if (auto *Shadow =
3959               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3960         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3961           return New->setInvalidDecl();
3962     }
3963   }
3964   if (!Old) {
3965     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3966         << New->getDeclName();
3967     notePreviousDefinition(Previous.getRepresentativeDecl(),
3968                            New->getLocation());
3969     return New->setInvalidDecl();
3970   }
3971 
3972   // Ensure the template parameters are compatible.
3973   if (NewTemplate &&
3974       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3975                                       OldTemplate->getTemplateParameters(),
3976                                       /*Complain=*/true, TPL_TemplateMatch))
3977     return New->setInvalidDecl();
3978 
3979   // C++ [class.mem]p1:
3980   //   A member shall not be declared twice in the member-specification [...]
3981   //
3982   // Here, we need only consider static data members.
3983   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3984     Diag(New->getLocation(), diag::err_duplicate_member)
3985       << New->getIdentifier();
3986     Diag(Old->getLocation(), diag::note_previous_declaration);
3987     New->setInvalidDecl();
3988   }
3989 
3990   mergeDeclAttributes(New, Old);
3991   // Warn if an already-declared variable is made a weak_import in a subsequent
3992   // declaration
3993   if (New->hasAttr<WeakImportAttr>() &&
3994       Old->getStorageClass() == SC_None &&
3995       !Old->hasAttr<WeakImportAttr>()) {
3996     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3997     notePreviousDefinition(Old, New->getLocation());
3998     // Remove weak_import attribute on new declaration.
3999     New->dropAttr<WeakImportAttr>();
4000   }
4001 
4002   if (New->hasAttr<InternalLinkageAttr>() &&
4003       !Old->hasAttr<InternalLinkageAttr>()) {
4004     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
4005         << New->getDeclName();
4006     notePreviousDefinition(Old, New->getLocation());
4007     New->dropAttr<InternalLinkageAttr>();
4008   }
4009 
4010   // Merge the types.
4011   VarDecl *MostRecent = Old->getMostRecentDecl();
4012   if (MostRecent != Old) {
4013     MergeVarDeclTypes(New, MostRecent,
4014                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4015     if (New->isInvalidDecl())
4016       return;
4017   }
4018 
4019   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4020   if (New->isInvalidDecl())
4021     return;
4022 
4023   diag::kind PrevDiag;
4024   SourceLocation OldLocation;
4025   std::tie(PrevDiag, OldLocation) =
4026       getNoteDiagForInvalidRedeclaration(Old, New);
4027 
4028   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4029   if (New->getStorageClass() == SC_Static &&
4030       !New->isStaticDataMember() &&
4031       Old->hasExternalFormalLinkage()) {
4032     if (getLangOpts().MicrosoftExt) {
4033       Diag(New->getLocation(), diag::ext_static_non_static)
4034           << New->getDeclName();
4035       Diag(OldLocation, PrevDiag);
4036     } else {
4037       Diag(New->getLocation(), diag::err_static_non_static)
4038           << New->getDeclName();
4039       Diag(OldLocation, PrevDiag);
4040       return New->setInvalidDecl();
4041     }
4042   }
4043   // C99 6.2.2p4:
4044   //   For an identifier declared with the storage-class specifier
4045   //   extern in a scope in which a prior declaration of that
4046   //   identifier is visible,23) if the prior declaration specifies
4047   //   internal or external linkage, the linkage of the identifier at
4048   //   the later declaration is the same as the linkage specified at
4049   //   the prior declaration. If no prior declaration is visible, or
4050   //   if the prior declaration specifies no linkage, then the
4051   //   identifier has external linkage.
4052   if (New->hasExternalStorage() && Old->hasLinkage())
4053     /* Okay */;
4054   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4055            !New->isStaticDataMember() &&
4056            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4057     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4058     Diag(OldLocation, PrevDiag);
4059     return New->setInvalidDecl();
4060   }
4061 
4062   // Check if extern is followed by non-extern and vice-versa.
4063   if (New->hasExternalStorage() &&
4064       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4065     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4066     Diag(OldLocation, PrevDiag);
4067     return New->setInvalidDecl();
4068   }
4069   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4070       !New->hasExternalStorage()) {
4071     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4072     Diag(OldLocation, PrevDiag);
4073     return New->setInvalidDecl();
4074   }
4075 
4076   if (CheckRedeclarationModuleOwnership(New, Old))
4077     return;
4078 
4079   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4080 
4081   // FIXME: The test for external storage here seems wrong? We still
4082   // need to check for mismatches.
4083   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4084       // Don't complain about out-of-line definitions of static members.
4085       !(Old->getLexicalDeclContext()->isRecord() &&
4086         !New->getLexicalDeclContext()->isRecord())) {
4087     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4088     Diag(OldLocation, PrevDiag);
4089     return New->setInvalidDecl();
4090   }
4091 
4092   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4093     if (VarDecl *Def = Old->getDefinition()) {
4094       // C++1z [dcl.fcn.spec]p4:
4095       //   If the definition of a variable appears in a translation unit before
4096       //   its first declaration as inline, the program is ill-formed.
4097       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4098       Diag(Def->getLocation(), diag::note_previous_definition);
4099     }
4100   }
4101 
4102   // If this redeclaration makes the variable inline, we may need to add it to
4103   // UndefinedButUsed.
4104   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4105       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4106     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4107                                            SourceLocation()));
4108 
4109   if (New->getTLSKind() != Old->getTLSKind()) {
4110     if (!Old->getTLSKind()) {
4111       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4112       Diag(OldLocation, PrevDiag);
4113     } else if (!New->getTLSKind()) {
4114       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4115       Diag(OldLocation, PrevDiag);
4116     } else {
4117       // Do not allow redeclaration to change the variable between requiring
4118       // static and dynamic initialization.
4119       // FIXME: GCC allows this, but uses the TLS keyword on the first
4120       // declaration to determine the kind. Do we need to be compatible here?
4121       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4122         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4123       Diag(OldLocation, PrevDiag);
4124     }
4125   }
4126 
4127   // C++ doesn't have tentative definitions, so go right ahead and check here.
4128   if (getLangOpts().CPlusPlus &&
4129       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4130     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4131         Old->getCanonicalDecl()->isConstexpr()) {
4132       // This definition won't be a definition any more once it's been merged.
4133       Diag(New->getLocation(),
4134            diag::warn_deprecated_redundant_constexpr_static_def);
4135     } else if (VarDecl *Def = Old->getDefinition()) {
4136       if (checkVarDeclRedefinition(Def, New))
4137         return;
4138     }
4139   }
4140 
4141   if (haveIncompatibleLanguageLinkages(Old, New)) {
4142     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4143     Diag(OldLocation, PrevDiag);
4144     New->setInvalidDecl();
4145     return;
4146   }
4147 
4148   // Merge "used" flag.
4149   if (Old->getMostRecentDecl()->isUsed(false))
4150     New->setIsUsed();
4151 
4152   // Keep a chain of previous declarations.
4153   New->setPreviousDecl(Old);
4154   if (NewTemplate)
4155     NewTemplate->setPreviousDecl(OldTemplate);
4156   adjustDeclContextForDeclaratorDecl(New, Old);
4157 
4158   // Inherit access appropriately.
4159   New->setAccess(Old->getAccess());
4160   if (NewTemplate)
4161     NewTemplate->setAccess(New->getAccess());
4162 
4163   if (Old->isInline())
4164     New->setImplicitlyInline();
4165 }
4166 
4167 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4168   SourceManager &SrcMgr = getSourceManager();
4169   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4170   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4171   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4172   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4173   auto &HSI = PP.getHeaderSearchInfo();
4174   StringRef HdrFilename =
4175       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4176 
4177   auto noteFromModuleOrInclude = [&](Module *Mod,
4178                                      SourceLocation IncLoc) -> bool {
4179     // Redefinition errors with modules are common with non modular mapped
4180     // headers, example: a non-modular header H in module A that also gets
4181     // included directly in a TU. Pointing twice to the same header/definition
4182     // is confusing, try to get better diagnostics when modules is on.
4183     if (IncLoc.isValid()) {
4184       if (Mod) {
4185         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4186             << HdrFilename.str() << Mod->getFullModuleName();
4187         if (!Mod->DefinitionLoc.isInvalid())
4188           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4189               << Mod->getFullModuleName();
4190       } else {
4191         Diag(IncLoc, diag::note_redefinition_include_same_file)
4192             << HdrFilename.str();
4193       }
4194       return true;
4195     }
4196 
4197     return false;
4198   };
4199 
4200   // Is it the same file and same offset? Provide more information on why
4201   // this leads to a redefinition error.
4202   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4203     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4204     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4205     bool EmittedDiag =
4206         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4207     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4208 
4209     // If the header has no guards, emit a note suggesting one.
4210     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4211       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4212 
4213     if (EmittedDiag)
4214       return;
4215   }
4216 
4217   // Redefinition coming from different files or couldn't do better above.
4218   if (Old->getLocation().isValid())
4219     Diag(Old->getLocation(), diag::note_previous_definition);
4220 }
4221 
4222 /// We've just determined that \p Old and \p New both appear to be definitions
4223 /// of the same variable. Either diagnose or fix the problem.
4224 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4225   if (!hasVisibleDefinition(Old) &&
4226       (New->getFormalLinkage() == InternalLinkage ||
4227        New->isInline() ||
4228        New->getDescribedVarTemplate() ||
4229        New->getNumTemplateParameterLists() ||
4230        New->getDeclContext()->isDependentContext())) {
4231     // The previous definition is hidden, and multiple definitions are
4232     // permitted (in separate TUs). Demote this to a declaration.
4233     New->demoteThisDefinitionToDeclaration();
4234 
4235     // Make the canonical definition visible.
4236     if (auto *OldTD = Old->getDescribedVarTemplate())
4237       makeMergedDefinitionVisible(OldTD);
4238     makeMergedDefinitionVisible(Old);
4239     return false;
4240   } else {
4241     Diag(New->getLocation(), diag::err_redefinition) << New;
4242     notePreviousDefinition(Old, New->getLocation());
4243     New->setInvalidDecl();
4244     return true;
4245   }
4246 }
4247 
4248 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4249 /// no declarator (e.g. "struct foo;") is parsed.
4250 Decl *
4251 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4252                                  RecordDecl *&AnonRecord) {
4253   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4254                                     AnonRecord);
4255 }
4256 
4257 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4258 // disambiguate entities defined in different scopes.
4259 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4260 // compatibility.
4261 // We will pick our mangling number depending on which version of MSVC is being
4262 // targeted.
4263 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4264   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4265              ? S->getMSCurManglingNumber()
4266              : S->getMSLastManglingNumber();
4267 }
4268 
4269 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4270   if (!Context.getLangOpts().CPlusPlus)
4271     return;
4272 
4273   if (isa<CXXRecordDecl>(Tag->getParent())) {
4274     // If this tag is the direct child of a class, number it if
4275     // it is anonymous.
4276     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4277       return;
4278     MangleNumberingContext &MCtx =
4279         Context.getManglingNumberContext(Tag->getParent());
4280     Context.setManglingNumber(
4281         Tag, MCtx.getManglingNumber(
4282                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4283     return;
4284   }
4285 
4286   // If this tag isn't a direct child of a class, number it if it is local.
4287   Decl *ManglingContextDecl;
4288   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4289           Tag->getDeclContext(), ManglingContextDecl)) {
4290     Context.setManglingNumber(
4291         Tag, MCtx->getManglingNumber(
4292                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4293   }
4294 }
4295 
4296 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4297                                         TypedefNameDecl *NewTD) {
4298   if (TagFromDeclSpec->isInvalidDecl())
4299     return;
4300 
4301   // Do nothing if the tag already has a name for linkage purposes.
4302   if (TagFromDeclSpec->hasNameForLinkage())
4303     return;
4304 
4305   // A well-formed anonymous tag must always be a TUK_Definition.
4306   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4307 
4308   // The type must match the tag exactly;  no qualifiers allowed.
4309   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4310                            Context.getTagDeclType(TagFromDeclSpec))) {
4311     if (getLangOpts().CPlusPlus)
4312       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4313     return;
4314   }
4315 
4316   // If we've already computed linkage for the anonymous tag, then
4317   // adding a typedef name for the anonymous decl can change that
4318   // linkage, which might be a serious problem.  Diagnose this as
4319   // unsupported and ignore the typedef name.  TODO: we should
4320   // pursue this as a language defect and establish a formal rule
4321   // for how to handle it.
4322   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4323     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4324 
4325     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4326     tagLoc = getLocForEndOfToken(tagLoc);
4327 
4328     llvm::SmallString<40> textToInsert;
4329     textToInsert += ' ';
4330     textToInsert += NewTD->getIdentifier()->getName();
4331     Diag(tagLoc, diag::note_typedef_changes_linkage)
4332         << FixItHint::CreateInsertion(tagLoc, textToInsert);
4333     return;
4334   }
4335 
4336   // Otherwise, set this is the anon-decl typedef for the tag.
4337   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4338 }
4339 
4340 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4341   switch (T) {
4342   case DeclSpec::TST_class:
4343     return 0;
4344   case DeclSpec::TST_struct:
4345     return 1;
4346   case DeclSpec::TST_interface:
4347     return 2;
4348   case DeclSpec::TST_union:
4349     return 3;
4350   case DeclSpec::TST_enum:
4351     return 4;
4352   default:
4353     llvm_unreachable("unexpected type specifier");
4354   }
4355 }
4356 
4357 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4358 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4359 /// parameters to cope with template friend declarations.
4360 Decl *
4361 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4362                                  MultiTemplateParamsArg TemplateParams,
4363                                  bool IsExplicitInstantiation,
4364                                  RecordDecl *&AnonRecord) {
4365   Decl *TagD = nullptr;
4366   TagDecl *Tag = nullptr;
4367   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4368       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4369       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4370       DS.getTypeSpecType() == DeclSpec::TST_union ||
4371       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4372     TagD = DS.getRepAsDecl();
4373 
4374     if (!TagD) // We probably had an error
4375       return nullptr;
4376 
4377     // Note that the above type specs guarantee that the
4378     // type rep is a Decl, whereas in many of the others
4379     // it's a Type.
4380     if (isa<TagDecl>(TagD))
4381       Tag = cast<TagDecl>(TagD);
4382     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4383       Tag = CTD->getTemplatedDecl();
4384   }
4385 
4386   if (Tag) {
4387     handleTagNumbering(Tag, S);
4388     Tag->setFreeStanding();
4389     if (Tag->isInvalidDecl())
4390       return Tag;
4391   }
4392 
4393   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4394     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4395     // or incomplete types shall not be restrict-qualified."
4396     if (TypeQuals & DeclSpec::TQ_restrict)
4397       Diag(DS.getRestrictSpecLoc(),
4398            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4399            << DS.getSourceRange();
4400   }
4401 
4402   if (DS.isInlineSpecified())
4403     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4404         << getLangOpts().CPlusPlus17;
4405 
4406   if (DS.hasConstexprSpecifier()) {
4407     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4408     // and definitions of functions and variables.
4409     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4410     // the declaration of a function or function template
4411     if (Tag)
4412       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4413           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4414           << DS.getConstexprSpecifier();
4415     else
4416       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4417           << DS.getConstexprSpecifier();
4418     // Don't emit warnings after this error.
4419     return TagD;
4420   }
4421 
4422   DiagnoseFunctionSpecifiers(DS);
4423 
4424   if (DS.isFriendSpecified()) {
4425     // If we're dealing with a decl but not a TagDecl, assume that
4426     // whatever routines created it handled the friendship aspect.
4427     if (TagD && !Tag)
4428       return nullptr;
4429     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4430   }
4431 
4432   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4433   bool IsExplicitSpecialization =
4434     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4435   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4436       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4437       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4438     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4439     // nested-name-specifier unless it is an explicit instantiation
4440     // or an explicit specialization.
4441     //
4442     // FIXME: We allow class template partial specializations here too, per the
4443     // obvious intent of DR1819.
4444     //
4445     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4446     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4447         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4448     return nullptr;
4449   }
4450 
4451   // Track whether this decl-specifier declares anything.
4452   bool DeclaresAnything = true;
4453 
4454   // Handle anonymous struct definitions.
4455   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4456     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4457         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4458       if (getLangOpts().CPlusPlus ||
4459           Record->getDeclContext()->isRecord()) {
4460         // If CurContext is a DeclContext that can contain statements,
4461         // RecursiveASTVisitor won't visit the decls that
4462         // BuildAnonymousStructOrUnion() will put into CurContext.
4463         // Also store them here so that they can be part of the
4464         // DeclStmt that gets created in this case.
4465         // FIXME: Also return the IndirectFieldDecls created by
4466         // BuildAnonymousStructOr union, for the same reason?
4467         if (CurContext->isFunctionOrMethod())
4468           AnonRecord = Record;
4469         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4470                                            Context.getPrintingPolicy());
4471       }
4472 
4473       DeclaresAnything = false;
4474     }
4475   }
4476 
4477   // C11 6.7.2.1p2:
4478   //   A struct-declaration that does not declare an anonymous structure or
4479   //   anonymous union shall contain a struct-declarator-list.
4480   //
4481   // This rule also existed in C89 and C99; the grammar for struct-declaration
4482   // did not permit a struct-declaration without a struct-declarator-list.
4483   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4484       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4485     // Check for Microsoft C extension: anonymous struct/union member.
4486     // Handle 2 kinds of anonymous struct/union:
4487     //   struct STRUCT;
4488     //   union UNION;
4489     // and
4490     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4491     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4492     if ((Tag && Tag->getDeclName()) ||
4493         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4494       RecordDecl *Record = nullptr;
4495       if (Tag)
4496         Record = dyn_cast<RecordDecl>(Tag);
4497       else if (const RecordType *RT =
4498                    DS.getRepAsType().get()->getAsStructureType())
4499         Record = RT->getDecl();
4500       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4501         Record = UT->getDecl();
4502 
4503       if (Record && getLangOpts().MicrosoftExt) {
4504         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4505             << Record->isUnion() << DS.getSourceRange();
4506         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4507       }
4508 
4509       DeclaresAnything = false;
4510     }
4511   }
4512 
4513   // Skip all the checks below if we have a type error.
4514   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4515       (TagD && TagD->isInvalidDecl()))
4516     return TagD;
4517 
4518   if (getLangOpts().CPlusPlus &&
4519       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4520     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4521       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4522           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4523         DeclaresAnything = false;
4524 
4525   if (!DS.isMissingDeclaratorOk()) {
4526     // Customize diagnostic for a typedef missing a name.
4527     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4528       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4529           << DS.getSourceRange();
4530     else
4531       DeclaresAnything = false;
4532   }
4533 
4534   if (DS.isModulePrivateSpecified() &&
4535       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4536     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4537       << Tag->getTagKind()
4538       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4539 
4540   ActOnDocumentableDecl(TagD);
4541 
4542   // C 6.7/2:
4543   //   A declaration [...] shall declare at least a declarator [...], a tag,
4544   //   or the members of an enumeration.
4545   // C++ [dcl.dcl]p3:
4546   //   [If there are no declarators], and except for the declaration of an
4547   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4548   //   names into the program, or shall redeclare a name introduced by a
4549   //   previous declaration.
4550   if (!DeclaresAnything) {
4551     // In C, we allow this as a (popular) extension / bug. Don't bother
4552     // producing further diagnostics for redundant qualifiers after this.
4553     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4554     return TagD;
4555   }
4556 
4557   // C++ [dcl.stc]p1:
4558   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4559   //   init-declarator-list of the declaration shall not be empty.
4560   // C++ [dcl.fct.spec]p1:
4561   //   If a cv-qualifier appears in a decl-specifier-seq, the
4562   //   init-declarator-list of the declaration shall not be empty.
4563   //
4564   // Spurious qualifiers here appear to be valid in C.
4565   unsigned DiagID = diag::warn_standalone_specifier;
4566   if (getLangOpts().CPlusPlus)
4567     DiagID = diag::ext_standalone_specifier;
4568 
4569   // Note that a linkage-specification sets a storage class, but
4570   // 'extern "C" struct foo;' is actually valid and not theoretically
4571   // useless.
4572   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4573     if (SCS == DeclSpec::SCS_mutable)
4574       // Since mutable is not a viable storage class specifier in C, there is
4575       // no reason to treat it as an extension. Instead, diagnose as an error.
4576       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4577     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4578       Diag(DS.getStorageClassSpecLoc(), DiagID)
4579         << DeclSpec::getSpecifierName(SCS);
4580   }
4581 
4582   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4583     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4584       << DeclSpec::getSpecifierName(TSCS);
4585   if (DS.getTypeQualifiers()) {
4586     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4587       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4588     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4589       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4590     // Restrict is covered above.
4591     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4592       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4593     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4594       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4595   }
4596 
4597   // Warn about ignored type attributes, for example:
4598   // __attribute__((aligned)) struct A;
4599   // Attributes should be placed after tag to apply to type declaration.
4600   if (!DS.getAttributes().empty()) {
4601     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4602     if (TypeSpecType == DeclSpec::TST_class ||
4603         TypeSpecType == DeclSpec::TST_struct ||
4604         TypeSpecType == DeclSpec::TST_interface ||
4605         TypeSpecType == DeclSpec::TST_union ||
4606         TypeSpecType == DeclSpec::TST_enum) {
4607       for (const ParsedAttr &AL : DS.getAttributes())
4608         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4609             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4610     }
4611   }
4612 
4613   return TagD;
4614 }
4615 
4616 /// We are trying to inject an anonymous member into the given scope;
4617 /// check if there's an existing declaration that can't be overloaded.
4618 ///
4619 /// \return true if this is a forbidden redeclaration
4620 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4621                                          Scope *S,
4622                                          DeclContext *Owner,
4623                                          DeclarationName Name,
4624                                          SourceLocation NameLoc,
4625                                          bool IsUnion) {
4626   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4627                  Sema::ForVisibleRedeclaration);
4628   if (!SemaRef.LookupName(R, S)) return false;
4629 
4630   // Pick a representative declaration.
4631   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4632   assert(PrevDecl && "Expected a non-null Decl");
4633 
4634   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4635     return false;
4636 
4637   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4638     << IsUnion << Name;
4639   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4640 
4641   return true;
4642 }
4643 
4644 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4645 /// anonymous struct or union AnonRecord into the owning context Owner
4646 /// and scope S. This routine will be invoked just after we realize
4647 /// that an unnamed union or struct is actually an anonymous union or
4648 /// struct, e.g.,
4649 ///
4650 /// @code
4651 /// union {
4652 ///   int i;
4653 ///   float f;
4654 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4655 ///    // f into the surrounding scope.x
4656 /// @endcode
4657 ///
4658 /// This routine is recursive, injecting the names of nested anonymous
4659 /// structs/unions into the owning context and scope as well.
4660 static bool
4661 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4662                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4663                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4664   bool Invalid = false;
4665 
4666   // Look every FieldDecl and IndirectFieldDecl with a name.
4667   for (auto *D : AnonRecord->decls()) {
4668     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4669         cast<NamedDecl>(D)->getDeclName()) {
4670       ValueDecl *VD = cast<ValueDecl>(D);
4671       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4672                                        VD->getLocation(),
4673                                        AnonRecord->isUnion())) {
4674         // C++ [class.union]p2:
4675         //   The names of the members of an anonymous union shall be
4676         //   distinct from the names of any other entity in the
4677         //   scope in which the anonymous union is declared.
4678         Invalid = true;
4679       } else {
4680         // C++ [class.union]p2:
4681         //   For the purpose of name lookup, after the anonymous union
4682         //   definition, the members of the anonymous union are
4683         //   considered to have been defined in the scope in which the
4684         //   anonymous union is declared.
4685         unsigned OldChainingSize = Chaining.size();
4686         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4687           Chaining.append(IF->chain_begin(), IF->chain_end());
4688         else
4689           Chaining.push_back(VD);
4690 
4691         assert(Chaining.size() >= 2);
4692         NamedDecl **NamedChain =
4693           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4694         for (unsigned i = 0; i < Chaining.size(); i++)
4695           NamedChain[i] = Chaining[i];
4696 
4697         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4698             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4699             VD->getType(), {NamedChain, Chaining.size()});
4700 
4701         for (const auto *Attr : VD->attrs())
4702           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4703 
4704         IndirectField->setAccess(AS);
4705         IndirectField->setImplicit();
4706         SemaRef.PushOnScopeChains(IndirectField, S);
4707 
4708         // That includes picking up the appropriate access specifier.
4709         if (AS != AS_none) IndirectField->setAccess(AS);
4710 
4711         Chaining.resize(OldChainingSize);
4712       }
4713     }
4714   }
4715 
4716   return Invalid;
4717 }
4718 
4719 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4720 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4721 /// illegal input values are mapped to SC_None.
4722 static StorageClass
4723 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4724   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4725   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4726          "Parser allowed 'typedef' as storage class VarDecl.");
4727   switch (StorageClassSpec) {
4728   case DeclSpec::SCS_unspecified:    return SC_None;
4729   case DeclSpec::SCS_extern:
4730     if (DS.isExternInLinkageSpec())
4731       return SC_None;
4732     return SC_Extern;
4733   case DeclSpec::SCS_static:         return SC_Static;
4734   case DeclSpec::SCS_auto:           return SC_Auto;
4735   case DeclSpec::SCS_register:       return SC_Register;
4736   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4737     // Illegal SCSs map to None: error reporting is up to the caller.
4738   case DeclSpec::SCS_mutable:        // Fall through.
4739   case DeclSpec::SCS_typedef:        return SC_None;
4740   }
4741   llvm_unreachable("unknown storage class specifier");
4742 }
4743 
4744 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4745   assert(Record->hasInClassInitializer());
4746 
4747   for (const auto *I : Record->decls()) {
4748     const auto *FD = dyn_cast<FieldDecl>(I);
4749     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4750       FD = IFD->getAnonField();
4751     if (FD && FD->hasInClassInitializer())
4752       return FD->getLocation();
4753   }
4754 
4755   llvm_unreachable("couldn't find in-class initializer");
4756 }
4757 
4758 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4759                                       SourceLocation DefaultInitLoc) {
4760   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4761     return;
4762 
4763   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4764   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4765 }
4766 
4767 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4768                                       CXXRecordDecl *AnonUnion) {
4769   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4770     return;
4771 
4772   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4773 }
4774 
4775 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4776 /// anonymous structure or union. Anonymous unions are a C++ feature
4777 /// (C++ [class.union]) and a C11 feature; anonymous structures
4778 /// are a C11 feature and GNU C++ extension.
4779 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4780                                         AccessSpecifier AS,
4781                                         RecordDecl *Record,
4782                                         const PrintingPolicy &Policy) {
4783   DeclContext *Owner = Record->getDeclContext();
4784 
4785   // Diagnose whether this anonymous struct/union is an extension.
4786   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4787     Diag(Record->getLocation(), diag::ext_anonymous_union);
4788   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4789     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4790   else if (!Record->isUnion() && !getLangOpts().C11)
4791     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4792 
4793   // C and C++ require different kinds of checks for anonymous
4794   // structs/unions.
4795   bool Invalid = false;
4796   if (getLangOpts().CPlusPlus) {
4797     const char *PrevSpec = nullptr;
4798     if (Record->isUnion()) {
4799       // C++ [class.union]p6:
4800       // C++17 [class.union.anon]p2:
4801       //   Anonymous unions declared in a named namespace or in the
4802       //   global namespace shall be declared static.
4803       unsigned DiagID;
4804       DeclContext *OwnerScope = Owner->getRedeclContext();
4805       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4806           (OwnerScope->isTranslationUnit() ||
4807            (OwnerScope->isNamespace() &&
4808             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
4809         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4810           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4811 
4812         // Recover by adding 'static'.
4813         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4814                                PrevSpec, DiagID, Policy);
4815       }
4816       // C++ [class.union]p6:
4817       //   A storage class is not allowed in a declaration of an
4818       //   anonymous union in a class scope.
4819       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4820                isa<RecordDecl>(Owner)) {
4821         Diag(DS.getStorageClassSpecLoc(),
4822              diag::err_anonymous_union_with_storage_spec)
4823           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4824 
4825         // Recover by removing the storage specifier.
4826         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4827                                SourceLocation(),
4828                                PrevSpec, DiagID, Context.getPrintingPolicy());
4829       }
4830     }
4831 
4832     // Ignore const/volatile/restrict qualifiers.
4833     if (DS.getTypeQualifiers()) {
4834       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4835         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4836           << Record->isUnion() << "const"
4837           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4838       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4839         Diag(DS.getVolatileSpecLoc(),
4840              diag::ext_anonymous_struct_union_qualified)
4841           << Record->isUnion() << "volatile"
4842           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4843       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4844         Diag(DS.getRestrictSpecLoc(),
4845              diag::ext_anonymous_struct_union_qualified)
4846           << Record->isUnion() << "restrict"
4847           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4848       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4849         Diag(DS.getAtomicSpecLoc(),
4850              diag::ext_anonymous_struct_union_qualified)
4851           << Record->isUnion() << "_Atomic"
4852           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4853       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4854         Diag(DS.getUnalignedSpecLoc(),
4855              diag::ext_anonymous_struct_union_qualified)
4856           << Record->isUnion() << "__unaligned"
4857           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4858 
4859       DS.ClearTypeQualifiers();
4860     }
4861 
4862     // C++ [class.union]p2:
4863     //   The member-specification of an anonymous union shall only
4864     //   define non-static data members. [Note: nested types and
4865     //   functions cannot be declared within an anonymous union. ]
4866     for (auto *Mem : Record->decls()) {
4867       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4868         // C++ [class.union]p3:
4869         //   An anonymous union shall not have private or protected
4870         //   members (clause 11).
4871         assert(FD->getAccess() != AS_none);
4872         if (FD->getAccess() != AS_public) {
4873           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4874             << Record->isUnion() << (FD->getAccess() == AS_protected);
4875           Invalid = true;
4876         }
4877 
4878         // C++ [class.union]p1
4879         //   An object of a class with a non-trivial constructor, a non-trivial
4880         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4881         //   assignment operator cannot be a member of a union, nor can an
4882         //   array of such objects.
4883         if (CheckNontrivialField(FD))
4884           Invalid = true;
4885       } else if (Mem->isImplicit()) {
4886         // Any implicit members are fine.
4887       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4888         // This is a type that showed up in an
4889         // elaborated-type-specifier inside the anonymous struct or
4890         // union, but which actually declares a type outside of the
4891         // anonymous struct or union. It's okay.
4892       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4893         if (!MemRecord->isAnonymousStructOrUnion() &&
4894             MemRecord->getDeclName()) {
4895           // Visual C++ allows type definition in anonymous struct or union.
4896           if (getLangOpts().MicrosoftExt)
4897             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4898               << Record->isUnion();
4899           else {
4900             // This is a nested type declaration.
4901             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4902               << Record->isUnion();
4903             Invalid = true;
4904           }
4905         } else {
4906           // This is an anonymous type definition within another anonymous type.
4907           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4908           // not part of standard C++.
4909           Diag(MemRecord->getLocation(),
4910                diag::ext_anonymous_record_with_anonymous_type)
4911             << Record->isUnion();
4912         }
4913       } else if (isa<AccessSpecDecl>(Mem)) {
4914         // Any access specifier is fine.
4915       } else if (isa<StaticAssertDecl>(Mem)) {
4916         // In C++1z, static_assert declarations are also fine.
4917       } else {
4918         // We have something that isn't a non-static data
4919         // member. Complain about it.
4920         unsigned DK = diag::err_anonymous_record_bad_member;
4921         if (isa<TypeDecl>(Mem))
4922           DK = diag::err_anonymous_record_with_type;
4923         else if (isa<FunctionDecl>(Mem))
4924           DK = diag::err_anonymous_record_with_function;
4925         else if (isa<VarDecl>(Mem))
4926           DK = diag::err_anonymous_record_with_static;
4927 
4928         // Visual C++ allows type definition in anonymous struct or union.
4929         if (getLangOpts().MicrosoftExt &&
4930             DK == diag::err_anonymous_record_with_type)
4931           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4932             << Record->isUnion();
4933         else {
4934           Diag(Mem->getLocation(), DK) << Record->isUnion();
4935           Invalid = true;
4936         }
4937       }
4938     }
4939 
4940     // C++11 [class.union]p8 (DR1460):
4941     //   At most one variant member of a union may have a
4942     //   brace-or-equal-initializer.
4943     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4944         Owner->isRecord())
4945       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4946                                 cast<CXXRecordDecl>(Record));
4947   }
4948 
4949   if (!Record->isUnion() && !Owner->isRecord()) {
4950     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4951       << getLangOpts().CPlusPlus;
4952     Invalid = true;
4953   }
4954 
4955   // C++ [dcl.dcl]p3:
4956   //   [If there are no declarators], and except for the declaration of an
4957   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4958   //   names into the program
4959   // C++ [class.mem]p2:
4960   //   each such member-declaration shall either declare at least one member
4961   //   name of the class or declare at least one unnamed bit-field
4962   //
4963   // For C this is an error even for a named struct, and is diagnosed elsewhere.
4964   if (getLangOpts().CPlusPlus && Record->field_empty())
4965     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4966 
4967   // Mock up a declarator.
4968   Declarator Dc(DS, DeclaratorContext::MemberContext);
4969   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4970   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4971 
4972   // Create a declaration for this anonymous struct/union.
4973   NamedDecl *Anon = nullptr;
4974   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4975     Anon = FieldDecl::Create(
4976         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
4977         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
4978         /*BitWidth=*/nullptr, /*Mutable=*/false,
4979         /*InitStyle=*/ICIS_NoInit);
4980     Anon->setAccess(AS);
4981     if (getLangOpts().CPlusPlus)
4982       FieldCollector->Add(cast<FieldDecl>(Anon));
4983   } else {
4984     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4985     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4986     if (SCSpec == DeclSpec::SCS_mutable) {
4987       // mutable can only appear on non-static class members, so it's always
4988       // an error here
4989       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4990       Invalid = true;
4991       SC = SC_None;
4992     }
4993 
4994     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
4995                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4996                            Context.getTypeDeclType(Record), TInfo, SC);
4997 
4998     // Default-initialize the implicit variable. This initialization will be
4999     // trivial in almost all cases, except if a union member has an in-class
5000     // initializer:
5001     //   union { int n = 0; };
5002     ActOnUninitializedDecl(Anon);
5003   }
5004   Anon->setImplicit();
5005 
5006   // Mark this as an anonymous struct/union type.
5007   Record->setAnonymousStructOrUnion(true);
5008 
5009   // Add the anonymous struct/union object to the current
5010   // context. We'll be referencing this object when we refer to one of
5011   // its members.
5012   Owner->addDecl(Anon);
5013 
5014   // Inject the members of the anonymous struct/union into the owning
5015   // context and into the identifier resolver chain for name lookup
5016   // purposes.
5017   SmallVector<NamedDecl*, 2> Chain;
5018   Chain.push_back(Anon);
5019 
5020   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5021     Invalid = true;
5022 
5023   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5024     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5025       Decl *ManglingContextDecl;
5026       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
5027               NewVD->getDeclContext(), ManglingContextDecl)) {
5028         Context.setManglingNumber(
5029             NewVD, MCtx->getManglingNumber(
5030                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5031         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5032       }
5033     }
5034   }
5035 
5036   if (Invalid)
5037     Anon->setInvalidDecl();
5038 
5039   return Anon;
5040 }
5041 
5042 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5043 /// Microsoft C anonymous structure.
5044 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5045 /// Example:
5046 ///
5047 /// struct A { int a; };
5048 /// struct B { struct A; int b; };
5049 ///
5050 /// void foo() {
5051 ///   B var;
5052 ///   var.a = 3;
5053 /// }
5054 ///
5055 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5056                                            RecordDecl *Record) {
5057   assert(Record && "expected a record!");
5058 
5059   // Mock up a declarator.
5060   Declarator Dc(DS, DeclaratorContext::TypeNameContext);
5061   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5062   assert(TInfo && "couldn't build declarator info for anonymous struct");
5063 
5064   auto *ParentDecl = cast<RecordDecl>(CurContext);
5065   QualType RecTy = Context.getTypeDeclType(Record);
5066 
5067   // Create a declaration for this anonymous struct.
5068   NamedDecl *Anon =
5069       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5070                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5071                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5072                         /*InitStyle=*/ICIS_NoInit);
5073   Anon->setImplicit();
5074 
5075   // Add the anonymous struct object to the current context.
5076   CurContext->addDecl(Anon);
5077 
5078   // Inject the members of the anonymous struct into the current
5079   // context and into the identifier resolver chain for name lookup
5080   // purposes.
5081   SmallVector<NamedDecl*, 2> Chain;
5082   Chain.push_back(Anon);
5083 
5084   RecordDecl *RecordDef = Record->getDefinition();
5085   if (RequireCompleteType(Anon->getLocation(), RecTy,
5086                           diag::err_field_incomplete) ||
5087       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5088                                           AS_none, Chain)) {
5089     Anon->setInvalidDecl();
5090     ParentDecl->setInvalidDecl();
5091   }
5092 
5093   return Anon;
5094 }
5095 
5096 /// GetNameForDeclarator - Determine the full declaration name for the
5097 /// given Declarator.
5098 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5099   return GetNameFromUnqualifiedId(D.getName());
5100 }
5101 
5102 /// Retrieves the declaration name from a parsed unqualified-id.
5103 DeclarationNameInfo
5104 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5105   DeclarationNameInfo NameInfo;
5106   NameInfo.setLoc(Name.StartLocation);
5107 
5108   switch (Name.getKind()) {
5109 
5110   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5111   case UnqualifiedIdKind::IK_Identifier:
5112     NameInfo.setName(Name.Identifier);
5113     return NameInfo;
5114 
5115   case UnqualifiedIdKind::IK_DeductionGuideName: {
5116     // C++ [temp.deduct.guide]p3:
5117     //   The simple-template-id shall name a class template specialization.
5118     //   The template-name shall be the same identifier as the template-name
5119     //   of the simple-template-id.
5120     // These together intend to imply that the template-name shall name a
5121     // class template.
5122     // FIXME: template<typename T> struct X {};
5123     //        template<typename T> using Y = X<T>;
5124     //        Y(int) -> Y<int>;
5125     //   satisfies these rules but does not name a class template.
5126     TemplateName TN = Name.TemplateName.get().get();
5127     auto *Template = TN.getAsTemplateDecl();
5128     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5129       Diag(Name.StartLocation,
5130            diag::err_deduction_guide_name_not_class_template)
5131         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5132       if (Template)
5133         Diag(Template->getLocation(), diag::note_template_decl_here);
5134       return DeclarationNameInfo();
5135     }
5136 
5137     NameInfo.setName(
5138         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5139     return NameInfo;
5140   }
5141 
5142   case UnqualifiedIdKind::IK_OperatorFunctionId:
5143     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5144                                            Name.OperatorFunctionId.Operator));
5145     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
5146       = Name.OperatorFunctionId.SymbolLocations[0];
5147     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
5148       = Name.EndLocation.getRawEncoding();
5149     return NameInfo;
5150 
5151   case UnqualifiedIdKind::IK_LiteralOperatorId:
5152     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5153                                                            Name.Identifier));
5154     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5155     return NameInfo;
5156 
5157   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5158     TypeSourceInfo *TInfo;
5159     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5160     if (Ty.isNull())
5161       return DeclarationNameInfo();
5162     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5163                                                Context.getCanonicalType(Ty)));
5164     NameInfo.setNamedTypeInfo(TInfo);
5165     return NameInfo;
5166   }
5167 
5168   case UnqualifiedIdKind::IK_ConstructorName: {
5169     TypeSourceInfo *TInfo;
5170     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5171     if (Ty.isNull())
5172       return DeclarationNameInfo();
5173     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5174                                               Context.getCanonicalType(Ty)));
5175     NameInfo.setNamedTypeInfo(TInfo);
5176     return NameInfo;
5177   }
5178 
5179   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5180     // In well-formed code, we can only have a constructor
5181     // template-id that refers to the current context, so go there
5182     // to find the actual type being constructed.
5183     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5184     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5185       return DeclarationNameInfo();
5186 
5187     // Determine the type of the class being constructed.
5188     QualType CurClassType = Context.getTypeDeclType(CurClass);
5189 
5190     // FIXME: Check two things: that the template-id names the same type as
5191     // CurClassType, and that the template-id does not occur when the name
5192     // was qualified.
5193 
5194     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5195                                     Context.getCanonicalType(CurClassType)));
5196     // FIXME: should we retrieve TypeSourceInfo?
5197     NameInfo.setNamedTypeInfo(nullptr);
5198     return NameInfo;
5199   }
5200 
5201   case UnqualifiedIdKind::IK_DestructorName: {
5202     TypeSourceInfo *TInfo;
5203     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5204     if (Ty.isNull())
5205       return DeclarationNameInfo();
5206     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5207                                               Context.getCanonicalType(Ty)));
5208     NameInfo.setNamedTypeInfo(TInfo);
5209     return NameInfo;
5210   }
5211 
5212   case UnqualifiedIdKind::IK_TemplateId: {
5213     TemplateName TName = Name.TemplateId->Template.get();
5214     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5215     return Context.getNameForTemplate(TName, TNameLoc);
5216   }
5217 
5218   } // switch (Name.getKind())
5219 
5220   llvm_unreachable("Unknown name kind");
5221 }
5222 
5223 static QualType getCoreType(QualType Ty) {
5224   do {
5225     if (Ty->isPointerType() || Ty->isReferenceType())
5226       Ty = Ty->getPointeeType();
5227     else if (Ty->isArrayType())
5228       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5229     else
5230       return Ty.withoutLocalFastQualifiers();
5231   } while (true);
5232 }
5233 
5234 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5235 /// and Definition have "nearly" matching parameters. This heuristic is
5236 /// used to improve diagnostics in the case where an out-of-line function
5237 /// definition doesn't match any declaration within the class or namespace.
5238 /// Also sets Params to the list of indices to the parameters that differ
5239 /// between the declaration and the definition. If hasSimilarParameters
5240 /// returns true and Params is empty, then all of the parameters match.
5241 static bool hasSimilarParameters(ASTContext &Context,
5242                                      FunctionDecl *Declaration,
5243                                      FunctionDecl *Definition,
5244                                      SmallVectorImpl<unsigned> &Params) {
5245   Params.clear();
5246   if (Declaration->param_size() != Definition->param_size())
5247     return false;
5248   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5249     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5250     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5251 
5252     // The parameter types are identical
5253     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5254       continue;
5255 
5256     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5257     QualType DefParamBaseTy = getCoreType(DefParamTy);
5258     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5259     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5260 
5261     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5262         (DeclTyName && DeclTyName == DefTyName))
5263       Params.push_back(Idx);
5264     else  // The two parameters aren't even close
5265       return false;
5266   }
5267 
5268   return true;
5269 }
5270 
5271 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5272 /// declarator needs to be rebuilt in the current instantiation.
5273 /// Any bits of declarator which appear before the name are valid for
5274 /// consideration here.  That's specifically the type in the decl spec
5275 /// and the base type in any member-pointer chunks.
5276 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5277                                                     DeclarationName Name) {
5278   // The types we specifically need to rebuild are:
5279   //   - typenames, typeofs, and decltypes
5280   //   - types which will become injected class names
5281   // Of course, we also need to rebuild any type referencing such a
5282   // type.  It's safest to just say "dependent", but we call out a
5283   // few cases here.
5284 
5285   DeclSpec &DS = D.getMutableDeclSpec();
5286   switch (DS.getTypeSpecType()) {
5287   case DeclSpec::TST_typename:
5288   case DeclSpec::TST_typeofType:
5289   case DeclSpec::TST_underlyingType:
5290   case DeclSpec::TST_atomic: {
5291     // Grab the type from the parser.
5292     TypeSourceInfo *TSI = nullptr;
5293     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5294     if (T.isNull() || !T->isDependentType()) break;
5295 
5296     // Make sure there's a type source info.  This isn't really much
5297     // of a waste; most dependent types should have type source info
5298     // attached already.
5299     if (!TSI)
5300       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5301 
5302     // Rebuild the type in the current instantiation.
5303     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5304     if (!TSI) return true;
5305 
5306     // Store the new type back in the decl spec.
5307     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5308     DS.UpdateTypeRep(LocType);
5309     break;
5310   }
5311 
5312   case DeclSpec::TST_decltype:
5313   case DeclSpec::TST_typeofExpr: {
5314     Expr *E = DS.getRepAsExpr();
5315     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5316     if (Result.isInvalid()) return true;
5317     DS.UpdateExprRep(Result.get());
5318     break;
5319   }
5320 
5321   default:
5322     // Nothing to do for these decl specs.
5323     break;
5324   }
5325 
5326   // It doesn't matter what order we do this in.
5327   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5328     DeclaratorChunk &Chunk = D.getTypeObject(I);
5329 
5330     // The only type information in the declarator which can come
5331     // before the declaration name is the base type of a member
5332     // pointer.
5333     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5334       continue;
5335 
5336     // Rebuild the scope specifier in-place.
5337     CXXScopeSpec &SS = Chunk.Mem.Scope();
5338     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5339       return true;
5340   }
5341 
5342   return false;
5343 }
5344 
5345 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5346   D.setFunctionDefinitionKind(FDK_Declaration);
5347   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5348 
5349   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5350       Dcl && Dcl->getDeclContext()->isFileContext())
5351     Dcl->setTopLevelDeclInObjCContainer();
5352 
5353   if (getLangOpts().OpenCL)
5354     setCurrentOpenCLExtensionForDecl(Dcl);
5355 
5356   return Dcl;
5357 }
5358 
5359 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5360 ///   If T is the name of a class, then each of the following shall have a
5361 ///   name different from T:
5362 ///     - every static data member of class T;
5363 ///     - every member function of class T
5364 ///     - every member of class T that is itself a type;
5365 /// \returns true if the declaration name violates these rules.
5366 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5367                                    DeclarationNameInfo NameInfo) {
5368   DeclarationName Name = NameInfo.getName();
5369 
5370   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5371   while (Record && Record->isAnonymousStructOrUnion())
5372     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5373   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5374     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5375     return true;
5376   }
5377 
5378   return false;
5379 }
5380 
5381 /// Diagnose a declaration whose declarator-id has the given
5382 /// nested-name-specifier.
5383 ///
5384 /// \param SS The nested-name-specifier of the declarator-id.
5385 ///
5386 /// \param DC The declaration context to which the nested-name-specifier
5387 /// resolves.
5388 ///
5389 /// \param Name The name of the entity being declared.
5390 ///
5391 /// \param Loc The location of the name of the entity being declared.
5392 ///
5393 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5394 /// we're declaring an explicit / partial specialization / instantiation.
5395 ///
5396 /// \returns true if we cannot safely recover from this error, false otherwise.
5397 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5398                                         DeclarationName Name,
5399                                         SourceLocation Loc, bool IsTemplateId) {
5400   DeclContext *Cur = CurContext;
5401   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5402     Cur = Cur->getParent();
5403 
5404   // If the user provided a superfluous scope specifier that refers back to the
5405   // class in which the entity is already declared, diagnose and ignore it.
5406   //
5407   // class X {
5408   //   void X::f();
5409   // };
5410   //
5411   // Note, it was once ill-formed to give redundant qualification in all
5412   // contexts, but that rule was removed by DR482.
5413   if (Cur->Equals(DC)) {
5414     if (Cur->isRecord()) {
5415       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5416                                       : diag::err_member_extra_qualification)
5417         << Name << FixItHint::CreateRemoval(SS.getRange());
5418       SS.clear();
5419     } else {
5420       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5421     }
5422     return false;
5423   }
5424 
5425   // Check whether the qualifying scope encloses the scope of the original
5426   // declaration. For a template-id, we perform the checks in
5427   // CheckTemplateSpecializationScope.
5428   if (!Cur->Encloses(DC) && !IsTemplateId) {
5429     if (Cur->isRecord())
5430       Diag(Loc, diag::err_member_qualification)
5431         << Name << SS.getRange();
5432     else if (isa<TranslationUnitDecl>(DC))
5433       Diag(Loc, diag::err_invalid_declarator_global_scope)
5434         << Name << SS.getRange();
5435     else if (isa<FunctionDecl>(Cur))
5436       Diag(Loc, diag::err_invalid_declarator_in_function)
5437         << Name << SS.getRange();
5438     else if (isa<BlockDecl>(Cur))
5439       Diag(Loc, diag::err_invalid_declarator_in_block)
5440         << Name << SS.getRange();
5441     else
5442       Diag(Loc, diag::err_invalid_declarator_scope)
5443       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5444 
5445     return true;
5446   }
5447 
5448   if (Cur->isRecord()) {
5449     // Cannot qualify members within a class.
5450     Diag(Loc, diag::err_member_qualification)
5451       << Name << SS.getRange();
5452     SS.clear();
5453 
5454     // C++ constructors and destructors with incorrect scopes can break
5455     // our AST invariants by having the wrong underlying types. If
5456     // that's the case, then drop this declaration entirely.
5457     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5458          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5459         !Context.hasSameType(Name.getCXXNameType(),
5460                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5461       return true;
5462 
5463     return false;
5464   }
5465 
5466   // C++11 [dcl.meaning]p1:
5467   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5468   //   not begin with a decltype-specifer"
5469   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5470   while (SpecLoc.getPrefix())
5471     SpecLoc = SpecLoc.getPrefix();
5472   if (dyn_cast_or_null<DecltypeType>(
5473         SpecLoc.getNestedNameSpecifier()->getAsType()))
5474     Diag(Loc, diag::err_decltype_in_declarator)
5475       << SpecLoc.getTypeLoc().getSourceRange();
5476 
5477   return false;
5478 }
5479 
5480 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5481                                   MultiTemplateParamsArg TemplateParamLists) {
5482   // TODO: consider using NameInfo for diagnostic.
5483   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5484   DeclarationName Name = NameInfo.getName();
5485 
5486   // All of these full declarators require an identifier.  If it doesn't have
5487   // one, the ParsedFreeStandingDeclSpec action should be used.
5488   if (D.isDecompositionDeclarator()) {
5489     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5490   } else if (!Name) {
5491     if (!D.isInvalidType())  // Reject this if we think it is valid.
5492       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5493           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5494     return nullptr;
5495   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5496     return nullptr;
5497 
5498   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5499   // we find one that is.
5500   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5501          (S->getFlags() & Scope::TemplateParamScope) != 0)
5502     S = S->getParent();
5503 
5504   DeclContext *DC = CurContext;
5505   if (D.getCXXScopeSpec().isInvalid())
5506     D.setInvalidType();
5507   else if (D.getCXXScopeSpec().isSet()) {
5508     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5509                                         UPPC_DeclarationQualifier))
5510       return nullptr;
5511 
5512     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5513     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5514     if (!DC || isa<EnumDecl>(DC)) {
5515       // If we could not compute the declaration context, it's because the
5516       // declaration context is dependent but does not refer to a class,
5517       // class template, or class template partial specialization. Complain
5518       // and return early, to avoid the coming semantic disaster.
5519       Diag(D.getIdentifierLoc(),
5520            diag::err_template_qualified_declarator_no_match)
5521         << D.getCXXScopeSpec().getScopeRep()
5522         << D.getCXXScopeSpec().getRange();
5523       return nullptr;
5524     }
5525     bool IsDependentContext = DC->isDependentContext();
5526 
5527     if (!IsDependentContext &&
5528         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5529       return nullptr;
5530 
5531     // If a class is incomplete, do not parse entities inside it.
5532     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5533       Diag(D.getIdentifierLoc(),
5534            diag::err_member_def_undefined_record)
5535         << Name << DC << D.getCXXScopeSpec().getRange();
5536       return nullptr;
5537     }
5538     if (!D.getDeclSpec().isFriendSpecified()) {
5539       if (diagnoseQualifiedDeclaration(
5540               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5541               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5542         if (DC->isRecord())
5543           return nullptr;
5544 
5545         D.setInvalidType();
5546       }
5547     }
5548 
5549     // Check whether we need to rebuild the type of the given
5550     // declaration in the current instantiation.
5551     if (EnteringContext && IsDependentContext &&
5552         TemplateParamLists.size() != 0) {
5553       ContextRAII SavedContext(*this, DC);
5554       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5555         D.setInvalidType();
5556     }
5557   }
5558 
5559   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5560   QualType R = TInfo->getType();
5561 
5562   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5563                                       UPPC_DeclarationType))
5564     D.setInvalidType();
5565 
5566   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5567                         forRedeclarationInCurContext());
5568 
5569   // See if this is a redefinition of a variable in the same scope.
5570   if (!D.getCXXScopeSpec().isSet()) {
5571     bool IsLinkageLookup = false;
5572     bool CreateBuiltins = false;
5573 
5574     // If the declaration we're planning to build will be a function
5575     // or object with linkage, then look for another declaration with
5576     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5577     //
5578     // If the declaration we're planning to build will be declared with
5579     // external linkage in the translation unit, create any builtin with
5580     // the same name.
5581     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5582       /* Do nothing*/;
5583     else if (CurContext->isFunctionOrMethod() &&
5584              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5585               R->isFunctionType())) {
5586       IsLinkageLookup = true;
5587       CreateBuiltins =
5588           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5589     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5590                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5591       CreateBuiltins = true;
5592 
5593     if (IsLinkageLookup) {
5594       Previous.clear(LookupRedeclarationWithLinkage);
5595       Previous.setRedeclarationKind(ForExternalRedeclaration);
5596     }
5597 
5598     LookupName(Previous, S, CreateBuiltins);
5599   } else { // Something like "int foo::x;"
5600     LookupQualifiedName(Previous, DC);
5601 
5602     // C++ [dcl.meaning]p1:
5603     //   When the declarator-id is qualified, the declaration shall refer to a
5604     //  previously declared member of the class or namespace to which the
5605     //  qualifier refers (or, in the case of a namespace, of an element of the
5606     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5607     //  thereof; [...]
5608     //
5609     // Note that we already checked the context above, and that we do not have
5610     // enough information to make sure that Previous contains the declaration
5611     // we want to match. For example, given:
5612     //
5613     //   class X {
5614     //     void f();
5615     //     void f(float);
5616     //   };
5617     //
5618     //   void X::f(int) { } // ill-formed
5619     //
5620     // In this case, Previous will point to the overload set
5621     // containing the two f's declared in X, but neither of them
5622     // matches.
5623 
5624     // C++ [dcl.meaning]p1:
5625     //   [...] the member shall not merely have been introduced by a
5626     //   using-declaration in the scope of the class or namespace nominated by
5627     //   the nested-name-specifier of the declarator-id.
5628     RemoveUsingDecls(Previous);
5629   }
5630 
5631   if (Previous.isSingleResult() &&
5632       Previous.getFoundDecl()->isTemplateParameter()) {
5633     // Maybe we will complain about the shadowed template parameter.
5634     if (!D.isInvalidType())
5635       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5636                                       Previous.getFoundDecl());
5637 
5638     // Just pretend that we didn't see the previous declaration.
5639     Previous.clear();
5640   }
5641 
5642   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5643     // Forget that the previous declaration is the injected-class-name.
5644     Previous.clear();
5645 
5646   // In C++, the previous declaration we find might be a tag type
5647   // (class or enum). In this case, the new declaration will hide the
5648   // tag type. Note that this applies to functions, function templates, and
5649   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5650   if (Previous.isSingleTagDecl() &&
5651       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5652       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5653     Previous.clear();
5654 
5655   // Check that there are no default arguments other than in the parameters
5656   // of a function declaration (C++ only).
5657   if (getLangOpts().CPlusPlus)
5658     CheckExtraCXXDefaultArguments(D);
5659 
5660   NamedDecl *New;
5661 
5662   bool AddToScope = true;
5663   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5664     if (TemplateParamLists.size()) {
5665       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5666       return nullptr;
5667     }
5668 
5669     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5670   } else if (R->isFunctionType()) {
5671     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5672                                   TemplateParamLists,
5673                                   AddToScope);
5674   } else {
5675     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5676                                   AddToScope);
5677   }
5678 
5679   if (!New)
5680     return nullptr;
5681 
5682   // If this has an identifier and is not a function template specialization,
5683   // add it to the scope stack.
5684   if (New->getDeclName() && AddToScope)
5685     PushOnScopeChains(New, S);
5686 
5687   if (isInOpenMPDeclareTargetContext())
5688     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5689 
5690   return New;
5691 }
5692 
5693 /// Helper method to turn variable array types into constant array
5694 /// types in certain situations which would otherwise be errors (for
5695 /// GCC compatibility).
5696 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5697                                                     ASTContext &Context,
5698                                                     bool &SizeIsNegative,
5699                                                     llvm::APSInt &Oversized) {
5700   // This method tries to turn a variable array into a constant
5701   // array even when the size isn't an ICE.  This is necessary
5702   // for compatibility with code that depends on gcc's buggy
5703   // constant expression folding, like struct {char x[(int)(char*)2];}
5704   SizeIsNegative = false;
5705   Oversized = 0;
5706 
5707   if (T->isDependentType())
5708     return QualType();
5709 
5710   QualifierCollector Qs;
5711   const Type *Ty = Qs.strip(T);
5712 
5713   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5714     QualType Pointee = PTy->getPointeeType();
5715     QualType FixedType =
5716         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5717                                             Oversized);
5718     if (FixedType.isNull()) return FixedType;
5719     FixedType = Context.getPointerType(FixedType);
5720     return Qs.apply(Context, FixedType);
5721   }
5722   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5723     QualType Inner = PTy->getInnerType();
5724     QualType FixedType =
5725         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5726                                             Oversized);
5727     if (FixedType.isNull()) return FixedType;
5728     FixedType = Context.getParenType(FixedType);
5729     return Qs.apply(Context, FixedType);
5730   }
5731 
5732   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5733   if (!VLATy)
5734     return QualType();
5735   // FIXME: We should probably handle this case
5736   if (VLATy->getElementType()->isVariablyModifiedType())
5737     return QualType();
5738 
5739   Expr::EvalResult Result;
5740   if (!VLATy->getSizeExpr() ||
5741       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5742     return QualType();
5743 
5744   llvm::APSInt Res = Result.Val.getInt();
5745 
5746   // Check whether the array size is negative.
5747   if (Res.isSigned() && Res.isNegative()) {
5748     SizeIsNegative = true;
5749     return QualType();
5750   }
5751 
5752   // Check whether the array is too large to be addressed.
5753   unsigned ActiveSizeBits
5754     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5755                                               Res);
5756   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5757     Oversized = Res;
5758     return QualType();
5759   }
5760 
5761   return Context.getConstantArrayType(VLATy->getElementType(),
5762                                       Res, ArrayType::Normal, 0);
5763 }
5764 
5765 static void
5766 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5767   SrcTL = SrcTL.getUnqualifiedLoc();
5768   DstTL = DstTL.getUnqualifiedLoc();
5769   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5770     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5771     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5772                                       DstPTL.getPointeeLoc());
5773     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5774     return;
5775   }
5776   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5777     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5778     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5779                                       DstPTL.getInnerLoc());
5780     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5781     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5782     return;
5783   }
5784   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5785   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5786   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5787   TypeLoc DstElemTL = DstATL.getElementLoc();
5788   DstElemTL.initializeFullCopy(SrcElemTL);
5789   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5790   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5791   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5792 }
5793 
5794 /// Helper method to turn variable array types into constant array
5795 /// types in certain situations which would otherwise be errors (for
5796 /// GCC compatibility).
5797 static TypeSourceInfo*
5798 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5799                                               ASTContext &Context,
5800                                               bool &SizeIsNegative,
5801                                               llvm::APSInt &Oversized) {
5802   QualType FixedTy
5803     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5804                                           SizeIsNegative, Oversized);
5805   if (FixedTy.isNull())
5806     return nullptr;
5807   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5808   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5809                                     FixedTInfo->getTypeLoc());
5810   return FixedTInfo;
5811 }
5812 
5813 /// Register the given locally-scoped extern "C" declaration so
5814 /// that it can be found later for redeclarations. We include any extern "C"
5815 /// declaration that is not visible in the translation unit here, not just
5816 /// function-scope declarations.
5817 void
5818 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5819   if (!getLangOpts().CPlusPlus &&
5820       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5821     // Don't need to track declarations in the TU in C.
5822     return;
5823 
5824   // Note that we have a locally-scoped external with this name.
5825   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5826 }
5827 
5828 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5829   // FIXME: We can have multiple results via __attribute__((overloadable)).
5830   auto Result = Context.getExternCContextDecl()->lookup(Name);
5831   return Result.empty() ? nullptr : *Result.begin();
5832 }
5833 
5834 /// Diagnose function specifiers on a declaration of an identifier that
5835 /// does not identify a function.
5836 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5837   // FIXME: We should probably indicate the identifier in question to avoid
5838   // confusion for constructs like "virtual int a(), b;"
5839   if (DS.isVirtualSpecified())
5840     Diag(DS.getVirtualSpecLoc(),
5841          diag::err_virtual_non_function);
5842 
5843   if (DS.hasExplicitSpecifier())
5844     Diag(DS.getExplicitSpecLoc(),
5845          diag::err_explicit_non_function);
5846 
5847   if (DS.isNoreturnSpecified())
5848     Diag(DS.getNoreturnSpecLoc(),
5849          diag::err_noreturn_non_function);
5850 }
5851 
5852 NamedDecl*
5853 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5854                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5855   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5856   if (D.getCXXScopeSpec().isSet()) {
5857     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5858       << D.getCXXScopeSpec().getRange();
5859     D.setInvalidType();
5860     // Pretend we didn't see the scope specifier.
5861     DC = CurContext;
5862     Previous.clear();
5863   }
5864 
5865   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5866 
5867   if (D.getDeclSpec().isInlineSpecified())
5868     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5869         << getLangOpts().CPlusPlus17;
5870   if (D.getDeclSpec().hasConstexprSpecifier())
5871     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5872         << 1 << D.getDeclSpec().getConstexprSpecifier();
5873 
5874   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
5875     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
5876       Diag(D.getName().StartLocation,
5877            diag::err_deduction_guide_invalid_specifier)
5878           << "typedef";
5879     else
5880       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5881           << D.getName().getSourceRange();
5882     return nullptr;
5883   }
5884 
5885   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5886   if (!NewTD) return nullptr;
5887 
5888   // Handle attributes prior to checking for duplicates in MergeVarDecl
5889   ProcessDeclAttributes(S, NewTD, D);
5890 
5891   CheckTypedefForVariablyModifiedType(S, NewTD);
5892 
5893   bool Redeclaration = D.isRedeclaration();
5894   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5895   D.setRedeclaration(Redeclaration);
5896   return ND;
5897 }
5898 
5899 void
5900 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5901   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5902   // then it shall have block scope.
5903   // Note that variably modified types must be fixed before merging the decl so
5904   // that redeclarations will match.
5905   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5906   QualType T = TInfo->getType();
5907   if (T->isVariablyModifiedType()) {
5908     setFunctionHasBranchProtectedScope();
5909 
5910     if (S->getFnParent() == nullptr) {
5911       bool SizeIsNegative;
5912       llvm::APSInt Oversized;
5913       TypeSourceInfo *FixedTInfo =
5914         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5915                                                       SizeIsNegative,
5916                                                       Oversized);
5917       if (FixedTInfo) {
5918         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5919         NewTD->setTypeSourceInfo(FixedTInfo);
5920       } else {
5921         if (SizeIsNegative)
5922           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5923         else if (T->isVariableArrayType())
5924           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5925         else if (Oversized.getBoolValue())
5926           Diag(NewTD->getLocation(), diag::err_array_too_large)
5927             << Oversized.toString(10);
5928         else
5929           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5930         NewTD->setInvalidDecl();
5931       }
5932     }
5933   }
5934 }
5935 
5936 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5937 /// declares a typedef-name, either using the 'typedef' type specifier or via
5938 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5939 NamedDecl*
5940 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5941                            LookupResult &Previous, bool &Redeclaration) {
5942 
5943   // Find the shadowed declaration before filtering for scope.
5944   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5945 
5946   // Merge the decl with the existing one if appropriate. If the decl is
5947   // in an outer scope, it isn't the same thing.
5948   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5949                        /*AllowInlineNamespace*/false);
5950   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5951   if (!Previous.empty()) {
5952     Redeclaration = true;
5953     MergeTypedefNameDecl(S, NewTD, Previous);
5954   } else {
5955     inferGslPointerAttribute(NewTD);
5956   }
5957 
5958   if (ShadowedDecl && !Redeclaration)
5959     CheckShadow(NewTD, ShadowedDecl, Previous);
5960 
5961   // If this is the C FILE type, notify the AST context.
5962   if (IdentifierInfo *II = NewTD->getIdentifier())
5963     if (!NewTD->isInvalidDecl() &&
5964         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5965       if (II->isStr("FILE"))
5966         Context.setFILEDecl(NewTD);
5967       else if (II->isStr("jmp_buf"))
5968         Context.setjmp_bufDecl(NewTD);
5969       else if (II->isStr("sigjmp_buf"))
5970         Context.setsigjmp_bufDecl(NewTD);
5971       else if (II->isStr("ucontext_t"))
5972         Context.setucontext_tDecl(NewTD);
5973     }
5974 
5975   return NewTD;
5976 }
5977 
5978 /// Determines whether the given declaration is an out-of-scope
5979 /// previous declaration.
5980 ///
5981 /// This routine should be invoked when name lookup has found a
5982 /// previous declaration (PrevDecl) that is not in the scope where a
5983 /// new declaration by the same name is being introduced. If the new
5984 /// declaration occurs in a local scope, previous declarations with
5985 /// linkage may still be considered previous declarations (C99
5986 /// 6.2.2p4-5, C++ [basic.link]p6).
5987 ///
5988 /// \param PrevDecl the previous declaration found by name
5989 /// lookup
5990 ///
5991 /// \param DC the context in which the new declaration is being
5992 /// declared.
5993 ///
5994 /// \returns true if PrevDecl is an out-of-scope previous declaration
5995 /// for a new delcaration with the same name.
5996 static bool
5997 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5998                                 ASTContext &Context) {
5999   if (!PrevDecl)
6000     return false;
6001 
6002   if (!PrevDecl->hasLinkage())
6003     return false;
6004 
6005   if (Context.getLangOpts().CPlusPlus) {
6006     // C++ [basic.link]p6:
6007     //   If there is a visible declaration of an entity with linkage
6008     //   having the same name and type, ignoring entities declared
6009     //   outside the innermost enclosing namespace scope, the block
6010     //   scope declaration declares that same entity and receives the
6011     //   linkage of the previous declaration.
6012     DeclContext *OuterContext = DC->getRedeclContext();
6013     if (!OuterContext->isFunctionOrMethod())
6014       // This rule only applies to block-scope declarations.
6015       return false;
6016 
6017     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6018     if (PrevOuterContext->isRecord())
6019       // We found a member function: ignore it.
6020       return false;
6021 
6022     // Find the innermost enclosing namespace for the new and
6023     // previous declarations.
6024     OuterContext = OuterContext->getEnclosingNamespaceContext();
6025     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6026 
6027     // The previous declaration is in a different namespace, so it
6028     // isn't the same function.
6029     if (!OuterContext->Equals(PrevOuterContext))
6030       return false;
6031   }
6032 
6033   return true;
6034 }
6035 
6036 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6037   CXXScopeSpec &SS = D.getCXXScopeSpec();
6038   if (!SS.isSet()) return;
6039   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6040 }
6041 
6042 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6043   QualType type = decl->getType();
6044   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6045   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6046     // Various kinds of declaration aren't allowed to be __autoreleasing.
6047     unsigned kind = -1U;
6048     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6049       if (var->hasAttr<BlocksAttr>())
6050         kind = 0; // __block
6051       else if (!var->hasLocalStorage())
6052         kind = 1; // global
6053     } else if (isa<ObjCIvarDecl>(decl)) {
6054       kind = 3; // ivar
6055     } else if (isa<FieldDecl>(decl)) {
6056       kind = 2; // field
6057     }
6058 
6059     if (kind != -1U) {
6060       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6061         << kind;
6062     }
6063   } else if (lifetime == Qualifiers::OCL_None) {
6064     // Try to infer lifetime.
6065     if (!type->isObjCLifetimeType())
6066       return false;
6067 
6068     lifetime = type->getObjCARCImplicitLifetime();
6069     type = Context.getLifetimeQualifiedType(type, lifetime);
6070     decl->setType(type);
6071   }
6072 
6073   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6074     // Thread-local variables cannot have lifetime.
6075     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6076         var->getTLSKind()) {
6077       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6078         << var->getType();
6079       return true;
6080     }
6081   }
6082 
6083   return false;
6084 }
6085 
6086 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6087   // Ensure that an auto decl is deduced otherwise the checks below might cache
6088   // the wrong linkage.
6089   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6090 
6091   // 'weak' only applies to declarations with external linkage.
6092   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6093     if (!ND.isExternallyVisible()) {
6094       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6095       ND.dropAttr<WeakAttr>();
6096     }
6097   }
6098   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6099     if (ND.isExternallyVisible()) {
6100       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6101       ND.dropAttr<WeakRefAttr>();
6102       ND.dropAttr<AliasAttr>();
6103     }
6104   }
6105 
6106   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6107     if (VD->hasInit()) {
6108       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6109         assert(VD->isThisDeclarationADefinition() &&
6110                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6111         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6112         VD->dropAttr<AliasAttr>();
6113       }
6114     }
6115   }
6116 
6117   // 'selectany' only applies to externally visible variable declarations.
6118   // It does not apply to functions.
6119   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6120     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6121       S.Diag(Attr->getLocation(),
6122              diag::err_attribute_selectany_non_extern_data);
6123       ND.dropAttr<SelectAnyAttr>();
6124     }
6125   }
6126 
6127   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6128     auto *VD = dyn_cast<VarDecl>(&ND);
6129     bool IsAnonymousNS = false;
6130     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6131     if (VD) {
6132       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6133       while (NS && !IsAnonymousNS) {
6134         IsAnonymousNS = NS->isAnonymousNamespace();
6135         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6136       }
6137     }
6138     // dll attributes require external linkage. Static locals may have external
6139     // linkage but still cannot be explicitly imported or exported.
6140     // In Microsoft mode, a variable defined in anonymous namespace must have
6141     // external linkage in order to be exported.
6142     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6143     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6144         (!AnonNSInMicrosoftMode &&
6145          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6146       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6147         << &ND << Attr;
6148       ND.setInvalidDecl();
6149     }
6150   }
6151 
6152   // Virtual functions cannot be marked as 'notail'.
6153   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
6154     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
6155       if (MD->isVirtual()) {
6156         S.Diag(ND.getLocation(),
6157                diag::err_invalid_attribute_on_virtual_function)
6158             << Attr;
6159         ND.dropAttr<NotTailCalledAttr>();
6160       }
6161 
6162   // Check the attributes on the function type, if any.
6163   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6164     // Don't declare this variable in the second operand of the for-statement;
6165     // GCC miscompiles that by ending its lifetime before evaluating the
6166     // third operand. See gcc.gnu.org/PR86769.
6167     AttributedTypeLoc ATL;
6168     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6169          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6170          TL = ATL.getModifiedLoc()) {
6171       // The [[lifetimebound]] attribute can be applied to the implicit object
6172       // parameter of a non-static member function (other than a ctor or dtor)
6173       // by applying it to the function type.
6174       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6175         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6176         if (!MD || MD->isStatic()) {
6177           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6178               << !MD << A->getRange();
6179         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6180           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6181               << isa<CXXDestructorDecl>(MD) << A->getRange();
6182         }
6183       }
6184     }
6185   }
6186 }
6187 
6188 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6189                                            NamedDecl *NewDecl,
6190                                            bool IsSpecialization,
6191                                            bool IsDefinition) {
6192   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6193     return;
6194 
6195   bool IsTemplate = false;
6196   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6197     OldDecl = OldTD->getTemplatedDecl();
6198     IsTemplate = true;
6199     if (!IsSpecialization)
6200       IsDefinition = false;
6201   }
6202   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6203     NewDecl = NewTD->getTemplatedDecl();
6204     IsTemplate = true;
6205   }
6206 
6207   if (!OldDecl || !NewDecl)
6208     return;
6209 
6210   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6211   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6212   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6213   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6214 
6215   // dllimport and dllexport are inheritable attributes so we have to exclude
6216   // inherited attribute instances.
6217   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6218                     (NewExportAttr && !NewExportAttr->isInherited());
6219 
6220   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6221   // the only exception being explicit specializations.
6222   // Implicitly generated declarations are also excluded for now because there
6223   // is no other way to switch these to use dllimport or dllexport.
6224   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6225 
6226   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6227     // Allow with a warning for free functions and global variables.
6228     bool JustWarn = false;
6229     if (!OldDecl->isCXXClassMember()) {
6230       auto *VD = dyn_cast<VarDecl>(OldDecl);
6231       if (VD && !VD->getDescribedVarTemplate())
6232         JustWarn = true;
6233       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6234       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6235         JustWarn = true;
6236     }
6237 
6238     // We cannot change a declaration that's been used because IR has already
6239     // been emitted. Dllimported functions will still work though (modulo
6240     // address equality) as they can use the thunk.
6241     if (OldDecl->isUsed())
6242       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6243         JustWarn = false;
6244 
6245     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6246                                : diag::err_attribute_dll_redeclaration;
6247     S.Diag(NewDecl->getLocation(), DiagID)
6248         << NewDecl
6249         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6250     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6251     if (!JustWarn) {
6252       NewDecl->setInvalidDecl();
6253       return;
6254     }
6255   }
6256 
6257   // A redeclaration is not allowed to drop a dllimport attribute, the only
6258   // exceptions being inline function definitions (except for function
6259   // templates), local extern declarations, qualified friend declarations or
6260   // special MSVC extension: in the last case, the declaration is treated as if
6261   // it were marked dllexport.
6262   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6263   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6264   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6265     // Ignore static data because out-of-line definitions are diagnosed
6266     // separately.
6267     IsStaticDataMember = VD->isStaticDataMember();
6268     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6269                    VarDecl::DeclarationOnly;
6270   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6271     IsInline = FD->isInlined();
6272     IsQualifiedFriend = FD->getQualifier() &&
6273                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6274   }
6275 
6276   if (OldImportAttr && !HasNewAttr &&
6277       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6278       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6279     if (IsMicrosoft && IsDefinition) {
6280       S.Diag(NewDecl->getLocation(),
6281              diag::warn_redeclaration_without_import_attribute)
6282           << NewDecl;
6283       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6284       NewDecl->dropAttr<DLLImportAttr>();
6285       NewDecl->addAttr(
6286           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6287     } else {
6288       S.Diag(NewDecl->getLocation(),
6289              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6290           << NewDecl << OldImportAttr;
6291       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6292       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6293       OldDecl->dropAttr<DLLImportAttr>();
6294       NewDecl->dropAttr<DLLImportAttr>();
6295     }
6296   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6297     // In MinGW, seeing a function declared inline drops the dllimport
6298     // attribute.
6299     OldDecl->dropAttr<DLLImportAttr>();
6300     NewDecl->dropAttr<DLLImportAttr>();
6301     S.Diag(NewDecl->getLocation(),
6302            diag::warn_dllimport_dropped_from_inline_function)
6303         << NewDecl << OldImportAttr;
6304   }
6305 
6306   // A specialization of a class template member function is processed here
6307   // since it's a redeclaration. If the parent class is dllexport, the
6308   // specialization inherits that attribute. This doesn't happen automatically
6309   // since the parent class isn't instantiated until later.
6310   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6311     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6312         !NewImportAttr && !NewExportAttr) {
6313       if (const DLLExportAttr *ParentExportAttr =
6314               MD->getParent()->getAttr<DLLExportAttr>()) {
6315         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6316         NewAttr->setInherited(true);
6317         NewDecl->addAttr(NewAttr);
6318       }
6319     }
6320   }
6321 }
6322 
6323 /// Given that we are within the definition of the given function,
6324 /// will that definition behave like C99's 'inline', where the
6325 /// definition is discarded except for optimization purposes?
6326 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6327   // Try to avoid calling GetGVALinkageForFunction.
6328 
6329   // All cases of this require the 'inline' keyword.
6330   if (!FD->isInlined()) return false;
6331 
6332   // This is only possible in C++ with the gnu_inline attribute.
6333   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6334     return false;
6335 
6336   // Okay, go ahead and call the relatively-more-expensive function.
6337   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6338 }
6339 
6340 /// Determine whether a variable is extern "C" prior to attaching
6341 /// an initializer. We can't just call isExternC() here, because that
6342 /// will also compute and cache whether the declaration is externally
6343 /// visible, which might change when we attach the initializer.
6344 ///
6345 /// This can only be used if the declaration is known to not be a
6346 /// redeclaration of an internal linkage declaration.
6347 ///
6348 /// For instance:
6349 ///
6350 ///   auto x = []{};
6351 ///
6352 /// Attaching the initializer here makes this declaration not externally
6353 /// visible, because its type has internal linkage.
6354 ///
6355 /// FIXME: This is a hack.
6356 template<typename T>
6357 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6358   if (S.getLangOpts().CPlusPlus) {
6359     // In C++, the overloadable attribute negates the effects of extern "C".
6360     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6361       return false;
6362 
6363     // So do CUDA's host/device attributes.
6364     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6365                                  D->template hasAttr<CUDAHostAttr>()))
6366       return false;
6367   }
6368   return D->isExternC();
6369 }
6370 
6371 static bool shouldConsiderLinkage(const VarDecl *VD) {
6372   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6373   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6374       isa<OMPDeclareMapperDecl>(DC))
6375     return VD->hasExternalStorage();
6376   if (DC->isFileContext())
6377     return true;
6378   if (DC->isRecord())
6379     return false;
6380   llvm_unreachable("Unexpected context");
6381 }
6382 
6383 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6384   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6385   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6386       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6387     return true;
6388   if (DC->isRecord())
6389     return false;
6390   llvm_unreachable("Unexpected context");
6391 }
6392 
6393 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6394                           ParsedAttr::Kind Kind) {
6395   // Check decl attributes on the DeclSpec.
6396   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6397     return true;
6398 
6399   // Walk the declarator structure, checking decl attributes that were in a type
6400   // position to the decl itself.
6401   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6402     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6403       return true;
6404   }
6405 
6406   // Finally, check attributes on the decl itself.
6407   return PD.getAttributes().hasAttribute(Kind);
6408 }
6409 
6410 /// Adjust the \c DeclContext for a function or variable that might be a
6411 /// function-local external declaration.
6412 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6413   if (!DC->isFunctionOrMethod())
6414     return false;
6415 
6416   // If this is a local extern function or variable declared within a function
6417   // template, don't add it into the enclosing namespace scope until it is
6418   // instantiated; it might have a dependent type right now.
6419   if (DC->isDependentContext())
6420     return true;
6421 
6422   // C++11 [basic.link]p7:
6423   //   When a block scope declaration of an entity with linkage is not found to
6424   //   refer to some other declaration, then that entity is a member of the
6425   //   innermost enclosing namespace.
6426   //
6427   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6428   // semantically-enclosing namespace, not a lexically-enclosing one.
6429   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6430     DC = DC->getParent();
6431   return true;
6432 }
6433 
6434 /// Returns true if given declaration has external C language linkage.
6435 static bool isDeclExternC(const Decl *D) {
6436   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6437     return FD->isExternC();
6438   if (const auto *VD = dyn_cast<VarDecl>(D))
6439     return VD->isExternC();
6440 
6441   llvm_unreachable("Unknown type of decl!");
6442 }
6443 
6444 NamedDecl *Sema::ActOnVariableDeclarator(
6445     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6446     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6447     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6448   QualType R = TInfo->getType();
6449   DeclarationName Name = GetNameForDeclarator(D).getName();
6450 
6451   IdentifierInfo *II = Name.getAsIdentifierInfo();
6452 
6453   if (D.isDecompositionDeclarator()) {
6454     // Take the name of the first declarator as our name for diagnostic
6455     // purposes.
6456     auto &Decomp = D.getDecompositionDeclarator();
6457     if (!Decomp.bindings().empty()) {
6458       II = Decomp.bindings()[0].Name;
6459       Name = II;
6460     }
6461   } else if (!II) {
6462     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6463     return nullptr;
6464   }
6465 
6466   if (getLangOpts().OpenCL) {
6467     // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6468     // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6469     // argument.
6470     if (R->isImageType() || R->isPipeType()) {
6471       Diag(D.getIdentifierLoc(),
6472            diag::err_opencl_type_can_only_be_used_as_function_parameter)
6473           << R;
6474       D.setInvalidType();
6475       return nullptr;
6476     }
6477 
6478     // OpenCL v1.2 s6.9.r:
6479     // The event type cannot be used to declare a program scope variable.
6480     // OpenCL v2.0 s6.9.q:
6481     // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6482     if (NULL == S->getParent()) {
6483       if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6484         Diag(D.getIdentifierLoc(),
6485              diag::err_invalid_type_for_program_scope_var) << R;
6486         D.setInvalidType();
6487         return nullptr;
6488       }
6489     }
6490 
6491     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6492     QualType NR = R;
6493     while (NR->isPointerType()) {
6494       if (NR->isFunctionPointerType()) {
6495         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6496         D.setInvalidType();
6497         break;
6498       }
6499       NR = NR->getPointeeType();
6500     }
6501 
6502     if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6503       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6504       // half array type (unless the cl_khr_fp16 extension is enabled).
6505       if (Context.getBaseElementType(R)->isHalfType()) {
6506         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6507         D.setInvalidType();
6508       }
6509     }
6510 
6511     if (R->isSamplerT()) {
6512       // OpenCL v1.2 s6.9.b p4:
6513       // The sampler type cannot be used with the __local and __global address
6514       // space qualifiers.
6515       if (R.getAddressSpace() == LangAS::opencl_local ||
6516           R.getAddressSpace() == LangAS::opencl_global) {
6517         Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6518       }
6519 
6520       // OpenCL v1.2 s6.12.14.1:
6521       // A global sampler must be declared with either the constant address
6522       // space qualifier or with the const qualifier.
6523       if (DC->isTranslationUnit() &&
6524           !(R.getAddressSpace() == LangAS::opencl_constant ||
6525           R.isConstQualified())) {
6526         Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6527         D.setInvalidType();
6528       }
6529     }
6530 
6531     // OpenCL v1.2 s6.9.r:
6532     // The event type cannot be used with the __local, __constant and __global
6533     // address space qualifiers.
6534     if (R->isEventT()) {
6535       if (R.getAddressSpace() != LangAS::opencl_private) {
6536         Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6537         D.setInvalidType();
6538       }
6539     }
6540 
6541     // C++ for OpenCL does not allow the thread_local storage qualifier.
6542     // OpenCL C does not support thread_local either, and
6543     // also reject all other thread storage class specifiers.
6544     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6545     if (TSC != TSCS_unspecified) {
6546       bool IsCXX = getLangOpts().OpenCLCPlusPlus;
6547       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6548            diag::err_opencl_unknown_type_specifier)
6549           << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString()
6550           << DeclSpec::getSpecifierName(TSC) << 1;
6551       D.setInvalidType();
6552       return nullptr;
6553     }
6554   }
6555 
6556   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6557   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6558 
6559   // dllimport globals without explicit storage class are treated as extern. We
6560   // have to change the storage class this early to get the right DeclContext.
6561   if (SC == SC_None && !DC->isRecord() &&
6562       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6563       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6564     SC = SC_Extern;
6565 
6566   DeclContext *OriginalDC = DC;
6567   bool IsLocalExternDecl = SC == SC_Extern &&
6568                            adjustContextForLocalExternDecl(DC);
6569 
6570   if (SCSpec == DeclSpec::SCS_mutable) {
6571     // mutable can only appear on non-static class members, so it's always
6572     // an error here
6573     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6574     D.setInvalidType();
6575     SC = SC_None;
6576   }
6577 
6578   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6579       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6580                               D.getDeclSpec().getStorageClassSpecLoc())) {
6581     // In C++11, the 'register' storage class specifier is deprecated.
6582     // Suppress the warning in system macros, it's used in macros in some
6583     // popular C system headers, such as in glibc's htonl() macro.
6584     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6585          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6586                                    : diag::warn_deprecated_register)
6587       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6588   }
6589 
6590   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6591 
6592   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6593     // C99 6.9p2: The storage-class specifiers auto and register shall not
6594     // appear in the declaration specifiers in an external declaration.
6595     // Global Register+Asm is a GNU extension we support.
6596     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6597       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6598       D.setInvalidType();
6599     }
6600   }
6601 
6602   bool IsMemberSpecialization = false;
6603   bool IsVariableTemplateSpecialization = false;
6604   bool IsPartialSpecialization = false;
6605   bool IsVariableTemplate = false;
6606   VarDecl *NewVD = nullptr;
6607   VarTemplateDecl *NewTemplate = nullptr;
6608   TemplateParameterList *TemplateParams = nullptr;
6609   if (!getLangOpts().CPlusPlus) {
6610     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6611                             II, R, TInfo, SC);
6612 
6613     if (R->getContainedDeducedType())
6614       ParsingInitForAutoVars.insert(NewVD);
6615 
6616     if (D.isInvalidType())
6617       NewVD->setInvalidDecl();
6618 
6619     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
6620         NewVD->hasLocalStorage())
6621       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
6622                             NTCUC_AutoVar, NTCUK_Destruct);
6623   } else {
6624     bool Invalid = false;
6625 
6626     if (DC->isRecord() && !CurContext->isRecord()) {
6627       // This is an out-of-line definition of a static data member.
6628       switch (SC) {
6629       case SC_None:
6630         break;
6631       case SC_Static:
6632         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6633              diag::err_static_out_of_line)
6634           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6635         break;
6636       case SC_Auto:
6637       case SC_Register:
6638       case SC_Extern:
6639         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6640         // to names of variables declared in a block or to function parameters.
6641         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6642         // of class members
6643 
6644         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6645              diag::err_storage_class_for_static_member)
6646           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6647         break;
6648       case SC_PrivateExtern:
6649         llvm_unreachable("C storage class in c++!");
6650       }
6651     }
6652 
6653     if (SC == SC_Static && CurContext->isRecord()) {
6654       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6655         if (RD->isLocalClass())
6656           Diag(D.getIdentifierLoc(),
6657                diag::err_static_data_member_not_allowed_in_local_class)
6658             << Name << RD->getDeclName();
6659 
6660         // C++98 [class.union]p1: If a union contains a static data member,
6661         // the program is ill-formed. C++11 drops this restriction.
6662         if (RD->isUnion())
6663           Diag(D.getIdentifierLoc(),
6664                getLangOpts().CPlusPlus11
6665                  ? diag::warn_cxx98_compat_static_data_member_in_union
6666                  : diag::ext_static_data_member_in_union) << Name;
6667         // We conservatively disallow static data members in anonymous structs.
6668         else if (!RD->getDeclName())
6669           Diag(D.getIdentifierLoc(),
6670                diag::err_static_data_member_not_allowed_in_anon_struct)
6671             << Name << RD->isUnion();
6672       }
6673     }
6674 
6675     // Match up the template parameter lists with the scope specifier, then
6676     // determine whether we have a template or a template specialization.
6677     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6678         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6679         D.getCXXScopeSpec(),
6680         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6681             ? D.getName().TemplateId
6682             : nullptr,
6683         TemplateParamLists,
6684         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6685 
6686     if (TemplateParams) {
6687       if (!TemplateParams->size() &&
6688           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6689         // There is an extraneous 'template<>' for this variable. Complain
6690         // about it, but allow the declaration of the variable.
6691         Diag(TemplateParams->getTemplateLoc(),
6692              diag::err_template_variable_noparams)
6693           << II
6694           << SourceRange(TemplateParams->getTemplateLoc(),
6695                          TemplateParams->getRAngleLoc());
6696         TemplateParams = nullptr;
6697       } else {
6698         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6699           // This is an explicit specialization or a partial specialization.
6700           // FIXME: Check that we can declare a specialization here.
6701           IsVariableTemplateSpecialization = true;
6702           IsPartialSpecialization = TemplateParams->size() > 0;
6703         } else { // if (TemplateParams->size() > 0)
6704           // This is a template declaration.
6705           IsVariableTemplate = true;
6706 
6707           // Check that we can declare a template here.
6708           if (CheckTemplateDeclScope(S, TemplateParams))
6709             return nullptr;
6710 
6711           // Only C++1y supports variable templates (N3651).
6712           Diag(D.getIdentifierLoc(),
6713                getLangOpts().CPlusPlus14
6714                    ? diag::warn_cxx11_compat_variable_template
6715                    : diag::ext_variable_template);
6716         }
6717       }
6718     } else {
6719       assert((Invalid ||
6720               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
6721              "should have a 'template<>' for this decl");
6722     }
6723 
6724     if (IsVariableTemplateSpecialization) {
6725       SourceLocation TemplateKWLoc =
6726           TemplateParamLists.size() > 0
6727               ? TemplateParamLists[0]->getTemplateLoc()
6728               : SourceLocation();
6729       DeclResult Res = ActOnVarTemplateSpecialization(
6730           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6731           IsPartialSpecialization);
6732       if (Res.isInvalid())
6733         return nullptr;
6734       NewVD = cast<VarDecl>(Res.get());
6735       AddToScope = false;
6736     } else if (D.isDecompositionDeclarator()) {
6737       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
6738                                         D.getIdentifierLoc(), R, TInfo, SC,
6739                                         Bindings);
6740     } else
6741       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
6742                               D.getIdentifierLoc(), II, R, TInfo, SC);
6743 
6744     // If this is supposed to be a variable template, create it as such.
6745     if (IsVariableTemplate) {
6746       NewTemplate =
6747           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6748                                   TemplateParams, NewVD);
6749       NewVD->setDescribedVarTemplate(NewTemplate);
6750     }
6751 
6752     // If this decl has an auto type in need of deduction, make a note of the
6753     // Decl so we can diagnose uses of it in its own initializer.
6754     if (R->getContainedDeducedType())
6755       ParsingInitForAutoVars.insert(NewVD);
6756 
6757     if (D.isInvalidType() || Invalid) {
6758       NewVD->setInvalidDecl();
6759       if (NewTemplate)
6760         NewTemplate->setInvalidDecl();
6761     }
6762 
6763     SetNestedNameSpecifier(*this, NewVD, D);
6764 
6765     // If we have any template parameter lists that don't directly belong to
6766     // the variable (matching the scope specifier), store them.
6767     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6768     if (TemplateParamLists.size() > VDTemplateParamLists)
6769       NewVD->setTemplateParameterListsInfo(
6770           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6771   }
6772 
6773   if (D.getDeclSpec().isInlineSpecified()) {
6774     if (!getLangOpts().CPlusPlus) {
6775       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6776           << 0;
6777     } else if (CurContext->isFunctionOrMethod()) {
6778       // 'inline' is not allowed on block scope variable declaration.
6779       Diag(D.getDeclSpec().getInlineSpecLoc(),
6780            diag::err_inline_declaration_block_scope) << Name
6781         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6782     } else {
6783       Diag(D.getDeclSpec().getInlineSpecLoc(),
6784            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
6785                                      : diag::ext_inline_variable);
6786       NewVD->setInlineSpecified();
6787     }
6788   }
6789 
6790   // Set the lexical context. If the declarator has a C++ scope specifier, the
6791   // lexical context will be different from the semantic context.
6792   NewVD->setLexicalDeclContext(CurContext);
6793   if (NewTemplate)
6794     NewTemplate->setLexicalDeclContext(CurContext);
6795 
6796   if (IsLocalExternDecl) {
6797     if (D.isDecompositionDeclarator())
6798       for (auto *B : Bindings)
6799         B->setLocalExternDecl();
6800     else
6801       NewVD->setLocalExternDecl();
6802   }
6803 
6804   bool EmitTLSUnsupportedError = false;
6805   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6806     // C++11 [dcl.stc]p4:
6807     //   When thread_local is applied to a variable of block scope the
6808     //   storage-class-specifier static is implied if it does not appear
6809     //   explicitly.
6810     // Core issue: 'static' is not implied if the variable is declared
6811     //   'extern'.
6812     if (NewVD->hasLocalStorage() &&
6813         (SCSpec != DeclSpec::SCS_unspecified ||
6814          TSCS != DeclSpec::TSCS_thread_local ||
6815          !DC->isFunctionOrMethod()))
6816       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6817            diag::err_thread_non_global)
6818         << DeclSpec::getSpecifierName(TSCS);
6819     else if (!Context.getTargetInfo().isTLSSupported()) {
6820       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6821         // Postpone error emission until we've collected attributes required to
6822         // figure out whether it's a host or device variable and whether the
6823         // error should be ignored.
6824         EmitTLSUnsupportedError = true;
6825         // We still need to mark the variable as TLS so it shows up in AST with
6826         // proper storage class for other tools to use even if we're not going
6827         // to emit any code for it.
6828         NewVD->setTSCSpec(TSCS);
6829       } else
6830         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6831              diag::err_thread_unsupported);
6832     } else
6833       NewVD->setTSCSpec(TSCS);
6834   }
6835 
6836   switch (D.getDeclSpec().getConstexprSpecifier()) {
6837   case CSK_unspecified:
6838     break;
6839 
6840   case CSK_consteval:
6841     Diag(D.getDeclSpec().getConstexprSpecLoc(),
6842         diag::err_constexpr_wrong_decl_kind)
6843       << D.getDeclSpec().getConstexprSpecifier();
6844     LLVM_FALLTHROUGH;
6845 
6846   case CSK_constexpr:
6847     NewVD->setConstexpr(true);
6848     // C++1z [dcl.spec.constexpr]p1:
6849     //   A static data member declared with the constexpr specifier is
6850     //   implicitly an inline variable.
6851     if (NewVD->isStaticDataMember() &&
6852         (getLangOpts().CPlusPlus17 ||
6853          Context.getTargetInfo().getCXXABI().isMicrosoft()))
6854       NewVD->setImplicitlyInline();
6855     break;
6856 
6857   case CSK_constinit:
6858     if (!NewVD->hasGlobalStorage())
6859       Diag(D.getDeclSpec().getConstexprSpecLoc(),
6860            diag::err_constinit_local_variable);
6861     else
6862       NewVD->addAttr(ConstInitAttr::Create(
6863           Context, D.getDeclSpec().getConstexprSpecLoc(),
6864           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
6865     break;
6866   }
6867 
6868   // C99 6.7.4p3
6869   //   An inline definition of a function with external linkage shall
6870   //   not contain a definition of a modifiable object with static or
6871   //   thread storage duration...
6872   // We only apply this when the function is required to be defined
6873   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6874   // that a local variable with thread storage duration still has to
6875   // be marked 'static'.  Also note that it's possible to get these
6876   // semantics in C++ using __attribute__((gnu_inline)).
6877   if (SC == SC_Static && S->getFnParent() != nullptr &&
6878       !NewVD->getType().isConstQualified()) {
6879     FunctionDecl *CurFD = getCurFunctionDecl();
6880     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6881       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6882            diag::warn_static_local_in_extern_inline);
6883       MaybeSuggestAddingStaticToDecl(CurFD);
6884     }
6885   }
6886 
6887   if (D.getDeclSpec().isModulePrivateSpecified()) {
6888     if (IsVariableTemplateSpecialization)
6889       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6890           << (IsPartialSpecialization ? 1 : 0)
6891           << FixItHint::CreateRemoval(
6892                  D.getDeclSpec().getModulePrivateSpecLoc());
6893     else if (IsMemberSpecialization)
6894       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6895         << 2
6896         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6897     else if (NewVD->hasLocalStorage())
6898       Diag(NewVD->getLocation(), diag::err_module_private_local)
6899         << 0 << NewVD->getDeclName()
6900         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6901         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6902     else {
6903       NewVD->setModulePrivate();
6904       if (NewTemplate)
6905         NewTemplate->setModulePrivate();
6906       for (auto *B : Bindings)
6907         B->setModulePrivate();
6908     }
6909   }
6910 
6911   // Handle attributes prior to checking for duplicates in MergeVarDecl
6912   ProcessDeclAttributes(S, NewVD, D);
6913 
6914   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6915     if (EmitTLSUnsupportedError &&
6916         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
6917          (getLangOpts().OpenMPIsDevice &&
6918           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
6919       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6920            diag::err_thread_unsupported);
6921     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6922     // storage [duration]."
6923     if (SC == SC_None && S->getFnParent() != nullptr &&
6924         (NewVD->hasAttr<CUDASharedAttr>() ||
6925          NewVD->hasAttr<CUDAConstantAttr>())) {
6926       NewVD->setStorageClass(SC_Static);
6927     }
6928   }
6929 
6930   // Ensure that dllimport globals without explicit storage class are treated as
6931   // extern. The storage class is set above using parsed attributes. Now we can
6932   // check the VarDecl itself.
6933   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6934          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6935          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6936 
6937   // In auto-retain/release, infer strong retension for variables of
6938   // retainable type.
6939   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6940     NewVD->setInvalidDecl();
6941 
6942   // Handle GNU asm-label extension (encoded as an attribute).
6943   if (Expr *E = (Expr*)D.getAsmLabel()) {
6944     // The parser guarantees this is a string.
6945     StringLiteral *SE = cast<StringLiteral>(E);
6946     StringRef Label = SE->getString();
6947     if (S->getFnParent() != nullptr) {
6948       switch (SC) {
6949       case SC_None:
6950       case SC_Auto:
6951         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6952         break;
6953       case SC_Register:
6954         // Local Named register
6955         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6956             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6957           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6958         break;
6959       case SC_Static:
6960       case SC_Extern:
6961       case SC_PrivateExtern:
6962         break;
6963       }
6964     } else if (SC == SC_Register) {
6965       // Global Named register
6966       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6967         const auto &TI = Context.getTargetInfo();
6968         bool HasSizeMismatch;
6969 
6970         if (!TI.isValidGCCRegisterName(Label))
6971           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6972         else if (!TI.validateGlobalRegisterVariable(Label,
6973                                                     Context.getTypeSize(R),
6974                                                     HasSizeMismatch))
6975           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6976         else if (HasSizeMismatch)
6977           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6978       }
6979 
6980       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6981         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
6982         NewVD->setInvalidDecl(true);
6983       }
6984     }
6985 
6986     NewVD->addAttr(::new (Context) AsmLabelAttr(
6987         Context, SE->getStrTokenLoc(0), Label, /*IsLiteralLabel=*/true));
6988   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6989     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6990       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6991     if (I != ExtnameUndeclaredIdentifiers.end()) {
6992       if (isDeclExternC(NewVD)) {
6993         NewVD->addAttr(I->second);
6994         ExtnameUndeclaredIdentifiers.erase(I);
6995       } else
6996         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6997             << /*Variable*/1 << NewVD;
6998     }
6999   }
7000 
7001   // Find the shadowed declaration before filtering for scope.
7002   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7003                                 ? getShadowedDeclaration(NewVD, Previous)
7004                                 : nullptr;
7005 
7006   // Don't consider existing declarations that are in a different
7007   // scope and are out-of-semantic-context declarations (if the new
7008   // declaration has linkage).
7009   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7010                        D.getCXXScopeSpec().isNotEmpty() ||
7011                        IsMemberSpecialization ||
7012                        IsVariableTemplateSpecialization);
7013 
7014   // Check whether the previous declaration is in the same block scope. This
7015   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7016   if (getLangOpts().CPlusPlus &&
7017       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7018     NewVD->setPreviousDeclInSameBlockScope(
7019         Previous.isSingleResult() && !Previous.isShadowed() &&
7020         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7021 
7022   if (!getLangOpts().CPlusPlus) {
7023     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7024   } else {
7025     // If this is an explicit specialization of a static data member, check it.
7026     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7027         CheckMemberSpecialization(NewVD, Previous))
7028       NewVD->setInvalidDecl();
7029 
7030     // Merge the decl with the existing one if appropriate.
7031     if (!Previous.empty()) {
7032       if (Previous.isSingleResult() &&
7033           isa<FieldDecl>(Previous.getFoundDecl()) &&
7034           D.getCXXScopeSpec().isSet()) {
7035         // The user tried to define a non-static data member
7036         // out-of-line (C++ [dcl.meaning]p1).
7037         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7038           << D.getCXXScopeSpec().getRange();
7039         Previous.clear();
7040         NewVD->setInvalidDecl();
7041       }
7042     } else if (D.getCXXScopeSpec().isSet()) {
7043       // No previous declaration in the qualifying scope.
7044       Diag(D.getIdentifierLoc(), diag::err_no_member)
7045         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7046         << D.getCXXScopeSpec().getRange();
7047       NewVD->setInvalidDecl();
7048     }
7049 
7050     if (!IsVariableTemplateSpecialization)
7051       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7052 
7053     if (NewTemplate) {
7054       VarTemplateDecl *PrevVarTemplate =
7055           NewVD->getPreviousDecl()
7056               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7057               : nullptr;
7058 
7059       // Check the template parameter list of this declaration, possibly
7060       // merging in the template parameter list from the previous variable
7061       // template declaration.
7062       if (CheckTemplateParameterList(
7063               TemplateParams,
7064               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7065                               : nullptr,
7066               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7067                DC->isDependentContext())
7068                   ? TPC_ClassTemplateMember
7069                   : TPC_VarTemplate))
7070         NewVD->setInvalidDecl();
7071 
7072       // If we are providing an explicit specialization of a static variable
7073       // template, make a note of that.
7074       if (PrevVarTemplate &&
7075           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7076         PrevVarTemplate->setMemberSpecialization();
7077     }
7078   }
7079 
7080   // Diagnose shadowed variables iff this isn't a redeclaration.
7081   if (ShadowedDecl && !D.isRedeclaration())
7082     CheckShadow(NewVD, ShadowedDecl, Previous);
7083 
7084   ProcessPragmaWeak(S, NewVD);
7085 
7086   // If this is the first declaration of an extern C variable, update
7087   // the map of such variables.
7088   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7089       isIncompleteDeclExternC(*this, NewVD))
7090     RegisterLocallyScopedExternCDecl(NewVD, S);
7091 
7092   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7093     Decl *ManglingContextDecl;
7094     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
7095             NewVD->getDeclContext(), ManglingContextDecl)) {
7096       Context.setManglingNumber(
7097           NewVD, MCtx->getManglingNumber(
7098                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7099       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7100     }
7101   }
7102 
7103   // Special handling of variable named 'main'.
7104   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7105       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7106       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7107 
7108     // C++ [basic.start.main]p3
7109     // A program that declares a variable main at global scope is ill-formed.
7110     if (getLangOpts().CPlusPlus)
7111       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7112 
7113     // In C, and external-linkage variable named main results in undefined
7114     // behavior.
7115     else if (NewVD->hasExternalFormalLinkage())
7116       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7117   }
7118 
7119   if (D.isRedeclaration() && !Previous.empty()) {
7120     NamedDecl *Prev = Previous.getRepresentativeDecl();
7121     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7122                                    D.isFunctionDefinition());
7123   }
7124 
7125   if (NewTemplate) {
7126     if (NewVD->isInvalidDecl())
7127       NewTemplate->setInvalidDecl();
7128     ActOnDocumentableDecl(NewTemplate);
7129     return NewTemplate;
7130   }
7131 
7132   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7133     CompleteMemberSpecialization(NewVD, Previous);
7134 
7135   return NewVD;
7136 }
7137 
7138 /// Enum describing the %select options in diag::warn_decl_shadow.
7139 enum ShadowedDeclKind {
7140   SDK_Local,
7141   SDK_Global,
7142   SDK_StaticMember,
7143   SDK_Field,
7144   SDK_Typedef,
7145   SDK_Using
7146 };
7147 
7148 /// Determine what kind of declaration we're shadowing.
7149 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7150                                                 const DeclContext *OldDC) {
7151   if (isa<TypeAliasDecl>(ShadowedDecl))
7152     return SDK_Using;
7153   else if (isa<TypedefDecl>(ShadowedDecl))
7154     return SDK_Typedef;
7155   else if (isa<RecordDecl>(OldDC))
7156     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7157 
7158   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7159 }
7160 
7161 /// Return the location of the capture if the given lambda captures the given
7162 /// variable \p VD, or an invalid source location otherwise.
7163 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7164                                          const VarDecl *VD) {
7165   for (const Capture &Capture : LSI->Captures) {
7166     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7167       return Capture.getLocation();
7168   }
7169   return SourceLocation();
7170 }
7171 
7172 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7173                                      const LookupResult &R) {
7174   // Only diagnose if we're shadowing an unambiguous field or variable.
7175   if (R.getResultKind() != LookupResult::Found)
7176     return false;
7177 
7178   // Return false if warning is ignored.
7179   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7180 }
7181 
7182 /// Return the declaration shadowed by the given variable \p D, or null
7183 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7184 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7185                                         const LookupResult &R) {
7186   if (!shouldWarnIfShadowedDecl(Diags, R))
7187     return nullptr;
7188 
7189   // Don't diagnose declarations at file scope.
7190   if (D->hasGlobalStorage())
7191     return nullptr;
7192 
7193   NamedDecl *ShadowedDecl = R.getFoundDecl();
7194   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
7195              ? ShadowedDecl
7196              : nullptr;
7197 }
7198 
7199 /// Return the declaration shadowed by the given typedef \p D, or null
7200 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7201 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7202                                         const LookupResult &R) {
7203   // Don't warn if typedef declaration is part of a class
7204   if (D->getDeclContext()->isRecord())
7205     return nullptr;
7206 
7207   if (!shouldWarnIfShadowedDecl(Diags, R))
7208     return nullptr;
7209 
7210   NamedDecl *ShadowedDecl = R.getFoundDecl();
7211   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7212 }
7213 
7214 /// Diagnose variable or built-in function shadowing.  Implements
7215 /// -Wshadow.
7216 ///
7217 /// This method is called whenever a VarDecl is added to a "useful"
7218 /// scope.
7219 ///
7220 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7221 /// \param R the lookup of the name
7222 ///
7223 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7224                        const LookupResult &R) {
7225   DeclContext *NewDC = D->getDeclContext();
7226 
7227   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7228     // Fields are not shadowed by variables in C++ static methods.
7229     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7230       if (MD->isStatic())
7231         return;
7232 
7233     // Fields shadowed by constructor parameters are a special case. Usually
7234     // the constructor initializes the field with the parameter.
7235     if (isa<CXXConstructorDecl>(NewDC))
7236       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7237         // Remember that this was shadowed so we can either warn about its
7238         // modification or its existence depending on warning settings.
7239         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7240         return;
7241       }
7242   }
7243 
7244   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7245     if (shadowedVar->isExternC()) {
7246       // For shadowing external vars, make sure that we point to the global
7247       // declaration, not a locally scoped extern declaration.
7248       for (auto I : shadowedVar->redecls())
7249         if (I->isFileVarDecl()) {
7250           ShadowedDecl = I;
7251           break;
7252         }
7253     }
7254 
7255   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7256 
7257   unsigned WarningDiag = diag::warn_decl_shadow;
7258   SourceLocation CaptureLoc;
7259   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7260       isa<CXXMethodDecl>(NewDC)) {
7261     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7262       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7263         if (RD->getLambdaCaptureDefault() == LCD_None) {
7264           // Try to avoid warnings for lambdas with an explicit capture list.
7265           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7266           // Warn only when the lambda captures the shadowed decl explicitly.
7267           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7268           if (CaptureLoc.isInvalid())
7269             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7270         } else {
7271           // Remember that this was shadowed so we can avoid the warning if the
7272           // shadowed decl isn't captured and the warning settings allow it.
7273           cast<LambdaScopeInfo>(getCurFunction())
7274               ->ShadowingDecls.push_back(
7275                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7276           return;
7277         }
7278       }
7279 
7280       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7281         // A variable can't shadow a local variable in an enclosing scope, if
7282         // they are separated by a non-capturing declaration context.
7283         for (DeclContext *ParentDC = NewDC;
7284              ParentDC && !ParentDC->Equals(OldDC);
7285              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7286           // Only block literals, captured statements, and lambda expressions
7287           // can capture; other scopes don't.
7288           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7289               !isLambdaCallOperator(ParentDC)) {
7290             return;
7291           }
7292         }
7293       }
7294     }
7295   }
7296 
7297   // Only warn about certain kinds of shadowing for class members.
7298   if (NewDC && NewDC->isRecord()) {
7299     // In particular, don't warn about shadowing non-class members.
7300     if (!OldDC->isRecord())
7301       return;
7302 
7303     // TODO: should we warn about static data members shadowing
7304     // static data members from base classes?
7305 
7306     // TODO: don't diagnose for inaccessible shadowed members.
7307     // This is hard to do perfectly because we might friend the
7308     // shadowing context, but that's just a false negative.
7309   }
7310 
7311 
7312   DeclarationName Name = R.getLookupName();
7313 
7314   // Emit warning and note.
7315   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7316     return;
7317   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7318   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7319   if (!CaptureLoc.isInvalid())
7320     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7321         << Name << /*explicitly*/ 1;
7322   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7323 }
7324 
7325 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7326 /// when these variables are captured by the lambda.
7327 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7328   for (const auto &Shadow : LSI->ShadowingDecls) {
7329     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7330     // Try to avoid the warning when the shadowed decl isn't captured.
7331     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7332     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7333     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7334                                        ? diag::warn_decl_shadow_uncaptured_local
7335                                        : diag::warn_decl_shadow)
7336         << Shadow.VD->getDeclName()
7337         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7338     if (!CaptureLoc.isInvalid())
7339       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7340           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7341     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7342   }
7343 }
7344 
7345 /// Check -Wshadow without the advantage of a previous lookup.
7346 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7347   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7348     return;
7349 
7350   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7351                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7352   LookupName(R, S);
7353   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7354     CheckShadow(D, ShadowedDecl, R);
7355 }
7356 
7357 /// Check if 'E', which is an expression that is about to be modified, refers
7358 /// to a constructor parameter that shadows a field.
7359 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7360   // Quickly ignore expressions that can't be shadowing ctor parameters.
7361   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7362     return;
7363   E = E->IgnoreParenImpCasts();
7364   auto *DRE = dyn_cast<DeclRefExpr>(E);
7365   if (!DRE)
7366     return;
7367   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7368   auto I = ShadowingDecls.find(D);
7369   if (I == ShadowingDecls.end())
7370     return;
7371   const NamedDecl *ShadowedDecl = I->second;
7372   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7373   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7374   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7375   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7376 
7377   // Avoid issuing multiple warnings about the same decl.
7378   ShadowingDecls.erase(I);
7379 }
7380 
7381 /// Check for conflict between this global or extern "C" declaration and
7382 /// previous global or extern "C" declarations. This is only used in C++.
7383 template<typename T>
7384 static bool checkGlobalOrExternCConflict(
7385     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7386   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7387   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7388 
7389   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7390     // The common case: this global doesn't conflict with any extern "C"
7391     // declaration.
7392     return false;
7393   }
7394 
7395   if (Prev) {
7396     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7397       // Both the old and new declarations have C language linkage. This is a
7398       // redeclaration.
7399       Previous.clear();
7400       Previous.addDecl(Prev);
7401       return true;
7402     }
7403 
7404     // This is a global, non-extern "C" declaration, and there is a previous
7405     // non-global extern "C" declaration. Diagnose if this is a variable
7406     // declaration.
7407     if (!isa<VarDecl>(ND))
7408       return false;
7409   } else {
7410     // The declaration is extern "C". Check for any declaration in the
7411     // translation unit which might conflict.
7412     if (IsGlobal) {
7413       // We have already performed the lookup into the translation unit.
7414       IsGlobal = false;
7415       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7416            I != E; ++I) {
7417         if (isa<VarDecl>(*I)) {
7418           Prev = *I;
7419           break;
7420         }
7421       }
7422     } else {
7423       DeclContext::lookup_result R =
7424           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7425       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7426            I != E; ++I) {
7427         if (isa<VarDecl>(*I)) {
7428           Prev = *I;
7429           break;
7430         }
7431         // FIXME: If we have any other entity with this name in global scope,
7432         // the declaration is ill-formed, but that is a defect: it breaks the
7433         // 'stat' hack, for instance. Only variables can have mangled name
7434         // clashes with extern "C" declarations, so only they deserve a
7435         // diagnostic.
7436       }
7437     }
7438 
7439     if (!Prev)
7440       return false;
7441   }
7442 
7443   // Use the first declaration's location to ensure we point at something which
7444   // is lexically inside an extern "C" linkage-spec.
7445   assert(Prev && "should have found a previous declaration to diagnose");
7446   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7447     Prev = FD->getFirstDecl();
7448   else
7449     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7450 
7451   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7452     << IsGlobal << ND;
7453   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7454     << IsGlobal;
7455   return false;
7456 }
7457 
7458 /// Apply special rules for handling extern "C" declarations. Returns \c true
7459 /// if we have found that this is a redeclaration of some prior entity.
7460 ///
7461 /// Per C++ [dcl.link]p6:
7462 ///   Two declarations [for a function or variable] with C language linkage
7463 ///   with the same name that appear in different scopes refer to the same
7464 ///   [entity]. An entity with C language linkage shall not be declared with
7465 ///   the same name as an entity in global scope.
7466 template<typename T>
7467 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7468                                                   LookupResult &Previous) {
7469   if (!S.getLangOpts().CPlusPlus) {
7470     // In C, when declaring a global variable, look for a corresponding 'extern'
7471     // variable declared in function scope. We don't need this in C++, because
7472     // we find local extern decls in the surrounding file-scope DeclContext.
7473     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7474       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7475         Previous.clear();
7476         Previous.addDecl(Prev);
7477         return true;
7478       }
7479     }
7480     return false;
7481   }
7482 
7483   // A declaration in the translation unit can conflict with an extern "C"
7484   // declaration.
7485   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7486     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7487 
7488   // An extern "C" declaration can conflict with a declaration in the
7489   // translation unit or can be a redeclaration of an extern "C" declaration
7490   // in another scope.
7491   if (isIncompleteDeclExternC(S,ND))
7492     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7493 
7494   // Neither global nor extern "C": nothing to do.
7495   return false;
7496 }
7497 
7498 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7499   // If the decl is already known invalid, don't check it.
7500   if (NewVD->isInvalidDecl())
7501     return;
7502 
7503   QualType T = NewVD->getType();
7504 
7505   // Defer checking an 'auto' type until its initializer is attached.
7506   if (T->isUndeducedType())
7507     return;
7508 
7509   if (NewVD->hasAttrs())
7510     CheckAlignasUnderalignment(NewVD);
7511 
7512   if (T->isObjCObjectType()) {
7513     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7514       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7515     T = Context.getObjCObjectPointerType(T);
7516     NewVD->setType(T);
7517   }
7518 
7519   // Emit an error if an address space was applied to decl with local storage.
7520   // This includes arrays of objects with address space qualifiers, but not
7521   // automatic variables that point to other address spaces.
7522   // ISO/IEC TR 18037 S5.1.2
7523   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7524       T.getAddressSpace() != LangAS::Default) {
7525     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7526     NewVD->setInvalidDecl();
7527     return;
7528   }
7529 
7530   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7531   // scope.
7532   if (getLangOpts().OpenCLVersion == 120 &&
7533       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7534       NewVD->isStaticLocal()) {
7535     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7536     NewVD->setInvalidDecl();
7537     return;
7538   }
7539 
7540   if (getLangOpts().OpenCL) {
7541     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7542     if (NewVD->hasAttr<BlocksAttr>()) {
7543       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7544       return;
7545     }
7546 
7547     if (T->isBlockPointerType()) {
7548       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7549       // can't use 'extern' storage class.
7550       if (!T.isConstQualified()) {
7551         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7552             << 0 /*const*/;
7553         NewVD->setInvalidDecl();
7554         return;
7555       }
7556       if (NewVD->hasExternalStorage()) {
7557         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7558         NewVD->setInvalidDecl();
7559         return;
7560       }
7561     }
7562     // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7563     // __constant address space.
7564     // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7565     // variables inside a function can also be declared in the global
7566     // address space.
7567     // C++ for OpenCL inherits rule from OpenCL C v2.0.
7568     // FIXME: Adding local AS in C++ for OpenCL might make sense.
7569     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7570         NewVD->hasExternalStorage()) {
7571       if (!T->isSamplerT() &&
7572           !(T.getAddressSpace() == LangAS::opencl_constant ||
7573             (T.getAddressSpace() == LangAS::opencl_global &&
7574              (getLangOpts().OpenCLVersion == 200 ||
7575               getLangOpts().OpenCLCPlusPlus)))) {
7576         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7577         if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7578           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7579               << Scope << "global or constant";
7580         else
7581           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7582               << Scope << "constant";
7583         NewVD->setInvalidDecl();
7584         return;
7585       }
7586     } else {
7587       if (T.getAddressSpace() == LangAS::opencl_global) {
7588         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7589             << 1 /*is any function*/ << "global";
7590         NewVD->setInvalidDecl();
7591         return;
7592       }
7593       if (T.getAddressSpace() == LangAS::opencl_constant ||
7594           T.getAddressSpace() == LangAS::opencl_local) {
7595         FunctionDecl *FD = getCurFunctionDecl();
7596         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7597         // in functions.
7598         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7599           if (T.getAddressSpace() == LangAS::opencl_constant)
7600             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7601                 << 0 /*non-kernel only*/ << "constant";
7602           else
7603             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7604                 << 0 /*non-kernel only*/ << "local";
7605           NewVD->setInvalidDecl();
7606           return;
7607         }
7608         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7609         // in the outermost scope of a kernel function.
7610         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7611           if (!getCurScope()->isFunctionScope()) {
7612             if (T.getAddressSpace() == LangAS::opencl_constant)
7613               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7614                   << "constant";
7615             else
7616               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7617                   << "local";
7618             NewVD->setInvalidDecl();
7619             return;
7620           }
7621         }
7622       } else if (T.getAddressSpace() != LangAS::opencl_private &&
7623                  // If we are parsing a template we didn't deduce an addr
7624                  // space yet.
7625                  T.getAddressSpace() != LangAS::Default) {
7626         // Do not allow other address spaces on automatic variable.
7627         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7628         NewVD->setInvalidDecl();
7629         return;
7630       }
7631     }
7632   }
7633 
7634   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7635       && !NewVD->hasAttr<BlocksAttr>()) {
7636     if (getLangOpts().getGC() != LangOptions::NonGC)
7637       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7638     else {
7639       assert(!getLangOpts().ObjCAutoRefCount);
7640       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7641     }
7642   }
7643 
7644   bool isVM = T->isVariablyModifiedType();
7645   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7646       NewVD->hasAttr<BlocksAttr>())
7647     setFunctionHasBranchProtectedScope();
7648 
7649   if ((isVM && NewVD->hasLinkage()) ||
7650       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7651     bool SizeIsNegative;
7652     llvm::APSInt Oversized;
7653     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7654         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7655     QualType FixedT;
7656     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
7657       FixedT = FixedTInfo->getType();
7658     else if (FixedTInfo) {
7659       // Type and type-as-written are canonically different. We need to fix up
7660       // both types separately.
7661       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7662                                                    Oversized);
7663     }
7664     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7665       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7666       // FIXME: This won't give the correct result for
7667       // int a[10][n];
7668       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7669 
7670       if (NewVD->isFileVarDecl())
7671         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7672         << SizeRange;
7673       else if (NewVD->isStaticLocal())
7674         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7675         << SizeRange;
7676       else
7677         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7678         << SizeRange;
7679       NewVD->setInvalidDecl();
7680       return;
7681     }
7682 
7683     if (!FixedTInfo) {
7684       if (NewVD->isFileVarDecl())
7685         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7686       else
7687         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7688       NewVD->setInvalidDecl();
7689       return;
7690     }
7691 
7692     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7693     NewVD->setType(FixedT);
7694     NewVD->setTypeSourceInfo(FixedTInfo);
7695   }
7696 
7697   if (T->isVoidType()) {
7698     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7699     //                    of objects and functions.
7700     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7701       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7702         << T;
7703       NewVD->setInvalidDecl();
7704       return;
7705     }
7706   }
7707 
7708   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7709     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7710     NewVD->setInvalidDecl();
7711     return;
7712   }
7713 
7714   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7715     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7716     NewVD->setInvalidDecl();
7717     return;
7718   }
7719 
7720   if (NewVD->isConstexpr() && !T->isDependentType() &&
7721       RequireLiteralType(NewVD->getLocation(), T,
7722                          diag::err_constexpr_var_non_literal)) {
7723     NewVD->setInvalidDecl();
7724     return;
7725   }
7726 }
7727 
7728 /// Perform semantic checking on a newly-created variable
7729 /// declaration.
7730 ///
7731 /// This routine performs all of the type-checking required for a
7732 /// variable declaration once it has been built. It is used both to
7733 /// check variables after they have been parsed and their declarators
7734 /// have been translated into a declaration, and to check variables
7735 /// that have been instantiated from a template.
7736 ///
7737 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7738 ///
7739 /// Returns true if the variable declaration is a redeclaration.
7740 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7741   CheckVariableDeclarationType(NewVD);
7742 
7743   // If the decl is already known invalid, don't check it.
7744   if (NewVD->isInvalidDecl())
7745     return false;
7746 
7747   // If we did not find anything by this name, look for a non-visible
7748   // extern "C" declaration with the same name.
7749   if (Previous.empty() &&
7750       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7751     Previous.setShadowed();
7752 
7753   if (!Previous.empty()) {
7754     MergeVarDecl(NewVD, Previous);
7755     return true;
7756   }
7757   return false;
7758 }
7759 
7760 namespace {
7761 struct FindOverriddenMethod {
7762   Sema *S;
7763   CXXMethodDecl *Method;
7764 
7765   /// Member lookup function that determines whether a given C++
7766   /// method overrides a method in a base class, to be used with
7767   /// CXXRecordDecl::lookupInBases().
7768   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7769     RecordDecl *BaseRecord =
7770         Specifier->getType()->getAs<RecordType>()->getDecl();
7771 
7772     DeclarationName Name = Method->getDeclName();
7773 
7774     // FIXME: Do we care about other names here too?
7775     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7776       // We really want to find the base class destructor here.
7777       QualType T = S->Context.getTypeDeclType(BaseRecord);
7778       CanQualType CT = S->Context.getCanonicalType(T);
7779 
7780       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7781     }
7782 
7783     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7784          Path.Decls = Path.Decls.slice(1)) {
7785       NamedDecl *D = Path.Decls.front();
7786       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7787         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7788           return true;
7789       }
7790     }
7791 
7792     return false;
7793   }
7794 };
7795 
7796 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7797 } // end anonymous namespace
7798 
7799 /// Report an error regarding overriding, along with any relevant
7800 /// overridden methods.
7801 ///
7802 /// \param DiagID the primary error to report.
7803 /// \param MD the overriding method.
7804 /// \param OEK which overrides to include as notes.
7805 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7806                             OverrideErrorKind OEK = OEK_All) {
7807   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7808   for (const CXXMethodDecl *O : MD->overridden_methods()) {
7809     // This check (& the OEK parameter) could be replaced by a predicate, but
7810     // without lambdas that would be overkill. This is still nicer than writing
7811     // out the diag loop 3 times.
7812     if ((OEK == OEK_All) ||
7813         (OEK == OEK_NonDeleted && !O->isDeleted()) ||
7814         (OEK == OEK_Deleted && O->isDeleted()))
7815       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7816   }
7817 }
7818 
7819 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7820 /// and if so, check that it's a valid override and remember it.
7821 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7822   // Look for methods in base classes that this method might override.
7823   CXXBasePaths Paths;
7824   FindOverriddenMethod FOM;
7825   FOM.Method = MD;
7826   FOM.S = this;
7827   bool hasDeletedOverridenMethods = false;
7828   bool hasNonDeletedOverridenMethods = false;
7829   bool AddedAny = false;
7830   if (DC->lookupInBases(FOM, Paths)) {
7831     for (auto *I : Paths.found_decls()) {
7832       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7833         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7834         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7835             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7836             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7837             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7838           hasDeletedOverridenMethods |= OldMD->isDeleted();
7839           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7840           AddedAny = true;
7841         }
7842       }
7843     }
7844   }
7845 
7846   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7847     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7848   }
7849   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7850     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7851   }
7852 
7853   return AddedAny;
7854 }
7855 
7856 namespace {
7857   // Struct for holding all of the extra arguments needed by
7858   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7859   struct ActOnFDArgs {
7860     Scope *S;
7861     Declarator &D;
7862     MultiTemplateParamsArg TemplateParamLists;
7863     bool AddToScope;
7864   };
7865 } // end anonymous namespace
7866 
7867 namespace {
7868 
7869 // Callback to only accept typo corrections that have a non-zero edit distance.
7870 // Also only accept corrections that have the same parent decl.
7871 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
7872  public:
7873   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7874                             CXXRecordDecl *Parent)
7875       : Context(Context), OriginalFD(TypoFD),
7876         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7877 
7878   bool ValidateCandidate(const TypoCorrection &candidate) override {
7879     if (candidate.getEditDistance() == 0)
7880       return false;
7881 
7882     SmallVector<unsigned, 1> MismatchedParams;
7883     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7884                                           CDeclEnd = candidate.end();
7885          CDecl != CDeclEnd; ++CDecl) {
7886       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7887 
7888       if (FD && !FD->hasBody() &&
7889           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7890         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7891           CXXRecordDecl *Parent = MD->getParent();
7892           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7893             return true;
7894         } else if (!ExpectedParent) {
7895           return true;
7896         }
7897       }
7898     }
7899 
7900     return false;
7901   }
7902 
7903   std::unique_ptr<CorrectionCandidateCallback> clone() override {
7904     return std::make_unique<DifferentNameValidatorCCC>(*this);
7905   }
7906 
7907  private:
7908   ASTContext &Context;
7909   FunctionDecl *OriginalFD;
7910   CXXRecordDecl *ExpectedParent;
7911 };
7912 
7913 } // end anonymous namespace
7914 
7915 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
7916   TypoCorrectedFunctionDefinitions.insert(F);
7917 }
7918 
7919 /// Generate diagnostics for an invalid function redeclaration.
7920 ///
7921 /// This routine handles generating the diagnostic messages for an invalid
7922 /// function redeclaration, including finding possible similar declarations
7923 /// or performing typo correction if there are no previous declarations with
7924 /// the same name.
7925 ///
7926 /// Returns a NamedDecl iff typo correction was performed and substituting in
7927 /// the new declaration name does not cause new errors.
7928 static NamedDecl *DiagnoseInvalidRedeclaration(
7929     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7930     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7931   DeclarationName Name = NewFD->getDeclName();
7932   DeclContext *NewDC = NewFD->getDeclContext();
7933   SmallVector<unsigned, 1> MismatchedParams;
7934   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7935   TypoCorrection Correction;
7936   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7937   unsigned DiagMsg =
7938     IsLocalFriend ? diag::err_no_matching_local_friend :
7939     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
7940     diag::err_member_decl_does_not_match;
7941   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7942                     IsLocalFriend ? Sema::LookupLocalFriendName
7943                                   : Sema::LookupOrdinaryName,
7944                     Sema::ForVisibleRedeclaration);
7945 
7946   NewFD->setInvalidDecl();
7947   if (IsLocalFriend)
7948     SemaRef.LookupName(Prev, S);
7949   else
7950     SemaRef.LookupQualifiedName(Prev, NewDC);
7951   assert(!Prev.isAmbiguous() &&
7952          "Cannot have an ambiguity in previous-declaration lookup");
7953   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7954   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
7955                                 MD ? MD->getParent() : nullptr);
7956   if (!Prev.empty()) {
7957     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7958          Func != FuncEnd; ++Func) {
7959       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7960       if (FD &&
7961           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7962         // Add 1 to the index so that 0 can mean the mismatch didn't
7963         // involve a parameter
7964         unsigned ParamNum =
7965             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7966         NearMatches.push_back(std::make_pair(FD, ParamNum));
7967       }
7968     }
7969   // If the qualified name lookup yielded nothing, try typo correction
7970   } else if ((Correction = SemaRef.CorrectTypo(
7971                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7972                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
7973                   IsLocalFriend ? nullptr : NewDC))) {
7974     // Set up everything for the call to ActOnFunctionDeclarator
7975     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7976                               ExtraArgs.D.getIdentifierLoc());
7977     Previous.clear();
7978     Previous.setLookupName(Correction.getCorrection());
7979     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7980                                     CDeclEnd = Correction.end();
7981          CDecl != CDeclEnd; ++CDecl) {
7982       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7983       if (FD && !FD->hasBody() &&
7984           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7985         Previous.addDecl(FD);
7986       }
7987     }
7988     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7989 
7990     NamedDecl *Result;
7991     // Retry building the function declaration with the new previous
7992     // declarations, and with errors suppressed.
7993     {
7994       // Trap errors.
7995       Sema::SFINAETrap Trap(SemaRef);
7996 
7997       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7998       // pieces need to verify the typo-corrected C++ declaration and hopefully
7999       // eliminate the need for the parameter pack ExtraArgs.
8000       Result = SemaRef.ActOnFunctionDeclarator(
8001           ExtraArgs.S, ExtraArgs.D,
8002           Correction.getCorrectionDecl()->getDeclContext(),
8003           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8004           ExtraArgs.AddToScope);
8005 
8006       if (Trap.hasErrorOccurred())
8007         Result = nullptr;
8008     }
8009 
8010     if (Result) {
8011       // Determine which correction we picked.
8012       Decl *Canonical = Result->getCanonicalDecl();
8013       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8014            I != E; ++I)
8015         if ((*I)->getCanonicalDecl() == Canonical)
8016           Correction.setCorrectionDecl(*I);
8017 
8018       // Let Sema know about the correction.
8019       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8020       SemaRef.diagnoseTypo(
8021           Correction,
8022           SemaRef.PDiag(IsLocalFriend
8023                           ? diag::err_no_matching_local_friend_suggest
8024                           : diag::err_member_decl_does_not_match_suggest)
8025             << Name << NewDC << IsDefinition);
8026       return Result;
8027     }
8028 
8029     // Pretend the typo correction never occurred
8030     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8031                               ExtraArgs.D.getIdentifierLoc());
8032     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8033     Previous.clear();
8034     Previous.setLookupName(Name);
8035   }
8036 
8037   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8038       << Name << NewDC << IsDefinition << NewFD->getLocation();
8039 
8040   bool NewFDisConst = false;
8041   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8042     NewFDisConst = NewMD->isConst();
8043 
8044   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8045        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8046        NearMatch != NearMatchEnd; ++NearMatch) {
8047     FunctionDecl *FD = NearMatch->first;
8048     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8049     bool FDisConst = MD && MD->isConst();
8050     bool IsMember = MD || !IsLocalFriend;
8051 
8052     // FIXME: These notes are poorly worded for the local friend case.
8053     if (unsigned Idx = NearMatch->second) {
8054       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8055       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8056       if (Loc.isInvalid()) Loc = FD->getLocation();
8057       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8058                                  : diag::note_local_decl_close_param_match)
8059         << Idx << FDParam->getType()
8060         << NewFD->getParamDecl(Idx - 1)->getType();
8061     } else if (FDisConst != NewFDisConst) {
8062       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8063           << NewFDisConst << FD->getSourceRange().getEnd();
8064     } else
8065       SemaRef.Diag(FD->getLocation(),
8066                    IsMember ? diag::note_member_def_close_match
8067                             : diag::note_local_decl_close_match);
8068   }
8069   return nullptr;
8070 }
8071 
8072 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8073   switch (D.getDeclSpec().getStorageClassSpec()) {
8074   default: llvm_unreachable("Unknown storage class!");
8075   case DeclSpec::SCS_auto:
8076   case DeclSpec::SCS_register:
8077   case DeclSpec::SCS_mutable:
8078     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8079                  diag::err_typecheck_sclass_func);
8080     D.getMutableDeclSpec().ClearStorageClassSpecs();
8081     D.setInvalidType();
8082     break;
8083   case DeclSpec::SCS_unspecified: break;
8084   case DeclSpec::SCS_extern:
8085     if (D.getDeclSpec().isExternInLinkageSpec())
8086       return SC_None;
8087     return SC_Extern;
8088   case DeclSpec::SCS_static: {
8089     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8090       // C99 6.7.1p5:
8091       //   The declaration of an identifier for a function that has
8092       //   block scope shall have no explicit storage-class specifier
8093       //   other than extern
8094       // See also (C++ [dcl.stc]p4).
8095       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8096                    diag::err_static_block_func);
8097       break;
8098     } else
8099       return SC_Static;
8100   }
8101   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8102   }
8103 
8104   // No explicit storage class has already been returned
8105   return SC_None;
8106 }
8107 
8108 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8109                                            DeclContext *DC, QualType &R,
8110                                            TypeSourceInfo *TInfo,
8111                                            StorageClass SC,
8112                                            bool &IsVirtualOkay) {
8113   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8114   DeclarationName Name = NameInfo.getName();
8115 
8116   FunctionDecl *NewFD = nullptr;
8117   bool isInline = D.getDeclSpec().isInlineSpecified();
8118 
8119   if (!SemaRef.getLangOpts().CPlusPlus) {
8120     // Determine whether the function was written with a
8121     // prototype. This true when:
8122     //   - there is a prototype in the declarator, or
8123     //   - the type R of the function is some kind of typedef or other non-
8124     //     attributed reference to a type name (which eventually refers to a
8125     //     function type).
8126     bool HasPrototype =
8127       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8128       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8129 
8130     NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8131                                  R, TInfo, SC, isInline, HasPrototype,
8132                                  CSK_unspecified);
8133     if (D.isInvalidType())
8134       NewFD->setInvalidDecl();
8135 
8136     return NewFD;
8137   }
8138 
8139   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8140 
8141   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8142   if (ConstexprKind == CSK_constinit) {
8143     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8144                  diag::err_constexpr_wrong_decl_kind)
8145         << ConstexprKind;
8146     ConstexprKind = CSK_unspecified;
8147     D.getMutableDeclSpec().ClearConstexprSpec();
8148   }
8149 
8150   // Check that the return type is not an abstract class type.
8151   // For record types, this is done by the AbstractClassUsageDiagnoser once
8152   // the class has been completely parsed.
8153   if (!DC->isRecord() &&
8154       SemaRef.RequireNonAbstractType(
8155           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
8156           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8157     D.setInvalidType();
8158 
8159   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8160     // This is a C++ constructor declaration.
8161     assert(DC->isRecord() &&
8162            "Constructors can only be declared in a member context");
8163 
8164     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8165     return CXXConstructorDecl::Create(
8166         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8167         TInfo, ExplicitSpecifier, isInline,
8168         /*isImplicitlyDeclared=*/false, ConstexprKind);
8169 
8170   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8171     // This is a C++ destructor declaration.
8172     if (DC->isRecord()) {
8173       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8174       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8175       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8176           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8177           isInline,
8178           /*isImplicitlyDeclared=*/false, ConstexprKind);
8179 
8180       // If the destructor needs an implicit exception specification, set it
8181       // now. FIXME: It'd be nice to be able to create the right type to start
8182       // with, but the type needs to reference the destructor declaration.
8183       if (SemaRef.getLangOpts().CPlusPlus11)
8184         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8185 
8186       IsVirtualOkay = true;
8187       return NewDD;
8188 
8189     } else {
8190       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8191       D.setInvalidType();
8192 
8193       // Create a FunctionDecl to satisfy the function definition parsing
8194       // code path.
8195       return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8196                                   D.getIdentifierLoc(), Name, R, TInfo, SC,
8197                                   isInline,
8198                                   /*hasPrototype=*/true, ConstexprKind);
8199     }
8200 
8201   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8202     if (!DC->isRecord()) {
8203       SemaRef.Diag(D.getIdentifierLoc(),
8204            diag::err_conv_function_not_member);
8205       return nullptr;
8206     }
8207 
8208     SemaRef.CheckConversionDeclarator(D, R, SC);
8209     IsVirtualOkay = true;
8210     return CXXConversionDecl::Create(
8211         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8212         TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation());
8213 
8214   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8215     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8216 
8217     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8218                                          ExplicitSpecifier, NameInfo, R, TInfo,
8219                                          D.getEndLoc());
8220   } else if (DC->isRecord()) {
8221     // If the name of the function is the same as the name of the record,
8222     // then this must be an invalid constructor that has a return type.
8223     // (The parser checks for a return type and makes the declarator a
8224     // constructor if it has no return type).
8225     if (Name.getAsIdentifierInfo() &&
8226         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8227       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8228         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8229         << SourceRange(D.getIdentifierLoc());
8230       return nullptr;
8231     }
8232 
8233     // This is a C++ method declaration.
8234     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8235         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8236         TInfo, SC, isInline, ConstexprKind, SourceLocation());
8237     IsVirtualOkay = !Ret->isStatic();
8238     return Ret;
8239   } else {
8240     bool isFriend =
8241         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8242     if (!isFriend && SemaRef.CurContext->isRecord())
8243       return nullptr;
8244 
8245     // Determine whether the function was written with a
8246     // prototype. This true when:
8247     //   - we're in C++ (where every function has a prototype),
8248     return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8249                                 R, TInfo, SC, isInline, true /*HasPrototype*/,
8250                                 ConstexprKind);
8251   }
8252 }
8253 
8254 enum OpenCLParamType {
8255   ValidKernelParam,
8256   PtrPtrKernelParam,
8257   PtrKernelParam,
8258   InvalidAddrSpacePtrKernelParam,
8259   InvalidKernelParam,
8260   RecordKernelParam
8261 };
8262 
8263 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8264   // Size dependent types are just typedefs to normal integer types
8265   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8266   // integers other than by their names.
8267   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8268 
8269   // Remove typedefs one by one until we reach a typedef
8270   // for a size dependent type.
8271   QualType DesugaredTy = Ty;
8272   do {
8273     ArrayRef<StringRef> Names(SizeTypeNames);
8274     auto Match = llvm::find(Names, DesugaredTy.getAsString());
8275     if (Names.end() != Match)
8276       return true;
8277 
8278     Ty = DesugaredTy;
8279     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8280   } while (DesugaredTy != Ty);
8281 
8282   return false;
8283 }
8284 
8285 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8286   if (PT->isPointerType()) {
8287     QualType PointeeType = PT->getPointeeType();
8288     if (PointeeType->isPointerType())
8289       return PtrPtrKernelParam;
8290     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8291         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8292         PointeeType.getAddressSpace() == LangAS::Default)
8293       return InvalidAddrSpacePtrKernelParam;
8294     return PtrKernelParam;
8295   }
8296 
8297   // OpenCL v1.2 s6.9.k:
8298   // Arguments to kernel functions in a program cannot be declared with the
8299   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8300   // uintptr_t or a struct and/or union that contain fields declared to be one
8301   // of these built-in scalar types.
8302   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8303     return InvalidKernelParam;
8304 
8305   if (PT->isImageType())
8306     return PtrKernelParam;
8307 
8308   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8309     return InvalidKernelParam;
8310 
8311   // OpenCL extension spec v1.2 s9.5:
8312   // This extension adds support for half scalar and vector types as built-in
8313   // types that can be used for arithmetic operations, conversions etc.
8314   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8315     return InvalidKernelParam;
8316 
8317   if (PT->isRecordType())
8318     return RecordKernelParam;
8319 
8320   // Look into an array argument to check if it has a forbidden type.
8321   if (PT->isArrayType()) {
8322     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8323     // Call ourself to check an underlying type of an array. Since the
8324     // getPointeeOrArrayElementType returns an innermost type which is not an
8325     // array, this recursive call only happens once.
8326     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8327   }
8328 
8329   return ValidKernelParam;
8330 }
8331 
8332 static void checkIsValidOpenCLKernelParameter(
8333   Sema &S,
8334   Declarator &D,
8335   ParmVarDecl *Param,
8336   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8337   QualType PT = Param->getType();
8338 
8339   // Cache the valid types we encounter to avoid rechecking structs that are
8340   // used again
8341   if (ValidTypes.count(PT.getTypePtr()))
8342     return;
8343 
8344   switch (getOpenCLKernelParameterType(S, PT)) {
8345   case PtrPtrKernelParam:
8346     // OpenCL v1.2 s6.9.a:
8347     // A kernel function argument cannot be declared as a
8348     // pointer to a pointer type.
8349     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8350     D.setInvalidType();
8351     return;
8352 
8353   case InvalidAddrSpacePtrKernelParam:
8354     // OpenCL v1.0 s6.5:
8355     // __kernel function arguments declared to be a pointer of a type can point
8356     // to one of the following address spaces only : __global, __local or
8357     // __constant.
8358     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8359     D.setInvalidType();
8360     return;
8361 
8362     // OpenCL v1.2 s6.9.k:
8363     // Arguments to kernel functions in a program cannot be declared with the
8364     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8365     // uintptr_t or a struct and/or union that contain fields declared to be
8366     // one of these built-in scalar types.
8367 
8368   case InvalidKernelParam:
8369     // OpenCL v1.2 s6.8 n:
8370     // A kernel function argument cannot be declared
8371     // of event_t type.
8372     // Do not diagnose half type since it is diagnosed as invalid argument
8373     // type for any function elsewhere.
8374     if (!PT->isHalfType()) {
8375       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8376 
8377       // Explain what typedefs are involved.
8378       const TypedefType *Typedef = nullptr;
8379       while ((Typedef = PT->getAs<TypedefType>())) {
8380         SourceLocation Loc = Typedef->getDecl()->getLocation();
8381         // SourceLocation may be invalid for a built-in type.
8382         if (Loc.isValid())
8383           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8384         PT = Typedef->desugar();
8385       }
8386     }
8387 
8388     D.setInvalidType();
8389     return;
8390 
8391   case PtrKernelParam:
8392   case ValidKernelParam:
8393     ValidTypes.insert(PT.getTypePtr());
8394     return;
8395 
8396   case RecordKernelParam:
8397     break;
8398   }
8399 
8400   // Track nested structs we will inspect
8401   SmallVector<const Decl *, 4> VisitStack;
8402 
8403   // Track where we are in the nested structs. Items will migrate from
8404   // VisitStack to HistoryStack as we do the DFS for bad field.
8405   SmallVector<const FieldDecl *, 4> HistoryStack;
8406   HistoryStack.push_back(nullptr);
8407 
8408   // At this point we already handled everything except of a RecordType or
8409   // an ArrayType of a RecordType.
8410   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8411   const RecordType *RecTy =
8412       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8413   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8414 
8415   VisitStack.push_back(RecTy->getDecl());
8416   assert(VisitStack.back() && "First decl null?");
8417 
8418   do {
8419     const Decl *Next = VisitStack.pop_back_val();
8420     if (!Next) {
8421       assert(!HistoryStack.empty());
8422       // Found a marker, we have gone up a level
8423       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8424         ValidTypes.insert(Hist->getType().getTypePtr());
8425 
8426       continue;
8427     }
8428 
8429     // Adds everything except the original parameter declaration (which is not a
8430     // field itself) to the history stack.
8431     const RecordDecl *RD;
8432     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8433       HistoryStack.push_back(Field);
8434 
8435       QualType FieldTy = Field->getType();
8436       // Other field types (known to be valid or invalid) are handled while we
8437       // walk around RecordDecl::fields().
8438       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8439              "Unexpected type.");
8440       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8441 
8442       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8443     } else {
8444       RD = cast<RecordDecl>(Next);
8445     }
8446 
8447     // Add a null marker so we know when we've gone back up a level
8448     VisitStack.push_back(nullptr);
8449 
8450     for (const auto *FD : RD->fields()) {
8451       QualType QT = FD->getType();
8452 
8453       if (ValidTypes.count(QT.getTypePtr()))
8454         continue;
8455 
8456       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8457       if (ParamType == ValidKernelParam)
8458         continue;
8459 
8460       if (ParamType == RecordKernelParam) {
8461         VisitStack.push_back(FD);
8462         continue;
8463       }
8464 
8465       // OpenCL v1.2 s6.9.p:
8466       // Arguments to kernel functions that are declared to be a struct or union
8467       // do not allow OpenCL objects to be passed as elements of the struct or
8468       // union.
8469       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8470           ParamType == InvalidAddrSpacePtrKernelParam) {
8471         S.Diag(Param->getLocation(),
8472                diag::err_record_with_pointers_kernel_param)
8473           << PT->isUnionType()
8474           << PT;
8475       } else {
8476         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8477       }
8478 
8479       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8480           << OrigRecDecl->getDeclName();
8481 
8482       // We have an error, now let's go back up through history and show where
8483       // the offending field came from
8484       for (ArrayRef<const FieldDecl *>::const_iterator
8485                I = HistoryStack.begin() + 1,
8486                E = HistoryStack.end();
8487            I != E; ++I) {
8488         const FieldDecl *OuterField = *I;
8489         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8490           << OuterField->getType();
8491       }
8492 
8493       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8494         << QT->isPointerType()
8495         << QT;
8496       D.setInvalidType();
8497       return;
8498     }
8499   } while (!VisitStack.empty());
8500 }
8501 
8502 /// Find the DeclContext in which a tag is implicitly declared if we see an
8503 /// elaborated type specifier in the specified context, and lookup finds
8504 /// nothing.
8505 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8506   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8507     DC = DC->getParent();
8508   return DC;
8509 }
8510 
8511 /// Find the Scope in which a tag is implicitly declared if we see an
8512 /// elaborated type specifier in the specified context, and lookup finds
8513 /// nothing.
8514 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8515   while (S->isClassScope() ||
8516          (LangOpts.CPlusPlus &&
8517           S->isFunctionPrototypeScope()) ||
8518          ((S->getFlags() & Scope::DeclScope) == 0) ||
8519          (S->getEntity() && S->getEntity()->isTransparentContext()))
8520     S = S->getParent();
8521   return S;
8522 }
8523 
8524 NamedDecl*
8525 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8526                               TypeSourceInfo *TInfo, LookupResult &Previous,
8527                               MultiTemplateParamsArg TemplateParamLists,
8528                               bool &AddToScope) {
8529   QualType R = TInfo->getType();
8530 
8531   assert(R->isFunctionType());
8532 
8533   // TODO: consider using NameInfo for diagnostic.
8534   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8535   DeclarationName Name = NameInfo.getName();
8536   StorageClass SC = getFunctionStorageClass(*this, D);
8537 
8538   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8539     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8540          diag::err_invalid_thread)
8541       << DeclSpec::getSpecifierName(TSCS);
8542 
8543   if (D.isFirstDeclarationOfMember())
8544     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8545                            D.getIdentifierLoc());
8546 
8547   bool isFriend = false;
8548   FunctionTemplateDecl *FunctionTemplate = nullptr;
8549   bool isMemberSpecialization = false;
8550   bool isFunctionTemplateSpecialization = false;
8551 
8552   bool isDependentClassScopeExplicitSpecialization = false;
8553   bool HasExplicitTemplateArgs = false;
8554   TemplateArgumentListInfo TemplateArgs;
8555 
8556   bool isVirtualOkay = false;
8557 
8558   DeclContext *OriginalDC = DC;
8559   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8560 
8561   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8562                                               isVirtualOkay);
8563   if (!NewFD) return nullptr;
8564 
8565   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8566     NewFD->setTopLevelDeclInObjCContainer();
8567 
8568   // Set the lexical context. If this is a function-scope declaration, or has a
8569   // C++ scope specifier, or is the object of a friend declaration, the lexical
8570   // context will be different from the semantic context.
8571   NewFD->setLexicalDeclContext(CurContext);
8572 
8573   if (IsLocalExternDecl)
8574     NewFD->setLocalExternDecl();
8575 
8576   if (getLangOpts().CPlusPlus) {
8577     bool isInline = D.getDeclSpec().isInlineSpecified();
8578     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8579     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
8580     isFriend = D.getDeclSpec().isFriendSpecified();
8581     if (isFriend && !isInline && D.isFunctionDefinition()) {
8582       // C++ [class.friend]p5
8583       //   A function can be defined in a friend declaration of a
8584       //   class . . . . Such a function is implicitly inline.
8585       NewFD->setImplicitlyInline();
8586     }
8587 
8588     // If this is a method defined in an __interface, and is not a constructor
8589     // or an overloaded operator, then set the pure flag (isVirtual will already
8590     // return true).
8591     if (const CXXRecordDecl *Parent =
8592           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8593       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8594         NewFD->setPure(true);
8595 
8596       // C++ [class.union]p2
8597       //   A union can have member functions, but not virtual functions.
8598       if (isVirtual && Parent->isUnion())
8599         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8600     }
8601 
8602     SetNestedNameSpecifier(*this, NewFD, D);
8603     isMemberSpecialization = false;
8604     isFunctionTemplateSpecialization = false;
8605     if (D.isInvalidType())
8606       NewFD->setInvalidDecl();
8607 
8608     // Match up the template parameter lists with the scope specifier, then
8609     // determine whether we have a template or a template specialization.
8610     bool Invalid = false;
8611     if (TemplateParameterList *TemplateParams =
8612             MatchTemplateParametersToScopeSpecifier(
8613                 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8614                 D.getCXXScopeSpec(),
8615                 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8616                     ? D.getName().TemplateId
8617                     : nullptr,
8618                 TemplateParamLists, isFriend, isMemberSpecialization,
8619                 Invalid)) {
8620       if (TemplateParams->size() > 0) {
8621         // This is a function template
8622 
8623         // Check that we can declare a template here.
8624         if (CheckTemplateDeclScope(S, TemplateParams))
8625           NewFD->setInvalidDecl();
8626 
8627         // A destructor cannot be a template.
8628         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8629           Diag(NewFD->getLocation(), diag::err_destructor_template);
8630           NewFD->setInvalidDecl();
8631         }
8632 
8633         // If we're adding a template to a dependent context, we may need to
8634         // rebuilding some of the types used within the template parameter list,
8635         // now that we know what the current instantiation is.
8636         if (DC->isDependentContext()) {
8637           ContextRAII SavedContext(*this, DC);
8638           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8639             Invalid = true;
8640         }
8641 
8642         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8643                                                         NewFD->getLocation(),
8644                                                         Name, TemplateParams,
8645                                                         NewFD);
8646         FunctionTemplate->setLexicalDeclContext(CurContext);
8647         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8648 
8649         // For source fidelity, store the other template param lists.
8650         if (TemplateParamLists.size() > 1) {
8651           NewFD->setTemplateParameterListsInfo(Context,
8652                                                TemplateParamLists.drop_back(1));
8653         }
8654       } else {
8655         // This is a function template specialization.
8656         isFunctionTemplateSpecialization = true;
8657         // For source fidelity, store all the template param lists.
8658         if (TemplateParamLists.size() > 0)
8659           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8660 
8661         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8662         if (isFriend) {
8663           // We want to remove the "template<>", found here.
8664           SourceRange RemoveRange = TemplateParams->getSourceRange();
8665 
8666           // If we remove the template<> and the name is not a
8667           // template-id, we're actually silently creating a problem:
8668           // the friend declaration will refer to an untemplated decl,
8669           // and clearly the user wants a template specialization.  So
8670           // we need to insert '<>' after the name.
8671           SourceLocation InsertLoc;
8672           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8673             InsertLoc = D.getName().getSourceRange().getEnd();
8674             InsertLoc = getLocForEndOfToken(InsertLoc);
8675           }
8676 
8677           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8678             << Name << RemoveRange
8679             << FixItHint::CreateRemoval(RemoveRange)
8680             << FixItHint::CreateInsertion(InsertLoc, "<>");
8681         }
8682       }
8683     } else {
8684       // All template param lists were matched against the scope specifier:
8685       // this is NOT (an explicit specialization of) a template.
8686       if (TemplateParamLists.size() > 0)
8687         // For source fidelity, store all the template param lists.
8688         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8689     }
8690 
8691     if (Invalid) {
8692       NewFD->setInvalidDecl();
8693       if (FunctionTemplate)
8694         FunctionTemplate->setInvalidDecl();
8695     }
8696 
8697     // C++ [dcl.fct.spec]p5:
8698     //   The virtual specifier shall only be used in declarations of
8699     //   nonstatic class member functions that appear within a
8700     //   member-specification of a class declaration; see 10.3.
8701     //
8702     if (isVirtual && !NewFD->isInvalidDecl()) {
8703       if (!isVirtualOkay) {
8704         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8705              diag::err_virtual_non_function);
8706       } else if (!CurContext->isRecord()) {
8707         // 'virtual' was specified outside of the class.
8708         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8709              diag::err_virtual_out_of_class)
8710           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8711       } else if (NewFD->getDescribedFunctionTemplate()) {
8712         // C++ [temp.mem]p3:
8713         //  A member function template shall not be virtual.
8714         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8715              diag::err_virtual_member_function_template)
8716           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8717       } else {
8718         // Okay: Add virtual to the method.
8719         NewFD->setVirtualAsWritten(true);
8720       }
8721 
8722       if (getLangOpts().CPlusPlus14 &&
8723           NewFD->getReturnType()->isUndeducedType())
8724         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8725     }
8726 
8727     if (getLangOpts().CPlusPlus14 &&
8728         (NewFD->isDependentContext() ||
8729          (isFriend && CurContext->isDependentContext())) &&
8730         NewFD->getReturnType()->isUndeducedType()) {
8731       // If the function template is referenced directly (for instance, as a
8732       // member of the current instantiation), pretend it has a dependent type.
8733       // This is not really justified by the standard, but is the only sane
8734       // thing to do.
8735       // FIXME: For a friend function, we have not marked the function as being
8736       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8737       const FunctionProtoType *FPT =
8738           NewFD->getType()->castAs<FunctionProtoType>();
8739       QualType Result =
8740           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8741       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8742                                              FPT->getExtProtoInfo()));
8743     }
8744 
8745     // C++ [dcl.fct.spec]p3:
8746     //  The inline specifier shall not appear on a block scope function
8747     //  declaration.
8748     if (isInline && !NewFD->isInvalidDecl()) {
8749       if (CurContext->isFunctionOrMethod()) {
8750         // 'inline' is not allowed on block scope function declaration.
8751         Diag(D.getDeclSpec().getInlineSpecLoc(),
8752              diag::err_inline_declaration_block_scope) << Name
8753           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8754       }
8755     }
8756 
8757     // C++ [dcl.fct.spec]p6:
8758     //  The explicit specifier shall be used only in the declaration of a
8759     //  constructor or conversion function within its class definition;
8760     //  see 12.3.1 and 12.3.2.
8761     if (hasExplicit && !NewFD->isInvalidDecl() &&
8762         !isa<CXXDeductionGuideDecl>(NewFD)) {
8763       if (!CurContext->isRecord()) {
8764         // 'explicit' was specified outside of the class.
8765         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8766              diag::err_explicit_out_of_class)
8767             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
8768       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8769                  !isa<CXXConversionDecl>(NewFD)) {
8770         // 'explicit' was specified on a function that wasn't a constructor
8771         // or conversion function.
8772         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8773              diag::err_explicit_non_ctor_or_conv_function)
8774             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
8775       }
8776     }
8777 
8778     if (ConstexprSpecKind ConstexprKind =
8779             D.getDeclSpec().getConstexprSpecifier()) {
8780       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8781       // are implicitly inline.
8782       NewFD->setImplicitlyInline();
8783 
8784       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8785       // be either constructors or to return a literal type. Therefore,
8786       // destructors cannot be declared constexpr.
8787       if (isa<CXXDestructorDecl>(NewFD) && !getLangOpts().CPlusPlus2a) {
8788         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
8789             << ConstexprKind;
8790       }
8791     }
8792 
8793     // If __module_private__ was specified, mark the function accordingly.
8794     if (D.getDeclSpec().isModulePrivateSpecified()) {
8795       if (isFunctionTemplateSpecialization) {
8796         SourceLocation ModulePrivateLoc
8797           = D.getDeclSpec().getModulePrivateSpecLoc();
8798         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8799           << 0
8800           << FixItHint::CreateRemoval(ModulePrivateLoc);
8801       } else {
8802         NewFD->setModulePrivate();
8803         if (FunctionTemplate)
8804           FunctionTemplate->setModulePrivate();
8805       }
8806     }
8807 
8808     if (isFriend) {
8809       if (FunctionTemplate) {
8810         FunctionTemplate->setObjectOfFriendDecl();
8811         FunctionTemplate->setAccess(AS_public);
8812       }
8813       NewFD->setObjectOfFriendDecl();
8814       NewFD->setAccess(AS_public);
8815     }
8816 
8817     // If a function is defined as defaulted or deleted, mark it as such now.
8818     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8819     // definition kind to FDK_Definition.
8820     switch (D.getFunctionDefinitionKind()) {
8821       case FDK_Declaration:
8822       case FDK_Definition:
8823         break;
8824 
8825       case FDK_Defaulted:
8826         NewFD->setDefaulted();
8827         break;
8828 
8829       case FDK_Deleted:
8830         NewFD->setDeletedAsWritten();
8831         break;
8832     }
8833 
8834     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8835         D.isFunctionDefinition()) {
8836       // C++ [class.mfct]p2:
8837       //   A member function may be defined (8.4) in its class definition, in
8838       //   which case it is an inline member function (7.1.2)
8839       NewFD->setImplicitlyInline();
8840     }
8841 
8842     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8843         !CurContext->isRecord()) {
8844       // C++ [class.static]p1:
8845       //   A data or function member of a class may be declared static
8846       //   in a class definition, in which case it is a static member of
8847       //   the class.
8848 
8849       // Complain about the 'static' specifier if it's on an out-of-line
8850       // member function definition.
8851 
8852       // MSVC permits the use of a 'static' storage specifier on an out-of-line
8853       // member function template declaration and class member template
8854       // declaration (MSVC versions before 2015), warn about this.
8855       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8856            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
8857              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
8858            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
8859            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
8860         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8861     }
8862 
8863     // C++11 [except.spec]p15:
8864     //   A deallocation function with no exception-specification is treated
8865     //   as if it were specified with noexcept(true).
8866     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8867     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8868          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8869         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8870       NewFD->setType(Context.getFunctionType(
8871           FPT->getReturnType(), FPT->getParamTypes(),
8872           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8873   }
8874 
8875   // Filter out previous declarations that don't match the scope.
8876   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8877                        D.getCXXScopeSpec().isNotEmpty() ||
8878                        isMemberSpecialization ||
8879                        isFunctionTemplateSpecialization);
8880 
8881   // Handle GNU asm-label extension (encoded as an attribute).
8882   if (Expr *E = (Expr*) D.getAsmLabel()) {
8883     // The parser guarantees this is a string.
8884     StringLiteral *SE = cast<StringLiteral>(E);
8885     NewFD->addAttr(::new (Context)
8886                        AsmLabelAttr(Context, SE->getStrTokenLoc(0),
8887                                     SE->getString(), /*IsLiteralLabel=*/true));
8888   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8889     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8890       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8891     if (I != ExtnameUndeclaredIdentifiers.end()) {
8892       if (isDeclExternC(NewFD)) {
8893         NewFD->addAttr(I->second);
8894         ExtnameUndeclaredIdentifiers.erase(I);
8895       } else
8896         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8897             << /*Variable*/0 << NewFD;
8898     }
8899   }
8900 
8901   // Copy the parameter declarations from the declarator D to the function
8902   // declaration NewFD, if they are available.  First scavenge them into Params.
8903   SmallVector<ParmVarDecl*, 16> Params;
8904   unsigned FTIIdx;
8905   if (D.isFunctionDeclarator(FTIIdx)) {
8906     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8907 
8908     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8909     // function that takes no arguments, not a function that takes a
8910     // single void argument.
8911     // We let through "const void" here because Sema::GetTypeForDeclarator
8912     // already checks for that case.
8913     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8914       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8915         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8916         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8917         Param->setDeclContext(NewFD);
8918         Params.push_back(Param);
8919 
8920         if (Param->isInvalidDecl())
8921           NewFD->setInvalidDecl();
8922       }
8923     }
8924 
8925     if (!getLangOpts().CPlusPlus) {
8926       // In C, find all the tag declarations from the prototype and move them
8927       // into the function DeclContext. Remove them from the surrounding tag
8928       // injection context of the function, which is typically but not always
8929       // the TU.
8930       DeclContext *PrototypeTagContext =
8931           getTagInjectionContext(NewFD->getLexicalDeclContext());
8932       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8933         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8934 
8935         // We don't want to reparent enumerators. Look at their parent enum
8936         // instead.
8937         if (!TD) {
8938           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8939             TD = cast<EnumDecl>(ECD->getDeclContext());
8940         }
8941         if (!TD)
8942           continue;
8943         DeclContext *TagDC = TD->getLexicalDeclContext();
8944         if (!TagDC->containsDecl(TD))
8945           continue;
8946         TagDC->removeDecl(TD);
8947         TD->setDeclContext(NewFD);
8948         NewFD->addDecl(TD);
8949 
8950         // Preserve the lexical DeclContext if it is not the surrounding tag
8951         // injection context of the FD. In this example, the semantic context of
8952         // E will be f and the lexical context will be S, while both the
8953         // semantic and lexical contexts of S will be f:
8954         //   void f(struct S { enum E { a } f; } s);
8955         if (TagDC != PrototypeTagContext)
8956           TD->setLexicalDeclContext(TagDC);
8957       }
8958     }
8959   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8960     // When we're declaring a function with a typedef, typeof, etc as in the
8961     // following example, we'll need to synthesize (unnamed)
8962     // parameters for use in the declaration.
8963     //
8964     // @code
8965     // typedef void fn(int);
8966     // fn f;
8967     // @endcode
8968 
8969     // Synthesize a parameter for each argument type.
8970     for (const auto &AI : FT->param_types()) {
8971       ParmVarDecl *Param =
8972           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8973       Param->setScopeInfo(0, Params.size());
8974       Params.push_back(Param);
8975     }
8976   } else {
8977     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8978            "Should not need args for typedef of non-prototype fn");
8979   }
8980 
8981   // Finally, we know we have the right number of parameters, install them.
8982   NewFD->setParams(Params);
8983 
8984   if (D.getDeclSpec().isNoreturnSpecified())
8985     NewFD->addAttr(C11NoReturnAttr::Create(Context,
8986                                            D.getDeclSpec().getNoreturnSpecLoc(),
8987                                            AttributeCommonInfo::AS_Keyword));
8988 
8989   // Functions returning a variably modified type violate C99 6.7.5.2p2
8990   // because all functions have linkage.
8991   if (!NewFD->isInvalidDecl() &&
8992       NewFD->getReturnType()->isVariablyModifiedType()) {
8993     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8994     NewFD->setInvalidDecl();
8995   }
8996 
8997   // Apply an implicit SectionAttr if '#pragma clang section text' is active
8998   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
8999       !NewFD->hasAttr<SectionAttr>())
9000     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9001         Context, PragmaClangTextSection.SectionName,
9002         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9003 
9004   // Apply an implicit SectionAttr if #pragma code_seg is active.
9005   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9006       !NewFD->hasAttr<SectionAttr>()) {
9007     NewFD->addAttr(SectionAttr::CreateImplicit(
9008         Context, CodeSegStack.CurrentValue->getString(),
9009         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9010         SectionAttr::Declspec_allocate));
9011     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9012                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9013                          ASTContext::PSF_Read,
9014                      NewFD))
9015       NewFD->dropAttr<SectionAttr>();
9016   }
9017 
9018   // Apply an implicit CodeSegAttr from class declspec or
9019   // apply an implicit SectionAttr from #pragma code_seg if active.
9020   if (!NewFD->hasAttr<CodeSegAttr>()) {
9021     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9022                                                                  D.isFunctionDefinition())) {
9023       NewFD->addAttr(SAttr);
9024     }
9025   }
9026 
9027   // Handle attributes.
9028   ProcessDeclAttributes(S, NewFD, D);
9029 
9030   if (getLangOpts().OpenCL) {
9031     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9032     // type declaration will generate a compilation error.
9033     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9034     if (AddressSpace != LangAS::Default) {
9035       Diag(NewFD->getLocation(),
9036            diag::err_opencl_return_value_with_address_space);
9037       NewFD->setInvalidDecl();
9038     }
9039   }
9040 
9041   if (!getLangOpts().CPlusPlus) {
9042     // Perform semantic checking on the function declaration.
9043     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9044       CheckMain(NewFD, D.getDeclSpec());
9045 
9046     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9047       CheckMSVCRTEntryPoint(NewFD);
9048 
9049     if (!NewFD->isInvalidDecl())
9050       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9051                                                   isMemberSpecialization));
9052     else if (!Previous.empty())
9053       // Recover gracefully from an invalid redeclaration.
9054       D.setRedeclaration(true);
9055     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9056             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9057            "previous declaration set still overloaded");
9058 
9059     // Diagnose no-prototype function declarations with calling conventions that
9060     // don't support variadic calls. Only do this in C and do it after merging
9061     // possibly prototyped redeclarations.
9062     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9063     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9064       CallingConv CC = FT->getExtInfo().getCC();
9065       if (!supportsVariadicCall(CC)) {
9066         // Windows system headers sometimes accidentally use stdcall without
9067         // (void) parameters, so we relax this to a warning.
9068         int DiagID =
9069             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9070         Diag(NewFD->getLocation(), DiagID)
9071             << FunctionType::getNameForCallConv(CC);
9072       }
9073     }
9074 
9075    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9076        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9077      checkNonTrivialCUnion(NewFD->getReturnType(),
9078                            NewFD->getReturnTypeSourceRange().getBegin(),
9079                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9080   } else {
9081     // C++11 [replacement.functions]p3:
9082     //  The program's definitions shall not be specified as inline.
9083     //
9084     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9085     //
9086     // Suppress the diagnostic if the function is __attribute__((used)), since
9087     // that forces an external definition to be emitted.
9088     if (D.getDeclSpec().isInlineSpecified() &&
9089         NewFD->isReplaceableGlobalAllocationFunction() &&
9090         !NewFD->hasAttr<UsedAttr>())
9091       Diag(D.getDeclSpec().getInlineSpecLoc(),
9092            diag::ext_operator_new_delete_declared_inline)
9093         << NewFD->getDeclName();
9094 
9095     // If the declarator is a template-id, translate the parser's template
9096     // argument list into our AST format.
9097     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9098       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9099       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9100       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9101       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9102                                          TemplateId->NumArgs);
9103       translateTemplateArguments(TemplateArgsPtr,
9104                                  TemplateArgs);
9105 
9106       HasExplicitTemplateArgs = true;
9107 
9108       if (NewFD->isInvalidDecl()) {
9109         HasExplicitTemplateArgs = false;
9110       } else if (FunctionTemplate) {
9111         // Function template with explicit template arguments.
9112         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9113           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9114 
9115         HasExplicitTemplateArgs = false;
9116       } else {
9117         assert((isFunctionTemplateSpecialization ||
9118                 D.getDeclSpec().isFriendSpecified()) &&
9119                "should have a 'template<>' for this decl");
9120         // "friend void foo<>(int);" is an implicit specialization decl.
9121         isFunctionTemplateSpecialization = true;
9122       }
9123     } else if (isFriend && isFunctionTemplateSpecialization) {
9124       // This combination is only possible in a recovery case;  the user
9125       // wrote something like:
9126       //   template <> friend void foo(int);
9127       // which we're recovering from as if the user had written:
9128       //   friend void foo<>(int);
9129       // Go ahead and fake up a template id.
9130       HasExplicitTemplateArgs = true;
9131       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9132       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9133     }
9134 
9135     // We do not add HD attributes to specializations here because
9136     // they may have different constexpr-ness compared to their
9137     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9138     // may end up with different effective targets. Instead, a
9139     // specialization inherits its target attributes from its template
9140     // in the CheckFunctionTemplateSpecialization() call below.
9141     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9142       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9143 
9144     // If it's a friend (and only if it's a friend), it's possible
9145     // that either the specialized function type or the specialized
9146     // template is dependent, and therefore matching will fail.  In
9147     // this case, don't check the specialization yet.
9148     bool InstantiationDependent = false;
9149     if (isFunctionTemplateSpecialization && isFriend &&
9150         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9151          TemplateSpecializationType::anyDependentTemplateArguments(
9152             TemplateArgs,
9153             InstantiationDependent))) {
9154       assert(HasExplicitTemplateArgs &&
9155              "friend function specialization without template args");
9156       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9157                                                        Previous))
9158         NewFD->setInvalidDecl();
9159     } else if (isFunctionTemplateSpecialization) {
9160       if (CurContext->isDependentContext() && CurContext->isRecord()
9161           && !isFriend) {
9162         isDependentClassScopeExplicitSpecialization = true;
9163       } else if (!NewFD->isInvalidDecl() &&
9164                  CheckFunctionTemplateSpecialization(
9165                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9166                      Previous))
9167         NewFD->setInvalidDecl();
9168 
9169       // C++ [dcl.stc]p1:
9170       //   A storage-class-specifier shall not be specified in an explicit
9171       //   specialization (14.7.3)
9172       FunctionTemplateSpecializationInfo *Info =
9173           NewFD->getTemplateSpecializationInfo();
9174       if (Info && SC != SC_None) {
9175         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9176           Diag(NewFD->getLocation(),
9177                diag::err_explicit_specialization_inconsistent_storage_class)
9178             << SC
9179             << FixItHint::CreateRemoval(
9180                                       D.getDeclSpec().getStorageClassSpecLoc());
9181 
9182         else
9183           Diag(NewFD->getLocation(),
9184                diag::ext_explicit_specialization_storage_class)
9185             << FixItHint::CreateRemoval(
9186                                       D.getDeclSpec().getStorageClassSpecLoc());
9187       }
9188     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9189       if (CheckMemberSpecialization(NewFD, Previous))
9190           NewFD->setInvalidDecl();
9191     }
9192 
9193     // Perform semantic checking on the function declaration.
9194     if (!isDependentClassScopeExplicitSpecialization) {
9195       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9196         CheckMain(NewFD, D.getDeclSpec());
9197 
9198       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9199         CheckMSVCRTEntryPoint(NewFD);
9200 
9201       if (!NewFD->isInvalidDecl())
9202         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9203                                                     isMemberSpecialization));
9204       else if (!Previous.empty())
9205         // Recover gracefully from an invalid redeclaration.
9206         D.setRedeclaration(true);
9207     }
9208 
9209     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9210             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9211            "previous declaration set still overloaded");
9212 
9213     NamedDecl *PrincipalDecl = (FunctionTemplate
9214                                 ? cast<NamedDecl>(FunctionTemplate)
9215                                 : NewFD);
9216 
9217     if (isFriend && NewFD->getPreviousDecl()) {
9218       AccessSpecifier Access = AS_public;
9219       if (!NewFD->isInvalidDecl())
9220         Access = NewFD->getPreviousDecl()->getAccess();
9221 
9222       NewFD->setAccess(Access);
9223       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9224     }
9225 
9226     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9227         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9228       PrincipalDecl->setNonMemberOperator();
9229 
9230     // If we have a function template, check the template parameter
9231     // list. This will check and merge default template arguments.
9232     if (FunctionTemplate) {
9233       FunctionTemplateDecl *PrevTemplate =
9234                                      FunctionTemplate->getPreviousDecl();
9235       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9236                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9237                                     : nullptr,
9238                             D.getDeclSpec().isFriendSpecified()
9239                               ? (D.isFunctionDefinition()
9240                                    ? TPC_FriendFunctionTemplateDefinition
9241                                    : TPC_FriendFunctionTemplate)
9242                               : (D.getCXXScopeSpec().isSet() &&
9243                                  DC && DC->isRecord() &&
9244                                  DC->isDependentContext())
9245                                   ? TPC_ClassTemplateMember
9246                                   : TPC_FunctionTemplate);
9247     }
9248 
9249     if (NewFD->isInvalidDecl()) {
9250       // Ignore all the rest of this.
9251     } else if (!D.isRedeclaration()) {
9252       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9253                                        AddToScope };
9254       // Fake up an access specifier if it's supposed to be a class member.
9255       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9256         NewFD->setAccess(AS_public);
9257 
9258       // Qualified decls generally require a previous declaration.
9259       if (D.getCXXScopeSpec().isSet()) {
9260         // ...with the major exception of templated-scope or
9261         // dependent-scope friend declarations.
9262 
9263         // TODO: we currently also suppress this check in dependent
9264         // contexts because (1) the parameter depth will be off when
9265         // matching friend templates and (2) we might actually be
9266         // selecting a friend based on a dependent factor.  But there
9267         // are situations where these conditions don't apply and we
9268         // can actually do this check immediately.
9269         //
9270         // Unless the scope is dependent, it's always an error if qualified
9271         // redeclaration lookup found nothing at all. Diagnose that now;
9272         // nothing will diagnose that error later.
9273         if (isFriend &&
9274             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9275              (!Previous.empty() && CurContext->isDependentContext()))) {
9276           // ignore these
9277         } else {
9278           // The user tried to provide an out-of-line definition for a
9279           // function that is a member of a class or namespace, but there
9280           // was no such member function declared (C++ [class.mfct]p2,
9281           // C++ [namespace.memdef]p2). For example:
9282           //
9283           // class X {
9284           //   void f() const;
9285           // };
9286           //
9287           // void X::f() { } // ill-formed
9288           //
9289           // Complain about this problem, and attempt to suggest close
9290           // matches (e.g., those that differ only in cv-qualifiers and
9291           // whether the parameter types are references).
9292 
9293           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9294                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9295             AddToScope = ExtraArgs.AddToScope;
9296             return Result;
9297           }
9298         }
9299 
9300         // Unqualified local friend declarations are required to resolve
9301         // to something.
9302       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9303         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9304                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9305           AddToScope = ExtraArgs.AddToScope;
9306           return Result;
9307         }
9308       }
9309     } else if (!D.isFunctionDefinition() &&
9310                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9311                !isFriend && !isFunctionTemplateSpecialization &&
9312                !isMemberSpecialization) {
9313       // An out-of-line member function declaration must also be a
9314       // definition (C++ [class.mfct]p2).
9315       // Note that this is not the case for explicit specializations of
9316       // function templates or member functions of class templates, per
9317       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9318       // extension for compatibility with old SWIG code which likes to
9319       // generate them.
9320       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9321         << D.getCXXScopeSpec().getRange();
9322     }
9323   }
9324 
9325   ProcessPragmaWeak(S, NewFD);
9326   checkAttributesAfterMerging(*this, *NewFD);
9327 
9328   AddKnownFunctionAttributes(NewFD);
9329 
9330   if (NewFD->hasAttr<OverloadableAttr>() &&
9331       !NewFD->getType()->getAs<FunctionProtoType>()) {
9332     Diag(NewFD->getLocation(),
9333          diag::err_attribute_overloadable_no_prototype)
9334       << NewFD;
9335 
9336     // Turn this into a variadic function with no parameters.
9337     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9338     FunctionProtoType::ExtProtoInfo EPI(
9339         Context.getDefaultCallingConvention(true, false));
9340     EPI.Variadic = true;
9341     EPI.ExtInfo = FT->getExtInfo();
9342 
9343     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9344     NewFD->setType(R);
9345   }
9346 
9347   // If there's a #pragma GCC visibility in scope, and this isn't a class
9348   // member, set the visibility of this function.
9349   if (!DC->isRecord() && NewFD->isExternallyVisible())
9350     AddPushedVisibilityAttribute(NewFD);
9351 
9352   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9353   // marking the function.
9354   AddCFAuditedAttribute(NewFD);
9355 
9356   // If this is a function definition, check if we have to apply optnone due to
9357   // a pragma.
9358   if(D.isFunctionDefinition())
9359     AddRangeBasedOptnone(NewFD);
9360 
9361   // If this is the first declaration of an extern C variable, update
9362   // the map of such variables.
9363   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9364       isIncompleteDeclExternC(*this, NewFD))
9365     RegisterLocallyScopedExternCDecl(NewFD, S);
9366 
9367   // Set this FunctionDecl's range up to the right paren.
9368   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9369 
9370   if (D.isRedeclaration() && !Previous.empty()) {
9371     NamedDecl *Prev = Previous.getRepresentativeDecl();
9372     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9373                                    isMemberSpecialization ||
9374                                        isFunctionTemplateSpecialization,
9375                                    D.isFunctionDefinition());
9376   }
9377 
9378   if (getLangOpts().CUDA) {
9379     IdentifierInfo *II = NewFD->getIdentifier();
9380     if (II && II->isStr(getCudaConfigureFuncName()) &&
9381         !NewFD->isInvalidDecl() &&
9382         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9383       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9384         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9385             << getCudaConfigureFuncName();
9386       Context.setcudaConfigureCallDecl(NewFD);
9387     }
9388 
9389     // Variadic functions, other than a *declaration* of printf, are not allowed
9390     // in device-side CUDA code, unless someone passed
9391     // -fcuda-allow-variadic-functions.
9392     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9393         (NewFD->hasAttr<CUDADeviceAttr>() ||
9394          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9395         !(II && II->isStr("printf") && NewFD->isExternC() &&
9396           !D.isFunctionDefinition())) {
9397       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9398     }
9399   }
9400 
9401   MarkUnusedFileScopedDecl(NewFD);
9402 
9403 
9404 
9405   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9406     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9407     if ((getLangOpts().OpenCLVersion >= 120)
9408         && (SC == SC_Static)) {
9409       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9410       D.setInvalidType();
9411     }
9412 
9413     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9414     if (!NewFD->getReturnType()->isVoidType()) {
9415       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9416       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9417           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9418                                 : FixItHint());
9419       D.setInvalidType();
9420     }
9421 
9422     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9423     for (auto Param : NewFD->parameters())
9424       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9425 
9426     if (getLangOpts().OpenCLCPlusPlus) {
9427       if (DC->isRecord()) {
9428         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9429         D.setInvalidType();
9430       }
9431       if (FunctionTemplate) {
9432         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9433         D.setInvalidType();
9434       }
9435     }
9436   }
9437 
9438   if (getLangOpts().CPlusPlus) {
9439     if (FunctionTemplate) {
9440       if (NewFD->isInvalidDecl())
9441         FunctionTemplate->setInvalidDecl();
9442       return FunctionTemplate;
9443     }
9444 
9445     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9446       CompleteMemberSpecialization(NewFD, Previous);
9447   }
9448 
9449   for (const ParmVarDecl *Param : NewFD->parameters()) {
9450     QualType PT = Param->getType();
9451 
9452     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9453     // types.
9454     if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
9455       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9456         QualType ElemTy = PipeTy->getElementType();
9457           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9458             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9459             D.setInvalidType();
9460           }
9461       }
9462     }
9463   }
9464 
9465   // Here we have an function template explicit specialization at class scope.
9466   // The actual specialization will be postponed to template instatiation
9467   // time via the ClassScopeFunctionSpecializationDecl node.
9468   if (isDependentClassScopeExplicitSpecialization) {
9469     ClassScopeFunctionSpecializationDecl *NewSpec =
9470                          ClassScopeFunctionSpecializationDecl::Create(
9471                                 Context, CurContext, NewFD->getLocation(),
9472                                 cast<CXXMethodDecl>(NewFD),
9473                                 HasExplicitTemplateArgs, TemplateArgs);
9474     CurContext->addDecl(NewSpec);
9475     AddToScope = false;
9476   }
9477 
9478   // Diagnose availability attributes. Availability cannot be used on functions
9479   // that are run during load/unload.
9480   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9481     if (NewFD->hasAttr<ConstructorAttr>()) {
9482       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9483           << 1;
9484       NewFD->dropAttr<AvailabilityAttr>();
9485     }
9486     if (NewFD->hasAttr<DestructorAttr>()) {
9487       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9488           << 2;
9489       NewFD->dropAttr<AvailabilityAttr>();
9490     }
9491   }
9492 
9493   return NewFD;
9494 }
9495 
9496 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
9497 /// when __declspec(code_seg) "is applied to a class, all member functions of
9498 /// the class and nested classes -- this includes compiler-generated special
9499 /// member functions -- are put in the specified segment."
9500 /// The actual behavior is a little more complicated. The Microsoft compiler
9501 /// won't check outer classes if there is an active value from #pragma code_seg.
9502 /// The CodeSeg is always applied from the direct parent but only from outer
9503 /// classes when the #pragma code_seg stack is empty. See:
9504 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9505 /// available since MS has removed the page.
9506 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9507   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9508   if (!Method)
9509     return nullptr;
9510   const CXXRecordDecl *Parent = Method->getParent();
9511   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9512     Attr *NewAttr = SAttr->clone(S.getASTContext());
9513     NewAttr->setImplicit(true);
9514     return NewAttr;
9515   }
9516 
9517   // The Microsoft compiler won't check outer classes for the CodeSeg
9518   // when the #pragma code_seg stack is active.
9519   if (S.CodeSegStack.CurrentValue)
9520    return nullptr;
9521 
9522   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9523     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9524       Attr *NewAttr = SAttr->clone(S.getASTContext());
9525       NewAttr->setImplicit(true);
9526       return NewAttr;
9527     }
9528   }
9529   return nullptr;
9530 }
9531 
9532 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9533 /// containing class. Otherwise it will return implicit SectionAttr if the
9534 /// function is a definition and there is an active value on CodeSegStack
9535 /// (from the current #pragma code-seg value).
9536 ///
9537 /// \param FD Function being declared.
9538 /// \param IsDefinition Whether it is a definition or just a declarartion.
9539 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
9540 ///          nullptr if no attribute should be added.
9541 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9542                                                        bool IsDefinition) {
9543   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9544     return A;
9545   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9546       CodeSegStack.CurrentValue)
9547     return SectionAttr::CreateImplicit(
9548         getASTContext(), CodeSegStack.CurrentValue->getString(),
9549         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9550         SectionAttr::Declspec_allocate);
9551   return nullptr;
9552 }
9553 
9554 /// Determines if we can perform a correct type check for \p D as a
9555 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
9556 /// best-effort check.
9557 ///
9558 /// \param NewD The new declaration.
9559 /// \param OldD The old declaration.
9560 /// \param NewT The portion of the type of the new declaration to check.
9561 /// \param OldT The portion of the type of the old declaration to check.
9562 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
9563                                           QualType NewT, QualType OldT) {
9564   if (!NewD->getLexicalDeclContext()->isDependentContext())
9565     return true;
9566 
9567   // For dependently-typed local extern declarations and friends, we can't
9568   // perform a correct type check in general until instantiation:
9569   //
9570   //   int f();
9571   //   template<typename T> void g() { T f(); }
9572   //
9573   // (valid if g() is only instantiated with T = int).
9574   if (NewT->isDependentType() &&
9575       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
9576     return false;
9577 
9578   // Similarly, if the previous declaration was a dependent local extern
9579   // declaration, we don't really know its type yet.
9580   if (OldT->isDependentType() && OldD->isLocalExternDecl())
9581     return false;
9582 
9583   return true;
9584 }
9585 
9586 /// Checks if the new declaration declared in dependent context must be
9587 /// put in the same redeclaration chain as the specified declaration.
9588 ///
9589 /// \param D Declaration that is checked.
9590 /// \param PrevDecl Previous declaration found with proper lookup method for the
9591 ///                 same declaration name.
9592 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9593 ///          belongs to.
9594 ///
9595 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9596   if (!D->getLexicalDeclContext()->isDependentContext())
9597     return true;
9598 
9599   // Don't chain dependent friend function definitions until instantiation, to
9600   // permit cases like
9601   //
9602   //   void func();
9603   //   template<typename T> class C1 { friend void func() {} };
9604   //   template<typename T> class C2 { friend void func() {} };
9605   //
9606   // ... which is valid if only one of C1 and C2 is ever instantiated.
9607   //
9608   // FIXME: This need only apply to function definitions. For now, we proxy
9609   // this by checking for a file-scope function. We do not want this to apply
9610   // to friend declarations nominating member functions, because that gets in
9611   // the way of access checks.
9612   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
9613     return false;
9614 
9615   auto *VD = dyn_cast<ValueDecl>(D);
9616   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
9617   return !VD || !PrevVD ||
9618          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
9619                                         PrevVD->getType());
9620 }
9621 
9622 /// Check the target attribute of the function for MultiVersion
9623 /// validity.
9624 ///
9625 /// Returns true if there was an error, false otherwise.
9626 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9627   const auto *TA = FD->getAttr<TargetAttr>();
9628   assert(TA && "MultiVersion Candidate requires a target attribute");
9629   TargetAttr::ParsedTargetAttr ParseInfo = TA->parse();
9630   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9631   enum ErrType { Feature = 0, Architecture = 1 };
9632 
9633   if (!ParseInfo.Architecture.empty() &&
9634       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
9635     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9636         << Architecture << ParseInfo.Architecture;
9637     return true;
9638   }
9639 
9640   for (const auto &Feat : ParseInfo.Features) {
9641     auto BareFeat = StringRef{Feat}.substr(1);
9642     if (Feat[0] == '-') {
9643       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9644           << Feature << ("no-" + BareFeat).str();
9645       return true;
9646     }
9647 
9648     if (!TargetInfo.validateCpuSupports(BareFeat) ||
9649         !TargetInfo.isValidFeatureName(BareFeat)) {
9650       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9651           << Feature << BareFeat;
9652       return true;
9653     }
9654   }
9655   return false;
9656 }
9657 
9658 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD,
9659                                          MultiVersionKind MVType) {
9660   for (const Attr *A : FD->attrs()) {
9661     switch (A->getKind()) {
9662     case attr::CPUDispatch:
9663     case attr::CPUSpecific:
9664       if (MVType != MultiVersionKind::CPUDispatch &&
9665           MVType != MultiVersionKind::CPUSpecific)
9666         return true;
9667       break;
9668     case attr::Target:
9669       if (MVType != MultiVersionKind::Target)
9670         return true;
9671       break;
9672     default:
9673       return true;
9674     }
9675   }
9676   return false;
9677 }
9678 
9679 bool Sema::areMultiversionVariantFunctionsCompatible(
9680     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
9681     const PartialDiagnostic &NoProtoDiagID,
9682     const PartialDiagnosticAt &NoteCausedDiagIDAt,
9683     const PartialDiagnosticAt &NoSupportDiagIDAt,
9684     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
9685     bool ConstexprSupported) {
9686   enum DoesntSupport {
9687     FuncTemplates = 0,
9688     VirtFuncs = 1,
9689     DeducedReturn = 2,
9690     Constructors = 3,
9691     Destructors = 4,
9692     DeletedFuncs = 5,
9693     DefaultedFuncs = 6,
9694     ConstexprFuncs = 7,
9695     ConstevalFuncs = 8,
9696   };
9697   enum Different {
9698     CallingConv = 0,
9699     ReturnType = 1,
9700     ConstexprSpec = 2,
9701     InlineSpec = 3,
9702     StorageClass = 4,
9703     Linkage = 5,
9704   };
9705 
9706   if (OldFD && !OldFD->getType()->getAs<FunctionProtoType>()) {
9707     Diag(OldFD->getLocation(), NoProtoDiagID);
9708     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
9709     return true;
9710   }
9711 
9712   if (!NewFD->getType()->getAs<FunctionProtoType>())
9713     return Diag(NewFD->getLocation(), NoProtoDiagID);
9714 
9715   if (!TemplatesSupported &&
9716       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9717     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9718            << FuncTemplates;
9719 
9720   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
9721     if (NewCXXFD->isVirtual())
9722       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9723              << VirtFuncs;
9724 
9725     if (isa<CXXConstructorDecl>(NewCXXFD))
9726       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9727              << Constructors;
9728 
9729     if (isa<CXXDestructorDecl>(NewCXXFD))
9730       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9731              << Destructors;
9732   }
9733 
9734   if (NewFD->isDeleted())
9735     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9736            << DeletedFuncs;
9737 
9738   if (NewFD->isDefaulted())
9739     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9740            << DefaultedFuncs;
9741 
9742   if (!ConstexprSupported && NewFD->isConstexpr())
9743     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9744            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
9745 
9746   QualType NewQType = Context.getCanonicalType(NewFD->getType());
9747   const auto *NewType = cast<FunctionType>(NewQType);
9748   QualType NewReturnType = NewType->getReturnType();
9749 
9750   if (NewReturnType->isUndeducedType())
9751     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9752            << DeducedReturn;
9753 
9754   // Ensure the return type is identical.
9755   if (OldFD) {
9756     QualType OldQType = Context.getCanonicalType(OldFD->getType());
9757     const auto *OldType = cast<FunctionType>(OldQType);
9758     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
9759     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
9760 
9761     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
9762       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
9763 
9764     QualType OldReturnType = OldType->getReturnType();
9765 
9766     if (OldReturnType != NewReturnType)
9767       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
9768 
9769     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
9770       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
9771 
9772     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
9773       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
9774 
9775     if (OldFD->getStorageClass() != NewFD->getStorageClass())
9776       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass;
9777 
9778     if (OldFD->isExternC() != NewFD->isExternC())
9779       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
9780 
9781     if (CheckEquivalentExceptionSpec(
9782             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
9783             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
9784       return true;
9785   }
9786   return false;
9787 }
9788 
9789 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
9790                                              const FunctionDecl *NewFD,
9791                                              bool CausesMV,
9792                                              MultiVersionKind MVType) {
9793   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9794     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9795     if (OldFD)
9796       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9797     return true;
9798   }
9799 
9800   bool IsCPUSpecificCPUDispatchMVType =
9801       MVType == MultiVersionKind::CPUDispatch ||
9802       MVType == MultiVersionKind::CPUSpecific;
9803 
9804   // For now, disallow all other attributes.  These should be opt-in, but
9805   // an analysis of all of them is a future FIXME.
9806   if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) {
9807     S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
9808         << IsCPUSpecificCPUDispatchMVType;
9809     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9810     return true;
9811   }
9812 
9813   if (HasNonMultiVersionAttributes(NewFD, MVType))
9814     return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
9815            << IsCPUSpecificCPUDispatchMVType;
9816 
9817   // Only allow transition to MultiVersion if it hasn't been used.
9818   if (OldFD && CausesMV && OldFD->isUsed(false))
9819     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
9820 
9821   return S.areMultiversionVariantFunctionsCompatible(
9822       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
9823       PartialDiagnosticAt(NewFD->getLocation(),
9824                           S.PDiag(diag::note_multiversioning_caused_here)),
9825       PartialDiagnosticAt(NewFD->getLocation(),
9826                           S.PDiag(diag::err_multiversion_doesnt_support)
9827                               << IsCPUSpecificCPUDispatchMVType),
9828       PartialDiagnosticAt(NewFD->getLocation(),
9829                           S.PDiag(diag::err_multiversion_diff)),
9830       /*TemplatesSupported=*/false,
9831       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType);
9832 }
9833 
9834 /// Check the validity of a multiversion function declaration that is the
9835 /// first of its kind. Also sets the multiversion'ness' of the function itself.
9836 ///
9837 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9838 ///
9839 /// Returns true if there was an error, false otherwise.
9840 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
9841                                            MultiVersionKind MVType,
9842                                            const TargetAttr *TA) {
9843   assert(MVType != MultiVersionKind::None &&
9844          "Function lacks multiversion attribute");
9845 
9846   // Target only causes MV if it is default, otherwise this is a normal
9847   // function.
9848   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
9849     return false;
9850 
9851   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
9852     FD->setInvalidDecl();
9853     return true;
9854   }
9855 
9856   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
9857     FD->setInvalidDecl();
9858     return true;
9859   }
9860 
9861   FD->setIsMultiVersion();
9862   return false;
9863 }
9864 
9865 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
9866   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
9867     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
9868       return true;
9869   }
9870 
9871   return false;
9872 }
9873 
9874 static bool CheckTargetCausesMultiVersioning(
9875     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
9876     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
9877     LookupResult &Previous) {
9878   const auto *OldTA = OldFD->getAttr<TargetAttr>();
9879   TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse();
9880   // Sort order doesn't matter, it just needs to be consistent.
9881   llvm::sort(NewParsed.Features);
9882 
9883   // If the old decl is NOT MultiVersioned yet, and we don't cause that
9884   // to change, this is a simple redeclaration.
9885   if (!NewTA->isDefaultVersion() &&
9886       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
9887     return false;
9888 
9889   // Otherwise, this decl causes MultiVersioning.
9890   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9891     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9892     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9893     NewFD->setInvalidDecl();
9894     return true;
9895   }
9896 
9897   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
9898                                        MultiVersionKind::Target)) {
9899     NewFD->setInvalidDecl();
9900     return true;
9901   }
9902 
9903   if (CheckMultiVersionValue(S, NewFD)) {
9904     NewFD->setInvalidDecl();
9905     return true;
9906   }
9907 
9908   // If this is 'default', permit the forward declaration.
9909   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
9910     Redeclaration = true;
9911     OldDecl = OldFD;
9912     OldFD->setIsMultiVersion();
9913     NewFD->setIsMultiVersion();
9914     return false;
9915   }
9916 
9917   if (CheckMultiVersionValue(S, OldFD)) {
9918     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9919     NewFD->setInvalidDecl();
9920     return true;
9921   }
9922 
9923   TargetAttr::ParsedTargetAttr OldParsed =
9924       OldTA->parse(std::less<std::string>());
9925 
9926   if (OldParsed == NewParsed) {
9927     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9928     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9929     NewFD->setInvalidDecl();
9930     return true;
9931   }
9932 
9933   for (const auto *FD : OldFD->redecls()) {
9934     const auto *CurTA = FD->getAttr<TargetAttr>();
9935     // We allow forward declarations before ANY multiversioning attributes, but
9936     // nothing after the fact.
9937     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
9938         (!CurTA || CurTA->isInherited())) {
9939       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
9940           << 0;
9941       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9942       NewFD->setInvalidDecl();
9943       return true;
9944     }
9945   }
9946 
9947   OldFD->setIsMultiVersion();
9948   NewFD->setIsMultiVersion();
9949   Redeclaration = false;
9950   MergeTypeWithPrevious = false;
9951   OldDecl = nullptr;
9952   Previous.clear();
9953   return false;
9954 }
9955 
9956 /// Check the validity of a new function declaration being added to an existing
9957 /// multiversioned declaration collection.
9958 static bool CheckMultiVersionAdditionalDecl(
9959     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
9960     MultiVersionKind NewMVType, const TargetAttr *NewTA,
9961     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
9962     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
9963     LookupResult &Previous) {
9964 
9965   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
9966   // Disallow mixing of multiversioning types.
9967   if ((OldMVType == MultiVersionKind::Target &&
9968        NewMVType != MultiVersionKind::Target) ||
9969       (NewMVType == MultiVersionKind::Target &&
9970        OldMVType != MultiVersionKind::Target)) {
9971     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
9972     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9973     NewFD->setInvalidDecl();
9974     return true;
9975   }
9976 
9977   TargetAttr::ParsedTargetAttr NewParsed;
9978   if (NewTA) {
9979     NewParsed = NewTA->parse();
9980     llvm::sort(NewParsed.Features);
9981   }
9982 
9983   bool UseMemberUsingDeclRules =
9984       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
9985 
9986   // Next, check ALL non-overloads to see if this is a redeclaration of a
9987   // previous member of the MultiVersion set.
9988   for (NamedDecl *ND : Previous) {
9989     FunctionDecl *CurFD = ND->getAsFunction();
9990     if (!CurFD)
9991       continue;
9992     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
9993       continue;
9994 
9995     if (NewMVType == MultiVersionKind::Target) {
9996       const auto *CurTA = CurFD->getAttr<TargetAttr>();
9997       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
9998         NewFD->setIsMultiVersion();
9999         Redeclaration = true;
10000         OldDecl = ND;
10001         return false;
10002       }
10003 
10004       TargetAttr::ParsedTargetAttr CurParsed =
10005           CurTA->parse(std::less<std::string>());
10006       if (CurParsed == NewParsed) {
10007         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10008         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10009         NewFD->setInvalidDecl();
10010         return true;
10011       }
10012     } else {
10013       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10014       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10015       // Handle CPUDispatch/CPUSpecific versions.
10016       // Only 1 CPUDispatch function is allowed, this will make it go through
10017       // the redeclaration errors.
10018       if (NewMVType == MultiVersionKind::CPUDispatch &&
10019           CurFD->hasAttr<CPUDispatchAttr>()) {
10020         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10021             std::equal(
10022                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10023                 NewCPUDisp->cpus_begin(),
10024                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10025                   return Cur->getName() == New->getName();
10026                 })) {
10027           NewFD->setIsMultiVersion();
10028           Redeclaration = true;
10029           OldDecl = ND;
10030           return false;
10031         }
10032 
10033         // If the declarations don't match, this is an error condition.
10034         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10035         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10036         NewFD->setInvalidDecl();
10037         return true;
10038       }
10039       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10040 
10041         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10042             std::equal(
10043                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10044                 NewCPUSpec->cpus_begin(),
10045                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10046                   return Cur->getName() == New->getName();
10047                 })) {
10048           NewFD->setIsMultiVersion();
10049           Redeclaration = true;
10050           OldDecl = ND;
10051           return false;
10052         }
10053 
10054         // Only 1 version of CPUSpecific is allowed for each CPU.
10055         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10056           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10057             if (CurII == NewII) {
10058               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10059                   << NewII;
10060               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10061               NewFD->setInvalidDecl();
10062               return true;
10063             }
10064           }
10065         }
10066       }
10067       // If the two decls aren't the same MVType, there is no possible error
10068       // condition.
10069     }
10070   }
10071 
10072   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10073   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10074   // handled in the attribute adding step.
10075   if (NewMVType == MultiVersionKind::Target &&
10076       CheckMultiVersionValue(S, NewFD)) {
10077     NewFD->setInvalidDecl();
10078     return true;
10079   }
10080 
10081   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10082                                        !OldFD->isMultiVersion(), NewMVType)) {
10083     NewFD->setInvalidDecl();
10084     return true;
10085   }
10086 
10087   // Permit forward declarations in the case where these two are compatible.
10088   if (!OldFD->isMultiVersion()) {
10089     OldFD->setIsMultiVersion();
10090     NewFD->setIsMultiVersion();
10091     Redeclaration = true;
10092     OldDecl = OldFD;
10093     return false;
10094   }
10095 
10096   NewFD->setIsMultiVersion();
10097   Redeclaration = false;
10098   MergeTypeWithPrevious = false;
10099   OldDecl = nullptr;
10100   Previous.clear();
10101   return false;
10102 }
10103 
10104 
10105 /// Check the validity of a mulitversion function declaration.
10106 /// Also sets the multiversion'ness' of the function itself.
10107 ///
10108 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10109 ///
10110 /// Returns true if there was an error, false otherwise.
10111 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10112                                       bool &Redeclaration, NamedDecl *&OldDecl,
10113                                       bool &MergeTypeWithPrevious,
10114                                       LookupResult &Previous) {
10115   const auto *NewTA = NewFD->getAttr<TargetAttr>();
10116   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10117   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10118 
10119   // Mixing Multiversioning types is prohibited.
10120   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
10121       (NewCPUDisp && NewCPUSpec)) {
10122     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10123     NewFD->setInvalidDecl();
10124     return true;
10125   }
10126 
10127   MultiVersionKind  MVType = NewFD->getMultiVersionKind();
10128 
10129   // Main isn't allowed to become a multiversion function, however it IS
10130   // permitted to have 'main' be marked with the 'target' optimization hint.
10131   if (NewFD->isMain()) {
10132     if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10133         MVType == MultiVersionKind::CPUDispatch ||
10134         MVType == MultiVersionKind::CPUSpecific) {
10135       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10136       NewFD->setInvalidDecl();
10137       return true;
10138     }
10139     return false;
10140   }
10141 
10142   if (!OldDecl || !OldDecl->getAsFunction() ||
10143       OldDecl->getDeclContext()->getRedeclContext() !=
10144           NewFD->getDeclContext()->getRedeclContext()) {
10145     // If there's no previous declaration, AND this isn't attempting to cause
10146     // multiversioning, this isn't an error condition.
10147     if (MVType == MultiVersionKind::None)
10148       return false;
10149     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10150   }
10151 
10152   FunctionDecl *OldFD = OldDecl->getAsFunction();
10153 
10154   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10155     return false;
10156 
10157   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10158     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10159         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10160     NewFD->setInvalidDecl();
10161     return true;
10162   }
10163 
10164   // Handle the target potentially causes multiversioning case.
10165   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10166     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10167                                             Redeclaration, OldDecl,
10168                                             MergeTypeWithPrevious, Previous);
10169 
10170   // At this point, we have a multiversion function decl (in OldFD) AND an
10171   // appropriate attribute in the current function decl.  Resolve that these are
10172   // still compatible with previous declarations.
10173   return CheckMultiVersionAdditionalDecl(
10174       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10175       OldDecl, MergeTypeWithPrevious, Previous);
10176 }
10177 
10178 /// Perform semantic checking of a new function declaration.
10179 ///
10180 /// Performs semantic analysis of the new function declaration
10181 /// NewFD. This routine performs all semantic checking that does not
10182 /// require the actual declarator involved in the declaration, and is
10183 /// used both for the declaration of functions as they are parsed
10184 /// (called via ActOnDeclarator) and for the declaration of functions
10185 /// that have been instantiated via C++ template instantiation (called
10186 /// via InstantiateDecl).
10187 ///
10188 /// \param IsMemberSpecialization whether this new function declaration is
10189 /// a member specialization (that replaces any definition provided by the
10190 /// previous declaration).
10191 ///
10192 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10193 ///
10194 /// \returns true if the function declaration is a redeclaration.
10195 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10196                                     LookupResult &Previous,
10197                                     bool IsMemberSpecialization) {
10198   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10199          "Variably modified return types are not handled here");
10200 
10201   // Determine whether the type of this function should be merged with
10202   // a previous visible declaration. This never happens for functions in C++,
10203   // and always happens in C if the previous declaration was visible.
10204   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10205                                !Previous.isShadowed();
10206 
10207   bool Redeclaration = false;
10208   NamedDecl *OldDecl = nullptr;
10209   bool MayNeedOverloadableChecks = false;
10210 
10211   // Merge or overload the declaration with an existing declaration of
10212   // the same name, if appropriate.
10213   if (!Previous.empty()) {
10214     // Determine whether NewFD is an overload of PrevDecl or
10215     // a declaration that requires merging. If it's an overload,
10216     // there's no more work to do here; we'll just add the new
10217     // function to the scope.
10218     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10219       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10220       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10221         Redeclaration = true;
10222         OldDecl = Candidate;
10223       }
10224     } else {
10225       MayNeedOverloadableChecks = true;
10226       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10227                             /*NewIsUsingDecl*/ false)) {
10228       case Ovl_Match:
10229         Redeclaration = true;
10230         break;
10231 
10232       case Ovl_NonFunction:
10233         Redeclaration = true;
10234         break;
10235 
10236       case Ovl_Overload:
10237         Redeclaration = false;
10238         break;
10239       }
10240     }
10241   }
10242 
10243   // Check for a previous extern "C" declaration with this name.
10244   if (!Redeclaration &&
10245       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10246     if (!Previous.empty()) {
10247       // This is an extern "C" declaration with the same name as a previous
10248       // declaration, and thus redeclares that entity...
10249       Redeclaration = true;
10250       OldDecl = Previous.getFoundDecl();
10251       MergeTypeWithPrevious = false;
10252 
10253       // ... except in the presence of __attribute__((overloadable)).
10254       if (OldDecl->hasAttr<OverloadableAttr>() ||
10255           NewFD->hasAttr<OverloadableAttr>()) {
10256         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10257           MayNeedOverloadableChecks = true;
10258           Redeclaration = false;
10259           OldDecl = nullptr;
10260         }
10261       }
10262     }
10263   }
10264 
10265   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10266                                 MergeTypeWithPrevious, Previous))
10267     return Redeclaration;
10268 
10269   // C++11 [dcl.constexpr]p8:
10270   //   A constexpr specifier for a non-static member function that is not
10271   //   a constructor declares that member function to be const.
10272   //
10273   // This needs to be delayed until we know whether this is an out-of-line
10274   // definition of a static member function.
10275   //
10276   // This rule is not present in C++1y, so we produce a backwards
10277   // compatibility warning whenever it happens in C++11.
10278   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10279   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10280       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10281       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10282     CXXMethodDecl *OldMD = nullptr;
10283     if (OldDecl)
10284       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10285     if (!OldMD || !OldMD->isStatic()) {
10286       const FunctionProtoType *FPT =
10287         MD->getType()->castAs<FunctionProtoType>();
10288       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10289       EPI.TypeQuals.addConst();
10290       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10291                                           FPT->getParamTypes(), EPI));
10292 
10293       // Warn that we did this, if we're not performing template instantiation.
10294       // In that case, we'll have warned already when the template was defined.
10295       if (!inTemplateInstantiation()) {
10296         SourceLocation AddConstLoc;
10297         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10298                 .IgnoreParens().getAs<FunctionTypeLoc>())
10299           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10300 
10301         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10302           << FixItHint::CreateInsertion(AddConstLoc, " const");
10303       }
10304     }
10305   }
10306 
10307   if (Redeclaration) {
10308     // NewFD and OldDecl represent declarations that need to be
10309     // merged.
10310     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10311       NewFD->setInvalidDecl();
10312       return Redeclaration;
10313     }
10314 
10315     Previous.clear();
10316     Previous.addDecl(OldDecl);
10317 
10318     if (FunctionTemplateDecl *OldTemplateDecl =
10319             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10320       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10321       FunctionTemplateDecl *NewTemplateDecl
10322         = NewFD->getDescribedFunctionTemplate();
10323       assert(NewTemplateDecl && "Template/non-template mismatch");
10324 
10325       // The call to MergeFunctionDecl above may have created some state in
10326       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10327       // can add it as a redeclaration.
10328       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10329 
10330       NewFD->setPreviousDeclaration(OldFD);
10331       adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10332       if (NewFD->isCXXClassMember()) {
10333         NewFD->setAccess(OldTemplateDecl->getAccess());
10334         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10335       }
10336 
10337       // If this is an explicit specialization of a member that is a function
10338       // template, mark it as a member specialization.
10339       if (IsMemberSpecialization &&
10340           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10341         NewTemplateDecl->setMemberSpecialization();
10342         assert(OldTemplateDecl->isMemberSpecialization());
10343         // Explicit specializations of a member template do not inherit deleted
10344         // status from the parent member template that they are specializing.
10345         if (OldFD->isDeleted()) {
10346           // FIXME: This assert will not hold in the presence of modules.
10347           assert(OldFD->getCanonicalDecl() == OldFD);
10348           // FIXME: We need an update record for this AST mutation.
10349           OldFD->setDeletedAsWritten(false);
10350         }
10351       }
10352 
10353     } else {
10354       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10355         auto *OldFD = cast<FunctionDecl>(OldDecl);
10356         // This needs to happen first so that 'inline' propagates.
10357         NewFD->setPreviousDeclaration(OldFD);
10358         adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10359         if (NewFD->isCXXClassMember())
10360           NewFD->setAccess(OldFD->getAccess());
10361       }
10362     }
10363   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10364              !NewFD->getAttr<OverloadableAttr>()) {
10365     assert((Previous.empty() ||
10366             llvm::any_of(Previous,
10367                          [](const NamedDecl *ND) {
10368                            return ND->hasAttr<OverloadableAttr>();
10369                          })) &&
10370            "Non-redecls shouldn't happen without overloadable present");
10371 
10372     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10373       const auto *FD = dyn_cast<FunctionDecl>(ND);
10374       return FD && !FD->hasAttr<OverloadableAttr>();
10375     });
10376 
10377     if (OtherUnmarkedIter != Previous.end()) {
10378       Diag(NewFD->getLocation(),
10379            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10380       Diag((*OtherUnmarkedIter)->getLocation(),
10381            diag::note_attribute_overloadable_prev_overload)
10382           << false;
10383 
10384       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10385     }
10386   }
10387 
10388   // Semantic checking for this function declaration (in isolation).
10389 
10390   if (getLangOpts().CPlusPlus) {
10391     // C++-specific checks.
10392     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10393       CheckConstructor(Constructor);
10394     } else if (CXXDestructorDecl *Destructor =
10395                 dyn_cast<CXXDestructorDecl>(NewFD)) {
10396       CXXRecordDecl *Record = Destructor->getParent();
10397       QualType ClassType = Context.getTypeDeclType(Record);
10398 
10399       // FIXME: Shouldn't we be able to perform this check even when the class
10400       // type is dependent? Both gcc and edg can handle that.
10401       if (!ClassType->isDependentType()) {
10402         DeclarationName Name
10403           = Context.DeclarationNames.getCXXDestructorName(
10404                                         Context.getCanonicalType(ClassType));
10405         if (NewFD->getDeclName() != Name) {
10406           Diag(NewFD->getLocation(), diag::err_destructor_name);
10407           NewFD->setInvalidDecl();
10408           return Redeclaration;
10409         }
10410       }
10411     } else if (CXXConversionDecl *Conversion
10412                = dyn_cast<CXXConversionDecl>(NewFD)) {
10413       ActOnConversionDeclarator(Conversion);
10414     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10415       if (auto *TD = Guide->getDescribedFunctionTemplate())
10416         CheckDeductionGuideTemplate(TD);
10417 
10418       // A deduction guide is not on the list of entities that can be
10419       // explicitly specialized.
10420       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10421         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10422             << /*explicit specialization*/ 1;
10423     }
10424 
10425     // Find any virtual functions that this function overrides.
10426     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10427       if (!Method->isFunctionTemplateSpecialization() &&
10428           !Method->getDescribedFunctionTemplate() &&
10429           Method->isCanonicalDecl()) {
10430         if (AddOverriddenMethods(Method->getParent(), Method)) {
10431           // If the function was marked as "static", we have a problem.
10432           if (NewFD->getStorageClass() == SC_Static) {
10433             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
10434           }
10435         }
10436       }
10437 
10438       if (Method->isStatic())
10439         checkThisInStaticMemberFunctionType(Method);
10440     }
10441 
10442     // Extra checking for C++ overloaded operators (C++ [over.oper]).
10443     if (NewFD->isOverloadedOperator() &&
10444         CheckOverloadedOperatorDeclaration(NewFD)) {
10445       NewFD->setInvalidDecl();
10446       return Redeclaration;
10447     }
10448 
10449     // Extra checking for C++0x literal operators (C++0x [over.literal]).
10450     if (NewFD->getLiteralIdentifier() &&
10451         CheckLiteralOperatorDeclaration(NewFD)) {
10452       NewFD->setInvalidDecl();
10453       return Redeclaration;
10454     }
10455 
10456     // In C++, check default arguments now that we have merged decls. Unless
10457     // the lexical context is the class, because in this case this is done
10458     // during delayed parsing anyway.
10459     if (!CurContext->isRecord())
10460       CheckCXXDefaultArguments(NewFD);
10461 
10462     // If this function declares a builtin function, check the type of this
10463     // declaration against the expected type for the builtin.
10464     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10465       ASTContext::GetBuiltinTypeError Error;
10466       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
10467       QualType T = Context.GetBuiltinType(BuiltinID, Error);
10468       // If the type of the builtin differs only in its exception
10469       // specification, that's OK.
10470       // FIXME: If the types do differ in this way, it would be better to
10471       // retain the 'noexcept' form of the type.
10472       if (!T.isNull() &&
10473           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10474                                                             NewFD->getType()))
10475         // The type of this function differs from the type of the builtin,
10476         // so forget about the builtin entirely.
10477         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10478     }
10479 
10480     // If this function is declared as being extern "C", then check to see if
10481     // the function returns a UDT (class, struct, or union type) that is not C
10482     // compatible, and if it does, warn the user.
10483     // But, issue any diagnostic on the first declaration only.
10484     if (Previous.empty() && NewFD->isExternC()) {
10485       QualType R = NewFD->getReturnType();
10486       if (R->isIncompleteType() && !R->isVoidType())
10487         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10488             << NewFD << R;
10489       else if (!R.isPODType(Context) && !R->isVoidType() &&
10490                !R->isObjCObjectPointerType())
10491         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10492     }
10493 
10494     // C++1z [dcl.fct]p6:
10495     //   [...] whether the function has a non-throwing exception-specification
10496     //   [is] part of the function type
10497     //
10498     // This results in an ABI break between C++14 and C++17 for functions whose
10499     // declared type includes an exception-specification in a parameter or
10500     // return type. (Exception specifications on the function itself are OK in
10501     // most cases, and exception specifications are not permitted in most other
10502     // contexts where they could make it into a mangling.)
10503     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10504       auto HasNoexcept = [&](QualType T) -> bool {
10505         // Strip off declarator chunks that could be between us and a function
10506         // type. We don't need to look far, exception specifications are very
10507         // restricted prior to C++17.
10508         if (auto *RT = T->getAs<ReferenceType>())
10509           T = RT->getPointeeType();
10510         else if (T->isAnyPointerType())
10511           T = T->getPointeeType();
10512         else if (auto *MPT = T->getAs<MemberPointerType>())
10513           T = MPT->getPointeeType();
10514         if (auto *FPT = T->getAs<FunctionProtoType>())
10515           if (FPT->isNothrow())
10516             return true;
10517         return false;
10518       };
10519 
10520       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10521       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10522       for (QualType T : FPT->param_types())
10523         AnyNoexcept |= HasNoexcept(T);
10524       if (AnyNoexcept)
10525         Diag(NewFD->getLocation(),
10526              diag::warn_cxx17_compat_exception_spec_in_signature)
10527             << NewFD;
10528     }
10529 
10530     if (!Redeclaration && LangOpts.CUDA)
10531       checkCUDATargetOverload(NewFD, Previous);
10532   }
10533   return Redeclaration;
10534 }
10535 
10536 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10537   // C++11 [basic.start.main]p3:
10538   //   A program that [...] declares main to be inline, static or
10539   //   constexpr is ill-formed.
10540   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
10541   //   appear in a declaration of main.
10542   // static main is not an error under C99, but we should warn about it.
10543   // We accept _Noreturn main as an extension.
10544   if (FD->getStorageClass() == SC_Static)
10545     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10546          ? diag::err_static_main : diag::warn_static_main)
10547       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10548   if (FD->isInlineSpecified())
10549     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10550       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10551   if (DS.isNoreturnSpecified()) {
10552     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10553     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10554     Diag(NoreturnLoc, diag::ext_noreturn_main);
10555     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10556       << FixItHint::CreateRemoval(NoreturnRange);
10557   }
10558   if (FD->isConstexpr()) {
10559     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10560         << FD->isConsteval()
10561         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10562     FD->setConstexprKind(CSK_unspecified);
10563   }
10564 
10565   if (getLangOpts().OpenCL) {
10566     Diag(FD->getLocation(), diag::err_opencl_no_main)
10567         << FD->hasAttr<OpenCLKernelAttr>();
10568     FD->setInvalidDecl();
10569     return;
10570   }
10571 
10572   QualType T = FD->getType();
10573   assert(T->isFunctionType() && "function decl is not of function type");
10574   const FunctionType* FT = T->castAs<FunctionType>();
10575 
10576   // Set default calling convention for main()
10577   if (FT->getCallConv() != CC_C) {
10578     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10579     FD->setType(QualType(FT, 0));
10580     T = Context.getCanonicalType(FD->getType());
10581   }
10582 
10583   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10584     // In C with GNU extensions we allow main() to have non-integer return
10585     // type, but we should warn about the extension, and we disable the
10586     // implicit-return-zero rule.
10587 
10588     // GCC in C mode accepts qualified 'int'.
10589     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
10590       FD->setHasImplicitReturnZero(true);
10591     else {
10592       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
10593       SourceRange RTRange = FD->getReturnTypeSourceRange();
10594       if (RTRange.isValid())
10595         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
10596             << FixItHint::CreateReplacement(RTRange, "int");
10597     }
10598   } else {
10599     // In C and C++, main magically returns 0 if you fall off the end;
10600     // set the flag which tells us that.
10601     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
10602 
10603     // All the standards say that main() should return 'int'.
10604     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
10605       FD->setHasImplicitReturnZero(true);
10606     else {
10607       // Otherwise, this is just a flat-out error.
10608       SourceRange RTRange = FD->getReturnTypeSourceRange();
10609       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
10610           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
10611                                 : FixItHint());
10612       FD->setInvalidDecl(true);
10613     }
10614   }
10615 
10616   // Treat protoless main() as nullary.
10617   if (isa<FunctionNoProtoType>(FT)) return;
10618 
10619   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
10620   unsigned nparams = FTP->getNumParams();
10621   assert(FD->getNumParams() == nparams);
10622 
10623   bool HasExtraParameters = (nparams > 3);
10624 
10625   if (FTP->isVariadic()) {
10626     Diag(FD->getLocation(), diag::ext_variadic_main);
10627     // FIXME: if we had information about the location of the ellipsis, we
10628     // could add a FixIt hint to remove it as a parameter.
10629   }
10630 
10631   // Darwin passes an undocumented fourth argument of type char**.  If
10632   // other platforms start sprouting these, the logic below will start
10633   // getting shifty.
10634   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
10635     HasExtraParameters = false;
10636 
10637   if (HasExtraParameters) {
10638     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
10639     FD->setInvalidDecl(true);
10640     nparams = 3;
10641   }
10642 
10643   // FIXME: a lot of the following diagnostics would be improved
10644   // if we had some location information about types.
10645 
10646   QualType CharPP =
10647     Context.getPointerType(Context.getPointerType(Context.CharTy));
10648   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
10649 
10650   for (unsigned i = 0; i < nparams; ++i) {
10651     QualType AT = FTP->getParamType(i);
10652 
10653     bool mismatch = true;
10654 
10655     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
10656       mismatch = false;
10657     else if (Expected[i] == CharPP) {
10658       // As an extension, the following forms are okay:
10659       //   char const **
10660       //   char const * const *
10661       //   char * const *
10662 
10663       QualifierCollector qs;
10664       const PointerType* PT;
10665       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
10666           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
10667           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
10668                               Context.CharTy)) {
10669         qs.removeConst();
10670         mismatch = !qs.empty();
10671       }
10672     }
10673 
10674     if (mismatch) {
10675       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
10676       // TODO: suggest replacing given type with expected type
10677       FD->setInvalidDecl(true);
10678     }
10679   }
10680 
10681   if (nparams == 1 && !FD->isInvalidDecl()) {
10682     Diag(FD->getLocation(), diag::warn_main_one_arg);
10683   }
10684 
10685   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10686     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10687     FD->setInvalidDecl();
10688   }
10689 }
10690 
10691 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
10692   QualType T = FD->getType();
10693   assert(T->isFunctionType() && "function decl is not of function type");
10694   const FunctionType *FT = T->castAs<FunctionType>();
10695 
10696   // Set an implicit return of 'zero' if the function can return some integral,
10697   // enumeration, pointer or nullptr type.
10698   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
10699       FT->getReturnType()->isAnyPointerType() ||
10700       FT->getReturnType()->isNullPtrType())
10701     // DllMain is exempt because a return value of zero means it failed.
10702     if (FD->getName() != "DllMain")
10703       FD->setHasImplicitReturnZero(true);
10704 
10705   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10706     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10707     FD->setInvalidDecl();
10708   }
10709 }
10710 
10711 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
10712   // FIXME: Need strict checking.  In C89, we need to check for
10713   // any assignment, increment, decrement, function-calls, or
10714   // commas outside of a sizeof.  In C99, it's the same list,
10715   // except that the aforementioned are allowed in unevaluated
10716   // expressions.  Everything else falls under the
10717   // "may accept other forms of constant expressions" exception.
10718   // (We never end up here for C++, so the constant expression
10719   // rules there don't matter.)
10720   const Expr *Culprit;
10721   if (Init->isConstantInitializer(Context, false, &Culprit))
10722     return false;
10723   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
10724     << Culprit->getSourceRange();
10725   return true;
10726 }
10727 
10728 namespace {
10729   // Visits an initialization expression to see if OrigDecl is evaluated in
10730   // its own initialization and throws a warning if it does.
10731   class SelfReferenceChecker
10732       : public EvaluatedExprVisitor<SelfReferenceChecker> {
10733     Sema &S;
10734     Decl *OrigDecl;
10735     bool isRecordType;
10736     bool isPODType;
10737     bool isReferenceType;
10738 
10739     bool isInitList;
10740     llvm::SmallVector<unsigned, 4> InitFieldIndex;
10741 
10742   public:
10743     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
10744 
10745     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
10746                                                     S(S), OrigDecl(OrigDecl) {
10747       isPODType = false;
10748       isRecordType = false;
10749       isReferenceType = false;
10750       isInitList = false;
10751       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
10752         isPODType = VD->getType().isPODType(S.Context);
10753         isRecordType = VD->getType()->isRecordType();
10754         isReferenceType = VD->getType()->isReferenceType();
10755       }
10756     }
10757 
10758     // For most expressions, just call the visitor.  For initializer lists,
10759     // track the index of the field being initialized since fields are
10760     // initialized in order allowing use of previously initialized fields.
10761     void CheckExpr(Expr *E) {
10762       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
10763       if (!InitList) {
10764         Visit(E);
10765         return;
10766       }
10767 
10768       // Track and increment the index here.
10769       isInitList = true;
10770       InitFieldIndex.push_back(0);
10771       for (auto Child : InitList->children()) {
10772         CheckExpr(cast<Expr>(Child));
10773         ++InitFieldIndex.back();
10774       }
10775       InitFieldIndex.pop_back();
10776     }
10777 
10778     // Returns true if MemberExpr is checked and no further checking is needed.
10779     // Returns false if additional checking is required.
10780     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
10781       llvm::SmallVector<FieldDecl*, 4> Fields;
10782       Expr *Base = E;
10783       bool ReferenceField = false;
10784 
10785       // Get the field members used.
10786       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10787         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
10788         if (!FD)
10789           return false;
10790         Fields.push_back(FD);
10791         if (FD->getType()->isReferenceType())
10792           ReferenceField = true;
10793         Base = ME->getBase()->IgnoreParenImpCasts();
10794       }
10795 
10796       // Keep checking only if the base Decl is the same.
10797       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
10798       if (!DRE || DRE->getDecl() != OrigDecl)
10799         return false;
10800 
10801       // A reference field can be bound to an unininitialized field.
10802       if (CheckReference && !ReferenceField)
10803         return true;
10804 
10805       // Convert FieldDecls to their index number.
10806       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
10807       for (const FieldDecl *I : llvm::reverse(Fields))
10808         UsedFieldIndex.push_back(I->getFieldIndex());
10809 
10810       // See if a warning is needed by checking the first difference in index
10811       // numbers.  If field being used has index less than the field being
10812       // initialized, then the use is safe.
10813       for (auto UsedIter = UsedFieldIndex.begin(),
10814                 UsedEnd = UsedFieldIndex.end(),
10815                 OrigIter = InitFieldIndex.begin(),
10816                 OrigEnd = InitFieldIndex.end();
10817            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
10818         if (*UsedIter < *OrigIter)
10819           return true;
10820         if (*UsedIter > *OrigIter)
10821           break;
10822       }
10823 
10824       // TODO: Add a different warning which will print the field names.
10825       HandleDeclRefExpr(DRE);
10826       return true;
10827     }
10828 
10829     // For most expressions, the cast is directly above the DeclRefExpr.
10830     // For conditional operators, the cast can be outside the conditional
10831     // operator if both expressions are DeclRefExpr's.
10832     void HandleValue(Expr *E) {
10833       E = E->IgnoreParens();
10834       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
10835         HandleDeclRefExpr(DRE);
10836         return;
10837       }
10838 
10839       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
10840         Visit(CO->getCond());
10841         HandleValue(CO->getTrueExpr());
10842         HandleValue(CO->getFalseExpr());
10843         return;
10844       }
10845 
10846       if (BinaryConditionalOperator *BCO =
10847               dyn_cast<BinaryConditionalOperator>(E)) {
10848         Visit(BCO->getCond());
10849         HandleValue(BCO->getFalseExpr());
10850         return;
10851       }
10852 
10853       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
10854         HandleValue(OVE->getSourceExpr());
10855         return;
10856       }
10857 
10858       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10859         if (BO->getOpcode() == BO_Comma) {
10860           Visit(BO->getLHS());
10861           HandleValue(BO->getRHS());
10862           return;
10863         }
10864       }
10865 
10866       if (isa<MemberExpr>(E)) {
10867         if (isInitList) {
10868           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
10869                                       false /*CheckReference*/))
10870             return;
10871         }
10872 
10873         Expr *Base = E->IgnoreParenImpCasts();
10874         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10875           // Check for static member variables and don't warn on them.
10876           if (!isa<FieldDecl>(ME->getMemberDecl()))
10877             return;
10878           Base = ME->getBase()->IgnoreParenImpCasts();
10879         }
10880         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
10881           HandleDeclRefExpr(DRE);
10882         return;
10883       }
10884 
10885       Visit(E);
10886     }
10887 
10888     // Reference types not handled in HandleValue are handled here since all
10889     // uses of references are bad, not just r-value uses.
10890     void VisitDeclRefExpr(DeclRefExpr *E) {
10891       if (isReferenceType)
10892         HandleDeclRefExpr(E);
10893     }
10894 
10895     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
10896       if (E->getCastKind() == CK_LValueToRValue) {
10897         HandleValue(E->getSubExpr());
10898         return;
10899       }
10900 
10901       Inherited::VisitImplicitCastExpr(E);
10902     }
10903 
10904     void VisitMemberExpr(MemberExpr *E) {
10905       if (isInitList) {
10906         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
10907           return;
10908       }
10909 
10910       // Don't warn on arrays since they can be treated as pointers.
10911       if (E->getType()->canDecayToPointerType()) return;
10912 
10913       // Warn when a non-static method call is followed by non-static member
10914       // field accesses, which is followed by a DeclRefExpr.
10915       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
10916       bool Warn = (MD && !MD->isStatic());
10917       Expr *Base = E->getBase()->IgnoreParenImpCasts();
10918       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10919         if (!isa<FieldDecl>(ME->getMemberDecl()))
10920           Warn = false;
10921         Base = ME->getBase()->IgnoreParenImpCasts();
10922       }
10923 
10924       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
10925         if (Warn)
10926           HandleDeclRefExpr(DRE);
10927         return;
10928       }
10929 
10930       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
10931       // Visit that expression.
10932       Visit(Base);
10933     }
10934 
10935     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
10936       Expr *Callee = E->getCallee();
10937 
10938       if (isa<UnresolvedLookupExpr>(Callee))
10939         return Inherited::VisitCXXOperatorCallExpr(E);
10940 
10941       Visit(Callee);
10942       for (auto Arg: E->arguments())
10943         HandleValue(Arg->IgnoreParenImpCasts());
10944     }
10945 
10946     void VisitUnaryOperator(UnaryOperator *E) {
10947       // For POD record types, addresses of its own members are well-defined.
10948       if (E->getOpcode() == UO_AddrOf && isRecordType &&
10949           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
10950         if (!isPODType)
10951           HandleValue(E->getSubExpr());
10952         return;
10953       }
10954 
10955       if (E->isIncrementDecrementOp()) {
10956         HandleValue(E->getSubExpr());
10957         return;
10958       }
10959 
10960       Inherited::VisitUnaryOperator(E);
10961     }
10962 
10963     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
10964 
10965     void VisitCXXConstructExpr(CXXConstructExpr *E) {
10966       if (E->getConstructor()->isCopyConstructor()) {
10967         Expr *ArgExpr = E->getArg(0);
10968         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
10969           if (ILE->getNumInits() == 1)
10970             ArgExpr = ILE->getInit(0);
10971         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
10972           if (ICE->getCastKind() == CK_NoOp)
10973             ArgExpr = ICE->getSubExpr();
10974         HandleValue(ArgExpr);
10975         return;
10976       }
10977       Inherited::VisitCXXConstructExpr(E);
10978     }
10979 
10980     void VisitCallExpr(CallExpr *E) {
10981       // Treat std::move as a use.
10982       if (E->isCallToStdMove()) {
10983         HandleValue(E->getArg(0));
10984         return;
10985       }
10986 
10987       Inherited::VisitCallExpr(E);
10988     }
10989 
10990     void VisitBinaryOperator(BinaryOperator *E) {
10991       if (E->isCompoundAssignmentOp()) {
10992         HandleValue(E->getLHS());
10993         Visit(E->getRHS());
10994         return;
10995       }
10996 
10997       Inherited::VisitBinaryOperator(E);
10998     }
10999 
11000     // A custom visitor for BinaryConditionalOperator is needed because the
11001     // regular visitor would check the condition and true expression separately
11002     // but both point to the same place giving duplicate diagnostics.
11003     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11004       Visit(E->getCond());
11005       Visit(E->getFalseExpr());
11006     }
11007 
11008     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11009       Decl* ReferenceDecl = DRE->getDecl();
11010       if (OrigDecl != ReferenceDecl) return;
11011       unsigned diag;
11012       if (isReferenceType) {
11013         diag = diag::warn_uninit_self_reference_in_reference_init;
11014       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11015         diag = diag::warn_static_self_reference_in_init;
11016       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11017                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11018                  DRE->getDecl()->getType()->isRecordType()) {
11019         diag = diag::warn_uninit_self_reference_in_init;
11020       } else {
11021         // Local variables will be handled by the CFG analysis.
11022         return;
11023       }
11024 
11025       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11026                             S.PDiag(diag)
11027                                 << DRE->getDecl() << OrigDecl->getLocation()
11028                                 << DRE->getSourceRange());
11029     }
11030   };
11031 
11032   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11033   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11034                                  bool DirectInit) {
11035     // Parameters arguments are occassionially constructed with itself,
11036     // for instance, in recursive functions.  Skip them.
11037     if (isa<ParmVarDecl>(OrigDecl))
11038       return;
11039 
11040     E = E->IgnoreParens();
11041 
11042     // Skip checking T a = a where T is not a record or reference type.
11043     // Doing so is a way to silence uninitialized warnings.
11044     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11045       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11046         if (ICE->getCastKind() == CK_LValueToRValue)
11047           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11048             if (DRE->getDecl() == OrigDecl)
11049               return;
11050 
11051     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11052   }
11053 } // end anonymous namespace
11054 
11055 namespace {
11056   // Simple wrapper to add the name of a variable or (if no variable is
11057   // available) a DeclarationName into a diagnostic.
11058   struct VarDeclOrName {
11059     VarDecl *VDecl;
11060     DeclarationName Name;
11061 
11062     friend const Sema::SemaDiagnosticBuilder &
11063     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11064       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11065     }
11066   };
11067 } // end anonymous namespace
11068 
11069 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11070                                             DeclarationName Name, QualType Type,
11071                                             TypeSourceInfo *TSI,
11072                                             SourceRange Range, bool DirectInit,
11073                                             Expr *Init) {
11074   bool IsInitCapture = !VDecl;
11075   assert((!VDecl || !VDecl->isInitCapture()) &&
11076          "init captures are expected to be deduced prior to initialization");
11077 
11078   VarDeclOrName VN{VDecl, Name};
11079 
11080   DeducedType *Deduced = Type->getContainedDeducedType();
11081   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11082 
11083   // C++11 [dcl.spec.auto]p3
11084   if (!Init) {
11085     assert(VDecl && "no init for init capture deduction?");
11086 
11087     // Except for class argument deduction, and then for an initializing
11088     // declaration only, i.e. no static at class scope or extern.
11089     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11090         VDecl->hasExternalStorage() ||
11091         VDecl->isStaticDataMember()) {
11092       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11093         << VDecl->getDeclName() << Type;
11094       return QualType();
11095     }
11096   }
11097 
11098   ArrayRef<Expr*> DeduceInits;
11099   if (Init)
11100     DeduceInits = Init;
11101 
11102   if (DirectInit) {
11103     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11104       DeduceInits = PL->exprs();
11105   }
11106 
11107   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11108     assert(VDecl && "non-auto type for init capture deduction?");
11109     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11110     InitializationKind Kind = InitializationKind::CreateForInit(
11111         VDecl->getLocation(), DirectInit, Init);
11112     // FIXME: Initialization should not be taking a mutable list of inits.
11113     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11114     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11115                                                        InitsCopy);
11116   }
11117 
11118   if (DirectInit) {
11119     if (auto *IL = dyn_cast<InitListExpr>(Init))
11120       DeduceInits = IL->inits();
11121   }
11122 
11123   // Deduction only works if we have exactly one source expression.
11124   if (DeduceInits.empty()) {
11125     // It isn't possible to write this directly, but it is possible to
11126     // end up in this situation with "auto x(some_pack...);"
11127     Diag(Init->getBeginLoc(), IsInitCapture
11128                                   ? diag::err_init_capture_no_expression
11129                                   : diag::err_auto_var_init_no_expression)
11130         << VN << Type << Range;
11131     return QualType();
11132   }
11133 
11134   if (DeduceInits.size() > 1) {
11135     Diag(DeduceInits[1]->getBeginLoc(),
11136          IsInitCapture ? diag::err_init_capture_multiple_expressions
11137                        : diag::err_auto_var_init_multiple_expressions)
11138         << VN << Type << Range;
11139     return QualType();
11140   }
11141 
11142   Expr *DeduceInit = DeduceInits[0];
11143   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11144     Diag(Init->getBeginLoc(), IsInitCapture
11145                                   ? diag::err_init_capture_paren_braces
11146                                   : diag::err_auto_var_init_paren_braces)
11147         << isa<InitListExpr>(Init) << VN << Type << Range;
11148     return QualType();
11149   }
11150 
11151   // Expressions default to 'id' when we're in a debugger.
11152   bool DefaultedAnyToId = false;
11153   if (getLangOpts().DebuggerCastResultToId &&
11154       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11155     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11156     if (Result.isInvalid()) {
11157       return QualType();
11158     }
11159     Init = Result.get();
11160     DefaultedAnyToId = true;
11161   }
11162 
11163   // C++ [dcl.decomp]p1:
11164   //   If the assignment-expression [...] has array type A and no ref-qualifier
11165   //   is present, e has type cv A
11166   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11167       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11168       DeduceInit->getType()->isConstantArrayType())
11169     return Context.getQualifiedType(DeduceInit->getType(),
11170                                     Type.getQualifiers());
11171 
11172   QualType DeducedType;
11173   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11174     if (!IsInitCapture)
11175       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11176     else if (isa<InitListExpr>(Init))
11177       Diag(Range.getBegin(),
11178            diag::err_init_capture_deduction_failure_from_init_list)
11179           << VN
11180           << (DeduceInit->getType().isNull() ? TSI->getType()
11181                                              : DeduceInit->getType())
11182           << DeduceInit->getSourceRange();
11183     else
11184       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11185           << VN << TSI->getType()
11186           << (DeduceInit->getType().isNull() ? TSI->getType()
11187                                              : DeduceInit->getType())
11188           << DeduceInit->getSourceRange();
11189   }
11190 
11191   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11192   // 'id' instead of a specific object type prevents most of our usual
11193   // checks.
11194   // We only want to warn outside of template instantiations, though:
11195   // inside a template, the 'id' could have come from a parameter.
11196   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11197       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11198     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11199     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11200   }
11201 
11202   return DeducedType;
11203 }
11204 
11205 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11206                                          Expr *Init) {
11207   QualType DeducedType = deduceVarTypeFromInitializer(
11208       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11209       VDecl->getSourceRange(), DirectInit, Init);
11210   if (DeducedType.isNull()) {
11211     VDecl->setInvalidDecl();
11212     return true;
11213   }
11214 
11215   VDecl->setType(DeducedType);
11216   assert(VDecl->isLinkageValid());
11217 
11218   // In ARC, infer lifetime.
11219   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11220     VDecl->setInvalidDecl();
11221 
11222   // If this is a redeclaration, check that the type we just deduced matches
11223   // the previously declared type.
11224   if (VarDecl *Old = VDecl->getPreviousDecl()) {
11225     // We never need to merge the type, because we cannot form an incomplete
11226     // array of auto, nor deduce such a type.
11227     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11228   }
11229 
11230   // Check the deduced type is valid for a variable declaration.
11231   CheckVariableDeclarationType(VDecl);
11232   return VDecl->isInvalidDecl();
11233 }
11234 
11235 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11236                                               SourceLocation Loc) {
11237   if (auto *CE = dyn_cast<ConstantExpr>(Init))
11238     Init = CE->getSubExpr();
11239 
11240   QualType InitType = Init->getType();
11241   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11242           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
11243          "shouldn't be called if type doesn't have a non-trivial C struct");
11244   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11245     for (auto I : ILE->inits()) {
11246       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11247           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11248         continue;
11249       SourceLocation SL = I->getExprLoc();
11250       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11251     }
11252     return;
11253   }
11254 
11255   if (isa<ImplicitValueInitExpr>(Init)) {
11256     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11257       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11258                             NTCUK_Init);
11259   } else {
11260     // Assume all other explicit initializers involving copying some existing
11261     // object.
11262     // TODO: ignore any explicit initializers where we can guarantee
11263     // copy-elision.
11264     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11265       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11266   }
11267 }
11268 
11269 namespace {
11270 
11271 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11272   // Ignore unavailable fields. A field can be marked as unavailable explicitly
11273   // in the source code or implicitly by the compiler if it is in a union
11274   // defined in a system header and has non-trivial ObjC ownership
11275   // qualifications. We don't want those fields to participate in determining
11276   // whether the containing union is non-trivial.
11277   return FD->hasAttr<UnavailableAttr>();
11278 }
11279 
11280 struct DiagNonTrivalCUnionDefaultInitializeVisitor
11281     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11282                                     void> {
11283   using Super =
11284       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11285                                     void>;
11286 
11287   DiagNonTrivalCUnionDefaultInitializeVisitor(
11288       QualType OrigTy, SourceLocation OrigLoc,
11289       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11290       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11291 
11292   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11293                      const FieldDecl *FD, bool InNonTrivialUnion) {
11294     if (const auto *AT = S.Context.getAsArrayType(QT))
11295       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11296                                      InNonTrivialUnion);
11297     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11298   }
11299 
11300   void visitARCStrong(QualType QT, const FieldDecl *FD,
11301                       bool InNonTrivialUnion) {
11302     if (InNonTrivialUnion)
11303       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11304           << 1 << 0 << QT << FD->getName();
11305   }
11306 
11307   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11308     if (InNonTrivialUnion)
11309       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11310           << 1 << 0 << QT << FD->getName();
11311   }
11312 
11313   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11314     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11315     if (RD->isUnion()) {
11316       if (OrigLoc.isValid()) {
11317         bool IsUnion = false;
11318         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11319           IsUnion = OrigRD->isUnion();
11320         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11321             << 0 << OrigTy << IsUnion << UseContext;
11322         // Reset OrigLoc so that this diagnostic is emitted only once.
11323         OrigLoc = SourceLocation();
11324       }
11325       InNonTrivialUnion = true;
11326     }
11327 
11328     if (InNonTrivialUnion)
11329       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11330           << 0 << 0 << QT.getUnqualifiedType() << "";
11331 
11332     for (const FieldDecl *FD : RD->fields())
11333       if (!shouldIgnoreForRecordTriviality(FD))
11334         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11335   }
11336 
11337   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11338 
11339   // The non-trivial C union type or the struct/union type that contains a
11340   // non-trivial C union.
11341   QualType OrigTy;
11342   SourceLocation OrigLoc;
11343   Sema::NonTrivialCUnionContext UseContext;
11344   Sema &S;
11345 };
11346 
11347 struct DiagNonTrivalCUnionDestructedTypeVisitor
11348     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
11349   using Super =
11350       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
11351 
11352   DiagNonTrivalCUnionDestructedTypeVisitor(
11353       QualType OrigTy, SourceLocation OrigLoc,
11354       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11355       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11356 
11357   void visitWithKind(QualType::DestructionKind DK, QualType QT,
11358                      const FieldDecl *FD, bool InNonTrivialUnion) {
11359     if (const auto *AT = S.Context.getAsArrayType(QT))
11360       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11361                                      InNonTrivialUnion);
11362     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
11363   }
11364 
11365   void visitARCStrong(QualType QT, const FieldDecl *FD,
11366                       bool InNonTrivialUnion) {
11367     if (InNonTrivialUnion)
11368       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11369           << 1 << 1 << QT << FD->getName();
11370   }
11371 
11372   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11373     if (InNonTrivialUnion)
11374       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11375           << 1 << 1 << QT << FD->getName();
11376   }
11377 
11378   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11379     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11380     if (RD->isUnion()) {
11381       if (OrigLoc.isValid()) {
11382         bool IsUnion = false;
11383         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11384           IsUnion = OrigRD->isUnion();
11385         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11386             << 1 << OrigTy << IsUnion << UseContext;
11387         // Reset OrigLoc so that this diagnostic is emitted only once.
11388         OrigLoc = SourceLocation();
11389       }
11390       InNonTrivialUnion = true;
11391     }
11392 
11393     if (InNonTrivialUnion)
11394       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11395           << 0 << 1 << QT.getUnqualifiedType() << "";
11396 
11397     for (const FieldDecl *FD : RD->fields())
11398       if (!shouldIgnoreForRecordTriviality(FD))
11399         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11400   }
11401 
11402   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11403   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
11404                           bool InNonTrivialUnion) {}
11405 
11406   // The non-trivial C union type or the struct/union type that contains a
11407   // non-trivial C union.
11408   QualType OrigTy;
11409   SourceLocation OrigLoc;
11410   Sema::NonTrivialCUnionContext UseContext;
11411   Sema &S;
11412 };
11413 
11414 struct DiagNonTrivalCUnionCopyVisitor
11415     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
11416   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
11417 
11418   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
11419                                  Sema::NonTrivialCUnionContext UseContext,
11420                                  Sema &S)
11421       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11422 
11423   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
11424                      const FieldDecl *FD, bool InNonTrivialUnion) {
11425     if (const auto *AT = S.Context.getAsArrayType(QT))
11426       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11427                                      InNonTrivialUnion);
11428     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
11429   }
11430 
11431   void visitARCStrong(QualType QT, const FieldDecl *FD,
11432                       bool InNonTrivialUnion) {
11433     if (InNonTrivialUnion)
11434       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11435           << 1 << 2 << QT << FD->getName();
11436   }
11437 
11438   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11439     if (InNonTrivialUnion)
11440       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11441           << 1 << 2 << QT << FD->getName();
11442   }
11443 
11444   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11445     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11446     if (RD->isUnion()) {
11447       if (OrigLoc.isValid()) {
11448         bool IsUnion = false;
11449         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11450           IsUnion = OrigRD->isUnion();
11451         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11452             << 2 << OrigTy << IsUnion << UseContext;
11453         // Reset OrigLoc so that this diagnostic is emitted only once.
11454         OrigLoc = SourceLocation();
11455       }
11456       InNonTrivialUnion = true;
11457     }
11458 
11459     if (InNonTrivialUnion)
11460       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11461           << 0 << 2 << QT.getUnqualifiedType() << "";
11462 
11463     for (const FieldDecl *FD : RD->fields())
11464       if (!shouldIgnoreForRecordTriviality(FD))
11465         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11466   }
11467 
11468   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
11469                 const FieldDecl *FD, bool InNonTrivialUnion) {}
11470   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11471   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
11472                             bool InNonTrivialUnion) {}
11473 
11474   // The non-trivial C union type or the struct/union type that contains a
11475   // non-trivial C union.
11476   QualType OrigTy;
11477   SourceLocation OrigLoc;
11478   Sema::NonTrivialCUnionContext UseContext;
11479   Sema &S;
11480 };
11481 
11482 } // namespace
11483 
11484 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
11485                                  NonTrivialCUnionContext UseContext,
11486                                  unsigned NonTrivialKind) {
11487   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11488           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
11489           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
11490          "shouldn't be called if type doesn't have a non-trivial C union");
11491 
11492   if ((NonTrivialKind & NTCUK_Init) &&
11493       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11494     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
11495         .visit(QT, nullptr, false);
11496   if ((NonTrivialKind & NTCUK_Destruct) &&
11497       QT.hasNonTrivialToPrimitiveDestructCUnion())
11498     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
11499         .visit(QT, nullptr, false);
11500   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
11501     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
11502         .visit(QT, nullptr, false);
11503 }
11504 
11505 /// AddInitializerToDecl - Adds the initializer Init to the
11506 /// declaration dcl. If DirectInit is true, this is C++ direct
11507 /// initialization rather than copy initialization.
11508 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
11509   // If there is no declaration, there was an error parsing it.  Just ignore
11510   // the initializer.
11511   if (!RealDecl || RealDecl->isInvalidDecl()) {
11512     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
11513     return;
11514   }
11515 
11516   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
11517     // Pure-specifiers are handled in ActOnPureSpecifier.
11518     Diag(Method->getLocation(), diag::err_member_function_initialization)
11519       << Method->getDeclName() << Init->getSourceRange();
11520     Method->setInvalidDecl();
11521     return;
11522   }
11523 
11524   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
11525   if (!VDecl) {
11526     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
11527     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
11528     RealDecl->setInvalidDecl();
11529     return;
11530   }
11531 
11532   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
11533   if (VDecl->getType()->isUndeducedType()) {
11534     // Attempt typo correction early so that the type of the init expression can
11535     // be deduced based on the chosen correction if the original init contains a
11536     // TypoExpr.
11537     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
11538     if (!Res.isUsable()) {
11539       RealDecl->setInvalidDecl();
11540       return;
11541     }
11542     Init = Res.get();
11543 
11544     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
11545       return;
11546   }
11547 
11548   // dllimport cannot be used on variable definitions.
11549   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
11550     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
11551     VDecl->setInvalidDecl();
11552     return;
11553   }
11554 
11555   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
11556     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
11557     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
11558     VDecl->setInvalidDecl();
11559     return;
11560   }
11561 
11562   if (!VDecl->getType()->isDependentType()) {
11563     // A definition must end up with a complete type, which means it must be
11564     // complete with the restriction that an array type might be completed by
11565     // the initializer; note that later code assumes this restriction.
11566     QualType BaseDeclType = VDecl->getType();
11567     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
11568       BaseDeclType = Array->getElementType();
11569     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
11570                             diag::err_typecheck_decl_incomplete_type)) {
11571       RealDecl->setInvalidDecl();
11572       return;
11573     }
11574 
11575     // The variable can not have an abstract class type.
11576     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
11577                                diag::err_abstract_type_in_decl,
11578                                AbstractVariableType))
11579       VDecl->setInvalidDecl();
11580   }
11581 
11582   // If adding the initializer will turn this declaration into a definition,
11583   // and we already have a definition for this variable, diagnose or otherwise
11584   // handle the situation.
11585   VarDecl *Def;
11586   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
11587       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
11588       !VDecl->isThisDeclarationADemotedDefinition() &&
11589       checkVarDeclRedefinition(Def, VDecl))
11590     return;
11591 
11592   if (getLangOpts().CPlusPlus) {
11593     // C++ [class.static.data]p4
11594     //   If a static data member is of const integral or const
11595     //   enumeration type, its declaration in the class definition can
11596     //   specify a constant-initializer which shall be an integral
11597     //   constant expression (5.19). In that case, the member can appear
11598     //   in integral constant expressions. The member shall still be
11599     //   defined in a namespace scope if it is used in the program and the
11600     //   namespace scope definition shall not contain an initializer.
11601     //
11602     // We already performed a redefinition check above, but for static
11603     // data members we also need to check whether there was an in-class
11604     // declaration with an initializer.
11605     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
11606       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
11607           << VDecl->getDeclName();
11608       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
11609            diag::note_previous_initializer)
11610           << 0;
11611       return;
11612     }
11613 
11614     if (VDecl->hasLocalStorage())
11615       setFunctionHasBranchProtectedScope();
11616 
11617     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
11618       VDecl->setInvalidDecl();
11619       return;
11620     }
11621   }
11622 
11623   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
11624   // a kernel function cannot be initialized."
11625   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
11626     Diag(VDecl->getLocation(), diag::err_local_cant_init);
11627     VDecl->setInvalidDecl();
11628     return;
11629   }
11630 
11631   // Get the decls type and save a reference for later, since
11632   // CheckInitializerTypes may change it.
11633   QualType DclT = VDecl->getType(), SavT = DclT;
11634 
11635   // Expressions default to 'id' when we're in a debugger
11636   // and we are assigning it to a variable of Objective-C pointer type.
11637   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
11638       Init->getType() == Context.UnknownAnyTy) {
11639     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11640     if (Result.isInvalid()) {
11641       VDecl->setInvalidDecl();
11642       return;
11643     }
11644     Init = Result.get();
11645   }
11646 
11647   // Perform the initialization.
11648   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
11649   if (!VDecl->isInvalidDecl()) {
11650     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11651     InitializationKind Kind = InitializationKind::CreateForInit(
11652         VDecl->getLocation(), DirectInit, Init);
11653 
11654     MultiExprArg Args = Init;
11655     if (CXXDirectInit)
11656       Args = MultiExprArg(CXXDirectInit->getExprs(),
11657                           CXXDirectInit->getNumExprs());
11658 
11659     // Try to correct any TypoExprs in the initialization arguments.
11660     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
11661       ExprResult Res = CorrectDelayedTyposInExpr(
11662           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
11663             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
11664             return Init.Failed() ? ExprError() : E;
11665           });
11666       if (Res.isInvalid()) {
11667         VDecl->setInvalidDecl();
11668       } else if (Res.get() != Args[Idx]) {
11669         Args[Idx] = Res.get();
11670       }
11671     }
11672     if (VDecl->isInvalidDecl())
11673       return;
11674 
11675     InitializationSequence InitSeq(*this, Entity, Kind, Args,
11676                                    /*TopLevelOfInitList=*/false,
11677                                    /*TreatUnavailableAsInvalid=*/false);
11678     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
11679     if (Result.isInvalid()) {
11680       VDecl->setInvalidDecl();
11681       return;
11682     }
11683 
11684     Init = Result.getAs<Expr>();
11685   }
11686 
11687   // Check for self-references within variable initializers.
11688   // Variables declared within a function/method body (except for references)
11689   // are handled by a dataflow analysis.
11690   // This is undefined behavior in C++, but valid in C.
11691   if (getLangOpts().CPlusPlus) {
11692     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
11693         VDecl->getType()->isReferenceType()) {
11694       CheckSelfReference(*this, RealDecl, Init, DirectInit);
11695     }
11696   }
11697 
11698   // If the type changed, it means we had an incomplete type that was
11699   // completed by the initializer. For example:
11700   //   int ary[] = { 1, 3, 5 };
11701   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
11702   if (!VDecl->isInvalidDecl() && (DclT != SavT))
11703     VDecl->setType(DclT);
11704 
11705   if (!VDecl->isInvalidDecl()) {
11706     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
11707 
11708     if (VDecl->hasAttr<BlocksAttr>())
11709       checkRetainCycles(VDecl, Init);
11710 
11711     // It is safe to assign a weak reference into a strong variable.
11712     // Although this code can still have problems:
11713     //   id x = self.weakProp;
11714     //   id y = self.weakProp;
11715     // we do not warn to warn spuriously when 'x' and 'y' are on separate
11716     // paths through the function. This should be revisited if
11717     // -Wrepeated-use-of-weak is made flow-sensitive.
11718     if (FunctionScopeInfo *FSI = getCurFunction())
11719       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
11720            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
11721           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11722                            Init->getBeginLoc()))
11723         FSI->markSafeWeakUse(Init);
11724   }
11725 
11726   // The initialization is usually a full-expression.
11727   //
11728   // FIXME: If this is a braced initialization of an aggregate, it is not
11729   // an expression, and each individual field initializer is a separate
11730   // full-expression. For instance, in:
11731   //
11732   //   struct Temp { ~Temp(); };
11733   //   struct S { S(Temp); };
11734   //   struct T { S a, b; } t = { Temp(), Temp() }
11735   //
11736   // we should destroy the first Temp before constructing the second.
11737   ExprResult Result =
11738       ActOnFinishFullExpr(Init, VDecl->getLocation(),
11739                           /*DiscardedValue*/ false, VDecl->isConstexpr());
11740   if (Result.isInvalid()) {
11741     VDecl->setInvalidDecl();
11742     return;
11743   }
11744   Init = Result.get();
11745 
11746   // Attach the initializer to the decl.
11747   VDecl->setInit(Init);
11748 
11749   if (VDecl->isLocalVarDecl()) {
11750     // Don't check the initializer if the declaration is malformed.
11751     if (VDecl->isInvalidDecl()) {
11752       // do nothing
11753 
11754     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
11755     // This is true even in C++ for OpenCL.
11756     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
11757       CheckForConstantInitializer(Init, DclT);
11758 
11759     // Otherwise, C++ does not restrict the initializer.
11760     } else if (getLangOpts().CPlusPlus) {
11761       // do nothing
11762 
11763     // C99 6.7.8p4: All the expressions in an initializer for an object that has
11764     // static storage duration shall be constant expressions or string literals.
11765     } else if (VDecl->getStorageClass() == SC_Static) {
11766       CheckForConstantInitializer(Init, DclT);
11767 
11768     // C89 is stricter than C99 for aggregate initializers.
11769     // C89 6.5.7p3: All the expressions [...] in an initializer list
11770     // for an object that has aggregate or union type shall be
11771     // constant expressions.
11772     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
11773                isa<InitListExpr>(Init)) {
11774       const Expr *Culprit;
11775       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
11776         Diag(Culprit->getExprLoc(),
11777              diag::ext_aggregate_init_not_constant)
11778           << Culprit->getSourceRange();
11779       }
11780     }
11781 
11782     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
11783       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
11784         if (VDecl->hasLocalStorage())
11785           BE->getBlockDecl()->setCanAvoidCopyToHeap();
11786   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
11787              VDecl->getLexicalDeclContext()->isRecord()) {
11788     // This is an in-class initialization for a static data member, e.g.,
11789     //
11790     // struct S {
11791     //   static const int value = 17;
11792     // };
11793 
11794     // C++ [class.mem]p4:
11795     //   A member-declarator can contain a constant-initializer only
11796     //   if it declares a static member (9.4) of const integral or
11797     //   const enumeration type, see 9.4.2.
11798     //
11799     // C++11 [class.static.data]p3:
11800     //   If a non-volatile non-inline const static data member is of integral
11801     //   or enumeration type, its declaration in the class definition can
11802     //   specify a brace-or-equal-initializer in which every initializer-clause
11803     //   that is an assignment-expression is a constant expression. A static
11804     //   data member of literal type can be declared in the class definition
11805     //   with the constexpr specifier; if so, its declaration shall specify a
11806     //   brace-or-equal-initializer in which every initializer-clause that is
11807     //   an assignment-expression is a constant expression.
11808 
11809     // Do nothing on dependent types.
11810     if (DclT->isDependentType()) {
11811 
11812     // Allow any 'static constexpr' members, whether or not they are of literal
11813     // type. We separately check that every constexpr variable is of literal
11814     // type.
11815     } else if (VDecl->isConstexpr()) {
11816 
11817     // Require constness.
11818     } else if (!DclT.isConstQualified()) {
11819       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
11820         << Init->getSourceRange();
11821       VDecl->setInvalidDecl();
11822 
11823     // We allow integer constant expressions in all cases.
11824     } else if (DclT->isIntegralOrEnumerationType()) {
11825       // Check whether the expression is a constant expression.
11826       SourceLocation Loc;
11827       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
11828         // In C++11, a non-constexpr const static data member with an
11829         // in-class initializer cannot be volatile.
11830         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
11831       else if (Init->isValueDependent())
11832         ; // Nothing to check.
11833       else if (Init->isIntegerConstantExpr(Context, &Loc))
11834         ; // Ok, it's an ICE!
11835       else if (Init->getType()->isScopedEnumeralType() &&
11836                Init->isCXX11ConstantExpr(Context))
11837         ; // Ok, it is a scoped-enum constant expression.
11838       else if (Init->isEvaluatable(Context)) {
11839         // If we can constant fold the initializer through heroics, accept it,
11840         // but report this as a use of an extension for -pedantic.
11841         Diag(Loc, diag::ext_in_class_initializer_non_constant)
11842           << Init->getSourceRange();
11843       } else {
11844         // Otherwise, this is some crazy unknown case.  Report the issue at the
11845         // location provided by the isIntegerConstantExpr failed check.
11846         Diag(Loc, diag::err_in_class_initializer_non_constant)
11847           << Init->getSourceRange();
11848         VDecl->setInvalidDecl();
11849       }
11850 
11851     // We allow foldable floating-point constants as an extension.
11852     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
11853       // In C++98, this is a GNU extension. In C++11, it is not, but we support
11854       // it anyway and provide a fixit to add the 'constexpr'.
11855       if (getLangOpts().CPlusPlus11) {
11856         Diag(VDecl->getLocation(),
11857              diag::ext_in_class_initializer_float_type_cxx11)
11858             << DclT << Init->getSourceRange();
11859         Diag(VDecl->getBeginLoc(),
11860              diag::note_in_class_initializer_float_type_cxx11)
11861             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11862       } else {
11863         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
11864           << DclT << Init->getSourceRange();
11865 
11866         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
11867           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
11868             << Init->getSourceRange();
11869           VDecl->setInvalidDecl();
11870         }
11871       }
11872 
11873     // Suggest adding 'constexpr' in C++11 for literal types.
11874     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
11875       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
11876           << DclT << Init->getSourceRange()
11877           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11878       VDecl->setConstexpr(true);
11879 
11880     } else {
11881       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
11882         << DclT << Init->getSourceRange();
11883       VDecl->setInvalidDecl();
11884     }
11885   } else if (VDecl->isFileVarDecl()) {
11886     // In C, extern is typically used to avoid tentative definitions when
11887     // declaring variables in headers, but adding an intializer makes it a
11888     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
11889     // In C++, extern is often used to give implictly static const variables
11890     // external linkage, so don't warn in that case. If selectany is present,
11891     // this might be header code intended for C and C++ inclusion, so apply the
11892     // C++ rules.
11893     if (VDecl->getStorageClass() == SC_Extern &&
11894         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
11895          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
11896         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
11897         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
11898       Diag(VDecl->getLocation(), diag::warn_extern_init);
11899 
11900     // In Microsoft C++ mode, a const variable defined in namespace scope has
11901     // external linkage by default if the variable is declared with
11902     // __declspec(dllexport).
11903     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
11904         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
11905         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
11906       VDecl->setStorageClass(SC_Extern);
11907 
11908     // C99 6.7.8p4. All file scoped initializers need to be constant.
11909     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
11910       CheckForConstantInitializer(Init, DclT);
11911   }
11912 
11913   QualType InitType = Init->getType();
11914   if (!InitType.isNull() &&
11915       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11916        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
11917     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
11918 
11919   // We will represent direct-initialization similarly to copy-initialization:
11920   //    int x(1);  -as-> int x = 1;
11921   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
11922   //
11923   // Clients that want to distinguish between the two forms, can check for
11924   // direct initializer using VarDecl::getInitStyle().
11925   // A major benefit is that clients that don't particularly care about which
11926   // exactly form was it (like the CodeGen) can handle both cases without
11927   // special case code.
11928 
11929   // C++ 8.5p11:
11930   // The form of initialization (using parentheses or '=') is generally
11931   // insignificant, but does matter when the entity being initialized has a
11932   // class type.
11933   if (CXXDirectInit) {
11934     assert(DirectInit && "Call-style initializer must be direct init.");
11935     VDecl->setInitStyle(VarDecl::CallInit);
11936   } else if (DirectInit) {
11937     // This must be list-initialization. No other way is direct-initialization.
11938     VDecl->setInitStyle(VarDecl::ListInit);
11939   }
11940 
11941   CheckCompleteVariableDeclaration(VDecl);
11942 }
11943 
11944 /// ActOnInitializerError - Given that there was an error parsing an
11945 /// initializer for the given declaration, try to return to some form
11946 /// of sanity.
11947 void Sema::ActOnInitializerError(Decl *D) {
11948   // Our main concern here is re-establishing invariants like "a
11949   // variable's type is either dependent or complete".
11950   if (!D || D->isInvalidDecl()) return;
11951 
11952   VarDecl *VD = dyn_cast<VarDecl>(D);
11953   if (!VD) return;
11954 
11955   // Bindings are not usable if we can't make sense of the initializer.
11956   if (auto *DD = dyn_cast<DecompositionDecl>(D))
11957     for (auto *BD : DD->bindings())
11958       BD->setInvalidDecl();
11959 
11960   // Auto types are meaningless if we can't make sense of the initializer.
11961   if (ParsingInitForAutoVars.count(D)) {
11962     D->setInvalidDecl();
11963     return;
11964   }
11965 
11966   QualType Ty = VD->getType();
11967   if (Ty->isDependentType()) return;
11968 
11969   // Require a complete type.
11970   if (RequireCompleteType(VD->getLocation(),
11971                           Context.getBaseElementType(Ty),
11972                           diag::err_typecheck_decl_incomplete_type)) {
11973     VD->setInvalidDecl();
11974     return;
11975   }
11976 
11977   // Require a non-abstract type.
11978   if (RequireNonAbstractType(VD->getLocation(), Ty,
11979                              diag::err_abstract_type_in_decl,
11980                              AbstractVariableType)) {
11981     VD->setInvalidDecl();
11982     return;
11983   }
11984 
11985   // Don't bother complaining about constructors or destructors,
11986   // though.
11987 }
11988 
11989 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
11990   // If there is no declaration, there was an error parsing it. Just ignore it.
11991   if (!RealDecl)
11992     return;
11993 
11994   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
11995     QualType Type = Var->getType();
11996 
11997     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
11998     if (isa<DecompositionDecl>(RealDecl)) {
11999       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12000       Var->setInvalidDecl();
12001       return;
12002     }
12003 
12004     if (Type->isUndeducedType() &&
12005         DeduceVariableDeclarationType(Var, false, nullptr))
12006       return;
12007 
12008     // C++11 [class.static.data]p3: A static data member can be declared with
12009     // the constexpr specifier; if so, its declaration shall specify
12010     // a brace-or-equal-initializer.
12011     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12012     // the definition of a variable [...] or the declaration of a static data
12013     // member.
12014     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12015         !Var->isThisDeclarationADemotedDefinition()) {
12016       if (Var->isStaticDataMember()) {
12017         // C++1z removes the relevant rule; the in-class declaration is always
12018         // a definition there.
12019         if (!getLangOpts().CPlusPlus17 &&
12020             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12021           Diag(Var->getLocation(),
12022                diag::err_constexpr_static_mem_var_requires_init)
12023             << Var->getDeclName();
12024           Var->setInvalidDecl();
12025           return;
12026         }
12027       } else {
12028         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12029         Var->setInvalidDecl();
12030         return;
12031       }
12032     }
12033 
12034     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12035     // be initialized.
12036     if (!Var->isInvalidDecl() &&
12037         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12038         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12039       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12040       Var->setInvalidDecl();
12041       return;
12042     }
12043 
12044     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12045     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12046         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12047       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12048                             NTCUC_DefaultInitializedObject, NTCUK_Init);
12049 
12050 
12051     switch (DefKind) {
12052     case VarDecl::Definition:
12053       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12054         break;
12055 
12056       // We have an out-of-line definition of a static data member
12057       // that has an in-class initializer, so we type-check this like
12058       // a declaration.
12059       //
12060       LLVM_FALLTHROUGH;
12061 
12062     case VarDecl::DeclarationOnly:
12063       // It's only a declaration.
12064 
12065       // Block scope. C99 6.7p7: If an identifier for an object is
12066       // declared with no linkage (C99 6.2.2p6), the type for the
12067       // object shall be complete.
12068       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12069           !Var->hasLinkage() && !Var->isInvalidDecl() &&
12070           RequireCompleteType(Var->getLocation(), Type,
12071                               diag::err_typecheck_decl_incomplete_type))
12072         Var->setInvalidDecl();
12073 
12074       // Make sure that the type is not abstract.
12075       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12076           RequireNonAbstractType(Var->getLocation(), Type,
12077                                  diag::err_abstract_type_in_decl,
12078                                  AbstractVariableType))
12079         Var->setInvalidDecl();
12080       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12081           Var->getStorageClass() == SC_PrivateExtern) {
12082         Diag(Var->getLocation(), diag::warn_private_extern);
12083         Diag(Var->getLocation(), diag::note_private_extern);
12084       }
12085 
12086       return;
12087 
12088     case VarDecl::TentativeDefinition:
12089       // File scope. C99 6.9.2p2: A declaration of an identifier for an
12090       // object that has file scope without an initializer, and without a
12091       // storage-class specifier or with the storage-class specifier "static",
12092       // constitutes a tentative definition. Note: A tentative definition with
12093       // external linkage is valid (C99 6.2.2p5).
12094       if (!Var->isInvalidDecl()) {
12095         if (const IncompleteArrayType *ArrayT
12096                                     = Context.getAsIncompleteArrayType(Type)) {
12097           if (RequireCompleteType(Var->getLocation(),
12098                                   ArrayT->getElementType(),
12099                                   diag::err_illegal_decl_array_incomplete_type))
12100             Var->setInvalidDecl();
12101         } else if (Var->getStorageClass() == SC_Static) {
12102           // C99 6.9.2p3: If the declaration of an identifier for an object is
12103           // a tentative definition and has internal linkage (C99 6.2.2p3), the
12104           // declared type shall not be an incomplete type.
12105           // NOTE: code such as the following
12106           //     static struct s;
12107           //     struct s { int a; };
12108           // is accepted by gcc. Hence here we issue a warning instead of
12109           // an error and we do not invalidate the static declaration.
12110           // NOTE: to avoid multiple warnings, only check the first declaration.
12111           if (Var->isFirstDecl())
12112             RequireCompleteType(Var->getLocation(), Type,
12113                                 diag::ext_typecheck_decl_incomplete_type);
12114         }
12115       }
12116 
12117       // Record the tentative definition; we're done.
12118       if (!Var->isInvalidDecl())
12119         TentativeDefinitions.push_back(Var);
12120       return;
12121     }
12122 
12123     // Provide a specific diagnostic for uninitialized variable
12124     // definitions with incomplete array type.
12125     if (Type->isIncompleteArrayType()) {
12126       Diag(Var->getLocation(),
12127            diag::err_typecheck_incomplete_array_needs_initializer);
12128       Var->setInvalidDecl();
12129       return;
12130     }
12131 
12132     // Provide a specific diagnostic for uninitialized variable
12133     // definitions with reference type.
12134     if (Type->isReferenceType()) {
12135       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12136         << Var->getDeclName()
12137         << SourceRange(Var->getLocation(), Var->getLocation());
12138       Var->setInvalidDecl();
12139       return;
12140     }
12141 
12142     // Do not attempt to type-check the default initializer for a
12143     // variable with dependent type.
12144     if (Type->isDependentType())
12145       return;
12146 
12147     if (Var->isInvalidDecl())
12148       return;
12149 
12150     if (!Var->hasAttr<AliasAttr>()) {
12151       if (RequireCompleteType(Var->getLocation(),
12152                               Context.getBaseElementType(Type),
12153                               diag::err_typecheck_decl_incomplete_type)) {
12154         Var->setInvalidDecl();
12155         return;
12156       }
12157     } else {
12158       return;
12159     }
12160 
12161     // The variable can not have an abstract class type.
12162     if (RequireNonAbstractType(Var->getLocation(), Type,
12163                                diag::err_abstract_type_in_decl,
12164                                AbstractVariableType)) {
12165       Var->setInvalidDecl();
12166       return;
12167     }
12168 
12169     // Check for jumps past the implicit initializer.  C++0x
12170     // clarifies that this applies to a "variable with automatic
12171     // storage duration", not a "local variable".
12172     // C++11 [stmt.dcl]p3
12173     //   A program that jumps from a point where a variable with automatic
12174     //   storage duration is not in scope to a point where it is in scope is
12175     //   ill-formed unless the variable has scalar type, class type with a
12176     //   trivial default constructor and a trivial destructor, a cv-qualified
12177     //   version of one of these types, or an array of one of the preceding
12178     //   types and is declared without an initializer.
12179     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12180       if (const RecordType *Record
12181             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12182         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12183         // Mark the function (if we're in one) for further checking even if the
12184         // looser rules of C++11 do not require such checks, so that we can
12185         // diagnose incompatibilities with C++98.
12186         if (!CXXRecord->isPOD())
12187           setFunctionHasBranchProtectedScope();
12188       }
12189     }
12190     // In OpenCL, we can't initialize objects in the __local address space,
12191     // even implicitly, so don't synthesize an implicit initializer.
12192     if (getLangOpts().OpenCL &&
12193         Var->getType().getAddressSpace() == LangAS::opencl_local)
12194       return;
12195     // C++03 [dcl.init]p9:
12196     //   If no initializer is specified for an object, and the
12197     //   object is of (possibly cv-qualified) non-POD class type (or
12198     //   array thereof), the object shall be default-initialized; if
12199     //   the object is of const-qualified type, the underlying class
12200     //   type shall have a user-declared default
12201     //   constructor. Otherwise, if no initializer is specified for
12202     //   a non- static object, the object and its subobjects, if
12203     //   any, have an indeterminate initial value); if the object
12204     //   or any of its subobjects are of const-qualified type, the
12205     //   program is ill-formed.
12206     // C++0x [dcl.init]p11:
12207     //   If no initializer is specified for an object, the object is
12208     //   default-initialized; [...].
12209     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12210     InitializationKind Kind
12211       = InitializationKind::CreateDefault(Var->getLocation());
12212 
12213     InitializationSequence InitSeq(*this, Entity, Kind, None);
12214     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12215     if (Init.isInvalid())
12216       Var->setInvalidDecl();
12217     else if (Init.get()) {
12218       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12219       // This is important for template substitution.
12220       Var->setInitStyle(VarDecl::CallInit);
12221     }
12222 
12223     CheckCompleteVariableDeclaration(Var);
12224   }
12225 }
12226 
12227 void Sema::ActOnCXXForRangeDecl(Decl *D) {
12228   // If there is no declaration, there was an error parsing it. Ignore it.
12229   if (!D)
12230     return;
12231 
12232   VarDecl *VD = dyn_cast<VarDecl>(D);
12233   if (!VD) {
12234     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12235     D->setInvalidDecl();
12236     return;
12237   }
12238 
12239   VD->setCXXForRangeDecl(true);
12240 
12241   // for-range-declaration cannot be given a storage class specifier.
12242   int Error = -1;
12243   switch (VD->getStorageClass()) {
12244   case SC_None:
12245     break;
12246   case SC_Extern:
12247     Error = 0;
12248     break;
12249   case SC_Static:
12250     Error = 1;
12251     break;
12252   case SC_PrivateExtern:
12253     Error = 2;
12254     break;
12255   case SC_Auto:
12256     Error = 3;
12257     break;
12258   case SC_Register:
12259     Error = 4;
12260     break;
12261   }
12262   if (Error != -1) {
12263     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12264       << VD->getDeclName() << Error;
12265     D->setInvalidDecl();
12266   }
12267 }
12268 
12269 StmtResult
12270 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
12271                                  IdentifierInfo *Ident,
12272                                  ParsedAttributes &Attrs,
12273                                  SourceLocation AttrEnd) {
12274   // C++1y [stmt.iter]p1:
12275   //   A range-based for statement of the form
12276   //      for ( for-range-identifier : for-range-initializer ) statement
12277   //   is equivalent to
12278   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
12279   DeclSpec DS(Attrs.getPool().getFactory());
12280 
12281   const char *PrevSpec;
12282   unsigned DiagID;
12283   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
12284                      getPrintingPolicy());
12285 
12286   Declarator D(DS, DeclaratorContext::ForContext);
12287   D.SetIdentifier(Ident, IdentLoc);
12288   D.takeAttributes(Attrs, AttrEnd);
12289 
12290   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
12291                 IdentLoc);
12292   Decl *Var = ActOnDeclarator(S, D);
12293   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
12294   FinalizeDeclaration(Var);
12295   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
12296                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
12297 }
12298 
12299 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
12300   if (var->isInvalidDecl()) return;
12301 
12302   if (getLangOpts().OpenCL) {
12303     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
12304     // initialiser
12305     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
12306         !var->hasInit()) {
12307       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
12308           << 1 /*Init*/;
12309       var->setInvalidDecl();
12310       return;
12311     }
12312   }
12313 
12314   // In Objective-C, don't allow jumps past the implicit initialization of a
12315   // local retaining variable.
12316   if (getLangOpts().ObjC &&
12317       var->hasLocalStorage()) {
12318     switch (var->getType().getObjCLifetime()) {
12319     case Qualifiers::OCL_None:
12320     case Qualifiers::OCL_ExplicitNone:
12321     case Qualifiers::OCL_Autoreleasing:
12322       break;
12323 
12324     case Qualifiers::OCL_Weak:
12325     case Qualifiers::OCL_Strong:
12326       setFunctionHasBranchProtectedScope();
12327       break;
12328     }
12329   }
12330 
12331   if (var->hasLocalStorage() &&
12332       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
12333     setFunctionHasBranchProtectedScope();
12334 
12335   // Warn about externally-visible variables being defined without a
12336   // prior declaration.  We only want to do this for global
12337   // declarations, but we also specifically need to avoid doing it for
12338   // class members because the linkage of an anonymous class can
12339   // change if it's later given a typedef name.
12340   if (var->isThisDeclarationADefinition() &&
12341       var->getDeclContext()->getRedeclContext()->isFileContext() &&
12342       var->isExternallyVisible() && var->hasLinkage() &&
12343       !var->isInline() && !var->getDescribedVarTemplate() &&
12344       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
12345       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
12346                                   var->getLocation())) {
12347     // Find a previous declaration that's not a definition.
12348     VarDecl *prev = var->getPreviousDecl();
12349     while (prev && prev->isThisDeclarationADefinition())
12350       prev = prev->getPreviousDecl();
12351 
12352     if (!prev) {
12353       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
12354       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
12355           << /* variable */ 0;
12356     }
12357   }
12358 
12359   // Cache the result of checking for constant initialization.
12360   Optional<bool> CacheHasConstInit;
12361   const Expr *CacheCulprit = nullptr;
12362   auto checkConstInit = [&]() mutable {
12363     if (!CacheHasConstInit)
12364       CacheHasConstInit = var->getInit()->isConstantInitializer(
12365             Context, var->getType()->isReferenceType(), &CacheCulprit);
12366     return *CacheHasConstInit;
12367   };
12368 
12369   if (var->getTLSKind() == VarDecl::TLS_Static) {
12370     if (var->getType().isDestructedType()) {
12371       // GNU C++98 edits for __thread, [basic.start.term]p3:
12372       //   The type of an object with thread storage duration shall not
12373       //   have a non-trivial destructor.
12374       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
12375       if (getLangOpts().CPlusPlus11)
12376         Diag(var->getLocation(), diag::note_use_thread_local);
12377     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
12378       if (!checkConstInit()) {
12379         // GNU C++98 edits for __thread, [basic.start.init]p4:
12380         //   An object of thread storage duration shall not require dynamic
12381         //   initialization.
12382         // FIXME: Need strict checking here.
12383         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
12384           << CacheCulprit->getSourceRange();
12385         if (getLangOpts().CPlusPlus11)
12386           Diag(var->getLocation(), diag::note_use_thread_local);
12387       }
12388     }
12389   }
12390 
12391   // Apply section attributes and pragmas to global variables.
12392   bool GlobalStorage = var->hasGlobalStorage();
12393   if (GlobalStorage && var->isThisDeclarationADefinition() &&
12394       !inTemplateInstantiation()) {
12395     PragmaStack<StringLiteral *> *Stack = nullptr;
12396     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
12397     if (var->getType().isConstQualified())
12398       Stack = &ConstSegStack;
12399     else if (!var->getInit()) {
12400       Stack = &BSSSegStack;
12401       SectionFlags |= ASTContext::PSF_Write;
12402     } else {
12403       Stack = &DataSegStack;
12404       SectionFlags |= ASTContext::PSF_Write;
12405     }
12406     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>())
12407       var->addAttr(SectionAttr::CreateImplicit(
12408           Context, Stack->CurrentValue->getString(),
12409           Stack->CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
12410           SectionAttr::Declspec_allocate));
12411     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
12412       if (UnifySection(SA->getName(), SectionFlags, var))
12413         var->dropAttr<SectionAttr>();
12414 
12415     // Apply the init_seg attribute if this has an initializer.  If the
12416     // initializer turns out to not be dynamic, we'll end up ignoring this
12417     // attribute.
12418     if (CurInitSeg && var->getInit())
12419       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
12420                                                CurInitSegLoc,
12421                                                AttributeCommonInfo::AS_Pragma));
12422   }
12423 
12424   // All the following checks are C++ only.
12425   if (!getLangOpts().CPlusPlus) {
12426       // If this variable must be emitted, add it as an initializer for the
12427       // current module.
12428      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12429        Context.addModuleInitializer(ModuleScopes.back().Module, var);
12430      return;
12431   }
12432 
12433   if (auto *DD = dyn_cast<DecompositionDecl>(var))
12434     CheckCompleteDecompositionDeclaration(DD);
12435 
12436   QualType type = var->getType();
12437   if (type->isDependentType()) return;
12438 
12439   if (var->hasAttr<BlocksAttr>())
12440     getCurFunction()->addByrefBlockVar(var);
12441 
12442   Expr *Init = var->getInit();
12443   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
12444   QualType baseType = Context.getBaseElementType(type);
12445 
12446   if (Init && !Init->isValueDependent()) {
12447     if (var->isConstexpr()) {
12448       SmallVector<PartialDiagnosticAt, 8> Notes;
12449       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
12450         SourceLocation DiagLoc = var->getLocation();
12451         // If the note doesn't add any useful information other than a source
12452         // location, fold it into the primary diagnostic.
12453         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12454               diag::note_invalid_subexpr_in_const_expr) {
12455           DiagLoc = Notes[0].first;
12456           Notes.clear();
12457         }
12458         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
12459           << var << Init->getSourceRange();
12460         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
12461           Diag(Notes[I].first, Notes[I].second);
12462       }
12463     } else if (var->mightBeUsableInConstantExpressions(Context)) {
12464       // Check whether the initializer of a const variable of integral or
12465       // enumeration type is an ICE now, since we can't tell whether it was
12466       // initialized by a constant expression if we check later.
12467       var->checkInitIsICE();
12468     }
12469 
12470     // Don't emit further diagnostics about constexpr globals since they
12471     // were just diagnosed.
12472     if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) {
12473       // FIXME: Need strict checking in C++03 here.
12474       bool DiagErr = getLangOpts().CPlusPlus11
12475           ? !var->checkInitIsICE() : !checkConstInit();
12476       if (DiagErr) {
12477         auto *Attr = var->getAttr<ConstInitAttr>();
12478         Diag(var->getLocation(), diag::err_require_constant_init_failed)
12479           << Init->getSourceRange();
12480         Diag(Attr->getLocation(),
12481              diag::note_declared_required_constant_init_here)
12482             << Attr->getRange() << Attr->isConstinit();
12483         if (getLangOpts().CPlusPlus11) {
12484           APValue Value;
12485           SmallVector<PartialDiagnosticAt, 8> Notes;
12486           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
12487           for (auto &it : Notes)
12488             Diag(it.first, it.second);
12489         } else {
12490           Diag(CacheCulprit->getExprLoc(),
12491                diag::note_invalid_subexpr_in_const_expr)
12492               << CacheCulprit->getSourceRange();
12493         }
12494       }
12495     }
12496     else if (!var->isConstexpr() && IsGlobal &&
12497              !getDiagnostics().isIgnored(diag::warn_global_constructor,
12498                                     var->getLocation())) {
12499       // Warn about globals which don't have a constant initializer.  Don't
12500       // warn about globals with a non-trivial destructor because we already
12501       // warned about them.
12502       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
12503       if (!(RD && !RD->hasTrivialDestructor())) {
12504         if (!checkConstInit())
12505           Diag(var->getLocation(), diag::warn_global_constructor)
12506             << Init->getSourceRange();
12507       }
12508     }
12509   }
12510 
12511   // Require the destructor.
12512   if (const RecordType *recordType = baseType->getAs<RecordType>())
12513     FinalizeVarWithDestructor(var, recordType);
12514 
12515   // If this variable must be emitted, add it as an initializer for the current
12516   // module.
12517   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12518     Context.addModuleInitializer(ModuleScopes.back().Module, var);
12519 }
12520 
12521 /// Determines if a variable's alignment is dependent.
12522 static bool hasDependentAlignment(VarDecl *VD) {
12523   if (VD->getType()->isDependentType())
12524     return true;
12525   for (auto *I : VD->specific_attrs<AlignedAttr>())
12526     if (I->isAlignmentDependent())
12527       return true;
12528   return false;
12529 }
12530 
12531 /// Check if VD needs to be dllexport/dllimport due to being in a
12532 /// dllexport/import function.
12533 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
12534   assert(VD->isStaticLocal());
12535 
12536   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12537 
12538   // Find outermost function when VD is in lambda function.
12539   while (FD && !getDLLAttr(FD) &&
12540          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
12541          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
12542     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
12543   }
12544 
12545   if (!FD)
12546     return;
12547 
12548   // Static locals inherit dll attributes from their function.
12549   if (Attr *A = getDLLAttr(FD)) {
12550     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
12551     NewAttr->setInherited(true);
12552     VD->addAttr(NewAttr);
12553   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
12554     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
12555     NewAttr->setInherited(true);
12556     VD->addAttr(NewAttr);
12557 
12558     // Export this function to enforce exporting this static variable even
12559     // if it is not used in this compilation unit.
12560     if (!FD->hasAttr<DLLExportAttr>())
12561       FD->addAttr(NewAttr);
12562 
12563   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
12564     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
12565     NewAttr->setInherited(true);
12566     VD->addAttr(NewAttr);
12567   }
12568 }
12569 
12570 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
12571 /// any semantic actions necessary after any initializer has been attached.
12572 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
12573   // Note that we are no longer parsing the initializer for this declaration.
12574   ParsingInitForAutoVars.erase(ThisDecl);
12575 
12576   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
12577   if (!VD)
12578     return;
12579 
12580   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
12581   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
12582       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
12583     if (PragmaClangBSSSection.Valid)
12584       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
12585           Context, PragmaClangBSSSection.SectionName,
12586           PragmaClangBSSSection.PragmaLocation,
12587           AttributeCommonInfo::AS_Pragma));
12588     if (PragmaClangDataSection.Valid)
12589       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
12590           Context, PragmaClangDataSection.SectionName,
12591           PragmaClangDataSection.PragmaLocation,
12592           AttributeCommonInfo::AS_Pragma));
12593     if (PragmaClangRodataSection.Valid)
12594       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
12595           Context, PragmaClangRodataSection.SectionName,
12596           PragmaClangRodataSection.PragmaLocation,
12597           AttributeCommonInfo::AS_Pragma));
12598   }
12599 
12600   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
12601     for (auto *BD : DD->bindings()) {
12602       FinalizeDeclaration(BD);
12603     }
12604   }
12605 
12606   checkAttributesAfterMerging(*this, *VD);
12607 
12608   // Perform TLS alignment check here after attributes attached to the variable
12609   // which may affect the alignment have been processed. Only perform the check
12610   // if the target has a maximum TLS alignment (zero means no constraints).
12611   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
12612     // Protect the check so that it's not performed on dependent types and
12613     // dependent alignments (we can't determine the alignment in that case).
12614     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
12615         !VD->isInvalidDecl()) {
12616       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
12617       if (Context.getDeclAlign(VD) > MaxAlignChars) {
12618         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
12619           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
12620           << (unsigned)MaxAlignChars.getQuantity();
12621       }
12622     }
12623   }
12624 
12625   if (VD->isStaticLocal()) {
12626     CheckStaticLocalForDllExport(VD);
12627 
12628     if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
12629       // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
12630       // function, only __shared__ variables or variables without any device
12631       // memory qualifiers may be declared with static storage class.
12632       // Note: It is unclear how a function-scope non-const static variable
12633       // without device memory qualifier is implemented, therefore only static
12634       // const variable without device memory qualifier is allowed.
12635       [&]() {
12636         if (!getLangOpts().CUDA)
12637           return;
12638         if (VD->hasAttr<CUDASharedAttr>())
12639           return;
12640         if (VD->getType().isConstQualified() &&
12641             !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
12642           return;
12643         if (CUDADiagIfDeviceCode(VD->getLocation(),
12644                                  diag::err_device_static_local_var)
12645             << CurrentCUDATarget())
12646           VD->setInvalidDecl();
12647       }();
12648     }
12649   }
12650 
12651   // Perform check for initializers of device-side global variables.
12652   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
12653   // 7.5). We must also apply the same checks to all __shared__
12654   // variables whether they are local or not. CUDA also allows
12655   // constant initializers for __constant__ and __device__ variables.
12656   if (getLangOpts().CUDA)
12657     checkAllowedCUDAInitializer(VD);
12658 
12659   // Grab the dllimport or dllexport attribute off of the VarDecl.
12660   const InheritableAttr *DLLAttr = getDLLAttr(VD);
12661 
12662   // Imported static data members cannot be defined out-of-line.
12663   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
12664     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
12665         VD->isThisDeclarationADefinition()) {
12666       // We allow definitions of dllimport class template static data members
12667       // with a warning.
12668       CXXRecordDecl *Context =
12669         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
12670       bool IsClassTemplateMember =
12671           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
12672           Context->getDescribedClassTemplate();
12673 
12674       Diag(VD->getLocation(),
12675            IsClassTemplateMember
12676                ? diag::warn_attribute_dllimport_static_field_definition
12677                : diag::err_attribute_dllimport_static_field_definition);
12678       Diag(IA->getLocation(), diag::note_attribute);
12679       if (!IsClassTemplateMember)
12680         VD->setInvalidDecl();
12681     }
12682   }
12683 
12684   // dllimport/dllexport variables cannot be thread local, their TLS index
12685   // isn't exported with the variable.
12686   if (DLLAttr && VD->getTLSKind()) {
12687     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12688     if (F && getDLLAttr(F)) {
12689       assert(VD->isStaticLocal());
12690       // But if this is a static local in a dlimport/dllexport function, the
12691       // function will never be inlined, which means the var would never be
12692       // imported, so having it marked import/export is safe.
12693     } else {
12694       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
12695                                                                     << DLLAttr;
12696       VD->setInvalidDecl();
12697     }
12698   }
12699 
12700   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
12701     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
12702       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
12703       VD->dropAttr<UsedAttr>();
12704     }
12705   }
12706 
12707   const DeclContext *DC = VD->getDeclContext();
12708   // If there's a #pragma GCC visibility in scope, and this isn't a class
12709   // member, set the visibility of this variable.
12710   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
12711     AddPushedVisibilityAttribute(VD);
12712 
12713   // FIXME: Warn on unused var template partial specializations.
12714   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
12715     MarkUnusedFileScopedDecl(VD);
12716 
12717   // Now we have parsed the initializer and can update the table of magic
12718   // tag values.
12719   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
12720       !VD->getType()->isIntegralOrEnumerationType())
12721     return;
12722 
12723   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
12724     const Expr *MagicValueExpr = VD->getInit();
12725     if (!MagicValueExpr) {
12726       continue;
12727     }
12728     llvm::APSInt MagicValueInt;
12729     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
12730       Diag(I->getRange().getBegin(),
12731            diag::err_type_tag_for_datatype_not_ice)
12732         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12733       continue;
12734     }
12735     if (MagicValueInt.getActiveBits() > 64) {
12736       Diag(I->getRange().getBegin(),
12737            diag::err_type_tag_for_datatype_too_large)
12738         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12739       continue;
12740     }
12741     uint64_t MagicValue = MagicValueInt.getZExtValue();
12742     RegisterTypeTagForDatatype(I->getArgumentKind(),
12743                                MagicValue,
12744                                I->getMatchingCType(),
12745                                I->getLayoutCompatible(),
12746                                I->getMustBeNull());
12747   }
12748 }
12749 
12750 static bool hasDeducedAuto(DeclaratorDecl *DD) {
12751   auto *VD = dyn_cast<VarDecl>(DD);
12752   return VD && !VD->getType()->hasAutoForTrailingReturnType();
12753 }
12754 
12755 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
12756                                                    ArrayRef<Decl *> Group) {
12757   SmallVector<Decl*, 8> Decls;
12758 
12759   if (DS.isTypeSpecOwned())
12760     Decls.push_back(DS.getRepAsDecl());
12761 
12762   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
12763   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
12764   bool DiagnosedMultipleDecomps = false;
12765   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
12766   bool DiagnosedNonDeducedAuto = false;
12767 
12768   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12769     if (Decl *D = Group[i]) {
12770       // For declarators, there are some additional syntactic-ish checks we need
12771       // to perform.
12772       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
12773         if (!FirstDeclaratorInGroup)
12774           FirstDeclaratorInGroup = DD;
12775         if (!FirstDecompDeclaratorInGroup)
12776           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
12777         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
12778             !hasDeducedAuto(DD))
12779           FirstNonDeducedAutoInGroup = DD;
12780 
12781         if (FirstDeclaratorInGroup != DD) {
12782           // A decomposition declaration cannot be combined with any other
12783           // declaration in the same group.
12784           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
12785             Diag(FirstDecompDeclaratorInGroup->getLocation(),
12786                  diag::err_decomp_decl_not_alone)
12787                 << FirstDeclaratorInGroup->getSourceRange()
12788                 << DD->getSourceRange();
12789             DiagnosedMultipleDecomps = true;
12790           }
12791 
12792           // A declarator that uses 'auto' in any way other than to declare a
12793           // variable with a deduced type cannot be combined with any other
12794           // declarator in the same group.
12795           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
12796             Diag(FirstNonDeducedAutoInGroup->getLocation(),
12797                  diag::err_auto_non_deduced_not_alone)
12798                 << FirstNonDeducedAutoInGroup->getType()
12799                        ->hasAutoForTrailingReturnType()
12800                 << FirstDeclaratorInGroup->getSourceRange()
12801                 << DD->getSourceRange();
12802             DiagnosedNonDeducedAuto = true;
12803           }
12804         }
12805       }
12806 
12807       Decls.push_back(D);
12808     }
12809   }
12810 
12811   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
12812     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
12813       handleTagNumbering(Tag, S);
12814       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
12815           getLangOpts().CPlusPlus)
12816         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
12817     }
12818   }
12819 
12820   return BuildDeclaratorGroup(Decls);
12821 }
12822 
12823 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
12824 /// group, performing any necessary semantic checking.
12825 Sema::DeclGroupPtrTy
12826 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
12827   // C++14 [dcl.spec.auto]p7: (DR1347)
12828   //   If the type that replaces the placeholder type is not the same in each
12829   //   deduction, the program is ill-formed.
12830   if (Group.size() > 1) {
12831     QualType Deduced;
12832     VarDecl *DeducedDecl = nullptr;
12833     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12834       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
12835       if (!D || D->isInvalidDecl())
12836         break;
12837       DeducedType *DT = D->getType()->getContainedDeducedType();
12838       if (!DT || DT->getDeducedType().isNull())
12839         continue;
12840       if (Deduced.isNull()) {
12841         Deduced = DT->getDeducedType();
12842         DeducedDecl = D;
12843       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
12844         auto *AT = dyn_cast<AutoType>(DT);
12845         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
12846              diag::err_auto_different_deductions)
12847           << (AT ? (unsigned)AT->getKeyword() : 3)
12848           << Deduced << DeducedDecl->getDeclName()
12849           << DT->getDeducedType() << D->getDeclName()
12850           << DeducedDecl->getInit()->getSourceRange()
12851           << D->getInit()->getSourceRange();
12852         D->setInvalidDecl();
12853         break;
12854       }
12855     }
12856   }
12857 
12858   ActOnDocumentableDecls(Group);
12859 
12860   return DeclGroupPtrTy::make(
12861       DeclGroupRef::Create(Context, Group.data(), Group.size()));
12862 }
12863 
12864 void Sema::ActOnDocumentableDecl(Decl *D) {
12865   ActOnDocumentableDecls(D);
12866 }
12867 
12868 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
12869   // Don't parse the comment if Doxygen diagnostics are ignored.
12870   if (Group.empty() || !Group[0])
12871     return;
12872 
12873   if (Diags.isIgnored(diag::warn_doc_param_not_found,
12874                       Group[0]->getLocation()) &&
12875       Diags.isIgnored(diag::warn_unknown_comment_command_name,
12876                       Group[0]->getLocation()))
12877     return;
12878 
12879   if (Group.size() >= 2) {
12880     // This is a decl group.  Normally it will contain only declarations
12881     // produced from declarator list.  But in case we have any definitions or
12882     // additional declaration references:
12883     //   'typedef struct S {} S;'
12884     //   'typedef struct S *S;'
12885     //   'struct S *pS;'
12886     // FinalizeDeclaratorGroup adds these as separate declarations.
12887     Decl *MaybeTagDecl = Group[0];
12888     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
12889       Group = Group.slice(1);
12890     }
12891   }
12892 
12893   // FIMXE: We assume every Decl in the group is in the same file.
12894   // This is false when preprocessor constructs the group from decls in
12895   // different files (e. g. macros or #include).
12896   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
12897 }
12898 
12899 /// Common checks for a parameter-declaration that should apply to both function
12900 /// parameters and non-type template parameters.
12901 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
12902   // Check that there are no default arguments inside the type of this
12903   // parameter.
12904   if (getLangOpts().CPlusPlus)
12905     CheckExtraCXXDefaultArguments(D);
12906 
12907   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
12908   if (D.getCXXScopeSpec().isSet()) {
12909     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
12910       << D.getCXXScopeSpec().getRange();
12911   }
12912 
12913   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
12914   // simple identifier except [...irrelevant cases...].
12915   switch (D.getName().getKind()) {
12916   case UnqualifiedIdKind::IK_Identifier:
12917     break;
12918 
12919   case UnqualifiedIdKind::IK_OperatorFunctionId:
12920   case UnqualifiedIdKind::IK_ConversionFunctionId:
12921   case UnqualifiedIdKind::IK_LiteralOperatorId:
12922   case UnqualifiedIdKind::IK_ConstructorName:
12923   case UnqualifiedIdKind::IK_DestructorName:
12924   case UnqualifiedIdKind::IK_ImplicitSelfParam:
12925   case UnqualifiedIdKind::IK_DeductionGuideName:
12926     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
12927       << GetNameForDeclarator(D).getName();
12928     break;
12929 
12930   case UnqualifiedIdKind::IK_TemplateId:
12931   case UnqualifiedIdKind::IK_ConstructorTemplateId:
12932     // GetNameForDeclarator would not produce a useful name in this case.
12933     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
12934     break;
12935   }
12936 }
12937 
12938 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
12939 /// to introduce parameters into function prototype scope.
12940 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
12941   const DeclSpec &DS = D.getDeclSpec();
12942 
12943   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
12944 
12945   // C++03 [dcl.stc]p2 also permits 'auto'.
12946   StorageClass SC = SC_None;
12947   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
12948     SC = SC_Register;
12949     // In C++11, the 'register' storage class specifier is deprecated.
12950     // In C++17, it is not allowed, but we tolerate it as an extension.
12951     if (getLangOpts().CPlusPlus11) {
12952       Diag(DS.getStorageClassSpecLoc(),
12953            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
12954                                      : diag::warn_deprecated_register)
12955         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
12956     }
12957   } else if (getLangOpts().CPlusPlus &&
12958              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
12959     SC = SC_Auto;
12960   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
12961     Diag(DS.getStorageClassSpecLoc(),
12962          diag::err_invalid_storage_class_in_func_decl);
12963     D.getMutableDeclSpec().ClearStorageClassSpecs();
12964   }
12965 
12966   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
12967     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
12968       << DeclSpec::getSpecifierName(TSCS);
12969   if (DS.isInlineSpecified())
12970     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
12971         << getLangOpts().CPlusPlus17;
12972   if (DS.hasConstexprSpecifier())
12973     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
12974         << 0 << D.getDeclSpec().getConstexprSpecifier();
12975 
12976   DiagnoseFunctionSpecifiers(DS);
12977 
12978   CheckFunctionOrTemplateParamDeclarator(S, D);
12979 
12980   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12981   QualType parmDeclType = TInfo->getType();
12982 
12983   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
12984   IdentifierInfo *II = D.getIdentifier();
12985   if (II) {
12986     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
12987                    ForVisibleRedeclaration);
12988     LookupName(R, S);
12989     if (R.isSingleResult()) {
12990       NamedDecl *PrevDecl = R.getFoundDecl();
12991       if (PrevDecl->isTemplateParameter()) {
12992         // Maybe we will complain about the shadowed template parameter.
12993         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12994         // Just pretend that we didn't see the previous declaration.
12995         PrevDecl = nullptr;
12996       } else if (S->isDeclScope(PrevDecl)) {
12997         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
12998         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12999 
13000         // Recover by removing the name
13001         II = nullptr;
13002         D.SetIdentifier(nullptr, D.getIdentifierLoc());
13003         D.setInvalidType(true);
13004       }
13005     }
13006   }
13007 
13008   // Temporarily put parameter variables in the translation unit, not
13009   // the enclosing context.  This prevents them from accidentally
13010   // looking like class members in C++.
13011   ParmVarDecl *New =
13012       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13013                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13014 
13015   if (D.isInvalidType())
13016     New->setInvalidDecl();
13017 
13018   assert(S->isFunctionPrototypeScope());
13019   assert(S->getFunctionPrototypeDepth() >= 1);
13020   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13021                     S->getNextFunctionPrototypeIndex());
13022 
13023   // Add the parameter declaration into this scope.
13024   S->AddDecl(New);
13025   if (II)
13026     IdResolver.AddDecl(New);
13027 
13028   ProcessDeclAttributes(S, New, D);
13029 
13030   if (D.getDeclSpec().isModulePrivateSpecified())
13031     Diag(New->getLocation(), diag::err_module_private_local)
13032       << 1 << New->getDeclName()
13033       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13034       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13035 
13036   if (New->hasAttr<BlocksAttr>()) {
13037     Diag(New->getLocation(), diag::err_block_on_nonlocal);
13038   }
13039   return New;
13040 }
13041 
13042 /// Synthesizes a variable for a parameter arising from a
13043 /// typedef.
13044 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13045                                               SourceLocation Loc,
13046                                               QualType T) {
13047   /* FIXME: setting StartLoc == Loc.
13048      Would it be worth to modify callers so as to provide proper source
13049      location for the unnamed parameters, embedding the parameter's type? */
13050   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13051                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
13052                                            SC_None, nullptr);
13053   Param->setImplicit();
13054   return Param;
13055 }
13056 
13057 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13058   // Don't diagnose unused-parameter errors in template instantiations; we
13059   // will already have done so in the template itself.
13060   if (inTemplateInstantiation())
13061     return;
13062 
13063   for (const ParmVarDecl *Parameter : Parameters) {
13064     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13065         !Parameter->hasAttr<UnusedAttr>()) {
13066       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13067         << Parameter->getDeclName();
13068     }
13069   }
13070 }
13071 
13072 void Sema::DiagnoseSizeOfParametersAndReturnValue(
13073     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13074   if (LangOpts.NumLargeByValueCopy == 0) // No check.
13075     return;
13076 
13077   // Warn if the return value is pass-by-value and larger than the specified
13078   // threshold.
13079   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13080     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13081     if (Size > LangOpts.NumLargeByValueCopy)
13082       Diag(D->getLocation(), diag::warn_return_value_size)
13083           << D->getDeclName() << Size;
13084   }
13085 
13086   // Warn if any parameter is pass-by-value and larger than the specified
13087   // threshold.
13088   for (const ParmVarDecl *Parameter : Parameters) {
13089     QualType T = Parameter->getType();
13090     if (T->isDependentType() || !T.isPODType(Context))
13091       continue;
13092     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13093     if (Size > LangOpts.NumLargeByValueCopy)
13094       Diag(Parameter->getLocation(), diag::warn_parameter_size)
13095           << Parameter->getDeclName() << Size;
13096   }
13097 }
13098 
13099 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13100                                   SourceLocation NameLoc, IdentifierInfo *Name,
13101                                   QualType T, TypeSourceInfo *TSInfo,
13102                                   StorageClass SC) {
13103   // In ARC, infer a lifetime qualifier for appropriate parameter types.
13104   if (getLangOpts().ObjCAutoRefCount &&
13105       T.getObjCLifetime() == Qualifiers::OCL_None &&
13106       T->isObjCLifetimeType()) {
13107 
13108     Qualifiers::ObjCLifetime lifetime;
13109 
13110     // Special cases for arrays:
13111     //   - if it's const, use __unsafe_unretained
13112     //   - otherwise, it's an error
13113     if (T->isArrayType()) {
13114       if (!T.isConstQualified()) {
13115         if (DelayedDiagnostics.shouldDelayDiagnostics())
13116           DelayedDiagnostics.add(
13117               sema::DelayedDiagnostic::makeForbiddenType(
13118               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13119         else
13120           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13121               << TSInfo->getTypeLoc().getSourceRange();
13122       }
13123       lifetime = Qualifiers::OCL_ExplicitNone;
13124     } else {
13125       lifetime = T->getObjCARCImplicitLifetime();
13126     }
13127     T = Context.getLifetimeQualifiedType(T, lifetime);
13128   }
13129 
13130   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13131                                          Context.getAdjustedParameterType(T),
13132                                          TSInfo, SC, nullptr);
13133 
13134   // Make a note if we created a new pack in the scope of a lambda, so that
13135   // we know that references to that pack must also be expanded within the
13136   // lambda scope.
13137   if (New->isParameterPack())
13138     if (auto *LSI = getEnclosingLambda())
13139       LSI->LocalPacks.push_back(New);
13140 
13141   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13142       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13143     checkNonTrivialCUnion(New->getType(), New->getLocation(),
13144                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13145 
13146   // Parameters can not be abstract class types.
13147   // For record types, this is done by the AbstractClassUsageDiagnoser once
13148   // the class has been completely parsed.
13149   if (!CurContext->isRecord() &&
13150       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13151                              AbstractParamType))
13152     New->setInvalidDecl();
13153 
13154   // Parameter declarators cannot be interface types. All ObjC objects are
13155   // passed by reference.
13156   if (T->isObjCObjectType()) {
13157     SourceLocation TypeEndLoc =
13158         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13159     Diag(NameLoc,
13160          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13161       << FixItHint::CreateInsertion(TypeEndLoc, "*");
13162     T = Context.getObjCObjectPointerType(T);
13163     New->setType(T);
13164   }
13165 
13166   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13167   // duration shall not be qualified by an address-space qualifier."
13168   // Since all parameters have automatic store duration, they can not have
13169   // an address space.
13170   if (T.getAddressSpace() != LangAS::Default &&
13171       // OpenCL allows function arguments declared to be an array of a type
13172       // to be qualified with an address space.
13173       !(getLangOpts().OpenCL &&
13174         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13175     Diag(NameLoc, diag::err_arg_with_address_space);
13176     New->setInvalidDecl();
13177   }
13178 
13179   return New;
13180 }
13181 
13182 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
13183                                            SourceLocation LocAfterDecls) {
13184   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
13185 
13186   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
13187   // for a K&R function.
13188   if (!FTI.hasPrototype) {
13189     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
13190       --i;
13191       if (FTI.Params[i].Param == nullptr) {
13192         SmallString<256> Code;
13193         llvm::raw_svector_ostream(Code)
13194             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
13195         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
13196             << FTI.Params[i].Ident
13197             << FixItHint::CreateInsertion(LocAfterDecls, Code);
13198 
13199         // Implicitly declare the argument as type 'int' for lack of a better
13200         // type.
13201         AttributeFactory attrs;
13202         DeclSpec DS(attrs);
13203         const char* PrevSpec; // unused
13204         unsigned DiagID; // unused
13205         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
13206                            DiagID, Context.getPrintingPolicy());
13207         // Use the identifier location for the type source range.
13208         DS.SetRangeStart(FTI.Params[i].IdentLoc);
13209         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
13210         Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
13211         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
13212         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
13213       }
13214     }
13215   }
13216 }
13217 
13218 Decl *
13219 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
13220                               MultiTemplateParamsArg TemplateParameterLists,
13221                               SkipBodyInfo *SkipBody) {
13222   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
13223   assert(D.isFunctionDeclarator() && "Not a function declarator!");
13224   Scope *ParentScope = FnBodyScope->getParent();
13225 
13226   D.setFunctionDefinitionKind(FDK_Definition);
13227   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
13228   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
13229 }
13230 
13231 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
13232   Consumer.HandleInlineFunctionDefinition(D);
13233 }
13234 
13235 static bool
13236 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
13237                                 const FunctionDecl *&PossiblePrototype) {
13238   // Don't warn about invalid declarations.
13239   if (FD->isInvalidDecl())
13240     return false;
13241 
13242   // Or declarations that aren't global.
13243   if (!FD->isGlobal())
13244     return false;
13245 
13246   // Don't warn about C++ member functions.
13247   if (isa<CXXMethodDecl>(FD))
13248     return false;
13249 
13250   // Don't warn about 'main'.
13251   if (FD->isMain())
13252     return false;
13253 
13254   // Don't warn about inline functions.
13255   if (FD->isInlined())
13256     return false;
13257 
13258   // Don't warn about function templates.
13259   if (FD->getDescribedFunctionTemplate())
13260     return false;
13261 
13262   // Don't warn about function template specializations.
13263   if (FD->isFunctionTemplateSpecialization())
13264     return false;
13265 
13266   // Don't warn for OpenCL kernels.
13267   if (FD->hasAttr<OpenCLKernelAttr>())
13268     return false;
13269 
13270   // Don't warn on explicitly deleted functions.
13271   if (FD->isDeleted())
13272     return false;
13273 
13274   for (const FunctionDecl *Prev = FD->getPreviousDecl();
13275        Prev; Prev = Prev->getPreviousDecl()) {
13276     // Ignore any declarations that occur in function or method
13277     // scope, because they aren't visible from the header.
13278     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
13279       continue;
13280 
13281     PossiblePrototype = Prev;
13282     return Prev->getType()->isFunctionNoProtoType();
13283   }
13284 
13285   return true;
13286 }
13287 
13288 void
13289 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
13290                                    const FunctionDecl *EffectiveDefinition,
13291                                    SkipBodyInfo *SkipBody) {
13292   const FunctionDecl *Definition = EffectiveDefinition;
13293   if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
13294     // If this is a friend function defined in a class template, it does not
13295     // have a body until it is used, nevertheless it is a definition, see
13296     // [temp.inst]p2:
13297     //
13298     // ... for the purpose of determining whether an instantiated redeclaration
13299     // is valid according to [basic.def.odr] and [class.mem], a declaration that
13300     // corresponds to a definition in the template is considered to be a
13301     // definition.
13302     //
13303     // The following code must produce redefinition error:
13304     //
13305     //     template<typename T> struct C20 { friend void func_20() {} };
13306     //     C20<int> c20i;
13307     //     void func_20() {}
13308     //
13309     for (auto I : FD->redecls()) {
13310       if (I != FD && !I->isInvalidDecl() &&
13311           I->getFriendObjectKind() != Decl::FOK_None) {
13312         if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
13313           if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
13314             // A merged copy of the same function, instantiated as a member of
13315             // the same class, is OK.
13316             if (declaresSameEntity(OrigFD, Original) &&
13317                 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
13318                                    cast<Decl>(FD->getLexicalDeclContext())))
13319               continue;
13320           }
13321 
13322           if (Original->isThisDeclarationADefinition()) {
13323             Definition = I;
13324             break;
13325           }
13326         }
13327       }
13328     }
13329   }
13330 
13331   if (!Definition)
13332     // Similar to friend functions a friend function template may be a
13333     // definition and do not have a body if it is instantiated in a class
13334     // template.
13335     if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
13336       for (auto I : FTD->redecls()) {
13337         auto D = cast<FunctionTemplateDecl>(I);
13338         if (D != FTD) {
13339           assert(!D->isThisDeclarationADefinition() &&
13340                  "More than one definition in redeclaration chain");
13341           if (D->getFriendObjectKind() != Decl::FOK_None)
13342             if (FunctionTemplateDecl *FT =
13343                                        D->getInstantiatedFromMemberTemplate()) {
13344               if (FT->isThisDeclarationADefinition()) {
13345                 Definition = D->getTemplatedDecl();
13346                 break;
13347               }
13348             }
13349         }
13350       }
13351     }
13352 
13353   if (!Definition)
13354     return;
13355 
13356   if (canRedefineFunction(Definition, getLangOpts()))
13357     return;
13358 
13359   // Don't emit an error when this is redefinition of a typo-corrected
13360   // definition.
13361   if (TypoCorrectedFunctionDefinitions.count(Definition))
13362     return;
13363 
13364   // If we don't have a visible definition of the function, and it's inline or
13365   // a template, skip the new definition.
13366   if (SkipBody && !hasVisibleDefinition(Definition) &&
13367       (Definition->getFormalLinkage() == InternalLinkage ||
13368        Definition->isInlined() ||
13369        Definition->getDescribedFunctionTemplate() ||
13370        Definition->getNumTemplateParameterLists())) {
13371     SkipBody->ShouldSkip = true;
13372     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
13373     if (auto *TD = Definition->getDescribedFunctionTemplate())
13374       makeMergedDefinitionVisible(TD);
13375     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
13376     return;
13377   }
13378 
13379   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
13380       Definition->getStorageClass() == SC_Extern)
13381     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
13382         << FD->getDeclName() << getLangOpts().CPlusPlus;
13383   else
13384     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
13385 
13386   Diag(Definition->getLocation(), diag::note_previous_definition);
13387   FD->setInvalidDecl();
13388 }
13389 
13390 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
13391                                    Sema &S) {
13392   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
13393 
13394   LambdaScopeInfo *LSI = S.PushLambdaScope();
13395   LSI->CallOperator = CallOperator;
13396   LSI->Lambda = LambdaClass;
13397   LSI->ReturnType = CallOperator->getReturnType();
13398   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
13399 
13400   if (LCD == LCD_None)
13401     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
13402   else if (LCD == LCD_ByCopy)
13403     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
13404   else if (LCD == LCD_ByRef)
13405     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
13406   DeclarationNameInfo DNI = CallOperator->getNameInfo();
13407 
13408   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
13409   LSI->Mutable = !CallOperator->isConst();
13410 
13411   // Add the captures to the LSI so they can be noted as already
13412   // captured within tryCaptureVar.
13413   auto I = LambdaClass->field_begin();
13414   for (const auto &C : LambdaClass->captures()) {
13415     if (C.capturesVariable()) {
13416       VarDecl *VD = C.getCapturedVar();
13417       if (VD->isInitCapture())
13418         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
13419       QualType CaptureType = VD->getType();
13420       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
13421       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
13422           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
13423           /*EllipsisLoc*/C.isPackExpansion()
13424                          ? C.getEllipsisLoc() : SourceLocation(),
13425           CaptureType, /*Invalid*/false);
13426 
13427     } else if (C.capturesThis()) {
13428       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
13429                           C.getCaptureKind() == LCK_StarThis);
13430     } else {
13431       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
13432                              I->getType());
13433     }
13434     ++I;
13435   }
13436 }
13437 
13438 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
13439                                     SkipBodyInfo *SkipBody) {
13440   if (!D) {
13441     // Parsing the function declaration failed in some way. Push on a fake scope
13442     // anyway so we can try to parse the function body.
13443     PushFunctionScope();
13444     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13445     return D;
13446   }
13447 
13448   FunctionDecl *FD = nullptr;
13449 
13450   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
13451     FD = FunTmpl->getTemplatedDecl();
13452   else
13453     FD = cast<FunctionDecl>(D);
13454 
13455   // Do not push if it is a lambda because one is already pushed when building
13456   // the lambda in ActOnStartOfLambdaDefinition().
13457   if (!isLambdaCallOperator(FD))
13458     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13459 
13460   // Check for defining attributes before the check for redefinition.
13461   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
13462     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
13463     FD->dropAttr<AliasAttr>();
13464     FD->setInvalidDecl();
13465   }
13466   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
13467     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
13468     FD->dropAttr<IFuncAttr>();
13469     FD->setInvalidDecl();
13470   }
13471 
13472   // See if this is a redefinition. If 'will have body' is already set, then
13473   // these checks were already performed when it was set.
13474   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
13475     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
13476 
13477     // If we're skipping the body, we're done. Don't enter the scope.
13478     if (SkipBody && SkipBody->ShouldSkip)
13479       return D;
13480   }
13481 
13482   // Mark this function as "will have a body eventually".  This lets users to
13483   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
13484   // this function.
13485   FD->setWillHaveBody();
13486 
13487   // If we are instantiating a generic lambda call operator, push
13488   // a LambdaScopeInfo onto the function stack.  But use the information
13489   // that's already been calculated (ActOnLambdaExpr) to prime the current
13490   // LambdaScopeInfo.
13491   // When the template operator is being specialized, the LambdaScopeInfo,
13492   // has to be properly restored so that tryCaptureVariable doesn't try
13493   // and capture any new variables. In addition when calculating potential
13494   // captures during transformation of nested lambdas, it is necessary to
13495   // have the LSI properly restored.
13496   if (isGenericLambdaCallOperatorSpecialization(FD)) {
13497     assert(inTemplateInstantiation() &&
13498            "There should be an active template instantiation on the stack "
13499            "when instantiating a generic lambda!");
13500     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
13501   } else {
13502     // Enter a new function scope
13503     PushFunctionScope();
13504   }
13505 
13506   // Builtin functions cannot be defined.
13507   if (unsigned BuiltinID = FD->getBuiltinID()) {
13508     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
13509         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
13510       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
13511       FD->setInvalidDecl();
13512     }
13513   }
13514 
13515   // The return type of a function definition must be complete
13516   // (C99 6.9.1p3, C++ [dcl.fct]p6).
13517   QualType ResultType = FD->getReturnType();
13518   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
13519       !FD->isInvalidDecl() &&
13520       RequireCompleteType(FD->getLocation(), ResultType,
13521                           diag::err_func_def_incomplete_result))
13522     FD->setInvalidDecl();
13523 
13524   if (FnBodyScope)
13525     PushDeclContext(FnBodyScope, FD);
13526 
13527   // Check the validity of our function parameters
13528   CheckParmsForFunctionDef(FD->parameters(),
13529                            /*CheckParameterNames=*/true);
13530 
13531   // Add non-parameter declarations already in the function to the current
13532   // scope.
13533   if (FnBodyScope) {
13534     for (Decl *NPD : FD->decls()) {
13535       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
13536       if (!NonParmDecl)
13537         continue;
13538       assert(!isa<ParmVarDecl>(NonParmDecl) &&
13539              "parameters should not be in newly created FD yet");
13540 
13541       // If the decl has a name, make it accessible in the current scope.
13542       if (NonParmDecl->getDeclName())
13543         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
13544 
13545       // Similarly, dive into enums and fish their constants out, making them
13546       // accessible in this scope.
13547       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
13548         for (auto *EI : ED->enumerators())
13549           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
13550       }
13551     }
13552   }
13553 
13554   // Introduce our parameters into the function scope
13555   for (auto Param : FD->parameters()) {
13556     Param->setOwningFunction(FD);
13557 
13558     // If this has an identifier, add it to the scope stack.
13559     if (Param->getIdentifier() && FnBodyScope) {
13560       CheckShadow(FnBodyScope, Param);
13561 
13562       PushOnScopeChains(Param, FnBodyScope);
13563     }
13564   }
13565 
13566   // Ensure that the function's exception specification is instantiated.
13567   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
13568     ResolveExceptionSpec(D->getLocation(), FPT);
13569 
13570   // dllimport cannot be applied to non-inline function definitions.
13571   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
13572       !FD->isTemplateInstantiation()) {
13573     assert(!FD->hasAttr<DLLExportAttr>());
13574     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
13575     FD->setInvalidDecl();
13576     return D;
13577   }
13578   // We want to attach documentation to original Decl (which might be
13579   // a function template).
13580   ActOnDocumentableDecl(D);
13581   if (getCurLexicalContext()->isObjCContainer() &&
13582       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
13583       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
13584     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
13585 
13586   return D;
13587 }
13588 
13589 /// Given the set of return statements within a function body,
13590 /// compute the variables that are subject to the named return value
13591 /// optimization.
13592 ///
13593 /// Each of the variables that is subject to the named return value
13594 /// optimization will be marked as NRVO variables in the AST, and any
13595 /// return statement that has a marked NRVO variable as its NRVO candidate can
13596 /// use the named return value optimization.
13597 ///
13598 /// This function applies a very simplistic algorithm for NRVO: if every return
13599 /// statement in the scope of a variable has the same NRVO candidate, that
13600 /// candidate is an NRVO variable.
13601 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
13602   ReturnStmt **Returns = Scope->Returns.data();
13603 
13604   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
13605     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
13606       if (!NRVOCandidate->isNRVOVariable())
13607         Returns[I]->setNRVOCandidate(nullptr);
13608     }
13609   }
13610 }
13611 
13612 bool Sema::canDelayFunctionBody(const Declarator &D) {
13613   // We can't delay parsing the body of a constexpr function template (yet).
13614   if (D.getDeclSpec().hasConstexprSpecifier())
13615     return false;
13616 
13617   // We can't delay parsing the body of a function template with a deduced
13618   // return type (yet).
13619   if (D.getDeclSpec().hasAutoTypeSpec()) {
13620     // If the placeholder introduces a non-deduced trailing return type,
13621     // we can still delay parsing it.
13622     if (D.getNumTypeObjects()) {
13623       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
13624       if (Outer.Kind == DeclaratorChunk::Function &&
13625           Outer.Fun.hasTrailingReturnType()) {
13626         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
13627         return Ty.isNull() || !Ty->isUndeducedType();
13628       }
13629     }
13630     return false;
13631   }
13632 
13633   return true;
13634 }
13635 
13636 bool Sema::canSkipFunctionBody(Decl *D) {
13637   // We cannot skip the body of a function (or function template) which is
13638   // constexpr, since we may need to evaluate its body in order to parse the
13639   // rest of the file.
13640   // We cannot skip the body of a function with an undeduced return type,
13641   // because any callers of that function need to know the type.
13642   if (const FunctionDecl *FD = D->getAsFunction()) {
13643     if (FD->isConstexpr())
13644       return false;
13645     // We can't simply call Type::isUndeducedType here, because inside template
13646     // auto can be deduced to a dependent type, which is not considered
13647     // "undeduced".
13648     if (FD->getReturnType()->getContainedDeducedType())
13649       return false;
13650   }
13651   return Consumer.shouldSkipFunctionBody(D);
13652 }
13653 
13654 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
13655   if (!Decl)
13656     return nullptr;
13657   if (FunctionDecl *FD = Decl->getAsFunction())
13658     FD->setHasSkippedBody();
13659   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
13660     MD->setHasSkippedBody();
13661   return Decl;
13662 }
13663 
13664 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
13665   return ActOnFinishFunctionBody(D, BodyArg, false);
13666 }
13667 
13668 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
13669 /// body.
13670 class ExitFunctionBodyRAII {
13671 public:
13672   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
13673   ~ExitFunctionBodyRAII() {
13674     if (!IsLambda)
13675       S.PopExpressionEvaluationContext();
13676   }
13677 
13678 private:
13679   Sema &S;
13680   bool IsLambda = false;
13681 };
13682 
13683 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
13684   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
13685 
13686   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
13687     if (EscapeInfo.count(BD))
13688       return EscapeInfo[BD];
13689 
13690     bool R = false;
13691     const BlockDecl *CurBD = BD;
13692 
13693     do {
13694       R = !CurBD->doesNotEscape();
13695       if (R)
13696         break;
13697       CurBD = CurBD->getParent()->getInnermostBlockDecl();
13698     } while (CurBD);
13699 
13700     return EscapeInfo[BD] = R;
13701   };
13702 
13703   // If the location where 'self' is implicitly retained is inside a escaping
13704   // block, emit a diagnostic.
13705   for (const std::pair<SourceLocation, const BlockDecl *> &P :
13706        S.ImplicitlyRetainedSelfLocs)
13707     if (IsOrNestedInEscapingBlock(P.second))
13708       S.Diag(P.first, diag::warn_implicitly_retains_self)
13709           << FixItHint::CreateInsertion(P.first, "self->");
13710 }
13711 
13712 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
13713                                     bool IsInstantiation) {
13714   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
13715 
13716   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13717   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
13718 
13719   if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
13720     CheckCompletedCoroutineBody(FD, Body);
13721 
13722   // Do not call PopExpressionEvaluationContext() if it is a lambda because one
13723   // is already popped when finishing the lambda in BuildLambdaExpr(). This is
13724   // meant to pop the context added in ActOnStartOfFunctionDef().
13725   ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
13726 
13727   if (FD) {
13728     FD->setBody(Body);
13729     FD->setWillHaveBody(false);
13730 
13731     if (getLangOpts().CPlusPlus14) {
13732       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
13733           FD->getReturnType()->isUndeducedType()) {
13734         // If the function has a deduced result type but contains no 'return'
13735         // statements, the result type as written must be exactly 'auto', and
13736         // the deduced result type is 'void'.
13737         if (!FD->getReturnType()->getAs<AutoType>()) {
13738           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
13739               << FD->getReturnType();
13740           FD->setInvalidDecl();
13741         } else {
13742           // Substitute 'void' for the 'auto' in the type.
13743           TypeLoc ResultType = getReturnTypeLoc(FD);
13744           Context.adjustDeducedFunctionResultType(
13745               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
13746         }
13747       }
13748     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
13749       // In C++11, we don't use 'auto' deduction rules for lambda call
13750       // operators because we don't support return type deduction.
13751       auto *LSI = getCurLambda();
13752       if (LSI->HasImplicitReturnType) {
13753         deduceClosureReturnType(*LSI);
13754 
13755         // C++11 [expr.prim.lambda]p4:
13756         //   [...] if there are no return statements in the compound-statement
13757         //   [the deduced type is] the type void
13758         QualType RetType =
13759             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
13760 
13761         // Update the return type to the deduced type.
13762         const FunctionProtoType *Proto =
13763             FD->getType()->getAs<FunctionProtoType>();
13764         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
13765                                             Proto->getExtProtoInfo()));
13766       }
13767     }
13768 
13769     // If the function implicitly returns zero (like 'main') or is naked,
13770     // don't complain about missing return statements.
13771     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
13772       WP.disableCheckFallThrough();
13773 
13774     // MSVC permits the use of pure specifier (=0) on function definition,
13775     // defined at class scope, warn about this non-standard construct.
13776     if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
13777       Diag(FD->getLocation(), diag::ext_pure_function_definition);
13778 
13779     if (!FD->isInvalidDecl()) {
13780       // Don't diagnose unused parameters of defaulted or deleted functions.
13781       if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
13782         DiagnoseUnusedParameters(FD->parameters());
13783       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
13784                                              FD->getReturnType(), FD);
13785 
13786       // If this is a structor, we need a vtable.
13787       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
13788         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
13789       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
13790         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
13791 
13792       // Try to apply the named return value optimization. We have to check
13793       // if we can do this here because lambdas keep return statements around
13794       // to deduce an implicit return type.
13795       if (FD->getReturnType()->isRecordType() &&
13796           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
13797         computeNRVO(Body, getCurFunction());
13798     }
13799 
13800     // GNU warning -Wmissing-prototypes:
13801     //   Warn if a global function is defined without a previous
13802     //   prototype declaration. This warning is issued even if the
13803     //   definition itself provides a prototype. The aim is to detect
13804     //   global functions that fail to be declared in header files.
13805     const FunctionDecl *PossiblePrototype = nullptr;
13806     if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
13807       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
13808 
13809       if (PossiblePrototype) {
13810         // We found a declaration that is not a prototype,
13811         // but that could be a zero-parameter prototype
13812         if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
13813           TypeLoc TL = TI->getTypeLoc();
13814           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
13815             Diag(PossiblePrototype->getLocation(),
13816                  diag::note_declaration_not_a_prototype)
13817                 << (FD->getNumParams() != 0)
13818                 << (FD->getNumParams() == 0
13819                         ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
13820                         : FixItHint{});
13821         }
13822       } else {
13823         Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13824             << /* function */ 1
13825             << (FD->getStorageClass() == SC_None
13826                     ? FixItHint::CreateInsertion(FD->getTypeSpecStartLoc(),
13827                                                  "static ")
13828                     : FixItHint{});
13829       }
13830 
13831       // GNU warning -Wstrict-prototypes
13832       //   Warn if K&R function is defined without a previous declaration.
13833       //   This warning is issued only if the definition itself does not provide
13834       //   a prototype. Only K&R definitions do not provide a prototype.
13835       //   An empty list in a function declarator that is part of a definition
13836       //   of that function specifies that the function has no parameters
13837       //   (C99 6.7.5.3p14)
13838       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
13839           !LangOpts.CPlusPlus) {
13840         TypeSourceInfo *TI = FD->getTypeSourceInfo();
13841         TypeLoc TL = TI->getTypeLoc();
13842         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
13843         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
13844       }
13845     }
13846 
13847     // Warn on CPUDispatch with an actual body.
13848     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
13849       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
13850         if (!CmpndBody->body_empty())
13851           Diag(CmpndBody->body_front()->getBeginLoc(),
13852                diag::warn_dispatch_body_ignored);
13853 
13854     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13855       const CXXMethodDecl *KeyFunction;
13856       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
13857           MD->isVirtual() &&
13858           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
13859           MD == KeyFunction->getCanonicalDecl()) {
13860         // Update the key-function state if necessary for this ABI.
13861         if (FD->isInlined() &&
13862             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13863           Context.setNonKeyFunction(MD);
13864 
13865           // If the newly-chosen key function is already defined, then we
13866           // need to mark the vtable as used retroactively.
13867           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
13868           const FunctionDecl *Definition;
13869           if (KeyFunction && KeyFunction->isDefined(Definition))
13870             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
13871         } else {
13872           // We just defined they key function; mark the vtable as used.
13873           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
13874         }
13875       }
13876     }
13877 
13878     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
13879            "Function parsing confused");
13880   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
13881     assert(MD == getCurMethodDecl() && "Method parsing confused");
13882     MD->setBody(Body);
13883     if (!MD->isInvalidDecl()) {
13884       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
13885                                              MD->getReturnType(), MD);
13886 
13887       if (Body)
13888         computeNRVO(Body, getCurFunction());
13889     }
13890     if (getCurFunction()->ObjCShouldCallSuper) {
13891       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
13892           << MD->getSelector().getAsString();
13893       getCurFunction()->ObjCShouldCallSuper = false;
13894     }
13895     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
13896       const ObjCMethodDecl *InitMethod = nullptr;
13897       bool isDesignated =
13898           MD->isDesignatedInitializerForTheInterface(&InitMethod);
13899       assert(isDesignated && InitMethod);
13900       (void)isDesignated;
13901 
13902       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
13903         auto IFace = MD->getClassInterface();
13904         if (!IFace)
13905           return false;
13906         auto SuperD = IFace->getSuperClass();
13907         if (!SuperD)
13908           return false;
13909         return SuperD->getIdentifier() ==
13910             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
13911       };
13912       // Don't issue this warning for unavailable inits or direct subclasses
13913       // of NSObject.
13914       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
13915         Diag(MD->getLocation(),
13916              diag::warn_objc_designated_init_missing_super_call);
13917         Diag(InitMethod->getLocation(),
13918              diag::note_objc_designated_init_marked_here);
13919       }
13920       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
13921     }
13922     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
13923       // Don't issue this warning for unavaialable inits.
13924       if (!MD->isUnavailable())
13925         Diag(MD->getLocation(),
13926              diag::warn_objc_secondary_init_missing_init_call);
13927       getCurFunction()->ObjCWarnForNoInitDelegation = false;
13928     }
13929 
13930     diagnoseImplicitlyRetainedSelf(*this);
13931   } else {
13932     // Parsing the function declaration failed in some way. Pop the fake scope
13933     // we pushed on.
13934     PopFunctionScopeInfo(ActivePolicy, dcl);
13935     return nullptr;
13936   }
13937 
13938   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13939     DiagnoseUnguardedAvailabilityViolations(dcl);
13940 
13941   assert(!getCurFunction()->ObjCShouldCallSuper &&
13942          "This should only be set for ObjC methods, which should have been "
13943          "handled in the block above.");
13944 
13945   // Verify and clean out per-function state.
13946   if (Body && (!FD || !FD->isDefaulted())) {
13947     // C++ constructors that have function-try-blocks can't have return
13948     // statements in the handlers of that block. (C++ [except.handle]p14)
13949     // Verify this.
13950     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
13951       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
13952 
13953     // Verify that gotos and switch cases don't jump into scopes illegally.
13954     if (getCurFunction()->NeedsScopeChecking() &&
13955         !PP.isCodeCompletionEnabled())
13956       DiagnoseInvalidJumps(Body);
13957 
13958     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
13959       if (!Destructor->getParent()->isDependentType())
13960         CheckDestructor(Destructor);
13961 
13962       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13963                                              Destructor->getParent());
13964     }
13965 
13966     // If any errors have occurred, clear out any temporaries that may have
13967     // been leftover. This ensures that these temporaries won't be picked up for
13968     // deletion in some later function.
13969     if (getDiagnostics().hasErrorOccurred() ||
13970         getDiagnostics().getSuppressAllDiagnostics()) {
13971       DiscardCleanupsInEvaluationContext();
13972     }
13973     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
13974         !isa<FunctionTemplateDecl>(dcl)) {
13975       // Since the body is valid, issue any analysis-based warnings that are
13976       // enabled.
13977       ActivePolicy = &WP;
13978     }
13979 
13980     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
13981         !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
13982       FD->setInvalidDecl();
13983 
13984     if (FD && FD->hasAttr<NakedAttr>()) {
13985       for (const Stmt *S : Body->children()) {
13986         // Allow local register variables without initializer as they don't
13987         // require prologue.
13988         bool RegisterVariables = false;
13989         if (auto *DS = dyn_cast<DeclStmt>(S)) {
13990           for (const auto *Decl : DS->decls()) {
13991             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
13992               RegisterVariables =
13993                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
13994               if (!RegisterVariables)
13995                 break;
13996             }
13997           }
13998         }
13999         if (RegisterVariables)
14000           continue;
14001         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14002           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14003           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14004           FD->setInvalidDecl();
14005           break;
14006         }
14007       }
14008     }
14009 
14010     assert(ExprCleanupObjects.size() ==
14011                ExprEvalContexts.back().NumCleanupObjects &&
14012            "Leftover temporaries in function");
14013     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
14014     assert(MaybeODRUseExprs.empty() &&
14015            "Leftover expressions for odr-use checking");
14016   }
14017 
14018   if (!IsInstantiation)
14019     PopDeclContext();
14020 
14021   PopFunctionScopeInfo(ActivePolicy, dcl);
14022   // If any errors have occurred, clear out any temporaries that may have
14023   // been leftover. This ensures that these temporaries won't be picked up for
14024   // deletion in some later function.
14025   if (getDiagnostics().hasErrorOccurred()) {
14026     DiscardCleanupsInEvaluationContext();
14027   }
14028 
14029   return dcl;
14030 }
14031 
14032 /// When we finish delayed parsing of an attribute, we must attach it to the
14033 /// relevant Decl.
14034 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14035                                        ParsedAttributes &Attrs) {
14036   // Always attach attributes to the underlying decl.
14037   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14038     D = TD->getTemplatedDecl();
14039   ProcessDeclAttributeList(S, D, Attrs);
14040 
14041   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14042     if (Method->isStatic())
14043       checkThisInStaticMemberFunctionAttributes(Method);
14044 }
14045 
14046 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14047 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
14048 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14049                                           IdentifierInfo &II, Scope *S) {
14050   // Find the scope in which the identifier is injected and the corresponding
14051   // DeclContext.
14052   // FIXME: C89 does not say what happens if there is no enclosing block scope.
14053   // In that case, we inject the declaration into the translation unit scope
14054   // instead.
14055   Scope *BlockScope = S;
14056   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14057     BlockScope = BlockScope->getParent();
14058 
14059   Scope *ContextScope = BlockScope;
14060   while (!ContextScope->getEntity())
14061     ContextScope = ContextScope->getParent();
14062   ContextRAII SavedContext(*this, ContextScope->getEntity());
14063 
14064   // Before we produce a declaration for an implicitly defined
14065   // function, see whether there was a locally-scoped declaration of
14066   // this name as a function or variable. If so, use that
14067   // (non-visible) declaration, and complain about it.
14068   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14069   if (ExternCPrev) {
14070     // We still need to inject the function into the enclosing block scope so
14071     // that later (non-call) uses can see it.
14072     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14073 
14074     // C89 footnote 38:
14075     //   If in fact it is not defined as having type "function returning int",
14076     //   the behavior is undefined.
14077     if (!isa<FunctionDecl>(ExternCPrev) ||
14078         !Context.typesAreCompatible(
14079             cast<FunctionDecl>(ExternCPrev)->getType(),
14080             Context.getFunctionNoProtoType(Context.IntTy))) {
14081       Diag(Loc, diag::ext_use_out_of_scope_declaration)
14082           << ExternCPrev << !getLangOpts().C99;
14083       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14084       return ExternCPrev;
14085     }
14086   }
14087 
14088   // Extension in C99.  Legal in C90, but warn about it.
14089   unsigned diag_id;
14090   if (II.getName().startswith("__builtin_"))
14091     diag_id = diag::warn_builtin_unknown;
14092   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14093   else if (getLangOpts().OpenCL)
14094     diag_id = diag::err_opencl_implicit_function_decl;
14095   else if (getLangOpts().C99)
14096     diag_id = diag::ext_implicit_function_decl;
14097   else
14098     diag_id = diag::warn_implicit_function_decl;
14099   Diag(Loc, diag_id) << &II;
14100 
14101   // If we found a prior declaration of this function, don't bother building
14102   // another one. We've already pushed that one into scope, so there's nothing
14103   // more to do.
14104   if (ExternCPrev)
14105     return ExternCPrev;
14106 
14107   // Because typo correction is expensive, only do it if the implicit
14108   // function declaration is going to be treated as an error.
14109   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
14110     TypoCorrection Corrected;
14111     DeclFilterCCC<FunctionDecl> CCC{};
14112     if (S && (Corrected =
14113                   CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
14114                               S, nullptr, CCC, CTK_NonError)))
14115       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
14116                    /*ErrorRecovery*/false);
14117   }
14118 
14119   // Set a Declarator for the implicit definition: int foo();
14120   const char *Dummy;
14121   AttributeFactory attrFactory;
14122   DeclSpec DS(attrFactory);
14123   unsigned DiagID;
14124   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
14125                                   Context.getPrintingPolicy());
14126   (void)Error; // Silence warning.
14127   assert(!Error && "Error setting up implicit decl!");
14128   SourceLocation NoLoc;
14129   Declarator D(DS, DeclaratorContext::BlockContext);
14130   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
14131                                              /*IsAmbiguous=*/false,
14132                                              /*LParenLoc=*/NoLoc,
14133                                              /*Params=*/nullptr,
14134                                              /*NumParams=*/0,
14135                                              /*EllipsisLoc=*/NoLoc,
14136                                              /*RParenLoc=*/NoLoc,
14137                                              /*RefQualifierIsLvalueRef=*/true,
14138                                              /*RefQualifierLoc=*/NoLoc,
14139                                              /*MutableLoc=*/NoLoc, EST_None,
14140                                              /*ESpecRange=*/SourceRange(),
14141                                              /*Exceptions=*/nullptr,
14142                                              /*ExceptionRanges=*/nullptr,
14143                                              /*NumExceptions=*/0,
14144                                              /*NoexceptExpr=*/nullptr,
14145                                              /*ExceptionSpecTokens=*/nullptr,
14146                                              /*DeclsInPrototype=*/None, Loc,
14147                                              Loc, D),
14148                 std::move(DS.getAttributes()), SourceLocation());
14149   D.SetIdentifier(&II, Loc);
14150 
14151   // Insert this function into the enclosing block scope.
14152   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
14153   FD->setImplicit();
14154 
14155   AddKnownFunctionAttributes(FD);
14156 
14157   return FD;
14158 }
14159 
14160 /// Adds any function attributes that we know a priori based on
14161 /// the declaration of this function.
14162 ///
14163 /// These attributes can apply both to implicitly-declared builtins
14164 /// (like __builtin___printf_chk) or to library-declared functions
14165 /// like NSLog or printf.
14166 ///
14167 /// We need to check for duplicate attributes both here and where user-written
14168 /// attributes are applied to declarations.
14169 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
14170   if (FD->isInvalidDecl())
14171     return;
14172 
14173   // If this is a built-in function, map its builtin attributes to
14174   // actual attributes.
14175   if (unsigned BuiltinID = FD->getBuiltinID()) {
14176     // Handle printf-formatting attributes.
14177     unsigned FormatIdx;
14178     bool HasVAListArg;
14179     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
14180       if (!FD->hasAttr<FormatAttr>()) {
14181         const char *fmt = "printf";
14182         unsigned int NumParams = FD->getNumParams();
14183         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
14184             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
14185           fmt = "NSString";
14186         FD->addAttr(FormatAttr::CreateImplicit(Context,
14187                                                &Context.Idents.get(fmt),
14188                                                FormatIdx+1,
14189                                                HasVAListArg ? 0 : FormatIdx+2,
14190                                                FD->getLocation()));
14191       }
14192     }
14193     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
14194                                              HasVAListArg)) {
14195      if (!FD->hasAttr<FormatAttr>())
14196        FD->addAttr(FormatAttr::CreateImplicit(Context,
14197                                               &Context.Idents.get("scanf"),
14198                                               FormatIdx+1,
14199                                               HasVAListArg ? 0 : FormatIdx+2,
14200                                               FD->getLocation()));
14201     }
14202 
14203     // Handle automatically recognized callbacks.
14204     SmallVector<int, 4> Encoding;
14205     if (!FD->hasAttr<CallbackAttr>() &&
14206         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
14207       FD->addAttr(CallbackAttr::CreateImplicit(
14208           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
14209 
14210     // Mark const if we don't care about errno and that is the only thing
14211     // preventing the function from being const. This allows IRgen to use LLVM
14212     // intrinsics for such functions.
14213     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
14214         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
14215       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14216 
14217     // We make "fma" on some platforms const because we know it does not set
14218     // errno in those environments even though it could set errno based on the
14219     // C standard.
14220     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
14221     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
14222         !FD->hasAttr<ConstAttr>()) {
14223       switch (BuiltinID) {
14224       case Builtin::BI__builtin_fma:
14225       case Builtin::BI__builtin_fmaf:
14226       case Builtin::BI__builtin_fmal:
14227       case Builtin::BIfma:
14228       case Builtin::BIfmaf:
14229       case Builtin::BIfmal:
14230         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14231         break;
14232       default:
14233         break;
14234       }
14235     }
14236 
14237     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
14238         !FD->hasAttr<ReturnsTwiceAttr>())
14239       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
14240                                          FD->getLocation()));
14241     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
14242       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14243     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
14244       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
14245     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
14246       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14247     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
14248         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
14249       // Add the appropriate attribute, depending on the CUDA compilation mode
14250       // and which target the builtin belongs to. For example, during host
14251       // compilation, aux builtins are __device__, while the rest are __host__.
14252       if (getLangOpts().CUDAIsDevice !=
14253           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
14254         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
14255       else
14256         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
14257     }
14258   }
14259 
14260   // If C++ exceptions are enabled but we are told extern "C" functions cannot
14261   // throw, add an implicit nothrow attribute to any extern "C" function we come
14262   // across.
14263   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
14264       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
14265     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
14266     if (!FPT || FPT->getExceptionSpecType() == EST_None)
14267       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14268   }
14269 
14270   IdentifierInfo *Name = FD->getIdentifier();
14271   if (!Name)
14272     return;
14273   if ((!getLangOpts().CPlusPlus &&
14274        FD->getDeclContext()->isTranslationUnit()) ||
14275       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
14276        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
14277        LinkageSpecDecl::lang_c)) {
14278     // Okay: this could be a libc/libm/Objective-C function we know
14279     // about.
14280   } else
14281     return;
14282 
14283   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
14284     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
14285     // target-specific builtins, perhaps?
14286     if (!FD->hasAttr<FormatAttr>())
14287       FD->addAttr(FormatAttr::CreateImplicit(Context,
14288                                              &Context.Idents.get("printf"), 2,
14289                                              Name->isStr("vasprintf") ? 0 : 3,
14290                                              FD->getLocation()));
14291   }
14292 
14293   if (Name->isStr("__CFStringMakeConstantString")) {
14294     // We already have a __builtin___CFStringMakeConstantString,
14295     // but builds that use -fno-constant-cfstrings don't go through that.
14296     if (!FD->hasAttr<FormatArgAttr>())
14297       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
14298                                                 FD->getLocation()));
14299   }
14300 }
14301 
14302 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
14303                                     TypeSourceInfo *TInfo) {
14304   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
14305   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
14306 
14307   if (!TInfo) {
14308     assert(D.isInvalidType() && "no declarator info for valid type");
14309     TInfo = Context.getTrivialTypeSourceInfo(T);
14310   }
14311 
14312   // Scope manipulation handled by caller.
14313   TypedefDecl *NewTD =
14314       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
14315                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
14316 
14317   // Bail out immediately if we have an invalid declaration.
14318   if (D.isInvalidType()) {
14319     NewTD->setInvalidDecl();
14320     return NewTD;
14321   }
14322 
14323   if (D.getDeclSpec().isModulePrivateSpecified()) {
14324     if (CurContext->isFunctionOrMethod())
14325       Diag(NewTD->getLocation(), diag::err_module_private_local)
14326         << 2 << NewTD->getDeclName()
14327         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14328         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
14329     else
14330       NewTD->setModulePrivate();
14331   }
14332 
14333   // C++ [dcl.typedef]p8:
14334   //   If the typedef declaration defines an unnamed class (or
14335   //   enum), the first typedef-name declared by the declaration
14336   //   to be that class type (or enum type) is used to denote the
14337   //   class type (or enum type) for linkage purposes only.
14338   // We need to check whether the type was declared in the declaration.
14339   switch (D.getDeclSpec().getTypeSpecType()) {
14340   case TST_enum:
14341   case TST_struct:
14342   case TST_interface:
14343   case TST_union:
14344   case TST_class: {
14345     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
14346     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
14347     break;
14348   }
14349 
14350   default:
14351     break;
14352   }
14353 
14354   return NewTD;
14355 }
14356 
14357 /// Check that this is a valid underlying type for an enum declaration.
14358 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
14359   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
14360   QualType T = TI->getType();
14361 
14362   if (T->isDependentType())
14363     return false;
14364 
14365   if (const BuiltinType *BT = T->getAs<BuiltinType>())
14366     if (BT->isInteger())
14367       return false;
14368 
14369   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
14370   return true;
14371 }
14372 
14373 /// Check whether this is a valid redeclaration of a previous enumeration.
14374 /// \return true if the redeclaration was invalid.
14375 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
14376                                   QualType EnumUnderlyingTy, bool IsFixed,
14377                                   const EnumDecl *Prev) {
14378   if (IsScoped != Prev->isScoped()) {
14379     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
14380       << Prev->isScoped();
14381     Diag(Prev->getLocation(), diag::note_previous_declaration);
14382     return true;
14383   }
14384 
14385   if (IsFixed && Prev->isFixed()) {
14386     if (!EnumUnderlyingTy->isDependentType() &&
14387         !Prev->getIntegerType()->isDependentType() &&
14388         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
14389                                         Prev->getIntegerType())) {
14390       // TODO: Highlight the underlying type of the redeclaration.
14391       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
14392         << EnumUnderlyingTy << Prev->getIntegerType();
14393       Diag(Prev->getLocation(), diag::note_previous_declaration)
14394           << Prev->getIntegerTypeRange();
14395       return true;
14396     }
14397   } else if (IsFixed != Prev->isFixed()) {
14398     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
14399       << Prev->isFixed();
14400     Diag(Prev->getLocation(), diag::note_previous_declaration);
14401     return true;
14402   }
14403 
14404   return false;
14405 }
14406 
14407 /// Get diagnostic %select index for tag kind for
14408 /// redeclaration diagnostic message.
14409 /// WARNING: Indexes apply to particular diagnostics only!
14410 ///
14411 /// \returns diagnostic %select index.
14412 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
14413   switch (Tag) {
14414   case TTK_Struct: return 0;
14415   case TTK_Interface: return 1;
14416   case TTK_Class:  return 2;
14417   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
14418   }
14419 }
14420 
14421 /// Determine if tag kind is a class-key compatible with
14422 /// class for redeclaration (class, struct, or __interface).
14423 ///
14424 /// \returns true iff the tag kind is compatible.
14425 static bool isClassCompatTagKind(TagTypeKind Tag)
14426 {
14427   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
14428 }
14429 
14430 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
14431                                              TagTypeKind TTK) {
14432   if (isa<TypedefDecl>(PrevDecl))
14433     return NTK_Typedef;
14434   else if (isa<TypeAliasDecl>(PrevDecl))
14435     return NTK_TypeAlias;
14436   else if (isa<ClassTemplateDecl>(PrevDecl))
14437     return NTK_Template;
14438   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
14439     return NTK_TypeAliasTemplate;
14440   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
14441     return NTK_TemplateTemplateArgument;
14442   switch (TTK) {
14443   case TTK_Struct:
14444   case TTK_Interface:
14445   case TTK_Class:
14446     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
14447   case TTK_Union:
14448     return NTK_NonUnion;
14449   case TTK_Enum:
14450     return NTK_NonEnum;
14451   }
14452   llvm_unreachable("invalid TTK");
14453 }
14454 
14455 /// Determine whether a tag with a given kind is acceptable
14456 /// as a redeclaration of the given tag declaration.
14457 ///
14458 /// \returns true if the new tag kind is acceptable, false otherwise.
14459 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
14460                                         TagTypeKind NewTag, bool isDefinition,
14461                                         SourceLocation NewTagLoc,
14462                                         const IdentifierInfo *Name) {
14463   // C++ [dcl.type.elab]p3:
14464   //   The class-key or enum keyword present in the
14465   //   elaborated-type-specifier shall agree in kind with the
14466   //   declaration to which the name in the elaborated-type-specifier
14467   //   refers. This rule also applies to the form of
14468   //   elaborated-type-specifier that declares a class-name or
14469   //   friend class since it can be construed as referring to the
14470   //   definition of the class. Thus, in any
14471   //   elaborated-type-specifier, the enum keyword shall be used to
14472   //   refer to an enumeration (7.2), the union class-key shall be
14473   //   used to refer to a union (clause 9), and either the class or
14474   //   struct class-key shall be used to refer to a class (clause 9)
14475   //   declared using the class or struct class-key.
14476   TagTypeKind OldTag = Previous->getTagKind();
14477   if (OldTag != NewTag &&
14478       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
14479     return false;
14480 
14481   // Tags are compatible, but we might still want to warn on mismatched tags.
14482   // Non-class tags can't be mismatched at this point.
14483   if (!isClassCompatTagKind(NewTag))
14484     return true;
14485 
14486   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
14487   // by our warning analysis. We don't want to warn about mismatches with (eg)
14488   // declarations in system headers that are designed to be specialized, but if
14489   // a user asks us to warn, we should warn if their code contains mismatched
14490   // declarations.
14491   auto IsIgnoredLoc = [&](SourceLocation Loc) {
14492     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
14493                                       Loc);
14494   };
14495   if (IsIgnoredLoc(NewTagLoc))
14496     return true;
14497 
14498   auto IsIgnored = [&](const TagDecl *Tag) {
14499     return IsIgnoredLoc(Tag->getLocation());
14500   };
14501   while (IsIgnored(Previous)) {
14502     Previous = Previous->getPreviousDecl();
14503     if (!Previous)
14504       return true;
14505     OldTag = Previous->getTagKind();
14506   }
14507 
14508   bool isTemplate = false;
14509   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
14510     isTemplate = Record->getDescribedClassTemplate();
14511 
14512   if (inTemplateInstantiation()) {
14513     if (OldTag != NewTag) {
14514       // In a template instantiation, do not offer fix-its for tag mismatches
14515       // since they usually mess up the template instead of fixing the problem.
14516       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14517         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14518         << getRedeclDiagFromTagKind(OldTag);
14519       // FIXME: Note previous location?
14520     }
14521     return true;
14522   }
14523 
14524   if (isDefinition) {
14525     // On definitions, check all previous tags and issue a fix-it for each
14526     // one that doesn't match the current tag.
14527     if (Previous->getDefinition()) {
14528       // Don't suggest fix-its for redefinitions.
14529       return true;
14530     }
14531 
14532     bool previousMismatch = false;
14533     for (const TagDecl *I : Previous->redecls()) {
14534       if (I->getTagKind() != NewTag) {
14535         // Ignore previous declarations for which the warning was disabled.
14536         if (IsIgnored(I))
14537           continue;
14538 
14539         if (!previousMismatch) {
14540           previousMismatch = true;
14541           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
14542             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14543             << getRedeclDiagFromTagKind(I->getTagKind());
14544         }
14545         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
14546           << getRedeclDiagFromTagKind(NewTag)
14547           << FixItHint::CreateReplacement(I->getInnerLocStart(),
14548                TypeWithKeyword::getTagTypeKindName(NewTag));
14549       }
14550     }
14551     return true;
14552   }
14553 
14554   // Identify the prevailing tag kind: this is the kind of the definition (if
14555   // there is a non-ignored definition), or otherwise the kind of the prior
14556   // (non-ignored) declaration.
14557   const TagDecl *PrevDef = Previous->getDefinition();
14558   if (PrevDef && IsIgnored(PrevDef))
14559     PrevDef = nullptr;
14560   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
14561   if (Redecl->getTagKind() != NewTag) {
14562     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14563       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14564       << getRedeclDiagFromTagKind(OldTag);
14565     Diag(Redecl->getLocation(), diag::note_previous_use);
14566 
14567     // If there is a previous definition, suggest a fix-it.
14568     if (PrevDef) {
14569       Diag(NewTagLoc, diag::note_struct_class_suggestion)
14570         << getRedeclDiagFromTagKind(Redecl->getTagKind())
14571         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
14572              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
14573     }
14574   }
14575 
14576   return true;
14577 }
14578 
14579 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
14580 /// from an outer enclosing namespace or file scope inside a friend declaration.
14581 /// This should provide the commented out code in the following snippet:
14582 ///   namespace N {
14583 ///     struct X;
14584 ///     namespace M {
14585 ///       struct Y { friend struct /*N::*/ X; };
14586 ///     }
14587 ///   }
14588 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
14589                                          SourceLocation NameLoc) {
14590   // While the decl is in a namespace, do repeated lookup of that name and see
14591   // if we get the same namespace back.  If we do not, continue until
14592   // translation unit scope, at which point we have a fully qualified NNS.
14593   SmallVector<IdentifierInfo *, 4> Namespaces;
14594   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14595   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
14596     // This tag should be declared in a namespace, which can only be enclosed by
14597     // other namespaces.  Bail if there's an anonymous namespace in the chain.
14598     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
14599     if (!Namespace || Namespace->isAnonymousNamespace())
14600       return FixItHint();
14601     IdentifierInfo *II = Namespace->getIdentifier();
14602     Namespaces.push_back(II);
14603     NamedDecl *Lookup = SemaRef.LookupSingleName(
14604         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
14605     if (Lookup == Namespace)
14606       break;
14607   }
14608 
14609   // Once we have all the namespaces, reverse them to go outermost first, and
14610   // build an NNS.
14611   SmallString<64> Insertion;
14612   llvm::raw_svector_ostream OS(Insertion);
14613   if (DC->isTranslationUnit())
14614     OS << "::";
14615   std::reverse(Namespaces.begin(), Namespaces.end());
14616   for (auto *II : Namespaces)
14617     OS << II->getName() << "::";
14618   return FixItHint::CreateInsertion(NameLoc, Insertion);
14619 }
14620 
14621 /// Determine whether a tag originally declared in context \p OldDC can
14622 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
14623 /// found a declaration in \p OldDC as a previous decl, perhaps through a
14624 /// using-declaration).
14625 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
14626                                          DeclContext *NewDC) {
14627   OldDC = OldDC->getRedeclContext();
14628   NewDC = NewDC->getRedeclContext();
14629 
14630   if (OldDC->Equals(NewDC))
14631     return true;
14632 
14633   // In MSVC mode, we allow a redeclaration if the contexts are related (either
14634   // encloses the other).
14635   if (S.getLangOpts().MSVCCompat &&
14636       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
14637     return true;
14638 
14639   return false;
14640 }
14641 
14642 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
14643 /// former case, Name will be non-null.  In the later case, Name will be null.
14644 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
14645 /// reference/declaration/definition of a tag.
14646 ///
14647 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
14648 /// trailing-type-specifier) other than one in an alias-declaration.
14649 ///
14650 /// \param SkipBody If non-null, will be set to indicate if the caller should
14651 /// skip the definition of this tag and treat it as if it were a declaration.
14652 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
14653                      SourceLocation KWLoc, CXXScopeSpec &SS,
14654                      IdentifierInfo *Name, SourceLocation NameLoc,
14655                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
14656                      SourceLocation ModulePrivateLoc,
14657                      MultiTemplateParamsArg TemplateParameterLists,
14658                      bool &OwnedDecl, bool &IsDependent,
14659                      SourceLocation ScopedEnumKWLoc,
14660                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
14661                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
14662                      SkipBodyInfo *SkipBody) {
14663   // If this is not a definition, it must have a name.
14664   IdentifierInfo *OrigName = Name;
14665   assert((Name != nullptr || TUK == TUK_Definition) &&
14666          "Nameless record must be a definition!");
14667   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
14668 
14669   OwnedDecl = false;
14670   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14671   bool ScopedEnum = ScopedEnumKWLoc.isValid();
14672 
14673   // FIXME: Check member specializations more carefully.
14674   bool isMemberSpecialization = false;
14675   bool Invalid = false;
14676 
14677   // We only need to do this matching if we have template parameters
14678   // or a scope specifier, which also conveniently avoids this work
14679   // for non-C++ cases.
14680   if (TemplateParameterLists.size() > 0 ||
14681       (SS.isNotEmpty() && TUK != TUK_Reference)) {
14682     if (TemplateParameterList *TemplateParams =
14683             MatchTemplateParametersToScopeSpecifier(
14684                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
14685                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
14686       if (Kind == TTK_Enum) {
14687         Diag(KWLoc, diag::err_enum_template);
14688         return nullptr;
14689       }
14690 
14691       if (TemplateParams->size() > 0) {
14692         // This is a declaration or definition of a class template (which may
14693         // be a member of another template).
14694 
14695         if (Invalid)
14696           return nullptr;
14697 
14698         OwnedDecl = false;
14699         DeclResult Result = CheckClassTemplate(
14700             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
14701             AS, ModulePrivateLoc,
14702             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
14703             TemplateParameterLists.data(), SkipBody);
14704         return Result.get();
14705       } else {
14706         // The "template<>" header is extraneous.
14707         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14708           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14709         isMemberSpecialization = true;
14710       }
14711     }
14712   }
14713 
14714   // Figure out the underlying type if this a enum declaration. We need to do
14715   // this early, because it's needed to detect if this is an incompatible
14716   // redeclaration.
14717   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
14718   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
14719 
14720   if (Kind == TTK_Enum) {
14721     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
14722       // No underlying type explicitly specified, or we failed to parse the
14723       // type, default to int.
14724       EnumUnderlying = Context.IntTy.getTypePtr();
14725     } else if (UnderlyingType.get()) {
14726       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
14727       // integral type; any cv-qualification is ignored.
14728       TypeSourceInfo *TI = nullptr;
14729       GetTypeFromParser(UnderlyingType.get(), &TI);
14730       EnumUnderlying = TI;
14731 
14732       if (CheckEnumUnderlyingType(TI))
14733         // Recover by falling back to int.
14734         EnumUnderlying = Context.IntTy.getTypePtr();
14735 
14736       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
14737                                           UPPC_FixedUnderlyingType))
14738         EnumUnderlying = Context.IntTy.getTypePtr();
14739 
14740     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
14741       // For MSVC ABI compatibility, unfixed enums must use an underlying type
14742       // of 'int'. However, if this is an unfixed forward declaration, don't set
14743       // the underlying type unless the user enables -fms-compatibility. This
14744       // makes unfixed forward declared enums incomplete and is more conforming.
14745       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
14746         EnumUnderlying = Context.IntTy.getTypePtr();
14747     }
14748   }
14749 
14750   DeclContext *SearchDC = CurContext;
14751   DeclContext *DC = CurContext;
14752   bool isStdBadAlloc = false;
14753   bool isStdAlignValT = false;
14754 
14755   RedeclarationKind Redecl = forRedeclarationInCurContext();
14756   if (TUK == TUK_Friend || TUK == TUK_Reference)
14757     Redecl = NotForRedeclaration;
14758 
14759   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
14760   /// implemented asks for structural equivalence checking, the returned decl
14761   /// here is passed back to the parser, allowing the tag body to be parsed.
14762   auto createTagFromNewDecl = [&]() -> TagDecl * {
14763     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
14764     // If there is an identifier, use the location of the identifier as the
14765     // location of the decl, otherwise use the location of the struct/union
14766     // keyword.
14767     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14768     TagDecl *New = nullptr;
14769 
14770     if (Kind == TTK_Enum) {
14771       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
14772                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
14773       // If this is an undefined enum, bail.
14774       if (TUK != TUK_Definition && !Invalid)
14775         return nullptr;
14776       if (EnumUnderlying) {
14777         EnumDecl *ED = cast<EnumDecl>(New);
14778         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
14779           ED->setIntegerTypeSourceInfo(TI);
14780         else
14781           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
14782         ED->setPromotionType(ED->getIntegerType());
14783       }
14784     } else { // struct/union
14785       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14786                                nullptr);
14787     }
14788 
14789     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14790       // Add alignment attributes if necessary; these attributes are checked
14791       // when the ASTContext lays out the structure.
14792       //
14793       // It is important for implementing the correct semantics that this
14794       // happen here (in ActOnTag). The #pragma pack stack is
14795       // maintained as a result of parser callbacks which can occur at
14796       // many points during the parsing of a struct declaration (because
14797       // the #pragma tokens are effectively skipped over during the
14798       // parsing of the struct).
14799       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
14800         AddAlignmentAttributesForRecord(RD);
14801         AddMsStructLayoutForRecord(RD);
14802       }
14803     }
14804     New->setLexicalDeclContext(CurContext);
14805     return New;
14806   };
14807 
14808   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
14809   if (Name && SS.isNotEmpty()) {
14810     // We have a nested-name tag ('struct foo::bar').
14811 
14812     // Check for invalid 'foo::'.
14813     if (SS.isInvalid()) {
14814       Name = nullptr;
14815       goto CreateNewDecl;
14816     }
14817 
14818     // If this is a friend or a reference to a class in a dependent
14819     // context, don't try to make a decl for it.
14820     if (TUK == TUK_Friend || TUK == TUK_Reference) {
14821       DC = computeDeclContext(SS, false);
14822       if (!DC) {
14823         IsDependent = true;
14824         return nullptr;
14825       }
14826     } else {
14827       DC = computeDeclContext(SS, true);
14828       if (!DC) {
14829         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
14830           << SS.getRange();
14831         return nullptr;
14832       }
14833     }
14834 
14835     if (RequireCompleteDeclContext(SS, DC))
14836       return nullptr;
14837 
14838     SearchDC = DC;
14839     // Look-up name inside 'foo::'.
14840     LookupQualifiedName(Previous, DC);
14841 
14842     if (Previous.isAmbiguous())
14843       return nullptr;
14844 
14845     if (Previous.empty()) {
14846       // Name lookup did not find anything. However, if the
14847       // nested-name-specifier refers to the current instantiation,
14848       // and that current instantiation has any dependent base
14849       // classes, we might find something at instantiation time: treat
14850       // this as a dependent elaborated-type-specifier.
14851       // But this only makes any sense for reference-like lookups.
14852       if (Previous.wasNotFoundInCurrentInstantiation() &&
14853           (TUK == TUK_Reference || TUK == TUK_Friend)) {
14854         IsDependent = true;
14855         return nullptr;
14856       }
14857 
14858       // A tag 'foo::bar' must already exist.
14859       Diag(NameLoc, diag::err_not_tag_in_scope)
14860         << Kind << Name << DC << SS.getRange();
14861       Name = nullptr;
14862       Invalid = true;
14863       goto CreateNewDecl;
14864     }
14865   } else if (Name) {
14866     // C++14 [class.mem]p14:
14867     //   If T is the name of a class, then each of the following shall have a
14868     //   name different from T:
14869     //    -- every member of class T that is itself a type
14870     if (TUK != TUK_Reference && TUK != TUK_Friend &&
14871         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
14872       return nullptr;
14873 
14874     // If this is a named struct, check to see if there was a previous forward
14875     // declaration or definition.
14876     // FIXME: We're looking into outer scopes here, even when we
14877     // shouldn't be. Doing so can result in ambiguities that we
14878     // shouldn't be diagnosing.
14879     LookupName(Previous, S);
14880 
14881     // When declaring or defining a tag, ignore ambiguities introduced
14882     // by types using'ed into this scope.
14883     if (Previous.isAmbiguous() &&
14884         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
14885       LookupResult::Filter F = Previous.makeFilter();
14886       while (F.hasNext()) {
14887         NamedDecl *ND = F.next();
14888         if (!ND->getDeclContext()->getRedeclContext()->Equals(
14889                 SearchDC->getRedeclContext()))
14890           F.erase();
14891       }
14892       F.done();
14893     }
14894 
14895     // C++11 [namespace.memdef]p3:
14896     //   If the name in a friend declaration is neither qualified nor
14897     //   a template-id and the declaration is a function or an
14898     //   elaborated-type-specifier, the lookup to determine whether
14899     //   the entity has been previously declared shall not consider
14900     //   any scopes outside the innermost enclosing namespace.
14901     //
14902     // MSVC doesn't implement the above rule for types, so a friend tag
14903     // declaration may be a redeclaration of a type declared in an enclosing
14904     // scope.  They do implement this rule for friend functions.
14905     //
14906     // Does it matter that this should be by scope instead of by
14907     // semantic context?
14908     if (!Previous.empty() && TUK == TUK_Friend) {
14909       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
14910       LookupResult::Filter F = Previous.makeFilter();
14911       bool FriendSawTagOutsideEnclosingNamespace = false;
14912       while (F.hasNext()) {
14913         NamedDecl *ND = F.next();
14914         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14915         if (DC->isFileContext() &&
14916             !EnclosingNS->Encloses(ND->getDeclContext())) {
14917           if (getLangOpts().MSVCCompat)
14918             FriendSawTagOutsideEnclosingNamespace = true;
14919           else
14920             F.erase();
14921         }
14922       }
14923       F.done();
14924 
14925       // Diagnose this MSVC extension in the easy case where lookup would have
14926       // unambiguously found something outside the enclosing namespace.
14927       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
14928         NamedDecl *ND = Previous.getFoundDecl();
14929         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
14930             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
14931       }
14932     }
14933 
14934     // Note:  there used to be some attempt at recovery here.
14935     if (Previous.isAmbiguous())
14936       return nullptr;
14937 
14938     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
14939       // FIXME: This makes sure that we ignore the contexts associated
14940       // with C structs, unions, and enums when looking for a matching
14941       // tag declaration or definition. See the similar lookup tweak
14942       // in Sema::LookupName; is there a better way to deal with this?
14943       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
14944         SearchDC = SearchDC->getParent();
14945     }
14946   }
14947 
14948   if (Previous.isSingleResult() &&
14949       Previous.getFoundDecl()->isTemplateParameter()) {
14950     // Maybe we will complain about the shadowed template parameter.
14951     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
14952     // Just pretend that we didn't see the previous declaration.
14953     Previous.clear();
14954   }
14955 
14956   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
14957       DC->Equals(getStdNamespace())) {
14958     if (Name->isStr("bad_alloc")) {
14959       // This is a declaration of or a reference to "std::bad_alloc".
14960       isStdBadAlloc = true;
14961 
14962       // If std::bad_alloc has been implicitly declared (but made invisible to
14963       // name lookup), fill in this implicit declaration as the previous
14964       // declaration, so that the declarations get chained appropriately.
14965       if (Previous.empty() && StdBadAlloc)
14966         Previous.addDecl(getStdBadAlloc());
14967     } else if (Name->isStr("align_val_t")) {
14968       isStdAlignValT = true;
14969       if (Previous.empty() && StdAlignValT)
14970         Previous.addDecl(getStdAlignValT());
14971     }
14972   }
14973 
14974   // If we didn't find a previous declaration, and this is a reference
14975   // (or friend reference), move to the correct scope.  In C++, we
14976   // also need to do a redeclaration lookup there, just in case
14977   // there's a shadow friend decl.
14978   if (Name && Previous.empty() &&
14979       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
14980     if (Invalid) goto CreateNewDecl;
14981     assert(SS.isEmpty());
14982 
14983     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
14984       // C++ [basic.scope.pdecl]p5:
14985       //   -- for an elaborated-type-specifier of the form
14986       //
14987       //          class-key identifier
14988       //
14989       //      if the elaborated-type-specifier is used in the
14990       //      decl-specifier-seq or parameter-declaration-clause of a
14991       //      function defined in namespace scope, the identifier is
14992       //      declared as a class-name in the namespace that contains
14993       //      the declaration; otherwise, except as a friend
14994       //      declaration, the identifier is declared in the smallest
14995       //      non-class, non-function-prototype scope that contains the
14996       //      declaration.
14997       //
14998       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
14999       // C structs and unions.
15000       //
15001       // It is an error in C++ to declare (rather than define) an enum
15002       // type, including via an elaborated type specifier.  We'll
15003       // diagnose that later; for now, declare the enum in the same
15004       // scope as we would have picked for any other tag type.
15005       //
15006       // GNU C also supports this behavior as part of its incomplete
15007       // enum types extension, while GNU C++ does not.
15008       //
15009       // Find the context where we'll be declaring the tag.
15010       // FIXME: We would like to maintain the current DeclContext as the
15011       // lexical context,
15012       SearchDC = getTagInjectionContext(SearchDC);
15013 
15014       // Find the scope where we'll be declaring the tag.
15015       S = getTagInjectionScope(S, getLangOpts());
15016     } else {
15017       assert(TUK == TUK_Friend);
15018       // C++ [namespace.memdef]p3:
15019       //   If a friend declaration in a non-local class first declares a
15020       //   class or function, the friend class or function is a member of
15021       //   the innermost enclosing namespace.
15022       SearchDC = SearchDC->getEnclosingNamespaceContext();
15023     }
15024 
15025     // In C++, we need to do a redeclaration lookup to properly
15026     // diagnose some problems.
15027     // FIXME: redeclaration lookup is also used (with and without C++) to find a
15028     // hidden declaration so that we don't get ambiguity errors when using a
15029     // type declared by an elaborated-type-specifier.  In C that is not correct
15030     // and we should instead merge compatible types found by lookup.
15031     if (getLangOpts().CPlusPlus) {
15032       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15033       LookupQualifiedName(Previous, SearchDC);
15034     } else {
15035       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15036       LookupName(Previous, S);
15037     }
15038   }
15039 
15040   // If we have a known previous declaration to use, then use it.
15041   if (Previous.empty() && SkipBody && SkipBody->Previous)
15042     Previous.addDecl(SkipBody->Previous);
15043 
15044   if (!Previous.empty()) {
15045     NamedDecl *PrevDecl = Previous.getFoundDecl();
15046     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
15047 
15048     // It's okay to have a tag decl in the same scope as a typedef
15049     // which hides a tag decl in the same scope.  Finding this
15050     // insanity with a redeclaration lookup can only actually happen
15051     // in C++.
15052     //
15053     // This is also okay for elaborated-type-specifiers, which is
15054     // technically forbidden by the current standard but which is
15055     // okay according to the likely resolution of an open issue;
15056     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
15057     if (getLangOpts().CPlusPlus) {
15058       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15059         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
15060           TagDecl *Tag = TT->getDecl();
15061           if (Tag->getDeclName() == Name &&
15062               Tag->getDeclContext()->getRedeclContext()
15063                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
15064             PrevDecl = Tag;
15065             Previous.clear();
15066             Previous.addDecl(Tag);
15067             Previous.resolveKind();
15068           }
15069         }
15070       }
15071     }
15072 
15073     // If this is a redeclaration of a using shadow declaration, it must
15074     // declare a tag in the same context. In MSVC mode, we allow a
15075     // redefinition if either context is within the other.
15076     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
15077       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
15078       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
15079           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
15080           !(OldTag && isAcceptableTagRedeclContext(
15081                           *this, OldTag->getDeclContext(), SearchDC))) {
15082         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
15083         Diag(Shadow->getTargetDecl()->getLocation(),
15084              diag::note_using_decl_target);
15085         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
15086             << 0;
15087         // Recover by ignoring the old declaration.
15088         Previous.clear();
15089         goto CreateNewDecl;
15090       }
15091     }
15092 
15093     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
15094       // If this is a use of a previous tag, or if the tag is already declared
15095       // in the same scope (so that the definition/declaration completes or
15096       // rementions the tag), reuse the decl.
15097       if (TUK == TUK_Reference || TUK == TUK_Friend ||
15098           isDeclInScope(DirectPrevDecl, SearchDC, S,
15099                         SS.isNotEmpty() || isMemberSpecialization)) {
15100         // Make sure that this wasn't declared as an enum and now used as a
15101         // struct or something similar.
15102         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
15103                                           TUK == TUK_Definition, KWLoc,
15104                                           Name)) {
15105           bool SafeToContinue
15106             = (PrevTagDecl->getTagKind() != TTK_Enum &&
15107                Kind != TTK_Enum);
15108           if (SafeToContinue)
15109             Diag(KWLoc, diag::err_use_with_wrong_tag)
15110               << Name
15111               << FixItHint::CreateReplacement(SourceRange(KWLoc),
15112                                               PrevTagDecl->getKindName());
15113           else
15114             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
15115           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
15116 
15117           if (SafeToContinue)
15118             Kind = PrevTagDecl->getTagKind();
15119           else {
15120             // Recover by making this an anonymous redefinition.
15121             Name = nullptr;
15122             Previous.clear();
15123             Invalid = true;
15124           }
15125         }
15126 
15127         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
15128           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
15129 
15130           // If this is an elaborated-type-specifier for a scoped enumeration,
15131           // the 'class' keyword is not necessary and not permitted.
15132           if (TUK == TUK_Reference || TUK == TUK_Friend) {
15133             if (ScopedEnum)
15134               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
15135                 << PrevEnum->isScoped()
15136                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
15137             return PrevTagDecl;
15138           }
15139 
15140           QualType EnumUnderlyingTy;
15141           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15142             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
15143           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
15144             EnumUnderlyingTy = QualType(T, 0);
15145 
15146           // All conflicts with previous declarations are recovered by
15147           // returning the previous declaration, unless this is a definition,
15148           // in which case we want the caller to bail out.
15149           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
15150                                      ScopedEnum, EnumUnderlyingTy,
15151                                      IsFixed, PrevEnum))
15152             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
15153         }
15154 
15155         // C++11 [class.mem]p1:
15156         //   A member shall not be declared twice in the member-specification,
15157         //   except that a nested class or member class template can be declared
15158         //   and then later defined.
15159         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
15160             S->isDeclScope(PrevDecl)) {
15161           Diag(NameLoc, diag::ext_member_redeclared);
15162           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
15163         }
15164 
15165         if (!Invalid) {
15166           // If this is a use, just return the declaration we found, unless
15167           // we have attributes.
15168           if (TUK == TUK_Reference || TUK == TUK_Friend) {
15169             if (!Attrs.empty()) {
15170               // FIXME: Diagnose these attributes. For now, we create a new
15171               // declaration to hold them.
15172             } else if (TUK == TUK_Reference &&
15173                        (PrevTagDecl->getFriendObjectKind() ==
15174                             Decl::FOK_Undeclared ||
15175                         PrevDecl->getOwningModule() != getCurrentModule()) &&
15176                        SS.isEmpty()) {
15177               // This declaration is a reference to an existing entity, but
15178               // has different visibility from that entity: it either makes
15179               // a friend visible or it makes a type visible in a new module.
15180               // In either case, create a new declaration. We only do this if
15181               // the declaration would have meant the same thing if no prior
15182               // declaration were found, that is, if it was found in the same
15183               // scope where we would have injected a declaration.
15184               if (!getTagInjectionContext(CurContext)->getRedeclContext()
15185                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
15186                 return PrevTagDecl;
15187               // This is in the injected scope, create a new declaration in
15188               // that scope.
15189               S = getTagInjectionScope(S, getLangOpts());
15190             } else {
15191               return PrevTagDecl;
15192             }
15193           }
15194 
15195           // Diagnose attempts to redefine a tag.
15196           if (TUK == TUK_Definition) {
15197             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
15198               // If we're defining a specialization and the previous definition
15199               // is from an implicit instantiation, don't emit an error
15200               // here; we'll catch this in the general case below.
15201               bool IsExplicitSpecializationAfterInstantiation = false;
15202               if (isMemberSpecialization) {
15203                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
15204                   IsExplicitSpecializationAfterInstantiation =
15205                     RD->getTemplateSpecializationKind() !=
15206                     TSK_ExplicitSpecialization;
15207                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
15208                   IsExplicitSpecializationAfterInstantiation =
15209                     ED->getTemplateSpecializationKind() !=
15210                     TSK_ExplicitSpecialization;
15211               }
15212 
15213               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
15214               // not keep more that one definition around (merge them). However,
15215               // ensure the decl passes the structural compatibility check in
15216               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
15217               NamedDecl *Hidden = nullptr;
15218               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
15219                 // There is a definition of this tag, but it is not visible. We
15220                 // explicitly make use of C++'s one definition rule here, and
15221                 // assume that this definition is identical to the hidden one
15222                 // we already have. Make the existing definition visible and
15223                 // use it in place of this one.
15224                 if (!getLangOpts().CPlusPlus) {
15225                   // Postpone making the old definition visible until after we
15226                   // complete parsing the new one and do the structural
15227                   // comparison.
15228                   SkipBody->CheckSameAsPrevious = true;
15229                   SkipBody->New = createTagFromNewDecl();
15230                   SkipBody->Previous = Def;
15231                   return Def;
15232                 } else {
15233                   SkipBody->ShouldSkip = true;
15234                   SkipBody->Previous = Def;
15235                   makeMergedDefinitionVisible(Hidden);
15236                   // Carry on and handle it like a normal definition. We'll
15237                   // skip starting the definitiion later.
15238                 }
15239               } else if (!IsExplicitSpecializationAfterInstantiation) {
15240                 // A redeclaration in function prototype scope in C isn't
15241                 // visible elsewhere, so merely issue a warning.
15242                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
15243                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
15244                 else
15245                   Diag(NameLoc, diag::err_redefinition) << Name;
15246                 notePreviousDefinition(Def,
15247                                        NameLoc.isValid() ? NameLoc : KWLoc);
15248                 // If this is a redefinition, recover by making this
15249                 // struct be anonymous, which will make any later
15250                 // references get the previous definition.
15251                 Name = nullptr;
15252                 Previous.clear();
15253                 Invalid = true;
15254               }
15255             } else {
15256               // If the type is currently being defined, complain
15257               // about a nested redefinition.
15258               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
15259               if (TD->isBeingDefined()) {
15260                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
15261                 Diag(PrevTagDecl->getLocation(),
15262                      diag::note_previous_definition);
15263                 Name = nullptr;
15264                 Previous.clear();
15265                 Invalid = true;
15266               }
15267             }
15268 
15269             // Okay, this is definition of a previously declared or referenced
15270             // tag. We're going to create a new Decl for it.
15271           }
15272 
15273           // Okay, we're going to make a redeclaration.  If this is some kind
15274           // of reference, make sure we build the redeclaration in the same DC
15275           // as the original, and ignore the current access specifier.
15276           if (TUK == TUK_Friend || TUK == TUK_Reference) {
15277             SearchDC = PrevTagDecl->getDeclContext();
15278             AS = AS_none;
15279           }
15280         }
15281         // If we get here we have (another) forward declaration or we
15282         // have a definition.  Just create a new decl.
15283 
15284       } else {
15285         // If we get here, this is a definition of a new tag type in a nested
15286         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
15287         // new decl/type.  We set PrevDecl to NULL so that the entities
15288         // have distinct types.
15289         Previous.clear();
15290       }
15291       // If we get here, we're going to create a new Decl. If PrevDecl
15292       // is non-NULL, it's a definition of the tag declared by
15293       // PrevDecl. If it's NULL, we have a new definition.
15294 
15295     // Otherwise, PrevDecl is not a tag, but was found with tag
15296     // lookup.  This is only actually possible in C++, where a few
15297     // things like templates still live in the tag namespace.
15298     } else {
15299       // Use a better diagnostic if an elaborated-type-specifier
15300       // found the wrong kind of type on the first
15301       // (non-redeclaration) lookup.
15302       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
15303           !Previous.isForRedeclaration()) {
15304         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15305         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
15306                                                        << Kind;
15307         Diag(PrevDecl->getLocation(), diag::note_declared_at);
15308         Invalid = true;
15309 
15310       // Otherwise, only diagnose if the declaration is in scope.
15311       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
15312                                 SS.isNotEmpty() || isMemberSpecialization)) {
15313         // do nothing
15314 
15315       // Diagnose implicit declarations introduced by elaborated types.
15316       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
15317         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15318         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
15319         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15320         Invalid = true;
15321 
15322       // Otherwise it's a declaration.  Call out a particularly common
15323       // case here.
15324       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15325         unsigned Kind = 0;
15326         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
15327         Diag(NameLoc, diag::err_tag_definition_of_typedef)
15328           << Name << Kind << TND->getUnderlyingType();
15329         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15330         Invalid = true;
15331 
15332       // Otherwise, diagnose.
15333       } else {
15334         // The tag name clashes with something else in the target scope,
15335         // issue an error and recover by making this tag be anonymous.
15336         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
15337         notePreviousDefinition(PrevDecl, NameLoc);
15338         Name = nullptr;
15339         Invalid = true;
15340       }
15341 
15342       // The existing declaration isn't relevant to us; we're in a
15343       // new scope, so clear out the previous declaration.
15344       Previous.clear();
15345     }
15346   }
15347 
15348 CreateNewDecl:
15349 
15350   TagDecl *PrevDecl = nullptr;
15351   if (Previous.isSingleResult())
15352     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
15353 
15354   // If there is an identifier, use the location of the identifier as the
15355   // location of the decl, otherwise use the location of the struct/union
15356   // keyword.
15357   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15358 
15359   // Otherwise, create a new declaration. If there is a previous
15360   // declaration of the same entity, the two will be linked via
15361   // PrevDecl.
15362   TagDecl *New;
15363 
15364   if (Kind == TTK_Enum) {
15365     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15366     // enum X { A, B, C } D;    D should chain to X.
15367     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
15368                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
15369                            ScopedEnumUsesClassTag, IsFixed);
15370 
15371     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
15372       StdAlignValT = cast<EnumDecl>(New);
15373 
15374     // If this is an undefined enum, warn.
15375     if (TUK != TUK_Definition && !Invalid) {
15376       TagDecl *Def;
15377       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
15378         // C++0x: 7.2p2: opaque-enum-declaration.
15379         // Conflicts are diagnosed above. Do nothing.
15380       }
15381       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
15382         Diag(Loc, diag::ext_forward_ref_enum_def)
15383           << New;
15384         Diag(Def->getLocation(), diag::note_previous_definition);
15385       } else {
15386         unsigned DiagID = diag::ext_forward_ref_enum;
15387         if (getLangOpts().MSVCCompat)
15388           DiagID = diag::ext_ms_forward_ref_enum;
15389         else if (getLangOpts().CPlusPlus)
15390           DiagID = diag::err_forward_ref_enum;
15391         Diag(Loc, DiagID);
15392       }
15393     }
15394 
15395     if (EnumUnderlying) {
15396       EnumDecl *ED = cast<EnumDecl>(New);
15397       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15398         ED->setIntegerTypeSourceInfo(TI);
15399       else
15400         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
15401       ED->setPromotionType(ED->getIntegerType());
15402       assert(ED->isComplete() && "enum with type should be complete");
15403     }
15404   } else {
15405     // struct/union/class
15406 
15407     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15408     // struct X { int A; } D;    D should chain to X.
15409     if (getLangOpts().CPlusPlus) {
15410       // FIXME: Look for a way to use RecordDecl for simple structs.
15411       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15412                                   cast_or_null<CXXRecordDecl>(PrevDecl));
15413 
15414       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
15415         StdBadAlloc = cast<CXXRecordDecl>(New);
15416     } else
15417       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15418                                cast_or_null<RecordDecl>(PrevDecl));
15419   }
15420 
15421   // C++11 [dcl.type]p3:
15422   //   A type-specifier-seq shall not define a class or enumeration [...].
15423   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
15424       TUK == TUK_Definition) {
15425     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
15426       << Context.getTagDeclType(New);
15427     Invalid = true;
15428   }
15429 
15430   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
15431       DC->getDeclKind() == Decl::Enum) {
15432     Diag(New->getLocation(), diag::err_type_defined_in_enum)
15433       << Context.getTagDeclType(New);
15434     Invalid = true;
15435   }
15436 
15437   // Maybe add qualifier info.
15438   if (SS.isNotEmpty()) {
15439     if (SS.isSet()) {
15440       // If this is either a declaration or a definition, check the
15441       // nested-name-specifier against the current context.
15442       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
15443           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
15444                                        isMemberSpecialization))
15445         Invalid = true;
15446 
15447       New->setQualifierInfo(SS.getWithLocInContext(Context));
15448       if (TemplateParameterLists.size() > 0) {
15449         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
15450       }
15451     }
15452     else
15453       Invalid = true;
15454   }
15455 
15456   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15457     // Add alignment attributes if necessary; these attributes are checked when
15458     // the ASTContext lays out the structure.
15459     //
15460     // It is important for implementing the correct semantics that this
15461     // happen here (in ActOnTag). The #pragma pack stack is
15462     // maintained as a result of parser callbacks which can occur at
15463     // many points during the parsing of a struct declaration (because
15464     // the #pragma tokens are effectively skipped over during the
15465     // parsing of the struct).
15466     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15467       AddAlignmentAttributesForRecord(RD);
15468       AddMsStructLayoutForRecord(RD);
15469     }
15470   }
15471 
15472   if (ModulePrivateLoc.isValid()) {
15473     if (isMemberSpecialization)
15474       Diag(New->getLocation(), diag::err_module_private_specialization)
15475         << 2
15476         << FixItHint::CreateRemoval(ModulePrivateLoc);
15477     // __module_private__ does not apply to local classes. However, we only
15478     // diagnose this as an error when the declaration specifiers are
15479     // freestanding. Here, we just ignore the __module_private__.
15480     else if (!SearchDC->isFunctionOrMethod())
15481       New->setModulePrivate();
15482   }
15483 
15484   // If this is a specialization of a member class (of a class template),
15485   // check the specialization.
15486   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
15487     Invalid = true;
15488 
15489   // If we're declaring or defining a tag in function prototype scope in C,
15490   // note that this type can only be used within the function and add it to
15491   // the list of decls to inject into the function definition scope.
15492   if ((Name || Kind == TTK_Enum) &&
15493       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
15494     if (getLangOpts().CPlusPlus) {
15495       // C++ [dcl.fct]p6:
15496       //   Types shall not be defined in return or parameter types.
15497       if (TUK == TUK_Definition && !IsTypeSpecifier) {
15498         Diag(Loc, diag::err_type_defined_in_param_type)
15499             << Name;
15500         Invalid = true;
15501       }
15502     } else if (!PrevDecl) {
15503       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
15504     }
15505   }
15506 
15507   if (Invalid)
15508     New->setInvalidDecl();
15509 
15510   // Set the lexical context. If the tag has a C++ scope specifier, the
15511   // lexical context will be different from the semantic context.
15512   New->setLexicalDeclContext(CurContext);
15513 
15514   // Mark this as a friend decl if applicable.
15515   // In Microsoft mode, a friend declaration also acts as a forward
15516   // declaration so we always pass true to setObjectOfFriendDecl to make
15517   // the tag name visible.
15518   if (TUK == TUK_Friend)
15519     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
15520 
15521   // Set the access specifier.
15522   if (!Invalid && SearchDC->isRecord())
15523     SetMemberAccessSpecifier(New, PrevDecl, AS);
15524 
15525   if (PrevDecl)
15526     CheckRedeclarationModuleOwnership(New, PrevDecl);
15527 
15528   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
15529     New->startDefinition();
15530 
15531   ProcessDeclAttributeList(S, New, Attrs);
15532   AddPragmaAttributes(S, New);
15533 
15534   // If this has an identifier, add it to the scope stack.
15535   if (TUK == TUK_Friend) {
15536     // We might be replacing an existing declaration in the lookup tables;
15537     // if so, borrow its access specifier.
15538     if (PrevDecl)
15539       New->setAccess(PrevDecl->getAccess());
15540 
15541     DeclContext *DC = New->getDeclContext()->getRedeclContext();
15542     DC->makeDeclVisibleInContext(New);
15543     if (Name) // can be null along some error paths
15544       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
15545         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
15546   } else if (Name) {
15547     S = getNonFieldDeclScope(S);
15548     PushOnScopeChains(New, S, true);
15549   } else {
15550     CurContext->addDecl(New);
15551   }
15552 
15553   // If this is the C FILE type, notify the AST context.
15554   if (IdentifierInfo *II = New->getIdentifier())
15555     if (!New->isInvalidDecl() &&
15556         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
15557         II->isStr("FILE"))
15558       Context.setFILEDecl(New);
15559 
15560   if (PrevDecl)
15561     mergeDeclAttributes(New, PrevDecl);
15562 
15563   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
15564     inferGslOwnerPointerAttribute(CXXRD);
15565 
15566   // If there's a #pragma GCC visibility in scope, set the visibility of this
15567   // record.
15568   AddPushedVisibilityAttribute(New);
15569 
15570   if (isMemberSpecialization && !New->isInvalidDecl())
15571     CompleteMemberSpecialization(New, Previous);
15572 
15573   OwnedDecl = true;
15574   // In C++, don't return an invalid declaration. We can't recover well from
15575   // the cases where we make the type anonymous.
15576   if (Invalid && getLangOpts().CPlusPlus) {
15577     if (New->isBeingDefined())
15578       if (auto RD = dyn_cast<RecordDecl>(New))
15579         RD->completeDefinition();
15580     return nullptr;
15581   } else if (SkipBody && SkipBody->ShouldSkip) {
15582     return SkipBody->Previous;
15583   } else {
15584     return New;
15585   }
15586 }
15587 
15588 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
15589   AdjustDeclIfTemplate(TagD);
15590   TagDecl *Tag = cast<TagDecl>(TagD);
15591 
15592   // Enter the tag context.
15593   PushDeclContext(S, Tag);
15594 
15595   ActOnDocumentableDecl(TagD);
15596 
15597   // If there's a #pragma GCC visibility in scope, set the visibility of this
15598   // record.
15599   AddPushedVisibilityAttribute(Tag);
15600 }
15601 
15602 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
15603                                     SkipBodyInfo &SkipBody) {
15604   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
15605     return false;
15606 
15607   // Make the previous decl visible.
15608   makeMergedDefinitionVisible(SkipBody.Previous);
15609   return true;
15610 }
15611 
15612 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
15613   assert(isa<ObjCContainerDecl>(IDecl) &&
15614          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
15615   DeclContext *OCD = cast<DeclContext>(IDecl);
15616   assert(getContainingDC(OCD) == CurContext &&
15617       "The next DeclContext should be lexically contained in the current one.");
15618   CurContext = OCD;
15619   return IDecl;
15620 }
15621 
15622 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
15623                                            SourceLocation FinalLoc,
15624                                            bool IsFinalSpelledSealed,
15625                                            SourceLocation LBraceLoc) {
15626   AdjustDeclIfTemplate(TagD);
15627   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
15628 
15629   FieldCollector->StartClass();
15630 
15631   if (!Record->getIdentifier())
15632     return;
15633 
15634   if (FinalLoc.isValid())
15635     Record->addAttr(FinalAttr::Create(
15636         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
15637         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
15638 
15639   // C++ [class]p2:
15640   //   [...] The class-name is also inserted into the scope of the
15641   //   class itself; this is known as the injected-class-name. For
15642   //   purposes of access checking, the injected-class-name is treated
15643   //   as if it were a public member name.
15644   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
15645       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
15646       Record->getLocation(), Record->getIdentifier(),
15647       /*PrevDecl=*/nullptr,
15648       /*DelayTypeCreation=*/true);
15649   Context.getTypeDeclType(InjectedClassName, Record);
15650   InjectedClassName->setImplicit();
15651   InjectedClassName->setAccess(AS_public);
15652   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
15653       InjectedClassName->setDescribedClassTemplate(Template);
15654   PushOnScopeChains(InjectedClassName, S);
15655   assert(InjectedClassName->isInjectedClassName() &&
15656          "Broken injected-class-name");
15657 }
15658 
15659 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
15660                                     SourceRange BraceRange) {
15661   AdjustDeclIfTemplate(TagD);
15662   TagDecl *Tag = cast<TagDecl>(TagD);
15663   Tag->setBraceRange(BraceRange);
15664 
15665   // Make sure we "complete" the definition even it is invalid.
15666   if (Tag->isBeingDefined()) {
15667     assert(Tag->isInvalidDecl() && "We should already have completed it");
15668     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15669       RD->completeDefinition();
15670   }
15671 
15672   if (isa<CXXRecordDecl>(Tag)) {
15673     FieldCollector->FinishClass();
15674   }
15675 
15676   // Exit this scope of this tag's definition.
15677   PopDeclContext();
15678 
15679   if (getCurLexicalContext()->isObjCContainer() &&
15680       Tag->getDeclContext()->isFileContext())
15681     Tag->setTopLevelDeclInObjCContainer();
15682 
15683   // Notify the consumer that we've defined a tag.
15684   if (!Tag->isInvalidDecl())
15685     Consumer.HandleTagDeclDefinition(Tag);
15686 }
15687 
15688 void Sema::ActOnObjCContainerFinishDefinition() {
15689   // Exit this scope of this interface definition.
15690   PopDeclContext();
15691 }
15692 
15693 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
15694   assert(DC == CurContext && "Mismatch of container contexts");
15695   OriginalLexicalContext = DC;
15696   ActOnObjCContainerFinishDefinition();
15697 }
15698 
15699 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
15700   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
15701   OriginalLexicalContext = nullptr;
15702 }
15703 
15704 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
15705   AdjustDeclIfTemplate(TagD);
15706   TagDecl *Tag = cast<TagDecl>(TagD);
15707   Tag->setInvalidDecl();
15708 
15709   // Make sure we "complete" the definition even it is invalid.
15710   if (Tag->isBeingDefined()) {
15711     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15712       RD->completeDefinition();
15713   }
15714 
15715   // We're undoing ActOnTagStartDefinition here, not
15716   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
15717   // the FieldCollector.
15718 
15719   PopDeclContext();
15720 }
15721 
15722 // Note that FieldName may be null for anonymous bitfields.
15723 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
15724                                 IdentifierInfo *FieldName,
15725                                 QualType FieldTy, bool IsMsStruct,
15726                                 Expr *BitWidth, bool *ZeroWidth) {
15727   // Default to true; that shouldn't confuse checks for emptiness
15728   if (ZeroWidth)
15729     *ZeroWidth = true;
15730 
15731   // C99 6.7.2.1p4 - verify the field type.
15732   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
15733   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
15734     // Handle incomplete types with specific error.
15735     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
15736       return ExprError();
15737     if (FieldName)
15738       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
15739         << FieldName << FieldTy << BitWidth->getSourceRange();
15740     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
15741       << FieldTy << BitWidth->getSourceRange();
15742   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
15743                                              UPPC_BitFieldWidth))
15744     return ExprError();
15745 
15746   // If the bit-width is type- or value-dependent, don't try to check
15747   // it now.
15748   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
15749     return BitWidth;
15750 
15751   llvm::APSInt Value;
15752   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
15753   if (ICE.isInvalid())
15754     return ICE;
15755   BitWidth = ICE.get();
15756 
15757   if (Value != 0 && ZeroWidth)
15758     *ZeroWidth = false;
15759 
15760   // Zero-width bitfield is ok for anonymous field.
15761   if (Value == 0 && FieldName)
15762     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
15763 
15764   if (Value.isSigned() && Value.isNegative()) {
15765     if (FieldName)
15766       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
15767                << FieldName << Value.toString(10);
15768     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
15769       << Value.toString(10);
15770   }
15771 
15772   if (!FieldTy->isDependentType()) {
15773     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
15774     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
15775     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
15776 
15777     // Over-wide bitfields are an error in C or when using the MSVC bitfield
15778     // ABI.
15779     bool CStdConstraintViolation =
15780         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
15781     bool MSBitfieldViolation =
15782         Value.ugt(TypeStorageSize) &&
15783         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
15784     if (CStdConstraintViolation || MSBitfieldViolation) {
15785       unsigned DiagWidth =
15786           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
15787       if (FieldName)
15788         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
15789                << FieldName << (unsigned)Value.getZExtValue()
15790                << !CStdConstraintViolation << DiagWidth;
15791 
15792       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
15793              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
15794              << DiagWidth;
15795     }
15796 
15797     // Warn on types where the user might conceivably expect to get all
15798     // specified bits as value bits: that's all integral types other than
15799     // 'bool'.
15800     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
15801       if (FieldName)
15802         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
15803             << FieldName << (unsigned)Value.getZExtValue()
15804             << (unsigned)TypeWidth;
15805       else
15806         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
15807             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
15808     }
15809   }
15810 
15811   return BitWidth;
15812 }
15813 
15814 /// ActOnField - Each field of a C struct/union is passed into this in order
15815 /// to create a FieldDecl object for it.
15816 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
15817                        Declarator &D, Expr *BitfieldWidth) {
15818   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
15819                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
15820                                /*InitStyle=*/ICIS_NoInit, AS_public);
15821   return Res;
15822 }
15823 
15824 /// HandleField - Analyze a field of a C struct or a C++ data member.
15825 ///
15826 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
15827                              SourceLocation DeclStart,
15828                              Declarator &D, Expr *BitWidth,
15829                              InClassInitStyle InitStyle,
15830                              AccessSpecifier AS) {
15831   if (D.isDecompositionDeclarator()) {
15832     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
15833     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
15834       << Decomp.getSourceRange();
15835     return nullptr;
15836   }
15837 
15838   IdentifierInfo *II = D.getIdentifier();
15839   SourceLocation Loc = DeclStart;
15840   if (II) Loc = D.getIdentifierLoc();
15841 
15842   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15843   QualType T = TInfo->getType();
15844   if (getLangOpts().CPlusPlus) {
15845     CheckExtraCXXDefaultArguments(D);
15846 
15847     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15848                                         UPPC_DataMemberType)) {
15849       D.setInvalidType();
15850       T = Context.IntTy;
15851       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15852     }
15853   }
15854 
15855   DiagnoseFunctionSpecifiers(D.getDeclSpec());
15856 
15857   if (D.getDeclSpec().isInlineSpecified())
15858     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15859         << getLangOpts().CPlusPlus17;
15860   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15861     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15862          diag::err_invalid_thread)
15863       << DeclSpec::getSpecifierName(TSCS);
15864 
15865   // Check to see if this name was declared as a member previously
15866   NamedDecl *PrevDecl = nullptr;
15867   LookupResult Previous(*this, II, Loc, LookupMemberName,
15868                         ForVisibleRedeclaration);
15869   LookupName(Previous, S);
15870   switch (Previous.getResultKind()) {
15871     case LookupResult::Found:
15872     case LookupResult::FoundUnresolvedValue:
15873       PrevDecl = Previous.getAsSingle<NamedDecl>();
15874       break;
15875 
15876     case LookupResult::FoundOverloaded:
15877       PrevDecl = Previous.getRepresentativeDecl();
15878       break;
15879 
15880     case LookupResult::NotFound:
15881     case LookupResult::NotFoundInCurrentInstantiation:
15882     case LookupResult::Ambiguous:
15883       break;
15884   }
15885   Previous.suppressDiagnostics();
15886 
15887   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15888     // Maybe we will complain about the shadowed template parameter.
15889     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15890     // Just pretend that we didn't see the previous declaration.
15891     PrevDecl = nullptr;
15892   }
15893 
15894   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15895     PrevDecl = nullptr;
15896 
15897   bool Mutable
15898     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
15899   SourceLocation TSSL = D.getBeginLoc();
15900   FieldDecl *NewFD
15901     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
15902                      TSSL, AS, PrevDecl, &D);
15903 
15904   if (NewFD->isInvalidDecl())
15905     Record->setInvalidDecl();
15906 
15907   if (D.getDeclSpec().isModulePrivateSpecified())
15908     NewFD->setModulePrivate();
15909 
15910   if (NewFD->isInvalidDecl() && PrevDecl) {
15911     // Don't introduce NewFD into scope; there's already something
15912     // with the same name in the same scope.
15913   } else if (II) {
15914     PushOnScopeChains(NewFD, S);
15915   } else
15916     Record->addDecl(NewFD);
15917 
15918   return NewFD;
15919 }
15920 
15921 /// Build a new FieldDecl and check its well-formedness.
15922 ///
15923 /// This routine builds a new FieldDecl given the fields name, type,
15924 /// record, etc. \p PrevDecl should refer to any previous declaration
15925 /// with the same name and in the same scope as the field to be
15926 /// created.
15927 ///
15928 /// \returns a new FieldDecl.
15929 ///
15930 /// \todo The Declarator argument is a hack. It will be removed once
15931 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
15932                                 TypeSourceInfo *TInfo,
15933                                 RecordDecl *Record, SourceLocation Loc,
15934                                 bool Mutable, Expr *BitWidth,
15935                                 InClassInitStyle InitStyle,
15936                                 SourceLocation TSSL,
15937                                 AccessSpecifier AS, NamedDecl *PrevDecl,
15938                                 Declarator *D) {
15939   IdentifierInfo *II = Name.getAsIdentifierInfo();
15940   bool InvalidDecl = false;
15941   if (D) InvalidDecl = D->isInvalidType();
15942 
15943   // If we receive a broken type, recover by assuming 'int' and
15944   // marking this declaration as invalid.
15945   if (T.isNull()) {
15946     InvalidDecl = true;
15947     T = Context.IntTy;
15948   }
15949 
15950   QualType EltTy = Context.getBaseElementType(T);
15951   if (!EltTy->isDependentType()) {
15952     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
15953       // Fields of incomplete type force their record to be invalid.
15954       Record->setInvalidDecl();
15955       InvalidDecl = true;
15956     } else {
15957       NamedDecl *Def;
15958       EltTy->isIncompleteType(&Def);
15959       if (Def && Def->isInvalidDecl()) {
15960         Record->setInvalidDecl();
15961         InvalidDecl = true;
15962       }
15963     }
15964   }
15965 
15966   // TR 18037 does not allow fields to be declared with address space
15967   if (T.getQualifiers().hasAddressSpace() || T->isDependentAddressSpaceType() ||
15968       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
15969     Diag(Loc, diag::err_field_with_address_space);
15970     Record->setInvalidDecl();
15971     InvalidDecl = true;
15972   }
15973 
15974   if (LangOpts.OpenCL) {
15975     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
15976     // used as structure or union field: image, sampler, event or block types.
15977     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
15978         T->isBlockPointerType()) {
15979       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
15980       Record->setInvalidDecl();
15981       InvalidDecl = true;
15982     }
15983     // OpenCL v1.2 s6.9.c: bitfields are not supported.
15984     if (BitWidth) {
15985       Diag(Loc, diag::err_opencl_bitfields);
15986       InvalidDecl = true;
15987     }
15988   }
15989 
15990   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
15991   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
15992       T.hasQualifiers()) {
15993     InvalidDecl = true;
15994     Diag(Loc, diag::err_anon_bitfield_qualifiers);
15995   }
15996 
15997   // C99 6.7.2.1p8: A member of a structure or union may have any type other
15998   // than a variably modified type.
15999   if (!InvalidDecl && T->isVariablyModifiedType()) {
16000     bool SizeIsNegative;
16001     llvm::APSInt Oversized;
16002 
16003     TypeSourceInfo *FixedTInfo =
16004       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
16005                                                     SizeIsNegative,
16006                                                     Oversized);
16007     if (FixedTInfo) {
16008       Diag(Loc, diag::warn_illegal_constant_array_size);
16009       TInfo = FixedTInfo;
16010       T = FixedTInfo->getType();
16011     } else {
16012       if (SizeIsNegative)
16013         Diag(Loc, diag::err_typecheck_negative_array_size);
16014       else if (Oversized.getBoolValue())
16015         Diag(Loc, diag::err_array_too_large)
16016           << Oversized.toString(10);
16017       else
16018         Diag(Loc, diag::err_typecheck_field_variable_size);
16019       InvalidDecl = true;
16020     }
16021   }
16022 
16023   // Fields can not have abstract class types
16024   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
16025                                              diag::err_abstract_type_in_decl,
16026                                              AbstractFieldType))
16027     InvalidDecl = true;
16028 
16029   bool ZeroWidth = false;
16030   if (InvalidDecl)
16031     BitWidth = nullptr;
16032   // If this is declared as a bit-field, check the bit-field.
16033   if (BitWidth) {
16034     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
16035                               &ZeroWidth).get();
16036     if (!BitWidth) {
16037       InvalidDecl = true;
16038       BitWidth = nullptr;
16039       ZeroWidth = false;
16040     }
16041   }
16042 
16043   // Check that 'mutable' is consistent with the type of the declaration.
16044   if (!InvalidDecl && Mutable) {
16045     unsigned DiagID = 0;
16046     if (T->isReferenceType())
16047       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
16048                                         : diag::err_mutable_reference;
16049     else if (T.isConstQualified())
16050       DiagID = diag::err_mutable_const;
16051 
16052     if (DiagID) {
16053       SourceLocation ErrLoc = Loc;
16054       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
16055         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
16056       Diag(ErrLoc, DiagID);
16057       if (DiagID != diag::ext_mutable_reference) {
16058         Mutable = false;
16059         InvalidDecl = true;
16060       }
16061     }
16062   }
16063 
16064   // C++11 [class.union]p8 (DR1460):
16065   //   At most one variant member of a union may have a
16066   //   brace-or-equal-initializer.
16067   if (InitStyle != ICIS_NoInit)
16068     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
16069 
16070   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
16071                                        BitWidth, Mutable, InitStyle);
16072   if (InvalidDecl)
16073     NewFD->setInvalidDecl();
16074 
16075   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
16076     Diag(Loc, diag::err_duplicate_member) << II;
16077     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16078     NewFD->setInvalidDecl();
16079   }
16080 
16081   if (!InvalidDecl && getLangOpts().CPlusPlus) {
16082     if (Record->isUnion()) {
16083       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16084         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
16085         if (RDecl->getDefinition()) {
16086           // C++ [class.union]p1: An object of a class with a non-trivial
16087           // constructor, a non-trivial copy constructor, a non-trivial
16088           // destructor, or a non-trivial copy assignment operator
16089           // cannot be a member of a union, nor can an array of such
16090           // objects.
16091           if (CheckNontrivialField(NewFD))
16092             NewFD->setInvalidDecl();
16093         }
16094       }
16095 
16096       // C++ [class.union]p1: If a union contains a member of reference type,
16097       // the program is ill-formed, except when compiling with MSVC extensions
16098       // enabled.
16099       if (EltTy->isReferenceType()) {
16100         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
16101                                     diag::ext_union_member_of_reference_type :
16102                                     diag::err_union_member_of_reference_type)
16103           << NewFD->getDeclName() << EltTy;
16104         if (!getLangOpts().MicrosoftExt)
16105           NewFD->setInvalidDecl();
16106       }
16107     }
16108   }
16109 
16110   // FIXME: We need to pass in the attributes given an AST
16111   // representation, not a parser representation.
16112   if (D) {
16113     // FIXME: The current scope is almost... but not entirely... correct here.
16114     ProcessDeclAttributes(getCurScope(), NewFD, *D);
16115 
16116     if (NewFD->hasAttrs())
16117       CheckAlignasUnderalignment(NewFD);
16118   }
16119 
16120   // In auto-retain/release, infer strong retension for fields of
16121   // retainable type.
16122   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
16123     NewFD->setInvalidDecl();
16124 
16125   if (T.isObjCGCWeak())
16126     Diag(Loc, diag::warn_attribute_weak_on_field);
16127 
16128   NewFD->setAccess(AS);
16129   return NewFD;
16130 }
16131 
16132 bool Sema::CheckNontrivialField(FieldDecl *FD) {
16133   assert(FD);
16134   assert(getLangOpts().CPlusPlus && "valid check only for C++");
16135 
16136   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
16137     return false;
16138 
16139   QualType EltTy = Context.getBaseElementType(FD->getType());
16140   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16141     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
16142     if (RDecl->getDefinition()) {
16143       // We check for copy constructors before constructors
16144       // because otherwise we'll never get complaints about
16145       // copy constructors.
16146 
16147       CXXSpecialMember member = CXXInvalid;
16148       // We're required to check for any non-trivial constructors. Since the
16149       // implicit default constructor is suppressed if there are any
16150       // user-declared constructors, we just need to check that there is a
16151       // trivial default constructor and a trivial copy constructor. (We don't
16152       // worry about move constructors here, since this is a C++98 check.)
16153       if (RDecl->hasNonTrivialCopyConstructor())
16154         member = CXXCopyConstructor;
16155       else if (!RDecl->hasTrivialDefaultConstructor())
16156         member = CXXDefaultConstructor;
16157       else if (RDecl->hasNonTrivialCopyAssignment())
16158         member = CXXCopyAssignment;
16159       else if (RDecl->hasNonTrivialDestructor())
16160         member = CXXDestructor;
16161 
16162       if (member != CXXInvalid) {
16163         if (!getLangOpts().CPlusPlus11 &&
16164             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
16165           // Objective-C++ ARC: it is an error to have a non-trivial field of
16166           // a union. However, system headers in Objective-C programs
16167           // occasionally have Objective-C lifetime objects within unions,
16168           // and rather than cause the program to fail, we make those
16169           // members unavailable.
16170           SourceLocation Loc = FD->getLocation();
16171           if (getSourceManager().isInSystemHeader(Loc)) {
16172             if (!FD->hasAttr<UnavailableAttr>())
16173               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
16174                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
16175             return false;
16176           }
16177         }
16178 
16179         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
16180                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
16181                diag::err_illegal_union_or_anon_struct_member)
16182           << FD->getParent()->isUnion() << FD->getDeclName() << member;
16183         DiagnoseNontrivial(RDecl, member);
16184         return !getLangOpts().CPlusPlus11;
16185       }
16186     }
16187   }
16188 
16189   return false;
16190 }
16191 
16192 /// TranslateIvarVisibility - Translate visibility from a token ID to an
16193 ///  AST enum value.
16194 static ObjCIvarDecl::AccessControl
16195 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
16196   switch (ivarVisibility) {
16197   default: llvm_unreachable("Unknown visitibility kind");
16198   case tok::objc_private: return ObjCIvarDecl::Private;
16199   case tok::objc_public: return ObjCIvarDecl::Public;
16200   case tok::objc_protected: return ObjCIvarDecl::Protected;
16201   case tok::objc_package: return ObjCIvarDecl::Package;
16202   }
16203 }
16204 
16205 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
16206 /// in order to create an IvarDecl object for it.
16207 Decl *Sema::ActOnIvar(Scope *S,
16208                                 SourceLocation DeclStart,
16209                                 Declarator &D, Expr *BitfieldWidth,
16210                                 tok::ObjCKeywordKind Visibility) {
16211 
16212   IdentifierInfo *II = D.getIdentifier();
16213   Expr *BitWidth = (Expr*)BitfieldWidth;
16214   SourceLocation Loc = DeclStart;
16215   if (II) Loc = D.getIdentifierLoc();
16216 
16217   // FIXME: Unnamed fields can be handled in various different ways, for
16218   // example, unnamed unions inject all members into the struct namespace!
16219 
16220   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16221   QualType T = TInfo->getType();
16222 
16223   if (BitWidth) {
16224     // 6.7.2.1p3, 6.7.2.1p4
16225     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
16226     if (!BitWidth)
16227       D.setInvalidType();
16228   } else {
16229     // Not a bitfield.
16230 
16231     // validate II.
16232 
16233   }
16234   if (T->isReferenceType()) {
16235     Diag(Loc, diag::err_ivar_reference_type);
16236     D.setInvalidType();
16237   }
16238   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16239   // than a variably modified type.
16240   else if (T->isVariablyModifiedType()) {
16241     Diag(Loc, diag::err_typecheck_ivar_variable_size);
16242     D.setInvalidType();
16243   }
16244 
16245   // Get the visibility (access control) for this ivar.
16246   ObjCIvarDecl::AccessControl ac =
16247     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
16248                                         : ObjCIvarDecl::None;
16249   // Must set ivar's DeclContext to its enclosing interface.
16250   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
16251   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
16252     return nullptr;
16253   ObjCContainerDecl *EnclosingContext;
16254   if (ObjCImplementationDecl *IMPDecl =
16255       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16256     if (LangOpts.ObjCRuntime.isFragile()) {
16257     // Case of ivar declared in an implementation. Context is that of its class.
16258       EnclosingContext = IMPDecl->getClassInterface();
16259       assert(EnclosingContext && "Implementation has no class interface!");
16260     }
16261     else
16262       EnclosingContext = EnclosingDecl;
16263   } else {
16264     if (ObjCCategoryDecl *CDecl =
16265         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16266       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
16267         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
16268         return nullptr;
16269       }
16270     }
16271     EnclosingContext = EnclosingDecl;
16272   }
16273 
16274   // Construct the decl.
16275   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
16276                                              DeclStart, Loc, II, T,
16277                                              TInfo, ac, (Expr *)BitfieldWidth);
16278 
16279   if (II) {
16280     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
16281                                            ForVisibleRedeclaration);
16282     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
16283         && !isa<TagDecl>(PrevDecl)) {
16284       Diag(Loc, diag::err_duplicate_member) << II;
16285       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16286       NewID->setInvalidDecl();
16287     }
16288   }
16289 
16290   // Process attributes attached to the ivar.
16291   ProcessDeclAttributes(S, NewID, D);
16292 
16293   if (D.isInvalidType())
16294     NewID->setInvalidDecl();
16295 
16296   // In ARC, infer 'retaining' for ivars of retainable type.
16297   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
16298     NewID->setInvalidDecl();
16299 
16300   if (D.getDeclSpec().isModulePrivateSpecified())
16301     NewID->setModulePrivate();
16302 
16303   if (II) {
16304     // FIXME: When interfaces are DeclContexts, we'll need to add
16305     // these to the interface.
16306     S->AddDecl(NewID);
16307     IdResolver.AddDecl(NewID);
16308   }
16309 
16310   if (LangOpts.ObjCRuntime.isNonFragile() &&
16311       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
16312     Diag(Loc, diag::warn_ivars_in_interface);
16313 
16314   return NewID;
16315 }
16316 
16317 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
16318 /// class and class extensions. For every class \@interface and class
16319 /// extension \@interface, if the last ivar is a bitfield of any type,
16320 /// then add an implicit `char :0` ivar to the end of that interface.
16321 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
16322                              SmallVectorImpl<Decl *> &AllIvarDecls) {
16323   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
16324     return;
16325 
16326   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
16327   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
16328 
16329   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
16330     return;
16331   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
16332   if (!ID) {
16333     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
16334       if (!CD->IsClassExtension())
16335         return;
16336     }
16337     // No need to add this to end of @implementation.
16338     else
16339       return;
16340   }
16341   // All conditions are met. Add a new bitfield to the tail end of ivars.
16342   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
16343   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
16344 
16345   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
16346                               DeclLoc, DeclLoc, nullptr,
16347                               Context.CharTy,
16348                               Context.getTrivialTypeSourceInfo(Context.CharTy,
16349                                                                DeclLoc),
16350                               ObjCIvarDecl::Private, BW,
16351                               true);
16352   AllIvarDecls.push_back(Ivar);
16353 }
16354 
16355 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
16356                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
16357                        SourceLocation RBrac,
16358                        const ParsedAttributesView &Attrs) {
16359   assert(EnclosingDecl && "missing record or interface decl");
16360 
16361   // If this is an Objective-C @implementation or category and we have
16362   // new fields here we should reset the layout of the interface since
16363   // it will now change.
16364   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
16365     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
16366     switch (DC->getKind()) {
16367     default: break;
16368     case Decl::ObjCCategory:
16369       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
16370       break;
16371     case Decl::ObjCImplementation:
16372       Context.
16373         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
16374       break;
16375     }
16376   }
16377 
16378   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
16379   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
16380 
16381   // Start counting up the number of named members; make sure to include
16382   // members of anonymous structs and unions in the total.
16383   unsigned NumNamedMembers = 0;
16384   if (Record) {
16385     for (const auto *I : Record->decls()) {
16386       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
16387         if (IFD->getDeclName())
16388           ++NumNamedMembers;
16389     }
16390   }
16391 
16392   // Verify that all the fields are okay.
16393   SmallVector<FieldDecl*, 32> RecFields;
16394 
16395   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
16396        i != end; ++i) {
16397     FieldDecl *FD = cast<FieldDecl>(*i);
16398 
16399     // Get the type for the field.
16400     const Type *FDTy = FD->getType().getTypePtr();
16401 
16402     if (!FD->isAnonymousStructOrUnion()) {
16403       // Remember all fields written by the user.
16404       RecFields.push_back(FD);
16405     }
16406 
16407     // If the field is already invalid for some reason, don't emit more
16408     // diagnostics about it.
16409     if (FD->isInvalidDecl()) {
16410       EnclosingDecl->setInvalidDecl();
16411       continue;
16412     }
16413 
16414     // C99 6.7.2.1p2:
16415     //   A structure or union shall not contain a member with
16416     //   incomplete or function type (hence, a structure shall not
16417     //   contain an instance of itself, but may contain a pointer to
16418     //   an instance of itself), except that the last member of a
16419     //   structure with more than one named member may have incomplete
16420     //   array type; such a structure (and any union containing,
16421     //   possibly recursively, a member that is such a structure)
16422     //   shall not be a member of a structure or an element of an
16423     //   array.
16424     bool IsLastField = (i + 1 == Fields.end());
16425     if (FDTy->isFunctionType()) {
16426       // Field declared as a function.
16427       Diag(FD->getLocation(), diag::err_field_declared_as_function)
16428         << FD->getDeclName();
16429       FD->setInvalidDecl();
16430       EnclosingDecl->setInvalidDecl();
16431       continue;
16432     } else if (FDTy->isIncompleteArrayType() &&
16433                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
16434       if (Record) {
16435         // Flexible array member.
16436         // Microsoft and g++ is more permissive regarding flexible array.
16437         // It will accept flexible array in union and also
16438         // as the sole element of a struct/class.
16439         unsigned DiagID = 0;
16440         if (!Record->isUnion() && !IsLastField) {
16441           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
16442             << FD->getDeclName() << FD->getType() << Record->getTagKind();
16443           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
16444           FD->setInvalidDecl();
16445           EnclosingDecl->setInvalidDecl();
16446           continue;
16447         } else if (Record->isUnion())
16448           DiagID = getLangOpts().MicrosoftExt
16449                        ? diag::ext_flexible_array_union_ms
16450                        : getLangOpts().CPlusPlus
16451                              ? diag::ext_flexible_array_union_gnu
16452                              : diag::err_flexible_array_union;
16453         else if (NumNamedMembers < 1)
16454           DiagID = getLangOpts().MicrosoftExt
16455                        ? diag::ext_flexible_array_empty_aggregate_ms
16456                        : getLangOpts().CPlusPlus
16457                              ? diag::ext_flexible_array_empty_aggregate_gnu
16458                              : diag::err_flexible_array_empty_aggregate;
16459 
16460         if (DiagID)
16461           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
16462                                           << Record->getTagKind();
16463         // While the layout of types that contain virtual bases is not specified
16464         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
16465         // virtual bases after the derived members.  This would make a flexible
16466         // array member declared at the end of an object not adjacent to the end
16467         // of the type.
16468         if (CXXRecord && CXXRecord->getNumVBases() != 0)
16469           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
16470               << FD->getDeclName() << Record->getTagKind();
16471         if (!getLangOpts().C99)
16472           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
16473             << FD->getDeclName() << Record->getTagKind();
16474 
16475         // If the element type has a non-trivial destructor, we would not
16476         // implicitly destroy the elements, so disallow it for now.
16477         //
16478         // FIXME: GCC allows this. We should probably either implicitly delete
16479         // the destructor of the containing class, or just allow this.
16480         QualType BaseElem = Context.getBaseElementType(FD->getType());
16481         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
16482           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
16483             << FD->getDeclName() << FD->getType();
16484           FD->setInvalidDecl();
16485           EnclosingDecl->setInvalidDecl();
16486           continue;
16487         }
16488         // Okay, we have a legal flexible array member at the end of the struct.
16489         Record->setHasFlexibleArrayMember(true);
16490       } else {
16491         // In ObjCContainerDecl ivars with incomplete array type are accepted,
16492         // unless they are followed by another ivar. That check is done
16493         // elsewhere, after synthesized ivars are known.
16494       }
16495     } else if (!FDTy->isDependentType() &&
16496                RequireCompleteType(FD->getLocation(), FD->getType(),
16497                                    diag::err_field_incomplete)) {
16498       // Incomplete type
16499       FD->setInvalidDecl();
16500       EnclosingDecl->setInvalidDecl();
16501       continue;
16502     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
16503       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
16504         // A type which contains a flexible array member is considered to be a
16505         // flexible array member.
16506         Record->setHasFlexibleArrayMember(true);
16507         if (!Record->isUnion()) {
16508           // If this is a struct/class and this is not the last element, reject
16509           // it.  Note that GCC supports variable sized arrays in the middle of
16510           // structures.
16511           if (!IsLastField)
16512             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
16513               << FD->getDeclName() << FD->getType();
16514           else {
16515             // We support flexible arrays at the end of structs in
16516             // other structs as an extension.
16517             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
16518               << FD->getDeclName();
16519           }
16520         }
16521       }
16522       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
16523           RequireNonAbstractType(FD->getLocation(), FD->getType(),
16524                                  diag::err_abstract_type_in_decl,
16525                                  AbstractIvarType)) {
16526         // Ivars can not have abstract class types
16527         FD->setInvalidDecl();
16528       }
16529       if (Record && FDTTy->getDecl()->hasObjectMember())
16530         Record->setHasObjectMember(true);
16531       if (Record && FDTTy->getDecl()->hasVolatileMember())
16532         Record->setHasVolatileMember(true);
16533     } else if (FDTy->isObjCObjectType()) {
16534       /// A field cannot be an Objective-c object
16535       Diag(FD->getLocation(), diag::err_statically_allocated_object)
16536         << FixItHint::CreateInsertion(FD->getLocation(), "*");
16537       QualType T = Context.getObjCObjectPointerType(FD->getType());
16538       FD->setType(T);
16539     } else if (Record && Record->isUnion() &&
16540                FD->getType().hasNonTrivialObjCLifetime() &&
16541                getSourceManager().isInSystemHeader(FD->getLocation()) &&
16542                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
16543                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
16544                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
16545       // For backward compatibility, fields of C unions declared in system
16546       // headers that have non-trivial ObjC ownership qualifications are marked
16547       // as unavailable unless the qualifier is explicit and __strong. This can
16548       // break ABI compatibility between programs compiled with ARC and MRR, but
16549       // is a better option than rejecting programs using those unions under
16550       // ARC.
16551       FD->addAttr(UnavailableAttr::CreateImplicit(
16552           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
16553           FD->getLocation()));
16554     } else if (getLangOpts().ObjC &&
16555                getLangOpts().getGC() != LangOptions::NonGC &&
16556                Record && !Record->hasObjectMember()) {
16557       if (FD->getType()->isObjCObjectPointerType() ||
16558           FD->getType().isObjCGCStrong())
16559         Record->setHasObjectMember(true);
16560       else if (Context.getAsArrayType(FD->getType())) {
16561         QualType BaseType = Context.getBaseElementType(FD->getType());
16562         if (BaseType->isRecordType() &&
16563             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
16564           Record->setHasObjectMember(true);
16565         else if (BaseType->isObjCObjectPointerType() ||
16566                  BaseType.isObjCGCStrong())
16567                Record->setHasObjectMember(true);
16568       }
16569     }
16570 
16571     if (Record && !getLangOpts().CPlusPlus &&
16572         !shouldIgnoreForRecordTriviality(FD)) {
16573       QualType FT = FD->getType();
16574       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
16575         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
16576         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
16577             Record->isUnion())
16578           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
16579       }
16580       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
16581       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
16582         Record->setNonTrivialToPrimitiveCopy(true);
16583         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
16584           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
16585       }
16586       if (FT.isDestructedType()) {
16587         Record->setNonTrivialToPrimitiveDestroy(true);
16588         Record->setParamDestroyedInCallee(true);
16589         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
16590           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
16591       }
16592 
16593       if (const auto *RT = FT->getAs<RecordType>()) {
16594         if (RT->getDecl()->getArgPassingRestrictions() ==
16595             RecordDecl::APK_CanNeverPassInRegs)
16596           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16597       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
16598         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16599     }
16600 
16601     if (Record && FD->getType().isVolatileQualified())
16602       Record->setHasVolatileMember(true);
16603     // Keep track of the number of named members.
16604     if (FD->getIdentifier())
16605       ++NumNamedMembers;
16606   }
16607 
16608   // Okay, we successfully defined 'Record'.
16609   if (Record) {
16610     bool Completed = false;
16611     if (CXXRecord) {
16612       if (!CXXRecord->isInvalidDecl()) {
16613         // Set access bits correctly on the directly-declared conversions.
16614         for (CXXRecordDecl::conversion_iterator
16615                I = CXXRecord->conversion_begin(),
16616                E = CXXRecord->conversion_end(); I != E; ++I)
16617           I.setAccess((*I)->getAccess());
16618       }
16619 
16620       if (!CXXRecord->isDependentType()) {
16621         // Add any implicitly-declared members to this class.
16622         AddImplicitlyDeclaredMembersToClass(CXXRecord);
16623 
16624         if (!CXXRecord->isInvalidDecl()) {
16625           // If we have virtual base classes, we may end up finding multiple
16626           // final overriders for a given virtual function. Check for this
16627           // problem now.
16628           if (CXXRecord->getNumVBases()) {
16629             CXXFinalOverriderMap FinalOverriders;
16630             CXXRecord->getFinalOverriders(FinalOverriders);
16631 
16632             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
16633                                              MEnd = FinalOverriders.end();
16634                  M != MEnd; ++M) {
16635               for (OverridingMethods::iterator SO = M->second.begin(),
16636                                             SOEnd = M->second.end();
16637                    SO != SOEnd; ++SO) {
16638                 assert(SO->second.size() > 0 &&
16639                        "Virtual function without overriding functions?");
16640                 if (SO->second.size() == 1)
16641                   continue;
16642 
16643                 // C++ [class.virtual]p2:
16644                 //   In a derived class, if a virtual member function of a base
16645                 //   class subobject has more than one final overrider the
16646                 //   program is ill-formed.
16647                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
16648                   << (const NamedDecl *)M->first << Record;
16649                 Diag(M->first->getLocation(),
16650                      diag::note_overridden_virtual_function);
16651                 for (OverridingMethods::overriding_iterator
16652                           OM = SO->second.begin(),
16653                        OMEnd = SO->second.end();
16654                      OM != OMEnd; ++OM)
16655                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
16656                     << (const NamedDecl *)M->first << OM->Method->getParent();
16657 
16658                 Record->setInvalidDecl();
16659               }
16660             }
16661             CXXRecord->completeDefinition(&FinalOverriders);
16662             Completed = true;
16663           }
16664         }
16665       }
16666     }
16667 
16668     if (!Completed)
16669       Record->completeDefinition();
16670 
16671     // Handle attributes before checking the layout.
16672     ProcessDeclAttributeList(S, Record, Attrs);
16673 
16674     // We may have deferred checking for a deleted destructor. Check now.
16675     if (CXXRecord) {
16676       auto *Dtor = CXXRecord->getDestructor();
16677       if (Dtor && Dtor->isImplicit() &&
16678           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
16679         CXXRecord->setImplicitDestructorIsDeleted();
16680         SetDeclDeleted(Dtor, CXXRecord->getLocation());
16681       }
16682     }
16683 
16684     if (Record->hasAttrs()) {
16685       CheckAlignasUnderalignment(Record);
16686 
16687       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
16688         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
16689                                            IA->getRange(), IA->getBestCase(),
16690                                            IA->getSemanticSpelling());
16691     }
16692 
16693     // Check if the structure/union declaration is a type that can have zero
16694     // size in C. For C this is a language extension, for C++ it may cause
16695     // compatibility problems.
16696     bool CheckForZeroSize;
16697     if (!getLangOpts().CPlusPlus) {
16698       CheckForZeroSize = true;
16699     } else {
16700       // For C++ filter out types that cannot be referenced in C code.
16701       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
16702       CheckForZeroSize =
16703           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
16704           !CXXRecord->isDependentType() &&
16705           CXXRecord->isCLike();
16706     }
16707     if (CheckForZeroSize) {
16708       bool ZeroSize = true;
16709       bool IsEmpty = true;
16710       unsigned NonBitFields = 0;
16711       for (RecordDecl::field_iterator I = Record->field_begin(),
16712                                       E = Record->field_end();
16713            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
16714         IsEmpty = false;
16715         if (I->isUnnamedBitfield()) {
16716           if (!I->isZeroLengthBitField(Context))
16717             ZeroSize = false;
16718         } else {
16719           ++NonBitFields;
16720           QualType FieldType = I->getType();
16721           if (FieldType->isIncompleteType() ||
16722               !Context.getTypeSizeInChars(FieldType).isZero())
16723             ZeroSize = false;
16724         }
16725       }
16726 
16727       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
16728       // allowed in C++, but warn if its declaration is inside
16729       // extern "C" block.
16730       if (ZeroSize) {
16731         Diag(RecLoc, getLangOpts().CPlusPlus ?
16732                          diag::warn_zero_size_struct_union_in_extern_c :
16733                          diag::warn_zero_size_struct_union_compat)
16734           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
16735       }
16736 
16737       // Structs without named members are extension in C (C99 6.7.2.1p7),
16738       // but are accepted by GCC.
16739       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
16740         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
16741                                diag::ext_no_named_members_in_struct_union)
16742           << Record->isUnion();
16743       }
16744     }
16745   } else {
16746     ObjCIvarDecl **ClsFields =
16747       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
16748     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
16749       ID->setEndOfDefinitionLoc(RBrac);
16750       // Add ivar's to class's DeclContext.
16751       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16752         ClsFields[i]->setLexicalDeclContext(ID);
16753         ID->addDecl(ClsFields[i]);
16754       }
16755       // Must enforce the rule that ivars in the base classes may not be
16756       // duplicates.
16757       if (ID->getSuperClass())
16758         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
16759     } else if (ObjCImplementationDecl *IMPDecl =
16760                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16761       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
16762       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
16763         // Ivar declared in @implementation never belongs to the implementation.
16764         // Only it is in implementation's lexical context.
16765         ClsFields[I]->setLexicalDeclContext(IMPDecl);
16766       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
16767       IMPDecl->setIvarLBraceLoc(LBrac);
16768       IMPDecl->setIvarRBraceLoc(RBrac);
16769     } else if (ObjCCategoryDecl *CDecl =
16770                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16771       // case of ivars in class extension; all other cases have been
16772       // reported as errors elsewhere.
16773       // FIXME. Class extension does not have a LocEnd field.
16774       // CDecl->setLocEnd(RBrac);
16775       // Add ivar's to class extension's DeclContext.
16776       // Diagnose redeclaration of private ivars.
16777       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
16778       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16779         if (IDecl) {
16780           if (const ObjCIvarDecl *ClsIvar =
16781               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
16782             Diag(ClsFields[i]->getLocation(),
16783                  diag::err_duplicate_ivar_declaration);
16784             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
16785             continue;
16786           }
16787           for (const auto *Ext : IDecl->known_extensions()) {
16788             if (const ObjCIvarDecl *ClsExtIvar
16789                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
16790               Diag(ClsFields[i]->getLocation(),
16791                    diag::err_duplicate_ivar_declaration);
16792               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
16793               continue;
16794             }
16795           }
16796         }
16797         ClsFields[i]->setLexicalDeclContext(CDecl);
16798         CDecl->addDecl(ClsFields[i]);
16799       }
16800       CDecl->setIvarLBraceLoc(LBrac);
16801       CDecl->setIvarRBraceLoc(RBrac);
16802     }
16803   }
16804 }
16805 
16806 /// Determine whether the given integral value is representable within
16807 /// the given type T.
16808 static bool isRepresentableIntegerValue(ASTContext &Context,
16809                                         llvm::APSInt &Value,
16810                                         QualType T) {
16811   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
16812          "Integral type required!");
16813   unsigned BitWidth = Context.getIntWidth(T);
16814 
16815   if (Value.isUnsigned() || Value.isNonNegative()) {
16816     if (T->isSignedIntegerOrEnumerationType())
16817       --BitWidth;
16818     return Value.getActiveBits() <= BitWidth;
16819   }
16820   return Value.getMinSignedBits() <= BitWidth;
16821 }
16822 
16823 // Given an integral type, return the next larger integral type
16824 // (or a NULL type of no such type exists).
16825 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
16826   // FIXME: Int128/UInt128 support, which also needs to be introduced into
16827   // enum checking below.
16828   assert((T->isIntegralType(Context) ||
16829          T->isEnumeralType()) && "Integral type required!");
16830   const unsigned NumTypes = 4;
16831   QualType SignedIntegralTypes[NumTypes] = {
16832     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
16833   };
16834   QualType UnsignedIntegralTypes[NumTypes] = {
16835     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
16836     Context.UnsignedLongLongTy
16837   };
16838 
16839   unsigned BitWidth = Context.getTypeSize(T);
16840   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
16841                                                         : UnsignedIntegralTypes;
16842   for (unsigned I = 0; I != NumTypes; ++I)
16843     if (Context.getTypeSize(Types[I]) > BitWidth)
16844       return Types[I];
16845 
16846   return QualType();
16847 }
16848 
16849 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
16850                                           EnumConstantDecl *LastEnumConst,
16851                                           SourceLocation IdLoc,
16852                                           IdentifierInfo *Id,
16853                                           Expr *Val) {
16854   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16855   llvm::APSInt EnumVal(IntWidth);
16856   QualType EltTy;
16857 
16858   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
16859     Val = nullptr;
16860 
16861   if (Val)
16862     Val = DefaultLvalueConversion(Val).get();
16863 
16864   if (Val) {
16865     if (Enum->isDependentType() || Val->isTypeDependent())
16866       EltTy = Context.DependentTy;
16867     else {
16868       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
16869         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
16870         // constant-expression in the enumerator-definition shall be a converted
16871         // constant expression of the underlying type.
16872         EltTy = Enum->getIntegerType();
16873         ExprResult Converted =
16874           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
16875                                            CCEK_Enumerator);
16876         if (Converted.isInvalid())
16877           Val = nullptr;
16878         else
16879           Val = Converted.get();
16880       } else if (!Val->isValueDependent() &&
16881                  !(Val = VerifyIntegerConstantExpression(Val,
16882                                                          &EnumVal).get())) {
16883         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
16884       } else {
16885         if (Enum->isComplete()) {
16886           EltTy = Enum->getIntegerType();
16887 
16888           // In Obj-C and Microsoft mode, require the enumeration value to be
16889           // representable in the underlying type of the enumeration. In C++11,
16890           // we perform a non-narrowing conversion as part of converted constant
16891           // expression checking.
16892           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
16893             if (Context.getTargetInfo()
16894                     .getTriple()
16895                     .isWindowsMSVCEnvironment()) {
16896               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
16897             } else {
16898               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
16899             }
16900           }
16901 
16902           // Cast to the underlying type.
16903           Val = ImpCastExprToType(Val, EltTy,
16904                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
16905                                                          : CK_IntegralCast)
16906                     .get();
16907         } else if (getLangOpts().CPlusPlus) {
16908           // C++11 [dcl.enum]p5:
16909           //   If the underlying type is not fixed, the type of each enumerator
16910           //   is the type of its initializing value:
16911           //     - If an initializer is specified for an enumerator, the
16912           //       initializing value has the same type as the expression.
16913           EltTy = Val->getType();
16914         } else {
16915           // C99 6.7.2.2p2:
16916           //   The expression that defines the value of an enumeration constant
16917           //   shall be an integer constant expression that has a value
16918           //   representable as an int.
16919 
16920           // Complain if the value is not representable in an int.
16921           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
16922             Diag(IdLoc, diag::ext_enum_value_not_int)
16923               << EnumVal.toString(10) << Val->getSourceRange()
16924               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
16925           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
16926             // Force the type of the expression to 'int'.
16927             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
16928           }
16929           EltTy = Val->getType();
16930         }
16931       }
16932     }
16933   }
16934 
16935   if (!Val) {
16936     if (Enum->isDependentType())
16937       EltTy = Context.DependentTy;
16938     else if (!LastEnumConst) {
16939       // C++0x [dcl.enum]p5:
16940       //   If the underlying type is not fixed, the type of each enumerator
16941       //   is the type of its initializing value:
16942       //     - If no initializer is specified for the first enumerator, the
16943       //       initializing value has an unspecified integral type.
16944       //
16945       // GCC uses 'int' for its unspecified integral type, as does
16946       // C99 6.7.2.2p3.
16947       if (Enum->isFixed()) {
16948         EltTy = Enum->getIntegerType();
16949       }
16950       else {
16951         EltTy = Context.IntTy;
16952       }
16953     } else {
16954       // Assign the last value + 1.
16955       EnumVal = LastEnumConst->getInitVal();
16956       ++EnumVal;
16957       EltTy = LastEnumConst->getType();
16958 
16959       // Check for overflow on increment.
16960       if (EnumVal < LastEnumConst->getInitVal()) {
16961         // C++0x [dcl.enum]p5:
16962         //   If the underlying type is not fixed, the type of each enumerator
16963         //   is the type of its initializing value:
16964         //
16965         //     - Otherwise the type of the initializing value is the same as
16966         //       the type of the initializing value of the preceding enumerator
16967         //       unless the incremented value is not representable in that type,
16968         //       in which case the type is an unspecified integral type
16969         //       sufficient to contain the incremented value. If no such type
16970         //       exists, the program is ill-formed.
16971         QualType T = getNextLargerIntegralType(Context, EltTy);
16972         if (T.isNull() || Enum->isFixed()) {
16973           // There is no integral type larger enough to represent this
16974           // value. Complain, then allow the value to wrap around.
16975           EnumVal = LastEnumConst->getInitVal();
16976           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
16977           ++EnumVal;
16978           if (Enum->isFixed())
16979             // When the underlying type is fixed, this is ill-formed.
16980             Diag(IdLoc, diag::err_enumerator_wrapped)
16981               << EnumVal.toString(10)
16982               << EltTy;
16983           else
16984             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
16985               << EnumVal.toString(10);
16986         } else {
16987           EltTy = T;
16988         }
16989 
16990         // Retrieve the last enumerator's value, extent that type to the
16991         // type that is supposed to be large enough to represent the incremented
16992         // value, then increment.
16993         EnumVal = LastEnumConst->getInitVal();
16994         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
16995         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
16996         ++EnumVal;
16997 
16998         // If we're not in C++, diagnose the overflow of enumerator values,
16999         // which in C99 means that the enumerator value is not representable in
17000         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
17001         // permits enumerator values that are representable in some larger
17002         // integral type.
17003         if (!getLangOpts().CPlusPlus && !T.isNull())
17004           Diag(IdLoc, diag::warn_enum_value_overflow);
17005       } else if (!getLangOpts().CPlusPlus &&
17006                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17007         // Enforce C99 6.7.2.2p2 even when we compute the next value.
17008         Diag(IdLoc, diag::ext_enum_value_not_int)
17009           << EnumVal.toString(10) << 1;
17010       }
17011     }
17012   }
17013 
17014   if (!EltTy->isDependentType()) {
17015     // Make the enumerator value match the signedness and size of the
17016     // enumerator's type.
17017     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
17018     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17019   }
17020 
17021   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
17022                                   Val, EnumVal);
17023 }
17024 
17025 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
17026                                                 SourceLocation IILoc) {
17027   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
17028       !getLangOpts().CPlusPlus)
17029     return SkipBodyInfo();
17030 
17031   // We have an anonymous enum definition. Look up the first enumerator to
17032   // determine if we should merge the definition with an existing one and
17033   // skip the body.
17034   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
17035                                          forRedeclarationInCurContext());
17036   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
17037   if (!PrevECD)
17038     return SkipBodyInfo();
17039 
17040   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
17041   NamedDecl *Hidden;
17042   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
17043     SkipBodyInfo Skip;
17044     Skip.Previous = Hidden;
17045     return Skip;
17046   }
17047 
17048   return SkipBodyInfo();
17049 }
17050 
17051 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
17052                               SourceLocation IdLoc, IdentifierInfo *Id,
17053                               const ParsedAttributesView &Attrs,
17054                               SourceLocation EqualLoc, Expr *Val) {
17055   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
17056   EnumConstantDecl *LastEnumConst =
17057     cast_or_null<EnumConstantDecl>(lastEnumConst);
17058 
17059   // The scope passed in may not be a decl scope.  Zip up the scope tree until
17060   // we find one that is.
17061   S = getNonFieldDeclScope(S);
17062 
17063   // Verify that there isn't already something declared with this name in this
17064   // scope.
17065   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
17066   LookupName(R, S);
17067   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
17068 
17069   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17070     // Maybe we will complain about the shadowed template parameter.
17071     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
17072     // Just pretend that we didn't see the previous declaration.
17073     PrevDecl = nullptr;
17074   }
17075 
17076   // C++ [class.mem]p15:
17077   // If T is the name of a class, then each of the following shall have a name
17078   // different from T:
17079   // - every enumerator of every member of class T that is an unscoped
17080   // enumerated type
17081   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
17082     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
17083                             DeclarationNameInfo(Id, IdLoc));
17084 
17085   EnumConstantDecl *New =
17086     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
17087   if (!New)
17088     return nullptr;
17089 
17090   if (PrevDecl) {
17091     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
17092       // Check for other kinds of shadowing not already handled.
17093       CheckShadow(New, PrevDecl, R);
17094     }
17095 
17096     // When in C++, we may get a TagDecl with the same name; in this case the
17097     // enum constant will 'hide' the tag.
17098     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
17099            "Received TagDecl when not in C++!");
17100     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
17101       if (isa<EnumConstantDecl>(PrevDecl))
17102         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
17103       else
17104         Diag(IdLoc, diag::err_redefinition) << Id;
17105       notePreviousDefinition(PrevDecl, IdLoc);
17106       return nullptr;
17107     }
17108   }
17109 
17110   // Process attributes.
17111   ProcessDeclAttributeList(S, New, Attrs);
17112   AddPragmaAttributes(S, New);
17113 
17114   // Register this decl in the current scope stack.
17115   New->setAccess(TheEnumDecl->getAccess());
17116   PushOnScopeChains(New, S);
17117 
17118   ActOnDocumentableDecl(New);
17119 
17120   return New;
17121 }
17122 
17123 // Returns true when the enum initial expression does not trigger the
17124 // duplicate enum warning.  A few common cases are exempted as follows:
17125 // Element2 = Element1
17126 // Element2 = Element1 + 1
17127 // Element2 = Element1 - 1
17128 // Where Element2 and Element1 are from the same enum.
17129 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
17130   Expr *InitExpr = ECD->getInitExpr();
17131   if (!InitExpr)
17132     return true;
17133   InitExpr = InitExpr->IgnoreImpCasts();
17134 
17135   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
17136     if (!BO->isAdditiveOp())
17137       return true;
17138     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
17139     if (!IL)
17140       return true;
17141     if (IL->getValue() != 1)
17142       return true;
17143 
17144     InitExpr = BO->getLHS();
17145   }
17146 
17147   // This checks if the elements are from the same enum.
17148   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
17149   if (!DRE)
17150     return true;
17151 
17152   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
17153   if (!EnumConstant)
17154     return true;
17155 
17156   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
17157       Enum)
17158     return true;
17159 
17160   return false;
17161 }
17162 
17163 // Emits a warning when an element is implicitly set a value that
17164 // a previous element has already been set to.
17165 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
17166                                         EnumDecl *Enum, QualType EnumType) {
17167   // Avoid anonymous enums
17168   if (!Enum->getIdentifier())
17169     return;
17170 
17171   // Only check for small enums.
17172   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
17173     return;
17174 
17175   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
17176     return;
17177 
17178   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
17179   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
17180 
17181   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
17182   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
17183 
17184   // Use int64_t as a key to avoid needing special handling for DenseMap keys.
17185   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
17186     llvm::APSInt Val = D->getInitVal();
17187     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
17188   };
17189 
17190   DuplicatesVector DupVector;
17191   ValueToVectorMap EnumMap;
17192 
17193   // Populate the EnumMap with all values represented by enum constants without
17194   // an initializer.
17195   for (auto *Element : Elements) {
17196     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
17197 
17198     // Null EnumConstantDecl means a previous diagnostic has been emitted for
17199     // this constant.  Skip this enum since it may be ill-formed.
17200     if (!ECD) {
17201       return;
17202     }
17203 
17204     // Constants with initalizers are handled in the next loop.
17205     if (ECD->getInitExpr())
17206       continue;
17207 
17208     // Duplicate values are handled in the next loop.
17209     EnumMap.insert({EnumConstantToKey(ECD), ECD});
17210   }
17211 
17212   if (EnumMap.size() == 0)
17213     return;
17214 
17215   // Create vectors for any values that has duplicates.
17216   for (auto *Element : Elements) {
17217     // The last loop returned if any constant was null.
17218     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
17219     if (!ValidDuplicateEnum(ECD, Enum))
17220       continue;
17221 
17222     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
17223     if (Iter == EnumMap.end())
17224       continue;
17225 
17226     DeclOrVector& Entry = Iter->second;
17227     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
17228       // Ensure constants are different.
17229       if (D == ECD)
17230         continue;
17231 
17232       // Create new vector and push values onto it.
17233       auto Vec = std::make_unique<ECDVector>();
17234       Vec->push_back(D);
17235       Vec->push_back(ECD);
17236 
17237       // Update entry to point to the duplicates vector.
17238       Entry = Vec.get();
17239 
17240       // Store the vector somewhere we can consult later for quick emission of
17241       // diagnostics.
17242       DupVector.emplace_back(std::move(Vec));
17243       continue;
17244     }
17245 
17246     ECDVector *Vec = Entry.get<ECDVector*>();
17247     // Make sure constants are not added more than once.
17248     if (*Vec->begin() == ECD)
17249       continue;
17250 
17251     Vec->push_back(ECD);
17252   }
17253 
17254   // Emit diagnostics.
17255   for (const auto &Vec : DupVector) {
17256     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
17257 
17258     // Emit warning for one enum constant.
17259     auto *FirstECD = Vec->front();
17260     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
17261       << FirstECD << FirstECD->getInitVal().toString(10)
17262       << FirstECD->getSourceRange();
17263 
17264     // Emit one note for each of the remaining enum constants with
17265     // the same value.
17266     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
17267       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
17268         << ECD << ECD->getInitVal().toString(10)
17269         << ECD->getSourceRange();
17270   }
17271 }
17272 
17273 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
17274                              bool AllowMask) const {
17275   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
17276   assert(ED->isCompleteDefinition() && "expected enum definition");
17277 
17278   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
17279   llvm::APInt &FlagBits = R.first->second;
17280 
17281   if (R.second) {
17282     for (auto *E : ED->enumerators()) {
17283       const auto &EVal = E->getInitVal();
17284       // Only single-bit enumerators introduce new flag values.
17285       if (EVal.isPowerOf2())
17286         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
17287     }
17288   }
17289 
17290   // A value is in a flag enum if either its bits are a subset of the enum's
17291   // flag bits (the first condition) or we are allowing masks and the same is
17292   // true of its complement (the second condition). When masks are allowed, we
17293   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
17294   //
17295   // While it's true that any value could be used as a mask, the assumption is
17296   // that a mask will have all of the insignificant bits set. Anything else is
17297   // likely a logic error.
17298   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
17299   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
17300 }
17301 
17302 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
17303                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
17304                          const ParsedAttributesView &Attrs) {
17305   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
17306   QualType EnumType = Context.getTypeDeclType(Enum);
17307 
17308   ProcessDeclAttributeList(S, Enum, Attrs);
17309 
17310   if (Enum->isDependentType()) {
17311     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17312       EnumConstantDecl *ECD =
17313         cast_or_null<EnumConstantDecl>(Elements[i]);
17314       if (!ECD) continue;
17315 
17316       ECD->setType(EnumType);
17317     }
17318 
17319     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
17320     return;
17321   }
17322 
17323   // TODO: If the result value doesn't fit in an int, it must be a long or long
17324   // long value.  ISO C does not support this, but GCC does as an extension,
17325   // emit a warning.
17326   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17327   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
17328   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
17329 
17330   // Verify that all the values are okay, compute the size of the values, and
17331   // reverse the list.
17332   unsigned NumNegativeBits = 0;
17333   unsigned NumPositiveBits = 0;
17334 
17335   // Keep track of whether all elements have type int.
17336   bool AllElementsInt = true;
17337 
17338   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17339     EnumConstantDecl *ECD =
17340       cast_or_null<EnumConstantDecl>(Elements[i]);
17341     if (!ECD) continue;  // Already issued a diagnostic.
17342 
17343     const llvm::APSInt &InitVal = ECD->getInitVal();
17344 
17345     // Keep track of the size of positive and negative values.
17346     if (InitVal.isUnsigned() || InitVal.isNonNegative())
17347       NumPositiveBits = std::max(NumPositiveBits,
17348                                  (unsigned)InitVal.getActiveBits());
17349     else
17350       NumNegativeBits = std::max(NumNegativeBits,
17351                                  (unsigned)InitVal.getMinSignedBits());
17352 
17353     // Keep track of whether every enum element has type int (very common).
17354     if (AllElementsInt)
17355       AllElementsInt = ECD->getType() == Context.IntTy;
17356   }
17357 
17358   // Figure out the type that should be used for this enum.
17359   QualType BestType;
17360   unsigned BestWidth;
17361 
17362   // C++0x N3000 [conv.prom]p3:
17363   //   An rvalue of an unscoped enumeration type whose underlying
17364   //   type is not fixed can be converted to an rvalue of the first
17365   //   of the following types that can represent all the values of
17366   //   the enumeration: int, unsigned int, long int, unsigned long
17367   //   int, long long int, or unsigned long long int.
17368   // C99 6.4.4.3p2:
17369   //   An identifier declared as an enumeration constant has type int.
17370   // The C99 rule is modified by a gcc extension
17371   QualType BestPromotionType;
17372 
17373   bool Packed = Enum->hasAttr<PackedAttr>();
17374   // -fshort-enums is the equivalent to specifying the packed attribute on all
17375   // enum definitions.
17376   if (LangOpts.ShortEnums)
17377     Packed = true;
17378 
17379   // If the enum already has a type because it is fixed or dictated by the
17380   // target, promote that type instead of analyzing the enumerators.
17381   if (Enum->isComplete()) {
17382     BestType = Enum->getIntegerType();
17383     if (BestType->isPromotableIntegerType())
17384       BestPromotionType = Context.getPromotedIntegerType(BestType);
17385     else
17386       BestPromotionType = BestType;
17387 
17388     BestWidth = Context.getIntWidth(BestType);
17389   }
17390   else if (NumNegativeBits) {
17391     // If there is a negative value, figure out the smallest integer type (of
17392     // int/long/longlong) that fits.
17393     // If it's packed, check also if it fits a char or a short.
17394     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
17395       BestType = Context.SignedCharTy;
17396       BestWidth = CharWidth;
17397     } else if (Packed && NumNegativeBits <= ShortWidth &&
17398                NumPositiveBits < ShortWidth) {
17399       BestType = Context.ShortTy;
17400       BestWidth = ShortWidth;
17401     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
17402       BestType = Context.IntTy;
17403       BestWidth = IntWidth;
17404     } else {
17405       BestWidth = Context.getTargetInfo().getLongWidth();
17406 
17407       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
17408         BestType = Context.LongTy;
17409       } else {
17410         BestWidth = Context.getTargetInfo().getLongLongWidth();
17411 
17412         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
17413           Diag(Enum->getLocation(), diag::ext_enum_too_large);
17414         BestType = Context.LongLongTy;
17415       }
17416     }
17417     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
17418   } else {
17419     // If there is no negative value, figure out the smallest type that fits
17420     // all of the enumerator values.
17421     // If it's packed, check also if it fits a char or a short.
17422     if (Packed && NumPositiveBits <= CharWidth) {
17423       BestType = Context.UnsignedCharTy;
17424       BestPromotionType = Context.IntTy;
17425       BestWidth = CharWidth;
17426     } else if (Packed && NumPositiveBits <= ShortWidth) {
17427       BestType = Context.UnsignedShortTy;
17428       BestPromotionType = Context.IntTy;
17429       BestWidth = ShortWidth;
17430     } else if (NumPositiveBits <= IntWidth) {
17431       BestType = Context.UnsignedIntTy;
17432       BestWidth = IntWidth;
17433       BestPromotionType
17434         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17435                            ? Context.UnsignedIntTy : Context.IntTy;
17436     } else if (NumPositiveBits <=
17437                (BestWidth = Context.getTargetInfo().getLongWidth())) {
17438       BestType = Context.UnsignedLongTy;
17439       BestPromotionType
17440         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17441                            ? Context.UnsignedLongTy : Context.LongTy;
17442     } else {
17443       BestWidth = Context.getTargetInfo().getLongLongWidth();
17444       assert(NumPositiveBits <= BestWidth &&
17445              "How could an initializer get larger than ULL?");
17446       BestType = Context.UnsignedLongLongTy;
17447       BestPromotionType
17448         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17449                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
17450     }
17451   }
17452 
17453   // Loop over all of the enumerator constants, changing their types to match
17454   // the type of the enum if needed.
17455   for (auto *D : Elements) {
17456     auto *ECD = cast_or_null<EnumConstantDecl>(D);
17457     if (!ECD) continue;  // Already issued a diagnostic.
17458 
17459     // Standard C says the enumerators have int type, but we allow, as an
17460     // extension, the enumerators to be larger than int size.  If each
17461     // enumerator value fits in an int, type it as an int, otherwise type it the
17462     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
17463     // that X has type 'int', not 'unsigned'.
17464 
17465     // Determine whether the value fits into an int.
17466     llvm::APSInt InitVal = ECD->getInitVal();
17467 
17468     // If it fits into an integer type, force it.  Otherwise force it to match
17469     // the enum decl type.
17470     QualType NewTy;
17471     unsigned NewWidth;
17472     bool NewSign;
17473     if (!getLangOpts().CPlusPlus &&
17474         !Enum->isFixed() &&
17475         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
17476       NewTy = Context.IntTy;
17477       NewWidth = IntWidth;
17478       NewSign = true;
17479     } else if (ECD->getType() == BestType) {
17480       // Already the right type!
17481       if (getLangOpts().CPlusPlus)
17482         // C++ [dcl.enum]p4: Following the closing brace of an
17483         // enum-specifier, each enumerator has the type of its
17484         // enumeration.
17485         ECD->setType(EnumType);
17486       continue;
17487     } else {
17488       NewTy = BestType;
17489       NewWidth = BestWidth;
17490       NewSign = BestType->isSignedIntegerOrEnumerationType();
17491     }
17492 
17493     // Adjust the APSInt value.
17494     InitVal = InitVal.extOrTrunc(NewWidth);
17495     InitVal.setIsSigned(NewSign);
17496     ECD->setInitVal(InitVal);
17497 
17498     // Adjust the Expr initializer and type.
17499     if (ECD->getInitExpr() &&
17500         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
17501       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
17502                                                 CK_IntegralCast,
17503                                                 ECD->getInitExpr(),
17504                                                 /*base paths*/ nullptr,
17505                                                 VK_RValue));
17506     if (getLangOpts().CPlusPlus)
17507       // C++ [dcl.enum]p4: Following the closing brace of an
17508       // enum-specifier, each enumerator has the type of its
17509       // enumeration.
17510       ECD->setType(EnumType);
17511     else
17512       ECD->setType(NewTy);
17513   }
17514 
17515   Enum->completeDefinition(BestType, BestPromotionType,
17516                            NumPositiveBits, NumNegativeBits);
17517 
17518   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
17519 
17520   if (Enum->isClosedFlag()) {
17521     for (Decl *D : Elements) {
17522       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
17523       if (!ECD) continue;  // Already issued a diagnostic.
17524 
17525       llvm::APSInt InitVal = ECD->getInitVal();
17526       if (InitVal != 0 && !InitVal.isPowerOf2() &&
17527           !IsValueInFlagEnum(Enum, InitVal, true))
17528         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
17529           << ECD << Enum;
17530     }
17531   }
17532 
17533   // Now that the enum type is defined, ensure it's not been underaligned.
17534   if (Enum->hasAttrs())
17535     CheckAlignasUnderalignment(Enum);
17536 }
17537 
17538 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
17539                                   SourceLocation StartLoc,
17540                                   SourceLocation EndLoc) {
17541   StringLiteral *AsmString = cast<StringLiteral>(expr);
17542 
17543   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
17544                                                    AsmString, StartLoc,
17545                                                    EndLoc);
17546   CurContext->addDecl(New);
17547   return New;
17548 }
17549 
17550 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
17551                                       IdentifierInfo* AliasName,
17552                                       SourceLocation PragmaLoc,
17553                                       SourceLocation NameLoc,
17554                                       SourceLocation AliasNameLoc) {
17555   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
17556                                          LookupOrdinaryName);
17557   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
17558                            AttributeCommonInfo::AS_Pragma);
17559   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
17560       Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
17561 
17562   // If a declaration that:
17563   // 1) declares a function or a variable
17564   // 2) has external linkage
17565   // already exists, add a label attribute to it.
17566   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17567     if (isDeclExternC(PrevDecl))
17568       PrevDecl->addAttr(Attr);
17569     else
17570       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
17571           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
17572   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
17573   } else
17574     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
17575 }
17576 
17577 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
17578                              SourceLocation PragmaLoc,
17579                              SourceLocation NameLoc) {
17580   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
17581 
17582   if (PrevDecl) {
17583     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
17584   } else {
17585     (void)WeakUndeclaredIdentifiers.insert(
17586       std::pair<IdentifierInfo*,WeakInfo>
17587         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
17588   }
17589 }
17590 
17591 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
17592                                 IdentifierInfo* AliasName,
17593                                 SourceLocation PragmaLoc,
17594                                 SourceLocation NameLoc,
17595                                 SourceLocation AliasNameLoc) {
17596   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
17597                                     LookupOrdinaryName);
17598   WeakInfo W = WeakInfo(Name, NameLoc);
17599 
17600   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17601     if (!PrevDecl->hasAttr<AliasAttr>())
17602       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
17603         DeclApplyPragmaWeak(TUScope, ND, W);
17604   } else {
17605     (void)WeakUndeclaredIdentifiers.insert(
17606       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
17607   }
17608 }
17609 
17610 Decl *Sema::getObjCDeclContext() const {
17611   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
17612 }
17613