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 llvm::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       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1989           << getHeaderName(Context.BuiltinInfo, ID, Error)
1990           << Context.BuiltinInfo.getName(ID);
1991     return nullptr;
1992   }
1993 
1994   if (!ForRedeclaration &&
1995       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1996        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1997     Diag(Loc, diag::ext_implicit_lib_function_decl)
1998         << Context.BuiltinInfo.getName(ID) << R;
1999     if (Context.BuiltinInfo.getHeaderName(ID) &&
2000         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
2001       Diag(Loc, diag::note_include_header_or_declare)
2002           << Context.BuiltinInfo.getHeaderName(ID)
2003           << Context.BuiltinInfo.getName(ID);
2004   }
2005 
2006   if (R.isNull())
2007     return nullptr;
2008 
2009   DeclContext *Parent = Context.getTranslationUnitDecl();
2010   if (getLangOpts().CPlusPlus) {
2011     LinkageSpecDecl *CLinkageDecl =
2012         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
2013                                 LinkageSpecDecl::lang_c, false);
2014     CLinkageDecl->setImplicit();
2015     Parent->addDecl(CLinkageDecl);
2016     Parent = CLinkageDecl;
2017   }
2018 
2019   FunctionDecl *New = FunctionDecl::Create(Context,
2020                                            Parent,
2021                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
2022                                            SC_Extern,
2023                                            false,
2024                                            R->isFunctionProtoType());
2025   New->setImplicit();
2026 
2027   // Create Decl objects for each parameter, adding them to the
2028   // FunctionDecl.
2029   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
2030     SmallVector<ParmVarDecl*, 16> Params;
2031     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2032       ParmVarDecl *parm =
2033           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2034                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2035                               SC_None, nullptr);
2036       parm->setScopeInfo(0, i);
2037       Params.push_back(parm);
2038     }
2039     New->setParams(Params);
2040   }
2041 
2042   AddKnownFunctionAttributes(New);
2043   RegisterLocallyScopedExternCDecl(New, S);
2044 
2045   // TUScope is the translation-unit scope to insert this function into.
2046   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2047   // relate Scopes to DeclContexts, and probably eliminate CurContext
2048   // entirely, but we're not there yet.
2049   DeclContext *SavedContext = CurContext;
2050   CurContext = Parent;
2051   PushOnScopeChains(New, TUScope);
2052   CurContext = SavedContext;
2053   return New;
2054 }
2055 
2056 /// Typedef declarations don't have linkage, but they still denote the same
2057 /// entity if their types are the same.
2058 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2059 /// isSameEntity.
2060 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2061                                                      TypedefNameDecl *Decl,
2062                                                      LookupResult &Previous) {
2063   // This is only interesting when modules are enabled.
2064   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2065     return;
2066 
2067   // Empty sets are uninteresting.
2068   if (Previous.empty())
2069     return;
2070 
2071   LookupResult::Filter Filter = Previous.makeFilter();
2072   while (Filter.hasNext()) {
2073     NamedDecl *Old = Filter.next();
2074 
2075     // Non-hidden declarations are never ignored.
2076     if (S.isVisible(Old))
2077       continue;
2078 
2079     // Declarations of the same entity are not ignored, even if they have
2080     // different linkages.
2081     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2082       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2083                                 Decl->getUnderlyingType()))
2084         continue;
2085 
2086       // If both declarations give a tag declaration a typedef name for linkage
2087       // purposes, then they declare the same entity.
2088       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2089           Decl->getAnonDeclWithTypedefName())
2090         continue;
2091     }
2092 
2093     Filter.erase();
2094   }
2095 
2096   Filter.done();
2097 }
2098 
2099 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2100   QualType OldType;
2101   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2102     OldType = OldTypedef->getUnderlyingType();
2103   else
2104     OldType = Context.getTypeDeclType(Old);
2105   QualType NewType = New->getUnderlyingType();
2106 
2107   if (NewType->isVariablyModifiedType()) {
2108     // Must not redefine a typedef with a variably-modified type.
2109     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2110     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2111       << Kind << NewType;
2112     if (Old->getLocation().isValid())
2113       notePreviousDefinition(Old, New->getLocation());
2114     New->setInvalidDecl();
2115     return true;
2116   }
2117 
2118   if (OldType != NewType &&
2119       !OldType->isDependentType() &&
2120       !NewType->isDependentType() &&
2121       !Context.hasSameType(OldType, NewType)) {
2122     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2123     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2124       << Kind << NewType << OldType;
2125     if (Old->getLocation().isValid())
2126       notePreviousDefinition(Old, New->getLocation());
2127     New->setInvalidDecl();
2128     return true;
2129   }
2130   return false;
2131 }
2132 
2133 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2134 /// same name and scope as a previous declaration 'Old'.  Figure out
2135 /// how to resolve this situation, merging decls or emitting
2136 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2137 ///
2138 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2139                                 LookupResult &OldDecls) {
2140   // If the new decl is known invalid already, don't bother doing any
2141   // merging checks.
2142   if (New->isInvalidDecl()) return;
2143 
2144   // Allow multiple definitions for ObjC built-in typedefs.
2145   // FIXME: Verify the underlying types are equivalent!
2146   if (getLangOpts().ObjC) {
2147     const IdentifierInfo *TypeID = New->getIdentifier();
2148     switch (TypeID->getLength()) {
2149     default: break;
2150     case 2:
2151       {
2152         if (!TypeID->isStr("id"))
2153           break;
2154         QualType T = New->getUnderlyingType();
2155         if (!T->isPointerType())
2156           break;
2157         if (!T->isVoidPointerType()) {
2158           QualType PT = T->getAs<PointerType>()->getPointeeType();
2159           if (!PT->isStructureType())
2160             break;
2161         }
2162         Context.setObjCIdRedefinitionType(T);
2163         // Install the built-in type for 'id', ignoring the current definition.
2164         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2165         return;
2166       }
2167     case 5:
2168       if (!TypeID->isStr("Class"))
2169         break;
2170       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2171       // Install the built-in type for 'Class', ignoring the current definition.
2172       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2173       return;
2174     case 3:
2175       if (!TypeID->isStr("SEL"))
2176         break;
2177       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2178       // Install the built-in type for 'SEL', ignoring the current definition.
2179       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2180       return;
2181     }
2182     // Fall through - the typedef name was not a builtin type.
2183   }
2184 
2185   // Verify the old decl was also a type.
2186   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2187   if (!Old) {
2188     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2189       << New->getDeclName();
2190 
2191     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2192     if (OldD->getLocation().isValid())
2193       notePreviousDefinition(OldD, New->getLocation());
2194 
2195     return New->setInvalidDecl();
2196   }
2197 
2198   // If the old declaration is invalid, just give up here.
2199   if (Old->isInvalidDecl())
2200     return New->setInvalidDecl();
2201 
2202   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2203     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2204     auto *NewTag = New->getAnonDeclWithTypedefName();
2205     NamedDecl *Hidden = nullptr;
2206     if (OldTag && NewTag &&
2207         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2208         !hasVisibleDefinition(OldTag, &Hidden)) {
2209       // There is a definition of this tag, but it is not visible. Use it
2210       // instead of our tag.
2211       New->setTypeForDecl(OldTD->getTypeForDecl());
2212       if (OldTD->isModed())
2213         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2214                                     OldTD->getUnderlyingType());
2215       else
2216         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2217 
2218       // Make the old tag definition visible.
2219       makeMergedDefinitionVisible(Hidden);
2220 
2221       // If this was an unscoped enumeration, yank all of its enumerators
2222       // out of the scope.
2223       if (isa<EnumDecl>(NewTag)) {
2224         Scope *EnumScope = getNonFieldDeclScope(S);
2225         for (auto *D : NewTag->decls()) {
2226           auto *ED = cast<EnumConstantDecl>(D);
2227           assert(EnumScope->isDeclScope(ED));
2228           EnumScope->RemoveDecl(ED);
2229           IdResolver.RemoveDecl(ED);
2230           ED->getLexicalDeclContext()->removeDecl(ED);
2231         }
2232       }
2233     }
2234   }
2235 
2236   // If the typedef types are not identical, reject them in all languages and
2237   // with any extensions enabled.
2238   if (isIncompatibleTypedef(Old, New))
2239     return;
2240 
2241   // The types match.  Link up the redeclaration chain and merge attributes if
2242   // the old declaration was a typedef.
2243   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2244     New->setPreviousDecl(Typedef);
2245     mergeDeclAttributes(New, Old);
2246   }
2247 
2248   if (getLangOpts().MicrosoftExt)
2249     return;
2250 
2251   if (getLangOpts().CPlusPlus) {
2252     // C++ [dcl.typedef]p2:
2253     //   In a given non-class scope, a typedef specifier can be used to
2254     //   redefine the name of any type declared in that scope to refer
2255     //   to the type to which it already refers.
2256     if (!isa<CXXRecordDecl>(CurContext))
2257       return;
2258 
2259     // C++0x [dcl.typedef]p4:
2260     //   In a given class scope, a typedef specifier can be used to redefine
2261     //   any class-name declared in that scope that is not also a typedef-name
2262     //   to refer to the type to which it already refers.
2263     //
2264     // This wording came in via DR424, which was a correction to the
2265     // wording in DR56, which accidentally banned code like:
2266     //
2267     //   struct S {
2268     //     typedef struct A { } A;
2269     //   };
2270     //
2271     // in the C++03 standard. We implement the C++0x semantics, which
2272     // allow the above but disallow
2273     //
2274     //   struct S {
2275     //     typedef int I;
2276     //     typedef int I;
2277     //   };
2278     //
2279     // since that was the intent of DR56.
2280     if (!isa<TypedefNameDecl>(Old))
2281       return;
2282 
2283     Diag(New->getLocation(), diag::err_redefinition)
2284       << New->getDeclName();
2285     notePreviousDefinition(Old, New->getLocation());
2286     return New->setInvalidDecl();
2287   }
2288 
2289   // Modules always permit redefinition of typedefs, as does C11.
2290   if (getLangOpts().Modules || getLangOpts().C11)
2291     return;
2292 
2293   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2294   // is normally mapped to an error, but can be controlled with
2295   // -Wtypedef-redefinition.  If either the original or the redefinition is
2296   // in a system header, don't emit this for compatibility with GCC.
2297   if (getDiagnostics().getSuppressSystemWarnings() &&
2298       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2299       (Old->isImplicit() ||
2300        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2301        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2302     return;
2303 
2304   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2305     << New->getDeclName();
2306   notePreviousDefinition(Old, New->getLocation());
2307 }
2308 
2309 /// DeclhasAttr - returns true if decl Declaration already has the target
2310 /// attribute.
2311 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2312   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2313   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2314   for (const auto *i : D->attrs())
2315     if (i->getKind() == A->getKind()) {
2316       if (Ann) {
2317         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2318           return true;
2319         continue;
2320       }
2321       // FIXME: Don't hardcode this check
2322       if (OA && isa<OwnershipAttr>(i))
2323         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2324       return true;
2325     }
2326 
2327   return false;
2328 }
2329 
2330 static bool isAttributeTargetADefinition(Decl *D) {
2331   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2332     return VD->isThisDeclarationADefinition();
2333   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2334     return TD->isCompleteDefinition() || TD->isBeingDefined();
2335   return true;
2336 }
2337 
2338 /// Merge alignment attributes from \p Old to \p New, taking into account the
2339 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2340 ///
2341 /// \return \c true if any attributes were added to \p New.
2342 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2343   // Look for alignas attributes on Old, and pick out whichever attribute
2344   // specifies the strictest alignment requirement.
2345   AlignedAttr *OldAlignasAttr = nullptr;
2346   AlignedAttr *OldStrictestAlignAttr = nullptr;
2347   unsigned OldAlign = 0;
2348   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2349     // FIXME: We have no way of representing inherited dependent alignments
2350     // in a case like:
2351     //   template<int A, int B> struct alignas(A) X;
2352     //   template<int A, int B> struct alignas(B) X {};
2353     // For now, we just ignore any alignas attributes which are not on the
2354     // definition in such a case.
2355     if (I->isAlignmentDependent())
2356       return false;
2357 
2358     if (I->isAlignas())
2359       OldAlignasAttr = I;
2360 
2361     unsigned Align = I->getAlignment(S.Context);
2362     if (Align > OldAlign) {
2363       OldAlign = Align;
2364       OldStrictestAlignAttr = I;
2365     }
2366   }
2367 
2368   // Look for alignas attributes on New.
2369   AlignedAttr *NewAlignasAttr = nullptr;
2370   unsigned NewAlign = 0;
2371   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2372     if (I->isAlignmentDependent())
2373       return false;
2374 
2375     if (I->isAlignas())
2376       NewAlignasAttr = I;
2377 
2378     unsigned Align = I->getAlignment(S.Context);
2379     if (Align > NewAlign)
2380       NewAlign = Align;
2381   }
2382 
2383   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2384     // Both declarations have 'alignas' attributes. We require them to match.
2385     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2386     // fall short. (If two declarations both have alignas, they must both match
2387     // every definition, and so must match each other if there is a definition.)
2388 
2389     // If either declaration only contains 'alignas(0)' specifiers, then it
2390     // specifies the natural alignment for the type.
2391     if (OldAlign == 0 || NewAlign == 0) {
2392       QualType Ty;
2393       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2394         Ty = VD->getType();
2395       else
2396         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2397 
2398       if (OldAlign == 0)
2399         OldAlign = S.Context.getTypeAlign(Ty);
2400       if (NewAlign == 0)
2401         NewAlign = S.Context.getTypeAlign(Ty);
2402     }
2403 
2404     if (OldAlign != NewAlign) {
2405       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2406         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2407         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2408       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2409     }
2410   }
2411 
2412   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2413     // C++11 [dcl.align]p6:
2414     //   if any declaration of an entity has an alignment-specifier,
2415     //   every defining declaration of that entity shall specify an
2416     //   equivalent alignment.
2417     // C11 6.7.5/7:
2418     //   If the definition of an object does not have an alignment
2419     //   specifier, any other declaration of that object shall also
2420     //   have no alignment specifier.
2421     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2422       << OldAlignasAttr;
2423     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2424       << OldAlignasAttr;
2425   }
2426 
2427   bool AnyAdded = false;
2428 
2429   // Ensure we have an attribute representing the strictest alignment.
2430   if (OldAlign > NewAlign) {
2431     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2432     Clone->setInherited(true);
2433     New->addAttr(Clone);
2434     AnyAdded = true;
2435   }
2436 
2437   // Ensure we have an alignas attribute if the old declaration had one.
2438   if (OldAlignasAttr && !NewAlignasAttr &&
2439       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2440     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2441     Clone->setInherited(true);
2442     New->addAttr(Clone);
2443     AnyAdded = true;
2444   }
2445 
2446   return AnyAdded;
2447 }
2448 
2449 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2450                                const InheritableAttr *Attr,
2451                                Sema::AvailabilityMergeKind AMK) {
2452   // This function copies an attribute Attr from a previous declaration to the
2453   // new declaration D if the new declaration doesn't itself have that attribute
2454   // yet or if that attribute allows duplicates.
2455   // If you're adding a new attribute that requires logic different from
2456   // "use explicit attribute on decl if present, else use attribute from
2457   // previous decl", for example if the attribute needs to be consistent
2458   // between redeclarations, you need to call a custom merge function here.
2459   InheritableAttr *NewAttr = nullptr;
2460   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2461   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2462     NewAttr = S.mergeAvailabilityAttr(
2463         D, AA->getRange(), AA->getPlatform(), AA->isImplicit(),
2464         AA->getIntroduced(), AA->getDeprecated(), AA->getObsoleted(),
2465         AA->getUnavailable(), AA->getMessage(), AA->getStrict(),
2466         AA->getReplacement(), AMK, AA->getPriority(), AttrSpellingListIndex);
2467   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2468     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2469                                     AttrSpellingListIndex);
2470   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2471     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2472                                         AttrSpellingListIndex);
2473   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2474     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2475                                    AttrSpellingListIndex);
2476   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2477     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2478                                    AttrSpellingListIndex);
2479   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2480     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2481                                 FA->getFormatIdx(), FA->getFirstArg(),
2482                                 AttrSpellingListIndex);
2483   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2484     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2485                                  AttrSpellingListIndex);
2486   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2487     NewAttr = S.mergeCodeSegAttr(D, CSA->getRange(), CSA->getName(),
2488                                  AttrSpellingListIndex);
2489   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2490     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2491                                        AttrSpellingListIndex,
2492                                        IA->getSemanticSpelling());
2493   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2494     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2495                                       &S.Context.Idents.get(AA->getSpelling()),
2496                                       AttrSpellingListIndex);
2497   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2498            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2499             isa<CUDAGlobalAttr>(Attr))) {
2500     // CUDA target attributes are part of function signature for
2501     // overloading purposes and must not be merged.
2502     return false;
2503   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2504     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2505   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2506     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2507   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2508     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2509   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2510     NewAttr = S.mergeCommonAttr(D, *CommonA);
2511   else if (isa<AlignedAttr>(Attr))
2512     // AlignedAttrs are handled separately, because we need to handle all
2513     // such attributes on a declaration at the same time.
2514     NewAttr = nullptr;
2515   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2516            (AMK == Sema::AMK_Override ||
2517             AMK == Sema::AMK_ProtocolImplementation))
2518     NewAttr = nullptr;
2519   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2520     NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2521                               UA->getGuid());
2522   else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
2523     NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
2524   else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
2525     NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
2526   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2527     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2528 
2529   if (NewAttr) {
2530     NewAttr->setInherited(true);
2531     D->addAttr(NewAttr);
2532     if (isa<MSInheritanceAttr>(NewAttr))
2533       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2534     return true;
2535   }
2536 
2537   return false;
2538 }
2539 
2540 static const NamedDecl *getDefinition(const Decl *D) {
2541   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2542     return TD->getDefinition();
2543   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2544     const VarDecl *Def = VD->getDefinition();
2545     if (Def)
2546       return Def;
2547     return VD->getActingDefinition();
2548   }
2549   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2550     return FD->getDefinition();
2551   return nullptr;
2552 }
2553 
2554 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2555   for (const auto *Attribute : D->attrs())
2556     if (Attribute->getKind() == Kind)
2557       return true;
2558   return false;
2559 }
2560 
2561 /// checkNewAttributesAfterDef - If we already have a definition, check that
2562 /// there are no new attributes in this declaration.
2563 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2564   if (!New->hasAttrs())
2565     return;
2566 
2567   const NamedDecl *Def = getDefinition(Old);
2568   if (!Def || Def == New)
2569     return;
2570 
2571   AttrVec &NewAttributes = New->getAttrs();
2572   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2573     const Attr *NewAttribute = NewAttributes[I];
2574 
2575     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2576       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2577         Sema::SkipBodyInfo SkipBody;
2578         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2579 
2580         // If we're skipping this definition, drop the "alias" attribute.
2581         if (SkipBody.ShouldSkip) {
2582           NewAttributes.erase(NewAttributes.begin() + I);
2583           --E;
2584           continue;
2585         }
2586       } else {
2587         VarDecl *VD = cast<VarDecl>(New);
2588         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2589                                 VarDecl::TentativeDefinition
2590                             ? diag::err_alias_after_tentative
2591                             : diag::err_redefinition;
2592         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2593         if (Diag == diag::err_redefinition)
2594           S.notePreviousDefinition(Def, VD->getLocation());
2595         else
2596           S.Diag(Def->getLocation(), diag::note_previous_definition);
2597         VD->setInvalidDecl();
2598       }
2599       ++I;
2600       continue;
2601     }
2602 
2603     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2604       // Tentative definitions are only interesting for the alias check above.
2605       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2606         ++I;
2607         continue;
2608       }
2609     }
2610 
2611     if (hasAttribute(Def, NewAttribute->getKind())) {
2612       ++I;
2613       continue; // regular attr merging will take care of validating this.
2614     }
2615 
2616     if (isa<C11NoReturnAttr>(NewAttribute)) {
2617       // C's _Noreturn is allowed to be added to a function after it is defined.
2618       ++I;
2619       continue;
2620     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2621       if (AA->isAlignas()) {
2622         // C++11 [dcl.align]p6:
2623         //   if any declaration of an entity has an alignment-specifier,
2624         //   every defining declaration of that entity shall specify an
2625         //   equivalent alignment.
2626         // C11 6.7.5/7:
2627         //   If the definition of an object does not have an alignment
2628         //   specifier, any other declaration of that object shall also
2629         //   have no alignment specifier.
2630         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2631           << AA;
2632         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2633           << AA;
2634         NewAttributes.erase(NewAttributes.begin() + I);
2635         --E;
2636         continue;
2637       }
2638     }
2639 
2640     S.Diag(NewAttribute->getLocation(),
2641            diag::warn_attribute_precede_definition);
2642     S.Diag(Def->getLocation(), diag::note_previous_definition);
2643     NewAttributes.erase(NewAttributes.begin() + I);
2644     --E;
2645   }
2646 }
2647 
2648 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2649 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2650                                AvailabilityMergeKind AMK) {
2651   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2652     UsedAttr *NewAttr = OldAttr->clone(Context);
2653     NewAttr->setInherited(true);
2654     New->addAttr(NewAttr);
2655   }
2656 
2657   if (!Old->hasAttrs() && !New->hasAttrs())
2658     return;
2659 
2660   // Attributes declared post-definition are currently ignored.
2661   checkNewAttributesAfterDef(*this, New, Old);
2662 
2663   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2664     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2665       if (OldA->getLabel() != NewA->getLabel()) {
2666         // This redeclaration changes __asm__ label.
2667         Diag(New->getLocation(), diag::err_different_asm_label);
2668         Diag(OldA->getLocation(), diag::note_previous_declaration);
2669       }
2670     } else if (Old->isUsed()) {
2671       // This redeclaration adds an __asm__ label to a declaration that has
2672       // already been ODR-used.
2673       Diag(New->getLocation(), diag::err_late_asm_label_name)
2674         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2675     }
2676   }
2677 
2678   // Re-declaration cannot add abi_tag's.
2679   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2680     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2681       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2682         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2683                       NewTag) == OldAbiTagAttr->tags_end()) {
2684           Diag(NewAbiTagAttr->getLocation(),
2685                diag::err_new_abi_tag_on_redeclaration)
2686               << NewTag;
2687           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2688         }
2689       }
2690     } else {
2691       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2692       Diag(Old->getLocation(), diag::note_previous_declaration);
2693     }
2694   }
2695 
2696   // This redeclaration adds a section attribute.
2697   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2698     if (auto *VD = dyn_cast<VarDecl>(New)) {
2699       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2700         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2701         Diag(Old->getLocation(), diag::note_previous_declaration);
2702       }
2703     }
2704   }
2705 
2706   // Redeclaration adds code-seg attribute.
2707   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2708   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2709       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2710     Diag(New->getLocation(), diag::warn_mismatched_section)
2711          << 0 /*codeseg*/;
2712     Diag(Old->getLocation(), diag::note_previous_declaration);
2713   }
2714 
2715   if (!Old->hasAttrs())
2716     return;
2717 
2718   bool foundAny = New->hasAttrs();
2719 
2720   // Ensure that any moving of objects within the allocated map is done before
2721   // we process them.
2722   if (!foundAny) New->setAttrs(AttrVec());
2723 
2724   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2725     // Ignore deprecated/unavailable/availability attributes if requested.
2726     AvailabilityMergeKind LocalAMK = AMK_None;
2727     if (isa<DeprecatedAttr>(I) ||
2728         isa<UnavailableAttr>(I) ||
2729         isa<AvailabilityAttr>(I)) {
2730       switch (AMK) {
2731       case AMK_None:
2732         continue;
2733 
2734       case AMK_Redeclaration:
2735       case AMK_Override:
2736       case AMK_ProtocolImplementation:
2737         LocalAMK = AMK;
2738         break;
2739       }
2740     }
2741 
2742     // Already handled.
2743     if (isa<UsedAttr>(I))
2744       continue;
2745 
2746     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2747       foundAny = true;
2748   }
2749 
2750   if (mergeAlignedAttrs(*this, New, Old))
2751     foundAny = true;
2752 
2753   if (!foundAny) New->dropAttrs();
2754 }
2755 
2756 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2757 /// to the new one.
2758 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2759                                      const ParmVarDecl *oldDecl,
2760                                      Sema &S) {
2761   // C++11 [dcl.attr.depend]p2:
2762   //   The first declaration of a function shall specify the
2763   //   carries_dependency attribute for its declarator-id if any declaration
2764   //   of the function specifies the carries_dependency attribute.
2765   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2766   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2767     S.Diag(CDA->getLocation(),
2768            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2769     // Find the first declaration of the parameter.
2770     // FIXME: Should we build redeclaration chains for function parameters?
2771     const FunctionDecl *FirstFD =
2772       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2773     const ParmVarDecl *FirstVD =
2774       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2775     S.Diag(FirstVD->getLocation(),
2776            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2777   }
2778 
2779   if (!oldDecl->hasAttrs())
2780     return;
2781 
2782   bool foundAny = newDecl->hasAttrs();
2783 
2784   // Ensure that any moving of objects within the allocated map is
2785   // done before we process them.
2786   if (!foundAny) newDecl->setAttrs(AttrVec());
2787 
2788   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2789     if (!DeclHasAttr(newDecl, I)) {
2790       InheritableAttr *newAttr =
2791         cast<InheritableParamAttr>(I->clone(S.Context));
2792       newAttr->setInherited(true);
2793       newDecl->addAttr(newAttr);
2794       foundAny = true;
2795     }
2796   }
2797 
2798   if (!foundAny) newDecl->dropAttrs();
2799 }
2800 
2801 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2802                                 const ParmVarDecl *OldParam,
2803                                 Sema &S) {
2804   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2805     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2806       if (*Oldnullability != *Newnullability) {
2807         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2808           << DiagNullabilityKind(
2809                *Newnullability,
2810                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2811                 != 0))
2812           << DiagNullabilityKind(
2813                *Oldnullability,
2814                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2815                 != 0));
2816         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2817       }
2818     } else {
2819       QualType NewT = NewParam->getType();
2820       NewT = S.Context.getAttributedType(
2821                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2822                          NewT, NewT);
2823       NewParam->setType(NewT);
2824     }
2825   }
2826 }
2827 
2828 namespace {
2829 
2830 /// Used in MergeFunctionDecl to keep track of function parameters in
2831 /// C.
2832 struct GNUCompatibleParamWarning {
2833   ParmVarDecl *OldParm;
2834   ParmVarDecl *NewParm;
2835   QualType PromotedType;
2836 };
2837 
2838 } // end anonymous namespace
2839 
2840 /// getSpecialMember - get the special member enum for a method.
2841 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2842   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2843     if (Ctor->isDefaultConstructor())
2844       return Sema::CXXDefaultConstructor;
2845 
2846     if (Ctor->isCopyConstructor())
2847       return Sema::CXXCopyConstructor;
2848 
2849     if (Ctor->isMoveConstructor())
2850       return Sema::CXXMoveConstructor;
2851   } else if (isa<CXXDestructorDecl>(MD)) {
2852     return Sema::CXXDestructor;
2853   } else if (MD->isCopyAssignmentOperator()) {
2854     return Sema::CXXCopyAssignment;
2855   } else if (MD->isMoveAssignmentOperator()) {
2856     return Sema::CXXMoveAssignment;
2857   }
2858 
2859   return Sema::CXXInvalid;
2860 }
2861 
2862 // Determine whether the previous declaration was a definition, implicit
2863 // declaration, or a declaration.
2864 template <typename T>
2865 static std::pair<diag::kind, SourceLocation>
2866 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2867   diag::kind PrevDiag;
2868   SourceLocation OldLocation = Old->getLocation();
2869   if (Old->isThisDeclarationADefinition())
2870     PrevDiag = diag::note_previous_definition;
2871   else if (Old->isImplicit()) {
2872     PrevDiag = diag::note_previous_implicit_declaration;
2873     if (OldLocation.isInvalid())
2874       OldLocation = New->getLocation();
2875   } else
2876     PrevDiag = diag::note_previous_declaration;
2877   return std::make_pair(PrevDiag, OldLocation);
2878 }
2879 
2880 /// canRedefineFunction - checks if a function can be redefined. Currently,
2881 /// only extern inline functions can be redefined, and even then only in
2882 /// GNU89 mode.
2883 static bool canRedefineFunction(const FunctionDecl *FD,
2884                                 const LangOptions& LangOpts) {
2885   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2886           !LangOpts.CPlusPlus &&
2887           FD->isInlineSpecified() &&
2888           FD->getStorageClass() == SC_Extern);
2889 }
2890 
2891 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2892   const AttributedType *AT = T->getAs<AttributedType>();
2893   while (AT && !AT->isCallingConv())
2894     AT = AT->getModifiedType()->getAs<AttributedType>();
2895   return AT;
2896 }
2897 
2898 template <typename T>
2899 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2900   const DeclContext *DC = Old->getDeclContext();
2901   if (DC->isRecord())
2902     return false;
2903 
2904   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2905   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2906     return true;
2907   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2908     return true;
2909   return false;
2910 }
2911 
2912 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2913 static bool isExternC(VarTemplateDecl *) { return false; }
2914 
2915 /// Check whether a redeclaration of an entity introduced by a
2916 /// using-declaration is valid, given that we know it's not an overload
2917 /// (nor a hidden tag declaration).
2918 template<typename ExpectedDecl>
2919 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2920                                    ExpectedDecl *New) {
2921   // C++11 [basic.scope.declarative]p4:
2922   //   Given a set of declarations in a single declarative region, each of
2923   //   which specifies the same unqualified name,
2924   //   -- they shall all refer to the same entity, or all refer to functions
2925   //      and function templates; or
2926   //   -- exactly one declaration shall declare a class name or enumeration
2927   //      name that is not a typedef name and the other declarations shall all
2928   //      refer to the same variable or enumerator, or all refer to functions
2929   //      and function templates; in this case the class name or enumeration
2930   //      name is hidden (3.3.10).
2931 
2932   // C++11 [namespace.udecl]p14:
2933   //   If a function declaration in namespace scope or block scope has the
2934   //   same name and the same parameter-type-list as a function introduced
2935   //   by a using-declaration, and the declarations do not declare the same
2936   //   function, the program is ill-formed.
2937 
2938   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2939   if (Old &&
2940       !Old->getDeclContext()->getRedeclContext()->Equals(
2941           New->getDeclContext()->getRedeclContext()) &&
2942       !(isExternC(Old) && isExternC(New)))
2943     Old = nullptr;
2944 
2945   if (!Old) {
2946     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2947     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2948     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2949     return true;
2950   }
2951   return false;
2952 }
2953 
2954 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2955                                             const FunctionDecl *B) {
2956   assert(A->getNumParams() == B->getNumParams());
2957 
2958   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2959     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2960     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2961     if (AttrA == AttrB)
2962       return true;
2963     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
2964            AttrA->isDynamic() == AttrB->isDynamic();
2965   };
2966 
2967   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2968 }
2969 
2970 /// If necessary, adjust the semantic declaration context for a qualified
2971 /// declaration to name the correct inline namespace within the qualifier.
2972 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
2973                                                DeclaratorDecl *OldD) {
2974   // The only case where we need to update the DeclContext is when
2975   // redeclaration lookup for a qualified name finds a declaration
2976   // in an inline namespace within the context named by the qualifier:
2977   //
2978   //   inline namespace N { int f(); }
2979   //   int ::f(); // Sema DC needs adjusting from :: to N::.
2980   //
2981   // For unqualified declarations, the semantic context *can* change
2982   // along the redeclaration chain (for local extern declarations,
2983   // extern "C" declarations, and friend declarations in particular).
2984   if (!NewD->getQualifier())
2985     return;
2986 
2987   // NewD is probably already in the right context.
2988   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
2989   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
2990   if (NamedDC->Equals(SemaDC))
2991     return;
2992 
2993   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
2994           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
2995          "unexpected context for redeclaration");
2996 
2997   auto *LexDC = NewD->getLexicalDeclContext();
2998   auto FixSemaDC = [=](NamedDecl *D) {
2999     if (!D)
3000       return;
3001     D->setDeclContext(SemaDC);
3002     D->setLexicalDeclContext(LexDC);
3003   };
3004 
3005   FixSemaDC(NewD);
3006   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3007     FixSemaDC(FD->getDescribedFunctionTemplate());
3008   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3009     FixSemaDC(VD->getDescribedVarTemplate());
3010 }
3011 
3012 /// MergeFunctionDecl - We just parsed a function 'New' from
3013 /// declarator D which has the same name and scope as a previous
3014 /// declaration 'Old'.  Figure out how to resolve this situation,
3015 /// merging decls or emitting diagnostics as appropriate.
3016 ///
3017 /// In C++, New and Old must be declarations that are not
3018 /// overloaded. Use IsOverload to determine whether New and Old are
3019 /// overloaded, and to select the Old declaration that New should be
3020 /// merged with.
3021 ///
3022 /// Returns true if there was an error, false otherwise.
3023 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3024                              Scope *S, bool MergeTypeWithOld) {
3025   // Verify the old decl was also a function.
3026   FunctionDecl *Old = OldD->getAsFunction();
3027   if (!Old) {
3028     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3029       if (New->getFriendObjectKind()) {
3030         Diag(New->getLocation(), diag::err_using_decl_friend);
3031         Diag(Shadow->getTargetDecl()->getLocation(),
3032              diag::note_using_decl_target);
3033         Diag(Shadow->getUsingDecl()->getLocation(),
3034              diag::note_using_decl) << 0;
3035         return true;
3036       }
3037 
3038       // Check whether the two declarations might declare the same function.
3039       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3040         return true;
3041       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3042     } else {
3043       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3044         << New->getDeclName();
3045       notePreviousDefinition(OldD, New->getLocation());
3046       return true;
3047     }
3048   }
3049 
3050   // If the old declaration is invalid, just give up here.
3051   if (Old->isInvalidDecl())
3052     return true;
3053 
3054   // Disallow redeclaration of some builtins.
3055   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3056     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3057     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3058         << Old << Old->getType();
3059     return true;
3060   }
3061 
3062   diag::kind PrevDiag;
3063   SourceLocation OldLocation;
3064   std::tie(PrevDiag, OldLocation) =
3065       getNoteDiagForInvalidRedeclaration(Old, New);
3066 
3067   // Don't complain about this if we're in GNU89 mode and the old function
3068   // is an extern inline function.
3069   // Don't complain about specializations. They are not supposed to have
3070   // storage classes.
3071   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3072       New->getStorageClass() == SC_Static &&
3073       Old->hasExternalFormalLinkage() &&
3074       !New->getTemplateSpecializationInfo() &&
3075       !canRedefineFunction(Old, getLangOpts())) {
3076     if (getLangOpts().MicrosoftExt) {
3077       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3078       Diag(OldLocation, PrevDiag);
3079     } else {
3080       Diag(New->getLocation(), diag::err_static_non_static) << New;
3081       Diag(OldLocation, PrevDiag);
3082       return true;
3083     }
3084   }
3085 
3086   if (New->hasAttr<InternalLinkageAttr>() &&
3087       !Old->hasAttr<InternalLinkageAttr>()) {
3088     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3089         << New->getDeclName();
3090     notePreviousDefinition(Old, New->getLocation());
3091     New->dropAttr<InternalLinkageAttr>();
3092   }
3093 
3094   if (CheckRedeclarationModuleOwnership(New, Old))
3095     return true;
3096 
3097   if (!getLangOpts().CPlusPlus) {
3098     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3099     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3100       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3101         << New << OldOvl;
3102 
3103       // Try our best to find a decl that actually has the overloadable
3104       // attribute for the note. In most cases (e.g. programs with only one
3105       // broken declaration/definition), this won't matter.
3106       //
3107       // FIXME: We could do this if we juggled some extra state in
3108       // OverloadableAttr, rather than just removing it.
3109       const Decl *DiagOld = Old;
3110       if (OldOvl) {
3111         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3112           const auto *A = D->getAttr<OverloadableAttr>();
3113           return A && !A->isImplicit();
3114         });
3115         // If we've implicitly added *all* of the overloadable attrs to this
3116         // chain, emitting a "previous redecl" note is pointless.
3117         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3118       }
3119 
3120       if (DiagOld)
3121         Diag(DiagOld->getLocation(),
3122              diag::note_attribute_overloadable_prev_overload)
3123           << OldOvl;
3124 
3125       if (OldOvl)
3126         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3127       else
3128         New->dropAttr<OverloadableAttr>();
3129     }
3130   }
3131 
3132   // If a function is first declared with a calling convention, but is later
3133   // declared or defined without one, all following decls assume the calling
3134   // convention of the first.
3135   //
3136   // It's OK if a function is first declared without a calling convention,
3137   // but is later declared or defined with the default calling convention.
3138   //
3139   // To test if either decl has an explicit calling convention, we look for
3140   // AttributedType sugar nodes on the type as written.  If they are missing or
3141   // were canonicalized away, we assume the calling convention was implicit.
3142   //
3143   // Note also that we DO NOT return at this point, because we still have
3144   // other tests to run.
3145   QualType OldQType = Context.getCanonicalType(Old->getType());
3146   QualType NewQType = Context.getCanonicalType(New->getType());
3147   const FunctionType *OldType = cast<FunctionType>(OldQType);
3148   const FunctionType *NewType = cast<FunctionType>(NewQType);
3149   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3150   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3151   bool RequiresAdjustment = false;
3152 
3153   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3154     FunctionDecl *First = Old->getFirstDecl();
3155     const FunctionType *FT =
3156         First->getType().getCanonicalType()->castAs<FunctionType>();
3157     FunctionType::ExtInfo FI = FT->getExtInfo();
3158     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3159     if (!NewCCExplicit) {
3160       // Inherit the CC from the previous declaration if it was specified
3161       // there but not here.
3162       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3163       RequiresAdjustment = true;
3164     } else if (New->getBuiltinID()) {
3165       // Calling Conventions on a Builtin aren't really useful and setting a
3166       // default calling convention and cdecl'ing some builtin redeclarations is
3167       // common, so warn and ignore the calling convention on the redeclaration.
3168       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3169           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3170           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3171       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3172       RequiresAdjustment = true;
3173     } else {
3174       // Calling conventions aren't compatible, so complain.
3175       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3176       Diag(New->getLocation(), diag::err_cconv_change)
3177         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3178         << !FirstCCExplicit
3179         << (!FirstCCExplicit ? "" :
3180             FunctionType::getNameForCallConv(FI.getCC()));
3181 
3182       // Put the note on the first decl, since it is the one that matters.
3183       Diag(First->getLocation(), diag::note_previous_declaration);
3184       return true;
3185     }
3186   }
3187 
3188   // FIXME: diagnose the other way around?
3189   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3190     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3191     RequiresAdjustment = true;
3192   }
3193 
3194   // Merge regparm attribute.
3195   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3196       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3197     if (NewTypeInfo.getHasRegParm()) {
3198       Diag(New->getLocation(), diag::err_regparm_mismatch)
3199         << NewType->getRegParmType()
3200         << OldType->getRegParmType();
3201       Diag(OldLocation, diag::note_previous_declaration);
3202       return true;
3203     }
3204 
3205     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3206     RequiresAdjustment = true;
3207   }
3208 
3209   // Merge ns_returns_retained attribute.
3210   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3211     if (NewTypeInfo.getProducesResult()) {
3212       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3213           << "'ns_returns_retained'";
3214       Diag(OldLocation, diag::note_previous_declaration);
3215       return true;
3216     }
3217 
3218     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3219     RequiresAdjustment = true;
3220   }
3221 
3222   if (OldTypeInfo.getNoCallerSavedRegs() !=
3223       NewTypeInfo.getNoCallerSavedRegs()) {
3224     if (NewTypeInfo.getNoCallerSavedRegs()) {
3225       AnyX86NoCallerSavedRegistersAttr *Attr =
3226         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3227       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3228       Diag(OldLocation, diag::note_previous_declaration);
3229       return true;
3230     }
3231 
3232     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3233     RequiresAdjustment = true;
3234   }
3235 
3236   if (RequiresAdjustment) {
3237     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3238     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3239     New->setType(QualType(AdjustedType, 0));
3240     NewQType = Context.getCanonicalType(New->getType());
3241   }
3242 
3243   // If this redeclaration makes the function inline, we may need to add it to
3244   // UndefinedButUsed.
3245   if (!Old->isInlined() && New->isInlined() &&
3246       !New->hasAttr<GNUInlineAttr>() &&
3247       !getLangOpts().GNUInline &&
3248       Old->isUsed(false) &&
3249       !Old->isDefined() && !New->isThisDeclarationADefinition())
3250     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3251                                            SourceLocation()));
3252 
3253   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3254   // about it.
3255   if (New->hasAttr<GNUInlineAttr>() &&
3256       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3257     UndefinedButUsed.erase(Old->getCanonicalDecl());
3258   }
3259 
3260   // If pass_object_size params don't match up perfectly, this isn't a valid
3261   // redeclaration.
3262   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3263       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3264     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3265         << New->getDeclName();
3266     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3267     return true;
3268   }
3269 
3270   if (getLangOpts().CPlusPlus) {
3271     // C++1z [over.load]p2
3272     //   Certain function declarations cannot be overloaded:
3273     //     -- Function declarations that differ only in the return type,
3274     //        the exception specification, or both cannot be overloaded.
3275 
3276     // Check the exception specifications match. This may recompute the type of
3277     // both Old and New if it resolved exception specifications, so grab the
3278     // types again after this. Because this updates the type, we do this before
3279     // any of the other checks below, which may update the "de facto" NewQType
3280     // but do not necessarily update the type of New.
3281     if (CheckEquivalentExceptionSpec(Old, New))
3282       return true;
3283     OldQType = Context.getCanonicalType(Old->getType());
3284     NewQType = Context.getCanonicalType(New->getType());
3285 
3286     // Go back to the type source info to compare the declared return types,
3287     // per C++1y [dcl.type.auto]p13:
3288     //   Redeclarations or specializations of a function or function template
3289     //   with a declared return type that uses a placeholder type shall also
3290     //   use that placeholder, not a deduced type.
3291     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3292     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3293     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3294         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3295                                        OldDeclaredReturnType)) {
3296       QualType ResQT;
3297       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3298           OldDeclaredReturnType->isObjCObjectPointerType())
3299         // FIXME: This does the wrong thing for a deduced return type.
3300         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3301       if (ResQT.isNull()) {
3302         if (New->isCXXClassMember() && New->isOutOfLine())
3303           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3304               << New << New->getReturnTypeSourceRange();
3305         else
3306           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3307               << New->getReturnTypeSourceRange();
3308         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3309                                     << Old->getReturnTypeSourceRange();
3310         return true;
3311       }
3312       else
3313         NewQType = ResQT;
3314     }
3315 
3316     QualType OldReturnType = OldType->getReturnType();
3317     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3318     if (OldReturnType != NewReturnType) {
3319       // If this function has a deduced return type and has already been
3320       // defined, copy the deduced value from the old declaration.
3321       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3322       if (OldAT && OldAT->isDeduced()) {
3323         New->setType(
3324             SubstAutoType(New->getType(),
3325                           OldAT->isDependentType() ? Context.DependentTy
3326                                                    : OldAT->getDeducedType()));
3327         NewQType = Context.getCanonicalType(
3328             SubstAutoType(NewQType,
3329                           OldAT->isDependentType() ? Context.DependentTy
3330                                                    : OldAT->getDeducedType()));
3331       }
3332     }
3333 
3334     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3335     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3336     if (OldMethod && NewMethod) {
3337       // Preserve triviality.
3338       NewMethod->setTrivial(OldMethod->isTrivial());
3339 
3340       // MSVC allows explicit template specialization at class scope:
3341       // 2 CXXMethodDecls referring to the same function will be injected.
3342       // We don't want a redeclaration error.
3343       bool IsClassScopeExplicitSpecialization =
3344                               OldMethod->isFunctionTemplateSpecialization() &&
3345                               NewMethod->isFunctionTemplateSpecialization();
3346       bool isFriend = NewMethod->getFriendObjectKind();
3347 
3348       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3349           !IsClassScopeExplicitSpecialization) {
3350         //    -- Member function declarations with the same name and the
3351         //       same parameter types cannot be overloaded if any of them
3352         //       is a static member function declaration.
3353         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3354           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3355           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3356           return true;
3357         }
3358 
3359         // C++ [class.mem]p1:
3360         //   [...] A member shall not be declared twice in the
3361         //   member-specification, except that a nested class or member
3362         //   class template can be declared and then later defined.
3363         if (!inTemplateInstantiation()) {
3364           unsigned NewDiag;
3365           if (isa<CXXConstructorDecl>(OldMethod))
3366             NewDiag = diag::err_constructor_redeclared;
3367           else if (isa<CXXDestructorDecl>(NewMethod))
3368             NewDiag = diag::err_destructor_redeclared;
3369           else if (isa<CXXConversionDecl>(NewMethod))
3370             NewDiag = diag::err_conv_function_redeclared;
3371           else
3372             NewDiag = diag::err_member_redeclared;
3373 
3374           Diag(New->getLocation(), NewDiag);
3375         } else {
3376           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3377             << New << New->getType();
3378         }
3379         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3380         return true;
3381 
3382       // Complain if this is an explicit declaration of a special
3383       // member that was initially declared implicitly.
3384       //
3385       // As an exception, it's okay to befriend such methods in order
3386       // to permit the implicit constructor/destructor/operator calls.
3387       } else if (OldMethod->isImplicit()) {
3388         if (isFriend) {
3389           NewMethod->setImplicit();
3390         } else {
3391           Diag(NewMethod->getLocation(),
3392                diag::err_definition_of_implicitly_declared_member)
3393             << New << getSpecialMember(OldMethod);
3394           return true;
3395         }
3396       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3397         Diag(NewMethod->getLocation(),
3398              diag::err_definition_of_explicitly_defaulted_member)
3399           << getSpecialMember(OldMethod);
3400         return true;
3401       }
3402     }
3403 
3404     // C++11 [dcl.attr.noreturn]p1:
3405     //   The first declaration of a function shall specify the noreturn
3406     //   attribute if any declaration of that function specifies the noreturn
3407     //   attribute.
3408     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3409     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3410       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3411       Diag(Old->getFirstDecl()->getLocation(),
3412            diag::note_noreturn_missing_first_decl);
3413     }
3414 
3415     // C++11 [dcl.attr.depend]p2:
3416     //   The first declaration of a function shall specify the
3417     //   carries_dependency attribute for its declarator-id if any declaration
3418     //   of the function specifies the carries_dependency attribute.
3419     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3420     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3421       Diag(CDA->getLocation(),
3422            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3423       Diag(Old->getFirstDecl()->getLocation(),
3424            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3425     }
3426 
3427     // (C++98 8.3.5p3):
3428     //   All declarations for a function shall agree exactly in both the
3429     //   return type and the parameter-type-list.
3430     // We also want to respect all the extended bits except noreturn.
3431 
3432     // noreturn should now match unless the old type info didn't have it.
3433     QualType OldQTypeForComparison = OldQType;
3434     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3435       auto *OldType = OldQType->castAs<FunctionProtoType>();
3436       const FunctionType *OldTypeForComparison
3437         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3438       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3439       assert(OldQTypeForComparison.isCanonical());
3440     }
3441 
3442     if (haveIncompatibleLanguageLinkages(Old, New)) {
3443       // As a special case, retain the language linkage from previous
3444       // declarations of a friend function as an extension.
3445       //
3446       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3447       // and is useful because there's otherwise no way to specify language
3448       // linkage within class scope.
3449       //
3450       // Check cautiously as the friend object kind isn't yet complete.
3451       if (New->getFriendObjectKind() != Decl::FOK_None) {
3452         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3453         Diag(OldLocation, PrevDiag);
3454       } else {
3455         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3456         Diag(OldLocation, PrevDiag);
3457         return true;
3458       }
3459     }
3460 
3461     if (OldQTypeForComparison == NewQType)
3462       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3463 
3464     // If the types are imprecise (due to dependent constructs in friends or
3465     // local extern declarations), it's OK if they differ. We'll check again
3466     // during instantiation.
3467     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3468       return false;
3469 
3470     // Fall through for conflicting redeclarations and redefinitions.
3471   }
3472 
3473   // C: Function types need to be compatible, not identical. This handles
3474   // duplicate function decls like "void f(int); void f(enum X);" properly.
3475   if (!getLangOpts().CPlusPlus &&
3476       Context.typesAreCompatible(OldQType, NewQType)) {
3477     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3478     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3479     const FunctionProtoType *OldProto = nullptr;
3480     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3481         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3482       // The old declaration provided a function prototype, but the
3483       // new declaration does not. Merge in the prototype.
3484       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3485       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3486       NewQType =
3487           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3488                                   OldProto->getExtProtoInfo());
3489       New->setType(NewQType);
3490       New->setHasInheritedPrototype();
3491 
3492       // Synthesize parameters with the same types.
3493       SmallVector<ParmVarDecl*, 16> Params;
3494       for (const auto &ParamType : OldProto->param_types()) {
3495         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3496                                                  SourceLocation(), nullptr,
3497                                                  ParamType, /*TInfo=*/nullptr,
3498                                                  SC_None, nullptr);
3499         Param->setScopeInfo(0, Params.size());
3500         Param->setImplicit();
3501         Params.push_back(Param);
3502       }
3503 
3504       New->setParams(Params);
3505     }
3506 
3507     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3508   }
3509 
3510   // GNU C permits a K&R definition to follow a prototype declaration
3511   // if the declared types of the parameters in the K&R definition
3512   // match the types in the prototype declaration, even when the
3513   // promoted types of the parameters from the K&R definition differ
3514   // from the types in the prototype. GCC then keeps the types from
3515   // the prototype.
3516   //
3517   // If a variadic prototype is followed by a non-variadic K&R definition,
3518   // the K&R definition becomes variadic.  This is sort of an edge case, but
3519   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3520   // C99 6.9.1p8.
3521   if (!getLangOpts().CPlusPlus &&
3522       Old->hasPrototype() && !New->hasPrototype() &&
3523       New->getType()->getAs<FunctionProtoType>() &&
3524       Old->getNumParams() == New->getNumParams()) {
3525     SmallVector<QualType, 16> ArgTypes;
3526     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3527     const FunctionProtoType *OldProto
3528       = Old->getType()->getAs<FunctionProtoType>();
3529     const FunctionProtoType *NewProto
3530       = New->getType()->getAs<FunctionProtoType>();
3531 
3532     // Determine whether this is the GNU C extension.
3533     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3534                                                NewProto->getReturnType());
3535     bool LooseCompatible = !MergedReturn.isNull();
3536     for (unsigned Idx = 0, End = Old->getNumParams();
3537          LooseCompatible && Idx != End; ++Idx) {
3538       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3539       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3540       if (Context.typesAreCompatible(OldParm->getType(),
3541                                      NewProto->getParamType(Idx))) {
3542         ArgTypes.push_back(NewParm->getType());
3543       } else if (Context.typesAreCompatible(OldParm->getType(),
3544                                             NewParm->getType(),
3545                                             /*CompareUnqualified=*/true)) {
3546         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3547                                            NewProto->getParamType(Idx) };
3548         Warnings.push_back(Warn);
3549         ArgTypes.push_back(NewParm->getType());
3550       } else
3551         LooseCompatible = false;
3552     }
3553 
3554     if (LooseCompatible) {
3555       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3556         Diag(Warnings[Warn].NewParm->getLocation(),
3557              diag::ext_param_promoted_not_compatible_with_prototype)
3558           << Warnings[Warn].PromotedType
3559           << Warnings[Warn].OldParm->getType();
3560         if (Warnings[Warn].OldParm->getLocation().isValid())
3561           Diag(Warnings[Warn].OldParm->getLocation(),
3562                diag::note_previous_declaration);
3563       }
3564 
3565       if (MergeTypeWithOld)
3566         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3567                                              OldProto->getExtProtoInfo()));
3568       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3569     }
3570 
3571     // Fall through to diagnose conflicting types.
3572   }
3573 
3574   // A function that has already been declared has been redeclared or
3575   // defined with a different type; show an appropriate diagnostic.
3576 
3577   // If the previous declaration was an implicitly-generated builtin
3578   // declaration, then at the very least we should use a specialized note.
3579   unsigned BuiltinID;
3580   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3581     // If it's actually a library-defined builtin function like 'malloc'
3582     // or 'printf', just warn about the incompatible redeclaration.
3583     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3584       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3585       Diag(OldLocation, diag::note_previous_builtin_declaration)
3586         << Old << Old->getType();
3587 
3588       // If this is a global redeclaration, just forget hereafter
3589       // about the "builtin-ness" of the function.
3590       //
3591       // Doing this for local extern declarations is problematic.  If
3592       // the builtin declaration remains visible, a second invalid
3593       // local declaration will produce a hard error; if it doesn't
3594       // remain visible, a single bogus local redeclaration (which is
3595       // actually only a warning) could break all the downstream code.
3596       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3597         New->getIdentifier()->revertBuiltin();
3598 
3599       return false;
3600     }
3601 
3602     PrevDiag = diag::note_previous_builtin_declaration;
3603   }
3604 
3605   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3606   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3607   return true;
3608 }
3609 
3610 /// Completes the merge of two function declarations that are
3611 /// known to be compatible.
3612 ///
3613 /// This routine handles the merging of attributes and other
3614 /// properties of function declarations from the old declaration to
3615 /// the new declaration, once we know that New is in fact a
3616 /// redeclaration of Old.
3617 ///
3618 /// \returns false
3619 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3620                                         Scope *S, bool MergeTypeWithOld) {
3621   // Merge the attributes
3622   mergeDeclAttributes(New, Old);
3623 
3624   // Merge "pure" flag.
3625   if (Old->isPure())
3626     New->setPure();
3627 
3628   // Merge "used" flag.
3629   if (Old->getMostRecentDecl()->isUsed(false))
3630     New->setIsUsed();
3631 
3632   // Merge attributes from the parameters.  These can mismatch with K&R
3633   // declarations.
3634   if (New->getNumParams() == Old->getNumParams())
3635       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3636         ParmVarDecl *NewParam = New->getParamDecl(i);
3637         ParmVarDecl *OldParam = Old->getParamDecl(i);
3638         mergeParamDeclAttributes(NewParam, OldParam, *this);
3639         mergeParamDeclTypes(NewParam, OldParam, *this);
3640       }
3641 
3642   if (getLangOpts().CPlusPlus)
3643     return MergeCXXFunctionDecl(New, Old, S);
3644 
3645   // Merge the function types so the we get the composite types for the return
3646   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3647   // was visible.
3648   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3649   if (!Merged.isNull() && MergeTypeWithOld)
3650     New->setType(Merged);
3651 
3652   return false;
3653 }
3654 
3655 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3656                                 ObjCMethodDecl *oldMethod) {
3657   // Merge the attributes, including deprecated/unavailable
3658   AvailabilityMergeKind MergeKind =
3659     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3660       ? AMK_ProtocolImplementation
3661       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3662                                                        : AMK_Override;
3663 
3664   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3665 
3666   // Merge attributes from the parameters.
3667   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3668                                        oe = oldMethod->param_end();
3669   for (ObjCMethodDecl::param_iterator
3670          ni = newMethod->param_begin(), ne = newMethod->param_end();
3671        ni != ne && oi != oe; ++ni, ++oi)
3672     mergeParamDeclAttributes(*ni, *oi, *this);
3673 
3674   CheckObjCMethodOverride(newMethod, oldMethod);
3675 }
3676 
3677 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3678   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3679 
3680   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3681          ? diag::err_redefinition_different_type
3682          : diag::err_redeclaration_different_type)
3683     << New->getDeclName() << New->getType() << Old->getType();
3684 
3685   diag::kind PrevDiag;
3686   SourceLocation OldLocation;
3687   std::tie(PrevDiag, OldLocation)
3688     = getNoteDiagForInvalidRedeclaration(Old, New);
3689   S.Diag(OldLocation, PrevDiag);
3690   New->setInvalidDecl();
3691 }
3692 
3693 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3694 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3695 /// emitting diagnostics as appropriate.
3696 ///
3697 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3698 /// to here in AddInitializerToDecl. We can't check them before the initializer
3699 /// is attached.
3700 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3701                              bool MergeTypeWithOld) {
3702   if (New->isInvalidDecl() || Old->isInvalidDecl())
3703     return;
3704 
3705   QualType MergedT;
3706   if (getLangOpts().CPlusPlus) {
3707     if (New->getType()->isUndeducedType()) {
3708       // We don't know what the new type is until the initializer is attached.
3709       return;
3710     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3711       // These could still be something that needs exception specs checked.
3712       return MergeVarDeclExceptionSpecs(New, Old);
3713     }
3714     // C++ [basic.link]p10:
3715     //   [...] the types specified by all declarations referring to a given
3716     //   object or function shall be identical, except that declarations for an
3717     //   array object can specify array types that differ by the presence or
3718     //   absence of a major array bound (8.3.4).
3719     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3720       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3721       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3722 
3723       // We are merging a variable declaration New into Old. If it has an array
3724       // bound, and that bound differs from Old's bound, we should diagnose the
3725       // mismatch.
3726       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3727         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3728              PrevVD = PrevVD->getPreviousDecl()) {
3729           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3730           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3731             continue;
3732 
3733           if (!Context.hasSameType(NewArray, PrevVDTy))
3734             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3735         }
3736       }
3737 
3738       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3739         if (Context.hasSameType(OldArray->getElementType(),
3740                                 NewArray->getElementType()))
3741           MergedT = New->getType();
3742       }
3743       // FIXME: Check visibility. New is hidden but has a complete type. If New
3744       // has no array bound, it should not inherit one from Old, if Old is not
3745       // visible.
3746       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3747         if (Context.hasSameType(OldArray->getElementType(),
3748                                 NewArray->getElementType()))
3749           MergedT = Old->getType();
3750       }
3751     }
3752     else if (New->getType()->isObjCObjectPointerType() &&
3753                Old->getType()->isObjCObjectPointerType()) {
3754       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3755                                               Old->getType());
3756     }
3757   } else {
3758     // C 6.2.7p2:
3759     //   All declarations that refer to the same object or function shall have
3760     //   compatible type.
3761     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3762   }
3763   if (MergedT.isNull()) {
3764     // It's OK if we couldn't merge types if either type is dependent, for a
3765     // block-scope variable. In other cases (static data members of class
3766     // templates, variable templates, ...), we require the types to be
3767     // equivalent.
3768     // FIXME: The C++ standard doesn't say anything about this.
3769     if ((New->getType()->isDependentType() ||
3770          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3771       // If the old type was dependent, we can't merge with it, so the new type
3772       // becomes dependent for now. We'll reproduce the original type when we
3773       // instantiate the TypeSourceInfo for the variable.
3774       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3775         New->setType(Context.DependentTy);
3776       return;
3777     }
3778     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3779   }
3780 
3781   // Don't actually update the type on the new declaration if the old
3782   // declaration was an extern declaration in a different scope.
3783   if (MergeTypeWithOld)
3784     New->setType(MergedT);
3785 }
3786 
3787 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3788                                   LookupResult &Previous) {
3789   // C11 6.2.7p4:
3790   //   For an identifier with internal or external linkage declared
3791   //   in a scope in which a prior declaration of that identifier is
3792   //   visible, if the prior declaration specifies internal or
3793   //   external linkage, the type of the identifier at the later
3794   //   declaration becomes the composite type.
3795   //
3796   // If the variable isn't visible, we do not merge with its type.
3797   if (Previous.isShadowed())
3798     return false;
3799 
3800   if (S.getLangOpts().CPlusPlus) {
3801     // C++11 [dcl.array]p3:
3802     //   If there is a preceding declaration of the entity in the same
3803     //   scope in which the bound was specified, an omitted array bound
3804     //   is taken to be the same as in that earlier declaration.
3805     return NewVD->isPreviousDeclInSameBlockScope() ||
3806            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3807             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3808   } else {
3809     // If the old declaration was function-local, don't merge with its
3810     // type unless we're in the same function.
3811     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3812            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3813   }
3814 }
3815 
3816 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3817 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3818 /// situation, merging decls or emitting diagnostics as appropriate.
3819 ///
3820 /// Tentative definition rules (C99 6.9.2p2) are checked by
3821 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3822 /// definitions here, since the initializer hasn't been attached.
3823 ///
3824 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3825   // If the new decl is already invalid, don't do any other checking.
3826   if (New->isInvalidDecl())
3827     return;
3828 
3829   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3830     return;
3831 
3832   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3833 
3834   // Verify the old decl was also a variable or variable template.
3835   VarDecl *Old = nullptr;
3836   VarTemplateDecl *OldTemplate = nullptr;
3837   if (Previous.isSingleResult()) {
3838     if (NewTemplate) {
3839       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3840       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3841 
3842       if (auto *Shadow =
3843               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3844         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3845           return New->setInvalidDecl();
3846     } else {
3847       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3848 
3849       if (auto *Shadow =
3850               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3851         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3852           return New->setInvalidDecl();
3853     }
3854   }
3855   if (!Old) {
3856     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3857         << New->getDeclName();
3858     notePreviousDefinition(Previous.getRepresentativeDecl(),
3859                            New->getLocation());
3860     return New->setInvalidDecl();
3861   }
3862 
3863   // Ensure the template parameters are compatible.
3864   if (NewTemplate &&
3865       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3866                                       OldTemplate->getTemplateParameters(),
3867                                       /*Complain=*/true, TPL_TemplateMatch))
3868     return New->setInvalidDecl();
3869 
3870   // C++ [class.mem]p1:
3871   //   A member shall not be declared twice in the member-specification [...]
3872   //
3873   // Here, we need only consider static data members.
3874   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3875     Diag(New->getLocation(), diag::err_duplicate_member)
3876       << New->getIdentifier();
3877     Diag(Old->getLocation(), diag::note_previous_declaration);
3878     New->setInvalidDecl();
3879   }
3880 
3881   mergeDeclAttributes(New, Old);
3882   // Warn if an already-declared variable is made a weak_import in a subsequent
3883   // declaration
3884   if (New->hasAttr<WeakImportAttr>() &&
3885       Old->getStorageClass() == SC_None &&
3886       !Old->hasAttr<WeakImportAttr>()) {
3887     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3888     notePreviousDefinition(Old, New->getLocation());
3889     // Remove weak_import attribute on new declaration.
3890     New->dropAttr<WeakImportAttr>();
3891   }
3892 
3893   if (New->hasAttr<InternalLinkageAttr>() &&
3894       !Old->hasAttr<InternalLinkageAttr>()) {
3895     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3896         << New->getDeclName();
3897     notePreviousDefinition(Old, New->getLocation());
3898     New->dropAttr<InternalLinkageAttr>();
3899   }
3900 
3901   // Merge the types.
3902   VarDecl *MostRecent = Old->getMostRecentDecl();
3903   if (MostRecent != Old) {
3904     MergeVarDeclTypes(New, MostRecent,
3905                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3906     if (New->isInvalidDecl())
3907       return;
3908   }
3909 
3910   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3911   if (New->isInvalidDecl())
3912     return;
3913 
3914   diag::kind PrevDiag;
3915   SourceLocation OldLocation;
3916   std::tie(PrevDiag, OldLocation) =
3917       getNoteDiagForInvalidRedeclaration(Old, New);
3918 
3919   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3920   if (New->getStorageClass() == SC_Static &&
3921       !New->isStaticDataMember() &&
3922       Old->hasExternalFormalLinkage()) {
3923     if (getLangOpts().MicrosoftExt) {
3924       Diag(New->getLocation(), diag::ext_static_non_static)
3925           << New->getDeclName();
3926       Diag(OldLocation, PrevDiag);
3927     } else {
3928       Diag(New->getLocation(), diag::err_static_non_static)
3929           << New->getDeclName();
3930       Diag(OldLocation, PrevDiag);
3931       return New->setInvalidDecl();
3932     }
3933   }
3934   // C99 6.2.2p4:
3935   //   For an identifier declared with the storage-class specifier
3936   //   extern in a scope in which a prior declaration of that
3937   //   identifier is visible,23) if the prior declaration specifies
3938   //   internal or external linkage, the linkage of the identifier at
3939   //   the later declaration is the same as the linkage specified at
3940   //   the prior declaration. If no prior declaration is visible, or
3941   //   if the prior declaration specifies no linkage, then the
3942   //   identifier has external linkage.
3943   if (New->hasExternalStorage() && Old->hasLinkage())
3944     /* Okay */;
3945   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3946            !New->isStaticDataMember() &&
3947            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3948     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3949     Diag(OldLocation, PrevDiag);
3950     return New->setInvalidDecl();
3951   }
3952 
3953   // Check if extern is followed by non-extern and vice-versa.
3954   if (New->hasExternalStorage() &&
3955       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3956     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3957     Diag(OldLocation, PrevDiag);
3958     return New->setInvalidDecl();
3959   }
3960   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3961       !New->hasExternalStorage()) {
3962     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3963     Diag(OldLocation, PrevDiag);
3964     return New->setInvalidDecl();
3965   }
3966 
3967   if (CheckRedeclarationModuleOwnership(New, Old))
3968     return;
3969 
3970   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3971 
3972   // FIXME: The test for external storage here seems wrong? We still
3973   // need to check for mismatches.
3974   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3975       // Don't complain about out-of-line definitions of static members.
3976       !(Old->getLexicalDeclContext()->isRecord() &&
3977         !New->getLexicalDeclContext()->isRecord())) {
3978     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3979     Diag(OldLocation, PrevDiag);
3980     return New->setInvalidDecl();
3981   }
3982 
3983   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3984     if (VarDecl *Def = Old->getDefinition()) {
3985       // C++1z [dcl.fcn.spec]p4:
3986       //   If the definition of a variable appears in a translation unit before
3987       //   its first declaration as inline, the program is ill-formed.
3988       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3989       Diag(Def->getLocation(), diag::note_previous_definition);
3990     }
3991   }
3992 
3993   // If this redeclaration makes the variable inline, we may need to add it to
3994   // UndefinedButUsed.
3995   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3996       !Old->getDefinition() && !New->isThisDeclarationADefinition())
3997     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3998                                            SourceLocation()));
3999 
4000   if (New->getTLSKind() != Old->getTLSKind()) {
4001     if (!Old->getTLSKind()) {
4002       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4003       Diag(OldLocation, PrevDiag);
4004     } else if (!New->getTLSKind()) {
4005       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4006       Diag(OldLocation, PrevDiag);
4007     } else {
4008       // Do not allow redeclaration to change the variable between requiring
4009       // static and dynamic initialization.
4010       // FIXME: GCC allows this, but uses the TLS keyword on the first
4011       // declaration to determine the kind. Do we need to be compatible here?
4012       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4013         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4014       Diag(OldLocation, PrevDiag);
4015     }
4016   }
4017 
4018   // C++ doesn't have tentative definitions, so go right ahead and check here.
4019   if (getLangOpts().CPlusPlus &&
4020       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4021     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4022         Old->getCanonicalDecl()->isConstexpr()) {
4023       // This definition won't be a definition any more once it's been merged.
4024       Diag(New->getLocation(),
4025            diag::warn_deprecated_redundant_constexpr_static_def);
4026     } else if (VarDecl *Def = Old->getDefinition()) {
4027       if (checkVarDeclRedefinition(Def, New))
4028         return;
4029     }
4030   }
4031 
4032   if (haveIncompatibleLanguageLinkages(Old, New)) {
4033     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4034     Diag(OldLocation, PrevDiag);
4035     New->setInvalidDecl();
4036     return;
4037   }
4038 
4039   // Merge "used" flag.
4040   if (Old->getMostRecentDecl()->isUsed(false))
4041     New->setIsUsed();
4042 
4043   // Keep a chain of previous declarations.
4044   New->setPreviousDecl(Old);
4045   if (NewTemplate)
4046     NewTemplate->setPreviousDecl(OldTemplate);
4047   adjustDeclContextForDeclaratorDecl(New, Old);
4048 
4049   // Inherit access appropriately.
4050   New->setAccess(Old->getAccess());
4051   if (NewTemplate)
4052     NewTemplate->setAccess(New->getAccess());
4053 
4054   if (Old->isInline())
4055     New->setImplicitlyInline();
4056 }
4057 
4058 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4059   SourceManager &SrcMgr = getSourceManager();
4060   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4061   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4062   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4063   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4064   auto &HSI = PP.getHeaderSearchInfo();
4065   StringRef HdrFilename =
4066       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4067 
4068   auto noteFromModuleOrInclude = [&](Module *Mod,
4069                                      SourceLocation IncLoc) -> bool {
4070     // Redefinition errors with modules are common with non modular mapped
4071     // headers, example: a non-modular header H in module A that also gets
4072     // included directly in a TU. Pointing twice to the same header/definition
4073     // is confusing, try to get better diagnostics when modules is on.
4074     if (IncLoc.isValid()) {
4075       if (Mod) {
4076         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4077             << HdrFilename.str() << Mod->getFullModuleName();
4078         if (!Mod->DefinitionLoc.isInvalid())
4079           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4080               << Mod->getFullModuleName();
4081       } else {
4082         Diag(IncLoc, diag::note_redefinition_include_same_file)
4083             << HdrFilename.str();
4084       }
4085       return true;
4086     }
4087 
4088     return false;
4089   };
4090 
4091   // Is it the same file and same offset? Provide more information on why
4092   // this leads to a redefinition error.
4093   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4094     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4095     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4096     bool EmittedDiag =
4097         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4098     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4099 
4100     // If the header has no guards, emit a note suggesting one.
4101     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4102       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4103 
4104     if (EmittedDiag)
4105       return;
4106   }
4107 
4108   // Redefinition coming from different files or couldn't do better above.
4109   if (Old->getLocation().isValid())
4110     Diag(Old->getLocation(), diag::note_previous_definition);
4111 }
4112 
4113 /// We've just determined that \p Old and \p New both appear to be definitions
4114 /// of the same variable. Either diagnose or fix the problem.
4115 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4116   if (!hasVisibleDefinition(Old) &&
4117       (New->getFormalLinkage() == InternalLinkage ||
4118        New->isInline() ||
4119        New->getDescribedVarTemplate() ||
4120        New->getNumTemplateParameterLists() ||
4121        New->getDeclContext()->isDependentContext())) {
4122     // The previous definition is hidden, and multiple definitions are
4123     // permitted (in separate TUs). Demote this to a declaration.
4124     New->demoteThisDefinitionToDeclaration();
4125 
4126     // Make the canonical definition visible.
4127     if (auto *OldTD = Old->getDescribedVarTemplate())
4128       makeMergedDefinitionVisible(OldTD);
4129     makeMergedDefinitionVisible(Old);
4130     return false;
4131   } else {
4132     Diag(New->getLocation(), diag::err_redefinition) << New;
4133     notePreviousDefinition(Old, New->getLocation());
4134     New->setInvalidDecl();
4135     return true;
4136   }
4137 }
4138 
4139 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4140 /// no declarator (e.g. "struct foo;") is parsed.
4141 Decl *
4142 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4143                                  RecordDecl *&AnonRecord) {
4144   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4145                                     AnonRecord);
4146 }
4147 
4148 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4149 // disambiguate entities defined in different scopes.
4150 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4151 // compatibility.
4152 // We will pick our mangling number depending on which version of MSVC is being
4153 // targeted.
4154 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4155   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4156              ? S->getMSCurManglingNumber()
4157              : S->getMSLastManglingNumber();
4158 }
4159 
4160 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4161   if (!Context.getLangOpts().CPlusPlus)
4162     return;
4163 
4164   if (isa<CXXRecordDecl>(Tag->getParent())) {
4165     // If this tag is the direct child of a class, number it if
4166     // it is anonymous.
4167     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4168       return;
4169     MangleNumberingContext &MCtx =
4170         Context.getManglingNumberContext(Tag->getParent());
4171     Context.setManglingNumber(
4172         Tag, MCtx.getManglingNumber(
4173                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4174     return;
4175   }
4176 
4177   // If this tag isn't a direct child of a class, number it if it is local.
4178   Decl *ManglingContextDecl;
4179   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4180           Tag->getDeclContext(), ManglingContextDecl)) {
4181     Context.setManglingNumber(
4182         Tag, MCtx->getManglingNumber(
4183                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4184   }
4185 }
4186 
4187 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4188                                         TypedefNameDecl *NewTD) {
4189   if (TagFromDeclSpec->isInvalidDecl())
4190     return;
4191 
4192   // Do nothing if the tag already has a name for linkage purposes.
4193   if (TagFromDeclSpec->hasNameForLinkage())
4194     return;
4195 
4196   // A well-formed anonymous tag must always be a TUK_Definition.
4197   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4198 
4199   // The type must match the tag exactly;  no qualifiers allowed.
4200   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4201                            Context.getTagDeclType(TagFromDeclSpec))) {
4202     if (getLangOpts().CPlusPlus)
4203       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4204     return;
4205   }
4206 
4207   // If we've already computed linkage for the anonymous tag, then
4208   // adding a typedef name for the anonymous decl can change that
4209   // linkage, which might be a serious problem.  Diagnose this as
4210   // unsupported and ignore the typedef name.  TODO: we should
4211   // pursue this as a language defect and establish a formal rule
4212   // for how to handle it.
4213   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4214     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4215 
4216     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4217     tagLoc = getLocForEndOfToken(tagLoc);
4218 
4219     llvm::SmallString<40> textToInsert;
4220     textToInsert += ' ';
4221     textToInsert += NewTD->getIdentifier()->getName();
4222     Diag(tagLoc, diag::note_typedef_changes_linkage)
4223         << FixItHint::CreateInsertion(tagLoc, textToInsert);
4224     return;
4225   }
4226 
4227   // Otherwise, set this is the anon-decl typedef for the tag.
4228   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4229 }
4230 
4231 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4232   switch (T) {
4233   case DeclSpec::TST_class:
4234     return 0;
4235   case DeclSpec::TST_struct:
4236     return 1;
4237   case DeclSpec::TST_interface:
4238     return 2;
4239   case DeclSpec::TST_union:
4240     return 3;
4241   case DeclSpec::TST_enum:
4242     return 4;
4243   default:
4244     llvm_unreachable("unexpected type specifier");
4245   }
4246 }
4247 
4248 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4249 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4250 /// parameters to cope with template friend declarations.
4251 Decl *
4252 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4253                                  MultiTemplateParamsArg TemplateParams,
4254                                  bool IsExplicitInstantiation,
4255                                  RecordDecl *&AnonRecord) {
4256   Decl *TagD = nullptr;
4257   TagDecl *Tag = nullptr;
4258   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4259       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4260       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4261       DS.getTypeSpecType() == DeclSpec::TST_union ||
4262       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4263     TagD = DS.getRepAsDecl();
4264 
4265     if (!TagD) // We probably had an error
4266       return nullptr;
4267 
4268     // Note that the above type specs guarantee that the
4269     // type rep is a Decl, whereas in many of the others
4270     // it's a Type.
4271     if (isa<TagDecl>(TagD))
4272       Tag = cast<TagDecl>(TagD);
4273     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4274       Tag = CTD->getTemplatedDecl();
4275   }
4276 
4277   if (Tag) {
4278     handleTagNumbering(Tag, S);
4279     Tag->setFreeStanding();
4280     if (Tag->isInvalidDecl())
4281       return Tag;
4282   }
4283 
4284   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4285     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4286     // or incomplete types shall not be restrict-qualified."
4287     if (TypeQuals & DeclSpec::TQ_restrict)
4288       Diag(DS.getRestrictSpecLoc(),
4289            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4290            << DS.getSourceRange();
4291   }
4292 
4293   if (DS.isInlineSpecified())
4294     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4295         << getLangOpts().CPlusPlus17;
4296 
4297   if (DS.hasConstexprSpecifier()) {
4298     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4299     // and definitions of functions and variables.
4300     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4301     // the declaration of a function or function template
4302     bool IsConsteval = DS.getConstexprSpecifier() == CSK_consteval;
4303     if (Tag)
4304       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4305           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << IsConsteval;
4306     else
4307       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4308           << IsConsteval;
4309     // Don't emit warnings after this error.
4310     return TagD;
4311   }
4312 
4313   DiagnoseFunctionSpecifiers(DS);
4314 
4315   if (DS.isFriendSpecified()) {
4316     // If we're dealing with a decl but not a TagDecl, assume that
4317     // whatever routines created it handled the friendship aspect.
4318     if (TagD && !Tag)
4319       return nullptr;
4320     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4321   }
4322 
4323   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4324   bool IsExplicitSpecialization =
4325     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4326   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4327       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4328       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4329     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4330     // nested-name-specifier unless it is an explicit instantiation
4331     // or an explicit specialization.
4332     //
4333     // FIXME: We allow class template partial specializations here too, per the
4334     // obvious intent of DR1819.
4335     //
4336     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4337     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4338         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4339     return nullptr;
4340   }
4341 
4342   // Track whether this decl-specifier declares anything.
4343   bool DeclaresAnything = true;
4344 
4345   // Handle anonymous struct definitions.
4346   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4347     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4348         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4349       if (getLangOpts().CPlusPlus ||
4350           Record->getDeclContext()->isRecord()) {
4351         // If CurContext is a DeclContext that can contain statements,
4352         // RecursiveASTVisitor won't visit the decls that
4353         // BuildAnonymousStructOrUnion() will put into CurContext.
4354         // Also store them here so that they can be part of the
4355         // DeclStmt that gets created in this case.
4356         // FIXME: Also return the IndirectFieldDecls created by
4357         // BuildAnonymousStructOr union, for the same reason?
4358         if (CurContext->isFunctionOrMethod())
4359           AnonRecord = Record;
4360         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4361                                            Context.getPrintingPolicy());
4362       }
4363 
4364       DeclaresAnything = false;
4365     }
4366   }
4367 
4368   // C11 6.7.2.1p2:
4369   //   A struct-declaration that does not declare an anonymous structure or
4370   //   anonymous union shall contain a struct-declarator-list.
4371   //
4372   // This rule also existed in C89 and C99; the grammar for struct-declaration
4373   // did not permit a struct-declaration without a struct-declarator-list.
4374   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4375       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4376     // Check for Microsoft C extension: anonymous struct/union member.
4377     // Handle 2 kinds of anonymous struct/union:
4378     //   struct STRUCT;
4379     //   union UNION;
4380     // and
4381     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4382     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4383     if ((Tag && Tag->getDeclName()) ||
4384         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4385       RecordDecl *Record = nullptr;
4386       if (Tag)
4387         Record = dyn_cast<RecordDecl>(Tag);
4388       else if (const RecordType *RT =
4389                    DS.getRepAsType().get()->getAsStructureType())
4390         Record = RT->getDecl();
4391       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4392         Record = UT->getDecl();
4393 
4394       if (Record && getLangOpts().MicrosoftExt) {
4395         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4396             << Record->isUnion() << DS.getSourceRange();
4397         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4398       }
4399 
4400       DeclaresAnything = false;
4401     }
4402   }
4403 
4404   // Skip all the checks below if we have a type error.
4405   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4406       (TagD && TagD->isInvalidDecl()))
4407     return TagD;
4408 
4409   if (getLangOpts().CPlusPlus &&
4410       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4411     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4412       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4413           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4414         DeclaresAnything = false;
4415 
4416   if (!DS.isMissingDeclaratorOk()) {
4417     // Customize diagnostic for a typedef missing a name.
4418     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4419       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4420           << DS.getSourceRange();
4421     else
4422       DeclaresAnything = false;
4423   }
4424 
4425   if (DS.isModulePrivateSpecified() &&
4426       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4427     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4428       << Tag->getTagKind()
4429       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4430 
4431   ActOnDocumentableDecl(TagD);
4432 
4433   // C 6.7/2:
4434   //   A declaration [...] shall declare at least a declarator [...], a tag,
4435   //   or the members of an enumeration.
4436   // C++ [dcl.dcl]p3:
4437   //   [If there are no declarators], and except for the declaration of an
4438   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4439   //   names into the program, or shall redeclare a name introduced by a
4440   //   previous declaration.
4441   if (!DeclaresAnything) {
4442     // In C, we allow this as a (popular) extension / bug. Don't bother
4443     // producing further diagnostics for redundant qualifiers after this.
4444     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4445     return TagD;
4446   }
4447 
4448   // C++ [dcl.stc]p1:
4449   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4450   //   init-declarator-list of the declaration shall not be empty.
4451   // C++ [dcl.fct.spec]p1:
4452   //   If a cv-qualifier appears in a decl-specifier-seq, the
4453   //   init-declarator-list of the declaration shall not be empty.
4454   //
4455   // Spurious qualifiers here appear to be valid in C.
4456   unsigned DiagID = diag::warn_standalone_specifier;
4457   if (getLangOpts().CPlusPlus)
4458     DiagID = diag::ext_standalone_specifier;
4459 
4460   // Note that a linkage-specification sets a storage class, but
4461   // 'extern "C" struct foo;' is actually valid and not theoretically
4462   // useless.
4463   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4464     if (SCS == DeclSpec::SCS_mutable)
4465       // Since mutable is not a viable storage class specifier in C, there is
4466       // no reason to treat it as an extension. Instead, diagnose as an error.
4467       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4468     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4469       Diag(DS.getStorageClassSpecLoc(), DiagID)
4470         << DeclSpec::getSpecifierName(SCS);
4471   }
4472 
4473   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4474     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4475       << DeclSpec::getSpecifierName(TSCS);
4476   if (DS.getTypeQualifiers()) {
4477     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4478       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4479     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4480       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4481     // Restrict is covered above.
4482     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4483       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4484     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4485       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4486   }
4487 
4488   // Warn about ignored type attributes, for example:
4489   // __attribute__((aligned)) struct A;
4490   // Attributes should be placed after tag to apply to type declaration.
4491   if (!DS.getAttributes().empty()) {
4492     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4493     if (TypeSpecType == DeclSpec::TST_class ||
4494         TypeSpecType == DeclSpec::TST_struct ||
4495         TypeSpecType == DeclSpec::TST_interface ||
4496         TypeSpecType == DeclSpec::TST_union ||
4497         TypeSpecType == DeclSpec::TST_enum) {
4498       for (const ParsedAttr &AL : DS.getAttributes())
4499         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4500             << AL.getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4501     }
4502   }
4503 
4504   return TagD;
4505 }
4506 
4507 /// We are trying to inject an anonymous member into the given scope;
4508 /// check if there's an existing declaration that can't be overloaded.
4509 ///
4510 /// \return true if this is a forbidden redeclaration
4511 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4512                                          Scope *S,
4513                                          DeclContext *Owner,
4514                                          DeclarationName Name,
4515                                          SourceLocation NameLoc,
4516                                          bool IsUnion) {
4517   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4518                  Sema::ForVisibleRedeclaration);
4519   if (!SemaRef.LookupName(R, S)) return false;
4520 
4521   // Pick a representative declaration.
4522   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4523   assert(PrevDecl && "Expected a non-null Decl");
4524 
4525   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4526     return false;
4527 
4528   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4529     << IsUnion << Name;
4530   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4531 
4532   return true;
4533 }
4534 
4535 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4536 /// anonymous struct or union AnonRecord into the owning context Owner
4537 /// and scope S. This routine will be invoked just after we realize
4538 /// that an unnamed union or struct is actually an anonymous union or
4539 /// struct, e.g.,
4540 ///
4541 /// @code
4542 /// union {
4543 ///   int i;
4544 ///   float f;
4545 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4546 ///    // f into the surrounding scope.x
4547 /// @endcode
4548 ///
4549 /// This routine is recursive, injecting the names of nested anonymous
4550 /// structs/unions into the owning context and scope as well.
4551 static bool
4552 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4553                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4554                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4555   bool Invalid = false;
4556 
4557   // Look every FieldDecl and IndirectFieldDecl with a name.
4558   for (auto *D : AnonRecord->decls()) {
4559     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4560         cast<NamedDecl>(D)->getDeclName()) {
4561       ValueDecl *VD = cast<ValueDecl>(D);
4562       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4563                                        VD->getLocation(),
4564                                        AnonRecord->isUnion())) {
4565         // C++ [class.union]p2:
4566         //   The names of the members of an anonymous union shall be
4567         //   distinct from the names of any other entity in the
4568         //   scope in which the anonymous union is declared.
4569         Invalid = true;
4570       } else {
4571         // C++ [class.union]p2:
4572         //   For the purpose of name lookup, after the anonymous union
4573         //   definition, the members of the anonymous union are
4574         //   considered to have been defined in the scope in which the
4575         //   anonymous union is declared.
4576         unsigned OldChainingSize = Chaining.size();
4577         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4578           Chaining.append(IF->chain_begin(), IF->chain_end());
4579         else
4580           Chaining.push_back(VD);
4581 
4582         assert(Chaining.size() >= 2);
4583         NamedDecl **NamedChain =
4584           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4585         for (unsigned i = 0; i < Chaining.size(); i++)
4586           NamedChain[i] = Chaining[i];
4587 
4588         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4589             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4590             VD->getType(), {NamedChain, Chaining.size()});
4591 
4592         for (const auto *Attr : VD->attrs())
4593           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4594 
4595         IndirectField->setAccess(AS);
4596         IndirectField->setImplicit();
4597         SemaRef.PushOnScopeChains(IndirectField, S);
4598 
4599         // That includes picking up the appropriate access specifier.
4600         if (AS != AS_none) IndirectField->setAccess(AS);
4601 
4602         Chaining.resize(OldChainingSize);
4603       }
4604     }
4605   }
4606 
4607   return Invalid;
4608 }
4609 
4610 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4611 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4612 /// illegal input values are mapped to SC_None.
4613 static StorageClass
4614 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4615   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4616   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4617          "Parser allowed 'typedef' as storage class VarDecl.");
4618   switch (StorageClassSpec) {
4619   case DeclSpec::SCS_unspecified:    return SC_None;
4620   case DeclSpec::SCS_extern:
4621     if (DS.isExternInLinkageSpec())
4622       return SC_None;
4623     return SC_Extern;
4624   case DeclSpec::SCS_static:         return SC_Static;
4625   case DeclSpec::SCS_auto:           return SC_Auto;
4626   case DeclSpec::SCS_register:       return SC_Register;
4627   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4628     // Illegal SCSs map to None: error reporting is up to the caller.
4629   case DeclSpec::SCS_mutable:        // Fall through.
4630   case DeclSpec::SCS_typedef:        return SC_None;
4631   }
4632   llvm_unreachable("unknown storage class specifier");
4633 }
4634 
4635 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4636   assert(Record->hasInClassInitializer());
4637 
4638   for (const auto *I : Record->decls()) {
4639     const auto *FD = dyn_cast<FieldDecl>(I);
4640     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4641       FD = IFD->getAnonField();
4642     if (FD && FD->hasInClassInitializer())
4643       return FD->getLocation();
4644   }
4645 
4646   llvm_unreachable("couldn't find in-class initializer");
4647 }
4648 
4649 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4650                                       SourceLocation DefaultInitLoc) {
4651   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4652     return;
4653 
4654   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4655   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4656 }
4657 
4658 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4659                                       CXXRecordDecl *AnonUnion) {
4660   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4661     return;
4662 
4663   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4664 }
4665 
4666 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4667 /// anonymous structure or union. Anonymous unions are a C++ feature
4668 /// (C++ [class.union]) and a C11 feature; anonymous structures
4669 /// are a C11 feature and GNU C++ extension.
4670 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4671                                         AccessSpecifier AS,
4672                                         RecordDecl *Record,
4673                                         const PrintingPolicy &Policy) {
4674   DeclContext *Owner = Record->getDeclContext();
4675 
4676   // Diagnose whether this anonymous struct/union is an extension.
4677   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4678     Diag(Record->getLocation(), diag::ext_anonymous_union);
4679   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4680     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4681   else if (!Record->isUnion() && !getLangOpts().C11)
4682     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4683 
4684   // C and C++ require different kinds of checks for anonymous
4685   // structs/unions.
4686   bool Invalid = false;
4687   if (getLangOpts().CPlusPlus) {
4688     const char *PrevSpec = nullptr;
4689     if (Record->isUnion()) {
4690       // C++ [class.union]p6:
4691       // C++17 [class.union.anon]p2:
4692       //   Anonymous unions declared in a named namespace or in the
4693       //   global namespace shall be declared static.
4694       unsigned DiagID;
4695       DeclContext *OwnerScope = Owner->getRedeclContext();
4696       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4697           (OwnerScope->isTranslationUnit() ||
4698            (OwnerScope->isNamespace() &&
4699             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
4700         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4701           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4702 
4703         // Recover by adding 'static'.
4704         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4705                                PrevSpec, DiagID, Policy);
4706       }
4707       // C++ [class.union]p6:
4708       //   A storage class is not allowed in a declaration of an
4709       //   anonymous union in a class scope.
4710       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4711                isa<RecordDecl>(Owner)) {
4712         Diag(DS.getStorageClassSpecLoc(),
4713              diag::err_anonymous_union_with_storage_spec)
4714           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4715 
4716         // Recover by removing the storage specifier.
4717         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4718                                SourceLocation(),
4719                                PrevSpec, DiagID, Context.getPrintingPolicy());
4720       }
4721     }
4722 
4723     // Ignore const/volatile/restrict qualifiers.
4724     if (DS.getTypeQualifiers()) {
4725       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4726         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4727           << Record->isUnion() << "const"
4728           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4729       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4730         Diag(DS.getVolatileSpecLoc(),
4731              diag::ext_anonymous_struct_union_qualified)
4732           << Record->isUnion() << "volatile"
4733           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4734       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4735         Diag(DS.getRestrictSpecLoc(),
4736              diag::ext_anonymous_struct_union_qualified)
4737           << Record->isUnion() << "restrict"
4738           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4739       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4740         Diag(DS.getAtomicSpecLoc(),
4741              diag::ext_anonymous_struct_union_qualified)
4742           << Record->isUnion() << "_Atomic"
4743           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4744       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4745         Diag(DS.getUnalignedSpecLoc(),
4746              diag::ext_anonymous_struct_union_qualified)
4747           << Record->isUnion() << "__unaligned"
4748           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4749 
4750       DS.ClearTypeQualifiers();
4751     }
4752 
4753     // C++ [class.union]p2:
4754     //   The member-specification of an anonymous union shall only
4755     //   define non-static data members. [Note: nested types and
4756     //   functions cannot be declared within an anonymous union. ]
4757     for (auto *Mem : Record->decls()) {
4758       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4759         // C++ [class.union]p3:
4760         //   An anonymous union shall not have private or protected
4761         //   members (clause 11).
4762         assert(FD->getAccess() != AS_none);
4763         if (FD->getAccess() != AS_public) {
4764           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4765             << Record->isUnion() << (FD->getAccess() == AS_protected);
4766           Invalid = true;
4767         }
4768 
4769         // C++ [class.union]p1
4770         //   An object of a class with a non-trivial constructor, a non-trivial
4771         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4772         //   assignment operator cannot be a member of a union, nor can an
4773         //   array of such objects.
4774         if (CheckNontrivialField(FD))
4775           Invalid = true;
4776       } else if (Mem->isImplicit()) {
4777         // Any implicit members are fine.
4778       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4779         // This is a type that showed up in an
4780         // elaborated-type-specifier inside the anonymous struct or
4781         // union, but which actually declares a type outside of the
4782         // anonymous struct or union. It's okay.
4783       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4784         if (!MemRecord->isAnonymousStructOrUnion() &&
4785             MemRecord->getDeclName()) {
4786           // Visual C++ allows type definition in anonymous struct or union.
4787           if (getLangOpts().MicrosoftExt)
4788             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4789               << Record->isUnion();
4790           else {
4791             // This is a nested type declaration.
4792             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4793               << Record->isUnion();
4794             Invalid = true;
4795           }
4796         } else {
4797           // This is an anonymous type definition within another anonymous type.
4798           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4799           // not part of standard C++.
4800           Diag(MemRecord->getLocation(),
4801                diag::ext_anonymous_record_with_anonymous_type)
4802             << Record->isUnion();
4803         }
4804       } else if (isa<AccessSpecDecl>(Mem)) {
4805         // Any access specifier is fine.
4806       } else if (isa<StaticAssertDecl>(Mem)) {
4807         // In C++1z, static_assert declarations are also fine.
4808       } else {
4809         // We have something that isn't a non-static data
4810         // member. Complain about it.
4811         unsigned DK = diag::err_anonymous_record_bad_member;
4812         if (isa<TypeDecl>(Mem))
4813           DK = diag::err_anonymous_record_with_type;
4814         else if (isa<FunctionDecl>(Mem))
4815           DK = diag::err_anonymous_record_with_function;
4816         else if (isa<VarDecl>(Mem))
4817           DK = diag::err_anonymous_record_with_static;
4818 
4819         // Visual C++ allows type definition in anonymous struct or union.
4820         if (getLangOpts().MicrosoftExt &&
4821             DK == diag::err_anonymous_record_with_type)
4822           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4823             << Record->isUnion();
4824         else {
4825           Diag(Mem->getLocation(), DK) << Record->isUnion();
4826           Invalid = true;
4827         }
4828       }
4829     }
4830 
4831     // C++11 [class.union]p8 (DR1460):
4832     //   At most one variant member of a union may have a
4833     //   brace-or-equal-initializer.
4834     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4835         Owner->isRecord())
4836       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4837                                 cast<CXXRecordDecl>(Record));
4838   }
4839 
4840   if (!Record->isUnion() && !Owner->isRecord()) {
4841     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4842       << getLangOpts().CPlusPlus;
4843     Invalid = true;
4844   }
4845 
4846   // C++ [dcl.dcl]p3:
4847   //   [If there are no declarators], and except for the declaration of an
4848   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4849   //   names into the program
4850   // C++ [class.mem]p2:
4851   //   each such member-declaration shall either declare at least one member
4852   //   name of the class or declare at least one unnamed bit-field
4853   //
4854   // For C this is an error even for a named struct, and is diagnosed elsewhere.
4855   if (getLangOpts().CPlusPlus && Record->field_empty())
4856     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4857 
4858   // Mock up a declarator.
4859   Declarator Dc(DS, DeclaratorContext::MemberContext);
4860   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4861   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4862 
4863   // Create a declaration for this anonymous struct/union.
4864   NamedDecl *Anon = nullptr;
4865   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4866     Anon = FieldDecl::Create(
4867         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
4868         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
4869         /*BitWidth=*/nullptr, /*Mutable=*/false,
4870         /*InitStyle=*/ICIS_NoInit);
4871     Anon->setAccess(AS);
4872     if (getLangOpts().CPlusPlus)
4873       FieldCollector->Add(cast<FieldDecl>(Anon));
4874   } else {
4875     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4876     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4877     if (SCSpec == DeclSpec::SCS_mutable) {
4878       // mutable can only appear on non-static class members, so it's always
4879       // an error here
4880       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4881       Invalid = true;
4882       SC = SC_None;
4883     }
4884 
4885     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
4886                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4887                            Context.getTypeDeclType(Record), TInfo, SC);
4888 
4889     // Default-initialize the implicit variable. This initialization will be
4890     // trivial in almost all cases, except if a union member has an in-class
4891     // initializer:
4892     //   union { int n = 0; };
4893     ActOnUninitializedDecl(Anon);
4894   }
4895   Anon->setImplicit();
4896 
4897   // Mark this as an anonymous struct/union type.
4898   Record->setAnonymousStructOrUnion(true);
4899 
4900   // Add the anonymous struct/union object to the current
4901   // context. We'll be referencing this object when we refer to one of
4902   // its members.
4903   Owner->addDecl(Anon);
4904 
4905   // Inject the members of the anonymous struct/union into the owning
4906   // context and into the identifier resolver chain for name lookup
4907   // purposes.
4908   SmallVector<NamedDecl*, 2> Chain;
4909   Chain.push_back(Anon);
4910 
4911   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4912     Invalid = true;
4913 
4914   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4915     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4916       Decl *ManglingContextDecl;
4917       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4918               NewVD->getDeclContext(), ManglingContextDecl)) {
4919         Context.setManglingNumber(
4920             NewVD, MCtx->getManglingNumber(
4921                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4922         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4923       }
4924     }
4925   }
4926 
4927   if (Invalid)
4928     Anon->setInvalidDecl();
4929 
4930   return Anon;
4931 }
4932 
4933 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4934 /// Microsoft C anonymous structure.
4935 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4936 /// Example:
4937 ///
4938 /// struct A { int a; };
4939 /// struct B { struct A; int b; };
4940 ///
4941 /// void foo() {
4942 ///   B var;
4943 ///   var.a = 3;
4944 /// }
4945 ///
4946 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4947                                            RecordDecl *Record) {
4948   assert(Record && "expected a record!");
4949 
4950   // Mock up a declarator.
4951   Declarator Dc(DS, DeclaratorContext::TypeNameContext);
4952   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4953   assert(TInfo && "couldn't build declarator info for anonymous struct");
4954 
4955   auto *ParentDecl = cast<RecordDecl>(CurContext);
4956   QualType RecTy = Context.getTypeDeclType(Record);
4957 
4958   // Create a declaration for this anonymous struct.
4959   NamedDecl *Anon =
4960       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
4961                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
4962                         /*BitWidth=*/nullptr, /*Mutable=*/false,
4963                         /*InitStyle=*/ICIS_NoInit);
4964   Anon->setImplicit();
4965 
4966   // Add the anonymous struct object to the current context.
4967   CurContext->addDecl(Anon);
4968 
4969   // Inject the members of the anonymous struct into the current
4970   // context and into the identifier resolver chain for name lookup
4971   // purposes.
4972   SmallVector<NamedDecl*, 2> Chain;
4973   Chain.push_back(Anon);
4974 
4975   RecordDecl *RecordDef = Record->getDefinition();
4976   if (RequireCompleteType(Anon->getLocation(), RecTy,
4977                           diag::err_field_incomplete) ||
4978       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4979                                           AS_none, Chain)) {
4980     Anon->setInvalidDecl();
4981     ParentDecl->setInvalidDecl();
4982   }
4983 
4984   return Anon;
4985 }
4986 
4987 /// GetNameForDeclarator - Determine the full declaration name for the
4988 /// given Declarator.
4989 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4990   return GetNameFromUnqualifiedId(D.getName());
4991 }
4992 
4993 /// Retrieves the declaration name from a parsed unqualified-id.
4994 DeclarationNameInfo
4995 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4996   DeclarationNameInfo NameInfo;
4997   NameInfo.setLoc(Name.StartLocation);
4998 
4999   switch (Name.getKind()) {
5000 
5001   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5002   case UnqualifiedIdKind::IK_Identifier:
5003     NameInfo.setName(Name.Identifier);
5004     return NameInfo;
5005 
5006   case UnqualifiedIdKind::IK_DeductionGuideName: {
5007     // C++ [temp.deduct.guide]p3:
5008     //   The simple-template-id shall name a class template specialization.
5009     //   The template-name shall be the same identifier as the template-name
5010     //   of the simple-template-id.
5011     // These together intend to imply that the template-name shall name a
5012     // class template.
5013     // FIXME: template<typename T> struct X {};
5014     //        template<typename T> using Y = X<T>;
5015     //        Y(int) -> Y<int>;
5016     //   satisfies these rules but does not name a class template.
5017     TemplateName TN = Name.TemplateName.get().get();
5018     auto *Template = TN.getAsTemplateDecl();
5019     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5020       Diag(Name.StartLocation,
5021            diag::err_deduction_guide_name_not_class_template)
5022         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5023       if (Template)
5024         Diag(Template->getLocation(), diag::note_template_decl_here);
5025       return DeclarationNameInfo();
5026     }
5027 
5028     NameInfo.setName(
5029         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5030     return NameInfo;
5031   }
5032 
5033   case UnqualifiedIdKind::IK_OperatorFunctionId:
5034     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5035                                            Name.OperatorFunctionId.Operator));
5036     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
5037       = Name.OperatorFunctionId.SymbolLocations[0];
5038     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
5039       = Name.EndLocation.getRawEncoding();
5040     return NameInfo;
5041 
5042   case UnqualifiedIdKind::IK_LiteralOperatorId:
5043     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5044                                                            Name.Identifier));
5045     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5046     return NameInfo;
5047 
5048   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5049     TypeSourceInfo *TInfo;
5050     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5051     if (Ty.isNull())
5052       return DeclarationNameInfo();
5053     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5054                                                Context.getCanonicalType(Ty)));
5055     NameInfo.setNamedTypeInfo(TInfo);
5056     return NameInfo;
5057   }
5058 
5059   case UnqualifiedIdKind::IK_ConstructorName: {
5060     TypeSourceInfo *TInfo;
5061     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5062     if (Ty.isNull())
5063       return DeclarationNameInfo();
5064     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5065                                               Context.getCanonicalType(Ty)));
5066     NameInfo.setNamedTypeInfo(TInfo);
5067     return NameInfo;
5068   }
5069 
5070   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5071     // In well-formed code, we can only have a constructor
5072     // template-id that refers to the current context, so go there
5073     // to find the actual type being constructed.
5074     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5075     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5076       return DeclarationNameInfo();
5077 
5078     // Determine the type of the class being constructed.
5079     QualType CurClassType = Context.getTypeDeclType(CurClass);
5080 
5081     // FIXME: Check two things: that the template-id names the same type as
5082     // CurClassType, and that the template-id does not occur when the name
5083     // was qualified.
5084 
5085     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5086                                     Context.getCanonicalType(CurClassType)));
5087     // FIXME: should we retrieve TypeSourceInfo?
5088     NameInfo.setNamedTypeInfo(nullptr);
5089     return NameInfo;
5090   }
5091 
5092   case UnqualifiedIdKind::IK_DestructorName: {
5093     TypeSourceInfo *TInfo;
5094     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5095     if (Ty.isNull())
5096       return DeclarationNameInfo();
5097     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5098                                               Context.getCanonicalType(Ty)));
5099     NameInfo.setNamedTypeInfo(TInfo);
5100     return NameInfo;
5101   }
5102 
5103   case UnqualifiedIdKind::IK_TemplateId: {
5104     TemplateName TName = Name.TemplateId->Template.get();
5105     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5106     return Context.getNameForTemplate(TName, TNameLoc);
5107   }
5108 
5109   } // switch (Name.getKind())
5110 
5111   llvm_unreachable("Unknown name kind");
5112 }
5113 
5114 static QualType getCoreType(QualType Ty) {
5115   do {
5116     if (Ty->isPointerType() || Ty->isReferenceType())
5117       Ty = Ty->getPointeeType();
5118     else if (Ty->isArrayType())
5119       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5120     else
5121       return Ty.withoutLocalFastQualifiers();
5122   } while (true);
5123 }
5124 
5125 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5126 /// and Definition have "nearly" matching parameters. This heuristic is
5127 /// used to improve diagnostics in the case where an out-of-line function
5128 /// definition doesn't match any declaration within the class or namespace.
5129 /// Also sets Params to the list of indices to the parameters that differ
5130 /// between the declaration and the definition. If hasSimilarParameters
5131 /// returns true and Params is empty, then all of the parameters match.
5132 static bool hasSimilarParameters(ASTContext &Context,
5133                                      FunctionDecl *Declaration,
5134                                      FunctionDecl *Definition,
5135                                      SmallVectorImpl<unsigned> &Params) {
5136   Params.clear();
5137   if (Declaration->param_size() != Definition->param_size())
5138     return false;
5139   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5140     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5141     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5142 
5143     // The parameter types are identical
5144     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5145       continue;
5146 
5147     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5148     QualType DefParamBaseTy = getCoreType(DefParamTy);
5149     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5150     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5151 
5152     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5153         (DeclTyName && DeclTyName == DefTyName))
5154       Params.push_back(Idx);
5155     else  // The two parameters aren't even close
5156       return false;
5157   }
5158 
5159   return true;
5160 }
5161 
5162 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5163 /// declarator needs to be rebuilt in the current instantiation.
5164 /// Any bits of declarator which appear before the name are valid for
5165 /// consideration here.  That's specifically the type in the decl spec
5166 /// and the base type in any member-pointer chunks.
5167 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5168                                                     DeclarationName Name) {
5169   // The types we specifically need to rebuild are:
5170   //   - typenames, typeofs, and decltypes
5171   //   - types which will become injected class names
5172   // Of course, we also need to rebuild any type referencing such a
5173   // type.  It's safest to just say "dependent", but we call out a
5174   // few cases here.
5175 
5176   DeclSpec &DS = D.getMutableDeclSpec();
5177   switch (DS.getTypeSpecType()) {
5178   case DeclSpec::TST_typename:
5179   case DeclSpec::TST_typeofType:
5180   case DeclSpec::TST_underlyingType:
5181   case DeclSpec::TST_atomic: {
5182     // Grab the type from the parser.
5183     TypeSourceInfo *TSI = nullptr;
5184     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5185     if (T.isNull() || !T->isDependentType()) break;
5186 
5187     // Make sure there's a type source info.  This isn't really much
5188     // of a waste; most dependent types should have type source info
5189     // attached already.
5190     if (!TSI)
5191       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5192 
5193     // Rebuild the type in the current instantiation.
5194     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5195     if (!TSI) return true;
5196 
5197     // Store the new type back in the decl spec.
5198     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5199     DS.UpdateTypeRep(LocType);
5200     break;
5201   }
5202 
5203   case DeclSpec::TST_decltype:
5204   case DeclSpec::TST_typeofExpr: {
5205     Expr *E = DS.getRepAsExpr();
5206     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5207     if (Result.isInvalid()) return true;
5208     DS.UpdateExprRep(Result.get());
5209     break;
5210   }
5211 
5212   default:
5213     // Nothing to do for these decl specs.
5214     break;
5215   }
5216 
5217   // It doesn't matter what order we do this in.
5218   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5219     DeclaratorChunk &Chunk = D.getTypeObject(I);
5220 
5221     // The only type information in the declarator which can come
5222     // before the declaration name is the base type of a member
5223     // pointer.
5224     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5225       continue;
5226 
5227     // Rebuild the scope specifier in-place.
5228     CXXScopeSpec &SS = Chunk.Mem.Scope();
5229     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5230       return true;
5231   }
5232 
5233   return false;
5234 }
5235 
5236 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5237   D.setFunctionDefinitionKind(FDK_Declaration);
5238   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5239 
5240   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5241       Dcl && Dcl->getDeclContext()->isFileContext())
5242     Dcl->setTopLevelDeclInObjCContainer();
5243 
5244   if (getLangOpts().OpenCL)
5245     setCurrentOpenCLExtensionForDecl(Dcl);
5246 
5247   return Dcl;
5248 }
5249 
5250 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5251 ///   If T is the name of a class, then each of the following shall have a
5252 ///   name different from T:
5253 ///     - every static data member of class T;
5254 ///     - every member function of class T
5255 ///     - every member of class T that is itself a type;
5256 /// \returns true if the declaration name violates these rules.
5257 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5258                                    DeclarationNameInfo NameInfo) {
5259   DeclarationName Name = NameInfo.getName();
5260 
5261   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5262   while (Record && Record->isAnonymousStructOrUnion())
5263     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5264   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5265     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5266     return true;
5267   }
5268 
5269   return false;
5270 }
5271 
5272 /// Diagnose a declaration whose declarator-id has the given
5273 /// nested-name-specifier.
5274 ///
5275 /// \param SS The nested-name-specifier of the declarator-id.
5276 ///
5277 /// \param DC The declaration context to which the nested-name-specifier
5278 /// resolves.
5279 ///
5280 /// \param Name The name of the entity being declared.
5281 ///
5282 /// \param Loc The location of the name of the entity being declared.
5283 ///
5284 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5285 /// we're declaring an explicit / partial specialization / instantiation.
5286 ///
5287 /// \returns true if we cannot safely recover from this error, false otherwise.
5288 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5289                                         DeclarationName Name,
5290                                         SourceLocation Loc, bool IsTemplateId) {
5291   DeclContext *Cur = CurContext;
5292   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5293     Cur = Cur->getParent();
5294 
5295   // If the user provided a superfluous scope specifier that refers back to the
5296   // class in which the entity is already declared, diagnose and ignore it.
5297   //
5298   // class X {
5299   //   void X::f();
5300   // };
5301   //
5302   // Note, it was once ill-formed to give redundant qualification in all
5303   // contexts, but that rule was removed by DR482.
5304   if (Cur->Equals(DC)) {
5305     if (Cur->isRecord()) {
5306       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5307                                       : diag::err_member_extra_qualification)
5308         << Name << FixItHint::CreateRemoval(SS.getRange());
5309       SS.clear();
5310     } else {
5311       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5312     }
5313     return false;
5314   }
5315 
5316   // Check whether the qualifying scope encloses the scope of the original
5317   // declaration. For a template-id, we perform the checks in
5318   // CheckTemplateSpecializationScope.
5319   if (!Cur->Encloses(DC) && !IsTemplateId) {
5320     if (Cur->isRecord())
5321       Diag(Loc, diag::err_member_qualification)
5322         << Name << SS.getRange();
5323     else if (isa<TranslationUnitDecl>(DC))
5324       Diag(Loc, diag::err_invalid_declarator_global_scope)
5325         << Name << SS.getRange();
5326     else if (isa<FunctionDecl>(Cur))
5327       Diag(Loc, diag::err_invalid_declarator_in_function)
5328         << Name << SS.getRange();
5329     else if (isa<BlockDecl>(Cur))
5330       Diag(Loc, diag::err_invalid_declarator_in_block)
5331         << Name << SS.getRange();
5332     else
5333       Diag(Loc, diag::err_invalid_declarator_scope)
5334       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5335 
5336     return true;
5337   }
5338 
5339   if (Cur->isRecord()) {
5340     // Cannot qualify members within a class.
5341     Diag(Loc, diag::err_member_qualification)
5342       << Name << SS.getRange();
5343     SS.clear();
5344 
5345     // C++ constructors and destructors with incorrect scopes can break
5346     // our AST invariants by having the wrong underlying types. If
5347     // that's the case, then drop this declaration entirely.
5348     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5349          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5350         !Context.hasSameType(Name.getCXXNameType(),
5351                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5352       return true;
5353 
5354     return false;
5355   }
5356 
5357   // C++11 [dcl.meaning]p1:
5358   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5359   //   not begin with a decltype-specifer"
5360   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5361   while (SpecLoc.getPrefix())
5362     SpecLoc = SpecLoc.getPrefix();
5363   if (dyn_cast_or_null<DecltypeType>(
5364         SpecLoc.getNestedNameSpecifier()->getAsType()))
5365     Diag(Loc, diag::err_decltype_in_declarator)
5366       << SpecLoc.getTypeLoc().getSourceRange();
5367 
5368   return false;
5369 }
5370 
5371 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5372                                   MultiTemplateParamsArg TemplateParamLists) {
5373   // TODO: consider using NameInfo for diagnostic.
5374   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5375   DeclarationName Name = NameInfo.getName();
5376 
5377   // All of these full declarators require an identifier.  If it doesn't have
5378   // one, the ParsedFreeStandingDeclSpec action should be used.
5379   if (D.isDecompositionDeclarator()) {
5380     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5381   } else if (!Name) {
5382     if (!D.isInvalidType())  // Reject this if we think it is valid.
5383       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5384           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5385     return nullptr;
5386   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5387     return nullptr;
5388 
5389   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5390   // we find one that is.
5391   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5392          (S->getFlags() & Scope::TemplateParamScope) != 0)
5393     S = S->getParent();
5394 
5395   DeclContext *DC = CurContext;
5396   if (D.getCXXScopeSpec().isInvalid())
5397     D.setInvalidType();
5398   else if (D.getCXXScopeSpec().isSet()) {
5399     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5400                                         UPPC_DeclarationQualifier))
5401       return nullptr;
5402 
5403     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5404     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5405     if (!DC || isa<EnumDecl>(DC)) {
5406       // If we could not compute the declaration context, it's because the
5407       // declaration context is dependent but does not refer to a class,
5408       // class template, or class template partial specialization. Complain
5409       // and return early, to avoid the coming semantic disaster.
5410       Diag(D.getIdentifierLoc(),
5411            diag::err_template_qualified_declarator_no_match)
5412         << D.getCXXScopeSpec().getScopeRep()
5413         << D.getCXXScopeSpec().getRange();
5414       return nullptr;
5415     }
5416     bool IsDependentContext = DC->isDependentContext();
5417 
5418     if (!IsDependentContext &&
5419         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5420       return nullptr;
5421 
5422     // If a class is incomplete, do not parse entities inside it.
5423     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5424       Diag(D.getIdentifierLoc(),
5425            diag::err_member_def_undefined_record)
5426         << Name << DC << D.getCXXScopeSpec().getRange();
5427       return nullptr;
5428     }
5429     if (!D.getDeclSpec().isFriendSpecified()) {
5430       if (diagnoseQualifiedDeclaration(
5431               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5432               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5433         if (DC->isRecord())
5434           return nullptr;
5435 
5436         D.setInvalidType();
5437       }
5438     }
5439 
5440     // Check whether we need to rebuild the type of the given
5441     // declaration in the current instantiation.
5442     if (EnteringContext && IsDependentContext &&
5443         TemplateParamLists.size() != 0) {
5444       ContextRAII SavedContext(*this, DC);
5445       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5446         D.setInvalidType();
5447     }
5448   }
5449 
5450   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5451   QualType R = TInfo->getType();
5452 
5453   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5454                                       UPPC_DeclarationType))
5455     D.setInvalidType();
5456 
5457   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5458                         forRedeclarationInCurContext());
5459 
5460   // See if this is a redefinition of a variable in the same scope.
5461   if (!D.getCXXScopeSpec().isSet()) {
5462     bool IsLinkageLookup = false;
5463     bool CreateBuiltins = false;
5464 
5465     // If the declaration we're planning to build will be a function
5466     // or object with linkage, then look for another declaration with
5467     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5468     //
5469     // If the declaration we're planning to build will be declared with
5470     // external linkage in the translation unit, create any builtin with
5471     // the same name.
5472     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5473       /* Do nothing*/;
5474     else if (CurContext->isFunctionOrMethod() &&
5475              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5476               R->isFunctionType())) {
5477       IsLinkageLookup = true;
5478       CreateBuiltins =
5479           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5480     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5481                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5482       CreateBuiltins = true;
5483 
5484     if (IsLinkageLookup) {
5485       Previous.clear(LookupRedeclarationWithLinkage);
5486       Previous.setRedeclarationKind(ForExternalRedeclaration);
5487     }
5488 
5489     LookupName(Previous, S, CreateBuiltins);
5490   } else { // Something like "int foo::x;"
5491     LookupQualifiedName(Previous, DC);
5492 
5493     // C++ [dcl.meaning]p1:
5494     //   When the declarator-id is qualified, the declaration shall refer to a
5495     //  previously declared member of the class or namespace to which the
5496     //  qualifier refers (or, in the case of a namespace, of an element of the
5497     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5498     //  thereof; [...]
5499     //
5500     // Note that we already checked the context above, and that we do not have
5501     // enough information to make sure that Previous contains the declaration
5502     // we want to match. For example, given:
5503     //
5504     //   class X {
5505     //     void f();
5506     //     void f(float);
5507     //   };
5508     //
5509     //   void X::f(int) { } // ill-formed
5510     //
5511     // In this case, Previous will point to the overload set
5512     // containing the two f's declared in X, but neither of them
5513     // matches.
5514 
5515     // C++ [dcl.meaning]p1:
5516     //   [...] the member shall not merely have been introduced by a
5517     //   using-declaration in the scope of the class or namespace nominated by
5518     //   the nested-name-specifier of the declarator-id.
5519     RemoveUsingDecls(Previous);
5520   }
5521 
5522   if (Previous.isSingleResult() &&
5523       Previous.getFoundDecl()->isTemplateParameter()) {
5524     // Maybe we will complain about the shadowed template parameter.
5525     if (!D.isInvalidType())
5526       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5527                                       Previous.getFoundDecl());
5528 
5529     // Just pretend that we didn't see the previous declaration.
5530     Previous.clear();
5531   }
5532 
5533   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5534     // Forget that the previous declaration is the injected-class-name.
5535     Previous.clear();
5536 
5537   // In C++, the previous declaration we find might be a tag type
5538   // (class or enum). In this case, the new declaration will hide the
5539   // tag type. Note that this applies to functions, function templates, and
5540   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5541   if (Previous.isSingleTagDecl() &&
5542       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5543       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5544     Previous.clear();
5545 
5546   // Check that there are no default arguments other than in the parameters
5547   // of a function declaration (C++ only).
5548   if (getLangOpts().CPlusPlus)
5549     CheckExtraCXXDefaultArguments(D);
5550 
5551   NamedDecl *New;
5552 
5553   bool AddToScope = true;
5554   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5555     if (TemplateParamLists.size()) {
5556       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5557       return nullptr;
5558     }
5559 
5560     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5561   } else if (R->isFunctionType()) {
5562     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5563                                   TemplateParamLists,
5564                                   AddToScope);
5565   } else {
5566     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5567                                   AddToScope);
5568   }
5569 
5570   if (!New)
5571     return nullptr;
5572 
5573   // If this has an identifier and is not a function template specialization,
5574   // add it to the scope stack.
5575   if (New->getDeclName() && AddToScope)
5576     PushOnScopeChains(New, S);
5577 
5578   if (isInOpenMPDeclareTargetContext())
5579     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5580 
5581   return New;
5582 }
5583 
5584 /// Helper method to turn variable array types into constant array
5585 /// types in certain situations which would otherwise be errors (for
5586 /// GCC compatibility).
5587 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5588                                                     ASTContext &Context,
5589                                                     bool &SizeIsNegative,
5590                                                     llvm::APSInt &Oversized) {
5591   // This method tries to turn a variable array into a constant
5592   // array even when the size isn't an ICE.  This is necessary
5593   // for compatibility with code that depends on gcc's buggy
5594   // constant expression folding, like struct {char x[(int)(char*)2];}
5595   SizeIsNegative = false;
5596   Oversized = 0;
5597 
5598   if (T->isDependentType())
5599     return QualType();
5600 
5601   QualifierCollector Qs;
5602   const Type *Ty = Qs.strip(T);
5603 
5604   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5605     QualType Pointee = PTy->getPointeeType();
5606     QualType FixedType =
5607         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5608                                             Oversized);
5609     if (FixedType.isNull()) return FixedType;
5610     FixedType = Context.getPointerType(FixedType);
5611     return Qs.apply(Context, FixedType);
5612   }
5613   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5614     QualType Inner = PTy->getInnerType();
5615     QualType FixedType =
5616         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5617                                             Oversized);
5618     if (FixedType.isNull()) return FixedType;
5619     FixedType = Context.getParenType(FixedType);
5620     return Qs.apply(Context, FixedType);
5621   }
5622 
5623   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5624   if (!VLATy)
5625     return QualType();
5626   // FIXME: We should probably handle this case
5627   if (VLATy->getElementType()->isVariablyModifiedType())
5628     return QualType();
5629 
5630   Expr::EvalResult Result;
5631   if (!VLATy->getSizeExpr() ||
5632       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5633     return QualType();
5634 
5635   llvm::APSInt Res = Result.Val.getInt();
5636 
5637   // Check whether the array size is negative.
5638   if (Res.isSigned() && Res.isNegative()) {
5639     SizeIsNegative = true;
5640     return QualType();
5641   }
5642 
5643   // Check whether the array is too large to be addressed.
5644   unsigned ActiveSizeBits
5645     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5646                                               Res);
5647   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5648     Oversized = Res;
5649     return QualType();
5650   }
5651 
5652   return Context.getConstantArrayType(VLATy->getElementType(),
5653                                       Res, ArrayType::Normal, 0);
5654 }
5655 
5656 static void
5657 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5658   SrcTL = SrcTL.getUnqualifiedLoc();
5659   DstTL = DstTL.getUnqualifiedLoc();
5660   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5661     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5662     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5663                                       DstPTL.getPointeeLoc());
5664     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5665     return;
5666   }
5667   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5668     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5669     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5670                                       DstPTL.getInnerLoc());
5671     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5672     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5673     return;
5674   }
5675   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5676   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5677   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5678   TypeLoc DstElemTL = DstATL.getElementLoc();
5679   DstElemTL.initializeFullCopy(SrcElemTL);
5680   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5681   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5682   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5683 }
5684 
5685 /// Helper method to turn variable array types into constant array
5686 /// types in certain situations which would otherwise be errors (for
5687 /// GCC compatibility).
5688 static TypeSourceInfo*
5689 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5690                                               ASTContext &Context,
5691                                               bool &SizeIsNegative,
5692                                               llvm::APSInt &Oversized) {
5693   QualType FixedTy
5694     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5695                                           SizeIsNegative, Oversized);
5696   if (FixedTy.isNull())
5697     return nullptr;
5698   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5699   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5700                                     FixedTInfo->getTypeLoc());
5701   return FixedTInfo;
5702 }
5703 
5704 /// Register the given locally-scoped extern "C" declaration so
5705 /// that it can be found later for redeclarations. We include any extern "C"
5706 /// declaration that is not visible in the translation unit here, not just
5707 /// function-scope declarations.
5708 void
5709 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5710   if (!getLangOpts().CPlusPlus &&
5711       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5712     // Don't need to track declarations in the TU in C.
5713     return;
5714 
5715   // Note that we have a locally-scoped external with this name.
5716   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5717 }
5718 
5719 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5720   // FIXME: We can have multiple results via __attribute__((overloadable)).
5721   auto Result = Context.getExternCContextDecl()->lookup(Name);
5722   return Result.empty() ? nullptr : *Result.begin();
5723 }
5724 
5725 /// Diagnose function specifiers on a declaration of an identifier that
5726 /// does not identify a function.
5727 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5728   // FIXME: We should probably indicate the identifier in question to avoid
5729   // confusion for constructs like "virtual int a(), b;"
5730   if (DS.isVirtualSpecified())
5731     Diag(DS.getVirtualSpecLoc(),
5732          diag::err_virtual_non_function);
5733 
5734   if (DS.hasExplicitSpecifier())
5735     Diag(DS.getExplicitSpecLoc(),
5736          diag::err_explicit_non_function);
5737 
5738   if (DS.isNoreturnSpecified())
5739     Diag(DS.getNoreturnSpecLoc(),
5740          diag::err_noreturn_non_function);
5741 }
5742 
5743 NamedDecl*
5744 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5745                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5746   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5747   if (D.getCXXScopeSpec().isSet()) {
5748     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5749       << D.getCXXScopeSpec().getRange();
5750     D.setInvalidType();
5751     // Pretend we didn't see the scope specifier.
5752     DC = CurContext;
5753     Previous.clear();
5754   }
5755 
5756   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5757 
5758   if (D.getDeclSpec().isInlineSpecified())
5759     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5760         << getLangOpts().CPlusPlus17;
5761   if (D.getDeclSpec().hasConstexprSpecifier())
5762     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5763         << 1 << (D.getDeclSpec().getConstexprSpecifier() == CSK_consteval);
5764 
5765   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
5766     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
5767       Diag(D.getName().StartLocation,
5768            diag::err_deduction_guide_invalid_specifier)
5769           << "typedef";
5770     else
5771       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5772           << D.getName().getSourceRange();
5773     return nullptr;
5774   }
5775 
5776   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5777   if (!NewTD) return nullptr;
5778 
5779   // Handle attributes prior to checking for duplicates in MergeVarDecl
5780   ProcessDeclAttributes(S, NewTD, D);
5781 
5782   CheckTypedefForVariablyModifiedType(S, NewTD);
5783 
5784   bool Redeclaration = D.isRedeclaration();
5785   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5786   D.setRedeclaration(Redeclaration);
5787   return ND;
5788 }
5789 
5790 void
5791 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5792   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5793   // then it shall have block scope.
5794   // Note that variably modified types must be fixed before merging the decl so
5795   // that redeclarations will match.
5796   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5797   QualType T = TInfo->getType();
5798   if (T->isVariablyModifiedType()) {
5799     setFunctionHasBranchProtectedScope();
5800 
5801     if (S->getFnParent() == nullptr) {
5802       bool SizeIsNegative;
5803       llvm::APSInt Oversized;
5804       TypeSourceInfo *FixedTInfo =
5805         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5806                                                       SizeIsNegative,
5807                                                       Oversized);
5808       if (FixedTInfo) {
5809         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5810         NewTD->setTypeSourceInfo(FixedTInfo);
5811       } else {
5812         if (SizeIsNegative)
5813           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5814         else if (T->isVariableArrayType())
5815           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5816         else if (Oversized.getBoolValue())
5817           Diag(NewTD->getLocation(), diag::err_array_too_large)
5818             << Oversized.toString(10);
5819         else
5820           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5821         NewTD->setInvalidDecl();
5822       }
5823     }
5824   }
5825 }
5826 
5827 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5828 /// declares a typedef-name, either using the 'typedef' type specifier or via
5829 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5830 NamedDecl*
5831 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5832                            LookupResult &Previous, bool &Redeclaration) {
5833 
5834   // Find the shadowed declaration before filtering for scope.
5835   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5836 
5837   // Merge the decl with the existing one if appropriate. If the decl is
5838   // in an outer scope, it isn't the same thing.
5839   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5840                        /*AllowInlineNamespace*/false);
5841   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5842   if (!Previous.empty()) {
5843     Redeclaration = true;
5844     MergeTypedefNameDecl(S, NewTD, Previous);
5845   }
5846 
5847   if (ShadowedDecl && !Redeclaration)
5848     CheckShadow(NewTD, ShadowedDecl, Previous);
5849 
5850   // If this is the C FILE type, notify the AST context.
5851   if (IdentifierInfo *II = NewTD->getIdentifier())
5852     if (!NewTD->isInvalidDecl() &&
5853         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5854       if (II->isStr("FILE"))
5855         Context.setFILEDecl(NewTD);
5856       else if (II->isStr("jmp_buf"))
5857         Context.setjmp_bufDecl(NewTD);
5858       else if (II->isStr("sigjmp_buf"))
5859         Context.setsigjmp_bufDecl(NewTD);
5860       else if (II->isStr("ucontext_t"))
5861         Context.setucontext_tDecl(NewTD);
5862     }
5863 
5864   return NewTD;
5865 }
5866 
5867 /// Determines whether the given declaration is an out-of-scope
5868 /// previous declaration.
5869 ///
5870 /// This routine should be invoked when name lookup has found a
5871 /// previous declaration (PrevDecl) that is not in the scope where a
5872 /// new declaration by the same name is being introduced. If the new
5873 /// declaration occurs in a local scope, previous declarations with
5874 /// linkage may still be considered previous declarations (C99
5875 /// 6.2.2p4-5, C++ [basic.link]p6).
5876 ///
5877 /// \param PrevDecl the previous declaration found by name
5878 /// lookup
5879 ///
5880 /// \param DC the context in which the new declaration is being
5881 /// declared.
5882 ///
5883 /// \returns true if PrevDecl is an out-of-scope previous declaration
5884 /// for a new delcaration with the same name.
5885 static bool
5886 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5887                                 ASTContext &Context) {
5888   if (!PrevDecl)
5889     return false;
5890 
5891   if (!PrevDecl->hasLinkage())
5892     return false;
5893 
5894   if (Context.getLangOpts().CPlusPlus) {
5895     // C++ [basic.link]p6:
5896     //   If there is a visible declaration of an entity with linkage
5897     //   having the same name and type, ignoring entities declared
5898     //   outside the innermost enclosing namespace scope, the block
5899     //   scope declaration declares that same entity and receives the
5900     //   linkage of the previous declaration.
5901     DeclContext *OuterContext = DC->getRedeclContext();
5902     if (!OuterContext->isFunctionOrMethod())
5903       // This rule only applies to block-scope declarations.
5904       return false;
5905 
5906     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5907     if (PrevOuterContext->isRecord())
5908       // We found a member function: ignore it.
5909       return false;
5910 
5911     // Find the innermost enclosing namespace for the new and
5912     // previous declarations.
5913     OuterContext = OuterContext->getEnclosingNamespaceContext();
5914     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5915 
5916     // The previous declaration is in a different namespace, so it
5917     // isn't the same function.
5918     if (!OuterContext->Equals(PrevOuterContext))
5919       return false;
5920   }
5921 
5922   return true;
5923 }
5924 
5925 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
5926   CXXScopeSpec &SS = D.getCXXScopeSpec();
5927   if (!SS.isSet()) return;
5928   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
5929 }
5930 
5931 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5932   QualType type = decl->getType();
5933   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5934   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5935     // Various kinds of declaration aren't allowed to be __autoreleasing.
5936     unsigned kind = -1U;
5937     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5938       if (var->hasAttr<BlocksAttr>())
5939         kind = 0; // __block
5940       else if (!var->hasLocalStorage())
5941         kind = 1; // global
5942     } else if (isa<ObjCIvarDecl>(decl)) {
5943       kind = 3; // ivar
5944     } else if (isa<FieldDecl>(decl)) {
5945       kind = 2; // field
5946     }
5947 
5948     if (kind != -1U) {
5949       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5950         << kind;
5951     }
5952   } else if (lifetime == Qualifiers::OCL_None) {
5953     // Try to infer lifetime.
5954     if (!type->isObjCLifetimeType())
5955       return false;
5956 
5957     lifetime = type->getObjCARCImplicitLifetime();
5958     type = Context.getLifetimeQualifiedType(type, lifetime);
5959     decl->setType(type);
5960   }
5961 
5962   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5963     // Thread-local variables cannot have lifetime.
5964     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5965         var->getTLSKind()) {
5966       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5967         << var->getType();
5968       return true;
5969     }
5970   }
5971 
5972   return false;
5973 }
5974 
5975 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5976   // Ensure that an auto decl is deduced otherwise the checks below might cache
5977   // the wrong linkage.
5978   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5979 
5980   // 'weak' only applies to declarations with external linkage.
5981   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5982     if (!ND.isExternallyVisible()) {
5983       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5984       ND.dropAttr<WeakAttr>();
5985     }
5986   }
5987   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5988     if (ND.isExternallyVisible()) {
5989       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5990       ND.dropAttr<WeakRefAttr>();
5991       ND.dropAttr<AliasAttr>();
5992     }
5993   }
5994 
5995   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5996     if (VD->hasInit()) {
5997       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5998         assert(VD->isThisDeclarationADefinition() &&
5999                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6000         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6001         VD->dropAttr<AliasAttr>();
6002       }
6003     }
6004   }
6005 
6006   // 'selectany' only applies to externally visible variable declarations.
6007   // It does not apply to functions.
6008   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6009     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6010       S.Diag(Attr->getLocation(),
6011              diag::err_attribute_selectany_non_extern_data);
6012       ND.dropAttr<SelectAnyAttr>();
6013     }
6014   }
6015 
6016   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6017     auto *VD = dyn_cast<VarDecl>(&ND);
6018     bool IsAnonymousNS = false;
6019     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6020     if (VD) {
6021       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6022       while (NS && !IsAnonymousNS) {
6023         IsAnonymousNS = NS->isAnonymousNamespace();
6024         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6025       }
6026     }
6027     // dll attributes require external linkage. Static locals may have external
6028     // linkage but still cannot be explicitly imported or exported.
6029     // In Microsoft mode, a variable defined in anonymous namespace must have
6030     // external linkage in order to be exported.
6031     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6032     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6033         (!AnonNSInMicrosoftMode &&
6034          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6035       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6036         << &ND << Attr;
6037       ND.setInvalidDecl();
6038     }
6039   }
6040 
6041   // Virtual functions cannot be marked as 'notail'.
6042   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
6043     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
6044       if (MD->isVirtual()) {
6045         S.Diag(ND.getLocation(),
6046                diag::err_invalid_attribute_on_virtual_function)
6047             << Attr;
6048         ND.dropAttr<NotTailCalledAttr>();
6049       }
6050 
6051   // Check the attributes on the function type, if any.
6052   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6053     // Don't declare this variable in the second operand of the for-statement;
6054     // GCC miscompiles that by ending its lifetime before evaluating the
6055     // third operand. See gcc.gnu.org/PR86769.
6056     AttributedTypeLoc ATL;
6057     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6058          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6059          TL = ATL.getModifiedLoc()) {
6060       // The [[lifetimebound]] attribute can be applied to the implicit object
6061       // parameter of a non-static member function (other than a ctor or dtor)
6062       // by applying it to the function type.
6063       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6064         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6065         if (!MD || MD->isStatic()) {
6066           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6067               << !MD << A->getRange();
6068         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6069           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6070               << isa<CXXDestructorDecl>(MD) << A->getRange();
6071         }
6072       }
6073     }
6074   }
6075 }
6076 
6077 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6078                                            NamedDecl *NewDecl,
6079                                            bool IsSpecialization,
6080                                            bool IsDefinition) {
6081   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6082     return;
6083 
6084   bool IsTemplate = false;
6085   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6086     OldDecl = OldTD->getTemplatedDecl();
6087     IsTemplate = true;
6088     if (!IsSpecialization)
6089       IsDefinition = false;
6090   }
6091   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6092     NewDecl = NewTD->getTemplatedDecl();
6093     IsTemplate = true;
6094   }
6095 
6096   if (!OldDecl || !NewDecl)
6097     return;
6098 
6099   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6100   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6101   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6102   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6103 
6104   // dllimport and dllexport are inheritable attributes so we have to exclude
6105   // inherited attribute instances.
6106   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6107                     (NewExportAttr && !NewExportAttr->isInherited());
6108 
6109   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6110   // the only exception being explicit specializations.
6111   // Implicitly generated declarations are also excluded for now because there
6112   // is no other way to switch these to use dllimport or dllexport.
6113   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6114 
6115   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6116     // Allow with a warning for free functions and global variables.
6117     bool JustWarn = false;
6118     if (!OldDecl->isCXXClassMember()) {
6119       auto *VD = dyn_cast<VarDecl>(OldDecl);
6120       if (VD && !VD->getDescribedVarTemplate())
6121         JustWarn = true;
6122       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6123       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6124         JustWarn = true;
6125     }
6126 
6127     // We cannot change a declaration that's been used because IR has already
6128     // been emitted. Dllimported functions will still work though (modulo
6129     // address equality) as they can use the thunk.
6130     if (OldDecl->isUsed())
6131       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6132         JustWarn = false;
6133 
6134     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6135                                : diag::err_attribute_dll_redeclaration;
6136     S.Diag(NewDecl->getLocation(), DiagID)
6137         << NewDecl
6138         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6139     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6140     if (!JustWarn) {
6141       NewDecl->setInvalidDecl();
6142       return;
6143     }
6144   }
6145 
6146   // A redeclaration is not allowed to drop a dllimport attribute, the only
6147   // exceptions being inline function definitions (except for function
6148   // templates), local extern declarations, qualified friend declarations or
6149   // special MSVC extension: in the last case, the declaration is treated as if
6150   // it were marked dllexport.
6151   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6152   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6153   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6154     // Ignore static data because out-of-line definitions are diagnosed
6155     // separately.
6156     IsStaticDataMember = VD->isStaticDataMember();
6157     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6158                    VarDecl::DeclarationOnly;
6159   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6160     IsInline = FD->isInlined();
6161     IsQualifiedFriend = FD->getQualifier() &&
6162                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6163   }
6164 
6165   if (OldImportAttr && !HasNewAttr &&
6166       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6167       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6168     if (IsMicrosoft && IsDefinition) {
6169       S.Diag(NewDecl->getLocation(),
6170              diag::warn_redeclaration_without_import_attribute)
6171           << NewDecl;
6172       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6173       NewDecl->dropAttr<DLLImportAttr>();
6174       NewDecl->addAttr(::new (S.Context) DLLExportAttr(
6175           NewImportAttr->getRange(), S.Context,
6176           NewImportAttr->getSpellingListIndex()));
6177     } else {
6178       S.Diag(NewDecl->getLocation(),
6179              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6180           << NewDecl << OldImportAttr;
6181       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6182       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6183       OldDecl->dropAttr<DLLImportAttr>();
6184       NewDecl->dropAttr<DLLImportAttr>();
6185     }
6186   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6187     // In MinGW, seeing a function declared inline drops the dllimport
6188     // attribute.
6189     OldDecl->dropAttr<DLLImportAttr>();
6190     NewDecl->dropAttr<DLLImportAttr>();
6191     S.Diag(NewDecl->getLocation(),
6192            diag::warn_dllimport_dropped_from_inline_function)
6193         << NewDecl << OldImportAttr;
6194   }
6195 
6196   // A specialization of a class template member function is processed here
6197   // since it's a redeclaration. If the parent class is dllexport, the
6198   // specialization inherits that attribute. This doesn't happen automatically
6199   // since the parent class isn't instantiated until later.
6200   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6201     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6202         !NewImportAttr && !NewExportAttr) {
6203       if (const DLLExportAttr *ParentExportAttr =
6204               MD->getParent()->getAttr<DLLExportAttr>()) {
6205         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6206         NewAttr->setInherited(true);
6207         NewDecl->addAttr(NewAttr);
6208       }
6209     }
6210   }
6211 }
6212 
6213 /// Given that we are within the definition of the given function,
6214 /// will that definition behave like C99's 'inline', where the
6215 /// definition is discarded except for optimization purposes?
6216 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6217   // Try to avoid calling GetGVALinkageForFunction.
6218 
6219   // All cases of this require the 'inline' keyword.
6220   if (!FD->isInlined()) return false;
6221 
6222   // This is only possible in C++ with the gnu_inline attribute.
6223   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6224     return false;
6225 
6226   // Okay, go ahead and call the relatively-more-expensive function.
6227   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6228 }
6229 
6230 /// Determine whether a variable is extern "C" prior to attaching
6231 /// an initializer. We can't just call isExternC() here, because that
6232 /// will also compute and cache whether the declaration is externally
6233 /// visible, which might change when we attach the initializer.
6234 ///
6235 /// This can only be used if the declaration is known to not be a
6236 /// redeclaration of an internal linkage declaration.
6237 ///
6238 /// For instance:
6239 ///
6240 ///   auto x = []{};
6241 ///
6242 /// Attaching the initializer here makes this declaration not externally
6243 /// visible, because its type has internal linkage.
6244 ///
6245 /// FIXME: This is a hack.
6246 template<typename T>
6247 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6248   if (S.getLangOpts().CPlusPlus) {
6249     // In C++, the overloadable attribute negates the effects of extern "C".
6250     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6251       return false;
6252 
6253     // So do CUDA's host/device attributes.
6254     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6255                                  D->template hasAttr<CUDAHostAttr>()))
6256       return false;
6257   }
6258   return D->isExternC();
6259 }
6260 
6261 static bool shouldConsiderLinkage(const VarDecl *VD) {
6262   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6263   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6264       isa<OMPDeclareMapperDecl>(DC))
6265     return VD->hasExternalStorage();
6266   if (DC->isFileContext())
6267     return true;
6268   if (DC->isRecord())
6269     return false;
6270   llvm_unreachable("Unexpected context");
6271 }
6272 
6273 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6274   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6275   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6276       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6277     return true;
6278   if (DC->isRecord())
6279     return false;
6280   llvm_unreachable("Unexpected context");
6281 }
6282 
6283 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6284                           ParsedAttr::Kind Kind) {
6285   // Check decl attributes on the DeclSpec.
6286   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6287     return true;
6288 
6289   // Walk the declarator structure, checking decl attributes that were in a type
6290   // position to the decl itself.
6291   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6292     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6293       return true;
6294   }
6295 
6296   // Finally, check attributes on the decl itself.
6297   return PD.getAttributes().hasAttribute(Kind);
6298 }
6299 
6300 /// Adjust the \c DeclContext for a function or variable that might be a
6301 /// function-local external declaration.
6302 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6303   if (!DC->isFunctionOrMethod())
6304     return false;
6305 
6306   // If this is a local extern function or variable declared within a function
6307   // template, don't add it into the enclosing namespace scope until it is
6308   // instantiated; it might have a dependent type right now.
6309   if (DC->isDependentContext())
6310     return true;
6311 
6312   // C++11 [basic.link]p7:
6313   //   When a block scope declaration of an entity with linkage is not found to
6314   //   refer to some other declaration, then that entity is a member of the
6315   //   innermost enclosing namespace.
6316   //
6317   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6318   // semantically-enclosing namespace, not a lexically-enclosing one.
6319   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6320     DC = DC->getParent();
6321   return true;
6322 }
6323 
6324 /// Returns true if given declaration has external C language linkage.
6325 static bool isDeclExternC(const Decl *D) {
6326   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6327     return FD->isExternC();
6328   if (const auto *VD = dyn_cast<VarDecl>(D))
6329     return VD->isExternC();
6330 
6331   llvm_unreachable("Unknown type of decl!");
6332 }
6333 
6334 NamedDecl *Sema::ActOnVariableDeclarator(
6335     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6336     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6337     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6338   QualType R = TInfo->getType();
6339   DeclarationName Name = GetNameForDeclarator(D).getName();
6340 
6341   IdentifierInfo *II = Name.getAsIdentifierInfo();
6342 
6343   if (D.isDecompositionDeclarator()) {
6344     // Take the name of the first declarator as our name for diagnostic
6345     // purposes.
6346     auto &Decomp = D.getDecompositionDeclarator();
6347     if (!Decomp.bindings().empty()) {
6348       II = Decomp.bindings()[0].Name;
6349       Name = II;
6350     }
6351   } else if (!II) {
6352     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6353     return nullptr;
6354   }
6355 
6356   if (getLangOpts().OpenCL) {
6357     // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6358     // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6359     // argument.
6360     if (R->isImageType() || R->isPipeType()) {
6361       Diag(D.getIdentifierLoc(),
6362            diag::err_opencl_type_can_only_be_used_as_function_parameter)
6363           << R;
6364       D.setInvalidType();
6365       return nullptr;
6366     }
6367 
6368     // OpenCL v1.2 s6.9.r:
6369     // The event type cannot be used to declare a program scope variable.
6370     // OpenCL v2.0 s6.9.q:
6371     // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6372     if (NULL == S->getParent()) {
6373       if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6374         Diag(D.getIdentifierLoc(),
6375              diag::err_invalid_type_for_program_scope_var) << R;
6376         D.setInvalidType();
6377         return nullptr;
6378       }
6379     }
6380 
6381     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6382     QualType NR = R;
6383     while (NR->isPointerType()) {
6384       if (NR->isFunctionPointerType()) {
6385         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6386         D.setInvalidType();
6387         break;
6388       }
6389       NR = NR->getPointeeType();
6390     }
6391 
6392     if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6393       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6394       // half array type (unless the cl_khr_fp16 extension is enabled).
6395       if (Context.getBaseElementType(R)->isHalfType()) {
6396         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6397         D.setInvalidType();
6398       }
6399     }
6400 
6401     if (R->isSamplerT()) {
6402       // OpenCL v1.2 s6.9.b p4:
6403       // The sampler type cannot be used with the __local and __global address
6404       // space qualifiers.
6405       if (R.getAddressSpace() == LangAS::opencl_local ||
6406           R.getAddressSpace() == LangAS::opencl_global) {
6407         Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6408       }
6409 
6410       // OpenCL v1.2 s6.12.14.1:
6411       // A global sampler must be declared with either the constant address
6412       // space qualifier or with the const qualifier.
6413       if (DC->isTranslationUnit() &&
6414           !(R.getAddressSpace() == LangAS::opencl_constant ||
6415           R.isConstQualified())) {
6416         Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6417         D.setInvalidType();
6418       }
6419     }
6420 
6421     // OpenCL v1.2 s6.9.r:
6422     // The event type cannot be used with the __local, __constant and __global
6423     // address space qualifiers.
6424     if (R->isEventT()) {
6425       if (R.getAddressSpace() != LangAS::opencl_private) {
6426         Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6427         D.setInvalidType();
6428       }
6429     }
6430 
6431     // C++ for OpenCL does not allow the thread_local storage qualifier.
6432     // OpenCL C does not support thread_local either, and
6433     // also reject all other thread storage class specifiers.
6434     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6435     if (TSC != TSCS_unspecified) {
6436       bool IsCXX = getLangOpts().OpenCLCPlusPlus;
6437       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6438            diag::err_opencl_unknown_type_specifier)
6439           << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString()
6440           << DeclSpec::getSpecifierName(TSC) << 1;
6441       D.setInvalidType();
6442       return nullptr;
6443     }
6444   }
6445 
6446   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6447   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6448 
6449   // dllimport globals without explicit storage class are treated as extern. We
6450   // have to change the storage class this early to get the right DeclContext.
6451   if (SC == SC_None && !DC->isRecord() &&
6452       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6453       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6454     SC = SC_Extern;
6455 
6456   DeclContext *OriginalDC = DC;
6457   bool IsLocalExternDecl = SC == SC_Extern &&
6458                            adjustContextForLocalExternDecl(DC);
6459 
6460   if (SCSpec == DeclSpec::SCS_mutable) {
6461     // mutable can only appear on non-static class members, so it's always
6462     // an error here
6463     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6464     D.setInvalidType();
6465     SC = SC_None;
6466   }
6467 
6468   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6469       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6470                               D.getDeclSpec().getStorageClassSpecLoc())) {
6471     // In C++11, the 'register' storage class specifier is deprecated.
6472     // Suppress the warning in system macros, it's used in macros in some
6473     // popular C system headers, such as in glibc's htonl() macro.
6474     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6475          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6476                                    : diag::warn_deprecated_register)
6477       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6478   }
6479 
6480   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6481 
6482   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6483     // C99 6.9p2: The storage-class specifiers auto and register shall not
6484     // appear in the declaration specifiers in an external declaration.
6485     // Global Register+Asm is a GNU extension we support.
6486     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6487       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6488       D.setInvalidType();
6489     }
6490   }
6491 
6492   bool IsMemberSpecialization = false;
6493   bool IsVariableTemplateSpecialization = false;
6494   bool IsPartialSpecialization = false;
6495   bool IsVariableTemplate = false;
6496   VarDecl *NewVD = nullptr;
6497   VarTemplateDecl *NewTemplate = nullptr;
6498   TemplateParameterList *TemplateParams = nullptr;
6499   if (!getLangOpts().CPlusPlus) {
6500     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6501                             II, R, TInfo, SC);
6502 
6503     if (R->getContainedDeducedType())
6504       ParsingInitForAutoVars.insert(NewVD);
6505 
6506     if (D.isInvalidType())
6507       NewVD->setInvalidDecl();
6508 
6509     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
6510         NewVD->hasLocalStorage())
6511       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
6512                             NTCUC_AutoVar, NTCUK_Destruct);
6513   } else {
6514     bool Invalid = false;
6515 
6516     if (DC->isRecord() && !CurContext->isRecord()) {
6517       // This is an out-of-line definition of a static data member.
6518       switch (SC) {
6519       case SC_None:
6520         break;
6521       case SC_Static:
6522         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6523              diag::err_static_out_of_line)
6524           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6525         break;
6526       case SC_Auto:
6527       case SC_Register:
6528       case SC_Extern:
6529         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6530         // to names of variables declared in a block or to function parameters.
6531         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6532         // of class members
6533 
6534         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6535              diag::err_storage_class_for_static_member)
6536           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6537         break;
6538       case SC_PrivateExtern:
6539         llvm_unreachable("C storage class in c++!");
6540       }
6541     }
6542 
6543     if (SC == SC_Static && CurContext->isRecord()) {
6544       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6545         if (RD->isLocalClass())
6546           Diag(D.getIdentifierLoc(),
6547                diag::err_static_data_member_not_allowed_in_local_class)
6548             << Name << RD->getDeclName();
6549 
6550         // C++98 [class.union]p1: If a union contains a static data member,
6551         // the program is ill-formed. C++11 drops this restriction.
6552         if (RD->isUnion())
6553           Diag(D.getIdentifierLoc(),
6554                getLangOpts().CPlusPlus11
6555                  ? diag::warn_cxx98_compat_static_data_member_in_union
6556                  : diag::ext_static_data_member_in_union) << Name;
6557         // We conservatively disallow static data members in anonymous structs.
6558         else if (!RD->getDeclName())
6559           Diag(D.getIdentifierLoc(),
6560                diag::err_static_data_member_not_allowed_in_anon_struct)
6561             << Name << RD->isUnion();
6562       }
6563     }
6564 
6565     // Match up the template parameter lists with the scope specifier, then
6566     // determine whether we have a template or a template specialization.
6567     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6568         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6569         D.getCXXScopeSpec(),
6570         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6571             ? D.getName().TemplateId
6572             : nullptr,
6573         TemplateParamLists,
6574         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6575 
6576     if (TemplateParams) {
6577       if (!TemplateParams->size() &&
6578           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6579         // There is an extraneous 'template<>' for this variable. Complain
6580         // about it, but allow the declaration of the variable.
6581         Diag(TemplateParams->getTemplateLoc(),
6582              diag::err_template_variable_noparams)
6583           << II
6584           << SourceRange(TemplateParams->getTemplateLoc(),
6585                          TemplateParams->getRAngleLoc());
6586         TemplateParams = nullptr;
6587       } else {
6588         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6589           // This is an explicit specialization or a partial specialization.
6590           // FIXME: Check that we can declare a specialization here.
6591           IsVariableTemplateSpecialization = true;
6592           IsPartialSpecialization = TemplateParams->size() > 0;
6593         } else { // if (TemplateParams->size() > 0)
6594           // This is a template declaration.
6595           IsVariableTemplate = true;
6596 
6597           // Check that we can declare a template here.
6598           if (CheckTemplateDeclScope(S, TemplateParams))
6599             return nullptr;
6600 
6601           // Only C++1y supports variable templates (N3651).
6602           Diag(D.getIdentifierLoc(),
6603                getLangOpts().CPlusPlus14
6604                    ? diag::warn_cxx11_compat_variable_template
6605                    : diag::ext_variable_template);
6606         }
6607       }
6608     } else {
6609       assert((Invalid ||
6610               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
6611              "should have a 'template<>' for this decl");
6612     }
6613 
6614     if (IsVariableTemplateSpecialization) {
6615       SourceLocation TemplateKWLoc =
6616           TemplateParamLists.size() > 0
6617               ? TemplateParamLists[0]->getTemplateLoc()
6618               : SourceLocation();
6619       DeclResult Res = ActOnVarTemplateSpecialization(
6620           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6621           IsPartialSpecialization);
6622       if (Res.isInvalid())
6623         return nullptr;
6624       NewVD = cast<VarDecl>(Res.get());
6625       AddToScope = false;
6626     } else if (D.isDecompositionDeclarator()) {
6627       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
6628                                         D.getIdentifierLoc(), R, TInfo, SC,
6629                                         Bindings);
6630     } else
6631       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
6632                               D.getIdentifierLoc(), II, R, TInfo, SC);
6633 
6634     // If this is supposed to be a variable template, create it as such.
6635     if (IsVariableTemplate) {
6636       NewTemplate =
6637           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6638                                   TemplateParams, NewVD);
6639       NewVD->setDescribedVarTemplate(NewTemplate);
6640     }
6641 
6642     // If this decl has an auto type in need of deduction, make a note of the
6643     // Decl so we can diagnose uses of it in its own initializer.
6644     if (R->getContainedDeducedType())
6645       ParsingInitForAutoVars.insert(NewVD);
6646 
6647     if (D.isInvalidType() || Invalid) {
6648       NewVD->setInvalidDecl();
6649       if (NewTemplate)
6650         NewTemplate->setInvalidDecl();
6651     }
6652 
6653     SetNestedNameSpecifier(*this, NewVD, D);
6654 
6655     // If we have any template parameter lists that don't directly belong to
6656     // the variable (matching the scope specifier), store them.
6657     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6658     if (TemplateParamLists.size() > VDTemplateParamLists)
6659       NewVD->setTemplateParameterListsInfo(
6660           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6661 
6662     if (D.getDeclSpec().hasConstexprSpecifier()) {
6663       NewVD->setConstexpr(true);
6664       // C++1z [dcl.spec.constexpr]p1:
6665       //   A static data member declared with the constexpr specifier is
6666       //   implicitly an inline variable.
6667       if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17)
6668         NewVD->setImplicitlyInline();
6669       if (D.getDeclSpec().getConstexprSpecifier() == CSK_consteval)
6670         Diag(D.getDeclSpec().getConstexprSpecLoc(),
6671              diag::err_constexpr_wrong_decl_kind)
6672             << /*consteval*/ 1;
6673     }
6674   }
6675 
6676   if (D.getDeclSpec().isInlineSpecified()) {
6677     if (!getLangOpts().CPlusPlus) {
6678       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6679           << 0;
6680     } else if (CurContext->isFunctionOrMethod()) {
6681       // 'inline' is not allowed on block scope variable declaration.
6682       Diag(D.getDeclSpec().getInlineSpecLoc(),
6683            diag::err_inline_declaration_block_scope) << Name
6684         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6685     } else {
6686       Diag(D.getDeclSpec().getInlineSpecLoc(),
6687            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
6688                                      : diag::ext_inline_variable);
6689       NewVD->setInlineSpecified();
6690     }
6691   }
6692 
6693   // Set the lexical context. If the declarator has a C++ scope specifier, the
6694   // lexical context will be different from the semantic context.
6695   NewVD->setLexicalDeclContext(CurContext);
6696   if (NewTemplate)
6697     NewTemplate->setLexicalDeclContext(CurContext);
6698 
6699   if (IsLocalExternDecl) {
6700     if (D.isDecompositionDeclarator())
6701       for (auto *B : Bindings)
6702         B->setLocalExternDecl();
6703     else
6704       NewVD->setLocalExternDecl();
6705   }
6706 
6707   bool EmitTLSUnsupportedError = false;
6708   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6709     // C++11 [dcl.stc]p4:
6710     //   When thread_local is applied to a variable of block scope the
6711     //   storage-class-specifier static is implied if it does not appear
6712     //   explicitly.
6713     // Core issue: 'static' is not implied if the variable is declared
6714     //   'extern'.
6715     if (NewVD->hasLocalStorage() &&
6716         (SCSpec != DeclSpec::SCS_unspecified ||
6717          TSCS != DeclSpec::TSCS_thread_local ||
6718          !DC->isFunctionOrMethod()))
6719       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6720            diag::err_thread_non_global)
6721         << DeclSpec::getSpecifierName(TSCS);
6722     else if (!Context.getTargetInfo().isTLSSupported()) {
6723       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6724         // Postpone error emission until we've collected attributes required to
6725         // figure out whether it's a host or device variable and whether the
6726         // error should be ignored.
6727         EmitTLSUnsupportedError = true;
6728         // We still need to mark the variable as TLS so it shows up in AST with
6729         // proper storage class for other tools to use even if we're not going
6730         // to emit any code for it.
6731         NewVD->setTSCSpec(TSCS);
6732       } else
6733         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6734              diag::err_thread_unsupported);
6735     } else
6736       NewVD->setTSCSpec(TSCS);
6737   }
6738 
6739   // C99 6.7.4p3
6740   //   An inline definition of a function with external linkage shall
6741   //   not contain a definition of a modifiable object with static or
6742   //   thread storage duration...
6743   // We only apply this when the function is required to be defined
6744   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6745   // that a local variable with thread storage duration still has to
6746   // be marked 'static'.  Also note that it's possible to get these
6747   // semantics in C++ using __attribute__((gnu_inline)).
6748   if (SC == SC_Static && S->getFnParent() != nullptr &&
6749       !NewVD->getType().isConstQualified()) {
6750     FunctionDecl *CurFD = getCurFunctionDecl();
6751     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6752       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6753            diag::warn_static_local_in_extern_inline);
6754       MaybeSuggestAddingStaticToDecl(CurFD);
6755     }
6756   }
6757 
6758   if (D.getDeclSpec().isModulePrivateSpecified()) {
6759     if (IsVariableTemplateSpecialization)
6760       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6761           << (IsPartialSpecialization ? 1 : 0)
6762           << FixItHint::CreateRemoval(
6763                  D.getDeclSpec().getModulePrivateSpecLoc());
6764     else if (IsMemberSpecialization)
6765       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6766         << 2
6767         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6768     else if (NewVD->hasLocalStorage())
6769       Diag(NewVD->getLocation(), diag::err_module_private_local)
6770         << 0 << NewVD->getDeclName()
6771         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6772         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6773     else {
6774       NewVD->setModulePrivate();
6775       if (NewTemplate)
6776         NewTemplate->setModulePrivate();
6777       for (auto *B : Bindings)
6778         B->setModulePrivate();
6779     }
6780   }
6781 
6782   // Handle attributes prior to checking for duplicates in MergeVarDecl
6783   ProcessDeclAttributes(S, NewVD, D);
6784 
6785   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6786     if (EmitTLSUnsupportedError &&
6787         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
6788          (getLangOpts().OpenMPIsDevice &&
6789           NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
6790       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6791            diag::err_thread_unsupported);
6792     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6793     // storage [duration]."
6794     if (SC == SC_None && S->getFnParent() != nullptr &&
6795         (NewVD->hasAttr<CUDASharedAttr>() ||
6796          NewVD->hasAttr<CUDAConstantAttr>())) {
6797       NewVD->setStorageClass(SC_Static);
6798     }
6799   }
6800 
6801   // Ensure that dllimport globals without explicit storage class are treated as
6802   // extern. The storage class is set above using parsed attributes. Now we can
6803   // check the VarDecl itself.
6804   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6805          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6806          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6807 
6808   // In auto-retain/release, infer strong retension for variables of
6809   // retainable type.
6810   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6811     NewVD->setInvalidDecl();
6812 
6813   // Handle GNU asm-label extension (encoded as an attribute).
6814   if (Expr *E = (Expr*)D.getAsmLabel()) {
6815     // The parser guarantees this is a string.
6816     StringLiteral *SE = cast<StringLiteral>(E);
6817     StringRef Label = SE->getString();
6818     if (S->getFnParent() != nullptr) {
6819       switch (SC) {
6820       case SC_None:
6821       case SC_Auto:
6822         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6823         break;
6824       case SC_Register:
6825         // Local Named register
6826         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6827             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6828           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6829         break;
6830       case SC_Static:
6831       case SC_Extern:
6832       case SC_PrivateExtern:
6833         break;
6834       }
6835     } else if (SC == SC_Register) {
6836       // Global Named register
6837       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6838         const auto &TI = Context.getTargetInfo();
6839         bool HasSizeMismatch;
6840 
6841         if (!TI.isValidGCCRegisterName(Label))
6842           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6843         else if (!TI.validateGlobalRegisterVariable(Label,
6844                                                     Context.getTypeSize(R),
6845                                                     HasSizeMismatch))
6846           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6847         else if (HasSizeMismatch)
6848           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6849       }
6850 
6851       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6852         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
6853         NewVD->setInvalidDecl(true);
6854       }
6855     }
6856 
6857     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6858                                                 Context, Label, 0));
6859   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6860     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6861       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6862     if (I != ExtnameUndeclaredIdentifiers.end()) {
6863       if (isDeclExternC(NewVD)) {
6864         NewVD->addAttr(I->second);
6865         ExtnameUndeclaredIdentifiers.erase(I);
6866       } else
6867         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6868             << /*Variable*/1 << NewVD;
6869     }
6870   }
6871 
6872   // Find the shadowed declaration before filtering for scope.
6873   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6874                                 ? getShadowedDeclaration(NewVD, Previous)
6875                                 : nullptr;
6876 
6877   // Don't consider existing declarations that are in a different
6878   // scope and are out-of-semantic-context declarations (if the new
6879   // declaration has linkage).
6880   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6881                        D.getCXXScopeSpec().isNotEmpty() ||
6882                        IsMemberSpecialization ||
6883                        IsVariableTemplateSpecialization);
6884 
6885   // Check whether the previous declaration is in the same block scope. This
6886   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6887   if (getLangOpts().CPlusPlus &&
6888       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6889     NewVD->setPreviousDeclInSameBlockScope(
6890         Previous.isSingleResult() && !Previous.isShadowed() &&
6891         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6892 
6893   if (!getLangOpts().CPlusPlus) {
6894     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6895   } else {
6896     // If this is an explicit specialization of a static data member, check it.
6897     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
6898         CheckMemberSpecialization(NewVD, Previous))
6899       NewVD->setInvalidDecl();
6900 
6901     // Merge the decl with the existing one if appropriate.
6902     if (!Previous.empty()) {
6903       if (Previous.isSingleResult() &&
6904           isa<FieldDecl>(Previous.getFoundDecl()) &&
6905           D.getCXXScopeSpec().isSet()) {
6906         // The user tried to define a non-static data member
6907         // out-of-line (C++ [dcl.meaning]p1).
6908         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6909           << D.getCXXScopeSpec().getRange();
6910         Previous.clear();
6911         NewVD->setInvalidDecl();
6912       }
6913     } else if (D.getCXXScopeSpec().isSet()) {
6914       // No previous declaration in the qualifying scope.
6915       Diag(D.getIdentifierLoc(), diag::err_no_member)
6916         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6917         << D.getCXXScopeSpec().getRange();
6918       NewVD->setInvalidDecl();
6919     }
6920 
6921     if (!IsVariableTemplateSpecialization)
6922       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6923 
6924     if (NewTemplate) {
6925       VarTemplateDecl *PrevVarTemplate =
6926           NewVD->getPreviousDecl()
6927               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6928               : nullptr;
6929 
6930       // Check the template parameter list of this declaration, possibly
6931       // merging in the template parameter list from the previous variable
6932       // template declaration.
6933       if (CheckTemplateParameterList(
6934               TemplateParams,
6935               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6936                               : nullptr,
6937               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6938                DC->isDependentContext())
6939                   ? TPC_ClassTemplateMember
6940                   : TPC_VarTemplate))
6941         NewVD->setInvalidDecl();
6942 
6943       // If we are providing an explicit specialization of a static variable
6944       // template, make a note of that.
6945       if (PrevVarTemplate &&
6946           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6947         PrevVarTemplate->setMemberSpecialization();
6948     }
6949   }
6950 
6951   // Diagnose shadowed variables iff this isn't a redeclaration.
6952   if (ShadowedDecl && !D.isRedeclaration())
6953     CheckShadow(NewVD, ShadowedDecl, Previous);
6954 
6955   ProcessPragmaWeak(S, NewVD);
6956 
6957   // If this is the first declaration of an extern C variable, update
6958   // the map of such variables.
6959   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6960       isIncompleteDeclExternC(*this, NewVD))
6961     RegisterLocallyScopedExternCDecl(NewVD, S);
6962 
6963   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6964     Decl *ManglingContextDecl;
6965     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6966             NewVD->getDeclContext(), ManglingContextDecl)) {
6967       Context.setManglingNumber(
6968           NewVD, MCtx->getManglingNumber(
6969                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6970       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6971     }
6972   }
6973 
6974   // Special handling of variable named 'main'.
6975   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6976       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6977       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6978 
6979     // C++ [basic.start.main]p3
6980     // A program that declares a variable main at global scope is ill-formed.
6981     if (getLangOpts().CPlusPlus)
6982       Diag(D.getBeginLoc(), diag::err_main_global_variable);
6983 
6984     // In C, and external-linkage variable named main results in undefined
6985     // behavior.
6986     else if (NewVD->hasExternalFormalLinkage())
6987       Diag(D.getBeginLoc(), diag::warn_main_redefined);
6988   }
6989 
6990   if (D.isRedeclaration() && !Previous.empty()) {
6991     NamedDecl *Prev = Previous.getRepresentativeDecl();
6992     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
6993                                    D.isFunctionDefinition());
6994   }
6995 
6996   if (NewTemplate) {
6997     if (NewVD->isInvalidDecl())
6998       NewTemplate->setInvalidDecl();
6999     ActOnDocumentableDecl(NewTemplate);
7000     return NewTemplate;
7001   }
7002 
7003   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7004     CompleteMemberSpecialization(NewVD, Previous);
7005 
7006   return NewVD;
7007 }
7008 
7009 /// Enum describing the %select options in diag::warn_decl_shadow.
7010 enum ShadowedDeclKind {
7011   SDK_Local,
7012   SDK_Global,
7013   SDK_StaticMember,
7014   SDK_Field,
7015   SDK_Typedef,
7016   SDK_Using
7017 };
7018 
7019 /// Determine what kind of declaration we're shadowing.
7020 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7021                                                 const DeclContext *OldDC) {
7022   if (isa<TypeAliasDecl>(ShadowedDecl))
7023     return SDK_Using;
7024   else if (isa<TypedefDecl>(ShadowedDecl))
7025     return SDK_Typedef;
7026   else if (isa<RecordDecl>(OldDC))
7027     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7028 
7029   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7030 }
7031 
7032 /// Return the location of the capture if the given lambda captures the given
7033 /// variable \p VD, or an invalid source location otherwise.
7034 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7035                                          const VarDecl *VD) {
7036   for (const Capture &Capture : LSI->Captures) {
7037     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7038       return Capture.getLocation();
7039   }
7040   return SourceLocation();
7041 }
7042 
7043 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7044                                      const LookupResult &R) {
7045   // Only diagnose if we're shadowing an unambiguous field or variable.
7046   if (R.getResultKind() != LookupResult::Found)
7047     return false;
7048 
7049   // Return false if warning is ignored.
7050   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7051 }
7052 
7053 /// Return the declaration shadowed by the given variable \p D, or null
7054 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7055 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7056                                         const LookupResult &R) {
7057   if (!shouldWarnIfShadowedDecl(Diags, R))
7058     return nullptr;
7059 
7060   // Don't diagnose declarations at file scope.
7061   if (D->hasGlobalStorage())
7062     return nullptr;
7063 
7064   NamedDecl *ShadowedDecl = R.getFoundDecl();
7065   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
7066              ? ShadowedDecl
7067              : nullptr;
7068 }
7069 
7070 /// Return the declaration shadowed by the given typedef \p D, or null
7071 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7072 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7073                                         const LookupResult &R) {
7074   // Don't warn if typedef declaration is part of a class
7075   if (D->getDeclContext()->isRecord())
7076     return nullptr;
7077 
7078   if (!shouldWarnIfShadowedDecl(Diags, R))
7079     return nullptr;
7080 
7081   NamedDecl *ShadowedDecl = R.getFoundDecl();
7082   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7083 }
7084 
7085 /// Diagnose variable or built-in function shadowing.  Implements
7086 /// -Wshadow.
7087 ///
7088 /// This method is called whenever a VarDecl is added to a "useful"
7089 /// scope.
7090 ///
7091 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7092 /// \param R the lookup of the name
7093 ///
7094 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7095                        const LookupResult &R) {
7096   DeclContext *NewDC = D->getDeclContext();
7097 
7098   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7099     // Fields are not shadowed by variables in C++ static methods.
7100     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7101       if (MD->isStatic())
7102         return;
7103 
7104     // Fields shadowed by constructor parameters are a special case. Usually
7105     // the constructor initializes the field with the parameter.
7106     if (isa<CXXConstructorDecl>(NewDC))
7107       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7108         // Remember that this was shadowed so we can either warn about its
7109         // modification or its existence depending on warning settings.
7110         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7111         return;
7112       }
7113   }
7114 
7115   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7116     if (shadowedVar->isExternC()) {
7117       // For shadowing external vars, make sure that we point to the global
7118       // declaration, not a locally scoped extern declaration.
7119       for (auto I : shadowedVar->redecls())
7120         if (I->isFileVarDecl()) {
7121           ShadowedDecl = I;
7122           break;
7123         }
7124     }
7125 
7126   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7127 
7128   unsigned WarningDiag = diag::warn_decl_shadow;
7129   SourceLocation CaptureLoc;
7130   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7131       isa<CXXMethodDecl>(NewDC)) {
7132     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7133       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7134         if (RD->getLambdaCaptureDefault() == LCD_None) {
7135           // Try to avoid warnings for lambdas with an explicit capture list.
7136           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7137           // Warn only when the lambda captures the shadowed decl explicitly.
7138           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7139           if (CaptureLoc.isInvalid())
7140             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7141         } else {
7142           // Remember that this was shadowed so we can avoid the warning if the
7143           // shadowed decl isn't captured and the warning settings allow it.
7144           cast<LambdaScopeInfo>(getCurFunction())
7145               ->ShadowingDecls.push_back(
7146                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7147           return;
7148         }
7149       }
7150 
7151       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7152         // A variable can't shadow a local variable in an enclosing scope, if
7153         // they are separated by a non-capturing declaration context.
7154         for (DeclContext *ParentDC = NewDC;
7155              ParentDC && !ParentDC->Equals(OldDC);
7156              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7157           // Only block literals, captured statements, and lambda expressions
7158           // can capture; other scopes don't.
7159           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7160               !isLambdaCallOperator(ParentDC)) {
7161             return;
7162           }
7163         }
7164       }
7165     }
7166   }
7167 
7168   // Only warn about certain kinds of shadowing for class members.
7169   if (NewDC && NewDC->isRecord()) {
7170     // In particular, don't warn about shadowing non-class members.
7171     if (!OldDC->isRecord())
7172       return;
7173 
7174     // TODO: should we warn about static data members shadowing
7175     // static data members from base classes?
7176 
7177     // TODO: don't diagnose for inaccessible shadowed members.
7178     // This is hard to do perfectly because we might friend the
7179     // shadowing context, but that's just a false negative.
7180   }
7181 
7182 
7183   DeclarationName Name = R.getLookupName();
7184 
7185   // Emit warning and note.
7186   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7187     return;
7188   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7189   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7190   if (!CaptureLoc.isInvalid())
7191     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7192         << Name << /*explicitly*/ 1;
7193   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7194 }
7195 
7196 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7197 /// when these variables are captured by the lambda.
7198 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7199   for (const auto &Shadow : LSI->ShadowingDecls) {
7200     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7201     // Try to avoid the warning when the shadowed decl isn't captured.
7202     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7203     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7204     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7205                                        ? diag::warn_decl_shadow_uncaptured_local
7206                                        : diag::warn_decl_shadow)
7207         << Shadow.VD->getDeclName()
7208         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7209     if (!CaptureLoc.isInvalid())
7210       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7211           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7212     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7213   }
7214 }
7215 
7216 /// Check -Wshadow without the advantage of a previous lookup.
7217 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7218   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7219     return;
7220 
7221   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7222                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7223   LookupName(R, S);
7224   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7225     CheckShadow(D, ShadowedDecl, R);
7226 }
7227 
7228 /// Check if 'E', which is an expression that is about to be modified, refers
7229 /// to a constructor parameter that shadows a field.
7230 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7231   // Quickly ignore expressions that can't be shadowing ctor parameters.
7232   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7233     return;
7234   E = E->IgnoreParenImpCasts();
7235   auto *DRE = dyn_cast<DeclRefExpr>(E);
7236   if (!DRE)
7237     return;
7238   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7239   auto I = ShadowingDecls.find(D);
7240   if (I == ShadowingDecls.end())
7241     return;
7242   const NamedDecl *ShadowedDecl = I->second;
7243   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7244   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7245   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7246   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7247 
7248   // Avoid issuing multiple warnings about the same decl.
7249   ShadowingDecls.erase(I);
7250 }
7251 
7252 /// Check for conflict between this global or extern "C" declaration and
7253 /// previous global or extern "C" declarations. This is only used in C++.
7254 template<typename T>
7255 static bool checkGlobalOrExternCConflict(
7256     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7257   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7258   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7259 
7260   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7261     // The common case: this global doesn't conflict with any extern "C"
7262     // declaration.
7263     return false;
7264   }
7265 
7266   if (Prev) {
7267     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7268       // Both the old and new declarations have C language linkage. This is a
7269       // redeclaration.
7270       Previous.clear();
7271       Previous.addDecl(Prev);
7272       return true;
7273     }
7274 
7275     // This is a global, non-extern "C" declaration, and there is a previous
7276     // non-global extern "C" declaration. Diagnose if this is a variable
7277     // declaration.
7278     if (!isa<VarDecl>(ND))
7279       return false;
7280   } else {
7281     // The declaration is extern "C". Check for any declaration in the
7282     // translation unit which might conflict.
7283     if (IsGlobal) {
7284       // We have already performed the lookup into the translation unit.
7285       IsGlobal = false;
7286       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7287            I != E; ++I) {
7288         if (isa<VarDecl>(*I)) {
7289           Prev = *I;
7290           break;
7291         }
7292       }
7293     } else {
7294       DeclContext::lookup_result R =
7295           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7296       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7297            I != E; ++I) {
7298         if (isa<VarDecl>(*I)) {
7299           Prev = *I;
7300           break;
7301         }
7302         // FIXME: If we have any other entity with this name in global scope,
7303         // the declaration is ill-formed, but that is a defect: it breaks the
7304         // 'stat' hack, for instance. Only variables can have mangled name
7305         // clashes with extern "C" declarations, so only they deserve a
7306         // diagnostic.
7307       }
7308     }
7309 
7310     if (!Prev)
7311       return false;
7312   }
7313 
7314   // Use the first declaration's location to ensure we point at something which
7315   // is lexically inside an extern "C" linkage-spec.
7316   assert(Prev && "should have found a previous declaration to diagnose");
7317   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7318     Prev = FD->getFirstDecl();
7319   else
7320     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7321 
7322   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7323     << IsGlobal << ND;
7324   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7325     << IsGlobal;
7326   return false;
7327 }
7328 
7329 /// Apply special rules for handling extern "C" declarations. Returns \c true
7330 /// if we have found that this is a redeclaration of some prior entity.
7331 ///
7332 /// Per C++ [dcl.link]p6:
7333 ///   Two declarations [for a function or variable] with C language linkage
7334 ///   with the same name that appear in different scopes refer to the same
7335 ///   [entity]. An entity with C language linkage shall not be declared with
7336 ///   the same name as an entity in global scope.
7337 template<typename T>
7338 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7339                                                   LookupResult &Previous) {
7340   if (!S.getLangOpts().CPlusPlus) {
7341     // In C, when declaring a global variable, look for a corresponding 'extern'
7342     // variable declared in function scope. We don't need this in C++, because
7343     // we find local extern decls in the surrounding file-scope DeclContext.
7344     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7345       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7346         Previous.clear();
7347         Previous.addDecl(Prev);
7348         return true;
7349       }
7350     }
7351     return false;
7352   }
7353 
7354   // A declaration in the translation unit can conflict with an extern "C"
7355   // declaration.
7356   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7357     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7358 
7359   // An extern "C" declaration can conflict with a declaration in the
7360   // translation unit or can be a redeclaration of an extern "C" declaration
7361   // in another scope.
7362   if (isIncompleteDeclExternC(S,ND))
7363     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7364 
7365   // Neither global nor extern "C": nothing to do.
7366   return false;
7367 }
7368 
7369 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7370   // If the decl is already known invalid, don't check it.
7371   if (NewVD->isInvalidDecl())
7372     return;
7373 
7374   QualType T = NewVD->getType();
7375 
7376   // Defer checking an 'auto' type until its initializer is attached.
7377   if (T->isUndeducedType())
7378     return;
7379 
7380   if (NewVD->hasAttrs())
7381     CheckAlignasUnderalignment(NewVD);
7382 
7383   if (T->isObjCObjectType()) {
7384     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7385       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7386     T = Context.getObjCObjectPointerType(T);
7387     NewVD->setType(T);
7388   }
7389 
7390   // Emit an error if an address space was applied to decl with local storage.
7391   // This includes arrays of objects with address space qualifiers, but not
7392   // automatic variables that point to other address spaces.
7393   // ISO/IEC TR 18037 S5.1.2
7394   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7395       T.getAddressSpace() != LangAS::Default) {
7396     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7397     NewVD->setInvalidDecl();
7398     return;
7399   }
7400 
7401   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7402   // scope.
7403   if (getLangOpts().OpenCLVersion == 120 &&
7404       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7405       NewVD->isStaticLocal()) {
7406     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7407     NewVD->setInvalidDecl();
7408     return;
7409   }
7410 
7411   if (getLangOpts().OpenCL) {
7412     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7413     if (NewVD->hasAttr<BlocksAttr>()) {
7414       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7415       return;
7416     }
7417 
7418     if (T->isBlockPointerType()) {
7419       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7420       // can't use 'extern' storage class.
7421       if (!T.isConstQualified()) {
7422         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7423             << 0 /*const*/;
7424         NewVD->setInvalidDecl();
7425         return;
7426       }
7427       if (NewVD->hasExternalStorage()) {
7428         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7429         NewVD->setInvalidDecl();
7430         return;
7431       }
7432     }
7433     // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7434     // __constant address space.
7435     // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7436     // variables inside a function can also be declared in the global
7437     // address space.
7438     // C++ for OpenCL inherits rule from OpenCL C v2.0.
7439     // FIXME: Adding local AS in C++ for OpenCL might make sense.
7440     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7441         NewVD->hasExternalStorage()) {
7442       if (!T->isSamplerT() &&
7443           !(T.getAddressSpace() == LangAS::opencl_constant ||
7444             (T.getAddressSpace() == LangAS::opencl_global &&
7445              (getLangOpts().OpenCLVersion == 200 ||
7446               getLangOpts().OpenCLCPlusPlus)))) {
7447         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7448         if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7449           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7450               << Scope << "global or constant";
7451         else
7452           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7453               << Scope << "constant";
7454         NewVD->setInvalidDecl();
7455         return;
7456       }
7457     } else {
7458       if (T.getAddressSpace() == LangAS::opencl_global) {
7459         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7460             << 1 /*is any function*/ << "global";
7461         NewVD->setInvalidDecl();
7462         return;
7463       }
7464       if (T.getAddressSpace() == LangAS::opencl_constant ||
7465           T.getAddressSpace() == LangAS::opencl_local) {
7466         FunctionDecl *FD = getCurFunctionDecl();
7467         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7468         // in functions.
7469         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7470           if (T.getAddressSpace() == LangAS::opencl_constant)
7471             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7472                 << 0 /*non-kernel only*/ << "constant";
7473           else
7474             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7475                 << 0 /*non-kernel only*/ << "local";
7476           NewVD->setInvalidDecl();
7477           return;
7478         }
7479         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7480         // in the outermost scope of a kernel function.
7481         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7482           if (!getCurScope()->isFunctionScope()) {
7483             if (T.getAddressSpace() == LangAS::opencl_constant)
7484               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7485                   << "constant";
7486             else
7487               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7488                   << "local";
7489             NewVD->setInvalidDecl();
7490             return;
7491           }
7492         }
7493       } else if (T.getAddressSpace() != LangAS::opencl_private &&
7494                  // If we are parsing a template we didn't deduce an addr
7495                  // space yet.
7496                  T.getAddressSpace() != LangAS::Default) {
7497         // Do not allow other address spaces on automatic variable.
7498         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7499         NewVD->setInvalidDecl();
7500         return;
7501       }
7502     }
7503   }
7504 
7505   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7506       && !NewVD->hasAttr<BlocksAttr>()) {
7507     if (getLangOpts().getGC() != LangOptions::NonGC)
7508       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7509     else {
7510       assert(!getLangOpts().ObjCAutoRefCount);
7511       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7512     }
7513   }
7514 
7515   bool isVM = T->isVariablyModifiedType();
7516   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7517       NewVD->hasAttr<BlocksAttr>())
7518     setFunctionHasBranchProtectedScope();
7519 
7520   if ((isVM && NewVD->hasLinkage()) ||
7521       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7522     bool SizeIsNegative;
7523     llvm::APSInt Oversized;
7524     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7525         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7526     QualType FixedT;
7527     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
7528       FixedT = FixedTInfo->getType();
7529     else if (FixedTInfo) {
7530       // Type and type-as-written are canonically different. We need to fix up
7531       // both types separately.
7532       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7533                                                    Oversized);
7534     }
7535     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7536       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7537       // FIXME: This won't give the correct result for
7538       // int a[10][n];
7539       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7540 
7541       if (NewVD->isFileVarDecl())
7542         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7543         << SizeRange;
7544       else if (NewVD->isStaticLocal())
7545         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7546         << SizeRange;
7547       else
7548         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7549         << SizeRange;
7550       NewVD->setInvalidDecl();
7551       return;
7552     }
7553 
7554     if (!FixedTInfo) {
7555       if (NewVD->isFileVarDecl())
7556         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7557       else
7558         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7559       NewVD->setInvalidDecl();
7560       return;
7561     }
7562 
7563     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7564     NewVD->setType(FixedT);
7565     NewVD->setTypeSourceInfo(FixedTInfo);
7566   }
7567 
7568   if (T->isVoidType()) {
7569     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7570     //                    of objects and functions.
7571     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7572       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7573         << T;
7574       NewVD->setInvalidDecl();
7575       return;
7576     }
7577   }
7578 
7579   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7580     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7581     NewVD->setInvalidDecl();
7582     return;
7583   }
7584 
7585   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7586     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7587     NewVD->setInvalidDecl();
7588     return;
7589   }
7590 
7591   if (NewVD->isConstexpr() && !T->isDependentType() &&
7592       RequireLiteralType(NewVD->getLocation(), T,
7593                          diag::err_constexpr_var_non_literal)) {
7594     NewVD->setInvalidDecl();
7595     return;
7596   }
7597 }
7598 
7599 /// Perform semantic checking on a newly-created variable
7600 /// declaration.
7601 ///
7602 /// This routine performs all of the type-checking required for a
7603 /// variable declaration once it has been built. It is used both to
7604 /// check variables after they have been parsed and their declarators
7605 /// have been translated into a declaration, and to check variables
7606 /// that have been instantiated from a template.
7607 ///
7608 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7609 ///
7610 /// Returns true if the variable declaration is a redeclaration.
7611 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7612   CheckVariableDeclarationType(NewVD);
7613 
7614   // If the decl is already known invalid, don't check it.
7615   if (NewVD->isInvalidDecl())
7616     return false;
7617 
7618   // If we did not find anything by this name, look for a non-visible
7619   // extern "C" declaration with the same name.
7620   if (Previous.empty() &&
7621       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7622     Previous.setShadowed();
7623 
7624   if (!Previous.empty()) {
7625     MergeVarDecl(NewVD, Previous);
7626     return true;
7627   }
7628   return false;
7629 }
7630 
7631 namespace {
7632 struct FindOverriddenMethod {
7633   Sema *S;
7634   CXXMethodDecl *Method;
7635 
7636   /// Member lookup function that determines whether a given C++
7637   /// method overrides a method in a base class, to be used with
7638   /// CXXRecordDecl::lookupInBases().
7639   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7640     RecordDecl *BaseRecord =
7641         Specifier->getType()->getAs<RecordType>()->getDecl();
7642 
7643     DeclarationName Name = Method->getDeclName();
7644 
7645     // FIXME: Do we care about other names here too?
7646     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7647       // We really want to find the base class destructor here.
7648       QualType T = S->Context.getTypeDeclType(BaseRecord);
7649       CanQualType CT = S->Context.getCanonicalType(T);
7650 
7651       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7652     }
7653 
7654     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7655          Path.Decls = Path.Decls.slice(1)) {
7656       NamedDecl *D = Path.Decls.front();
7657       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7658         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7659           return true;
7660       }
7661     }
7662 
7663     return false;
7664   }
7665 };
7666 
7667 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7668 } // end anonymous namespace
7669 
7670 /// Report an error regarding overriding, along with any relevant
7671 /// overridden methods.
7672 ///
7673 /// \param DiagID the primary error to report.
7674 /// \param MD the overriding method.
7675 /// \param OEK which overrides to include as notes.
7676 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7677                             OverrideErrorKind OEK = OEK_All) {
7678   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7679   for (const CXXMethodDecl *O : MD->overridden_methods()) {
7680     // This check (& the OEK parameter) could be replaced by a predicate, but
7681     // without lambdas that would be overkill. This is still nicer than writing
7682     // out the diag loop 3 times.
7683     if ((OEK == OEK_All) ||
7684         (OEK == OEK_NonDeleted && !O->isDeleted()) ||
7685         (OEK == OEK_Deleted && O->isDeleted()))
7686       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7687   }
7688 }
7689 
7690 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7691 /// and if so, check that it's a valid override and remember it.
7692 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7693   // Look for methods in base classes that this method might override.
7694   CXXBasePaths Paths;
7695   FindOverriddenMethod FOM;
7696   FOM.Method = MD;
7697   FOM.S = this;
7698   bool hasDeletedOverridenMethods = false;
7699   bool hasNonDeletedOverridenMethods = false;
7700   bool AddedAny = false;
7701   if (DC->lookupInBases(FOM, Paths)) {
7702     for (auto *I : Paths.found_decls()) {
7703       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7704         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7705         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7706             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7707             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7708             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7709           hasDeletedOverridenMethods |= OldMD->isDeleted();
7710           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7711           AddedAny = true;
7712         }
7713       }
7714     }
7715   }
7716 
7717   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7718     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7719   }
7720   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7721     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7722   }
7723 
7724   return AddedAny;
7725 }
7726 
7727 namespace {
7728   // Struct for holding all of the extra arguments needed by
7729   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7730   struct ActOnFDArgs {
7731     Scope *S;
7732     Declarator &D;
7733     MultiTemplateParamsArg TemplateParamLists;
7734     bool AddToScope;
7735   };
7736 } // end anonymous namespace
7737 
7738 namespace {
7739 
7740 // Callback to only accept typo corrections that have a non-zero edit distance.
7741 // Also only accept corrections that have the same parent decl.
7742 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
7743  public:
7744   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7745                             CXXRecordDecl *Parent)
7746       : Context(Context), OriginalFD(TypoFD),
7747         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7748 
7749   bool ValidateCandidate(const TypoCorrection &candidate) override {
7750     if (candidate.getEditDistance() == 0)
7751       return false;
7752 
7753     SmallVector<unsigned, 1> MismatchedParams;
7754     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7755                                           CDeclEnd = candidate.end();
7756          CDecl != CDeclEnd; ++CDecl) {
7757       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7758 
7759       if (FD && !FD->hasBody() &&
7760           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7761         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7762           CXXRecordDecl *Parent = MD->getParent();
7763           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7764             return true;
7765         } else if (!ExpectedParent) {
7766           return true;
7767         }
7768       }
7769     }
7770 
7771     return false;
7772   }
7773 
7774   std::unique_ptr<CorrectionCandidateCallback> clone() override {
7775     return llvm::make_unique<DifferentNameValidatorCCC>(*this);
7776   }
7777 
7778  private:
7779   ASTContext &Context;
7780   FunctionDecl *OriginalFD;
7781   CXXRecordDecl *ExpectedParent;
7782 };
7783 
7784 } // end anonymous namespace
7785 
7786 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
7787   TypoCorrectedFunctionDefinitions.insert(F);
7788 }
7789 
7790 /// Generate diagnostics for an invalid function redeclaration.
7791 ///
7792 /// This routine handles generating the diagnostic messages for an invalid
7793 /// function redeclaration, including finding possible similar declarations
7794 /// or performing typo correction if there are no previous declarations with
7795 /// the same name.
7796 ///
7797 /// Returns a NamedDecl iff typo correction was performed and substituting in
7798 /// the new declaration name does not cause new errors.
7799 static NamedDecl *DiagnoseInvalidRedeclaration(
7800     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7801     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7802   DeclarationName Name = NewFD->getDeclName();
7803   DeclContext *NewDC = NewFD->getDeclContext();
7804   SmallVector<unsigned, 1> MismatchedParams;
7805   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7806   TypoCorrection Correction;
7807   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7808   unsigned DiagMsg =
7809     IsLocalFriend ? diag::err_no_matching_local_friend :
7810     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
7811     diag::err_member_decl_does_not_match;
7812   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7813                     IsLocalFriend ? Sema::LookupLocalFriendName
7814                                   : Sema::LookupOrdinaryName,
7815                     Sema::ForVisibleRedeclaration);
7816 
7817   NewFD->setInvalidDecl();
7818   if (IsLocalFriend)
7819     SemaRef.LookupName(Prev, S);
7820   else
7821     SemaRef.LookupQualifiedName(Prev, NewDC);
7822   assert(!Prev.isAmbiguous() &&
7823          "Cannot have an ambiguity in previous-declaration lookup");
7824   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7825   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
7826                                 MD ? MD->getParent() : nullptr);
7827   if (!Prev.empty()) {
7828     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7829          Func != FuncEnd; ++Func) {
7830       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7831       if (FD &&
7832           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7833         // Add 1 to the index so that 0 can mean the mismatch didn't
7834         // involve a parameter
7835         unsigned ParamNum =
7836             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7837         NearMatches.push_back(std::make_pair(FD, ParamNum));
7838       }
7839     }
7840   // If the qualified name lookup yielded nothing, try typo correction
7841   } else if ((Correction = SemaRef.CorrectTypo(
7842                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7843                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
7844                   IsLocalFriend ? nullptr : NewDC))) {
7845     // Set up everything for the call to ActOnFunctionDeclarator
7846     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7847                               ExtraArgs.D.getIdentifierLoc());
7848     Previous.clear();
7849     Previous.setLookupName(Correction.getCorrection());
7850     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7851                                     CDeclEnd = Correction.end();
7852          CDecl != CDeclEnd; ++CDecl) {
7853       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7854       if (FD && !FD->hasBody() &&
7855           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7856         Previous.addDecl(FD);
7857       }
7858     }
7859     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7860 
7861     NamedDecl *Result;
7862     // Retry building the function declaration with the new previous
7863     // declarations, and with errors suppressed.
7864     {
7865       // Trap errors.
7866       Sema::SFINAETrap Trap(SemaRef);
7867 
7868       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7869       // pieces need to verify the typo-corrected C++ declaration and hopefully
7870       // eliminate the need for the parameter pack ExtraArgs.
7871       Result = SemaRef.ActOnFunctionDeclarator(
7872           ExtraArgs.S, ExtraArgs.D,
7873           Correction.getCorrectionDecl()->getDeclContext(),
7874           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7875           ExtraArgs.AddToScope);
7876 
7877       if (Trap.hasErrorOccurred())
7878         Result = nullptr;
7879     }
7880 
7881     if (Result) {
7882       // Determine which correction we picked.
7883       Decl *Canonical = Result->getCanonicalDecl();
7884       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7885            I != E; ++I)
7886         if ((*I)->getCanonicalDecl() == Canonical)
7887           Correction.setCorrectionDecl(*I);
7888 
7889       // Let Sema know about the correction.
7890       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
7891       SemaRef.diagnoseTypo(
7892           Correction,
7893           SemaRef.PDiag(IsLocalFriend
7894                           ? diag::err_no_matching_local_friend_suggest
7895                           : diag::err_member_decl_does_not_match_suggest)
7896             << Name << NewDC << IsDefinition);
7897       return Result;
7898     }
7899 
7900     // Pretend the typo correction never occurred
7901     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7902                               ExtraArgs.D.getIdentifierLoc());
7903     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7904     Previous.clear();
7905     Previous.setLookupName(Name);
7906   }
7907 
7908   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7909       << Name << NewDC << IsDefinition << NewFD->getLocation();
7910 
7911   bool NewFDisConst = false;
7912   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7913     NewFDisConst = NewMD->isConst();
7914 
7915   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7916        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7917        NearMatch != NearMatchEnd; ++NearMatch) {
7918     FunctionDecl *FD = NearMatch->first;
7919     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7920     bool FDisConst = MD && MD->isConst();
7921     bool IsMember = MD || !IsLocalFriend;
7922 
7923     // FIXME: These notes are poorly worded for the local friend case.
7924     if (unsigned Idx = NearMatch->second) {
7925       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7926       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7927       if (Loc.isInvalid()) Loc = FD->getLocation();
7928       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7929                                  : diag::note_local_decl_close_param_match)
7930         << Idx << FDParam->getType()
7931         << NewFD->getParamDecl(Idx - 1)->getType();
7932     } else if (FDisConst != NewFDisConst) {
7933       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7934           << NewFDisConst << FD->getSourceRange().getEnd();
7935     } else
7936       SemaRef.Diag(FD->getLocation(),
7937                    IsMember ? diag::note_member_def_close_match
7938                             : diag::note_local_decl_close_match);
7939   }
7940   return nullptr;
7941 }
7942 
7943 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7944   switch (D.getDeclSpec().getStorageClassSpec()) {
7945   default: llvm_unreachable("Unknown storage class!");
7946   case DeclSpec::SCS_auto:
7947   case DeclSpec::SCS_register:
7948   case DeclSpec::SCS_mutable:
7949     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7950                  diag::err_typecheck_sclass_func);
7951     D.getMutableDeclSpec().ClearStorageClassSpecs();
7952     D.setInvalidType();
7953     break;
7954   case DeclSpec::SCS_unspecified: break;
7955   case DeclSpec::SCS_extern:
7956     if (D.getDeclSpec().isExternInLinkageSpec())
7957       return SC_None;
7958     return SC_Extern;
7959   case DeclSpec::SCS_static: {
7960     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7961       // C99 6.7.1p5:
7962       //   The declaration of an identifier for a function that has
7963       //   block scope shall have no explicit storage-class specifier
7964       //   other than extern
7965       // See also (C++ [dcl.stc]p4).
7966       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7967                    diag::err_static_block_func);
7968       break;
7969     } else
7970       return SC_Static;
7971   }
7972   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7973   }
7974 
7975   // No explicit storage class has already been returned
7976   return SC_None;
7977 }
7978 
7979 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7980                                            DeclContext *DC, QualType &R,
7981                                            TypeSourceInfo *TInfo,
7982                                            StorageClass SC,
7983                                            bool &IsVirtualOkay) {
7984   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7985   DeclarationName Name = NameInfo.getName();
7986 
7987   FunctionDecl *NewFD = nullptr;
7988   bool isInline = D.getDeclSpec().isInlineSpecified();
7989 
7990   if (!SemaRef.getLangOpts().CPlusPlus) {
7991     // Determine whether the function was written with a
7992     // prototype. This true when:
7993     //   - there is a prototype in the declarator, or
7994     //   - the type R of the function is some kind of typedef or other non-
7995     //     attributed reference to a type name (which eventually refers to a
7996     //     function type).
7997     bool HasPrototype =
7998       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7999       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8000 
8001     NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8002                                  R, TInfo, SC, isInline, HasPrototype,
8003                                  CSK_unspecified);
8004     if (D.isInvalidType())
8005       NewFD->setInvalidDecl();
8006 
8007     return NewFD;
8008   }
8009 
8010   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8011   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8012   // Check that the return type is not an abstract class type.
8013   // For record types, this is done by the AbstractClassUsageDiagnoser once
8014   // the class has been completely parsed.
8015   if (!DC->isRecord() &&
8016       SemaRef.RequireNonAbstractType(
8017           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
8018           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8019     D.setInvalidType();
8020 
8021   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8022     // This is a C++ constructor declaration.
8023     assert(DC->isRecord() &&
8024            "Constructors can only be declared in a member context");
8025 
8026     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8027     return CXXConstructorDecl::Create(
8028         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8029         TInfo, ExplicitSpecifier, isInline,
8030         /*isImplicitlyDeclared=*/false, ConstexprKind);
8031 
8032   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8033     // This is a C++ destructor declaration.
8034     if (DC->isRecord()) {
8035       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8036       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8037       CXXDestructorDecl *NewDD =
8038           CXXDestructorDecl::Create(SemaRef.Context, Record, D.getBeginLoc(),
8039                                     NameInfo, R, TInfo, isInline,
8040                                     /*isImplicitlyDeclared=*/false);
8041 
8042       // If the destructor needs an implicit exception specification, set it
8043       // now. FIXME: It'd be nice to be able to create the right type to start
8044       // with, but the type needs to reference the destructor declaration.
8045       if (SemaRef.getLangOpts().CPlusPlus11)
8046         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8047 
8048       IsVirtualOkay = true;
8049       return NewDD;
8050 
8051     } else {
8052       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8053       D.setInvalidType();
8054 
8055       // Create a FunctionDecl to satisfy the function definition parsing
8056       // code path.
8057       return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8058                                   D.getIdentifierLoc(), Name, R, TInfo, SC,
8059                                   isInline,
8060                                   /*hasPrototype=*/true, ConstexprKind);
8061     }
8062 
8063   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8064     if (!DC->isRecord()) {
8065       SemaRef.Diag(D.getIdentifierLoc(),
8066            diag::err_conv_function_not_member);
8067       return nullptr;
8068     }
8069 
8070     SemaRef.CheckConversionDeclarator(D, R, SC);
8071     IsVirtualOkay = true;
8072     return CXXConversionDecl::Create(
8073         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8074         TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation());
8075 
8076   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8077     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8078 
8079     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8080                                          ExplicitSpecifier, NameInfo, R, TInfo,
8081                                          D.getEndLoc());
8082   } else if (DC->isRecord()) {
8083     // If the name of the function is the same as the name of the record,
8084     // then this must be an invalid constructor that has a return type.
8085     // (The parser checks for a return type and makes the declarator a
8086     // constructor if it has no return type).
8087     if (Name.getAsIdentifierInfo() &&
8088         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8089       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8090         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8091         << SourceRange(D.getIdentifierLoc());
8092       return nullptr;
8093     }
8094 
8095     // This is a C++ method declaration.
8096     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8097         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8098         TInfo, SC, isInline, ConstexprKind, SourceLocation());
8099     IsVirtualOkay = !Ret->isStatic();
8100     return Ret;
8101   } else {
8102     bool isFriend =
8103         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8104     if (!isFriend && SemaRef.CurContext->isRecord())
8105       return nullptr;
8106 
8107     // Determine whether the function was written with a
8108     // prototype. This true when:
8109     //   - we're in C++ (where every function has a prototype),
8110     return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8111                                 R, TInfo, SC, isInline, true /*HasPrototype*/,
8112                                 ConstexprKind);
8113   }
8114 }
8115 
8116 enum OpenCLParamType {
8117   ValidKernelParam,
8118   PtrPtrKernelParam,
8119   PtrKernelParam,
8120   InvalidAddrSpacePtrKernelParam,
8121   InvalidKernelParam,
8122   RecordKernelParam
8123 };
8124 
8125 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8126   // Size dependent types are just typedefs to normal integer types
8127   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8128   // integers other than by their names.
8129   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8130 
8131   // Remove typedefs one by one until we reach a typedef
8132   // for a size dependent type.
8133   QualType DesugaredTy = Ty;
8134   do {
8135     ArrayRef<StringRef> Names(SizeTypeNames);
8136     auto Match = llvm::find(Names, DesugaredTy.getAsString());
8137     if (Names.end() != Match)
8138       return true;
8139 
8140     Ty = DesugaredTy;
8141     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8142   } while (DesugaredTy != Ty);
8143 
8144   return false;
8145 }
8146 
8147 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8148   if (PT->isPointerType()) {
8149     QualType PointeeType = PT->getPointeeType();
8150     if (PointeeType->isPointerType())
8151       return PtrPtrKernelParam;
8152     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8153         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8154         PointeeType.getAddressSpace() == LangAS::Default)
8155       return InvalidAddrSpacePtrKernelParam;
8156     return PtrKernelParam;
8157   }
8158 
8159   // OpenCL v1.2 s6.9.k:
8160   // Arguments to kernel functions in a program cannot be declared with the
8161   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8162   // uintptr_t or a struct and/or union that contain fields declared to be one
8163   // of these built-in scalar types.
8164   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8165     return InvalidKernelParam;
8166 
8167   if (PT->isImageType())
8168     return PtrKernelParam;
8169 
8170   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8171     return InvalidKernelParam;
8172 
8173   // OpenCL extension spec v1.2 s9.5:
8174   // This extension adds support for half scalar and vector types as built-in
8175   // types that can be used for arithmetic operations, conversions etc.
8176   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8177     return InvalidKernelParam;
8178 
8179   if (PT->isRecordType())
8180     return RecordKernelParam;
8181 
8182   // Look into an array argument to check if it has a forbidden type.
8183   if (PT->isArrayType()) {
8184     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8185     // Call ourself to check an underlying type of an array. Since the
8186     // getPointeeOrArrayElementType returns an innermost type which is not an
8187     // array, this recursive call only happens once.
8188     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8189   }
8190 
8191   return ValidKernelParam;
8192 }
8193 
8194 static void checkIsValidOpenCLKernelParameter(
8195   Sema &S,
8196   Declarator &D,
8197   ParmVarDecl *Param,
8198   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8199   QualType PT = Param->getType();
8200 
8201   // Cache the valid types we encounter to avoid rechecking structs that are
8202   // used again
8203   if (ValidTypes.count(PT.getTypePtr()))
8204     return;
8205 
8206   switch (getOpenCLKernelParameterType(S, PT)) {
8207   case PtrPtrKernelParam:
8208     // OpenCL v1.2 s6.9.a:
8209     // A kernel function argument cannot be declared as a
8210     // pointer to a pointer type.
8211     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8212     D.setInvalidType();
8213     return;
8214 
8215   case InvalidAddrSpacePtrKernelParam:
8216     // OpenCL v1.0 s6.5:
8217     // __kernel function arguments declared to be a pointer of a type can point
8218     // to one of the following address spaces only : __global, __local or
8219     // __constant.
8220     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8221     D.setInvalidType();
8222     return;
8223 
8224     // OpenCL v1.2 s6.9.k:
8225     // Arguments to kernel functions in a program cannot be declared with the
8226     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8227     // uintptr_t or a struct and/or union that contain fields declared to be
8228     // one of these built-in scalar types.
8229 
8230   case InvalidKernelParam:
8231     // OpenCL v1.2 s6.8 n:
8232     // A kernel function argument cannot be declared
8233     // of event_t type.
8234     // Do not diagnose half type since it is diagnosed as invalid argument
8235     // type for any function elsewhere.
8236     if (!PT->isHalfType()) {
8237       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8238 
8239       // Explain what typedefs are involved.
8240       const TypedefType *Typedef = nullptr;
8241       while ((Typedef = PT->getAs<TypedefType>())) {
8242         SourceLocation Loc = Typedef->getDecl()->getLocation();
8243         // SourceLocation may be invalid for a built-in type.
8244         if (Loc.isValid())
8245           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8246         PT = Typedef->desugar();
8247       }
8248     }
8249 
8250     D.setInvalidType();
8251     return;
8252 
8253   case PtrKernelParam:
8254   case ValidKernelParam:
8255     ValidTypes.insert(PT.getTypePtr());
8256     return;
8257 
8258   case RecordKernelParam:
8259     break;
8260   }
8261 
8262   // Track nested structs we will inspect
8263   SmallVector<const Decl *, 4> VisitStack;
8264 
8265   // Track where we are in the nested structs. Items will migrate from
8266   // VisitStack to HistoryStack as we do the DFS for bad field.
8267   SmallVector<const FieldDecl *, 4> HistoryStack;
8268   HistoryStack.push_back(nullptr);
8269 
8270   // At this point we already handled everything except of a RecordType or
8271   // an ArrayType of a RecordType.
8272   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8273   const RecordType *RecTy =
8274       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8275   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8276 
8277   VisitStack.push_back(RecTy->getDecl());
8278   assert(VisitStack.back() && "First decl null?");
8279 
8280   do {
8281     const Decl *Next = VisitStack.pop_back_val();
8282     if (!Next) {
8283       assert(!HistoryStack.empty());
8284       // Found a marker, we have gone up a level
8285       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8286         ValidTypes.insert(Hist->getType().getTypePtr());
8287 
8288       continue;
8289     }
8290 
8291     // Adds everything except the original parameter declaration (which is not a
8292     // field itself) to the history stack.
8293     const RecordDecl *RD;
8294     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8295       HistoryStack.push_back(Field);
8296 
8297       QualType FieldTy = Field->getType();
8298       // Other field types (known to be valid or invalid) are handled while we
8299       // walk around RecordDecl::fields().
8300       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8301              "Unexpected type.");
8302       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8303 
8304       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8305     } else {
8306       RD = cast<RecordDecl>(Next);
8307     }
8308 
8309     // Add a null marker so we know when we've gone back up a level
8310     VisitStack.push_back(nullptr);
8311 
8312     for (const auto *FD : RD->fields()) {
8313       QualType QT = FD->getType();
8314 
8315       if (ValidTypes.count(QT.getTypePtr()))
8316         continue;
8317 
8318       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8319       if (ParamType == ValidKernelParam)
8320         continue;
8321 
8322       if (ParamType == RecordKernelParam) {
8323         VisitStack.push_back(FD);
8324         continue;
8325       }
8326 
8327       // OpenCL v1.2 s6.9.p:
8328       // Arguments to kernel functions that are declared to be a struct or union
8329       // do not allow OpenCL objects to be passed as elements of the struct or
8330       // union.
8331       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8332           ParamType == InvalidAddrSpacePtrKernelParam) {
8333         S.Diag(Param->getLocation(),
8334                diag::err_record_with_pointers_kernel_param)
8335           << PT->isUnionType()
8336           << PT;
8337       } else {
8338         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8339       }
8340 
8341       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8342           << OrigRecDecl->getDeclName();
8343 
8344       // We have an error, now let's go back up through history and show where
8345       // the offending field came from
8346       for (ArrayRef<const FieldDecl *>::const_iterator
8347                I = HistoryStack.begin() + 1,
8348                E = HistoryStack.end();
8349            I != E; ++I) {
8350         const FieldDecl *OuterField = *I;
8351         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8352           << OuterField->getType();
8353       }
8354 
8355       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8356         << QT->isPointerType()
8357         << QT;
8358       D.setInvalidType();
8359       return;
8360     }
8361   } while (!VisitStack.empty());
8362 }
8363 
8364 /// Find the DeclContext in which a tag is implicitly declared if we see an
8365 /// elaborated type specifier in the specified context, and lookup finds
8366 /// nothing.
8367 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8368   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8369     DC = DC->getParent();
8370   return DC;
8371 }
8372 
8373 /// Find the Scope in which a tag is implicitly declared if we see an
8374 /// elaborated type specifier in the specified context, and lookup finds
8375 /// nothing.
8376 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8377   while (S->isClassScope() ||
8378          (LangOpts.CPlusPlus &&
8379           S->isFunctionPrototypeScope()) ||
8380          ((S->getFlags() & Scope::DeclScope) == 0) ||
8381          (S->getEntity() && S->getEntity()->isTransparentContext()))
8382     S = S->getParent();
8383   return S;
8384 }
8385 
8386 NamedDecl*
8387 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8388                               TypeSourceInfo *TInfo, LookupResult &Previous,
8389                               MultiTemplateParamsArg TemplateParamLists,
8390                               bool &AddToScope) {
8391   QualType R = TInfo->getType();
8392 
8393   assert(R->isFunctionType());
8394 
8395   // TODO: consider using NameInfo for diagnostic.
8396   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8397   DeclarationName Name = NameInfo.getName();
8398   StorageClass SC = getFunctionStorageClass(*this, D);
8399 
8400   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8401     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8402          diag::err_invalid_thread)
8403       << DeclSpec::getSpecifierName(TSCS);
8404 
8405   if (D.isFirstDeclarationOfMember())
8406     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8407                            D.getIdentifierLoc());
8408 
8409   bool isFriend = false;
8410   FunctionTemplateDecl *FunctionTemplate = nullptr;
8411   bool isMemberSpecialization = false;
8412   bool isFunctionTemplateSpecialization = false;
8413 
8414   bool isDependentClassScopeExplicitSpecialization = false;
8415   bool HasExplicitTemplateArgs = false;
8416   TemplateArgumentListInfo TemplateArgs;
8417 
8418   bool isVirtualOkay = false;
8419 
8420   DeclContext *OriginalDC = DC;
8421   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8422 
8423   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8424                                               isVirtualOkay);
8425   if (!NewFD) return nullptr;
8426 
8427   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8428     NewFD->setTopLevelDeclInObjCContainer();
8429 
8430   // Set the lexical context. If this is a function-scope declaration, or has a
8431   // C++ scope specifier, or is the object of a friend declaration, the lexical
8432   // context will be different from the semantic context.
8433   NewFD->setLexicalDeclContext(CurContext);
8434 
8435   if (IsLocalExternDecl)
8436     NewFD->setLocalExternDecl();
8437 
8438   if (getLangOpts().CPlusPlus) {
8439     bool isInline = D.getDeclSpec().isInlineSpecified();
8440     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8441     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
8442     ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8443     isFriend = D.getDeclSpec().isFriendSpecified();
8444     if (isFriend && !isInline && D.isFunctionDefinition()) {
8445       // C++ [class.friend]p5
8446       //   A function can be defined in a friend declaration of a
8447       //   class . . . . Such a function is implicitly inline.
8448       NewFD->setImplicitlyInline();
8449     }
8450 
8451     // If this is a method defined in an __interface, and is not a constructor
8452     // or an overloaded operator, then set the pure flag (isVirtual will already
8453     // return true).
8454     if (const CXXRecordDecl *Parent =
8455           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8456       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8457         NewFD->setPure(true);
8458 
8459       // C++ [class.union]p2
8460       //   A union can have member functions, but not virtual functions.
8461       if (isVirtual && Parent->isUnion())
8462         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8463     }
8464 
8465     SetNestedNameSpecifier(*this, NewFD, D);
8466     isMemberSpecialization = false;
8467     isFunctionTemplateSpecialization = false;
8468     if (D.isInvalidType())
8469       NewFD->setInvalidDecl();
8470 
8471     // Match up the template parameter lists with the scope specifier, then
8472     // determine whether we have a template or a template specialization.
8473     bool Invalid = false;
8474     if (TemplateParameterList *TemplateParams =
8475             MatchTemplateParametersToScopeSpecifier(
8476                 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8477                 D.getCXXScopeSpec(),
8478                 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8479                     ? D.getName().TemplateId
8480                     : nullptr,
8481                 TemplateParamLists, isFriend, isMemberSpecialization,
8482                 Invalid)) {
8483       if (TemplateParams->size() > 0) {
8484         // This is a function template
8485 
8486         // Check that we can declare a template here.
8487         if (CheckTemplateDeclScope(S, TemplateParams))
8488           NewFD->setInvalidDecl();
8489 
8490         // A destructor cannot be a template.
8491         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8492           Diag(NewFD->getLocation(), diag::err_destructor_template);
8493           NewFD->setInvalidDecl();
8494         }
8495 
8496         // If we're adding a template to a dependent context, we may need to
8497         // rebuilding some of the types used within the template parameter list,
8498         // now that we know what the current instantiation is.
8499         if (DC->isDependentContext()) {
8500           ContextRAII SavedContext(*this, DC);
8501           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8502             Invalid = true;
8503         }
8504 
8505         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8506                                                         NewFD->getLocation(),
8507                                                         Name, TemplateParams,
8508                                                         NewFD);
8509         FunctionTemplate->setLexicalDeclContext(CurContext);
8510         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8511 
8512         // For source fidelity, store the other template param lists.
8513         if (TemplateParamLists.size() > 1) {
8514           NewFD->setTemplateParameterListsInfo(Context,
8515                                                TemplateParamLists.drop_back(1));
8516         }
8517       } else {
8518         // This is a function template specialization.
8519         isFunctionTemplateSpecialization = true;
8520         // For source fidelity, store all the template param lists.
8521         if (TemplateParamLists.size() > 0)
8522           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8523 
8524         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8525         if (isFriend) {
8526           // We want to remove the "template<>", found here.
8527           SourceRange RemoveRange = TemplateParams->getSourceRange();
8528 
8529           // If we remove the template<> and the name is not a
8530           // template-id, we're actually silently creating a problem:
8531           // the friend declaration will refer to an untemplated decl,
8532           // and clearly the user wants a template specialization.  So
8533           // we need to insert '<>' after the name.
8534           SourceLocation InsertLoc;
8535           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8536             InsertLoc = D.getName().getSourceRange().getEnd();
8537             InsertLoc = getLocForEndOfToken(InsertLoc);
8538           }
8539 
8540           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8541             << Name << RemoveRange
8542             << FixItHint::CreateRemoval(RemoveRange)
8543             << FixItHint::CreateInsertion(InsertLoc, "<>");
8544         }
8545       }
8546     } else {
8547       // All template param lists were matched against the scope specifier:
8548       // this is NOT (an explicit specialization of) a template.
8549       if (TemplateParamLists.size() > 0)
8550         // For source fidelity, store all the template param lists.
8551         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8552     }
8553 
8554     if (Invalid) {
8555       NewFD->setInvalidDecl();
8556       if (FunctionTemplate)
8557         FunctionTemplate->setInvalidDecl();
8558     }
8559 
8560     // C++ [dcl.fct.spec]p5:
8561     //   The virtual specifier shall only be used in declarations of
8562     //   nonstatic class member functions that appear within a
8563     //   member-specification of a class declaration; see 10.3.
8564     //
8565     if (isVirtual && !NewFD->isInvalidDecl()) {
8566       if (!isVirtualOkay) {
8567         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8568              diag::err_virtual_non_function);
8569       } else if (!CurContext->isRecord()) {
8570         // 'virtual' was specified outside of the class.
8571         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8572              diag::err_virtual_out_of_class)
8573           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8574       } else if (NewFD->getDescribedFunctionTemplate()) {
8575         // C++ [temp.mem]p3:
8576         //  A member function template shall not be virtual.
8577         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8578              diag::err_virtual_member_function_template)
8579           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8580       } else {
8581         // Okay: Add virtual to the method.
8582         NewFD->setVirtualAsWritten(true);
8583       }
8584 
8585       if (getLangOpts().CPlusPlus14 &&
8586           NewFD->getReturnType()->isUndeducedType())
8587         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8588     }
8589 
8590     if (getLangOpts().CPlusPlus14 &&
8591         (NewFD->isDependentContext() ||
8592          (isFriend && CurContext->isDependentContext())) &&
8593         NewFD->getReturnType()->isUndeducedType()) {
8594       // If the function template is referenced directly (for instance, as a
8595       // member of the current instantiation), pretend it has a dependent type.
8596       // This is not really justified by the standard, but is the only sane
8597       // thing to do.
8598       // FIXME: For a friend function, we have not marked the function as being
8599       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8600       const FunctionProtoType *FPT =
8601           NewFD->getType()->castAs<FunctionProtoType>();
8602       QualType Result =
8603           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8604       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8605                                              FPT->getExtProtoInfo()));
8606     }
8607 
8608     // C++ [dcl.fct.spec]p3:
8609     //  The inline specifier shall not appear on a block scope function
8610     //  declaration.
8611     if (isInline && !NewFD->isInvalidDecl()) {
8612       if (CurContext->isFunctionOrMethod()) {
8613         // 'inline' is not allowed on block scope function declaration.
8614         Diag(D.getDeclSpec().getInlineSpecLoc(),
8615              diag::err_inline_declaration_block_scope) << Name
8616           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8617       }
8618     }
8619 
8620     // C++ [dcl.fct.spec]p6:
8621     //  The explicit specifier shall be used only in the declaration of a
8622     //  constructor or conversion function within its class definition;
8623     //  see 12.3.1 and 12.3.2.
8624     if (hasExplicit && !NewFD->isInvalidDecl() &&
8625         !isa<CXXDeductionGuideDecl>(NewFD)) {
8626       if (!CurContext->isRecord()) {
8627         // 'explicit' was specified outside of the class.
8628         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8629              diag::err_explicit_out_of_class)
8630             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
8631       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8632                  !isa<CXXConversionDecl>(NewFD)) {
8633         // 'explicit' was specified on a function that wasn't a constructor
8634         // or conversion function.
8635         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8636              diag::err_explicit_non_ctor_or_conv_function)
8637             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
8638       }
8639     }
8640 
8641     if (ConstexprKind != CSK_unspecified) {
8642       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8643       // are implicitly inline.
8644       NewFD->setImplicitlyInline();
8645 
8646       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8647       // be either constructors or to return a literal type. Therefore,
8648       // destructors cannot be declared constexpr.
8649       if (isa<CXXDestructorDecl>(NewFD))
8650         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
8651             << (ConstexprKind == CSK_consteval);
8652     }
8653 
8654     // If __module_private__ was specified, mark the function accordingly.
8655     if (D.getDeclSpec().isModulePrivateSpecified()) {
8656       if (isFunctionTemplateSpecialization) {
8657         SourceLocation ModulePrivateLoc
8658           = D.getDeclSpec().getModulePrivateSpecLoc();
8659         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8660           << 0
8661           << FixItHint::CreateRemoval(ModulePrivateLoc);
8662       } else {
8663         NewFD->setModulePrivate();
8664         if (FunctionTemplate)
8665           FunctionTemplate->setModulePrivate();
8666       }
8667     }
8668 
8669     if (isFriend) {
8670       if (FunctionTemplate) {
8671         FunctionTemplate->setObjectOfFriendDecl();
8672         FunctionTemplate->setAccess(AS_public);
8673       }
8674       NewFD->setObjectOfFriendDecl();
8675       NewFD->setAccess(AS_public);
8676     }
8677 
8678     // If a function is defined as defaulted or deleted, mark it as such now.
8679     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8680     // definition kind to FDK_Definition.
8681     switch (D.getFunctionDefinitionKind()) {
8682       case FDK_Declaration:
8683       case FDK_Definition:
8684         break;
8685 
8686       case FDK_Defaulted:
8687         NewFD->setDefaulted();
8688         break;
8689 
8690       case FDK_Deleted:
8691         NewFD->setDeletedAsWritten();
8692         break;
8693     }
8694 
8695     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8696         D.isFunctionDefinition()) {
8697       // C++ [class.mfct]p2:
8698       //   A member function may be defined (8.4) in its class definition, in
8699       //   which case it is an inline member function (7.1.2)
8700       NewFD->setImplicitlyInline();
8701     }
8702 
8703     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8704         !CurContext->isRecord()) {
8705       // C++ [class.static]p1:
8706       //   A data or function member of a class may be declared static
8707       //   in a class definition, in which case it is a static member of
8708       //   the class.
8709 
8710       // Complain about the 'static' specifier if it's on an out-of-line
8711       // member function definition.
8712 
8713       // MSVC permits the use of a 'static' storage specifier on an out-of-line
8714       // member function template declaration and class member template
8715       // declaration (MSVC versions before 2015), warn about this.
8716       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8717            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
8718              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
8719            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
8720            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
8721         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8722     }
8723 
8724     // C++11 [except.spec]p15:
8725     //   A deallocation function with no exception-specification is treated
8726     //   as if it were specified with noexcept(true).
8727     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8728     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8729          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8730         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8731       NewFD->setType(Context.getFunctionType(
8732           FPT->getReturnType(), FPT->getParamTypes(),
8733           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8734   }
8735 
8736   // Filter out previous declarations that don't match the scope.
8737   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8738                        D.getCXXScopeSpec().isNotEmpty() ||
8739                        isMemberSpecialization ||
8740                        isFunctionTemplateSpecialization);
8741 
8742   // Handle GNU asm-label extension (encoded as an attribute).
8743   if (Expr *E = (Expr*) D.getAsmLabel()) {
8744     // The parser guarantees this is a string.
8745     StringLiteral *SE = cast<StringLiteral>(E);
8746     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8747                                                 SE->getString(), 0));
8748   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8749     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8750       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8751     if (I != ExtnameUndeclaredIdentifiers.end()) {
8752       if (isDeclExternC(NewFD)) {
8753         NewFD->addAttr(I->second);
8754         ExtnameUndeclaredIdentifiers.erase(I);
8755       } else
8756         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8757             << /*Variable*/0 << NewFD;
8758     }
8759   }
8760 
8761   // Copy the parameter declarations from the declarator D to the function
8762   // declaration NewFD, if they are available.  First scavenge them into Params.
8763   SmallVector<ParmVarDecl*, 16> Params;
8764   unsigned FTIIdx;
8765   if (D.isFunctionDeclarator(FTIIdx)) {
8766     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8767 
8768     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8769     // function that takes no arguments, not a function that takes a
8770     // single void argument.
8771     // We let through "const void" here because Sema::GetTypeForDeclarator
8772     // already checks for that case.
8773     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8774       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8775         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8776         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8777         Param->setDeclContext(NewFD);
8778         Params.push_back(Param);
8779 
8780         if (Param->isInvalidDecl())
8781           NewFD->setInvalidDecl();
8782       }
8783     }
8784 
8785     if (!getLangOpts().CPlusPlus) {
8786       // In C, find all the tag declarations from the prototype and move them
8787       // into the function DeclContext. Remove them from the surrounding tag
8788       // injection context of the function, which is typically but not always
8789       // the TU.
8790       DeclContext *PrototypeTagContext =
8791           getTagInjectionContext(NewFD->getLexicalDeclContext());
8792       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8793         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8794 
8795         // We don't want to reparent enumerators. Look at their parent enum
8796         // instead.
8797         if (!TD) {
8798           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8799             TD = cast<EnumDecl>(ECD->getDeclContext());
8800         }
8801         if (!TD)
8802           continue;
8803         DeclContext *TagDC = TD->getLexicalDeclContext();
8804         if (!TagDC->containsDecl(TD))
8805           continue;
8806         TagDC->removeDecl(TD);
8807         TD->setDeclContext(NewFD);
8808         NewFD->addDecl(TD);
8809 
8810         // Preserve the lexical DeclContext if it is not the surrounding tag
8811         // injection context of the FD. In this example, the semantic context of
8812         // E will be f and the lexical context will be S, while both the
8813         // semantic and lexical contexts of S will be f:
8814         //   void f(struct S { enum E { a } f; } s);
8815         if (TagDC != PrototypeTagContext)
8816           TD->setLexicalDeclContext(TagDC);
8817       }
8818     }
8819   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8820     // When we're declaring a function with a typedef, typeof, etc as in the
8821     // following example, we'll need to synthesize (unnamed)
8822     // parameters for use in the declaration.
8823     //
8824     // @code
8825     // typedef void fn(int);
8826     // fn f;
8827     // @endcode
8828 
8829     // Synthesize a parameter for each argument type.
8830     for (const auto &AI : FT->param_types()) {
8831       ParmVarDecl *Param =
8832           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8833       Param->setScopeInfo(0, Params.size());
8834       Params.push_back(Param);
8835     }
8836   } else {
8837     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8838            "Should not need args for typedef of non-prototype fn");
8839   }
8840 
8841   // Finally, we know we have the right number of parameters, install them.
8842   NewFD->setParams(Params);
8843 
8844   if (D.getDeclSpec().isNoreturnSpecified())
8845     NewFD->addAttr(
8846         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8847                                        Context, 0));
8848 
8849   // Functions returning a variably modified type violate C99 6.7.5.2p2
8850   // because all functions have linkage.
8851   if (!NewFD->isInvalidDecl() &&
8852       NewFD->getReturnType()->isVariablyModifiedType()) {
8853     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8854     NewFD->setInvalidDecl();
8855   }
8856 
8857   // Apply an implicit SectionAttr if '#pragma clang section text' is active
8858   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
8859       !NewFD->hasAttr<SectionAttr>()) {
8860     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
8861                                                  PragmaClangTextSection.SectionName,
8862                                                  PragmaClangTextSection.PragmaLocation));
8863   }
8864 
8865   // Apply an implicit SectionAttr if #pragma code_seg is active.
8866   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8867       !NewFD->hasAttr<SectionAttr>()) {
8868     NewFD->addAttr(
8869         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8870                                     CodeSegStack.CurrentValue->getString(),
8871                                     CodeSegStack.CurrentPragmaLocation));
8872     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8873                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8874                          ASTContext::PSF_Read,
8875                      NewFD))
8876       NewFD->dropAttr<SectionAttr>();
8877   }
8878 
8879   // Apply an implicit CodeSegAttr from class declspec or
8880   // apply an implicit SectionAttr from #pragma code_seg if active.
8881   if (!NewFD->hasAttr<CodeSegAttr>()) {
8882     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
8883                                                                  D.isFunctionDefinition())) {
8884       NewFD->addAttr(SAttr);
8885     }
8886   }
8887 
8888   // Handle attributes.
8889   ProcessDeclAttributes(S, NewFD, D);
8890 
8891   if (getLangOpts().OpenCL) {
8892     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8893     // type declaration will generate a compilation error.
8894     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
8895     if (AddressSpace != LangAS::Default) {
8896       Diag(NewFD->getLocation(),
8897            diag::err_opencl_return_value_with_address_space);
8898       NewFD->setInvalidDecl();
8899     }
8900   }
8901 
8902   if (!getLangOpts().CPlusPlus) {
8903     // Perform semantic checking on the function declaration.
8904     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8905       CheckMain(NewFD, D.getDeclSpec());
8906 
8907     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8908       CheckMSVCRTEntryPoint(NewFD);
8909 
8910     if (!NewFD->isInvalidDecl())
8911       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8912                                                   isMemberSpecialization));
8913     else if (!Previous.empty())
8914       // Recover gracefully from an invalid redeclaration.
8915       D.setRedeclaration(true);
8916     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8917             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8918            "previous declaration set still overloaded");
8919 
8920     // Diagnose no-prototype function declarations with calling conventions that
8921     // don't support variadic calls. Only do this in C and do it after merging
8922     // possibly prototyped redeclarations.
8923     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8924     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8925       CallingConv CC = FT->getExtInfo().getCC();
8926       if (!supportsVariadicCall(CC)) {
8927         // Windows system headers sometimes accidentally use stdcall without
8928         // (void) parameters, so we relax this to a warning.
8929         int DiagID =
8930             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8931         Diag(NewFD->getLocation(), DiagID)
8932             << FunctionType::getNameForCallConv(CC);
8933       }
8934     }
8935 
8936    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
8937        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
8938      checkNonTrivialCUnion(NewFD->getReturnType(),
8939                            NewFD->getReturnTypeSourceRange().getBegin(),
8940                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
8941   } else {
8942     // C++11 [replacement.functions]p3:
8943     //  The program's definitions shall not be specified as inline.
8944     //
8945     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8946     //
8947     // Suppress the diagnostic if the function is __attribute__((used)), since
8948     // that forces an external definition to be emitted.
8949     if (D.getDeclSpec().isInlineSpecified() &&
8950         NewFD->isReplaceableGlobalAllocationFunction() &&
8951         !NewFD->hasAttr<UsedAttr>())
8952       Diag(D.getDeclSpec().getInlineSpecLoc(),
8953            diag::ext_operator_new_delete_declared_inline)
8954         << NewFD->getDeclName();
8955 
8956     // If the declarator is a template-id, translate the parser's template
8957     // argument list into our AST format.
8958     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
8959       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8960       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8961       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8962       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8963                                          TemplateId->NumArgs);
8964       translateTemplateArguments(TemplateArgsPtr,
8965                                  TemplateArgs);
8966 
8967       HasExplicitTemplateArgs = true;
8968 
8969       if (NewFD->isInvalidDecl()) {
8970         HasExplicitTemplateArgs = false;
8971       } else if (FunctionTemplate) {
8972         // Function template with explicit template arguments.
8973         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8974           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8975 
8976         HasExplicitTemplateArgs = false;
8977       } else {
8978         assert((isFunctionTemplateSpecialization ||
8979                 D.getDeclSpec().isFriendSpecified()) &&
8980                "should have a 'template<>' for this decl");
8981         // "friend void foo<>(int);" is an implicit specialization decl.
8982         isFunctionTemplateSpecialization = true;
8983       }
8984     } else if (isFriend && isFunctionTemplateSpecialization) {
8985       // This combination is only possible in a recovery case;  the user
8986       // wrote something like:
8987       //   template <> friend void foo(int);
8988       // which we're recovering from as if the user had written:
8989       //   friend void foo<>(int);
8990       // Go ahead and fake up a template id.
8991       HasExplicitTemplateArgs = true;
8992       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8993       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8994     }
8995 
8996     // We do not add HD attributes to specializations here because
8997     // they may have different constexpr-ness compared to their
8998     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8999     // may end up with different effective targets. Instead, a
9000     // specialization inherits its target attributes from its template
9001     // in the CheckFunctionTemplateSpecialization() call below.
9002     if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
9003       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9004 
9005     // If it's a friend (and only if it's a friend), it's possible
9006     // that either the specialized function type or the specialized
9007     // template is dependent, and therefore matching will fail.  In
9008     // this case, don't check the specialization yet.
9009     bool InstantiationDependent = false;
9010     if (isFunctionTemplateSpecialization && isFriend &&
9011         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9012          TemplateSpecializationType::anyDependentTemplateArguments(
9013             TemplateArgs,
9014             InstantiationDependent))) {
9015       assert(HasExplicitTemplateArgs &&
9016              "friend function specialization without template args");
9017       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9018                                                        Previous))
9019         NewFD->setInvalidDecl();
9020     } else if (isFunctionTemplateSpecialization) {
9021       if (CurContext->isDependentContext() && CurContext->isRecord()
9022           && !isFriend) {
9023         isDependentClassScopeExplicitSpecialization = true;
9024       } else if (!NewFD->isInvalidDecl() &&
9025                  CheckFunctionTemplateSpecialization(
9026                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9027                      Previous))
9028         NewFD->setInvalidDecl();
9029 
9030       // C++ [dcl.stc]p1:
9031       //   A storage-class-specifier shall not be specified in an explicit
9032       //   specialization (14.7.3)
9033       FunctionTemplateSpecializationInfo *Info =
9034           NewFD->getTemplateSpecializationInfo();
9035       if (Info && SC != SC_None) {
9036         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9037           Diag(NewFD->getLocation(),
9038                diag::err_explicit_specialization_inconsistent_storage_class)
9039             << SC
9040             << FixItHint::CreateRemoval(
9041                                       D.getDeclSpec().getStorageClassSpecLoc());
9042 
9043         else
9044           Diag(NewFD->getLocation(),
9045                diag::ext_explicit_specialization_storage_class)
9046             << FixItHint::CreateRemoval(
9047                                       D.getDeclSpec().getStorageClassSpecLoc());
9048       }
9049     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9050       if (CheckMemberSpecialization(NewFD, Previous))
9051           NewFD->setInvalidDecl();
9052     }
9053 
9054     // Perform semantic checking on the function declaration.
9055     if (!isDependentClassScopeExplicitSpecialization) {
9056       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9057         CheckMain(NewFD, D.getDeclSpec());
9058 
9059       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9060         CheckMSVCRTEntryPoint(NewFD);
9061 
9062       if (!NewFD->isInvalidDecl())
9063         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9064                                                     isMemberSpecialization));
9065       else if (!Previous.empty())
9066         // Recover gracefully from an invalid redeclaration.
9067         D.setRedeclaration(true);
9068     }
9069 
9070     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9071             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9072            "previous declaration set still overloaded");
9073 
9074     NamedDecl *PrincipalDecl = (FunctionTemplate
9075                                 ? cast<NamedDecl>(FunctionTemplate)
9076                                 : NewFD);
9077 
9078     if (isFriend && NewFD->getPreviousDecl()) {
9079       AccessSpecifier Access = AS_public;
9080       if (!NewFD->isInvalidDecl())
9081         Access = NewFD->getPreviousDecl()->getAccess();
9082 
9083       NewFD->setAccess(Access);
9084       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9085     }
9086 
9087     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9088         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9089       PrincipalDecl->setNonMemberOperator();
9090 
9091     // If we have a function template, check the template parameter
9092     // list. This will check and merge default template arguments.
9093     if (FunctionTemplate) {
9094       FunctionTemplateDecl *PrevTemplate =
9095                                      FunctionTemplate->getPreviousDecl();
9096       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9097                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9098                                     : nullptr,
9099                             D.getDeclSpec().isFriendSpecified()
9100                               ? (D.isFunctionDefinition()
9101                                    ? TPC_FriendFunctionTemplateDefinition
9102                                    : TPC_FriendFunctionTemplate)
9103                               : (D.getCXXScopeSpec().isSet() &&
9104                                  DC && DC->isRecord() &&
9105                                  DC->isDependentContext())
9106                                   ? TPC_ClassTemplateMember
9107                                   : TPC_FunctionTemplate);
9108     }
9109 
9110     if (NewFD->isInvalidDecl()) {
9111       // Ignore all the rest of this.
9112     } else if (!D.isRedeclaration()) {
9113       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9114                                        AddToScope };
9115       // Fake up an access specifier if it's supposed to be a class member.
9116       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9117         NewFD->setAccess(AS_public);
9118 
9119       // Qualified decls generally require a previous declaration.
9120       if (D.getCXXScopeSpec().isSet()) {
9121         // ...with the major exception of templated-scope or
9122         // dependent-scope friend declarations.
9123 
9124         // TODO: we currently also suppress this check in dependent
9125         // contexts because (1) the parameter depth will be off when
9126         // matching friend templates and (2) we might actually be
9127         // selecting a friend based on a dependent factor.  But there
9128         // are situations where these conditions don't apply and we
9129         // can actually do this check immediately.
9130         //
9131         // Unless the scope is dependent, it's always an error if qualified
9132         // redeclaration lookup found nothing at all. Diagnose that now;
9133         // nothing will diagnose that error later.
9134         if (isFriend &&
9135             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9136              (!Previous.empty() && CurContext->isDependentContext()))) {
9137           // ignore these
9138         } else {
9139           // The user tried to provide an out-of-line definition for a
9140           // function that is a member of a class or namespace, but there
9141           // was no such member function declared (C++ [class.mfct]p2,
9142           // C++ [namespace.memdef]p2). For example:
9143           //
9144           // class X {
9145           //   void f() const;
9146           // };
9147           //
9148           // void X::f() { } // ill-formed
9149           //
9150           // Complain about this problem, and attempt to suggest close
9151           // matches (e.g., those that differ only in cv-qualifiers and
9152           // whether the parameter types are references).
9153 
9154           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9155                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9156             AddToScope = ExtraArgs.AddToScope;
9157             return Result;
9158           }
9159         }
9160 
9161         // Unqualified local friend declarations are required to resolve
9162         // to something.
9163       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9164         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9165                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9166           AddToScope = ExtraArgs.AddToScope;
9167           return Result;
9168         }
9169       }
9170     } else if (!D.isFunctionDefinition() &&
9171                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9172                !isFriend && !isFunctionTemplateSpecialization &&
9173                !isMemberSpecialization) {
9174       // An out-of-line member function declaration must also be a
9175       // definition (C++ [class.mfct]p2).
9176       // Note that this is not the case for explicit specializations of
9177       // function templates or member functions of class templates, per
9178       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9179       // extension for compatibility with old SWIG code which likes to
9180       // generate them.
9181       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9182         << D.getCXXScopeSpec().getRange();
9183     }
9184   }
9185 
9186   ProcessPragmaWeak(S, NewFD);
9187   checkAttributesAfterMerging(*this, *NewFD);
9188 
9189   AddKnownFunctionAttributes(NewFD);
9190 
9191   if (NewFD->hasAttr<OverloadableAttr>() &&
9192       !NewFD->getType()->getAs<FunctionProtoType>()) {
9193     Diag(NewFD->getLocation(),
9194          diag::err_attribute_overloadable_no_prototype)
9195       << NewFD;
9196 
9197     // Turn this into a variadic function with no parameters.
9198     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9199     FunctionProtoType::ExtProtoInfo EPI(
9200         Context.getDefaultCallingConvention(true, false));
9201     EPI.Variadic = true;
9202     EPI.ExtInfo = FT->getExtInfo();
9203 
9204     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9205     NewFD->setType(R);
9206   }
9207 
9208   // If there's a #pragma GCC visibility in scope, and this isn't a class
9209   // member, set the visibility of this function.
9210   if (!DC->isRecord() && NewFD->isExternallyVisible())
9211     AddPushedVisibilityAttribute(NewFD);
9212 
9213   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9214   // marking the function.
9215   AddCFAuditedAttribute(NewFD);
9216 
9217   // If this is a function definition, check if we have to apply optnone due to
9218   // a pragma.
9219   if(D.isFunctionDefinition())
9220     AddRangeBasedOptnone(NewFD);
9221 
9222   // If this is the first declaration of an extern C variable, update
9223   // the map of such variables.
9224   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9225       isIncompleteDeclExternC(*this, NewFD))
9226     RegisterLocallyScopedExternCDecl(NewFD, S);
9227 
9228   // Set this FunctionDecl's range up to the right paren.
9229   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9230 
9231   if (D.isRedeclaration() && !Previous.empty()) {
9232     NamedDecl *Prev = Previous.getRepresentativeDecl();
9233     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9234                                    isMemberSpecialization ||
9235                                        isFunctionTemplateSpecialization,
9236                                    D.isFunctionDefinition());
9237   }
9238 
9239   if (getLangOpts().CUDA) {
9240     IdentifierInfo *II = NewFD->getIdentifier();
9241     if (II && II->isStr(getCudaConfigureFuncName()) &&
9242         !NewFD->isInvalidDecl() &&
9243         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9244       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9245         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9246             << getCudaConfigureFuncName();
9247       Context.setcudaConfigureCallDecl(NewFD);
9248     }
9249 
9250     // Variadic functions, other than a *declaration* of printf, are not allowed
9251     // in device-side CUDA code, unless someone passed
9252     // -fcuda-allow-variadic-functions.
9253     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9254         (NewFD->hasAttr<CUDADeviceAttr>() ||
9255          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9256         !(II && II->isStr("printf") && NewFD->isExternC() &&
9257           !D.isFunctionDefinition())) {
9258       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9259     }
9260   }
9261 
9262   MarkUnusedFileScopedDecl(NewFD);
9263 
9264 
9265 
9266   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9267     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9268     if ((getLangOpts().OpenCLVersion >= 120)
9269         && (SC == SC_Static)) {
9270       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9271       D.setInvalidType();
9272     }
9273 
9274     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9275     if (!NewFD->getReturnType()->isVoidType()) {
9276       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9277       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9278           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9279                                 : FixItHint());
9280       D.setInvalidType();
9281     }
9282 
9283     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9284     for (auto Param : NewFD->parameters())
9285       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9286 
9287     if (getLangOpts().OpenCLCPlusPlus) {
9288       if (DC->isRecord()) {
9289         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9290         D.setInvalidType();
9291       }
9292       if (FunctionTemplate) {
9293         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9294         D.setInvalidType();
9295       }
9296     }
9297   }
9298 
9299   if (getLangOpts().CPlusPlus) {
9300     if (FunctionTemplate) {
9301       if (NewFD->isInvalidDecl())
9302         FunctionTemplate->setInvalidDecl();
9303       return FunctionTemplate;
9304     }
9305 
9306     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9307       CompleteMemberSpecialization(NewFD, Previous);
9308   }
9309 
9310   for (const ParmVarDecl *Param : NewFD->parameters()) {
9311     QualType PT = Param->getType();
9312 
9313     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9314     // types.
9315     if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
9316       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9317         QualType ElemTy = PipeTy->getElementType();
9318           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9319             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9320             D.setInvalidType();
9321           }
9322       }
9323     }
9324   }
9325 
9326   // Here we have an function template explicit specialization at class scope.
9327   // The actual specialization will be postponed to template instatiation
9328   // time via the ClassScopeFunctionSpecializationDecl node.
9329   if (isDependentClassScopeExplicitSpecialization) {
9330     ClassScopeFunctionSpecializationDecl *NewSpec =
9331                          ClassScopeFunctionSpecializationDecl::Create(
9332                                 Context, CurContext, NewFD->getLocation(),
9333                                 cast<CXXMethodDecl>(NewFD),
9334                                 HasExplicitTemplateArgs, TemplateArgs);
9335     CurContext->addDecl(NewSpec);
9336     AddToScope = false;
9337   }
9338 
9339   // Diagnose availability attributes. Availability cannot be used on functions
9340   // that are run during load/unload.
9341   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9342     if (NewFD->hasAttr<ConstructorAttr>()) {
9343       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9344           << 1;
9345       NewFD->dropAttr<AvailabilityAttr>();
9346     }
9347     if (NewFD->hasAttr<DestructorAttr>()) {
9348       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9349           << 2;
9350       NewFD->dropAttr<AvailabilityAttr>();
9351     }
9352   }
9353 
9354   return NewFD;
9355 }
9356 
9357 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
9358 /// when __declspec(code_seg) "is applied to a class, all member functions of
9359 /// the class and nested classes -- this includes compiler-generated special
9360 /// member functions -- are put in the specified segment."
9361 /// The actual behavior is a little more complicated. The Microsoft compiler
9362 /// won't check outer classes if there is an active value from #pragma code_seg.
9363 /// The CodeSeg is always applied from the direct parent but only from outer
9364 /// classes when the #pragma code_seg stack is empty. See:
9365 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9366 /// available since MS has removed the page.
9367 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9368   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9369   if (!Method)
9370     return nullptr;
9371   const CXXRecordDecl *Parent = Method->getParent();
9372   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9373     Attr *NewAttr = SAttr->clone(S.getASTContext());
9374     NewAttr->setImplicit(true);
9375     return NewAttr;
9376   }
9377 
9378   // The Microsoft compiler won't check outer classes for the CodeSeg
9379   // when the #pragma code_seg stack is active.
9380   if (S.CodeSegStack.CurrentValue)
9381    return nullptr;
9382 
9383   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9384     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9385       Attr *NewAttr = SAttr->clone(S.getASTContext());
9386       NewAttr->setImplicit(true);
9387       return NewAttr;
9388     }
9389   }
9390   return nullptr;
9391 }
9392 
9393 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9394 /// containing class. Otherwise it will return implicit SectionAttr if the
9395 /// function is a definition and there is an active value on CodeSegStack
9396 /// (from the current #pragma code-seg value).
9397 ///
9398 /// \param FD Function being declared.
9399 /// \param IsDefinition Whether it is a definition or just a declarartion.
9400 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
9401 ///          nullptr if no attribute should be added.
9402 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9403                                                        bool IsDefinition) {
9404   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9405     return A;
9406   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9407       CodeSegStack.CurrentValue) {
9408     return SectionAttr::CreateImplicit(getASTContext(),
9409                                        SectionAttr::Declspec_allocate,
9410                                        CodeSegStack.CurrentValue->getString(),
9411                                        CodeSegStack.CurrentPragmaLocation);
9412   }
9413   return nullptr;
9414 }
9415 
9416 /// Determines if we can perform a correct type check for \p D as a
9417 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
9418 /// best-effort check.
9419 ///
9420 /// \param NewD The new declaration.
9421 /// \param OldD The old declaration.
9422 /// \param NewT The portion of the type of the new declaration to check.
9423 /// \param OldT The portion of the type of the old declaration to check.
9424 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
9425                                           QualType NewT, QualType OldT) {
9426   if (!NewD->getLexicalDeclContext()->isDependentContext())
9427     return true;
9428 
9429   // For dependently-typed local extern declarations and friends, we can't
9430   // perform a correct type check in general until instantiation:
9431   //
9432   //   int f();
9433   //   template<typename T> void g() { T f(); }
9434   //
9435   // (valid if g() is only instantiated with T = int).
9436   if (NewT->isDependentType() &&
9437       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
9438     return false;
9439 
9440   // Similarly, if the previous declaration was a dependent local extern
9441   // declaration, we don't really know its type yet.
9442   if (OldT->isDependentType() && OldD->isLocalExternDecl())
9443     return false;
9444 
9445   return true;
9446 }
9447 
9448 /// Checks if the new declaration declared in dependent context must be
9449 /// put in the same redeclaration chain as the specified declaration.
9450 ///
9451 /// \param D Declaration that is checked.
9452 /// \param PrevDecl Previous declaration found with proper lookup method for the
9453 ///                 same declaration name.
9454 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9455 ///          belongs to.
9456 ///
9457 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9458   if (!D->getLexicalDeclContext()->isDependentContext())
9459     return true;
9460 
9461   // Don't chain dependent friend function definitions until instantiation, to
9462   // permit cases like
9463   //
9464   //   void func();
9465   //   template<typename T> class C1 { friend void func() {} };
9466   //   template<typename T> class C2 { friend void func() {} };
9467   //
9468   // ... which is valid if only one of C1 and C2 is ever instantiated.
9469   //
9470   // FIXME: This need only apply to function definitions. For now, we proxy
9471   // this by checking for a file-scope function. We do not want this to apply
9472   // to friend declarations nominating member functions, because that gets in
9473   // the way of access checks.
9474   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
9475     return false;
9476 
9477   auto *VD = dyn_cast<ValueDecl>(D);
9478   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
9479   return !VD || !PrevVD ||
9480          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
9481                                         PrevVD->getType());
9482 }
9483 
9484 /// Check the target attribute of the function for MultiVersion
9485 /// validity.
9486 ///
9487 /// Returns true if there was an error, false otherwise.
9488 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9489   const auto *TA = FD->getAttr<TargetAttr>();
9490   assert(TA && "MultiVersion Candidate requires a target attribute");
9491   TargetAttr::ParsedTargetAttr ParseInfo = TA->parse();
9492   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9493   enum ErrType { Feature = 0, Architecture = 1 };
9494 
9495   if (!ParseInfo.Architecture.empty() &&
9496       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
9497     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9498         << Architecture << ParseInfo.Architecture;
9499     return true;
9500   }
9501 
9502   for (const auto &Feat : ParseInfo.Features) {
9503     auto BareFeat = StringRef{Feat}.substr(1);
9504     if (Feat[0] == '-') {
9505       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9506           << Feature << ("no-" + BareFeat).str();
9507       return true;
9508     }
9509 
9510     if (!TargetInfo.validateCpuSupports(BareFeat) ||
9511         !TargetInfo.isValidFeatureName(BareFeat)) {
9512       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9513           << Feature << BareFeat;
9514       return true;
9515     }
9516   }
9517   return false;
9518 }
9519 
9520 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD,
9521                                          MultiVersionKind MVType) {
9522   for (const Attr *A : FD->attrs()) {
9523     switch (A->getKind()) {
9524     case attr::CPUDispatch:
9525     case attr::CPUSpecific:
9526       if (MVType != MultiVersionKind::CPUDispatch &&
9527           MVType != MultiVersionKind::CPUSpecific)
9528         return true;
9529       break;
9530     case attr::Target:
9531       if (MVType != MultiVersionKind::Target)
9532         return true;
9533       break;
9534     default:
9535       return true;
9536     }
9537   }
9538   return false;
9539 }
9540 
9541 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
9542                                              const FunctionDecl *NewFD,
9543                                              bool CausesMV,
9544                                              MultiVersionKind MVType) {
9545   enum DoesntSupport {
9546     FuncTemplates = 0,
9547     VirtFuncs = 1,
9548     DeducedReturn = 2,
9549     Constructors = 3,
9550     Destructors = 4,
9551     DeletedFuncs = 5,
9552     DefaultedFuncs = 6,
9553     ConstexprFuncs = 7,
9554     ConstevalFuncs = 8,
9555   };
9556   enum Different {
9557     CallingConv = 0,
9558     ReturnType = 1,
9559     ConstexprSpec = 2,
9560     InlineSpec = 3,
9561     StorageClass = 4,
9562     Linkage = 5
9563   };
9564 
9565   bool IsCPUSpecificCPUDispatchMVType =
9566       MVType == MultiVersionKind::CPUDispatch ||
9567       MVType == MultiVersionKind::CPUSpecific;
9568 
9569   if (OldFD && !OldFD->getType()->getAs<FunctionProtoType>()) {
9570     S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto);
9571     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9572     return true;
9573   }
9574 
9575   if (!NewFD->getType()->getAs<FunctionProtoType>())
9576     return S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto);
9577 
9578   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9579     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9580     if (OldFD)
9581       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9582     return true;
9583   }
9584 
9585   // For now, disallow all other attributes.  These should be opt-in, but
9586   // an analysis of all of them is a future FIXME.
9587   if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) {
9588     S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
9589         << IsCPUSpecificCPUDispatchMVType;
9590     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9591     return true;
9592   }
9593 
9594   if (HasNonMultiVersionAttributes(NewFD, MVType))
9595     return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
9596            << IsCPUSpecificCPUDispatchMVType;
9597 
9598   if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9599     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9600            << IsCPUSpecificCPUDispatchMVType << FuncTemplates;
9601 
9602   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
9603     if (NewCXXFD->isVirtual())
9604       return S.Diag(NewCXXFD->getLocation(),
9605                     diag::err_multiversion_doesnt_support)
9606              << IsCPUSpecificCPUDispatchMVType << VirtFuncs;
9607 
9608     if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD))
9609       return S.Diag(NewCXXCtor->getLocation(),
9610                     diag::err_multiversion_doesnt_support)
9611              << IsCPUSpecificCPUDispatchMVType << Constructors;
9612 
9613     if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD))
9614       return S.Diag(NewCXXDtor->getLocation(),
9615                     diag::err_multiversion_doesnt_support)
9616              << IsCPUSpecificCPUDispatchMVType << Destructors;
9617   }
9618 
9619   if (NewFD->isDeleted())
9620     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9621            << IsCPUSpecificCPUDispatchMVType << DeletedFuncs;
9622 
9623   if (NewFD->isDefaulted())
9624     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9625            << IsCPUSpecificCPUDispatchMVType << DefaultedFuncs;
9626 
9627   if (NewFD->isConstexpr() && (MVType == MultiVersionKind::CPUDispatch ||
9628                                MVType == MultiVersionKind::CPUSpecific))
9629     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9630            << IsCPUSpecificCPUDispatchMVType
9631            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
9632 
9633   QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType());
9634   const auto *NewType = cast<FunctionType>(NewQType);
9635   QualType NewReturnType = NewType->getReturnType();
9636 
9637   if (NewReturnType->isUndeducedType())
9638     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9639            << IsCPUSpecificCPUDispatchMVType << DeducedReturn;
9640 
9641   // Only allow transition to MultiVersion if it hasn't been used.
9642   if (OldFD && CausesMV && OldFD->isUsed(false))
9643     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
9644 
9645   // Ensure the return type is identical.
9646   if (OldFD) {
9647     QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType());
9648     const auto *OldType = cast<FunctionType>(OldQType);
9649     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
9650     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
9651 
9652     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
9653       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9654              << CallingConv;
9655 
9656     QualType OldReturnType = OldType->getReturnType();
9657 
9658     if (OldReturnType != NewReturnType)
9659       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9660              << ReturnType;
9661 
9662     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
9663       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9664              << ConstexprSpec;
9665 
9666     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
9667       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9668              << InlineSpec;
9669 
9670     if (OldFD->getStorageClass() != NewFD->getStorageClass())
9671       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9672              << StorageClass;
9673 
9674     if (OldFD->isExternC() != NewFD->isExternC())
9675       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9676              << Linkage;
9677 
9678     if (S.CheckEquivalentExceptionSpec(
9679             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
9680             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
9681       return true;
9682   }
9683   return false;
9684 }
9685 
9686 /// Check the validity of a multiversion function declaration that is the
9687 /// first of its kind. Also sets the multiversion'ness' of the function itself.
9688 ///
9689 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9690 ///
9691 /// Returns true if there was an error, false otherwise.
9692 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
9693                                            MultiVersionKind MVType,
9694                                            const TargetAttr *TA) {
9695   assert(MVType != MultiVersionKind::None &&
9696          "Function lacks multiversion attribute");
9697 
9698   // Target only causes MV if it is default, otherwise this is a normal
9699   // function.
9700   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
9701     return false;
9702 
9703   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
9704     FD->setInvalidDecl();
9705     return true;
9706   }
9707 
9708   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
9709     FD->setInvalidDecl();
9710     return true;
9711   }
9712 
9713   FD->setIsMultiVersion();
9714   return false;
9715 }
9716 
9717 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
9718   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
9719     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
9720       return true;
9721   }
9722 
9723   return false;
9724 }
9725 
9726 static bool CheckTargetCausesMultiVersioning(
9727     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
9728     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
9729     LookupResult &Previous) {
9730   const auto *OldTA = OldFD->getAttr<TargetAttr>();
9731   TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse();
9732   // Sort order doesn't matter, it just needs to be consistent.
9733   llvm::sort(NewParsed.Features);
9734 
9735   // If the old decl is NOT MultiVersioned yet, and we don't cause that
9736   // to change, this is a simple redeclaration.
9737   if (!NewTA->isDefaultVersion() &&
9738       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
9739     return false;
9740 
9741   // Otherwise, this decl causes MultiVersioning.
9742   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9743     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9744     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9745     NewFD->setInvalidDecl();
9746     return true;
9747   }
9748 
9749   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
9750                                        MultiVersionKind::Target)) {
9751     NewFD->setInvalidDecl();
9752     return true;
9753   }
9754 
9755   if (CheckMultiVersionValue(S, NewFD)) {
9756     NewFD->setInvalidDecl();
9757     return true;
9758   }
9759 
9760   // If this is 'default', permit the forward declaration.
9761   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
9762     Redeclaration = true;
9763     OldDecl = OldFD;
9764     OldFD->setIsMultiVersion();
9765     NewFD->setIsMultiVersion();
9766     return false;
9767   }
9768 
9769   if (CheckMultiVersionValue(S, OldFD)) {
9770     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9771     NewFD->setInvalidDecl();
9772     return true;
9773   }
9774 
9775   TargetAttr::ParsedTargetAttr OldParsed =
9776       OldTA->parse(std::less<std::string>());
9777 
9778   if (OldParsed == NewParsed) {
9779     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9780     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9781     NewFD->setInvalidDecl();
9782     return true;
9783   }
9784 
9785   for (const auto *FD : OldFD->redecls()) {
9786     const auto *CurTA = FD->getAttr<TargetAttr>();
9787     // We allow forward declarations before ANY multiversioning attributes, but
9788     // nothing after the fact.
9789     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
9790         (!CurTA || CurTA->isInherited())) {
9791       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
9792           << 0;
9793       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9794       NewFD->setInvalidDecl();
9795       return true;
9796     }
9797   }
9798 
9799   OldFD->setIsMultiVersion();
9800   NewFD->setIsMultiVersion();
9801   Redeclaration = false;
9802   MergeTypeWithPrevious = false;
9803   OldDecl = nullptr;
9804   Previous.clear();
9805   return false;
9806 }
9807 
9808 /// Check the validity of a new function declaration being added to an existing
9809 /// multiversioned declaration collection.
9810 static bool CheckMultiVersionAdditionalDecl(
9811     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
9812     MultiVersionKind NewMVType, const TargetAttr *NewTA,
9813     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
9814     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
9815     LookupResult &Previous) {
9816 
9817   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
9818   // Disallow mixing of multiversioning types.
9819   if ((OldMVType == MultiVersionKind::Target &&
9820        NewMVType != MultiVersionKind::Target) ||
9821       (NewMVType == MultiVersionKind::Target &&
9822        OldMVType != MultiVersionKind::Target)) {
9823     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
9824     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9825     NewFD->setInvalidDecl();
9826     return true;
9827   }
9828 
9829   TargetAttr::ParsedTargetAttr NewParsed;
9830   if (NewTA) {
9831     NewParsed = NewTA->parse();
9832     llvm::sort(NewParsed.Features);
9833   }
9834 
9835   bool UseMemberUsingDeclRules =
9836       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
9837 
9838   // Next, check ALL non-overloads to see if this is a redeclaration of a
9839   // previous member of the MultiVersion set.
9840   for (NamedDecl *ND : Previous) {
9841     FunctionDecl *CurFD = ND->getAsFunction();
9842     if (!CurFD)
9843       continue;
9844     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
9845       continue;
9846 
9847     if (NewMVType == MultiVersionKind::Target) {
9848       const auto *CurTA = CurFD->getAttr<TargetAttr>();
9849       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
9850         NewFD->setIsMultiVersion();
9851         Redeclaration = true;
9852         OldDecl = ND;
9853         return false;
9854       }
9855 
9856       TargetAttr::ParsedTargetAttr CurParsed =
9857           CurTA->parse(std::less<std::string>());
9858       if (CurParsed == NewParsed) {
9859         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9860         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9861         NewFD->setInvalidDecl();
9862         return true;
9863       }
9864     } else {
9865       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
9866       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
9867       // Handle CPUDispatch/CPUSpecific versions.
9868       // Only 1 CPUDispatch function is allowed, this will make it go through
9869       // the redeclaration errors.
9870       if (NewMVType == MultiVersionKind::CPUDispatch &&
9871           CurFD->hasAttr<CPUDispatchAttr>()) {
9872         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
9873             std::equal(
9874                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
9875                 NewCPUDisp->cpus_begin(),
9876                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
9877                   return Cur->getName() == New->getName();
9878                 })) {
9879           NewFD->setIsMultiVersion();
9880           Redeclaration = true;
9881           OldDecl = ND;
9882           return false;
9883         }
9884 
9885         // If the declarations don't match, this is an error condition.
9886         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
9887         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9888         NewFD->setInvalidDecl();
9889         return true;
9890       }
9891       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
9892 
9893         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
9894             std::equal(
9895                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
9896                 NewCPUSpec->cpus_begin(),
9897                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
9898                   return Cur->getName() == New->getName();
9899                 })) {
9900           NewFD->setIsMultiVersion();
9901           Redeclaration = true;
9902           OldDecl = ND;
9903           return false;
9904         }
9905 
9906         // Only 1 version of CPUSpecific is allowed for each CPU.
9907         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
9908           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
9909             if (CurII == NewII) {
9910               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
9911                   << NewII;
9912               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9913               NewFD->setInvalidDecl();
9914               return true;
9915             }
9916           }
9917         }
9918       }
9919       // If the two decls aren't the same MVType, there is no possible error
9920       // condition.
9921     }
9922   }
9923 
9924   // Else, this is simply a non-redecl case.  Checking the 'value' is only
9925   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
9926   // handled in the attribute adding step.
9927   if (NewMVType == MultiVersionKind::Target &&
9928       CheckMultiVersionValue(S, NewFD)) {
9929     NewFD->setInvalidDecl();
9930     return true;
9931   }
9932 
9933   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
9934                                        !OldFD->isMultiVersion(), NewMVType)) {
9935     NewFD->setInvalidDecl();
9936     return true;
9937   }
9938 
9939   // Permit forward declarations in the case where these two are compatible.
9940   if (!OldFD->isMultiVersion()) {
9941     OldFD->setIsMultiVersion();
9942     NewFD->setIsMultiVersion();
9943     Redeclaration = true;
9944     OldDecl = OldFD;
9945     return false;
9946   }
9947 
9948   NewFD->setIsMultiVersion();
9949   Redeclaration = false;
9950   MergeTypeWithPrevious = false;
9951   OldDecl = nullptr;
9952   Previous.clear();
9953   return false;
9954 }
9955 
9956 
9957 /// Check the validity of a mulitversion function declaration.
9958 /// Also sets the multiversion'ness' of the function itself.
9959 ///
9960 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9961 ///
9962 /// Returns true if there was an error, false otherwise.
9963 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
9964                                       bool &Redeclaration, NamedDecl *&OldDecl,
9965                                       bool &MergeTypeWithPrevious,
9966                                       LookupResult &Previous) {
9967   const auto *NewTA = NewFD->getAttr<TargetAttr>();
9968   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
9969   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
9970 
9971   // Mixing Multiversioning types is prohibited.
9972   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
9973       (NewCPUDisp && NewCPUSpec)) {
9974     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
9975     NewFD->setInvalidDecl();
9976     return true;
9977   }
9978 
9979   MultiVersionKind  MVType = NewFD->getMultiVersionKind();
9980 
9981   // Main isn't allowed to become a multiversion function, however it IS
9982   // permitted to have 'main' be marked with the 'target' optimization hint.
9983   if (NewFD->isMain()) {
9984     if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
9985         MVType == MultiVersionKind::CPUDispatch ||
9986         MVType == MultiVersionKind::CPUSpecific) {
9987       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
9988       NewFD->setInvalidDecl();
9989       return true;
9990     }
9991     return false;
9992   }
9993 
9994   if (!OldDecl || !OldDecl->getAsFunction() ||
9995       OldDecl->getDeclContext()->getRedeclContext() !=
9996           NewFD->getDeclContext()->getRedeclContext()) {
9997     // If there's no previous declaration, AND this isn't attempting to cause
9998     // multiversioning, this isn't an error condition.
9999     if (MVType == MultiVersionKind::None)
10000       return false;
10001     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10002   }
10003 
10004   FunctionDecl *OldFD = OldDecl->getAsFunction();
10005 
10006   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10007     return false;
10008 
10009   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10010     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10011         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10012     NewFD->setInvalidDecl();
10013     return true;
10014   }
10015 
10016   // Handle the target potentially causes multiversioning case.
10017   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10018     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10019                                             Redeclaration, OldDecl,
10020                                             MergeTypeWithPrevious, Previous);
10021 
10022   // At this point, we have a multiversion function decl (in OldFD) AND an
10023   // appropriate attribute in the current function decl.  Resolve that these are
10024   // still compatible with previous declarations.
10025   return CheckMultiVersionAdditionalDecl(
10026       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10027       OldDecl, MergeTypeWithPrevious, Previous);
10028 }
10029 
10030 /// Perform semantic checking of a new function declaration.
10031 ///
10032 /// Performs semantic analysis of the new function declaration
10033 /// NewFD. This routine performs all semantic checking that does not
10034 /// require the actual declarator involved in the declaration, and is
10035 /// used both for the declaration of functions as they are parsed
10036 /// (called via ActOnDeclarator) and for the declaration of functions
10037 /// that have been instantiated via C++ template instantiation (called
10038 /// via InstantiateDecl).
10039 ///
10040 /// \param IsMemberSpecialization whether this new function declaration is
10041 /// a member specialization (that replaces any definition provided by the
10042 /// previous declaration).
10043 ///
10044 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10045 ///
10046 /// \returns true if the function declaration is a redeclaration.
10047 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10048                                     LookupResult &Previous,
10049                                     bool IsMemberSpecialization) {
10050   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10051          "Variably modified return types are not handled here");
10052 
10053   // Determine whether the type of this function should be merged with
10054   // a previous visible declaration. This never happens for functions in C++,
10055   // and always happens in C if the previous declaration was visible.
10056   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10057                                !Previous.isShadowed();
10058 
10059   bool Redeclaration = false;
10060   NamedDecl *OldDecl = nullptr;
10061   bool MayNeedOverloadableChecks = false;
10062 
10063   // Merge or overload the declaration with an existing declaration of
10064   // the same name, if appropriate.
10065   if (!Previous.empty()) {
10066     // Determine whether NewFD is an overload of PrevDecl or
10067     // a declaration that requires merging. If it's an overload,
10068     // there's no more work to do here; we'll just add the new
10069     // function to the scope.
10070     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10071       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10072       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10073         Redeclaration = true;
10074         OldDecl = Candidate;
10075       }
10076     } else {
10077       MayNeedOverloadableChecks = true;
10078       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10079                             /*NewIsUsingDecl*/ false)) {
10080       case Ovl_Match:
10081         Redeclaration = true;
10082         break;
10083 
10084       case Ovl_NonFunction:
10085         Redeclaration = true;
10086         break;
10087 
10088       case Ovl_Overload:
10089         Redeclaration = false;
10090         break;
10091       }
10092     }
10093   }
10094 
10095   // Check for a previous extern "C" declaration with this name.
10096   if (!Redeclaration &&
10097       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10098     if (!Previous.empty()) {
10099       // This is an extern "C" declaration with the same name as a previous
10100       // declaration, and thus redeclares that entity...
10101       Redeclaration = true;
10102       OldDecl = Previous.getFoundDecl();
10103       MergeTypeWithPrevious = false;
10104 
10105       // ... except in the presence of __attribute__((overloadable)).
10106       if (OldDecl->hasAttr<OverloadableAttr>() ||
10107           NewFD->hasAttr<OverloadableAttr>()) {
10108         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10109           MayNeedOverloadableChecks = true;
10110           Redeclaration = false;
10111           OldDecl = nullptr;
10112         }
10113       }
10114     }
10115   }
10116 
10117   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10118                                 MergeTypeWithPrevious, Previous))
10119     return Redeclaration;
10120 
10121   // C++11 [dcl.constexpr]p8:
10122   //   A constexpr specifier for a non-static member function that is not
10123   //   a constructor declares that member function to be const.
10124   //
10125   // This needs to be delayed until we know whether this is an out-of-line
10126   // definition of a static member function.
10127   //
10128   // This rule is not present in C++1y, so we produce a backwards
10129   // compatibility warning whenever it happens in C++11.
10130   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10131   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10132       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10133       !MD->getMethodQualifiers().hasConst()) {
10134     CXXMethodDecl *OldMD = nullptr;
10135     if (OldDecl)
10136       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10137     if (!OldMD || !OldMD->isStatic()) {
10138       const FunctionProtoType *FPT =
10139         MD->getType()->castAs<FunctionProtoType>();
10140       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10141       EPI.TypeQuals.addConst();
10142       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10143                                           FPT->getParamTypes(), EPI));
10144 
10145       // Warn that we did this, if we're not performing template instantiation.
10146       // In that case, we'll have warned already when the template was defined.
10147       if (!inTemplateInstantiation()) {
10148         SourceLocation AddConstLoc;
10149         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10150                 .IgnoreParens().getAs<FunctionTypeLoc>())
10151           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10152 
10153         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10154           << FixItHint::CreateInsertion(AddConstLoc, " const");
10155       }
10156     }
10157   }
10158 
10159   if (Redeclaration) {
10160     // NewFD and OldDecl represent declarations that need to be
10161     // merged.
10162     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10163       NewFD->setInvalidDecl();
10164       return Redeclaration;
10165     }
10166 
10167     Previous.clear();
10168     Previous.addDecl(OldDecl);
10169 
10170     if (FunctionTemplateDecl *OldTemplateDecl =
10171             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10172       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10173       FunctionTemplateDecl *NewTemplateDecl
10174         = NewFD->getDescribedFunctionTemplate();
10175       assert(NewTemplateDecl && "Template/non-template mismatch");
10176 
10177       // The call to MergeFunctionDecl above may have created some state in
10178       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10179       // can add it as a redeclaration.
10180       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10181 
10182       NewFD->setPreviousDeclaration(OldFD);
10183       adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10184       if (NewFD->isCXXClassMember()) {
10185         NewFD->setAccess(OldTemplateDecl->getAccess());
10186         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10187       }
10188 
10189       // If this is an explicit specialization of a member that is a function
10190       // template, mark it as a member specialization.
10191       if (IsMemberSpecialization &&
10192           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10193         NewTemplateDecl->setMemberSpecialization();
10194         assert(OldTemplateDecl->isMemberSpecialization());
10195         // Explicit specializations of a member template do not inherit deleted
10196         // status from the parent member template that they are specializing.
10197         if (OldFD->isDeleted()) {
10198           // FIXME: This assert will not hold in the presence of modules.
10199           assert(OldFD->getCanonicalDecl() == OldFD);
10200           // FIXME: We need an update record for this AST mutation.
10201           OldFD->setDeletedAsWritten(false);
10202         }
10203       }
10204 
10205     } else {
10206       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10207         auto *OldFD = cast<FunctionDecl>(OldDecl);
10208         // This needs to happen first so that 'inline' propagates.
10209         NewFD->setPreviousDeclaration(OldFD);
10210         adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10211         if (NewFD->isCXXClassMember())
10212           NewFD->setAccess(OldFD->getAccess());
10213       }
10214     }
10215   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10216              !NewFD->getAttr<OverloadableAttr>()) {
10217     assert((Previous.empty() ||
10218             llvm::any_of(Previous,
10219                          [](const NamedDecl *ND) {
10220                            return ND->hasAttr<OverloadableAttr>();
10221                          })) &&
10222            "Non-redecls shouldn't happen without overloadable present");
10223 
10224     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10225       const auto *FD = dyn_cast<FunctionDecl>(ND);
10226       return FD && !FD->hasAttr<OverloadableAttr>();
10227     });
10228 
10229     if (OtherUnmarkedIter != Previous.end()) {
10230       Diag(NewFD->getLocation(),
10231            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10232       Diag((*OtherUnmarkedIter)->getLocation(),
10233            diag::note_attribute_overloadable_prev_overload)
10234           << false;
10235 
10236       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10237     }
10238   }
10239 
10240   // Semantic checking for this function declaration (in isolation).
10241 
10242   if (getLangOpts().CPlusPlus) {
10243     // C++-specific checks.
10244     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10245       CheckConstructor(Constructor);
10246     } else if (CXXDestructorDecl *Destructor =
10247                 dyn_cast<CXXDestructorDecl>(NewFD)) {
10248       CXXRecordDecl *Record = Destructor->getParent();
10249       QualType ClassType = Context.getTypeDeclType(Record);
10250 
10251       // FIXME: Shouldn't we be able to perform this check even when the class
10252       // type is dependent? Both gcc and edg can handle that.
10253       if (!ClassType->isDependentType()) {
10254         DeclarationName Name
10255           = Context.DeclarationNames.getCXXDestructorName(
10256                                         Context.getCanonicalType(ClassType));
10257         if (NewFD->getDeclName() != Name) {
10258           Diag(NewFD->getLocation(), diag::err_destructor_name);
10259           NewFD->setInvalidDecl();
10260           return Redeclaration;
10261         }
10262       }
10263     } else if (CXXConversionDecl *Conversion
10264                = dyn_cast<CXXConversionDecl>(NewFD)) {
10265       ActOnConversionDeclarator(Conversion);
10266     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10267       if (auto *TD = Guide->getDescribedFunctionTemplate())
10268         CheckDeductionGuideTemplate(TD);
10269 
10270       // A deduction guide is not on the list of entities that can be
10271       // explicitly specialized.
10272       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10273         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10274             << /*explicit specialization*/ 1;
10275     }
10276 
10277     // Find any virtual functions that this function overrides.
10278     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10279       if (!Method->isFunctionTemplateSpecialization() &&
10280           !Method->getDescribedFunctionTemplate() &&
10281           Method->isCanonicalDecl()) {
10282         if (AddOverriddenMethods(Method->getParent(), Method)) {
10283           // If the function was marked as "static", we have a problem.
10284           if (NewFD->getStorageClass() == SC_Static) {
10285             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
10286           }
10287         }
10288       }
10289 
10290       if (Method->isStatic())
10291         checkThisInStaticMemberFunctionType(Method);
10292     }
10293 
10294     // Extra checking for C++ overloaded operators (C++ [over.oper]).
10295     if (NewFD->isOverloadedOperator() &&
10296         CheckOverloadedOperatorDeclaration(NewFD)) {
10297       NewFD->setInvalidDecl();
10298       return Redeclaration;
10299     }
10300 
10301     // Extra checking for C++0x literal operators (C++0x [over.literal]).
10302     if (NewFD->getLiteralIdentifier() &&
10303         CheckLiteralOperatorDeclaration(NewFD)) {
10304       NewFD->setInvalidDecl();
10305       return Redeclaration;
10306     }
10307 
10308     // In C++, check default arguments now that we have merged decls. Unless
10309     // the lexical context is the class, because in this case this is done
10310     // during delayed parsing anyway.
10311     if (!CurContext->isRecord())
10312       CheckCXXDefaultArguments(NewFD);
10313 
10314     // If this function declares a builtin function, check the type of this
10315     // declaration against the expected type for the builtin.
10316     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10317       ASTContext::GetBuiltinTypeError Error;
10318       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
10319       QualType T = Context.GetBuiltinType(BuiltinID, Error);
10320       // If the type of the builtin differs only in its exception
10321       // specification, that's OK.
10322       // FIXME: If the types do differ in this way, it would be better to
10323       // retain the 'noexcept' form of the type.
10324       if (!T.isNull() &&
10325           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10326                                                             NewFD->getType()))
10327         // The type of this function differs from the type of the builtin,
10328         // so forget about the builtin entirely.
10329         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10330     }
10331 
10332     // If this function is declared as being extern "C", then check to see if
10333     // the function returns a UDT (class, struct, or union type) that is not C
10334     // compatible, and if it does, warn the user.
10335     // But, issue any diagnostic on the first declaration only.
10336     if (Previous.empty() && NewFD->isExternC()) {
10337       QualType R = NewFD->getReturnType();
10338       if (R->isIncompleteType() && !R->isVoidType())
10339         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10340             << NewFD << R;
10341       else if (!R.isPODType(Context) && !R->isVoidType() &&
10342                !R->isObjCObjectPointerType())
10343         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10344     }
10345 
10346     // C++1z [dcl.fct]p6:
10347     //   [...] whether the function has a non-throwing exception-specification
10348     //   [is] part of the function type
10349     //
10350     // This results in an ABI break between C++14 and C++17 for functions whose
10351     // declared type includes an exception-specification in a parameter or
10352     // return type. (Exception specifications on the function itself are OK in
10353     // most cases, and exception specifications are not permitted in most other
10354     // contexts where they could make it into a mangling.)
10355     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10356       auto HasNoexcept = [&](QualType T) -> bool {
10357         // Strip off declarator chunks that could be between us and a function
10358         // type. We don't need to look far, exception specifications are very
10359         // restricted prior to C++17.
10360         if (auto *RT = T->getAs<ReferenceType>())
10361           T = RT->getPointeeType();
10362         else if (T->isAnyPointerType())
10363           T = T->getPointeeType();
10364         else if (auto *MPT = T->getAs<MemberPointerType>())
10365           T = MPT->getPointeeType();
10366         if (auto *FPT = T->getAs<FunctionProtoType>())
10367           if (FPT->isNothrow())
10368             return true;
10369         return false;
10370       };
10371 
10372       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10373       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10374       for (QualType T : FPT->param_types())
10375         AnyNoexcept |= HasNoexcept(T);
10376       if (AnyNoexcept)
10377         Diag(NewFD->getLocation(),
10378              diag::warn_cxx17_compat_exception_spec_in_signature)
10379             << NewFD;
10380     }
10381 
10382     if (!Redeclaration && LangOpts.CUDA)
10383       checkCUDATargetOverload(NewFD, Previous);
10384   }
10385   return Redeclaration;
10386 }
10387 
10388 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10389   // C++11 [basic.start.main]p3:
10390   //   A program that [...] declares main to be inline, static or
10391   //   constexpr is ill-formed.
10392   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
10393   //   appear in a declaration of main.
10394   // static main is not an error under C99, but we should warn about it.
10395   // We accept _Noreturn main as an extension.
10396   if (FD->getStorageClass() == SC_Static)
10397     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10398          ? diag::err_static_main : diag::warn_static_main)
10399       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10400   if (FD->isInlineSpecified())
10401     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10402       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10403   if (DS.isNoreturnSpecified()) {
10404     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10405     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10406     Diag(NoreturnLoc, diag::ext_noreturn_main);
10407     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10408       << FixItHint::CreateRemoval(NoreturnRange);
10409   }
10410   if (FD->isConstexpr()) {
10411     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10412         << FD->isConsteval()
10413         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10414     FD->setConstexprKind(CSK_unspecified);
10415   }
10416 
10417   if (getLangOpts().OpenCL) {
10418     Diag(FD->getLocation(), diag::err_opencl_no_main)
10419         << FD->hasAttr<OpenCLKernelAttr>();
10420     FD->setInvalidDecl();
10421     return;
10422   }
10423 
10424   QualType T = FD->getType();
10425   assert(T->isFunctionType() && "function decl is not of function type");
10426   const FunctionType* FT = T->castAs<FunctionType>();
10427 
10428   // Set default calling convention for main()
10429   if (FT->getCallConv() != CC_C) {
10430     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10431     FD->setType(QualType(FT, 0));
10432     T = Context.getCanonicalType(FD->getType());
10433   }
10434 
10435   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10436     // In C with GNU extensions we allow main() to have non-integer return
10437     // type, but we should warn about the extension, and we disable the
10438     // implicit-return-zero rule.
10439 
10440     // GCC in C mode accepts qualified 'int'.
10441     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
10442       FD->setHasImplicitReturnZero(true);
10443     else {
10444       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
10445       SourceRange RTRange = FD->getReturnTypeSourceRange();
10446       if (RTRange.isValid())
10447         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
10448             << FixItHint::CreateReplacement(RTRange, "int");
10449     }
10450   } else {
10451     // In C and C++, main magically returns 0 if you fall off the end;
10452     // set the flag which tells us that.
10453     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
10454 
10455     // All the standards say that main() should return 'int'.
10456     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
10457       FD->setHasImplicitReturnZero(true);
10458     else {
10459       // Otherwise, this is just a flat-out error.
10460       SourceRange RTRange = FD->getReturnTypeSourceRange();
10461       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
10462           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
10463                                 : FixItHint());
10464       FD->setInvalidDecl(true);
10465     }
10466   }
10467 
10468   // Treat protoless main() as nullary.
10469   if (isa<FunctionNoProtoType>(FT)) return;
10470 
10471   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
10472   unsigned nparams = FTP->getNumParams();
10473   assert(FD->getNumParams() == nparams);
10474 
10475   bool HasExtraParameters = (nparams > 3);
10476 
10477   if (FTP->isVariadic()) {
10478     Diag(FD->getLocation(), diag::ext_variadic_main);
10479     // FIXME: if we had information about the location of the ellipsis, we
10480     // could add a FixIt hint to remove it as a parameter.
10481   }
10482 
10483   // Darwin passes an undocumented fourth argument of type char**.  If
10484   // other platforms start sprouting these, the logic below will start
10485   // getting shifty.
10486   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
10487     HasExtraParameters = false;
10488 
10489   if (HasExtraParameters) {
10490     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
10491     FD->setInvalidDecl(true);
10492     nparams = 3;
10493   }
10494 
10495   // FIXME: a lot of the following diagnostics would be improved
10496   // if we had some location information about types.
10497 
10498   QualType CharPP =
10499     Context.getPointerType(Context.getPointerType(Context.CharTy));
10500   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
10501 
10502   for (unsigned i = 0; i < nparams; ++i) {
10503     QualType AT = FTP->getParamType(i);
10504 
10505     bool mismatch = true;
10506 
10507     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
10508       mismatch = false;
10509     else if (Expected[i] == CharPP) {
10510       // As an extension, the following forms are okay:
10511       //   char const **
10512       //   char const * const *
10513       //   char * const *
10514 
10515       QualifierCollector qs;
10516       const PointerType* PT;
10517       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
10518           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
10519           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
10520                               Context.CharTy)) {
10521         qs.removeConst();
10522         mismatch = !qs.empty();
10523       }
10524     }
10525 
10526     if (mismatch) {
10527       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
10528       // TODO: suggest replacing given type with expected type
10529       FD->setInvalidDecl(true);
10530     }
10531   }
10532 
10533   if (nparams == 1 && !FD->isInvalidDecl()) {
10534     Diag(FD->getLocation(), diag::warn_main_one_arg);
10535   }
10536 
10537   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10538     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10539     FD->setInvalidDecl();
10540   }
10541 }
10542 
10543 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
10544   QualType T = FD->getType();
10545   assert(T->isFunctionType() && "function decl is not of function type");
10546   const FunctionType *FT = T->castAs<FunctionType>();
10547 
10548   // Set an implicit return of 'zero' if the function can return some integral,
10549   // enumeration, pointer or nullptr type.
10550   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
10551       FT->getReturnType()->isAnyPointerType() ||
10552       FT->getReturnType()->isNullPtrType())
10553     // DllMain is exempt because a return value of zero means it failed.
10554     if (FD->getName() != "DllMain")
10555       FD->setHasImplicitReturnZero(true);
10556 
10557   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10558     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10559     FD->setInvalidDecl();
10560   }
10561 }
10562 
10563 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
10564   // FIXME: Need strict checking.  In C89, we need to check for
10565   // any assignment, increment, decrement, function-calls, or
10566   // commas outside of a sizeof.  In C99, it's the same list,
10567   // except that the aforementioned are allowed in unevaluated
10568   // expressions.  Everything else falls under the
10569   // "may accept other forms of constant expressions" exception.
10570   // (We never end up here for C++, so the constant expression
10571   // rules there don't matter.)
10572   const Expr *Culprit;
10573   if (Init->isConstantInitializer(Context, false, &Culprit))
10574     return false;
10575   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
10576     << Culprit->getSourceRange();
10577   return true;
10578 }
10579 
10580 namespace {
10581   // Visits an initialization expression to see if OrigDecl is evaluated in
10582   // its own initialization and throws a warning if it does.
10583   class SelfReferenceChecker
10584       : public EvaluatedExprVisitor<SelfReferenceChecker> {
10585     Sema &S;
10586     Decl *OrigDecl;
10587     bool isRecordType;
10588     bool isPODType;
10589     bool isReferenceType;
10590 
10591     bool isInitList;
10592     llvm::SmallVector<unsigned, 4> InitFieldIndex;
10593 
10594   public:
10595     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
10596 
10597     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
10598                                                     S(S), OrigDecl(OrigDecl) {
10599       isPODType = false;
10600       isRecordType = false;
10601       isReferenceType = false;
10602       isInitList = false;
10603       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
10604         isPODType = VD->getType().isPODType(S.Context);
10605         isRecordType = VD->getType()->isRecordType();
10606         isReferenceType = VD->getType()->isReferenceType();
10607       }
10608     }
10609 
10610     // For most expressions, just call the visitor.  For initializer lists,
10611     // track the index of the field being initialized since fields are
10612     // initialized in order allowing use of previously initialized fields.
10613     void CheckExpr(Expr *E) {
10614       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
10615       if (!InitList) {
10616         Visit(E);
10617         return;
10618       }
10619 
10620       // Track and increment the index here.
10621       isInitList = true;
10622       InitFieldIndex.push_back(0);
10623       for (auto Child : InitList->children()) {
10624         CheckExpr(cast<Expr>(Child));
10625         ++InitFieldIndex.back();
10626       }
10627       InitFieldIndex.pop_back();
10628     }
10629 
10630     // Returns true if MemberExpr is checked and no further checking is needed.
10631     // Returns false if additional checking is required.
10632     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
10633       llvm::SmallVector<FieldDecl*, 4> Fields;
10634       Expr *Base = E;
10635       bool ReferenceField = false;
10636 
10637       // Get the field members used.
10638       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10639         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
10640         if (!FD)
10641           return false;
10642         Fields.push_back(FD);
10643         if (FD->getType()->isReferenceType())
10644           ReferenceField = true;
10645         Base = ME->getBase()->IgnoreParenImpCasts();
10646       }
10647 
10648       // Keep checking only if the base Decl is the same.
10649       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
10650       if (!DRE || DRE->getDecl() != OrigDecl)
10651         return false;
10652 
10653       // A reference field can be bound to an unininitialized field.
10654       if (CheckReference && !ReferenceField)
10655         return true;
10656 
10657       // Convert FieldDecls to their index number.
10658       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
10659       for (const FieldDecl *I : llvm::reverse(Fields))
10660         UsedFieldIndex.push_back(I->getFieldIndex());
10661 
10662       // See if a warning is needed by checking the first difference in index
10663       // numbers.  If field being used has index less than the field being
10664       // initialized, then the use is safe.
10665       for (auto UsedIter = UsedFieldIndex.begin(),
10666                 UsedEnd = UsedFieldIndex.end(),
10667                 OrigIter = InitFieldIndex.begin(),
10668                 OrigEnd = InitFieldIndex.end();
10669            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
10670         if (*UsedIter < *OrigIter)
10671           return true;
10672         if (*UsedIter > *OrigIter)
10673           break;
10674       }
10675 
10676       // TODO: Add a different warning which will print the field names.
10677       HandleDeclRefExpr(DRE);
10678       return true;
10679     }
10680 
10681     // For most expressions, the cast is directly above the DeclRefExpr.
10682     // For conditional operators, the cast can be outside the conditional
10683     // operator if both expressions are DeclRefExpr's.
10684     void HandleValue(Expr *E) {
10685       E = E->IgnoreParens();
10686       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
10687         HandleDeclRefExpr(DRE);
10688         return;
10689       }
10690 
10691       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
10692         Visit(CO->getCond());
10693         HandleValue(CO->getTrueExpr());
10694         HandleValue(CO->getFalseExpr());
10695         return;
10696       }
10697 
10698       if (BinaryConditionalOperator *BCO =
10699               dyn_cast<BinaryConditionalOperator>(E)) {
10700         Visit(BCO->getCond());
10701         HandleValue(BCO->getFalseExpr());
10702         return;
10703       }
10704 
10705       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
10706         HandleValue(OVE->getSourceExpr());
10707         return;
10708       }
10709 
10710       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10711         if (BO->getOpcode() == BO_Comma) {
10712           Visit(BO->getLHS());
10713           HandleValue(BO->getRHS());
10714           return;
10715         }
10716       }
10717 
10718       if (isa<MemberExpr>(E)) {
10719         if (isInitList) {
10720           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
10721                                       false /*CheckReference*/))
10722             return;
10723         }
10724 
10725         Expr *Base = E->IgnoreParenImpCasts();
10726         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10727           // Check for static member variables and don't warn on them.
10728           if (!isa<FieldDecl>(ME->getMemberDecl()))
10729             return;
10730           Base = ME->getBase()->IgnoreParenImpCasts();
10731         }
10732         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
10733           HandleDeclRefExpr(DRE);
10734         return;
10735       }
10736 
10737       Visit(E);
10738     }
10739 
10740     // Reference types not handled in HandleValue are handled here since all
10741     // uses of references are bad, not just r-value uses.
10742     void VisitDeclRefExpr(DeclRefExpr *E) {
10743       if (isReferenceType)
10744         HandleDeclRefExpr(E);
10745     }
10746 
10747     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
10748       if (E->getCastKind() == CK_LValueToRValue) {
10749         HandleValue(E->getSubExpr());
10750         return;
10751       }
10752 
10753       Inherited::VisitImplicitCastExpr(E);
10754     }
10755 
10756     void VisitMemberExpr(MemberExpr *E) {
10757       if (isInitList) {
10758         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
10759           return;
10760       }
10761 
10762       // Don't warn on arrays since they can be treated as pointers.
10763       if (E->getType()->canDecayToPointerType()) return;
10764 
10765       // Warn when a non-static method call is followed by non-static member
10766       // field accesses, which is followed by a DeclRefExpr.
10767       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
10768       bool Warn = (MD && !MD->isStatic());
10769       Expr *Base = E->getBase()->IgnoreParenImpCasts();
10770       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10771         if (!isa<FieldDecl>(ME->getMemberDecl()))
10772           Warn = false;
10773         Base = ME->getBase()->IgnoreParenImpCasts();
10774       }
10775 
10776       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
10777         if (Warn)
10778           HandleDeclRefExpr(DRE);
10779         return;
10780       }
10781 
10782       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
10783       // Visit that expression.
10784       Visit(Base);
10785     }
10786 
10787     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
10788       Expr *Callee = E->getCallee();
10789 
10790       if (isa<UnresolvedLookupExpr>(Callee))
10791         return Inherited::VisitCXXOperatorCallExpr(E);
10792 
10793       Visit(Callee);
10794       for (auto Arg: E->arguments())
10795         HandleValue(Arg->IgnoreParenImpCasts());
10796     }
10797 
10798     void VisitUnaryOperator(UnaryOperator *E) {
10799       // For POD record types, addresses of its own members are well-defined.
10800       if (E->getOpcode() == UO_AddrOf && isRecordType &&
10801           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
10802         if (!isPODType)
10803           HandleValue(E->getSubExpr());
10804         return;
10805       }
10806 
10807       if (E->isIncrementDecrementOp()) {
10808         HandleValue(E->getSubExpr());
10809         return;
10810       }
10811 
10812       Inherited::VisitUnaryOperator(E);
10813     }
10814 
10815     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
10816 
10817     void VisitCXXConstructExpr(CXXConstructExpr *E) {
10818       if (E->getConstructor()->isCopyConstructor()) {
10819         Expr *ArgExpr = E->getArg(0);
10820         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
10821           if (ILE->getNumInits() == 1)
10822             ArgExpr = ILE->getInit(0);
10823         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
10824           if (ICE->getCastKind() == CK_NoOp)
10825             ArgExpr = ICE->getSubExpr();
10826         HandleValue(ArgExpr);
10827         return;
10828       }
10829       Inherited::VisitCXXConstructExpr(E);
10830     }
10831 
10832     void VisitCallExpr(CallExpr *E) {
10833       // Treat std::move as a use.
10834       if (E->isCallToStdMove()) {
10835         HandleValue(E->getArg(0));
10836         return;
10837       }
10838 
10839       Inherited::VisitCallExpr(E);
10840     }
10841 
10842     void VisitBinaryOperator(BinaryOperator *E) {
10843       if (E->isCompoundAssignmentOp()) {
10844         HandleValue(E->getLHS());
10845         Visit(E->getRHS());
10846         return;
10847       }
10848 
10849       Inherited::VisitBinaryOperator(E);
10850     }
10851 
10852     // A custom visitor for BinaryConditionalOperator is needed because the
10853     // regular visitor would check the condition and true expression separately
10854     // but both point to the same place giving duplicate diagnostics.
10855     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
10856       Visit(E->getCond());
10857       Visit(E->getFalseExpr());
10858     }
10859 
10860     void HandleDeclRefExpr(DeclRefExpr *DRE) {
10861       Decl* ReferenceDecl = DRE->getDecl();
10862       if (OrigDecl != ReferenceDecl) return;
10863       unsigned diag;
10864       if (isReferenceType) {
10865         diag = diag::warn_uninit_self_reference_in_reference_init;
10866       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
10867         diag = diag::warn_static_self_reference_in_init;
10868       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
10869                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
10870                  DRE->getDecl()->getType()->isRecordType()) {
10871         diag = diag::warn_uninit_self_reference_in_init;
10872       } else {
10873         // Local variables will be handled by the CFG analysis.
10874         return;
10875       }
10876 
10877       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
10878                             S.PDiag(diag)
10879                                 << DRE->getDecl() << OrigDecl->getLocation()
10880                                 << DRE->getSourceRange());
10881     }
10882   };
10883 
10884   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
10885   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
10886                                  bool DirectInit) {
10887     // Parameters arguments are occassionially constructed with itself,
10888     // for instance, in recursive functions.  Skip them.
10889     if (isa<ParmVarDecl>(OrigDecl))
10890       return;
10891 
10892     E = E->IgnoreParens();
10893 
10894     // Skip checking T a = a where T is not a record or reference type.
10895     // Doing so is a way to silence uninitialized warnings.
10896     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
10897       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
10898         if (ICE->getCastKind() == CK_LValueToRValue)
10899           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
10900             if (DRE->getDecl() == OrigDecl)
10901               return;
10902 
10903     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
10904   }
10905 } // end anonymous namespace
10906 
10907 namespace {
10908   // Simple wrapper to add the name of a variable or (if no variable is
10909   // available) a DeclarationName into a diagnostic.
10910   struct VarDeclOrName {
10911     VarDecl *VDecl;
10912     DeclarationName Name;
10913 
10914     friend const Sema::SemaDiagnosticBuilder &
10915     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
10916       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
10917     }
10918   };
10919 } // end anonymous namespace
10920 
10921 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
10922                                             DeclarationName Name, QualType Type,
10923                                             TypeSourceInfo *TSI,
10924                                             SourceRange Range, bool DirectInit,
10925                                             Expr *Init) {
10926   bool IsInitCapture = !VDecl;
10927   assert((!VDecl || !VDecl->isInitCapture()) &&
10928          "init captures are expected to be deduced prior to initialization");
10929 
10930   VarDeclOrName VN{VDecl, Name};
10931 
10932   DeducedType *Deduced = Type->getContainedDeducedType();
10933   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
10934 
10935   // C++11 [dcl.spec.auto]p3
10936   if (!Init) {
10937     assert(VDecl && "no init for init capture deduction?");
10938 
10939     // Except for class argument deduction, and then for an initializing
10940     // declaration only, i.e. no static at class scope or extern.
10941     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
10942         VDecl->hasExternalStorage() ||
10943         VDecl->isStaticDataMember()) {
10944       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
10945         << VDecl->getDeclName() << Type;
10946       return QualType();
10947     }
10948   }
10949 
10950   ArrayRef<Expr*> DeduceInits;
10951   if (Init)
10952     DeduceInits = Init;
10953 
10954   if (DirectInit) {
10955     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
10956       DeduceInits = PL->exprs();
10957   }
10958 
10959   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
10960     assert(VDecl && "non-auto type for init capture deduction?");
10961     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10962     InitializationKind Kind = InitializationKind::CreateForInit(
10963         VDecl->getLocation(), DirectInit, Init);
10964     // FIXME: Initialization should not be taking a mutable list of inits.
10965     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
10966     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
10967                                                        InitsCopy);
10968   }
10969 
10970   if (DirectInit) {
10971     if (auto *IL = dyn_cast<InitListExpr>(Init))
10972       DeduceInits = IL->inits();
10973   }
10974 
10975   // Deduction only works if we have exactly one source expression.
10976   if (DeduceInits.empty()) {
10977     // It isn't possible to write this directly, but it is possible to
10978     // end up in this situation with "auto x(some_pack...);"
10979     Diag(Init->getBeginLoc(), IsInitCapture
10980                                   ? diag::err_init_capture_no_expression
10981                                   : diag::err_auto_var_init_no_expression)
10982         << VN << Type << Range;
10983     return QualType();
10984   }
10985 
10986   if (DeduceInits.size() > 1) {
10987     Diag(DeduceInits[1]->getBeginLoc(),
10988          IsInitCapture ? diag::err_init_capture_multiple_expressions
10989                        : diag::err_auto_var_init_multiple_expressions)
10990         << VN << Type << Range;
10991     return QualType();
10992   }
10993 
10994   Expr *DeduceInit = DeduceInits[0];
10995   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
10996     Diag(Init->getBeginLoc(), IsInitCapture
10997                                   ? diag::err_init_capture_paren_braces
10998                                   : diag::err_auto_var_init_paren_braces)
10999         << isa<InitListExpr>(Init) << VN << Type << Range;
11000     return QualType();
11001   }
11002 
11003   // Expressions default to 'id' when we're in a debugger.
11004   bool DefaultedAnyToId = false;
11005   if (getLangOpts().DebuggerCastResultToId &&
11006       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11007     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11008     if (Result.isInvalid()) {
11009       return QualType();
11010     }
11011     Init = Result.get();
11012     DefaultedAnyToId = true;
11013   }
11014 
11015   // C++ [dcl.decomp]p1:
11016   //   If the assignment-expression [...] has array type A and no ref-qualifier
11017   //   is present, e has type cv A
11018   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11019       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11020       DeduceInit->getType()->isConstantArrayType())
11021     return Context.getQualifiedType(DeduceInit->getType(),
11022                                     Type.getQualifiers());
11023 
11024   QualType DeducedType;
11025   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11026     if (!IsInitCapture)
11027       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11028     else if (isa<InitListExpr>(Init))
11029       Diag(Range.getBegin(),
11030            diag::err_init_capture_deduction_failure_from_init_list)
11031           << VN
11032           << (DeduceInit->getType().isNull() ? TSI->getType()
11033                                              : DeduceInit->getType())
11034           << DeduceInit->getSourceRange();
11035     else
11036       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11037           << VN << TSI->getType()
11038           << (DeduceInit->getType().isNull() ? TSI->getType()
11039                                              : DeduceInit->getType())
11040           << DeduceInit->getSourceRange();
11041   }
11042 
11043   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11044   // 'id' instead of a specific object type prevents most of our usual
11045   // checks.
11046   // We only want to warn outside of template instantiations, though:
11047   // inside a template, the 'id' could have come from a parameter.
11048   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11049       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11050     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11051     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11052   }
11053 
11054   return DeducedType;
11055 }
11056 
11057 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11058                                          Expr *Init) {
11059   QualType DeducedType = deduceVarTypeFromInitializer(
11060       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11061       VDecl->getSourceRange(), DirectInit, Init);
11062   if (DeducedType.isNull()) {
11063     VDecl->setInvalidDecl();
11064     return true;
11065   }
11066 
11067   VDecl->setType(DeducedType);
11068   assert(VDecl->isLinkageValid());
11069 
11070   // In ARC, infer lifetime.
11071   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11072     VDecl->setInvalidDecl();
11073 
11074   // If this is a redeclaration, check that the type we just deduced matches
11075   // the previously declared type.
11076   if (VarDecl *Old = VDecl->getPreviousDecl()) {
11077     // We never need to merge the type, because we cannot form an incomplete
11078     // array of auto, nor deduce such a type.
11079     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11080   }
11081 
11082   // Check the deduced type is valid for a variable declaration.
11083   CheckVariableDeclarationType(VDecl);
11084   return VDecl->isInvalidDecl();
11085 }
11086 
11087 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11088                                               SourceLocation Loc) {
11089   if (auto *CE = dyn_cast<ConstantExpr>(Init))
11090     Init = CE->getSubExpr();
11091 
11092   QualType InitType = Init->getType();
11093   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11094           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
11095          "shouldn't be called if type doesn't have a non-trivial C struct");
11096   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11097     for (auto I : ILE->inits()) {
11098       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11099           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11100         continue;
11101       SourceLocation SL = I->getExprLoc();
11102       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11103     }
11104     return;
11105   }
11106 
11107   if (isa<ImplicitValueInitExpr>(Init)) {
11108     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11109       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11110                             NTCUK_Init);
11111   } else {
11112     // Assume all other explicit initializers involving copying some existing
11113     // object.
11114     // TODO: ignore any explicit initializers where we can guarantee
11115     // copy-elision.
11116     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11117       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11118   }
11119 }
11120 
11121 namespace {
11122 
11123 struct DiagNonTrivalCUnionDefaultInitializeVisitor
11124     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11125                                     void> {
11126   using Super =
11127       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11128                                     void>;
11129 
11130   DiagNonTrivalCUnionDefaultInitializeVisitor(
11131       QualType OrigTy, SourceLocation OrigLoc,
11132       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11133       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11134 
11135   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11136                      const FieldDecl *FD, bool InNonTrivialUnion) {
11137     if (const auto *AT = S.Context.getAsArrayType(QT))
11138       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11139                                      InNonTrivialUnion);
11140     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11141   }
11142 
11143   void visitARCStrong(QualType QT, const FieldDecl *FD,
11144                       bool InNonTrivialUnion) {
11145     if (InNonTrivialUnion)
11146       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11147           << 1 << 0 << QT << FD->getName();
11148   }
11149 
11150   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11151     if (InNonTrivialUnion)
11152       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11153           << 1 << 0 << QT << FD->getName();
11154   }
11155 
11156   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11157     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11158     if (RD->isUnion()) {
11159       if (OrigLoc.isValid()) {
11160         bool IsUnion = false;
11161         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11162           IsUnion = OrigRD->isUnion();
11163         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11164             << 0 << OrigTy << IsUnion << UseContext;
11165         // Reset OrigLoc so that this diagnostic is emitted only once.
11166         OrigLoc = SourceLocation();
11167       }
11168       InNonTrivialUnion = true;
11169     }
11170 
11171     if (InNonTrivialUnion)
11172       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11173           << 0 << 0 << QT.getUnqualifiedType() << "";
11174 
11175     for (const FieldDecl *FD : RD->fields())
11176       asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11177   }
11178 
11179   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11180 
11181   // The non-trivial C union type or the struct/union type that contains a
11182   // non-trivial C union.
11183   QualType OrigTy;
11184   SourceLocation OrigLoc;
11185   Sema::NonTrivialCUnionContext UseContext;
11186   Sema &S;
11187 };
11188 
11189 struct DiagNonTrivalCUnionDestructedTypeVisitor
11190     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
11191   using Super =
11192       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
11193 
11194   DiagNonTrivalCUnionDestructedTypeVisitor(
11195       QualType OrigTy, SourceLocation OrigLoc,
11196       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11197       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11198 
11199   void visitWithKind(QualType::DestructionKind DK, QualType QT,
11200                      const FieldDecl *FD, bool InNonTrivialUnion) {
11201     if (const auto *AT = S.Context.getAsArrayType(QT))
11202       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11203                                      InNonTrivialUnion);
11204     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
11205   }
11206 
11207   void visitARCStrong(QualType QT, const FieldDecl *FD,
11208                       bool InNonTrivialUnion) {
11209     if (InNonTrivialUnion)
11210       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11211           << 1 << 1 << QT << FD->getName();
11212   }
11213 
11214   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11215     if (InNonTrivialUnion)
11216       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11217           << 1 << 1 << QT << FD->getName();
11218   }
11219 
11220   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11221     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11222     if (RD->isUnion()) {
11223       if (OrigLoc.isValid()) {
11224         bool IsUnion = false;
11225         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11226           IsUnion = OrigRD->isUnion();
11227         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11228             << 1 << OrigTy << IsUnion << UseContext;
11229         // Reset OrigLoc so that this diagnostic is emitted only once.
11230         OrigLoc = SourceLocation();
11231       }
11232       InNonTrivialUnion = true;
11233     }
11234 
11235     if (InNonTrivialUnion)
11236       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11237           << 0 << 1 << QT.getUnqualifiedType() << "";
11238 
11239     for (const FieldDecl *FD : RD->fields())
11240       asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11241   }
11242 
11243   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11244   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
11245                           bool InNonTrivialUnion) {}
11246 
11247   // The non-trivial C union type or the struct/union type that contains a
11248   // non-trivial C union.
11249   QualType OrigTy;
11250   SourceLocation OrigLoc;
11251   Sema::NonTrivialCUnionContext UseContext;
11252   Sema &S;
11253 };
11254 
11255 struct DiagNonTrivalCUnionCopyVisitor
11256     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
11257   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
11258 
11259   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
11260                                  Sema::NonTrivialCUnionContext UseContext,
11261                                  Sema &S)
11262       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11263 
11264   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
11265                      const FieldDecl *FD, bool InNonTrivialUnion) {
11266     if (const auto *AT = S.Context.getAsArrayType(QT))
11267       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11268                                      InNonTrivialUnion);
11269     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
11270   }
11271 
11272   void visitARCStrong(QualType QT, const FieldDecl *FD,
11273                       bool InNonTrivialUnion) {
11274     if (InNonTrivialUnion)
11275       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11276           << 1 << 2 << QT << FD->getName();
11277   }
11278 
11279   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11280     if (InNonTrivialUnion)
11281       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11282           << 1 << 2 << QT << FD->getName();
11283   }
11284 
11285   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11286     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11287     if (RD->isUnion()) {
11288       if (OrigLoc.isValid()) {
11289         bool IsUnion = false;
11290         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11291           IsUnion = OrigRD->isUnion();
11292         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11293             << 2 << OrigTy << IsUnion << UseContext;
11294         // Reset OrigLoc so that this diagnostic is emitted only once.
11295         OrigLoc = SourceLocation();
11296       }
11297       InNonTrivialUnion = true;
11298     }
11299 
11300     if (InNonTrivialUnion)
11301       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11302           << 0 << 2 << QT.getUnqualifiedType() << "";
11303 
11304     for (const FieldDecl *FD : RD->fields())
11305       asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11306   }
11307 
11308   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
11309                 const FieldDecl *FD, bool InNonTrivialUnion) {}
11310   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11311   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
11312                             bool InNonTrivialUnion) {}
11313 
11314   // The non-trivial C union type or the struct/union type that contains a
11315   // non-trivial C union.
11316   QualType OrigTy;
11317   SourceLocation OrigLoc;
11318   Sema::NonTrivialCUnionContext UseContext;
11319   Sema &S;
11320 };
11321 
11322 } // namespace
11323 
11324 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
11325                                  NonTrivialCUnionContext UseContext,
11326                                  unsigned NonTrivialKind) {
11327   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11328           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
11329           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
11330          "shouldn't be called if type doesn't have a non-trivial C union");
11331 
11332   if ((NonTrivialKind & NTCUK_Init) &&
11333       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11334     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
11335         .visit(QT, nullptr, false);
11336   if ((NonTrivialKind & NTCUK_Destruct) &&
11337       QT.hasNonTrivialToPrimitiveDestructCUnion())
11338     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
11339         .visit(QT, nullptr, false);
11340   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
11341     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
11342         .visit(QT, nullptr, false);
11343 }
11344 
11345 /// AddInitializerToDecl - Adds the initializer Init to the
11346 /// declaration dcl. If DirectInit is true, this is C++ direct
11347 /// initialization rather than copy initialization.
11348 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
11349   // If there is no declaration, there was an error parsing it.  Just ignore
11350   // the initializer.
11351   if (!RealDecl || RealDecl->isInvalidDecl()) {
11352     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
11353     return;
11354   }
11355 
11356   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
11357     // Pure-specifiers are handled in ActOnPureSpecifier.
11358     Diag(Method->getLocation(), diag::err_member_function_initialization)
11359       << Method->getDeclName() << Init->getSourceRange();
11360     Method->setInvalidDecl();
11361     return;
11362   }
11363 
11364   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
11365   if (!VDecl) {
11366     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
11367     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
11368     RealDecl->setInvalidDecl();
11369     return;
11370   }
11371 
11372   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
11373   if (VDecl->getType()->isUndeducedType()) {
11374     // Attempt typo correction early so that the type of the init expression can
11375     // be deduced based on the chosen correction if the original init contains a
11376     // TypoExpr.
11377     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
11378     if (!Res.isUsable()) {
11379       RealDecl->setInvalidDecl();
11380       return;
11381     }
11382     Init = Res.get();
11383 
11384     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
11385       return;
11386   }
11387 
11388   // dllimport cannot be used on variable definitions.
11389   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
11390     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
11391     VDecl->setInvalidDecl();
11392     return;
11393   }
11394 
11395   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
11396     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
11397     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
11398     VDecl->setInvalidDecl();
11399     return;
11400   }
11401 
11402   if (!VDecl->getType()->isDependentType()) {
11403     // A definition must end up with a complete type, which means it must be
11404     // complete with the restriction that an array type might be completed by
11405     // the initializer; note that later code assumes this restriction.
11406     QualType BaseDeclType = VDecl->getType();
11407     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
11408       BaseDeclType = Array->getElementType();
11409     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
11410                             diag::err_typecheck_decl_incomplete_type)) {
11411       RealDecl->setInvalidDecl();
11412       return;
11413     }
11414 
11415     // The variable can not have an abstract class type.
11416     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
11417                                diag::err_abstract_type_in_decl,
11418                                AbstractVariableType))
11419       VDecl->setInvalidDecl();
11420   }
11421 
11422   // If adding the initializer will turn this declaration into a definition,
11423   // and we already have a definition for this variable, diagnose or otherwise
11424   // handle the situation.
11425   VarDecl *Def;
11426   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
11427       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
11428       !VDecl->isThisDeclarationADemotedDefinition() &&
11429       checkVarDeclRedefinition(Def, VDecl))
11430     return;
11431 
11432   if (getLangOpts().CPlusPlus) {
11433     // C++ [class.static.data]p4
11434     //   If a static data member is of const integral or const
11435     //   enumeration type, its declaration in the class definition can
11436     //   specify a constant-initializer which shall be an integral
11437     //   constant expression (5.19). In that case, the member can appear
11438     //   in integral constant expressions. The member shall still be
11439     //   defined in a namespace scope if it is used in the program and the
11440     //   namespace scope definition shall not contain an initializer.
11441     //
11442     // We already performed a redefinition check above, but for static
11443     // data members we also need to check whether there was an in-class
11444     // declaration with an initializer.
11445     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
11446       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
11447           << VDecl->getDeclName();
11448       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
11449            diag::note_previous_initializer)
11450           << 0;
11451       return;
11452     }
11453 
11454     if (VDecl->hasLocalStorage())
11455       setFunctionHasBranchProtectedScope();
11456 
11457     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
11458       VDecl->setInvalidDecl();
11459       return;
11460     }
11461   }
11462 
11463   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
11464   // a kernel function cannot be initialized."
11465   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
11466     Diag(VDecl->getLocation(), diag::err_local_cant_init);
11467     VDecl->setInvalidDecl();
11468     return;
11469   }
11470 
11471   // Get the decls type and save a reference for later, since
11472   // CheckInitializerTypes may change it.
11473   QualType DclT = VDecl->getType(), SavT = DclT;
11474 
11475   // Expressions default to 'id' when we're in a debugger
11476   // and we are assigning it to a variable of Objective-C pointer type.
11477   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
11478       Init->getType() == Context.UnknownAnyTy) {
11479     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11480     if (Result.isInvalid()) {
11481       VDecl->setInvalidDecl();
11482       return;
11483     }
11484     Init = Result.get();
11485   }
11486 
11487   // Perform the initialization.
11488   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
11489   if (!VDecl->isInvalidDecl()) {
11490     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11491     InitializationKind Kind = InitializationKind::CreateForInit(
11492         VDecl->getLocation(), DirectInit, Init);
11493 
11494     MultiExprArg Args = Init;
11495     if (CXXDirectInit)
11496       Args = MultiExprArg(CXXDirectInit->getExprs(),
11497                           CXXDirectInit->getNumExprs());
11498 
11499     // Try to correct any TypoExprs in the initialization arguments.
11500     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
11501       ExprResult Res = CorrectDelayedTyposInExpr(
11502           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
11503             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
11504             return Init.Failed() ? ExprError() : E;
11505           });
11506       if (Res.isInvalid()) {
11507         VDecl->setInvalidDecl();
11508       } else if (Res.get() != Args[Idx]) {
11509         Args[Idx] = Res.get();
11510       }
11511     }
11512     if (VDecl->isInvalidDecl())
11513       return;
11514 
11515     InitializationSequence InitSeq(*this, Entity, Kind, Args,
11516                                    /*TopLevelOfInitList=*/false,
11517                                    /*TreatUnavailableAsInvalid=*/false);
11518     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
11519     if (Result.isInvalid()) {
11520       VDecl->setInvalidDecl();
11521       return;
11522     }
11523 
11524     Init = Result.getAs<Expr>();
11525   }
11526 
11527   // Check for self-references within variable initializers.
11528   // Variables declared within a function/method body (except for references)
11529   // are handled by a dataflow analysis.
11530   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
11531       VDecl->getType()->isReferenceType()) {
11532     CheckSelfReference(*this, RealDecl, Init, DirectInit);
11533   }
11534 
11535   // If the type changed, it means we had an incomplete type that was
11536   // completed by the initializer. For example:
11537   //   int ary[] = { 1, 3, 5 };
11538   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
11539   if (!VDecl->isInvalidDecl() && (DclT != SavT))
11540     VDecl->setType(DclT);
11541 
11542   if (!VDecl->isInvalidDecl()) {
11543     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
11544 
11545     if (VDecl->hasAttr<BlocksAttr>())
11546       checkRetainCycles(VDecl, Init);
11547 
11548     // It is safe to assign a weak reference into a strong variable.
11549     // Although this code can still have problems:
11550     //   id x = self.weakProp;
11551     //   id y = self.weakProp;
11552     // we do not warn to warn spuriously when 'x' and 'y' are on separate
11553     // paths through the function. This should be revisited if
11554     // -Wrepeated-use-of-weak is made flow-sensitive.
11555     if (FunctionScopeInfo *FSI = getCurFunction())
11556       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
11557            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
11558           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11559                            Init->getBeginLoc()))
11560         FSI->markSafeWeakUse(Init);
11561   }
11562 
11563   // The initialization is usually a full-expression.
11564   //
11565   // FIXME: If this is a braced initialization of an aggregate, it is not
11566   // an expression, and each individual field initializer is a separate
11567   // full-expression. For instance, in:
11568   //
11569   //   struct Temp { ~Temp(); };
11570   //   struct S { S(Temp); };
11571   //   struct T { S a, b; } t = { Temp(), Temp() }
11572   //
11573   // we should destroy the first Temp before constructing the second.
11574   ExprResult Result =
11575       ActOnFinishFullExpr(Init, VDecl->getLocation(),
11576                           /*DiscardedValue*/ false, VDecl->isConstexpr());
11577   if (Result.isInvalid()) {
11578     VDecl->setInvalidDecl();
11579     return;
11580   }
11581   Init = Result.get();
11582 
11583   // Attach the initializer to the decl.
11584   VDecl->setInit(Init);
11585 
11586   if (VDecl->isLocalVarDecl()) {
11587     // Don't check the initializer if the declaration is malformed.
11588     if (VDecl->isInvalidDecl()) {
11589       // do nothing
11590 
11591     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
11592     // This is true even in C++ for OpenCL.
11593     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
11594       CheckForConstantInitializer(Init, DclT);
11595 
11596     // Otherwise, C++ does not restrict the initializer.
11597     } else if (getLangOpts().CPlusPlus) {
11598       // do nothing
11599 
11600     // C99 6.7.8p4: All the expressions in an initializer for an object that has
11601     // static storage duration shall be constant expressions or string literals.
11602     } else if (VDecl->getStorageClass() == SC_Static) {
11603       CheckForConstantInitializer(Init, DclT);
11604 
11605     // C89 is stricter than C99 for aggregate initializers.
11606     // C89 6.5.7p3: All the expressions [...] in an initializer list
11607     // for an object that has aggregate or union type shall be
11608     // constant expressions.
11609     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
11610                isa<InitListExpr>(Init)) {
11611       const Expr *Culprit;
11612       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
11613         Diag(Culprit->getExprLoc(),
11614              diag::ext_aggregate_init_not_constant)
11615           << Culprit->getSourceRange();
11616       }
11617     }
11618 
11619     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
11620       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
11621         if (VDecl->hasLocalStorage())
11622           BE->getBlockDecl()->setCanAvoidCopyToHeap();
11623   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
11624              VDecl->getLexicalDeclContext()->isRecord()) {
11625     // This is an in-class initialization for a static data member, e.g.,
11626     //
11627     // struct S {
11628     //   static const int value = 17;
11629     // };
11630 
11631     // C++ [class.mem]p4:
11632     //   A member-declarator can contain a constant-initializer only
11633     //   if it declares a static member (9.4) of const integral or
11634     //   const enumeration type, see 9.4.2.
11635     //
11636     // C++11 [class.static.data]p3:
11637     //   If a non-volatile non-inline const static data member is of integral
11638     //   or enumeration type, its declaration in the class definition can
11639     //   specify a brace-or-equal-initializer in which every initializer-clause
11640     //   that is an assignment-expression is a constant expression. A static
11641     //   data member of literal type can be declared in the class definition
11642     //   with the constexpr specifier; if so, its declaration shall specify a
11643     //   brace-or-equal-initializer in which every initializer-clause that is
11644     //   an assignment-expression is a constant expression.
11645 
11646     // Do nothing on dependent types.
11647     if (DclT->isDependentType()) {
11648 
11649     // Allow any 'static constexpr' members, whether or not they are of literal
11650     // type. We separately check that every constexpr variable is of literal
11651     // type.
11652     } else if (VDecl->isConstexpr()) {
11653 
11654     // Require constness.
11655     } else if (!DclT.isConstQualified()) {
11656       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
11657         << Init->getSourceRange();
11658       VDecl->setInvalidDecl();
11659 
11660     // We allow integer constant expressions in all cases.
11661     } else if (DclT->isIntegralOrEnumerationType()) {
11662       // Check whether the expression is a constant expression.
11663       SourceLocation Loc;
11664       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
11665         // In C++11, a non-constexpr const static data member with an
11666         // in-class initializer cannot be volatile.
11667         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
11668       else if (Init->isValueDependent())
11669         ; // Nothing to check.
11670       else if (Init->isIntegerConstantExpr(Context, &Loc))
11671         ; // Ok, it's an ICE!
11672       else if (Init->getType()->isScopedEnumeralType() &&
11673                Init->isCXX11ConstantExpr(Context))
11674         ; // Ok, it is a scoped-enum constant expression.
11675       else if (Init->isEvaluatable(Context)) {
11676         // If we can constant fold the initializer through heroics, accept it,
11677         // but report this as a use of an extension for -pedantic.
11678         Diag(Loc, diag::ext_in_class_initializer_non_constant)
11679           << Init->getSourceRange();
11680       } else {
11681         // Otherwise, this is some crazy unknown case.  Report the issue at the
11682         // location provided by the isIntegerConstantExpr failed check.
11683         Diag(Loc, diag::err_in_class_initializer_non_constant)
11684           << Init->getSourceRange();
11685         VDecl->setInvalidDecl();
11686       }
11687 
11688     // We allow foldable floating-point constants as an extension.
11689     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
11690       // In C++98, this is a GNU extension. In C++11, it is not, but we support
11691       // it anyway and provide a fixit to add the 'constexpr'.
11692       if (getLangOpts().CPlusPlus11) {
11693         Diag(VDecl->getLocation(),
11694              diag::ext_in_class_initializer_float_type_cxx11)
11695             << DclT << Init->getSourceRange();
11696         Diag(VDecl->getBeginLoc(),
11697              diag::note_in_class_initializer_float_type_cxx11)
11698             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11699       } else {
11700         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
11701           << DclT << Init->getSourceRange();
11702 
11703         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
11704           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
11705             << Init->getSourceRange();
11706           VDecl->setInvalidDecl();
11707         }
11708       }
11709 
11710     // Suggest adding 'constexpr' in C++11 for literal types.
11711     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
11712       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
11713           << DclT << Init->getSourceRange()
11714           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11715       VDecl->setConstexpr(true);
11716 
11717     } else {
11718       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
11719         << DclT << Init->getSourceRange();
11720       VDecl->setInvalidDecl();
11721     }
11722   } else if (VDecl->isFileVarDecl()) {
11723     // In C, extern is typically used to avoid tentative definitions when
11724     // declaring variables in headers, but adding an intializer makes it a
11725     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
11726     // In C++, extern is often used to give implictly static const variables
11727     // external linkage, so don't warn in that case. If selectany is present,
11728     // this might be header code intended for C and C++ inclusion, so apply the
11729     // C++ rules.
11730     if (VDecl->getStorageClass() == SC_Extern &&
11731         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
11732          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
11733         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
11734         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
11735       Diag(VDecl->getLocation(), diag::warn_extern_init);
11736 
11737     // In Microsoft C++ mode, a const variable defined in namespace scope has
11738     // external linkage by default if the variable is declared with
11739     // __declspec(dllexport).
11740     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
11741         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
11742         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
11743       VDecl->setStorageClass(SC_Extern);
11744 
11745     // C99 6.7.8p4. All file scoped initializers need to be constant.
11746     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
11747       CheckForConstantInitializer(Init, DclT);
11748   }
11749 
11750   QualType InitType = Init->getType();
11751   if (!InitType.isNull() &&
11752       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11753        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
11754     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
11755 
11756   // We will represent direct-initialization similarly to copy-initialization:
11757   //    int x(1);  -as-> int x = 1;
11758   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
11759   //
11760   // Clients that want to distinguish between the two forms, can check for
11761   // direct initializer using VarDecl::getInitStyle().
11762   // A major benefit is that clients that don't particularly care about which
11763   // exactly form was it (like the CodeGen) can handle both cases without
11764   // special case code.
11765 
11766   // C++ 8.5p11:
11767   // The form of initialization (using parentheses or '=') is generally
11768   // insignificant, but does matter when the entity being initialized has a
11769   // class type.
11770   if (CXXDirectInit) {
11771     assert(DirectInit && "Call-style initializer must be direct init.");
11772     VDecl->setInitStyle(VarDecl::CallInit);
11773   } else if (DirectInit) {
11774     // This must be list-initialization. No other way is direct-initialization.
11775     VDecl->setInitStyle(VarDecl::ListInit);
11776   }
11777 
11778   CheckCompleteVariableDeclaration(VDecl);
11779 }
11780 
11781 /// ActOnInitializerError - Given that there was an error parsing an
11782 /// initializer for the given declaration, try to return to some form
11783 /// of sanity.
11784 void Sema::ActOnInitializerError(Decl *D) {
11785   // Our main concern here is re-establishing invariants like "a
11786   // variable's type is either dependent or complete".
11787   if (!D || D->isInvalidDecl()) return;
11788 
11789   VarDecl *VD = dyn_cast<VarDecl>(D);
11790   if (!VD) return;
11791 
11792   // Bindings are not usable if we can't make sense of the initializer.
11793   if (auto *DD = dyn_cast<DecompositionDecl>(D))
11794     for (auto *BD : DD->bindings())
11795       BD->setInvalidDecl();
11796 
11797   // Auto types are meaningless if we can't make sense of the initializer.
11798   if (ParsingInitForAutoVars.count(D)) {
11799     D->setInvalidDecl();
11800     return;
11801   }
11802 
11803   QualType Ty = VD->getType();
11804   if (Ty->isDependentType()) return;
11805 
11806   // Require a complete type.
11807   if (RequireCompleteType(VD->getLocation(),
11808                           Context.getBaseElementType(Ty),
11809                           diag::err_typecheck_decl_incomplete_type)) {
11810     VD->setInvalidDecl();
11811     return;
11812   }
11813 
11814   // Require a non-abstract type.
11815   if (RequireNonAbstractType(VD->getLocation(), Ty,
11816                              diag::err_abstract_type_in_decl,
11817                              AbstractVariableType)) {
11818     VD->setInvalidDecl();
11819     return;
11820   }
11821 
11822   // Don't bother complaining about constructors or destructors,
11823   // though.
11824 }
11825 
11826 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
11827   // If there is no declaration, there was an error parsing it. Just ignore it.
11828   if (!RealDecl)
11829     return;
11830 
11831   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
11832     QualType Type = Var->getType();
11833 
11834     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
11835     if (isa<DecompositionDecl>(RealDecl)) {
11836       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
11837       Var->setInvalidDecl();
11838       return;
11839     }
11840 
11841     if (Type->isUndeducedType() &&
11842         DeduceVariableDeclarationType(Var, false, nullptr))
11843       return;
11844 
11845     // C++11 [class.static.data]p3: A static data member can be declared with
11846     // the constexpr specifier; if so, its declaration shall specify
11847     // a brace-or-equal-initializer.
11848     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
11849     // the definition of a variable [...] or the declaration of a static data
11850     // member.
11851     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
11852         !Var->isThisDeclarationADemotedDefinition()) {
11853       if (Var->isStaticDataMember()) {
11854         // C++1z removes the relevant rule; the in-class declaration is always
11855         // a definition there.
11856         if (!getLangOpts().CPlusPlus17) {
11857           Diag(Var->getLocation(),
11858                diag::err_constexpr_static_mem_var_requires_init)
11859             << Var->getDeclName();
11860           Var->setInvalidDecl();
11861           return;
11862         }
11863       } else {
11864         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
11865         Var->setInvalidDecl();
11866         return;
11867       }
11868     }
11869 
11870     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
11871     // be initialized.
11872     if (!Var->isInvalidDecl() &&
11873         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
11874         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
11875       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
11876       Var->setInvalidDecl();
11877       return;
11878     }
11879 
11880     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
11881     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
11882         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11883       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
11884                             NTCUC_DefaultInitializedObject, NTCUK_Init);
11885 
11886 
11887     switch (DefKind) {
11888     case VarDecl::Definition:
11889       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
11890         break;
11891 
11892       // We have an out-of-line definition of a static data member
11893       // that has an in-class initializer, so we type-check this like
11894       // a declaration.
11895       //
11896       LLVM_FALLTHROUGH;
11897 
11898     case VarDecl::DeclarationOnly:
11899       // It's only a declaration.
11900 
11901       // Block scope. C99 6.7p7: If an identifier for an object is
11902       // declared with no linkage (C99 6.2.2p6), the type for the
11903       // object shall be complete.
11904       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
11905           !Var->hasLinkage() && !Var->isInvalidDecl() &&
11906           RequireCompleteType(Var->getLocation(), Type,
11907                               diag::err_typecheck_decl_incomplete_type))
11908         Var->setInvalidDecl();
11909 
11910       // Make sure that the type is not abstract.
11911       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11912           RequireNonAbstractType(Var->getLocation(), Type,
11913                                  diag::err_abstract_type_in_decl,
11914                                  AbstractVariableType))
11915         Var->setInvalidDecl();
11916       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11917           Var->getStorageClass() == SC_PrivateExtern) {
11918         Diag(Var->getLocation(), diag::warn_private_extern);
11919         Diag(Var->getLocation(), diag::note_private_extern);
11920       }
11921 
11922       return;
11923 
11924     case VarDecl::TentativeDefinition:
11925       // File scope. C99 6.9.2p2: A declaration of an identifier for an
11926       // object that has file scope without an initializer, and without a
11927       // storage-class specifier or with the storage-class specifier "static",
11928       // constitutes a tentative definition. Note: A tentative definition with
11929       // external linkage is valid (C99 6.2.2p5).
11930       if (!Var->isInvalidDecl()) {
11931         if (const IncompleteArrayType *ArrayT
11932                                     = Context.getAsIncompleteArrayType(Type)) {
11933           if (RequireCompleteType(Var->getLocation(),
11934                                   ArrayT->getElementType(),
11935                                   diag::err_illegal_decl_array_incomplete_type))
11936             Var->setInvalidDecl();
11937         } else if (Var->getStorageClass() == SC_Static) {
11938           // C99 6.9.2p3: If the declaration of an identifier for an object is
11939           // a tentative definition and has internal linkage (C99 6.2.2p3), the
11940           // declared type shall not be an incomplete type.
11941           // NOTE: code such as the following
11942           //     static struct s;
11943           //     struct s { int a; };
11944           // is accepted by gcc. Hence here we issue a warning instead of
11945           // an error and we do not invalidate the static declaration.
11946           // NOTE: to avoid multiple warnings, only check the first declaration.
11947           if (Var->isFirstDecl())
11948             RequireCompleteType(Var->getLocation(), Type,
11949                                 diag::ext_typecheck_decl_incomplete_type);
11950         }
11951       }
11952 
11953       // Record the tentative definition; we're done.
11954       if (!Var->isInvalidDecl())
11955         TentativeDefinitions.push_back(Var);
11956       return;
11957     }
11958 
11959     // Provide a specific diagnostic for uninitialized variable
11960     // definitions with incomplete array type.
11961     if (Type->isIncompleteArrayType()) {
11962       Diag(Var->getLocation(),
11963            diag::err_typecheck_incomplete_array_needs_initializer);
11964       Var->setInvalidDecl();
11965       return;
11966     }
11967 
11968     // Provide a specific diagnostic for uninitialized variable
11969     // definitions with reference type.
11970     if (Type->isReferenceType()) {
11971       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
11972         << Var->getDeclName()
11973         << SourceRange(Var->getLocation(), Var->getLocation());
11974       Var->setInvalidDecl();
11975       return;
11976     }
11977 
11978     // Do not attempt to type-check the default initializer for a
11979     // variable with dependent type.
11980     if (Type->isDependentType())
11981       return;
11982 
11983     if (Var->isInvalidDecl())
11984       return;
11985 
11986     if (!Var->hasAttr<AliasAttr>()) {
11987       if (RequireCompleteType(Var->getLocation(),
11988                               Context.getBaseElementType(Type),
11989                               diag::err_typecheck_decl_incomplete_type)) {
11990         Var->setInvalidDecl();
11991         return;
11992       }
11993     } else {
11994       return;
11995     }
11996 
11997     // The variable can not have an abstract class type.
11998     if (RequireNonAbstractType(Var->getLocation(), Type,
11999                                diag::err_abstract_type_in_decl,
12000                                AbstractVariableType)) {
12001       Var->setInvalidDecl();
12002       return;
12003     }
12004 
12005     // Check for jumps past the implicit initializer.  C++0x
12006     // clarifies that this applies to a "variable with automatic
12007     // storage duration", not a "local variable".
12008     // C++11 [stmt.dcl]p3
12009     //   A program that jumps from a point where a variable with automatic
12010     //   storage duration is not in scope to a point where it is in scope is
12011     //   ill-formed unless the variable has scalar type, class type with a
12012     //   trivial default constructor and a trivial destructor, a cv-qualified
12013     //   version of one of these types, or an array of one of the preceding
12014     //   types and is declared without an initializer.
12015     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12016       if (const RecordType *Record
12017             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12018         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12019         // Mark the function (if we're in one) for further checking even if the
12020         // looser rules of C++11 do not require such checks, so that we can
12021         // diagnose incompatibilities with C++98.
12022         if (!CXXRecord->isPOD())
12023           setFunctionHasBranchProtectedScope();
12024       }
12025     }
12026     // In OpenCL, we can't initialize objects in the __local address space,
12027     // even implicitly, so don't synthesize an implicit initializer.
12028     if (getLangOpts().OpenCL &&
12029         Var->getType().getAddressSpace() == LangAS::opencl_local)
12030       return;
12031     // C++03 [dcl.init]p9:
12032     //   If no initializer is specified for an object, and the
12033     //   object is of (possibly cv-qualified) non-POD class type (or
12034     //   array thereof), the object shall be default-initialized; if
12035     //   the object is of const-qualified type, the underlying class
12036     //   type shall have a user-declared default
12037     //   constructor. Otherwise, if no initializer is specified for
12038     //   a non- static object, the object and its subobjects, if
12039     //   any, have an indeterminate initial value); if the object
12040     //   or any of its subobjects are of const-qualified type, the
12041     //   program is ill-formed.
12042     // C++0x [dcl.init]p11:
12043     //   If no initializer is specified for an object, the object is
12044     //   default-initialized; [...].
12045     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12046     InitializationKind Kind
12047       = InitializationKind::CreateDefault(Var->getLocation());
12048 
12049     InitializationSequence InitSeq(*this, Entity, Kind, None);
12050     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12051     if (Init.isInvalid())
12052       Var->setInvalidDecl();
12053     else if (Init.get()) {
12054       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12055       // This is important for template substitution.
12056       Var->setInitStyle(VarDecl::CallInit);
12057     }
12058 
12059     CheckCompleteVariableDeclaration(Var);
12060   }
12061 }
12062 
12063 void Sema::ActOnCXXForRangeDecl(Decl *D) {
12064   // If there is no declaration, there was an error parsing it. Ignore it.
12065   if (!D)
12066     return;
12067 
12068   VarDecl *VD = dyn_cast<VarDecl>(D);
12069   if (!VD) {
12070     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12071     D->setInvalidDecl();
12072     return;
12073   }
12074 
12075   VD->setCXXForRangeDecl(true);
12076 
12077   // for-range-declaration cannot be given a storage class specifier.
12078   int Error = -1;
12079   switch (VD->getStorageClass()) {
12080   case SC_None:
12081     break;
12082   case SC_Extern:
12083     Error = 0;
12084     break;
12085   case SC_Static:
12086     Error = 1;
12087     break;
12088   case SC_PrivateExtern:
12089     Error = 2;
12090     break;
12091   case SC_Auto:
12092     Error = 3;
12093     break;
12094   case SC_Register:
12095     Error = 4;
12096     break;
12097   }
12098   if (Error != -1) {
12099     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12100       << VD->getDeclName() << Error;
12101     D->setInvalidDecl();
12102   }
12103 }
12104 
12105 StmtResult
12106 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
12107                                  IdentifierInfo *Ident,
12108                                  ParsedAttributes &Attrs,
12109                                  SourceLocation AttrEnd) {
12110   // C++1y [stmt.iter]p1:
12111   //   A range-based for statement of the form
12112   //      for ( for-range-identifier : for-range-initializer ) statement
12113   //   is equivalent to
12114   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
12115   DeclSpec DS(Attrs.getPool().getFactory());
12116 
12117   const char *PrevSpec;
12118   unsigned DiagID;
12119   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
12120                      getPrintingPolicy());
12121 
12122   Declarator D(DS, DeclaratorContext::ForContext);
12123   D.SetIdentifier(Ident, IdentLoc);
12124   D.takeAttributes(Attrs, AttrEnd);
12125 
12126   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
12127                 IdentLoc);
12128   Decl *Var = ActOnDeclarator(S, D);
12129   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
12130   FinalizeDeclaration(Var);
12131   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
12132                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
12133 }
12134 
12135 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
12136   if (var->isInvalidDecl()) return;
12137 
12138   if (getLangOpts().OpenCL) {
12139     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
12140     // initialiser
12141     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
12142         !var->hasInit()) {
12143       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
12144           << 1 /*Init*/;
12145       var->setInvalidDecl();
12146       return;
12147     }
12148   }
12149 
12150   // In Objective-C, don't allow jumps past the implicit initialization of a
12151   // local retaining variable.
12152   if (getLangOpts().ObjC &&
12153       var->hasLocalStorage()) {
12154     switch (var->getType().getObjCLifetime()) {
12155     case Qualifiers::OCL_None:
12156     case Qualifiers::OCL_ExplicitNone:
12157     case Qualifiers::OCL_Autoreleasing:
12158       break;
12159 
12160     case Qualifiers::OCL_Weak:
12161     case Qualifiers::OCL_Strong:
12162       setFunctionHasBranchProtectedScope();
12163       break;
12164     }
12165   }
12166 
12167   if (var->hasLocalStorage() &&
12168       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
12169     setFunctionHasBranchProtectedScope();
12170 
12171   // Warn about externally-visible variables being defined without a
12172   // prior declaration.  We only want to do this for global
12173   // declarations, but we also specifically need to avoid doing it for
12174   // class members because the linkage of an anonymous class can
12175   // change if it's later given a typedef name.
12176   if (var->isThisDeclarationADefinition() &&
12177       var->getDeclContext()->getRedeclContext()->isFileContext() &&
12178       var->isExternallyVisible() && var->hasLinkage() &&
12179       !var->isInline() && !var->getDescribedVarTemplate() &&
12180       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
12181       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
12182                                   var->getLocation())) {
12183     // Find a previous declaration that's not a definition.
12184     VarDecl *prev = var->getPreviousDecl();
12185     while (prev && prev->isThisDeclarationADefinition())
12186       prev = prev->getPreviousDecl();
12187 
12188     if (!prev) {
12189       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
12190       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
12191           << /* variable */ 0;
12192     }
12193   }
12194 
12195   // Cache the result of checking for constant initialization.
12196   Optional<bool> CacheHasConstInit;
12197   const Expr *CacheCulprit = nullptr;
12198   auto checkConstInit = [&]() mutable {
12199     if (!CacheHasConstInit)
12200       CacheHasConstInit = var->getInit()->isConstantInitializer(
12201             Context, var->getType()->isReferenceType(), &CacheCulprit);
12202     return *CacheHasConstInit;
12203   };
12204 
12205   if (var->getTLSKind() == VarDecl::TLS_Static) {
12206     if (var->getType().isDestructedType()) {
12207       // GNU C++98 edits for __thread, [basic.start.term]p3:
12208       //   The type of an object with thread storage duration shall not
12209       //   have a non-trivial destructor.
12210       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
12211       if (getLangOpts().CPlusPlus11)
12212         Diag(var->getLocation(), diag::note_use_thread_local);
12213     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
12214       if (!checkConstInit()) {
12215         // GNU C++98 edits for __thread, [basic.start.init]p4:
12216         //   An object of thread storage duration shall not require dynamic
12217         //   initialization.
12218         // FIXME: Need strict checking here.
12219         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
12220           << CacheCulprit->getSourceRange();
12221         if (getLangOpts().CPlusPlus11)
12222           Diag(var->getLocation(), diag::note_use_thread_local);
12223       }
12224     }
12225   }
12226 
12227   // Apply section attributes and pragmas to global variables.
12228   bool GlobalStorage = var->hasGlobalStorage();
12229   if (GlobalStorage && var->isThisDeclarationADefinition() &&
12230       !inTemplateInstantiation()) {
12231     PragmaStack<StringLiteral *> *Stack = nullptr;
12232     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
12233     if (var->getType().isConstQualified())
12234       Stack = &ConstSegStack;
12235     else if (!var->getInit()) {
12236       Stack = &BSSSegStack;
12237       SectionFlags |= ASTContext::PSF_Write;
12238     } else {
12239       Stack = &DataSegStack;
12240       SectionFlags |= ASTContext::PSF_Write;
12241     }
12242     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
12243       var->addAttr(SectionAttr::CreateImplicit(
12244           Context, SectionAttr::Declspec_allocate,
12245           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
12246     }
12247     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
12248       if (UnifySection(SA->getName(), SectionFlags, var))
12249         var->dropAttr<SectionAttr>();
12250 
12251     // Apply the init_seg attribute if this has an initializer.  If the
12252     // initializer turns out to not be dynamic, we'll end up ignoring this
12253     // attribute.
12254     if (CurInitSeg && var->getInit())
12255       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
12256                                                CurInitSegLoc));
12257   }
12258 
12259   // All the following checks are C++ only.
12260   if (!getLangOpts().CPlusPlus) {
12261       // If this variable must be emitted, add it as an initializer for the
12262       // current module.
12263      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12264        Context.addModuleInitializer(ModuleScopes.back().Module, var);
12265      return;
12266   }
12267 
12268   if (auto *DD = dyn_cast<DecompositionDecl>(var))
12269     CheckCompleteDecompositionDeclaration(DD);
12270 
12271   QualType type = var->getType();
12272   if (type->isDependentType()) return;
12273 
12274   if (var->hasAttr<BlocksAttr>())
12275     getCurFunction()->addByrefBlockVar(var);
12276 
12277   Expr *Init = var->getInit();
12278   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
12279   QualType baseType = Context.getBaseElementType(type);
12280 
12281   if (Init && !Init->isValueDependent()) {
12282     if (var->isConstexpr()) {
12283       SmallVector<PartialDiagnosticAt, 8> Notes;
12284       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
12285         SourceLocation DiagLoc = var->getLocation();
12286         // If the note doesn't add any useful information other than a source
12287         // location, fold it into the primary diagnostic.
12288         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12289               diag::note_invalid_subexpr_in_const_expr) {
12290           DiagLoc = Notes[0].first;
12291           Notes.clear();
12292         }
12293         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
12294           << var << Init->getSourceRange();
12295         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
12296           Diag(Notes[I].first, Notes[I].second);
12297       }
12298     } else if (var->mightBeUsableInConstantExpressions(Context)) {
12299       // Check whether the initializer of a const variable of integral or
12300       // enumeration type is an ICE now, since we can't tell whether it was
12301       // initialized by a constant expression if we check later.
12302       var->checkInitIsICE();
12303     }
12304 
12305     // Don't emit further diagnostics about constexpr globals since they
12306     // were just diagnosed.
12307     if (!var->isConstexpr() && GlobalStorage &&
12308             var->hasAttr<RequireConstantInitAttr>()) {
12309       // FIXME: Need strict checking in C++03 here.
12310       bool DiagErr = getLangOpts().CPlusPlus11
12311           ? !var->checkInitIsICE() : !checkConstInit();
12312       if (DiagErr) {
12313         auto attr = var->getAttr<RequireConstantInitAttr>();
12314         Diag(var->getLocation(), diag::err_require_constant_init_failed)
12315           << Init->getSourceRange();
12316         Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
12317           << attr->getRange();
12318         if (getLangOpts().CPlusPlus11) {
12319           APValue Value;
12320           SmallVector<PartialDiagnosticAt, 8> Notes;
12321           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
12322           for (auto &it : Notes)
12323             Diag(it.first, it.second);
12324         } else {
12325           Diag(CacheCulprit->getExprLoc(),
12326                diag::note_invalid_subexpr_in_const_expr)
12327               << CacheCulprit->getSourceRange();
12328         }
12329       }
12330     }
12331     else if (!var->isConstexpr() && IsGlobal &&
12332              !getDiagnostics().isIgnored(diag::warn_global_constructor,
12333                                     var->getLocation())) {
12334       // Warn about globals which don't have a constant initializer.  Don't
12335       // warn about globals with a non-trivial destructor because we already
12336       // warned about them.
12337       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
12338       if (!(RD && !RD->hasTrivialDestructor())) {
12339         if (!checkConstInit())
12340           Diag(var->getLocation(), diag::warn_global_constructor)
12341             << Init->getSourceRange();
12342       }
12343     }
12344   }
12345 
12346   // Require the destructor.
12347   if (const RecordType *recordType = baseType->getAs<RecordType>())
12348     FinalizeVarWithDestructor(var, recordType);
12349 
12350   // If this variable must be emitted, add it as an initializer for the current
12351   // module.
12352   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12353     Context.addModuleInitializer(ModuleScopes.back().Module, var);
12354 }
12355 
12356 /// Determines if a variable's alignment is dependent.
12357 static bool hasDependentAlignment(VarDecl *VD) {
12358   if (VD->getType()->isDependentType())
12359     return true;
12360   for (auto *I : VD->specific_attrs<AlignedAttr>())
12361     if (I->isAlignmentDependent())
12362       return true;
12363   return false;
12364 }
12365 
12366 /// Check if VD needs to be dllexport/dllimport due to being in a
12367 /// dllexport/import function.
12368 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
12369   assert(VD->isStaticLocal());
12370 
12371   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12372 
12373   // Find outermost function when VD is in lambda function.
12374   while (FD && !getDLLAttr(FD) &&
12375          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
12376          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
12377     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
12378   }
12379 
12380   if (!FD)
12381     return;
12382 
12383   // Static locals inherit dll attributes from their function.
12384   if (Attr *A = getDLLAttr(FD)) {
12385     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
12386     NewAttr->setInherited(true);
12387     VD->addAttr(NewAttr);
12388   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
12389     auto *NewAttr = ::new (getASTContext()) DLLExportAttr(A->getRange(),
12390                                                           getASTContext(),
12391                                                           A->getSpellingListIndex());
12392     NewAttr->setInherited(true);
12393     VD->addAttr(NewAttr);
12394 
12395     // Export this function to enforce exporting this static variable even
12396     // if it is not used in this compilation unit.
12397     if (!FD->hasAttr<DLLExportAttr>())
12398       FD->addAttr(NewAttr);
12399 
12400   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
12401     auto *NewAttr = ::new (getASTContext()) DLLImportAttr(A->getRange(),
12402                                                           getASTContext(),
12403                                                           A->getSpellingListIndex());
12404     NewAttr->setInherited(true);
12405     VD->addAttr(NewAttr);
12406   }
12407 }
12408 
12409 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
12410 /// any semantic actions necessary after any initializer has been attached.
12411 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
12412   // Note that we are no longer parsing the initializer for this declaration.
12413   ParsingInitForAutoVars.erase(ThisDecl);
12414 
12415   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
12416   if (!VD)
12417     return;
12418 
12419   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
12420   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
12421       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
12422     if (PragmaClangBSSSection.Valid)
12423       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
12424                                                             PragmaClangBSSSection.SectionName,
12425                                                             PragmaClangBSSSection.PragmaLocation));
12426     if (PragmaClangDataSection.Valid)
12427       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
12428                                                              PragmaClangDataSection.SectionName,
12429                                                              PragmaClangDataSection.PragmaLocation));
12430     if (PragmaClangRodataSection.Valid)
12431       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
12432                                                                PragmaClangRodataSection.SectionName,
12433                                                                PragmaClangRodataSection.PragmaLocation));
12434   }
12435 
12436   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
12437     for (auto *BD : DD->bindings()) {
12438       FinalizeDeclaration(BD);
12439     }
12440   }
12441 
12442   checkAttributesAfterMerging(*this, *VD);
12443 
12444   // Perform TLS alignment check here after attributes attached to the variable
12445   // which may affect the alignment have been processed. Only perform the check
12446   // if the target has a maximum TLS alignment (zero means no constraints).
12447   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
12448     // Protect the check so that it's not performed on dependent types and
12449     // dependent alignments (we can't determine the alignment in that case).
12450     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
12451         !VD->isInvalidDecl()) {
12452       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
12453       if (Context.getDeclAlign(VD) > MaxAlignChars) {
12454         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
12455           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
12456           << (unsigned)MaxAlignChars.getQuantity();
12457       }
12458     }
12459   }
12460 
12461   if (VD->isStaticLocal()) {
12462     CheckStaticLocalForDllExport(VD);
12463 
12464     if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
12465       // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
12466       // function, only __shared__ variables or variables without any device
12467       // memory qualifiers may be declared with static storage class.
12468       // Note: It is unclear how a function-scope non-const static variable
12469       // without device memory qualifier is implemented, therefore only static
12470       // const variable without device memory qualifier is allowed.
12471       [&]() {
12472         if (!getLangOpts().CUDA)
12473           return;
12474         if (VD->hasAttr<CUDASharedAttr>())
12475           return;
12476         if (VD->getType().isConstQualified() &&
12477             !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
12478           return;
12479         if (CUDADiagIfDeviceCode(VD->getLocation(),
12480                                  diag::err_device_static_local_var)
12481             << CurrentCUDATarget())
12482           VD->setInvalidDecl();
12483       }();
12484     }
12485   }
12486 
12487   // Perform check for initializers of device-side global variables.
12488   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
12489   // 7.5). We must also apply the same checks to all __shared__
12490   // variables whether they are local or not. CUDA also allows
12491   // constant initializers for __constant__ and __device__ variables.
12492   if (getLangOpts().CUDA)
12493     checkAllowedCUDAInitializer(VD);
12494 
12495   // Grab the dllimport or dllexport attribute off of the VarDecl.
12496   const InheritableAttr *DLLAttr = getDLLAttr(VD);
12497 
12498   // Imported static data members cannot be defined out-of-line.
12499   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
12500     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
12501         VD->isThisDeclarationADefinition()) {
12502       // We allow definitions of dllimport class template static data members
12503       // with a warning.
12504       CXXRecordDecl *Context =
12505         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
12506       bool IsClassTemplateMember =
12507           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
12508           Context->getDescribedClassTemplate();
12509 
12510       Diag(VD->getLocation(),
12511            IsClassTemplateMember
12512                ? diag::warn_attribute_dllimport_static_field_definition
12513                : diag::err_attribute_dllimport_static_field_definition);
12514       Diag(IA->getLocation(), diag::note_attribute);
12515       if (!IsClassTemplateMember)
12516         VD->setInvalidDecl();
12517     }
12518   }
12519 
12520   // dllimport/dllexport variables cannot be thread local, their TLS index
12521   // isn't exported with the variable.
12522   if (DLLAttr && VD->getTLSKind()) {
12523     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12524     if (F && getDLLAttr(F)) {
12525       assert(VD->isStaticLocal());
12526       // But if this is a static local in a dlimport/dllexport function, the
12527       // function will never be inlined, which means the var would never be
12528       // imported, so having it marked import/export is safe.
12529     } else {
12530       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
12531                                                                     << DLLAttr;
12532       VD->setInvalidDecl();
12533     }
12534   }
12535 
12536   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
12537     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
12538       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
12539       VD->dropAttr<UsedAttr>();
12540     }
12541   }
12542 
12543   const DeclContext *DC = VD->getDeclContext();
12544   // If there's a #pragma GCC visibility in scope, and this isn't a class
12545   // member, set the visibility of this variable.
12546   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
12547     AddPushedVisibilityAttribute(VD);
12548 
12549   // FIXME: Warn on unused var template partial specializations.
12550   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
12551     MarkUnusedFileScopedDecl(VD);
12552 
12553   // Now we have parsed the initializer and can update the table of magic
12554   // tag values.
12555   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
12556       !VD->getType()->isIntegralOrEnumerationType())
12557     return;
12558 
12559   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
12560     const Expr *MagicValueExpr = VD->getInit();
12561     if (!MagicValueExpr) {
12562       continue;
12563     }
12564     llvm::APSInt MagicValueInt;
12565     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
12566       Diag(I->getRange().getBegin(),
12567            diag::err_type_tag_for_datatype_not_ice)
12568         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12569       continue;
12570     }
12571     if (MagicValueInt.getActiveBits() > 64) {
12572       Diag(I->getRange().getBegin(),
12573            diag::err_type_tag_for_datatype_too_large)
12574         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12575       continue;
12576     }
12577     uint64_t MagicValue = MagicValueInt.getZExtValue();
12578     RegisterTypeTagForDatatype(I->getArgumentKind(),
12579                                MagicValue,
12580                                I->getMatchingCType(),
12581                                I->getLayoutCompatible(),
12582                                I->getMustBeNull());
12583   }
12584 }
12585 
12586 static bool hasDeducedAuto(DeclaratorDecl *DD) {
12587   auto *VD = dyn_cast<VarDecl>(DD);
12588   return VD && !VD->getType()->hasAutoForTrailingReturnType();
12589 }
12590 
12591 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
12592                                                    ArrayRef<Decl *> Group) {
12593   SmallVector<Decl*, 8> Decls;
12594 
12595   if (DS.isTypeSpecOwned())
12596     Decls.push_back(DS.getRepAsDecl());
12597 
12598   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
12599   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
12600   bool DiagnosedMultipleDecomps = false;
12601   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
12602   bool DiagnosedNonDeducedAuto = false;
12603 
12604   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12605     if (Decl *D = Group[i]) {
12606       // For declarators, there are some additional syntactic-ish checks we need
12607       // to perform.
12608       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
12609         if (!FirstDeclaratorInGroup)
12610           FirstDeclaratorInGroup = DD;
12611         if (!FirstDecompDeclaratorInGroup)
12612           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
12613         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
12614             !hasDeducedAuto(DD))
12615           FirstNonDeducedAutoInGroup = DD;
12616 
12617         if (FirstDeclaratorInGroup != DD) {
12618           // A decomposition declaration cannot be combined with any other
12619           // declaration in the same group.
12620           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
12621             Diag(FirstDecompDeclaratorInGroup->getLocation(),
12622                  diag::err_decomp_decl_not_alone)
12623                 << FirstDeclaratorInGroup->getSourceRange()
12624                 << DD->getSourceRange();
12625             DiagnosedMultipleDecomps = true;
12626           }
12627 
12628           // A declarator that uses 'auto' in any way other than to declare a
12629           // variable with a deduced type cannot be combined with any other
12630           // declarator in the same group.
12631           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
12632             Diag(FirstNonDeducedAutoInGroup->getLocation(),
12633                  diag::err_auto_non_deduced_not_alone)
12634                 << FirstNonDeducedAutoInGroup->getType()
12635                        ->hasAutoForTrailingReturnType()
12636                 << FirstDeclaratorInGroup->getSourceRange()
12637                 << DD->getSourceRange();
12638             DiagnosedNonDeducedAuto = true;
12639           }
12640         }
12641       }
12642 
12643       Decls.push_back(D);
12644     }
12645   }
12646 
12647   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
12648     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
12649       handleTagNumbering(Tag, S);
12650       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
12651           getLangOpts().CPlusPlus)
12652         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
12653     }
12654   }
12655 
12656   return BuildDeclaratorGroup(Decls);
12657 }
12658 
12659 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
12660 /// group, performing any necessary semantic checking.
12661 Sema::DeclGroupPtrTy
12662 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
12663   // C++14 [dcl.spec.auto]p7: (DR1347)
12664   //   If the type that replaces the placeholder type is not the same in each
12665   //   deduction, the program is ill-formed.
12666   if (Group.size() > 1) {
12667     QualType Deduced;
12668     VarDecl *DeducedDecl = nullptr;
12669     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12670       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
12671       if (!D || D->isInvalidDecl())
12672         break;
12673       DeducedType *DT = D->getType()->getContainedDeducedType();
12674       if (!DT || DT->getDeducedType().isNull())
12675         continue;
12676       if (Deduced.isNull()) {
12677         Deduced = DT->getDeducedType();
12678         DeducedDecl = D;
12679       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
12680         auto *AT = dyn_cast<AutoType>(DT);
12681         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
12682              diag::err_auto_different_deductions)
12683           << (AT ? (unsigned)AT->getKeyword() : 3)
12684           << Deduced << DeducedDecl->getDeclName()
12685           << DT->getDeducedType() << D->getDeclName()
12686           << DeducedDecl->getInit()->getSourceRange()
12687           << D->getInit()->getSourceRange();
12688         D->setInvalidDecl();
12689         break;
12690       }
12691     }
12692   }
12693 
12694   ActOnDocumentableDecls(Group);
12695 
12696   return DeclGroupPtrTy::make(
12697       DeclGroupRef::Create(Context, Group.data(), Group.size()));
12698 }
12699 
12700 void Sema::ActOnDocumentableDecl(Decl *D) {
12701   ActOnDocumentableDecls(D);
12702 }
12703 
12704 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
12705   // Don't parse the comment if Doxygen diagnostics are ignored.
12706   if (Group.empty() || !Group[0])
12707     return;
12708 
12709   if (Diags.isIgnored(diag::warn_doc_param_not_found,
12710                       Group[0]->getLocation()) &&
12711       Diags.isIgnored(diag::warn_unknown_comment_command_name,
12712                       Group[0]->getLocation()))
12713     return;
12714 
12715   if (Group.size() >= 2) {
12716     // This is a decl group.  Normally it will contain only declarations
12717     // produced from declarator list.  But in case we have any definitions or
12718     // additional declaration references:
12719     //   'typedef struct S {} S;'
12720     //   'typedef struct S *S;'
12721     //   'struct S *pS;'
12722     // FinalizeDeclaratorGroup adds these as separate declarations.
12723     Decl *MaybeTagDecl = Group[0];
12724     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
12725       Group = Group.slice(1);
12726     }
12727   }
12728 
12729   // See if there are any new comments that are not attached to a decl.
12730   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
12731   if (!Comments.empty() &&
12732       !Comments.back()->isAttached()) {
12733     // There is at least one comment that not attached to a decl.
12734     // Maybe it should be attached to one of these decls?
12735     //
12736     // Note that this way we pick up not only comments that precede the
12737     // declaration, but also comments that *follow* the declaration -- thanks to
12738     // the lookahead in the lexer: we've consumed the semicolon and looked
12739     // ahead through comments.
12740     for (unsigned i = 0, e = Group.size(); i != e; ++i)
12741       Context.getCommentForDecl(Group[i], &PP);
12742   }
12743 }
12744 
12745 /// Common checks for a parameter-declaration that should apply to both function
12746 /// parameters and non-type template parameters.
12747 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
12748   // Check that there are no default arguments inside the type of this
12749   // parameter.
12750   if (getLangOpts().CPlusPlus)
12751     CheckExtraCXXDefaultArguments(D);
12752 
12753   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
12754   if (D.getCXXScopeSpec().isSet()) {
12755     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
12756       << D.getCXXScopeSpec().getRange();
12757   }
12758 
12759   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
12760   // simple identifier except [...irrelevant cases...].
12761   switch (D.getName().getKind()) {
12762   case UnqualifiedIdKind::IK_Identifier:
12763     break;
12764 
12765   case UnqualifiedIdKind::IK_OperatorFunctionId:
12766   case UnqualifiedIdKind::IK_ConversionFunctionId:
12767   case UnqualifiedIdKind::IK_LiteralOperatorId:
12768   case UnqualifiedIdKind::IK_ConstructorName:
12769   case UnqualifiedIdKind::IK_DestructorName:
12770   case UnqualifiedIdKind::IK_ImplicitSelfParam:
12771   case UnqualifiedIdKind::IK_DeductionGuideName:
12772     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
12773       << GetNameForDeclarator(D).getName();
12774     break;
12775 
12776   case UnqualifiedIdKind::IK_TemplateId:
12777   case UnqualifiedIdKind::IK_ConstructorTemplateId:
12778     // GetNameForDeclarator would not produce a useful name in this case.
12779     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
12780     break;
12781   }
12782 }
12783 
12784 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
12785 /// to introduce parameters into function prototype scope.
12786 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
12787   const DeclSpec &DS = D.getDeclSpec();
12788 
12789   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
12790 
12791   // C++03 [dcl.stc]p2 also permits 'auto'.
12792   StorageClass SC = SC_None;
12793   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
12794     SC = SC_Register;
12795     // In C++11, the 'register' storage class specifier is deprecated.
12796     // In C++17, it is not allowed, but we tolerate it as an extension.
12797     if (getLangOpts().CPlusPlus11) {
12798       Diag(DS.getStorageClassSpecLoc(),
12799            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
12800                                      : diag::warn_deprecated_register)
12801         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
12802     }
12803   } else if (getLangOpts().CPlusPlus &&
12804              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
12805     SC = SC_Auto;
12806   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
12807     Diag(DS.getStorageClassSpecLoc(),
12808          diag::err_invalid_storage_class_in_func_decl);
12809     D.getMutableDeclSpec().ClearStorageClassSpecs();
12810   }
12811 
12812   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
12813     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
12814       << DeclSpec::getSpecifierName(TSCS);
12815   if (DS.isInlineSpecified())
12816     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
12817         << getLangOpts().CPlusPlus17;
12818   if (DS.hasConstexprSpecifier())
12819     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
12820         << 0 << (D.getDeclSpec().getConstexprSpecifier() == CSK_consteval);
12821 
12822   DiagnoseFunctionSpecifiers(DS);
12823 
12824   CheckFunctionOrTemplateParamDeclarator(S, D);
12825 
12826   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12827   QualType parmDeclType = TInfo->getType();
12828 
12829   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
12830   IdentifierInfo *II = D.getIdentifier();
12831   if (II) {
12832     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
12833                    ForVisibleRedeclaration);
12834     LookupName(R, S);
12835     if (R.isSingleResult()) {
12836       NamedDecl *PrevDecl = R.getFoundDecl();
12837       if (PrevDecl->isTemplateParameter()) {
12838         // Maybe we will complain about the shadowed template parameter.
12839         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12840         // Just pretend that we didn't see the previous declaration.
12841         PrevDecl = nullptr;
12842       } else if (S->isDeclScope(PrevDecl)) {
12843         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
12844         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12845 
12846         // Recover by removing the name
12847         II = nullptr;
12848         D.SetIdentifier(nullptr, D.getIdentifierLoc());
12849         D.setInvalidType(true);
12850       }
12851     }
12852   }
12853 
12854   // Temporarily put parameter variables in the translation unit, not
12855   // the enclosing context.  This prevents them from accidentally
12856   // looking like class members in C++.
12857   ParmVarDecl *New =
12858       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
12859                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
12860 
12861   if (D.isInvalidType())
12862     New->setInvalidDecl();
12863 
12864   assert(S->isFunctionPrototypeScope());
12865   assert(S->getFunctionPrototypeDepth() >= 1);
12866   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
12867                     S->getNextFunctionPrototypeIndex());
12868 
12869   // Add the parameter declaration into this scope.
12870   S->AddDecl(New);
12871   if (II)
12872     IdResolver.AddDecl(New);
12873 
12874   ProcessDeclAttributes(S, New, D);
12875 
12876   if (D.getDeclSpec().isModulePrivateSpecified())
12877     Diag(New->getLocation(), diag::err_module_private_local)
12878       << 1 << New->getDeclName()
12879       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12880       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12881 
12882   if (New->hasAttr<BlocksAttr>()) {
12883     Diag(New->getLocation(), diag::err_block_on_nonlocal);
12884   }
12885   return New;
12886 }
12887 
12888 /// Synthesizes a variable for a parameter arising from a
12889 /// typedef.
12890 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
12891                                               SourceLocation Loc,
12892                                               QualType T) {
12893   /* FIXME: setting StartLoc == Loc.
12894      Would it be worth to modify callers so as to provide proper source
12895      location for the unnamed parameters, embedding the parameter's type? */
12896   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
12897                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
12898                                            SC_None, nullptr);
12899   Param->setImplicit();
12900   return Param;
12901 }
12902 
12903 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
12904   // Don't diagnose unused-parameter errors in template instantiations; we
12905   // will already have done so in the template itself.
12906   if (inTemplateInstantiation())
12907     return;
12908 
12909   for (const ParmVarDecl *Parameter : Parameters) {
12910     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
12911         !Parameter->hasAttr<UnusedAttr>()) {
12912       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
12913         << Parameter->getDeclName();
12914     }
12915   }
12916 }
12917 
12918 void Sema::DiagnoseSizeOfParametersAndReturnValue(
12919     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
12920   if (LangOpts.NumLargeByValueCopy == 0) // No check.
12921     return;
12922 
12923   // Warn if the return value is pass-by-value and larger than the specified
12924   // threshold.
12925   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
12926     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
12927     if (Size > LangOpts.NumLargeByValueCopy)
12928       Diag(D->getLocation(), diag::warn_return_value_size)
12929           << D->getDeclName() << Size;
12930   }
12931 
12932   // Warn if any parameter is pass-by-value and larger than the specified
12933   // threshold.
12934   for (const ParmVarDecl *Parameter : Parameters) {
12935     QualType T = Parameter->getType();
12936     if (T->isDependentType() || !T.isPODType(Context))
12937       continue;
12938     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
12939     if (Size > LangOpts.NumLargeByValueCopy)
12940       Diag(Parameter->getLocation(), diag::warn_parameter_size)
12941           << Parameter->getDeclName() << Size;
12942   }
12943 }
12944 
12945 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
12946                                   SourceLocation NameLoc, IdentifierInfo *Name,
12947                                   QualType T, TypeSourceInfo *TSInfo,
12948                                   StorageClass SC) {
12949   // In ARC, infer a lifetime qualifier for appropriate parameter types.
12950   if (getLangOpts().ObjCAutoRefCount &&
12951       T.getObjCLifetime() == Qualifiers::OCL_None &&
12952       T->isObjCLifetimeType()) {
12953 
12954     Qualifiers::ObjCLifetime lifetime;
12955 
12956     // Special cases for arrays:
12957     //   - if it's const, use __unsafe_unretained
12958     //   - otherwise, it's an error
12959     if (T->isArrayType()) {
12960       if (!T.isConstQualified()) {
12961         if (DelayedDiagnostics.shouldDelayDiagnostics())
12962           DelayedDiagnostics.add(
12963               sema::DelayedDiagnostic::makeForbiddenType(
12964               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
12965         else
12966           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
12967               << TSInfo->getTypeLoc().getSourceRange();
12968       }
12969       lifetime = Qualifiers::OCL_ExplicitNone;
12970     } else {
12971       lifetime = T->getObjCARCImplicitLifetime();
12972     }
12973     T = Context.getLifetimeQualifiedType(T, lifetime);
12974   }
12975 
12976   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
12977                                          Context.getAdjustedParameterType(T),
12978                                          TSInfo, SC, nullptr);
12979 
12980   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
12981       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
12982     checkNonTrivialCUnion(New->getType(), New->getLocation(),
12983                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
12984 
12985   // Parameters can not be abstract class types.
12986   // For record types, this is done by the AbstractClassUsageDiagnoser once
12987   // the class has been completely parsed.
12988   if (!CurContext->isRecord() &&
12989       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
12990                              AbstractParamType))
12991     New->setInvalidDecl();
12992 
12993   // Parameter declarators cannot be interface types. All ObjC objects are
12994   // passed by reference.
12995   if (T->isObjCObjectType()) {
12996     SourceLocation TypeEndLoc =
12997         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
12998     Diag(NameLoc,
12999          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13000       << FixItHint::CreateInsertion(TypeEndLoc, "*");
13001     T = Context.getObjCObjectPointerType(T);
13002     New->setType(T);
13003   }
13004 
13005   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13006   // duration shall not be qualified by an address-space qualifier."
13007   // Since all parameters have automatic store duration, they can not have
13008   // an address space.
13009   if (T.getAddressSpace() != LangAS::Default &&
13010       // OpenCL allows function arguments declared to be an array of a type
13011       // to be qualified with an address space.
13012       !(getLangOpts().OpenCL &&
13013         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13014     Diag(NameLoc, diag::err_arg_with_address_space);
13015     New->setInvalidDecl();
13016   }
13017 
13018   return New;
13019 }
13020 
13021 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
13022                                            SourceLocation LocAfterDecls) {
13023   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
13024 
13025   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
13026   // for a K&R function.
13027   if (!FTI.hasPrototype) {
13028     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
13029       --i;
13030       if (FTI.Params[i].Param == nullptr) {
13031         SmallString<256> Code;
13032         llvm::raw_svector_ostream(Code)
13033             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
13034         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
13035             << FTI.Params[i].Ident
13036             << FixItHint::CreateInsertion(LocAfterDecls, Code);
13037 
13038         // Implicitly declare the argument as type 'int' for lack of a better
13039         // type.
13040         AttributeFactory attrs;
13041         DeclSpec DS(attrs);
13042         const char* PrevSpec; // unused
13043         unsigned DiagID; // unused
13044         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
13045                            DiagID, Context.getPrintingPolicy());
13046         // Use the identifier location for the type source range.
13047         DS.SetRangeStart(FTI.Params[i].IdentLoc);
13048         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
13049         Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
13050         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
13051         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
13052       }
13053     }
13054   }
13055 }
13056 
13057 Decl *
13058 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
13059                               MultiTemplateParamsArg TemplateParameterLists,
13060                               SkipBodyInfo *SkipBody) {
13061   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
13062   assert(D.isFunctionDeclarator() && "Not a function declarator!");
13063   Scope *ParentScope = FnBodyScope->getParent();
13064 
13065   D.setFunctionDefinitionKind(FDK_Definition);
13066   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
13067   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
13068 }
13069 
13070 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
13071   Consumer.HandleInlineFunctionDefinition(D);
13072 }
13073 
13074 static bool
13075 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
13076                                 const FunctionDecl *&PossiblePrototype) {
13077   // Don't warn about invalid declarations.
13078   if (FD->isInvalidDecl())
13079     return false;
13080 
13081   // Or declarations that aren't global.
13082   if (!FD->isGlobal())
13083     return false;
13084 
13085   // Don't warn about C++ member functions.
13086   if (isa<CXXMethodDecl>(FD))
13087     return false;
13088 
13089   // Don't warn about 'main'.
13090   if (FD->isMain())
13091     return false;
13092 
13093   // Don't warn about inline functions.
13094   if (FD->isInlined())
13095     return false;
13096 
13097   // Don't warn about function templates.
13098   if (FD->getDescribedFunctionTemplate())
13099     return false;
13100 
13101   // Don't warn about function template specializations.
13102   if (FD->isFunctionTemplateSpecialization())
13103     return false;
13104 
13105   // Don't warn for OpenCL kernels.
13106   if (FD->hasAttr<OpenCLKernelAttr>())
13107     return false;
13108 
13109   // Don't warn on explicitly deleted functions.
13110   if (FD->isDeleted())
13111     return false;
13112 
13113   for (const FunctionDecl *Prev = FD->getPreviousDecl();
13114        Prev; Prev = Prev->getPreviousDecl()) {
13115     // Ignore any declarations that occur in function or method
13116     // scope, because they aren't visible from the header.
13117     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
13118       continue;
13119 
13120     PossiblePrototype = Prev;
13121     return Prev->getType()->isFunctionNoProtoType();
13122   }
13123 
13124   return true;
13125 }
13126 
13127 void
13128 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
13129                                    const FunctionDecl *EffectiveDefinition,
13130                                    SkipBodyInfo *SkipBody) {
13131   const FunctionDecl *Definition = EffectiveDefinition;
13132   if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
13133     // If this is a friend function defined in a class template, it does not
13134     // have a body until it is used, nevertheless it is a definition, see
13135     // [temp.inst]p2:
13136     //
13137     // ... for the purpose of determining whether an instantiated redeclaration
13138     // is valid according to [basic.def.odr] and [class.mem], a declaration that
13139     // corresponds to a definition in the template is considered to be a
13140     // definition.
13141     //
13142     // The following code must produce redefinition error:
13143     //
13144     //     template<typename T> struct C20 { friend void func_20() {} };
13145     //     C20<int> c20i;
13146     //     void func_20() {}
13147     //
13148     for (auto I : FD->redecls()) {
13149       if (I != FD && !I->isInvalidDecl() &&
13150           I->getFriendObjectKind() != Decl::FOK_None) {
13151         if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
13152           if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
13153             // A merged copy of the same function, instantiated as a member of
13154             // the same class, is OK.
13155             if (declaresSameEntity(OrigFD, Original) &&
13156                 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
13157                                    cast<Decl>(FD->getLexicalDeclContext())))
13158               continue;
13159           }
13160 
13161           if (Original->isThisDeclarationADefinition()) {
13162             Definition = I;
13163             break;
13164           }
13165         }
13166       }
13167     }
13168   }
13169 
13170   if (!Definition)
13171     // Similar to friend functions a friend function template may be a
13172     // definition and do not have a body if it is instantiated in a class
13173     // template.
13174     if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
13175       for (auto I : FTD->redecls()) {
13176         auto D = cast<FunctionTemplateDecl>(I);
13177         if (D != FTD) {
13178           assert(!D->isThisDeclarationADefinition() &&
13179                  "More than one definition in redeclaration chain");
13180           if (D->getFriendObjectKind() != Decl::FOK_None)
13181             if (FunctionTemplateDecl *FT =
13182                                        D->getInstantiatedFromMemberTemplate()) {
13183               if (FT->isThisDeclarationADefinition()) {
13184                 Definition = D->getTemplatedDecl();
13185                 break;
13186               }
13187             }
13188         }
13189       }
13190     }
13191 
13192   if (!Definition)
13193     return;
13194 
13195   if (canRedefineFunction(Definition, getLangOpts()))
13196     return;
13197 
13198   // Don't emit an error when this is redefinition of a typo-corrected
13199   // definition.
13200   if (TypoCorrectedFunctionDefinitions.count(Definition))
13201     return;
13202 
13203   // If we don't have a visible definition of the function, and it's inline or
13204   // a template, skip the new definition.
13205   if (SkipBody && !hasVisibleDefinition(Definition) &&
13206       (Definition->getFormalLinkage() == InternalLinkage ||
13207        Definition->isInlined() ||
13208        Definition->getDescribedFunctionTemplate() ||
13209        Definition->getNumTemplateParameterLists())) {
13210     SkipBody->ShouldSkip = true;
13211     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
13212     if (auto *TD = Definition->getDescribedFunctionTemplate())
13213       makeMergedDefinitionVisible(TD);
13214     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
13215     return;
13216   }
13217 
13218   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
13219       Definition->getStorageClass() == SC_Extern)
13220     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
13221         << FD->getDeclName() << getLangOpts().CPlusPlus;
13222   else
13223     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
13224 
13225   Diag(Definition->getLocation(), diag::note_previous_definition);
13226   FD->setInvalidDecl();
13227 }
13228 
13229 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
13230                                    Sema &S) {
13231   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
13232 
13233   LambdaScopeInfo *LSI = S.PushLambdaScope();
13234   LSI->CallOperator = CallOperator;
13235   LSI->Lambda = LambdaClass;
13236   LSI->ReturnType = CallOperator->getReturnType();
13237   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
13238 
13239   if (LCD == LCD_None)
13240     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
13241   else if (LCD == LCD_ByCopy)
13242     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
13243   else if (LCD == LCD_ByRef)
13244     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
13245   DeclarationNameInfo DNI = CallOperator->getNameInfo();
13246 
13247   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
13248   LSI->Mutable = !CallOperator->isConst();
13249 
13250   // Add the captures to the LSI so they can be noted as already
13251   // captured within tryCaptureVar.
13252   auto I = LambdaClass->field_begin();
13253   for (const auto &C : LambdaClass->captures()) {
13254     if (C.capturesVariable()) {
13255       VarDecl *VD = C.getCapturedVar();
13256       if (VD->isInitCapture())
13257         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
13258       QualType CaptureType = VD->getType();
13259       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
13260       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
13261           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
13262           /*EllipsisLoc*/C.isPackExpansion()
13263                          ? C.getEllipsisLoc() : SourceLocation(),
13264           CaptureType, /*Invalid*/false);
13265 
13266     } else if (C.capturesThis()) {
13267       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
13268                           C.getCaptureKind() == LCK_StarThis);
13269     } else {
13270       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
13271                              I->getType());
13272     }
13273     ++I;
13274   }
13275 }
13276 
13277 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
13278                                     SkipBodyInfo *SkipBody) {
13279   if (!D) {
13280     // Parsing the function declaration failed in some way. Push on a fake scope
13281     // anyway so we can try to parse the function body.
13282     PushFunctionScope();
13283     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13284     return D;
13285   }
13286 
13287   FunctionDecl *FD = nullptr;
13288 
13289   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
13290     FD = FunTmpl->getTemplatedDecl();
13291   else
13292     FD = cast<FunctionDecl>(D);
13293 
13294   // Do not push if it is a lambda because one is already pushed when building
13295   // the lambda in ActOnStartOfLambdaDefinition().
13296   if (!isLambdaCallOperator(FD))
13297     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13298 
13299   // Check for defining attributes before the check for redefinition.
13300   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
13301     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
13302     FD->dropAttr<AliasAttr>();
13303     FD->setInvalidDecl();
13304   }
13305   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
13306     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
13307     FD->dropAttr<IFuncAttr>();
13308     FD->setInvalidDecl();
13309   }
13310 
13311   // See if this is a redefinition. If 'will have body' is already set, then
13312   // these checks were already performed when it was set.
13313   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
13314     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
13315 
13316     // If we're skipping the body, we're done. Don't enter the scope.
13317     if (SkipBody && SkipBody->ShouldSkip)
13318       return D;
13319   }
13320 
13321   // Mark this function as "will have a body eventually".  This lets users to
13322   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
13323   // this function.
13324   FD->setWillHaveBody();
13325 
13326   // If we are instantiating a generic lambda call operator, push
13327   // a LambdaScopeInfo onto the function stack.  But use the information
13328   // that's already been calculated (ActOnLambdaExpr) to prime the current
13329   // LambdaScopeInfo.
13330   // When the template operator is being specialized, the LambdaScopeInfo,
13331   // has to be properly restored so that tryCaptureVariable doesn't try
13332   // and capture any new variables. In addition when calculating potential
13333   // captures during transformation of nested lambdas, it is necessary to
13334   // have the LSI properly restored.
13335   if (isGenericLambdaCallOperatorSpecialization(FD)) {
13336     assert(inTemplateInstantiation() &&
13337            "There should be an active template instantiation on the stack "
13338            "when instantiating a generic lambda!");
13339     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
13340   } else {
13341     // Enter a new function scope
13342     PushFunctionScope();
13343   }
13344 
13345   // Builtin functions cannot be defined.
13346   if (unsigned BuiltinID = FD->getBuiltinID()) {
13347     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
13348         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
13349       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
13350       FD->setInvalidDecl();
13351     }
13352   }
13353 
13354   // The return type of a function definition must be complete
13355   // (C99 6.9.1p3, C++ [dcl.fct]p6).
13356   QualType ResultType = FD->getReturnType();
13357   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
13358       !FD->isInvalidDecl() &&
13359       RequireCompleteType(FD->getLocation(), ResultType,
13360                           diag::err_func_def_incomplete_result))
13361     FD->setInvalidDecl();
13362 
13363   if (FnBodyScope)
13364     PushDeclContext(FnBodyScope, FD);
13365 
13366   // Check the validity of our function parameters
13367   CheckParmsForFunctionDef(FD->parameters(),
13368                            /*CheckParameterNames=*/true);
13369 
13370   // Add non-parameter declarations already in the function to the current
13371   // scope.
13372   if (FnBodyScope) {
13373     for (Decl *NPD : FD->decls()) {
13374       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
13375       if (!NonParmDecl)
13376         continue;
13377       assert(!isa<ParmVarDecl>(NonParmDecl) &&
13378              "parameters should not be in newly created FD yet");
13379 
13380       // If the decl has a name, make it accessible in the current scope.
13381       if (NonParmDecl->getDeclName())
13382         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
13383 
13384       // Similarly, dive into enums and fish their constants out, making them
13385       // accessible in this scope.
13386       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
13387         for (auto *EI : ED->enumerators())
13388           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
13389       }
13390     }
13391   }
13392 
13393   // Introduce our parameters into the function scope
13394   for (auto Param : FD->parameters()) {
13395     Param->setOwningFunction(FD);
13396 
13397     // If this has an identifier, add it to the scope stack.
13398     if (Param->getIdentifier() && FnBodyScope) {
13399       CheckShadow(FnBodyScope, Param);
13400 
13401       PushOnScopeChains(Param, FnBodyScope);
13402     }
13403   }
13404 
13405   // Ensure that the function's exception specification is instantiated.
13406   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
13407     ResolveExceptionSpec(D->getLocation(), FPT);
13408 
13409   // dllimport cannot be applied to non-inline function definitions.
13410   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
13411       !FD->isTemplateInstantiation()) {
13412     assert(!FD->hasAttr<DLLExportAttr>());
13413     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
13414     FD->setInvalidDecl();
13415     return D;
13416   }
13417   // We want to attach documentation to original Decl (which might be
13418   // a function template).
13419   ActOnDocumentableDecl(D);
13420   if (getCurLexicalContext()->isObjCContainer() &&
13421       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
13422       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
13423     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
13424 
13425   return D;
13426 }
13427 
13428 /// Given the set of return statements within a function body,
13429 /// compute the variables that are subject to the named return value
13430 /// optimization.
13431 ///
13432 /// Each of the variables that is subject to the named return value
13433 /// optimization will be marked as NRVO variables in the AST, and any
13434 /// return statement that has a marked NRVO variable as its NRVO candidate can
13435 /// use the named return value optimization.
13436 ///
13437 /// This function applies a very simplistic algorithm for NRVO: if every return
13438 /// statement in the scope of a variable has the same NRVO candidate, that
13439 /// candidate is an NRVO variable.
13440 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
13441   ReturnStmt **Returns = Scope->Returns.data();
13442 
13443   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
13444     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
13445       if (!NRVOCandidate->isNRVOVariable())
13446         Returns[I]->setNRVOCandidate(nullptr);
13447     }
13448   }
13449 }
13450 
13451 bool Sema::canDelayFunctionBody(const Declarator &D) {
13452   // We can't delay parsing the body of a constexpr function template (yet).
13453   if (D.getDeclSpec().hasConstexprSpecifier())
13454     return false;
13455 
13456   // We can't delay parsing the body of a function template with a deduced
13457   // return type (yet).
13458   if (D.getDeclSpec().hasAutoTypeSpec()) {
13459     // If the placeholder introduces a non-deduced trailing return type,
13460     // we can still delay parsing it.
13461     if (D.getNumTypeObjects()) {
13462       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
13463       if (Outer.Kind == DeclaratorChunk::Function &&
13464           Outer.Fun.hasTrailingReturnType()) {
13465         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
13466         return Ty.isNull() || !Ty->isUndeducedType();
13467       }
13468     }
13469     return false;
13470   }
13471 
13472   return true;
13473 }
13474 
13475 bool Sema::canSkipFunctionBody(Decl *D) {
13476   // We cannot skip the body of a function (or function template) which is
13477   // constexpr, since we may need to evaluate its body in order to parse the
13478   // rest of the file.
13479   // We cannot skip the body of a function with an undeduced return type,
13480   // because any callers of that function need to know the type.
13481   if (const FunctionDecl *FD = D->getAsFunction()) {
13482     if (FD->isConstexpr())
13483       return false;
13484     // We can't simply call Type::isUndeducedType here, because inside template
13485     // auto can be deduced to a dependent type, which is not considered
13486     // "undeduced".
13487     if (FD->getReturnType()->getContainedDeducedType())
13488       return false;
13489   }
13490   return Consumer.shouldSkipFunctionBody(D);
13491 }
13492 
13493 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
13494   if (!Decl)
13495     return nullptr;
13496   if (FunctionDecl *FD = Decl->getAsFunction())
13497     FD->setHasSkippedBody();
13498   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
13499     MD->setHasSkippedBody();
13500   return Decl;
13501 }
13502 
13503 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
13504   return ActOnFinishFunctionBody(D, BodyArg, false);
13505 }
13506 
13507 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
13508 /// body.
13509 class ExitFunctionBodyRAII {
13510 public:
13511   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
13512   ~ExitFunctionBodyRAII() {
13513     if (!IsLambda)
13514       S.PopExpressionEvaluationContext();
13515   }
13516 
13517 private:
13518   Sema &S;
13519   bool IsLambda = false;
13520 };
13521 
13522 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
13523   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
13524 
13525   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
13526     if (EscapeInfo.count(BD))
13527       return EscapeInfo[BD];
13528 
13529     bool R = false;
13530     const BlockDecl *CurBD = BD;
13531 
13532     do {
13533       R = !CurBD->doesNotEscape();
13534       if (R)
13535         break;
13536       CurBD = CurBD->getParent()->getInnermostBlockDecl();
13537     } while (CurBD);
13538 
13539     return EscapeInfo[BD] = R;
13540   };
13541 
13542   // If the location where 'self' is implicitly retained is inside a escaping
13543   // block, emit a diagnostic.
13544   for (const std::pair<SourceLocation, const BlockDecl *> &P :
13545        S.ImplicitlyRetainedSelfLocs)
13546     if (IsOrNestedInEscapingBlock(P.second))
13547       S.Diag(P.first, diag::warn_implicitly_retains_self)
13548           << FixItHint::CreateInsertion(P.first, "self->");
13549 }
13550 
13551 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
13552                                     bool IsInstantiation) {
13553   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
13554 
13555   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13556   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
13557 
13558   if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
13559     CheckCompletedCoroutineBody(FD, Body);
13560 
13561   // Do not call PopExpressionEvaluationContext() if it is a lambda because one
13562   // is already popped when finishing the lambda in BuildLambdaExpr(). This is
13563   // meant to pop the context added in ActOnStartOfFunctionDef().
13564   ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
13565 
13566   if (FD) {
13567     FD->setBody(Body);
13568     FD->setWillHaveBody(false);
13569 
13570     if (getLangOpts().CPlusPlus14) {
13571       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
13572           FD->getReturnType()->isUndeducedType()) {
13573         // If the function has a deduced result type but contains no 'return'
13574         // statements, the result type as written must be exactly 'auto', and
13575         // the deduced result type is 'void'.
13576         if (!FD->getReturnType()->getAs<AutoType>()) {
13577           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
13578               << FD->getReturnType();
13579           FD->setInvalidDecl();
13580         } else {
13581           // Substitute 'void' for the 'auto' in the type.
13582           TypeLoc ResultType = getReturnTypeLoc(FD);
13583           Context.adjustDeducedFunctionResultType(
13584               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
13585         }
13586       }
13587     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
13588       // In C++11, we don't use 'auto' deduction rules for lambda call
13589       // operators because we don't support return type deduction.
13590       auto *LSI = getCurLambda();
13591       if (LSI->HasImplicitReturnType) {
13592         deduceClosureReturnType(*LSI);
13593 
13594         // C++11 [expr.prim.lambda]p4:
13595         //   [...] if there are no return statements in the compound-statement
13596         //   [the deduced type is] the type void
13597         QualType RetType =
13598             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
13599 
13600         // Update the return type to the deduced type.
13601         const FunctionProtoType *Proto =
13602             FD->getType()->getAs<FunctionProtoType>();
13603         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
13604                                             Proto->getExtProtoInfo()));
13605       }
13606     }
13607 
13608     // If the function implicitly returns zero (like 'main') or is naked,
13609     // don't complain about missing return statements.
13610     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
13611       WP.disableCheckFallThrough();
13612 
13613     // MSVC permits the use of pure specifier (=0) on function definition,
13614     // defined at class scope, warn about this non-standard construct.
13615     if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
13616       Diag(FD->getLocation(), diag::ext_pure_function_definition);
13617 
13618     if (!FD->isInvalidDecl()) {
13619       // Don't diagnose unused parameters of defaulted or deleted functions.
13620       if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
13621         DiagnoseUnusedParameters(FD->parameters());
13622       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
13623                                              FD->getReturnType(), FD);
13624 
13625       // If this is a structor, we need a vtable.
13626       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
13627         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
13628       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
13629         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
13630 
13631       // Try to apply the named return value optimization. We have to check
13632       // if we can do this here because lambdas keep return statements around
13633       // to deduce an implicit return type.
13634       if (FD->getReturnType()->isRecordType() &&
13635           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
13636         computeNRVO(Body, getCurFunction());
13637     }
13638 
13639     // GNU warning -Wmissing-prototypes:
13640     //   Warn if a global function is defined without a previous
13641     //   prototype declaration. This warning is issued even if the
13642     //   definition itself provides a prototype. The aim is to detect
13643     //   global functions that fail to be declared in header files.
13644     const FunctionDecl *PossiblePrototype = nullptr;
13645     if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
13646       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
13647 
13648       if (PossiblePrototype) {
13649         // We found a declaration that is not a prototype,
13650         // but that could be a zero-parameter prototype
13651         if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
13652           TypeLoc TL = TI->getTypeLoc();
13653           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
13654             Diag(PossiblePrototype->getLocation(),
13655                  diag::note_declaration_not_a_prototype)
13656                 << (FD->getNumParams() != 0)
13657                 << (FD->getNumParams() == 0
13658                         ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
13659                         : FixItHint{});
13660         }
13661       } else {
13662         Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13663             << /* function */ 1
13664             << (FD->getStorageClass() == SC_None
13665                     ? FixItHint::CreateInsertion(FD->getTypeSpecStartLoc(),
13666                                                  "static ")
13667                     : FixItHint{});
13668       }
13669 
13670       // GNU warning -Wstrict-prototypes
13671       //   Warn if K&R function is defined without a previous declaration.
13672       //   This warning is issued only if the definition itself does not provide
13673       //   a prototype. Only K&R definitions do not provide a prototype.
13674       //   An empty list in a function declarator that is part of a definition
13675       //   of that function specifies that the function has no parameters
13676       //   (C99 6.7.5.3p14)
13677       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
13678           !LangOpts.CPlusPlus) {
13679         TypeSourceInfo *TI = FD->getTypeSourceInfo();
13680         TypeLoc TL = TI->getTypeLoc();
13681         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
13682         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
13683       }
13684     }
13685 
13686     // Warn on CPUDispatch with an actual body.
13687     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
13688       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
13689         if (!CmpndBody->body_empty())
13690           Diag(CmpndBody->body_front()->getBeginLoc(),
13691                diag::warn_dispatch_body_ignored);
13692 
13693     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13694       const CXXMethodDecl *KeyFunction;
13695       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
13696           MD->isVirtual() &&
13697           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
13698           MD == KeyFunction->getCanonicalDecl()) {
13699         // Update the key-function state if necessary for this ABI.
13700         if (FD->isInlined() &&
13701             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13702           Context.setNonKeyFunction(MD);
13703 
13704           // If the newly-chosen key function is already defined, then we
13705           // need to mark the vtable as used retroactively.
13706           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
13707           const FunctionDecl *Definition;
13708           if (KeyFunction && KeyFunction->isDefined(Definition))
13709             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
13710         } else {
13711           // We just defined they key function; mark the vtable as used.
13712           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
13713         }
13714       }
13715     }
13716 
13717     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
13718            "Function parsing confused");
13719   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
13720     assert(MD == getCurMethodDecl() && "Method parsing confused");
13721     MD->setBody(Body);
13722     if (!MD->isInvalidDecl()) {
13723       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
13724                                              MD->getReturnType(), MD);
13725 
13726       if (Body)
13727         computeNRVO(Body, getCurFunction());
13728     }
13729     if (getCurFunction()->ObjCShouldCallSuper) {
13730       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
13731           << MD->getSelector().getAsString();
13732       getCurFunction()->ObjCShouldCallSuper = false;
13733     }
13734     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
13735       const ObjCMethodDecl *InitMethod = nullptr;
13736       bool isDesignated =
13737           MD->isDesignatedInitializerForTheInterface(&InitMethod);
13738       assert(isDesignated && InitMethod);
13739       (void)isDesignated;
13740 
13741       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
13742         auto IFace = MD->getClassInterface();
13743         if (!IFace)
13744           return false;
13745         auto SuperD = IFace->getSuperClass();
13746         if (!SuperD)
13747           return false;
13748         return SuperD->getIdentifier() ==
13749             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
13750       };
13751       // Don't issue this warning for unavailable inits or direct subclasses
13752       // of NSObject.
13753       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
13754         Diag(MD->getLocation(),
13755              diag::warn_objc_designated_init_missing_super_call);
13756         Diag(InitMethod->getLocation(),
13757              diag::note_objc_designated_init_marked_here);
13758       }
13759       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
13760     }
13761     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
13762       // Don't issue this warning for unavaialable inits.
13763       if (!MD->isUnavailable())
13764         Diag(MD->getLocation(),
13765              diag::warn_objc_secondary_init_missing_init_call);
13766       getCurFunction()->ObjCWarnForNoInitDelegation = false;
13767     }
13768 
13769     diagnoseImplicitlyRetainedSelf(*this);
13770   } else {
13771     // Parsing the function declaration failed in some way. Pop the fake scope
13772     // we pushed on.
13773     PopFunctionScopeInfo(ActivePolicy, dcl);
13774     return nullptr;
13775   }
13776 
13777   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13778     DiagnoseUnguardedAvailabilityViolations(dcl);
13779 
13780   assert(!getCurFunction()->ObjCShouldCallSuper &&
13781          "This should only be set for ObjC methods, which should have been "
13782          "handled in the block above.");
13783 
13784   // Verify and clean out per-function state.
13785   if (Body && (!FD || !FD->isDefaulted())) {
13786     // C++ constructors that have function-try-blocks can't have return
13787     // statements in the handlers of that block. (C++ [except.handle]p14)
13788     // Verify this.
13789     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
13790       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
13791 
13792     // Verify that gotos and switch cases don't jump into scopes illegally.
13793     if (getCurFunction()->NeedsScopeChecking() &&
13794         !PP.isCodeCompletionEnabled())
13795       DiagnoseInvalidJumps(Body);
13796 
13797     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
13798       if (!Destructor->getParent()->isDependentType())
13799         CheckDestructor(Destructor);
13800 
13801       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13802                                              Destructor->getParent());
13803     }
13804 
13805     // If any errors have occurred, clear out any temporaries that may have
13806     // been leftover. This ensures that these temporaries won't be picked up for
13807     // deletion in some later function.
13808     if (getDiagnostics().hasErrorOccurred() ||
13809         getDiagnostics().getSuppressAllDiagnostics()) {
13810       DiscardCleanupsInEvaluationContext();
13811     }
13812     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
13813         !isa<FunctionTemplateDecl>(dcl)) {
13814       // Since the body is valid, issue any analysis-based warnings that are
13815       // enabled.
13816       ActivePolicy = &WP;
13817     }
13818 
13819     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
13820         (!CheckConstexprFunctionDecl(FD) ||
13821          !CheckConstexprFunctionBody(FD, Body)))
13822       FD->setInvalidDecl();
13823 
13824     if (FD && FD->hasAttr<NakedAttr>()) {
13825       for (const Stmt *S : Body->children()) {
13826         // Allow local register variables without initializer as they don't
13827         // require prologue.
13828         bool RegisterVariables = false;
13829         if (auto *DS = dyn_cast<DeclStmt>(S)) {
13830           for (const auto *Decl : DS->decls()) {
13831             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
13832               RegisterVariables =
13833                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
13834               if (!RegisterVariables)
13835                 break;
13836             }
13837           }
13838         }
13839         if (RegisterVariables)
13840           continue;
13841         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
13842           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
13843           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
13844           FD->setInvalidDecl();
13845           break;
13846         }
13847       }
13848     }
13849 
13850     assert(ExprCleanupObjects.size() ==
13851                ExprEvalContexts.back().NumCleanupObjects &&
13852            "Leftover temporaries in function");
13853     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
13854     assert(MaybeODRUseExprs.empty() &&
13855            "Leftover expressions for odr-use checking");
13856   }
13857 
13858   if (!IsInstantiation)
13859     PopDeclContext();
13860 
13861   PopFunctionScopeInfo(ActivePolicy, dcl);
13862   // If any errors have occurred, clear out any temporaries that may have
13863   // been leftover. This ensures that these temporaries won't be picked up for
13864   // deletion in some later function.
13865   if (getDiagnostics().hasErrorOccurred()) {
13866     DiscardCleanupsInEvaluationContext();
13867   }
13868 
13869   return dcl;
13870 }
13871 
13872 /// When we finish delayed parsing of an attribute, we must attach it to the
13873 /// relevant Decl.
13874 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
13875                                        ParsedAttributes &Attrs) {
13876   // Always attach attributes to the underlying decl.
13877   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
13878     D = TD->getTemplatedDecl();
13879   ProcessDeclAttributeList(S, D, Attrs);
13880 
13881   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
13882     if (Method->isStatic())
13883       checkThisInStaticMemberFunctionAttributes(Method);
13884 }
13885 
13886 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
13887 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
13888 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
13889                                           IdentifierInfo &II, Scope *S) {
13890   // Find the scope in which the identifier is injected and the corresponding
13891   // DeclContext.
13892   // FIXME: C89 does not say what happens if there is no enclosing block scope.
13893   // In that case, we inject the declaration into the translation unit scope
13894   // instead.
13895   Scope *BlockScope = S;
13896   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
13897     BlockScope = BlockScope->getParent();
13898 
13899   Scope *ContextScope = BlockScope;
13900   while (!ContextScope->getEntity())
13901     ContextScope = ContextScope->getParent();
13902   ContextRAII SavedContext(*this, ContextScope->getEntity());
13903 
13904   // Before we produce a declaration for an implicitly defined
13905   // function, see whether there was a locally-scoped declaration of
13906   // this name as a function or variable. If so, use that
13907   // (non-visible) declaration, and complain about it.
13908   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
13909   if (ExternCPrev) {
13910     // We still need to inject the function into the enclosing block scope so
13911     // that later (non-call) uses can see it.
13912     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
13913 
13914     // C89 footnote 38:
13915     //   If in fact it is not defined as having type "function returning int",
13916     //   the behavior is undefined.
13917     if (!isa<FunctionDecl>(ExternCPrev) ||
13918         !Context.typesAreCompatible(
13919             cast<FunctionDecl>(ExternCPrev)->getType(),
13920             Context.getFunctionNoProtoType(Context.IntTy))) {
13921       Diag(Loc, diag::ext_use_out_of_scope_declaration)
13922           << ExternCPrev << !getLangOpts().C99;
13923       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
13924       return ExternCPrev;
13925     }
13926   }
13927 
13928   // Extension in C99.  Legal in C90, but warn about it.
13929   unsigned diag_id;
13930   if (II.getName().startswith("__builtin_"))
13931     diag_id = diag::warn_builtin_unknown;
13932   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
13933   else if (getLangOpts().OpenCL)
13934     diag_id = diag::err_opencl_implicit_function_decl;
13935   else if (getLangOpts().C99)
13936     diag_id = diag::ext_implicit_function_decl;
13937   else
13938     diag_id = diag::warn_implicit_function_decl;
13939   Diag(Loc, diag_id) << &II;
13940 
13941   // If we found a prior declaration of this function, don't bother building
13942   // another one. We've already pushed that one into scope, so there's nothing
13943   // more to do.
13944   if (ExternCPrev)
13945     return ExternCPrev;
13946 
13947   // Because typo correction is expensive, only do it if the implicit
13948   // function declaration is going to be treated as an error.
13949   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
13950     TypoCorrection Corrected;
13951     DeclFilterCCC<FunctionDecl> CCC{};
13952     if (S && (Corrected =
13953                   CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
13954                               S, nullptr, CCC, CTK_NonError)))
13955       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
13956                    /*ErrorRecovery*/false);
13957   }
13958 
13959   // Set a Declarator for the implicit definition: int foo();
13960   const char *Dummy;
13961   AttributeFactory attrFactory;
13962   DeclSpec DS(attrFactory);
13963   unsigned DiagID;
13964   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
13965                                   Context.getPrintingPolicy());
13966   (void)Error; // Silence warning.
13967   assert(!Error && "Error setting up implicit decl!");
13968   SourceLocation NoLoc;
13969   Declarator D(DS, DeclaratorContext::BlockContext);
13970   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
13971                                              /*IsAmbiguous=*/false,
13972                                              /*LParenLoc=*/NoLoc,
13973                                              /*Params=*/nullptr,
13974                                              /*NumParams=*/0,
13975                                              /*EllipsisLoc=*/NoLoc,
13976                                              /*RParenLoc=*/NoLoc,
13977                                              /*RefQualifierIsLvalueRef=*/true,
13978                                              /*RefQualifierLoc=*/NoLoc,
13979                                              /*MutableLoc=*/NoLoc, EST_None,
13980                                              /*ESpecRange=*/SourceRange(),
13981                                              /*Exceptions=*/nullptr,
13982                                              /*ExceptionRanges=*/nullptr,
13983                                              /*NumExceptions=*/0,
13984                                              /*NoexceptExpr=*/nullptr,
13985                                              /*ExceptionSpecTokens=*/nullptr,
13986                                              /*DeclsInPrototype=*/None, Loc,
13987                                              Loc, D),
13988                 std::move(DS.getAttributes()), SourceLocation());
13989   D.SetIdentifier(&II, Loc);
13990 
13991   // Insert this function into the enclosing block scope.
13992   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
13993   FD->setImplicit();
13994 
13995   AddKnownFunctionAttributes(FD);
13996 
13997   return FD;
13998 }
13999 
14000 /// Adds any function attributes that we know a priori based on
14001 /// the declaration of this function.
14002 ///
14003 /// These attributes can apply both to implicitly-declared builtins
14004 /// (like __builtin___printf_chk) or to library-declared functions
14005 /// like NSLog or printf.
14006 ///
14007 /// We need to check for duplicate attributes both here and where user-written
14008 /// attributes are applied to declarations.
14009 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
14010   if (FD->isInvalidDecl())
14011     return;
14012 
14013   // If this is a built-in function, map its builtin attributes to
14014   // actual attributes.
14015   if (unsigned BuiltinID = FD->getBuiltinID()) {
14016     // Handle printf-formatting attributes.
14017     unsigned FormatIdx;
14018     bool HasVAListArg;
14019     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
14020       if (!FD->hasAttr<FormatAttr>()) {
14021         const char *fmt = "printf";
14022         unsigned int NumParams = FD->getNumParams();
14023         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
14024             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
14025           fmt = "NSString";
14026         FD->addAttr(FormatAttr::CreateImplicit(Context,
14027                                                &Context.Idents.get(fmt),
14028                                                FormatIdx+1,
14029                                                HasVAListArg ? 0 : FormatIdx+2,
14030                                                FD->getLocation()));
14031       }
14032     }
14033     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
14034                                              HasVAListArg)) {
14035      if (!FD->hasAttr<FormatAttr>())
14036        FD->addAttr(FormatAttr::CreateImplicit(Context,
14037                                               &Context.Idents.get("scanf"),
14038                                               FormatIdx+1,
14039                                               HasVAListArg ? 0 : FormatIdx+2,
14040                                               FD->getLocation()));
14041     }
14042 
14043     // Handle automatically recognized callbacks.
14044     SmallVector<int, 4> Encoding;
14045     if (!FD->hasAttr<CallbackAttr>() &&
14046         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
14047       FD->addAttr(CallbackAttr::CreateImplicit(
14048           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
14049 
14050     // Mark const if we don't care about errno and that is the only thing
14051     // preventing the function from being const. This allows IRgen to use LLVM
14052     // intrinsics for such functions.
14053     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
14054         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
14055       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14056 
14057     // We make "fma" on some platforms const because we know it does not set
14058     // errno in those environments even though it could set errno based on the
14059     // C standard.
14060     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
14061     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
14062         !FD->hasAttr<ConstAttr>()) {
14063       switch (BuiltinID) {
14064       case Builtin::BI__builtin_fma:
14065       case Builtin::BI__builtin_fmaf:
14066       case Builtin::BI__builtin_fmal:
14067       case Builtin::BIfma:
14068       case Builtin::BIfmaf:
14069       case Builtin::BIfmal:
14070         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14071         break;
14072       default:
14073         break;
14074       }
14075     }
14076 
14077     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
14078         !FD->hasAttr<ReturnsTwiceAttr>())
14079       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
14080                                          FD->getLocation()));
14081     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
14082       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14083     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
14084       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
14085     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
14086       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14087     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
14088         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
14089       // Add the appropriate attribute, depending on the CUDA compilation mode
14090       // and which target the builtin belongs to. For example, during host
14091       // compilation, aux builtins are __device__, while the rest are __host__.
14092       if (getLangOpts().CUDAIsDevice !=
14093           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
14094         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
14095       else
14096         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
14097     }
14098   }
14099 
14100   // If C++ exceptions are enabled but we are told extern "C" functions cannot
14101   // throw, add an implicit nothrow attribute to any extern "C" function we come
14102   // across.
14103   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
14104       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
14105     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
14106     if (!FPT || FPT->getExceptionSpecType() == EST_None)
14107       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14108   }
14109 
14110   IdentifierInfo *Name = FD->getIdentifier();
14111   if (!Name)
14112     return;
14113   if ((!getLangOpts().CPlusPlus &&
14114        FD->getDeclContext()->isTranslationUnit()) ||
14115       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
14116        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
14117        LinkageSpecDecl::lang_c)) {
14118     // Okay: this could be a libc/libm/Objective-C function we know
14119     // about.
14120   } else
14121     return;
14122 
14123   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
14124     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
14125     // target-specific builtins, perhaps?
14126     if (!FD->hasAttr<FormatAttr>())
14127       FD->addAttr(FormatAttr::CreateImplicit(Context,
14128                                              &Context.Idents.get("printf"), 2,
14129                                              Name->isStr("vasprintf") ? 0 : 3,
14130                                              FD->getLocation()));
14131   }
14132 
14133   if (Name->isStr("__CFStringMakeConstantString")) {
14134     // We already have a __builtin___CFStringMakeConstantString,
14135     // but builds that use -fno-constant-cfstrings don't go through that.
14136     if (!FD->hasAttr<FormatArgAttr>())
14137       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
14138                                                 FD->getLocation()));
14139   }
14140 }
14141 
14142 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
14143                                     TypeSourceInfo *TInfo) {
14144   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
14145   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
14146 
14147   if (!TInfo) {
14148     assert(D.isInvalidType() && "no declarator info for valid type");
14149     TInfo = Context.getTrivialTypeSourceInfo(T);
14150   }
14151 
14152   // Scope manipulation handled by caller.
14153   TypedefDecl *NewTD =
14154       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
14155                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
14156 
14157   // Bail out immediately if we have an invalid declaration.
14158   if (D.isInvalidType()) {
14159     NewTD->setInvalidDecl();
14160     return NewTD;
14161   }
14162 
14163   if (D.getDeclSpec().isModulePrivateSpecified()) {
14164     if (CurContext->isFunctionOrMethod())
14165       Diag(NewTD->getLocation(), diag::err_module_private_local)
14166         << 2 << NewTD->getDeclName()
14167         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14168         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
14169     else
14170       NewTD->setModulePrivate();
14171   }
14172 
14173   // C++ [dcl.typedef]p8:
14174   //   If the typedef declaration defines an unnamed class (or
14175   //   enum), the first typedef-name declared by the declaration
14176   //   to be that class type (or enum type) is used to denote the
14177   //   class type (or enum type) for linkage purposes only.
14178   // We need to check whether the type was declared in the declaration.
14179   switch (D.getDeclSpec().getTypeSpecType()) {
14180   case TST_enum:
14181   case TST_struct:
14182   case TST_interface:
14183   case TST_union:
14184   case TST_class: {
14185     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
14186     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
14187     break;
14188   }
14189 
14190   default:
14191     break;
14192   }
14193 
14194   return NewTD;
14195 }
14196 
14197 /// Check that this is a valid underlying type for an enum declaration.
14198 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
14199   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
14200   QualType T = TI->getType();
14201 
14202   if (T->isDependentType())
14203     return false;
14204 
14205   if (const BuiltinType *BT = T->getAs<BuiltinType>())
14206     if (BT->isInteger())
14207       return false;
14208 
14209   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
14210   return true;
14211 }
14212 
14213 /// Check whether this is a valid redeclaration of a previous enumeration.
14214 /// \return true if the redeclaration was invalid.
14215 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
14216                                   QualType EnumUnderlyingTy, bool IsFixed,
14217                                   const EnumDecl *Prev) {
14218   if (IsScoped != Prev->isScoped()) {
14219     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
14220       << Prev->isScoped();
14221     Diag(Prev->getLocation(), diag::note_previous_declaration);
14222     return true;
14223   }
14224 
14225   if (IsFixed && Prev->isFixed()) {
14226     if (!EnumUnderlyingTy->isDependentType() &&
14227         !Prev->getIntegerType()->isDependentType() &&
14228         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
14229                                         Prev->getIntegerType())) {
14230       // TODO: Highlight the underlying type of the redeclaration.
14231       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
14232         << EnumUnderlyingTy << Prev->getIntegerType();
14233       Diag(Prev->getLocation(), diag::note_previous_declaration)
14234           << Prev->getIntegerTypeRange();
14235       return true;
14236     }
14237   } else if (IsFixed != Prev->isFixed()) {
14238     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
14239       << Prev->isFixed();
14240     Diag(Prev->getLocation(), diag::note_previous_declaration);
14241     return true;
14242   }
14243 
14244   return false;
14245 }
14246 
14247 /// Get diagnostic %select index for tag kind for
14248 /// redeclaration diagnostic message.
14249 /// WARNING: Indexes apply to particular diagnostics only!
14250 ///
14251 /// \returns diagnostic %select index.
14252 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
14253   switch (Tag) {
14254   case TTK_Struct: return 0;
14255   case TTK_Interface: return 1;
14256   case TTK_Class:  return 2;
14257   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
14258   }
14259 }
14260 
14261 /// Determine if tag kind is a class-key compatible with
14262 /// class for redeclaration (class, struct, or __interface).
14263 ///
14264 /// \returns true iff the tag kind is compatible.
14265 static bool isClassCompatTagKind(TagTypeKind Tag)
14266 {
14267   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
14268 }
14269 
14270 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
14271                                              TagTypeKind TTK) {
14272   if (isa<TypedefDecl>(PrevDecl))
14273     return NTK_Typedef;
14274   else if (isa<TypeAliasDecl>(PrevDecl))
14275     return NTK_TypeAlias;
14276   else if (isa<ClassTemplateDecl>(PrevDecl))
14277     return NTK_Template;
14278   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
14279     return NTK_TypeAliasTemplate;
14280   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
14281     return NTK_TemplateTemplateArgument;
14282   switch (TTK) {
14283   case TTK_Struct:
14284   case TTK_Interface:
14285   case TTK_Class:
14286     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
14287   case TTK_Union:
14288     return NTK_NonUnion;
14289   case TTK_Enum:
14290     return NTK_NonEnum;
14291   }
14292   llvm_unreachable("invalid TTK");
14293 }
14294 
14295 /// Determine whether a tag with a given kind is acceptable
14296 /// as a redeclaration of the given tag declaration.
14297 ///
14298 /// \returns true if the new tag kind is acceptable, false otherwise.
14299 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
14300                                         TagTypeKind NewTag, bool isDefinition,
14301                                         SourceLocation NewTagLoc,
14302                                         const IdentifierInfo *Name) {
14303   // C++ [dcl.type.elab]p3:
14304   //   The class-key or enum keyword present in the
14305   //   elaborated-type-specifier shall agree in kind with the
14306   //   declaration to which the name in the elaborated-type-specifier
14307   //   refers. This rule also applies to the form of
14308   //   elaborated-type-specifier that declares a class-name or
14309   //   friend class since it can be construed as referring to the
14310   //   definition of the class. Thus, in any
14311   //   elaborated-type-specifier, the enum keyword shall be used to
14312   //   refer to an enumeration (7.2), the union class-key shall be
14313   //   used to refer to a union (clause 9), and either the class or
14314   //   struct class-key shall be used to refer to a class (clause 9)
14315   //   declared using the class or struct class-key.
14316   TagTypeKind OldTag = Previous->getTagKind();
14317   if (OldTag != NewTag &&
14318       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
14319     return false;
14320 
14321   // Tags are compatible, but we might still want to warn on mismatched tags.
14322   // Non-class tags can't be mismatched at this point.
14323   if (!isClassCompatTagKind(NewTag))
14324     return true;
14325 
14326   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
14327   // by our warning analysis. We don't want to warn about mismatches with (eg)
14328   // declarations in system headers that are designed to be specialized, but if
14329   // a user asks us to warn, we should warn if their code contains mismatched
14330   // declarations.
14331   auto IsIgnoredLoc = [&](SourceLocation Loc) {
14332     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
14333                                       Loc);
14334   };
14335   if (IsIgnoredLoc(NewTagLoc))
14336     return true;
14337 
14338   auto IsIgnored = [&](const TagDecl *Tag) {
14339     return IsIgnoredLoc(Tag->getLocation());
14340   };
14341   while (IsIgnored(Previous)) {
14342     Previous = Previous->getPreviousDecl();
14343     if (!Previous)
14344       return true;
14345     OldTag = Previous->getTagKind();
14346   }
14347 
14348   bool isTemplate = false;
14349   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
14350     isTemplate = Record->getDescribedClassTemplate();
14351 
14352   if (inTemplateInstantiation()) {
14353     if (OldTag != NewTag) {
14354       // In a template instantiation, do not offer fix-its for tag mismatches
14355       // since they usually mess up the template instead of fixing the problem.
14356       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14357         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14358         << getRedeclDiagFromTagKind(OldTag);
14359       // FIXME: Note previous location?
14360     }
14361     return true;
14362   }
14363 
14364   if (isDefinition) {
14365     // On definitions, check all previous tags and issue a fix-it for each
14366     // one that doesn't match the current tag.
14367     if (Previous->getDefinition()) {
14368       // Don't suggest fix-its for redefinitions.
14369       return true;
14370     }
14371 
14372     bool previousMismatch = false;
14373     for (const TagDecl *I : Previous->redecls()) {
14374       if (I->getTagKind() != NewTag) {
14375         // Ignore previous declarations for which the warning was disabled.
14376         if (IsIgnored(I))
14377           continue;
14378 
14379         if (!previousMismatch) {
14380           previousMismatch = true;
14381           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
14382             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14383             << getRedeclDiagFromTagKind(I->getTagKind());
14384         }
14385         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
14386           << getRedeclDiagFromTagKind(NewTag)
14387           << FixItHint::CreateReplacement(I->getInnerLocStart(),
14388                TypeWithKeyword::getTagTypeKindName(NewTag));
14389       }
14390     }
14391     return true;
14392   }
14393 
14394   // Identify the prevailing tag kind: this is the kind of the definition (if
14395   // there is a non-ignored definition), or otherwise the kind of the prior
14396   // (non-ignored) declaration.
14397   const TagDecl *PrevDef = Previous->getDefinition();
14398   if (PrevDef && IsIgnored(PrevDef))
14399     PrevDef = nullptr;
14400   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
14401   if (Redecl->getTagKind() != NewTag) {
14402     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14403       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14404       << getRedeclDiagFromTagKind(OldTag);
14405     Diag(Redecl->getLocation(), diag::note_previous_use);
14406 
14407     // If there is a previous definition, suggest a fix-it.
14408     if (PrevDef) {
14409       Diag(NewTagLoc, diag::note_struct_class_suggestion)
14410         << getRedeclDiagFromTagKind(Redecl->getTagKind())
14411         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
14412              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
14413     }
14414   }
14415 
14416   return true;
14417 }
14418 
14419 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
14420 /// from an outer enclosing namespace or file scope inside a friend declaration.
14421 /// This should provide the commented out code in the following snippet:
14422 ///   namespace N {
14423 ///     struct X;
14424 ///     namespace M {
14425 ///       struct Y { friend struct /*N::*/ X; };
14426 ///     }
14427 ///   }
14428 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
14429                                          SourceLocation NameLoc) {
14430   // While the decl is in a namespace, do repeated lookup of that name and see
14431   // if we get the same namespace back.  If we do not, continue until
14432   // translation unit scope, at which point we have a fully qualified NNS.
14433   SmallVector<IdentifierInfo *, 4> Namespaces;
14434   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14435   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
14436     // This tag should be declared in a namespace, which can only be enclosed by
14437     // other namespaces.  Bail if there's an anonymous namespace in the chain.
14438     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
14439     if (!Namespace || Namespace->isAnonymousNamespace())
14440       return FixItHint();
14441     IdentifierInfo *II = Namespace->getIdentifier();
14442     Namespaces.push_back(II);
14443     NamedDecl *Lookup = SemaRef.LookupSingleName(
14444         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
14445     if (Lookup == Namespace)
14446       break;
14447   }
14448 
14449   // Once we have all the namespaces, reverse them to go outermost first, and
14450   // build an NNS.
14451   SmallString<64> Insertion;
14452   llvm::raw_svector_ostream OS(Insertion);
14453   if (DC->isTranslationUnit())
14454     OS << "::";
14455   std::reverse(Namespaces.begin(), Namespaces.end());
14456   for (auto *II : Namespaces)
14457     OS << II->getName() << "::";
14458   return FixItHint::CreateInsertion(NameLoc, Insertion);
14459 }
14460 
14461 /// Determine whether a tag originally declared in context \p OldDC can
14462 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
14463 /// found a declaration in \p OldDC as a previous decl, perhaps through a
14464 /// using-declaration).
14465 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
14466                                          DeclContext *NewDC) {
14467   OldDC = OldDC->getRedeclContext();
14468   NewDC = NewDC->getRedeclContext();
14469 
14470   if (OldDC->Equals(NewDC))
14471     return true;
14472 
14473   // In MSVC mode, we allow a redeclaration if the contexts are related (either
14474   // encloses the other).
14475   if (S.getLangOpts().MSVCCompat &&
14476       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
14477     return true;
14478 
14479   return false;
14480 }
14481 
14482 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
14483 /// former case, Name will be non-null.  In the later case, Name will be null.
14484 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
14485 /// reference/declaration/definition of a tag.
14486 ///
14487 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
14488 /// trailing-type-specifier) other than one in an alias-declaration.
14489 ///
14490 /// \param SkipBody If non-null, will be set to indicate if the caller should
14491 /// skip the definition of this tag and treat it as if it were a declaration.
14492 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
14493                      SourceLocation KWLoc, CXXScopeSpec &SS,
14494                      IdentifierInfo *Name, SourceLocation NameLoc,
14495                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
14496                      SourceLocation ModulePrivateLoc,
14497                      MultiTemplateParamsArg TemplateParameterLists,
14498                      bool &OwnedDecl, bool &IsDependent,
14499                      SourceLocation ScopedEnumKWLoc,
14500                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
14501                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
14502                      SkipBodyInfo *SkipBody) {
14503   // If this is not a definition, it must have a name.
14504   IdentifierInfo *OrigName = Name;
14505   assert((Name != nullptr || TUK == TUK_Definition) &&
14506          "Nameless record must be a definition!");
14507   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
14508 
14509   OwnedDecl = false;
14510   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14511   bool ScopedEnum = ScopedEnumKWLoc.isValid();
14512 
14513   // FIXME: Check member specializations more carefully.
14514   bool isMemberSpecialization = false;
14515   bool Invalid = false;
14516 
14517   // We only need to do this matching if we have template parameters
14518   // or a scope specifier, which also conveniently avoids this work
14519   // for non-C++ cases.
14520   if (TemplateParameterLists.size() > 0 ||
14521       (SS.isNotEmpty() && TUK != TUK_Reference)) {
14522     if (TemplateParameterList *TemplateParams =
14523             MatchTemplateParametersToScopeSpecifier(
14524                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
14525                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
14526       if (Kind == TTK_Enum) {
14527         Diag(KWLoc, diag::err_enum_template);
14528         return nullptr;
14529       }
14530 
14531       if (TemplateParams->size() > 0) {
14532         // This is a declaration or definition of a class template (which may
14533         // be a member of another template).
14534 
14535         if (Invalid)
14536           return nullptr;
14537 
14538         OwnedDecl = false;
14539         DeclResult Result = CheckClassTemplate(
14540             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
14541             AS, ModulePrivateLoc,
14542             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
14543             TemplateParameterLists.data(), SkipBody);
14544         return Result.get();
14545       } else {
14546         // The "template<>" header is extraneous.
14547         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14548           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14549         isMemberSpecialization = true;
14550       }
14551     }
14552   }
14553 
14554   // Figure out the underlying type if this a enum declaration. We need to do
14555   // this early, because it's needed to detect if this is an incompatible
14556   // redeclaration.
14557   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
14558   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
14559 
14560   if (Kind == TTK_Enum) {
14561     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
14562       // No underlying type explicitly specified, or we failed to parse the
14563       // type, default to int.
14564       EnumUnderlying = Context.IntTy.getTypePtr();
14565     } else if (UnderlyingType.get()) {
14566       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
14567       // integral type; any cv-qualification is ignored.
14568       TypeSourceInfo *TI = nullptr;
14569       GetTypeFromParser(UnderlyingType.get(), &TI);
14570       EnumUnderlying = TI;
14571 
14572       if (CheckEnumUnderlyingType(TI))
14573         // Recover by falling back to int.
14574         EnumUnderlying = Context.IntTy.getTypePtr();
14575 
14576       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
14577                                           UPPC_FixedUnderlyingType))
14578         EnumUnderlying = Context.IntTy.getTypePtr();
14579 
14580     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14581       // For MSVC ABI compatibility, unfixed enums must use an underlying type
14582       // of 'int'. However, if this is an unfixed forward declaration, don't set
14583       // the underlying type unless the user enables -fms-compatibility. This
14584       // makes unfixed forward declared enums incomplete and is more conforming.
14585       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
14586         EnumUnderlying = Context.IntTy.getTypePtr();
14587     }
14588   }
14589 
14590   DeclContext *SearchDC = CurContext;
14591   DeclContext *DC = CurContext;
14592   bool isStdBadAlloc = false;
14593   bool isStdAlignValT = false;
14594 
14595   RedeclarationKind Redecl = forRedeclarationInCurContext();
14596   if (TUK == TUK_Friend || TUK == TUK_Reference)
14597     Redecl = NotForRedeclaration;
14598 
14599   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
14600   /// implemented asks for structural equivalence checking, the returned decl
14601   /// here is passed back to the parser, allowing the tag body to be parsed.
14602   auto createTagFromNewDecl = [&]() -> TagDecl * {
14603     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
14604     // If there is an identifier, use the location of the identifier as the
14605     // location of the decl, otherwise use the location of the struct/union
14606     // keyword.
14607     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14608     TagDecl *New = nullptr;
14609 
14610     if (Kind == TTK_Enum) {
14611       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
14612                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
14613       // If this is an undefined enum, bail.
14614       if (TUK != TUK_Definition && !Invalid)
14615         return nullptr;
14616       if (EnumUnderlying) {
14617         EnumDecl *ED = cast<EnumDecl>(New);
14618         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
14619           ED->setIntegerTypeSourceInfo(TI);
14620         else
14621           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
14622         ED->setPromotionType(ED->getIntegerType());
14623       }
14624     } else { // struct/union
14625       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14626                                nullptr);
14627     }
14628 
14629     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14630       // Add alignment attributes if necessary; these attributes are checked
14631       // when the ASTContext lays out the structure.
14632       //
14633       // It is important for implementing the correct semantics that this
14634       // happen here (in ActOnTag). The #pragma pack stack is
14635       // maintained as a result of parser callbacks which can occur at
14636       // many points during the parsing of a struct declaration (because
14637       // the #pragma tokens are effectively skipped over during the
14638       // parsing of the struct).
14639       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
14640         AddAlignmentAttributesForRecord(RD);
14641         AddMsStructLayoutForRecord(RD);
14642       }
14643     }
14644     New->setLexicalDeclContext(CurContext);
14645     return New;
14646   };
14647 
14648   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
14649   if (Name && SS.isNotEmpty()) {
14650     // We have a nested-name tag ('struct foo::bar').
14651 
14652     // Check for invalid 'foo::'.
14653     if (SS.isInvalid()) {
14654       Name = nullptr;
14655       goto CreateNewDecl;
14656     }
14657 
14658     // If this is a friend or a reference to a class in a dependent
14659     // context, don't try to make a decl for it.
14660     if (TUK == TUK_Friend || TUK == TUK_Reference) {
14661       DC = computeDeclContext(SS, false);
14662       if (!DC) {
14663         IsDependent = true;
14664         return nullptr;
14665       }
14666     } else {
14667       DC = computeDeclContext(SS, true);
14668       if (!DC) {
14669         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
14670           << SS.getRange();
14671         return nullptr;
14672       }
14673     }
14674 
14675     if (RequireCompleteDeclContext(SS, DC))
14676       return nullptr;
14677 
14678     SearchDC = DC;
14679     // Look-up name inside 'foo::'.
14680     LookupQualifiedName(Previous, DC);
14681 
14682     if (Previous.isAmbiguous())
14683       return nullptr;
14684 
14685     if (Previous.empty()) {
14686       // Name lookup did not find anything. However, if the
14687       // nested-name-specifier refers to the current instantiation,
14688       // and that current instantiation has any dependent base
14689       // classes, we might find something at instantiation time: treat
14690       // this as a dependent elaborated-type-specifier.
14691       // But this only makes any sense for reference-like lookups.
14692       if (Previous.wasNotFoundInCurrentInstantiation() &&
14693           (TUK == TUK_Reference || TUK == TUK_Friend)) {
14694         IsDependent = true;
14695         return nullptr;
14696       }
14697 
14698       // A tag 'foo::bar' must already exist.
14699       Diag(NameLoc, diag::err_not_tag_in_scope)
14700         << Kind << Name << DC << SS.getRange();
14701       Name = nullptr;
14702       Invalid = true;
14703       goto CreateNewDecl;
14704     }
14705   } else if (Name) {
14706     // C++14 [class.mem]p14:
14707     //   If T is the name of a class, then each of the following shall have a
14708     //   name different from T:
14709     //    -- every member of class T that is itself a type
14710     if (TUK != TUK_Reference && TUK != TUK_Friend &&
14711         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
14712       return nullptr;
14713 
14714     // If this is a named struct, check to see if there was a previous forward
14715     // declaration or definition.
14716     // FIXME: We're looking into outer scopes here, even when we
14717     // shouldn't be. Doing so can result in ambiguities that we
14718     // shouldn't be diagnosing.
14719     LookupName(Previous, S);
14720 
14721     // When declaring or defining a tag, ignore ambiguities introduced
14722     // by types using'ed into this scope.
14723     if (Previous.isAmbiguous() &&
14724         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
14725       LookupResult::Filter F = Previous.makeFilter();
14726       while (F.hasNext()) {
14727         NamedDecl *ND = F.next();
14728         if (!ND->getDeclContext()->getRedeclContext()->Equals(
14729                 SearchDC->getRedeclContext()))
14730           F.erase();
14731       }
14732       F.done();
14733     }
14734 
14735     // C++11 [namespace.memdef]p3:
14736     //   If the name in a friend declaration is neither qualified nor
14737     //   a template-id and the declaration is a function or an
14738     //   elaborated-type-specifier, the lookup to determine whether
14739     //   the entity has been previously declared shall not consider
14740     //   any scopes outside the innermost enclosing namespace.
14741     //
14742     // MSVC doesn't implement the above rule for types, so a friend tag
14743     // declaration may be a redeclaration of a type declared in an enclosing
14744     // scope.  They do implement this rule for friend functions.
14745     //
14746     // Does it matter that this should be by scope instead of by
14747     // semantic context?
14748     if (!Previous.empty() && TUK == TUK_Friend) {
14749       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
14750       LookupResult::Filter F = Previous.makeFilter();
14751       bool FriendSawTagOutsideEnclosingNamespace = false;
14752       while (F.hasNext()) {
14753         NamedDecl *ND = F.next();
14754         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14755         if (DC->isFileContext() &&
14756             !EnclosingNS->Encloses(ND->getDeclContext())) {
14757           if (getLangOpts().MSVCCompat)
14758             FriendSawTagOutsideEnclosingNamespace = true;
14759           else
14760             F.erase();
14761         }
14762       }
14763       F.done();
14764 
14765       // Diagnose this MSVC extension in the easy case where lookup would have
14766       // unambiguously found something outside the enclosing namespace.
14767       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
14768         NamedDecl *ND = Previous.getFoundDecl();
14769         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
14770             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
14771       }
14772     }
14773 
14774     // Note:  there used to be some attempt at recovery here.
14775     if (Previous.isAmbiguous())
14776       return nullptr;
14777 
14778     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
14779       // FIXME: This makes sure that we ignore the contexts associated
14780       // with C structs, unions, and enums when looking for a matching
14781       // tag declaration or definition. See the similar lookup tweak
14782       // in Sema::LookupName; is there a better way to deal with this?
14783       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
14784         SearchDC = SearchDC->getParent();
14785     }
14786   }
14787 
14788   if (Previous.isSingleResult() &&
14789       Previous.getFoundDecl()->isTemplateParameter()) {
14790     // Maybe we will complain about the shadowed template parameter.
14791     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
14792     // Just pretend that we didn't see the previous declaration.
14793     Previous.clear();
14794   }
14795 
14796   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
14797       DC->Equals(getStdNamespace())) {
14798     if (Name->isStr("bad_alloc")) {
14799       // This is a declaration of or a reference to "std::bad_alloc".
14800       isStdBadAlloc = true;
14801 
14802       // If std::bad_alloc has been implicitly declared (but made invisible to
14803       // name lookup), fill in this implicit declaration as the previous
14804       // declaration, so that the declarations get chained appropriately.
14805       if (Previous.empty() && StdBadAlloc)
14806         Previous.addDecl(getStdBadAlloc());
14807     } else if (Name->isStr("align_val_t")) {
14808       isStdAlignValT = true;
14809       if (Previous.empty() && StdAlignValT)
14810         Previous.addDecl(getStdAlignValT());
14811     }
14812   }
14813 
14814   // If we didn't find a previous declaration, and this is a reference
14815   // (or friend reference), move to the correct scope.  In C++, we
14816   // also need to do a redeclaration lookup there, just in case
14817   // there's a shadow friend decl.
14818   if (Name && Previous.empty() &&
14819       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
14820     if (Invalid) goto CreateNewDecl;
14821     assert(SS.isEmpty());
14822 
14823     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
14824       // C++ [basic.scope.pdecl]p5:
14825       //   -- for an elaborated-type-specifier of the form
14826       //
14827       //          class-key identifier
14828       //
14829       //      if the elaborated-type-specifier is used in the
14830       //      decl-specifier-seq or parameter-declaration-clause of a
14831       //      function defined in namespace scope, the identifier is
14832       //      declared as a class-name in the namespace that contains
14833       //      the declaration; otherwise, except as a friend
14834       //      declaration, the identifier is declared in the smallest
14835       //      non-class, non-function-prototype scope that contains the
14836       //      declaration.
14837       //
14838       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
14839       // C structs and unions.
14840       //
14841       // It is an error in C++ to declare (rather than define) an enum
14842       // type, including via an elaborated type specifier.  We'll
14843       // diagnose that later; for now, declare the enum in the same
14844       // scope as we would have picked for any other tag type.
14845       //
14846       // GNU C also supports this behavior as part of its incomplete
14847       // enum types extension, while GNU C++ does not.
14848       //
14849       // Find the context where we'll be declaring the tag.
14850       // FIXME: We would like to maintain the current DeclContext as the
14851       // lexical context,
14852       SearchDC = getTagInjectionContext(SearchDC);
14853 
14854       // Find the scope where we'll be declaring the tag.
14855       S = getTagInjectionScope(S, getLangOpts());
14856     } else {
14857       assert(TUK == TUK_Friend);
14858       // C++ [namespace.memdef]p3:
14859       //   If a friend declaration in a non-local class first declares a
14860       //   class or function, the friend class or function is a member of
14861       //   the innermost enclosing namespace.
14862       SearchDC = SearchDC->getEnclosingNamespaceContext();
14863     }
14864 
14865     // In C++, we need to do a redeclaration lookup to properly
14866     // diagnose some problems.
14867     // FIXME: redeclaration lookup is also used (with and without C++) to find a
14868     // hidden declaration so that we don't get ambiguity errors when using a
14869     // type declared by an elaborated-type-specifier.  In C that is not correct
14870     // and we should instead merge compatible types found by lookup.
14871     if (getLangOpts().CPlusPlus) {
14872       Previous.setRedeclarationKind(forRedeclarationInCurContext());
14873       LookupQualifiedName(Previous, SearchDC);
14874     } else {
14875       Previous.setRedeclarationKind(forRedeclarationInCurContext());
14876       LookupName(Previous, S);
14877     }
14878   }
14879 
14880   // If we have a known previous declaration to use, then use it.
14881   if (Previous.empty() && SkipBody && SkipBody->Previous)
14882     Previous.addDecl(SkipBody->Previous);
14883 
14884   if (!Previous.empty()) {
14885     NamedDecl *PrevDecl = Previous.getFoundDecl();
14886     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
14887 
14888     // It's okay to have a tag decl in the same scope as a typedef
14889     // which hides a tag decl in the same scope.  Finding this
14890     // insanity with a redeclaration lookup can only actually happen
14891     // in C++.
14892     //
14893     // This is also okay for elaborated-type-specifiers, which is
14894     // technically forbidden by the current standard but which is
14895     // okay according to the likely resolution of an open issue;
14896     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
14897     if (getLangOpts().CPlusPlus) {
14898       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
14899         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
14900           TagDecl *Tag = TT->getDecl();
14901           if (Tag->getDeclName() == Name &&
14902               Tag->getDeclContext()->getRedeclContext()
14903                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
14904             PrevDecl = Tag;
14905             Previous.clear();
14906             Previous.addDecl(Tag);
14907             Previous.resolveKind();
14908           }
14909         }
14910       }
14911     }
14912 
14913     // If this is a redeclaration of a using shadow declaration, it must
14914     // declare a tag in the same context. In MSVC mode, we allow a
14915     // redefinition if either context is within the other.
14916     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
14917       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
14918       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
14919           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
14920           !(OldTag && isAcceptableTagRedeclContext(
14921                           *this, OldTag->getDeclContext(), SearchDC))) {
14922         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
14923         Diag(Shadow->getTargetDecl()->getLocation(),
14924              diag::note_using_decl_target);
14925         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
14926             << 0;
14927         // Recover by ignoring the old declaration.
14928         Previous.clear();
14929         goto CreateNewDecl;
14930       }
14931     }
14932 
14933     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
14934       // If this is a use of a previous tag, or if the tag is already declared
14935       // in the same scope (so that the definition/declaration completes or
14936       // rementions the tag), reuse the decl.
14937       if (TUK == TUK_Reference || TUK == TUK_Friend ||
14938           isDeclInScope(DirectPrevDecl, SearchDC, S,
14939                         SS.isNotEmpty() || isMemberSpecialization)) {
14940         // Make sure that this wasn't declared as an enum and now used as a
14941         // struct or something similar.
14942         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
14943                                           TUK == TUK_Definition, KWLoc,
14944                                           Name)) {
14945           bool SafeToContinue
14946             = (PrevTagDecl->getTagKind() != TTK_Enum &&
14947                Kind != TTK_Enum);
14948           if (SafeToContinue)
14949             Diag(KWLoc, diag::err_use_with_wrong_tag)
14950               << Name
14951               << FixItHint::CreateReplacement(SourceRange(KWLoc),
14952                                               PrevTagDecl->getKindName());
14953           else
14954             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
14955           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
14956 
14957           if (SafeToContinue)
14958             Kind = PrevTagDecl->getTagKind();
14959           else {
14960             // Recover by making this an anonymous redefinition.
14961             Name = nullptr;
14962             Previous.clear();
14963             Invalid = true;
14964           }
14965         }
14966 
14967         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
14968           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
14969 
14970           // If this is an elaborated-type-specifier for a scoped enumeration,
14971           // the 'class' keyword is not necessary and not permitted.
14972           if (TUK == TUK_Reference || TUK == TUK_Friend) {
14973             if (ScopedEnum)
14974               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
14975                 << PrevEnum->isScoped()
14976                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
14977             return PrevTagDecl;
14978           }
14979 
14980           QualType EnumUnderlyingTy;
14981           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
14982             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
14983           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
14984             EnumUnderlyingTy = QualType(T, 0);
14985 
14986           // All conflicts with previous declarations are recovered by
14987           // returning the previous declaration, unless this is a definition,
14988           // in which case we want the caller to bail out.
14989           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
14990                                      ScopedEnum, EnumUnderlyingTy,
14991                                      IsFixed, PrevEnum))
14992             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
14993         }
14994 
14995         // C++11 [class.mem]p1:
14996         //   A member shall not be declared twice in the member-specification,
14997         //   except that a nested class or member class template can be declared
14998         //   and then later defined.
14999         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
15000             S->isDeclScope(PrevDecl)) {
15001           Diag(NameLoc, diag::ext_member_redeclared);
15002           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
15003         }
15004 
15005         if (!Invalid) {
15006           // If this is a use, just return the declaration we found, unless
15007           // we have attributes.
15008           if (TUK == TUK_Reference || TUK == TUK_Friend) {
15009             if (!Attrs.empty()) {
15010               // FIXME: Diagnose these attributes. For now, we create a new
15011               // declaration to hold them.
15012             } else if (TUK == TUK_Reference &&
15013                        (PrevTagDecl->getFriendObjectKind() ==
15014                             Decl::FOK_Undeclared ||
15015                         PrevDecl->getOwningModule() != getCurrentModule()) &&
15016                        SS.isEmpty()) {
15017               // This declaration is a reference to an existing entity, but
15018               // has different visibility from that entity: it either makes
15019               // a friend visible or it makes a type visible in a new module.
15020               // In either case, create a new declaration. We only do this if
15021               // the declaration would have meant the same thing if no prior
15022               // declaration were found, that is, if it was found in the same
15023               // scope where we would have injected a declaration.
15024               if (!getTagInjectionContext(CurContext)->getRedeclContext()
15025                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
15026                 return PrevTagDecl;
15027               // This is in the injected scope, create a new declaration in
15028               // that scope.
15029               S = getTagInjectionScope(S, getLangOpts());
15030             } else {
15031               return PrevTagDecl;
15032             }
15033           }
15034 
15035           // Diagnose attempts to redefine a tag.
15036           if (TUK == TUK_Definition) {
15037             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
15038               // If we're defining a specialization and the previous definition
15039               // is from an implicit instantiation, don't emit an error
15040               // here; we'll catch this in the general case below.
15041               bool IsExplicitSpecializationAfterInstantiation = false;
15042               if (isMemberSpecialization) {
15043                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
15044                   IsExplicitSpecializationAfterInstantiation =
15045                     RD->getTemplateSpecializationKind() !=
15046                     TSK_ExplicitSpecialization;
15047                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
15048                   IsExplicitSpecializationAfterInstantiation =
15049                     ED->getTemplateSpecializationKind() !=
15050                     TSK_ExplicitSpecialization;
15051               }
15052 
15053               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
15054               // not keep more that one definition around (merge them). However,
15055               // ensure the decl passes the structural compatibility check in
15056               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
15057               NamedDecl *Hidden = nullptr;
15058               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
15059                 // There is a definition of this tag, but it is not visible. We
15060                 // explicitly make use of C++'s one definition rule here, and
15061                 // assume that this definition is identical to the hidden one
15062                 // we already have. Make the existing definition visible and
15063                 // use it in place of this one.
15064                 if (!getLangOpts().CPlusPlus) {
15065                   // Postpone making the old definition visible until after we
15066                   // complete parsing the new one and do the structural
15067                   // comparison.
15068                   SkipBody->CheckSameAsPrevious = true;
15069                   SkipBody->New = createTagFromNewDecl();
15070                   SkipBody->Previous = Def;
15071                   return Def;
15072                 } else {
15073                   SkipBody->ShouldSkip = true;
15074                   SkipBody->Previous = Def;
15075                   makeMergedDefinitionVisible(Hidden);
15076                   // Carry on and handle it like a normal definition. We'll
15077                   // skip starting the definitiion later.
15078                 }
15079               } else if (!IsExplicitSpecializationAfterInstantiation) {
15080                 // A redeclaration in function prototype scope in C isn't
15081                 // visible elsewhere, so merely issue a warning.
15082                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
15083                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
15084                 else
15085                   Diag(NameLoc, diag::err_redefinition) << Name;
15086                 notePreviousDefinition(Def,
15087                                        NameLoc.isValid() ? NameLoc : KWLoc);
15088                 // If this is a redefinition, recover by making this
15089                 // struct be anonymous, which will make any later
15090                 // references get the previous definition.
15091                 Name = nullptr;
15092                 Previous.clear();
15093                 Invalid = true;
15094               }
15095             } else {
15096               // If the type is currently being defined, complain
15097               // about a nested redefinition.
15098               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
15099               if (TD->isBeingDefined()) {
15100                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
15101                 Diag(PrevTagDecl->getLocation(),
15102                      diag::note_previous_definition);
15103                 Name = nullptr;
15104                 Previous.clear();
15105                 Invalid = true;
15106               }
15107             }
15108 
15109             // Okay, this is definition of a previously declared or referenced
15110             // tag. We're going to create a new Decl for it.
15111           }
15112 
15113           // Okay, we're going to make a redeclaration.  If this is some kind
15114           // of reference, make sure we build the redeclaration in the same DC
15115           // as the original, and ignore the current access specifier.
15116           if (TUK == TUK_Friend || TUK == TUK_Reference) {
15117             SearchDC = PrevTagDecl->getDeclContext();
15118             AS = AS_none;
15119           }
15120         }
15121         // If we get here we have (another) forward declaration or we
15122         // have a definition.  Just create a new decl.
15123 
15124       } else {
15125         // If we get here, this is a definition of a new tag type in a nested
15126         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
15127         // new decl/type.  We set PrevDecl to NULL so that the entities
15128         // have distinct types.
15129         Previous.clear();
15130       }
15131       // If we get here, we're going to create a new Decl. If PrevDecl
15132       // is non-NULL, it's a definition of the tag declared by
15133       // PrevDecl. If it's NULL, we have a new definition.
15134 
15135     // Otherwise, PrevDecl is not a tag, but was found with tag
15136     // lookup.  This is only actually possible in C++, where a few
15137     // things like templates still live in the tag namespace.
15138     } else {
15139       // Use a better diagnostic if an elaborated-type-specifier
15140       // found the wrong kind of type on the first
15141       // (non-redeclaration) lookup.
15142       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
15143           !Previous.isForRedeclaration()) {
15144         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15145         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
15146                                                        << Kind;
15147         Diag(PrevDecl->getLocation(), diag::note_declared_at);
15148         Invalid = true;
15149 
15150       // Otherwise, only diagnose if the declaration is in scope.
15151       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
15152                                 SS.isNotEmpty() || isMemberSpecialization)) {
15153         // do nothing
15154 
15155       // Diagnose implicit declarations introduced by elaborated types.
15156       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
15157         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15158         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
15159         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15160         Invalid = true;
15161 
15162       // Otherwise it's a declaration.  Call out a particularly common
15163       // case here.
15164       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15165         unsigned Kind = 0;
15166         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
15167         Diag(NameLoc, diag::err_tag_definition_of_typedef)
15168           << Name << Kind << TND->getUnderlyingType();
15169         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15170         Invalid = true;
15171 
15172       // Otherwise, diagnose.
15173       } else {
15174         // The tag name clashes with something else in the target scope,
15175         // issue an error and recover by making this tag be anonymous.
15176         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
15177         notePreviousDefinition(PrevDecl, NameLoc);
15178         Name = nullptr;
15179         Invalid = true;
15180       }
15181 
15182       // The existing declaration isn't relevant to us; we're in a
15183       // new scope, so clear out the previous declaration.
15184       Previous.clear();
15185     }
15186   }
15187 
15188 CreateNewDecl:
15189 
15190   TagDecl *PrevDecl = nullptr;
15191   if (Previous.isSingleResult())
15192     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
15193 
15194   // If there is an identifier, use the location of the identifier as the
15195   // location of the decl, otherwise use the location of the struct/union
15196   // keyword.
15197   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15198 
15199   // Otherwise, create a new declaration. If there is a previous
15200   // declaration of the same entity, the two will be linked via
15201   // PrevDecl.
15202   TagDecl *New;
15203 
15204   if (Kind == TTK_Enum) {
15205     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15206     // enum X { A, B, C } D;    D should chain to X.
15207     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
15208                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
15209                            ScopedEnumUsesClassTag, IsFixed);
15210 
15211     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
15212       StdAlignValT = cast<EnumDecl>(New);
15213 
15214     // If this is an undefined enum, warn.
15215     if (TUK != TUK_Definition && !Invalid) {
15216       TagDecl *Def;
15217       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
15218         // C++0x: 7.2p2: opaque-enum-declaration.
15219         // Conflicts are diagnosed above. Do nothing.
15220       }
15221       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
15222         Diag(Loc, diag::ext_forward_ref_enum_def)
15223           << New;
15224         Diag(Def->getLocation(), diag::note_previous_definition);
15225       } else {
15226         unsigned DiagID = diag::ext_forward_ref_enum;
15227         if (getLangOpts().MSVCCompat)
15228           DiagID = diag::ext_ms_forward_ref_enum;
15229         else if (getLangOpts().CPlusPlus)
15230           DiagID = diag::err_forward_ref_enum;
15231         Diag(Loc, DiagID);
15232       }
15233     }
15234 
15235     if (EnumUnderlying) {
15236       EnumDecl *ED = cast<EnumDecl>(New);
15237       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15238         ED->setIntegerTypeSourceInfo(TI);
15239       else
15240         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
15241       ED->setPromotionType(ED->getIntegerType());
15242       assert(ED->isComplete() && "enum with type should be complete");
15243     }
15244   } else {
15245     // struct/union/class
15246 
15247     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15248     // struct X { int A; } D;    D should chain to X.
15249     if (getLangOpts().CPlusPlus) {
15250       // FIXME: Look for a way to use RecordDecl for simple structs.
15251       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15252                                   cast_or_null<CXXRecordDecl>(PrevDecl));
15253 
15254       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
15255         StdBadAlloc = cast<CXXRecordDecl>(New);
15256     } else
15257       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15258                                cast_or_null<RecordDecl>(PrevDecl));
15259   }
15260 
15261   // C++11 [dcl.type]p3:
15262   //   A type-specifier-seq shall not define a class or enumeration [...].
15263   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
15264       TUK == TUK_Definition) {
15265     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
15266       << Context.getTagDeclType(New);
15267     Invalid = true;
15268   }
15269 
15270   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
15271       DC->getDeclKind() == Decl::Enum) {
15272     Diag(New->getLocation(), diag::err_type_defined_in_enum)
15273       << Context.getTagDeclType(New);
15274     Invalid = true;
15275   }
15276 
15277   // Maybe add qualifier info.
15278   if (SS.isNotEmpty()) {
15279     if (SS.isSet()) {
15280       // If this is either a declaration or a definition, check the
15281       // nested-name-specifier against the current context.
15282       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
15283           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
15284                                        isMemberSpecialization))
15285         Invalid = true;
15286 
15287       New->setQualifierInfo(SS.getWithLocInContext(Context));
15288       if (TemplateParameterLists.size() > 0) {
15289         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
15290       }
15291     }
15292     else
15293       Invalid = true;
15294   }
15295 
15296   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15297     // Add alignment attributes if necessary; these attributes are checked when
15298     // the ASTContext lays out the structure.
15299     //
15300     // It is important for implementing the correct semantics that this
15301     // happen here (in ActOnTag). The #pragma pack stack is
15302     // maintained as a result of parser callbacks which can occur at
15303     // many points during the parsing of a struct declaration (because
15304     // the #pragma tokens are effectively skipped over during the
15305     // parsing of the struct).
15306     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15307       AddAlignmentAttributesForRecord(RD);
15308       AddMsStructLayoutForRecord(RD);
15309     }
15310   }
15311 
15312   if (ModulePrivateLoc.isValid()) {
15313     if (isMemberSpecialization)
15314       Diag(New->getLocation(), diag::err_module_private_specialization)
15315         << 2
15316         << FixItHint::CreateRemoval(ModulePrivateLoc);
15317     // __module_private__ does not apply to local classes. However, we only
15318     // diagnose this as an error when the declaration specifiers are
15319     // freestanding. Here, we just ignore the __module_private__.
15320     else if (!SearchDC->isFunctionOrMethod())
15321       New->setModulePrivate();
15322   }
15323 
15324   // If this is a specialization of a member class (of a class template),
15325   // check the specialization.
15326   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
15327     Invalid = true;
15328 
15329   // If we're declaring or defining a tag in function prototype scope in C,
15330   // note that this type can only be used within the function and add it to
15331   // the list of decls to inject into the function definition scope.
15332   if ((Name || Kind == TTK_Enum) &&
15333       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
15334     if (getLangOpts().CPlusPlus) {
15335       // C++ [dcl.fct]p6:
15336       //   Types shall not be defined in return or parameter types.
15337       if (TUK == TUK_Definition && !IsTypeSpecifier) {
15338         Diag(Loc, diag::err_type_defined_in_param_type)
15339             << Name;
15340         Invalid = true;
15341       }
15342     } else if (!PrevDecl) {
15343       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
15344     }
15345   }
15346 
15347   if (Invalid)
15348     New->setInvalidDecl();
15349 
15350   // Set the lexical context. If the tag has a C++ scope specifier, the
15351   // lexical context will be different from the semantic context.
15352   New->setLexicalDeclContext(CurContext);
15353 
15354   // Mark this as a friend decl if applicable.
15355   // In Microsoft mode, a friend declaration also acts as a forward
15356   // declaration so we always pass true to setObjectOfFriendDecl to make
15357   // the tag name visible.
15358   if (TUK == TUK_Friend)
15359     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
15360 
15361   // Set the access specifier.
15362   if (!Invalid && SearchDC->isRecord())
15363     SetMemberAccessSpecifier(New, PrevDecl, AS);
15364 
15365   if (PrevDecl)
15366     CheckRedeclarationModuleOwnership(New, PrevDecl);
15367 
15368   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
15369     New->startDefinition();
15370 
15371   ProcessDeclAttributeList(S, New, Attrs);
15372   AddPragmaAttributes(S, New);
15373 
15374   // If this has an identifier, add it to the scope stack.
15375   if (TUK == TUK_Friend) {
15376     // We might be replacing an existing declaration in the lookup tables;
15377     // if so, borrow its access specifier.
15378     if (PrevDecl)
15379       New->setAccess(PrevDecl->getAccess());
15380 
15381     DeclContext *DC = New->getDeclContext()->getRedeclContext();
15382     DC->makeDeclVisibleInContext(New);
15383     if (Name) // can be null along some error paths
15384       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
15385         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
15386   } else if (Name) {
15387     S = getNonFieldDeclScope(S);
15388     PushOnScopeChains(New, S, true);
15389   } else {
15390     CurContext->addDecl(New);
15391   }
15392 
15393   // If this is the C FILE type, notify the AST context.
15394   if (IdentifierInfo *II = New->getIdentifier())
15395     if (!New->isInvalidDecl() &&
15396         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
15397         II->isStr("FILE"))
15398       Context.setFILEDecl(New);
15399 
15400   if (PrevDecl)
15401     mergeDeclAttributes(New, PrevDecl);
15402 
15403   // If there's a #pragma GCC visibility in scope, set the visibility of this
15404   // record.
15405   AddPushedVisibilityAttribute(New);
15406 
15407   if (isMemberSpecialization && !New->isInvalidDecl())
15408     CompleteMemberSpecialization(New, Previous);
15409 
15410   OwnedDecl = true;
15411   // In C++, don't return an invalid declaration. We can't recover well from
15412   // the cases where we make the type anonymous.
15413   if (Invalid && getLangOpts().CPlusPlus) {
15414     if (New->isBeingDefined())
15415       if (auto RD = dyn_cast<RecordDecl>(New))
15416         RD->completeDefinition();
15417     return nullptr;
15418   } else if (SkipBody && SkipBody->ShouldSkip) {
15419     return SkipBody->Previous;
15420   } else {
15421     return New;
15422   }
15423 }
15424 
15425 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
15426   AdjustDeclIfTemplate(TagD);
15427   TagDecl *Tag = cast<TagDecl>(TagD);
15428 
15429   // Enter the tag context.
15430   PushDeclContext(S, Tag);
15431 
15432   ActOnDocumentableDecl(TagD);
15433 
15434   // If there's a #pragma GCC visibility in scope, set the visibility of this
15435   // record.
15436   AddPushedVisibilityAttribute(Tag);
15437 }
15438 
15439 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
15440                                     SkipBodyInfo &SkipBody) {
15441   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
15442     return false;
15443 
15444   // Make the previous decl visible.
15445   makeMergedDefinitionVisible(SkipBody.Previous);
15446   return true;
15447 }
15448 
15449 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
15450   assert(isa<ObjCContainerDecl>(IDecl) &&
15451          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
15452   DeclContext *OCD = cast<DeclContext>(IDecl);
15453   assert(getContainingDC(OCD) == CurContext &&
15454       "The next DeclContext should be lexically contained in the current one.");
15455   CurContext = OCD;
15456   return IDecl;
15457 }
15458 
15459 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
15460                                            SourceLocation FinalLoc,
15461                                            bool IsFinalSpelledSealed,
15462                                            SourceLocation LBraceLoc) {
15463   AdjustDeclIfTemplate(TagD);
15464   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
15465 
15466   FieldCollector->StartClass();
15467 
15468   if (!Record->getIdentifier())
15469     return;
15470 
15471   if (FinalLoc.isValid())
15472     Record->addAttr(new (Context)
15473                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
15474 
15475   // C++ [class]p2:
15476   //   [...] The class-name is also inserted into the scope of the
15477   //   class itself; this is known as the injected-class-name. For
15478   //   purposes of access checking, the injected-class-name is treated
15479   //   as if it were a public member name.
15480   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
15481       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
15482       Record->getLocation(), Record->getIdentifier(),
15483       /*PrevDecl=*/nullptr,
15484       /*DelayTypeCreation=*/true);
15485   Context.getTypeDeclType(InjectedClassName, Record);
15486   InjectedClassName->setImplicit();
15487   InjectedClassName->setAccess(AS_public);
15488   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
15489       InjectedClassName->setDescribedClassTemplate(Template);
15490   PushOnScopeChains(InjectedClassName, S);
15491   assert(InjectedClassName->isInjectedClassName() &&
15492          "Broken injected-class-name");
15493 }
15494 
15495 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
15496                                     SourceRange BraceRange) {
15497   AdjustDeclIfTemplate(TagD);
15498   TagDecl *Tag = cast<TagDecl>(TagD);
15499   Tag->setBraceRange(BraceRange);
15500 
15501   // Make sure we "complete" the definition even it is invalid.
15502   if (Tag->isBeingDefined()) {
15503     assert(Tag->isInvalidDecl() && "We should already have completed it");
15504     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15505       RD->completeDefinition();
15506   }
15507 
15508   if (isa<CXXRecordDecl>(Tag)) {
15509     FieldCollector->FinishClass();
15510   }
15511 
15512   // Exit this scope of this tag's definition.
15513   PopDeclContext();
15514 
15515   if (getCurLexicalContext()->isObjCContainer() &&
15516       Tag->getDeclContext()->isFileContext())
15517     Tag->setTopLevelDeclInObjCContainer();
15518 
15519   // Notify the consumer that we've defined a tag.
15520   if (!Tag->isInvalidDecl())
15521     Consumer.HandleTagDeclDefinition(Tag);
15522 }
15523 
15524 void Sema::ActOnObjCContainerFinishDefinition() {
15525   // Exit this scope of this interface definition.
15526   PopDeclContext();
15527 }
15528 
15529 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
15530   assert(DC == CurContext && "Mismatch of container contexts");
15531   OriginalLexicalContext = DC;
15532   ActOnObjCContainerFinishDefinition();
15533 }
15534 
15535 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
15536   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
15537   OriginalLexicalContext = nullptr;
15538 }
15539 
15540 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
15541   AdjustDeclIfTemplate(TagD);
15542   TagDecl *Tag = cast<TagDecl>(TagD);
15543   Tag->setInvalidDecl();
15544 
15545   // Make sure we "complete" the definition even it is invalid.
15546   if (Tag->isBeingDefined()) {
15547     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15548       RD->completeDefinition();
15549   }
15550 
15551   // We're undoing ActOnTagStartDefinition here, not
15552   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
15553   // the FieldCollector.
15554 
15555   PopDeclContext();
15556 }
15557 
15558 // Note that FieldName may be null for anonymous bitfields.
15559 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
15560                                 IdentifierInfo *FieldName,
15561                                 QualType FieldTy, bool IsMsStruct,
15562                                 Expr *BitWidth, bool *ZeroWidth) {
15563   // Default to true; that shouldn't confuse checks for emptiness
15564   if (ZeroWidth)
15565     *ZeroWidth = true;
15566 
15567   // C99 6.7.2.1p4 - verify the field type.
15568   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
15569   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
15570     // Handle incomplete types with specific error.
15571     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
15572       return ExprError();
15573     if (FieldName)
15574       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
15575         << FieldName << FieldTy << BitWidth->getSourceRange();
15576     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
15577       << FieldTy << BitWidth->getSourceRange();
15578   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
15579                                              UPPC_BitFieldWidth))
15580     return ExprError();
15581 
15582   // If the bit-width is type- or value-dependent, don't try to check
15583   // it now.
15584   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
15585     return BitWidth;
15586 
15587   llvm::APSInt Value;
15588   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
15589   if (ICE.isInvalid())
15590     return ICE;
15591   BitWidth = ICE.get();
15592 
15593   if (Value != 0 && ZeroWidth)
15594     *ZeroWidth = false;
15595 
15596   // Zero-width bitfield is ok for anonymous field.
15597   if (Value == 0 && FieldName)
15598     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
15599 
15600   if (Value.isSigned() && Value.isNegative()) {
15601     if (FieldName)
15602       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
15603                << FieldName << Value.toString(10);
15604     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
15605       << Value.toString(10);
15606   }
15607 
15608   if (!FieldTy->isDependentType()) {
15609     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
15610     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
15611     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
15612 
15613     // Over-wide bitfields are an error in C or when using the MSVC bitfield
15614     // ABI.
15615     bool CStdConstraintViolation =
15616         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
15617     bool MSBitfieldViolation =
15618         Value.ugt(TypeStorageSize) &&
15619         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
15620     if (CStdConstraintViolation || MSBitfieldViolation) {
15621       unsigned DiagWidth =
15622           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
15623       if (FieldName)
15624         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
15625                << FieldName << (unsigned)Value.getZExtValue()
15626                << !CStdConstraintViolation << DiagWidth;
15627 
15628       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
15629              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
15630              << DiagWidth;
15631     }
15632 
15633     // Warn on types where the user might conceivably expect to get all
15634     // specified bits as value bits: that's all integral types other than
15635     // 'bool'.
15636     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
15637       if (FieldName)
15638         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
15639             << FieldName << (unsigned)Value.getZExtValue()
15640             << (unsigned)TypeWidth;
15641       else
15642         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
15643             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
15644     }
15645   }
15646 
15647   return BitWidth;
15648 }
15649 
15650 /// ActOnField - Each field of a C struct/union is passed into this in order
15651 /// to create a FieldDecl object for it.
15652 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
15653                        Declarator &D, Expr *BitfieldWidth) {
15654   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
15655                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
15656                                /*InitStyle=*/ICIS_NoInit, AS_public);
15657   return Res;
15658 }
15659 
15660 /// HandleField - Analyze a field of a C struct or a C++ data member.
15661 ///
15662 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
15663                              SourceLocation DeclStart,
15664                              Declarator &D, Expr *BitWidth,
15665                              InClassInitStyle InitStyle,
15666                              AccessSpecifier AS) {
15667   if (D.isDecompositionDeclarator()) {
15668     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
15669     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
15670       << Decomp.getSourceRange();
15671     return nullptr;
15672   }
15673 
15674   IdentifierInfo *II = D.getIdentifier();
15675   SourceLocation Loc = DeclStart;
15676   if (II) Loc = D.getIdentifierLoc();
15677 
15678   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15679   QualType T = TInfo->getType();
15680   if (getLangOpts().CPlusPlus) {
15681     CheckExtraCXXDefaultArguments(D);
15682 
15683     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15684                                         UPPC_DataMemberType)) {
15685       D.setInvalidType();
15686       T = Context.IntTy;
15687       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15688     }
15689   }
15690 
15691   DiagnoseFunctionSpecifiers(D.getDeclSpec());
15692 
15693   if (D.getDeclSpec().isInlineSpecified())
15694     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15695         << getLangOpts().CPlusPlus17;
15696   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15697     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15698          diag::err_invalid_thread)
15699       << DeclSpec::getSpecifierName(TSCS);
15700 
15701   // Check to see if this name was declared as a member previously
15702   NamedDecl *PrevDecl = nullptr;
15703   LookupResult Previous(*this, II, Loc, LookupMemberName,
15704                         ForVisibleRedeclaration);
15705   LookupName(Previous, S);
15706   switch (Previous.getResultKind()) {
15707     case LookupResult::Found:
15708     case LookupResult::FoundUnresolvedValue:
15709       PrevDecl = Previous.getAsSingle<NamedDecl>();
15710       break;
15711 
15712     case LookupResult::FoundOverloaded:
15713       PrevDecl = Previous.getRepresentativeDecl();
15714       break;
15715 
15716     case LookupResult::NotFound:
15717     case LookupResult::NotFoundInCurrentInstantiation:
15718     case LookupResult::Ambiguous:
15719       break;
15720   }
15721   Previous.suppressDiagnostics();
15722 
15723   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15724     // Maybe we will complain about the shadowed template parameter.
15725     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15726     // Just pretend that we didn't see the previous declaration.
15727     PrevDecl = nullptr;
15728   }
15729 
15730   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15731     PrevDecl = nullptr;
15732 
15733   bool Mutable
15734     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
15735   SourceLocation TSSL = D.getBeginLoc();
15736   FieldDecl *NewFD
15737     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
15738                      TSSL, AS, PrevDecl, &D);
15739 
15740   if (NewFD->isInvalidDecl())
15741     Record->setInvalidDecl();
15742 
15743   if (D.getDeclSpec().isModulePrivateSpecified())
15744     NewFD->setModulePrivate();
15745 
15746   if (NewFD->isInvalidDecl() && PrevDecl) {
15747     // Don't introduce NewFD into scope; there's already something
15748     // with the same name in the same scope.
15749   } else if (II) {
15750     PushOnScopeChains(NewFD, S);
15751   } else
15752     Record->addDecl(NewFD);
15753 
15754   return NewFD;
15755 }
15756 
15757 /// Build a new FieldDecl and check its well-formedness.
15758 ///
15759 /// This routine builds a new FieldDecl given the fields name, type,
15760 /// record, etc. \p PrevDecl should refer to any previous declaration
15761 /// with the same name and in the same scope as the field to be
15762 /// created.
15763 ///
15764 /// \returns a new FieldDecl.
15765 ///
15766 /// \todo The Declarator argument is a hack. It will be removed once
15767 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
15768                                 TypeSourceInfo *TInfo,
15769                                 RecordDecl *Record, SourceLocation Loc,
15770                                 bool Mutable, Expr *BitWidth,
15771                                 InClassInitStyle InitStyle,
15772                                 SourceLocation TSSL,
15773                                 AccessSpecifier AS, NamedDecl *PrevDecl,
15774                                 Declarator *D) {
15775   IdentifierInfo *II = Name.getAsIdentifierInfo();
15776   bool InvalidDecl = false;
15777   if (D) InvalidDecl = D->isInvalidType();
15778 
15779   // If we receive a broken type, recover by assuming 'int' and
15780   // marking this declaration as invalid.
15781   if (T.isNull()) {
15782     InvalidDecl = true;
15783     T = Context.IntTy;
15784   }
15785 
15786   QualType EltTy = Context.getBaseElementType(T);
15787   if (!EltTy->isDependentType()) {
15788     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
15789       // Fields of incomplete type force their record to be invalid.
15790       Record->setInvalidDecl();
15791       InvalidDecl = true;
15792     } else {
15793       NamedDecl *Def;
15794       EltTy->isIncompleteType(&Def);
15795       if (Def && Def->isInvalidDecl()) {
15796         Record->setInvalidDecl();
15797         InvalidDecl = true;
15798       }
15799     }
15800   }
15801 
15802   // TR 18037 does not allow fields to be declared with address space
15803   if (T.getQualifiers().hasAddressSpace() || T->isDependentAddressSpaceType() ||
15804       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
15805     Diag(Loc, diag::err_field_with_address_space);
15806     Record->setInvalidDecl();
15807     InvalidDecl = true;
15808   }
15809 
15810   if (LangOpts.OpenCL) {
15811     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
15812     // used as structure or union field: image, sampler, event or block types.
15813     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
15814         T->isBlockPointerType()) {
15815       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
15816       Record->setInvalidDecl();
15817       InvalidDecl = true;
15818     }
15819     // OpenCL v1.2 s6.9.c: bitfields are not supported.
15820     if (BitWidth) {
15821       Diag(Loc, diag::err_opencl_bitfields);
15822       InvalidDecl = true;
15823     }
15824   }
15825 
15826   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
15827   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
15828       T.hasQualifiers()) {
15829     InvalidDecl = true;
15830     Diag(Loc, diag::err_anon_bitfield_qualifiers);
15831   }
15832 
15833   // C99 6.7.2.1p8: A member of a structure or union may have any type other
15834   // than a variably modified type.
15835   if (!InvalidDecl && T->isVariablyModifiedType()) {
15836     bool SizeIsNegative;
15837     llvm::APSInt Oversized;
15838 
15839     TypeSourceInfo *FixedTInfo =
15840       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
15841                                                     SizeIsNegative,
15842                                                     Oversized);
15843     if (FixedTInfo) {
15844       Diag(Loc, diag::warn_illegal_constant_array_size);
15845       TInfo = FixedTInfo;
15846       T = FixedTInfo->getType();
15847     } else {
15848       if (SizeIsNegative)
15849         Diag(Loc, diag::err_typecheck_negative_array_size);
15850       else if (Oversized.getBoolValue())
15851         Diag(Loc, diag::err_array_too_large)
15852           << Oversized.toString(10);
15853       else
15854         Diag(Loc, diag::err_typecheck_field_variable_size);
15855       InvalidDecl = true;
15856     }
15857   }
15858 
15859   // Fields can not have abstract class types
15860   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
15861                                              diag::err_abstract_type_in_decl,
15862                                              AbstractFieldType))
15863     InvalidDecl = true;
15864 
15865   bool ZeroWidth = false;
15866   if (InvalidDecl)
15867     BitWidth = nullptr;
15868   // If this is declared as a bit-field, check the bit-field.
15869   if (BitWidth) {
15870     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
15871                               &ZeroWidth).get();
15872     if (!BitWidth) {
15873       InvalidDecl = true;
15874       BitWidth = nullptr;
15875       ZeroWidth = false;
15876     }
15877   }
15878 
15879   // Check that 'mutable' is consistent with the type of the declaration.
15880   if (!InvalidDecl && Mutable) {
15881     unsigned DiagID = 0;
15882     if (T->isReferenceType())
15883       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
15884                                         : diag::err_mutable_reference;
15885     else if (T.isConstQualified())
15886       DiagID = diag::err_mutable_const;
15887 
15888     if (DiagID) {
15889       SourceLocation ErrLoc = Loc;
15890       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
15891         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
15892       Diag(ErrLoc, DiagID);
15893       if (DiagID != diag::ext_mutable_reference) {
15894         Mutable = false;
15895         InvalidDecl = true;
15896       }
15897     }
15898   }
15899 
15900   // C++11 [class.union]p8 (DR1460):
15901   //   At most one variant member of a union may have a
15902   //   brace-or-equal-initializer.
15903   if (InitStyle != ICIS_NoInit)
15904     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
15905 
15906   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
15907                                        BitWidth, Mutable, InitStyle);
15908   if (InvalidDecl)
15909     NewFD->setInvalidDecl();
15910 
15911   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
15912     Diag(Loc, diag::err_duplicate_member) << II;
15913     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15914     NewFD->setInvalidDecl();
15915   }
15916 
15917   if (!InvalidDecl && getLangOpts().CPlusPlus) {
15918     if (Record->isUnion()) {
15919       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
15920         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
15921         if (RDecl->getDefinition()) {
15922           // C++ [class.union]p1: An object of a class with a non-trivial
15923           // constructor, a non-trivial copy constructor, a non-trivial
15924           // destructor, or a non-trivial copy assignment operator
15925           // cannot be a member of a union, nor can an array of such
15926           // objects.
15927           if (CheckNontrivialField(NewFD))
15928             NewFD->setInvalidDecl();
15929         }
15930       }
15931 
15932       // C++ [class.union]p1: If a union contains a member of reference type,
15933       // the program is ill-formed, except when compiling with MSVC extensions
15934       // enabled.
15935       if (EltTy->isReferenceType()) {
15936         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
15937                                     diag::ext_union_member_of_reference_type :
15938                                     diag::err_union_member_of_reference_type)
15939           << NewFD->getDeclName() << EltTy;
15940         if (!getLangOpts().MicrosoftExt)
15941           NewFD->setInvalidDecl();
15942       }
15943     }
15944   }
15945 
15946   // FIXME: We need to pass in the attributes given an AST
15947   // representation, not a parser representation.
15948   if (D) {
15949     // FIXME: The current scope is almost... but not entirely... correct here.
15950     ProcessDeclAttributes(getCurScope(), NewFD, *D);
15951 
15952     if (NewFD->hasAttrs())
15953       CheckAlignasUnderalignment(NewFD);
15954   }
15955 
15956   // In auto-retain/release, infer strong retension for fields of
15957   // retainable type.
15958   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
15959     NewFD->setInvalidDecl();
15960 
15961   if (T.isObjCGCWeak())
15962     Diag(Loc, diag::warn_attribute_weak_on_field);
15963 
15964   NewFD->setAccess(AS);
15965   return NewFD;
15966 }
15967 
15968 bool Sema::CheckNontrivialField(FieldDecl *FD) {
15969   assert(FD);
15970   assert(getLangOpts().CPlusPlus && "valid check only for C++");
15971 
15972   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
15973     return false;
15974 
15975   QualType EltTy = Context.getBaseElementType(FD->getType());
15976   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
15977     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
15978     if (RDecl->getDefinition()) {
15979       // We check for copy constructors before constructors
15980       // because otherwise we'll never get complaints about
15981       // copy constructors.
15982 
15983       CXXSpecialMember member = CXXInvalid;
15984       // We're required to check for any non-trivial constructors. Since the
15985       // implicit default constructor is suppressed if there are any
15986       // user-declared constructors, we just need to check that there is a
15987       // trivial default constructor and a trivial copy constructor. (We don't
15988       // worry about move constructors here, since this is a C++98 check.)
15989       if (RDecl->hasNonTrivialCopyConstructor())
15990         member = CXXCopyConstructor;
15991       else if (!RDecl->hasTrivialDefaultConstructor())
15992         member = CXXDefaultConstructor;
15993       else if (RDecl->hasNonTrivialCopyAssignment())
15994         member = CXXCopyAssignment;
15995       else if (RDecl->hasNonTrivialDestructor())
15996         member = CXXDestructor;
15997 
15998       if (member != CXXInvalid) {
15999         if (!getLangOpts().CPlusPlus11 &&
16000             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
16001           // Objective-C++ ARC: it is an error to have a non-trivial field of
16002           // a union. However, system headers in Objective-C programs
16003           // occasionally have Objective-C lifetime objects within unions,
16004           // and rather than cause the program to fail, we make those
16005           // members unavailable.
16006           SourceLocation Loc = FD->getLocation();
16007           if (getSourceManager().isInSystemHeader(Loc)) {
16008             if (!FD->hasAttr<UnavailableAttr>())
16009               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
16010                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
16011             return false;
16012           }
16013         }
16014 
16015         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
16016                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
16017                diag::err_illegal_union_or_anon_struct_member)
16018           << FD->getParent()->isUnion() << FD->getDeclName() << member;
16019         DiagnoseNontrivial(RDecl, member);
16020         return !getLangOpts().CPlusPlus11;
16021       }
16022     }
16023   }
16024 
16025   return false;
16026 }
16027 
16028 /// TranslateIvarVisibility - Translate visibility from a token ID to an
16029 ///  AST enum value.
16030 static ObjCIvarDecl::AccessControl
16031 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
16032   switch (ivarVisibility) {
16033   default: llvm_unreachable("Unknown visitibility kind");
16034   case tok::objc_private: return ObjCIvarDecl::Private;
16035   case tok::objc_public: return ObjCIvarDecl::Public;
16036   case tok::objc_protected: return ObjCIvarDecl::Protected;
16037   case tok::objc_package: return ObjCIvarDecl::Package;
16038   }
16039 }
16040 
16041 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
16042 /// in order to create an IvarDecl object for it.
16043 Decl *Sema::ActOnIvar(Scope *S,
16044                                 SourceLocation DeclStart,
16045                                 Declarator &D, Expr *BitfieldWidth,
16046                                 tok::ObjCKeywordKind Visibility) {
16047 
16048   IdentifierInfo *II = D.getIdentifier();
16049   Expr *BitWidth = (Expr*)BitfieldWidth;
16050   SourceLocation Loc = DeclStart;
16051   if (II) Loc = D.getIdentifierLoc();
16052 
16053   // FIXME: Unnamed fields can be handled in various different ways, for
16054   // example, unnamed unions inject all members into the struct namespace!
16055 
16056   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16057   QualType T = TInfo->getType();
16058 
16059   if (BitWidth) {
16060     // 6.7.2.1p3, 6.7.2.1p4
16061     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
16062     if (!BitWidth)
16063       D.setInvalidType();
16064   } else {
16065     // Not a bitfield.
16066 
16067     // validate II.
16068 
16069   }
16070   if (T->isReferenceType()) {
16071     Diag(Loc, diag::err_ivar_reference_type);
16072     D.setInvalidType();
16073   }
16074   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16075   // than a variably modified type.
16076   else if (T->isVariablyModifiedType()) {
16077     Diag(Loc, diag::err_typecheck_ivar_variable_size);
16078     D.setInvalidType();
16079   }
16080 
16081   // Get the visibility (access control) for this ivar.
16082   ObjCIvarDecl::AccessControl ac =
16083     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
16084                                         : ObjCIvarDecl::None;
16085   // Must set ivar's DeclContext to its enclosing interface.
16086   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
16087   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
16088     return nullptr;
16089   ObjCContainerDecl *EnclosingContext;
16090   if (ObjCImplementationDecl *IMPDecl =
16091       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16092     if (LangOpts.ObjCRuntime.isFragile()) {
16093     // Case of ivar declared in an implementation. Context is that of its class.
16094       EnclosingContext = IMPDecl->getClassInterface();
16095       assert(EnclosingContext && "Implementation has no class interface!");
16096     }
16097     else
16098       EnclosingContext = EnclosingDecl;
16099   } else {
16100     if (ObjCCategoryDecl *CDecl =
16101         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16102       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
16103         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
16104         return nullptr;
16105       }
16106     }
16107     EnclosingContext = EnclosingDecl;
16108   }
16109 
16110   // Construct the decl.
16111   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
16112                                              DeclStart, Loc, II, T,
16113                                              TInfo, ac, (Expr *)BitfieldWidth);
16114 
16115   if (II) {
16116     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
16117                                            ForVisibleRedeclaration);
16118     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
16119         && !isa<TagDecl>(PrevDecl)) {
16120       Diag(Loc, diag::err_duplicate_member) << II;
16121       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16122       NewID->setInvalidDecl();
16123     }
16124   }
16125 
16126   // Process attributes attached to the ivar.
16127   ProcessDeclAttributes(S, NewID, D);
16128 
16129   if (D.isInvalidType())
16130     NewID->setInvalidDecl();
16131 
16132   // In ARC, infer 'retaining' for ivars of retainable type.
16133   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
16134     NewID->setInvalidDecl();
16135 
16136   if (D.getDeclSpec().isModulePrivateSpecified())
16137     NewID->setModulePrivate();
16138 
16139   if (II) {
16140     // FIXME: When interfaces are DeclContexts, we'll need to add
16141     // these to the interface.
16142     S->AddDecl(NewID);
16143     IdResolver.AddDecl(NewID);
16144   }
16145 
16146   if (LangOpts.ObjCRuntime.isNonFragile() &&
16147       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
16148     Diag(Loc, diag::warn_ivars_in_interface);
16149 
16150   return NewID;
16151 }
16152 
16153 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
16154 /// class and class extensions. For every class \@interface and class
16155 /// extension \@interface, if the last ivar is a bitfield of any type,
16156 /// then add an implicit `char :0` ivar to the end of that interface.
16157 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
16158                              SmallVectorImpl<Decl *> &AllIvarDecls) {
16159   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
16160     return;
16161 
16162   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
16163   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
16164 
16165   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
16166     return;
16167   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
16168   if (!ID) {
16169     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
16170       if (!CD->IsClassExtension())
16171         return;
16172     }
16173     // No need to add this to end of @implementation.
16174     else
16175       return;
16176   }
16177   // All conditions are met. Add a new bitfield to the tail end of ivars.
16178   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
16179   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
16180 
16181   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
16182                               DeclLoc, DeclLoc, nullptr,
16183                               Context.CharTy,
16184                               Context.getTrivialTypeSourceInfo(Context.CharTy,
16185                                                                DeclLoc),
16186                               ObjCIvarDecl::Private, BW,
16187                               true);
16188   AllIvarDecls.push_back(Ivar);
16189 }
16190 
16191 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
16192                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
16193                        SourceLocation RBrac,
16194                        const ParsedAttributesView &Attrs) {
16195   assert(EnclosingDecl && "missing record or interface decl");
16196 
16197   // If this is an Objective-C @implementation or category and we have
16198   // new fields here we should reset the layout of the interface since
16199   // it will now change.
16200   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
16201     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
16202     switch (DC->getKind()) {
16203     default: break;
16204     case Decl::ObjCCategory:
16205       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
16206       break;
16207     case Decl::ObjCImplementation:
16208       Context.
16209         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
16210       break;
16211     }
16212   }
16213 
16214   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
16215   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
16216 
16217   // Start counting up the number of named members; make sure to include
16218   // members of anonymous structs and unions in the total.
16219   unsigned NumNamedMembers = 0;
16220   if (Record) {
16221     for (const auto *I : Record->decls()) {
16222       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
16223         if (IFD->getDeclName())
16224           ++NumNamedMembers;
16225     }
16226   }
16227 
16228   // Verify that all the fields are okay.
16229   SmallVector<FieldDecl*, 32> RecFields;
16230 
16231   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
16232        i != end; ++i) {
16233     FieldDecl *FD = cast<FieldDecl>(*i);
16234 
16235     // Get the type for the field.
16236     const Type *FDTy = FD->getType().getTypePtr();
16237 
16238     if (!FD->isAnonymousStructOrUnion()) {
16239       // Remember all fields written by the user.
16240       RecFields.push_back(FD);
16241     }
16242 
16243     // If the field is already invalid for some reason, don't emit more
16244     // diagnostics about it.
16245     if (FD->isInvalidDecl()) {
16246       EnclosingDecl->setInvalidDecl();
16247       continue;
16248     }
16249 
16250     // C99 6.7.2.1p2:
16251     //   A structure or union shall not contain a member with
16252     //   incomplete or function type (hence, a structure shall not
16253     //   contain an instance of itself, but may contain a pointer to
16254     //   an instance of itself), except that the last member of a
16255     //   structure with more than one named member may have incomplete
16256     //   array type; such a structure (and any union containing,
16257     //   possibly recursively, a member that is such a structure)
16258     //   shall not be a member of a structure or an element of an
16259     //   array.
16260     bool IsLastField = (i + 1 == Fields.end());
16261     if (FDTy->isFunctionType()) {
16262       // Field declared as a function.
16263       Diag(FD->getLocation(), diag::err_field_declared_as_function)
16264         << FD->getDeclName();
16265       FD->setInvalidDecl();
16266       EnclosingDecl->setInvalidDecl();
16267       continue;
16268     } else if (FDTy->isIncompleteArrayType() &&
16269                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
16270       if (Record) {
16271         // Flexible array member.
16272         // Microsoft and g++ is more permissive regarding flexible array.
16273         // It will accept flexible array in union and also
16274         // as the sole element of a struct/class.
16275         unsigned DiagID = 0;
16276         if (!Record->isUnion() && !IsLastField) {
16277           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
16278             << FD->getDeclName() << FD->getType() << Record->getTagKind();
16279           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
16280           FD->setInvalidDecl();
16281           EnclosingDecl->setInvalidDecl();
16282           continue;
16283         } else if (Record->isUnion())
16284           DiagID = getLangOpts().MicrosoftExt
16285                        ? diag::ext_flexible_array_union_ms
16286                        : getLangOpts().CPlusPlus
16287                              ? diag::ext_flexible_array_union_gnu
16288                              : diag::err_flexible_array_union;
16289         else if (NumNamedMembers < 1)
16290           DiagID = getLangOpts().MicrosoftExt
16291                        ? diag::ext_flexible_array_empty_aggregate_ms
16292                        : getLangOpts().CPlusPlus
16293                              ? diag::ext_flexible_array_empty_aggregate_gnu
16294                              : diag::err_flexible_array_empty_aggregate;
16295 
16296         if (DiagID)
16297           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
16298                                           << Record->getTagKind();
16299         // While the layout of types that contain virtual bases is not specified
16300         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
16301         // virtual bases after the derived members.  This would make a flexible
16302         // array member declared at the end of an object not adjacent to the end
16303         // of the type.
16304         if (CXXRecord && CXXRecord->getNumVBases() != 0)
16305           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
16306               << FD->getDeclName() << Record->getTagKind();
16307         if (!getLangOpts().C99)
16308           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
16309             << FD->getDeclName() << Record->getTagKind();
16310 
16311         // If the element type has a non-trivial destructor, we would not
16312         // implicitly destroy the elements, so disallow it for now.
16313         //
16314         // FIXME: GCC allows this. We should probably either implicitly delete
16315         // the destructor of the containing class, or just allow this.
16316         QualType BaseElem = Context.getBaseElementType(FD->getType());
16317         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
16318           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
16319             << FD->getDeclName() << FD->getType();
16320           FD->setInvalidDecl();
16321           EnclosingDecl->setInvalidDecl();
16322           continue;
16323         }
16324         // Okay, we have a legal flexible array member at the end of the struct.
16325         Record->setHasFlexibleArrayMember(true);
16326       } else {
16327         // In ObjCContainerDecl ivars with incomplete array type are accepted,
16328         // unless they are followed by another ivar. That check is done
16329         // elsewhere, after synthesized ivars are known.
16330       }
16331     } else if (!FDTy->isDependentType() &&
16332                RequireCompleteType(FD->getLocation(), FD->getType(),
16333                                    diag::err_field_incomplete)) {
16334       // Incomplete type
16335       FD->setInvalidDecl();
16336       EnclosingDecl->setInvalidDecl();
16337       continue;
16338     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
16339       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
16340         // A type which contains a flexible array member is considered to be a
16341         // flexible array member.
16342         Record->setHasFlexibleArrayMember(true);
16343         if (!Record->isUnion()) {
16344           // If this is a struct/class and this is not the last element, reject
16345           // it.  Note that GCC supports variable sized arrays in the middle of
16346           // structures.
16347           if (!IsLastField)
16348             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
16349               << FD->getDeclName() << FD->getType();
16350           else {
16351             // We support flexible arrays at the end of structs in
16352             // other structs as an extension.
16353             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
16354               << FD->getDeclName();
16355           }
16356         }
16357       }
16358       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
16359           RequireNonAbstractType(FD->getLocation(), FD->getType(),
16360                                  diag::err_abstract_type_in_decl,
16361                                  AbstractIvarType)) {
16362         // Ivars can not have abstract class types
16363         FD->setInvalidDecl();
16364       }
16365       if (Record && FDTTy->getDecl()->hasObjectMember())
16366         Record->setHasObjectMember(true);
16367       if (Record && FDTTy->getDecl()->hasVolatileMember())
16368         Record->setHasVolatileMember(true);
16369     } else if (FDTy->isObjCObjectType()) {
16370       /// A field cannot be an Objective-c object
16371       Diag(FD->getLocation(), diag::err_statically_allocated_object)
16372         << FixItHint::CreateInsertion(FD->getLocation(), "*");
16373       QualType T = Context.getObjCObjectPointerType(FD->getType());
16374       FD->setType(T);
16375     } else if (getLangOpts().ObjC &&
16376                getLangOpts().getGC() != LangOptions::NonGC &&
16377                Record && !Record->hasObjectMember()) {
16378       if (FD->getType()->isObjCObjectPointerType() ||
16379           FD->getType().isObjCGCStrong())
16380         Record->setHasObjectMember(true);
16381       else if (Context.getAsArrayType(FD->getType())) {
16382         QualType BaseType = Context.getBaseElementType(FD->getType());
16383         if (BaseType->isRecordType() &&
16384             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
16385           Record->setHasObjectMember(true);
16386         else if (BaseType->isObjCObjectPointerType() ||
16387                  BaseType.isObjCGCStrong())
16388                Record->setHasObjectMember(true);
16389       }
16390     }
16391 
16392     if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) {
16393       QualType FT = FD->getType();
16394       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
16395         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
16396         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
16397             Record->isUnion())
16398           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
16399       }
16400       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
16401       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
16402         Record->setNonTrivialToPrimitiveCopy(true);
16403         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
16404           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
16405       }
16406       if (FT.isDestructedType()) {
16407         Record->setNonTrivialToPrimitiveDestroy(true);
16408         Record->setParamDestroyedInCallee(true);
16409         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
16410           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
16411       }
16412 
16413       if (const auto *RT = FT->getAs<RecordType>()) {
16414         if (RT->getDecl()->getArgPassingRestrictions() ==
16415             RecordDecl::APK_CanNeverPassInRegs)
16416           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16417       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
16418         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16419     }
16420 
16421     if (Record && FD->getType().isVolatileQualified())
16422       Record->setHasVolatileMember(true);
16423     // Keep track of the number of named members.
16424     if (FD->getIdentifier())
16425       ++NumNamedMembers;
16426   }
16427 
16428   // Okay, we successfully defined 'Record'.
16429   if (Record) {
16430     bool Completed = false;
16431     if (CXXRecord) {
16432       if (!CXXRecord->isInvalidDecl()) {
16433         // Set access bits correctly on the directly-declared conversions.
16434         for (CXXRecordDecl::conversion_iterator
16435                I = CXXRecord->conversion_begin(),
16436                E = CXXRecord->conversion_end(); I != E; ++I)
16437           I.setAccess((*I)->getAccess());
16438       }
16439 
16440       if (!CXXRecord->isDependentType()) {
16441         // Add any implicitly-declared members to this class.
16442         AddImplicitlyDeclaredMembersToClass(CXXRecord);
16443 
16444         if (!CXXRecord->isInvalidDecl()) {
16445           // If we have virtual base classes, we may end up finding multiple
16446           // final overriders for a given virtual function. Check for this
16447           // problem now.
16448           if (CXXRecord->getNumVBases()) {
16449             CXXFinalOverriderMap FinalOverriders;
16450             CXXRecord->getFinalOverriders(FinalOverriders);
16451 
16452             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
16453                                              MEnd = FinalOverriders.end();
16454                  M != MEnd; ++M) {
16455               for (OverridingMethods::iterator SO = M->second.begin(),
16456                                             SOEnd = M->second.end();
16457                    SO != SOEnd; ++SO) {
16458                 assert(SO->second.size() > 0 &&
16459                        "Virtual function without overriding functions?");
16460                 if (SO->second.size() == 1)
16461                   continue;
16462 
16463                 // C++ [class.virtual]p2:
16464                 //   In a derived class, if a virtual member function of a base
16465                 //   class subobject has more than one final overrider the
16466                 //   program is ill-formed.
16467                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
16468                   << (const NamedDecl *)M->first << Record;
16469                 Diag(M->first->getLocation(),
16470                      diag::note_overridden_virtual_function);
16471                 for (OverridingMethods::overriding_iterator
16472                           OM = SO->second.begin(),
16473                        OMEnd = SO->second.end();
16474                      OM != OMEnd; ++OM)
16475                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
16476                     << (const NamedDecl *)M->first << OM->Method->getParent();
16477 
16478                 Record->setInvalidDecl();
16479               }
16480             }
16481             CXXRecord->completeDefinition(&FinalOverriders);
16482             Completed = true;
16483           }
16484         }
16485       }
16486     }
16487 
16488     if (!Completed)
16489       Record->completeDefinition();
16490 
16491     // Handle attributes before checking the layout.
16492     ProcessDeclAttributeList(S, Record, Attrs);
16493 
16494     // We may have deferred checking for a deleted destructor. Check now.
16495     if (CXXRecord) {
16496       auto *Dtor = CXXRecord->getDestructor();
16497       if (Dtor && Dtor->isImplicit() &&
16498           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
16499         CXXRecord->setImplicitDestructorIsDeleted();
16500         SetDeclDeleted(Dtor, CXXRecord->getLocation());
16501       }
16502     }
16503 
16504     if (Record->hasAttrs()) {
16505       CheckAlignasUnderalignment(Record);
16506 
16507       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
16508         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
16509                                            IA->getRange(), IA->getBestCase(),
16510                                            IA->getSemanticSpelling());
16511     }
16512 
16513     // Check if the structure/union declaration is a type that can have zero
16514     // size in C. For C this is a language extension, for C++ it may cause
16515     // compatibility problems.
16516     bool CheckForZeroSize;
16517     if (!getLangOpts().CPlusPlus) {
16518       CheckForZeroSize = true;
16519     } else {
16520       // For C++ filter out types that cannot be referenced in C code.
16521       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
16522       CheckForZeroSize =
16523           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
16524           !CXXRecord->isDependentType() &&
16525           CXXRecord->isCLike();
16526     }
16527     if (CheckForZeroSize) {
16528       bool ZeroSize = true;
16529       bool IsEmpty = true;
16530       unsigned NonBitFields = 0;
16531       for (RecordDecl::field_iterator I = Record->field_begin(),
16532                                       E = Record->field_end();
16533            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
16534         IsEmpty = false;
16535         if (I->isUnnamedBitfield()) {
16536           if (!I->isZeroLengthBitField(Context))
16537             ZeroSize = false;
16538         } else {
16539           ++NonBitFields;
16540           QualType FieldType = I->getType();
16541           if (FieldType->isIncompleteType() ||
16542               !Context.getTypeSizeInChars(FieldType).isZero())
16543             ZeroSize = false;
16544         }
16545       }
16546 
16547       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
16548       // allowed in C++, but warn if its declaration is inside
16549       // extern "C" block.
16550       if (ZeroSize) {
16551         Diag(RecLoc, getLangOpts().CPlusPlus ?
16552                          diag::warn_zero_size_struct_union_in_extern_c :
16553                          diag::warn_zero_size_struct_union_compat)
16554           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
16555       }
16556 
16557       // Structs without named members are extension in C (C99 6.7.2.1p7),
16558       // but are accepted by GCC.
16559       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
16560         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
16561                                diag::ext_no_named_members_in_struct_union)
16562           << Record->isUnion();
16563       }
16564     }
16565   } else {
16566     ObjCIvarDecl **ClsFields =
16567       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
16568     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
16569       ID->setEndOfDefinitionLoc(RBrac);
16570       // Add ivar's to class's DeclContext.
16571       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16572         ClsFields[i]->setLexicalDeclContext(ID);
16573         ID->addDecl(ClsFields[i]);
16574       }
16575       // Must enforce the rule that ivars in the base classes may not be
16576       // duplicates.
16577       if (ID->getSuperClass())
16578         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
16579     } else if (ObjCImplementationDecl *IMPDecl =
16580                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16581       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
16582       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
16583         // Ivar declared in @implementation never belongs to the implementation.
16584         // Only it is in implementation's lexical context.
16585         ClsFields[I]->setLexicalDeclContext(IMPDecl);
16586       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
16587       IMPDecl->setIvarLBraceLoc(LBrac);
16588       IMPDecl->setIvarRBraceLoc(RBrac);
16589     } else if (ObjCCategoryDecl *CDecl =
16590                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16591       // case of ivars in class extension; all other cases have been
16592       // reported as errors elsewhere.
16593       // FIXME. Class extension does not have a LocEnd field.
16594       // CDecl->setLocEnd(RBrac);
16595       // Add ivar's to class extension's DeclContext.
16596       // Diagnose redeclaration of private ivars.
16597       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
16598       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16599         if (IDecl) {
16600           if (const ObjCIvarDecl *ClsIvar =
16601               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
16602             Diag(ClsFields[i]->getLocation(),
16603                  diag::err_duplicate_ivar_declaration);
16604             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
16605             continue;
16606           }
16607           for (const auto *Ext : IDecl->known_extensions()) {
16608             if (const ObjCIvarDecl *ClsExtIvar
16609                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
16610               Diag(ClsFields[i]->getLocation(),
16611                    diag::err_duplicate_ivar_declaration);
16612               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
16613               continue;
16614             }
16615           }
16616         }
16617         ClsFields[i]->setLexicalDeclContext(CDecl);
16618         CDecl->addDecl(ClsFields[i]);
16619       }
16620       CDecl->setIvarLBraceLoc(LBrac);
16621       CDecl->setIvarRBraceLoc(RBrac);
16622     }
16623   }
16624 }
16625 
16626 /// Determine whether the given integral value is representable within
16627 /// the given type T.
16628 static bool isRepresentableIntegerValue(ASTContext &Context,
16629                                         llvm::APSInt &Value,
16630                                         QualType T) {
16631   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
16632          "Integral type required!");
16633   unsigned BitWidth = Context.getIntWidth(T);
16634 
16635   if (Value.isUnsigned() || Value.isNonNegative()) {
16636     if (T->isSignedIntegerOrEnumerationType())
16637       --BitWidth;
16638     return Value.getActiveBits() <= BitWidth;
16639   }
16640   return Value.getMinSignedBits() <= BitWidth;
16641 }
16642 
16643 // Given an integral type, return the next larger integral type
16644 // (or a NULL type of no such type exists).
16645 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
16646   // FIXME: Int128/UInt128 support, which also needs to be introduced into
16647   // enum checking below.
16648   assert((T->isIntegralType(Context) ||
16649          T->isEnumeralType()) && "Integral type required!");
16650   const unsigned NumTypes = 4;
16651   QualType SignedIntegralTypes[NumTypes] = {
16652     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
16653   };
16654   QualType UnsignedIntegralTypes[NumTypes] = {
16655     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
16656     Context.UnsignedLongLongTy
16657   };
16658 
16659   unsigned BitWidth = Context.getTypeSize(T);
16660   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
16661                                                         : UnsignedIntegralTypes;
16662   for (unsigned I = 0; I != NumTypes; ++I)
16663     if (Context.getTypeSize(Types[I]) > BitWidth)
16664       return Types[I];
16665 
16666   return QualType();
16667 }
16668 
16669 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
16670                                           EnumConstantDecl *LastEnumConst,
16671                                           SourceLocation IdLoc,
16672                                           IdentifierInfo *Id,
16673                                           Expr *Val) {
16674   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16675   llvm::APSInt EnumVal(IntWidth);
16676   QualType EltTy;
16677 
16678   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
16679     Val = nullptr;
16680 
16681   if (Val)
16682     Val = DefaultLvalueConversion(Val).get();
16683 
16684   if (Val) {
16685     if (Enum->isDependentType() || Val->isTypeDependent())
16686       EltTy = Context.DependentTy;
16687     else {
16688       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
16689           !getLangOpts().MSVCCompat) {
16690         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
16691         // constant-expression in the enumerator-definition shall be a converted
16692         // constant expression of the underlying type.
16693         EltTy = Enum->getIntegerType();
16694         ExprResult Converted =
16695           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
16696                                            CCEK_Enumerator);
16697         if (Converted.isInvalid())
16698           Val = nullptr;
16699         else
16700           Val = Converted.get();
16701       } else if (!Val->isValueDependent() &&
16702                  !(Val = VerifyIntegerConstantExpression(Val,
16703                                                          &EnumVal).get())) {
16704         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
16705       } else {
16706         if (Enum->isComplete()) {
16707           EltTy = Enum->getIntegerType();
16708 
16709           // In Obj-C and Microsoft mode, require the enumeration value to be
16710           // representable in the underlying type of the enumeration. In C++11,
16711           // we perform a non-narrowing conversion as part of converted constant
16712           // expression checking.
16713           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
16714             if (getLangOpts().MSVCCompat) {
16715               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
16716               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
16717             } else
16718               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
16719           } else
16720             Val = ImpCastExprToType(Val, EltTy,
16721                                     EltTy->isBooleanType() ?
16722                                     CK_IntegralToBoolean : CK_IntegralCast)
16723                     .get();
16724         } else if (getLangOpts().CPlusPlus) {
16725           // C++11 [dcl.enum]p5:
16726           //   If the underlying type is not fixed, the type of each enumerator
16727           //   is the type of its initializing value:
16728           //     - If an initializer is specified for an enumerator, the
16729           //       initializing value has the same type as the expression.
16730           EltTy = Val->getType();
16731         } else {
16732           // C99 6.7.2.2p2:
16733           //   The expression that defines the value of an enumeration constant
16734           //   shall be an integer constant expression that has a value
16735           //   representable as an int.
16736 
16737           // Complain if the value is not representable in an int.
16738           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
16739             Diag(IdLoc, diag::ext_enum_value_not_int)
16740               << EnumVal.toString(10) << Val->getSourceRange()
16741               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
16742           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
16743             // Force the type of the expression to 'int'.
16744             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
16745           }
16746           EltTy = Val->getType();
16747         }
16748       }
16749     }
16750   }
16751 
16752   if (!Val) {
16753     if (Enum->isDependentType())
16754       EltTy = Context.DependentTy;
16755     else if (!LastEnumConst) {
16756       // C++0x [dcl.enum]p5:
16757       //   If the underlying type is not fixed, the type of each enumerator
16758       //   is the type of its initializing value:
16759       //     - If no initializer is specified for the first enumerator, the
16760       //       initializing value has an unspecified integral type.
16761       //
16762       // GCC uses 'int' for its unspecified integral type, as does
16763       // C99 6.7.2.2p3.
16764       if (Enum->isFixed()) {
16765         EltTy = Enum->getIntegerType();
16766       }
16767       else {
16768         EltTy = Context.IntTy;
16769       }
16770     } else {
16771       // Assign the last value + 1.
16772       EnumVal = LastEnumConst->getInitVal();
16773       ++EnumVal;
16774       EltTy = LastEnumConst->getType();
16775 
16776       // Check for overflow on increment.
16777       if (EnumVal < LastEnumConst->getInitVal()) {
16778         // C++0x [dcl.enum]p5:
16779         //   If the underlying type is not fixed, the type of each enumerator
16780         //   is the type of its initializing value:
16781         //
16782         //     - Otherwise the type of the initializing value is the same as
16783         //       the type of the initializing value of the preceding enumerator
16784         //       unless the incremented value is not representable in that type,
16785         //       in which case the type is an unspecified integral type
16786         //       sufficient to contain the incremented value. If no such type
16787         //       exists, the program is ill-formed.
16788         QualType T = getNextLargerIntegralType(Context, EltTy);
16789         if (T.isNull() || Enum->isFixed()) {
16790           // There is no integral type larger enough to represent this
16791           // value. Complain, then allow the value to wrap around.
16792           EnumVal = LastEnumConst->getInitVal();
16793           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
16794           ++EnumVal;
16795           if (Enum->isFixed())
16796             // When the underlying type is fixed, this is ill-formed.
16797             Diag(IdLoc, diag::err_enumerator_wrapped)
16798               << EnumVal.toString(10)
16799               << EltTy;
16800           else
16801             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
16802               << EnumVal.toString(10);
16803         } else {
16804           EltTy = T;
16805         }
16806 
16807         // Retrieve the last enumerator's value, extent that type to the
16808         // type that is supposed to be large enough to represent the incremented
16809         // value, then increment.
16810         EnumVal = LastEnumConst->getInitVal();
16811         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
16812         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
16813         ++EnumVal;
16814 
16815         // If we're not in C++, diagnose the overflow of enumerator values,
16816         // which in C99 means that the enumerator value is not representable in
16817         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
16818         // permits enumerator values that are representable in some larger
16819         // integral type.
16820         if (!getLangOpts().CPlusPlus && !T.isNull())
16821           Diag(IdLoc, diag::warn_enum_value_overflow);
16822       } else if (!getLangOpts().CPlusPlus &&
16823                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
16824         // Enforce C99 6.7.2.2p2 even when we compute the next value.
16825         Diag(IdLoc, diag::ext_enum_value_not_int)
16826           << EnumVal.toString(10) << 1;
16827       }
16828     }
16829   }
16830 
16831   if (!EltTy->isDependentType()) {
16832     // Make the enumerator value match the signedness and size of the
16833     // enumerator's type.
16834     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
16835     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
16836   }
16837 
16838   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
16839                                   Val, EnumVal);
16840 }
16841 
16842 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
16843                                                 SourceLocation IILoc) {
16844   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
16845       !getLangOpts().CPlusPlus)
16846     return SkipBodyInfo();
16847 
16848   // We have an anonymous enum definition. Look up the first enumerator to
16849   // determine if we should merge the definition with an existing one and
16850   // skip the body.
16851   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
16852                                          forRedeclarationInCurContext());
16853   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
16854   if (!PrevECD)
16855     return SkipBodyInfo();
16856 
16857   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
16858   NamedDecl *Hidden;
16859   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
16860     SkipBodyInfo Skip;
16861     Skip.Previous = Hidden;
16862     return Skip;
16863   }
16864 
16865   return SkipBodyInfo();
16866 }
16867 
16868 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
16869                               SourceLocation IdLoc, IdentifierInfo *Id,
16870                               const ParsedAttributesView &Attrs,
16871                               SourceLocation EqualLoc, Expr *Val) {
16872   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
16873   EnumConstantDecl *LastEnumConst =
16874     cast_or_null<EnumConstantDecl>(lastEnumConst);
16875 
16876   // The scope passed in may not be a decl scope.  Zip up the scope tree until
16877   // we find one that is.
16878   S = getNonFieldDeclScope(S);
16879 
16880   // Verify that there isn't already something declared with this name in this
16881   // scope.
16882   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
16883   LookupName(R, S);
16884   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
16885 
16886   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16887     // Maybe we will complain about the shadowed template parameter.
16888     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
16889     // Just pretend that we didn't see the previous declaration.
16890     PrevDecl = nullptr;
16891   }
16892 
16893   // C++ [class.mem]p15:
16894   // If T is the name of a class, then each of the following shall have a name
16895   // different from T:
16896   // - every enumerator of every member of class T that is an unscoped
16897   // enumerated type
16898   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
16899     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
16900                             DeclarationNameInfo(Id, IdLoc));
16901 
16902   EnumConstantDecl *New =
16903     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
16904   if (!New)
16905     return nullptr;
16906 
16907   if (PrevDecl) {
16908     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
16909       // Check for other kinds of shadowing not already handled.
16910       CheckShadow(New, PrevDecl, R);
16911     }
16912 
16913     // When in C++, we may get a TagDecl with the same name; in this case the
16914     // enum constant will 'hide' the tag.
16915     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
16916            "Received TagDecl when not in C++!");
16917     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
16918       if (isa<EnumConstantDecl>(PrevDecl))
16919         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
16920       else
16921         Diag(IdLoc, diag::err_redefinition) << Id;
16922       notePreviousDefinition(PrevDecl, IdLoc);
16923       return nullptr;
16924     }
16925   }
16926 
16927   // Process attributes.
16928   ProcessDeclAttributeList(S, New, Attrs);
16929   AddPragmaAttributes(S, New);
16930 
16931   // Register this decl in the current scope stack.
16932   New->setAccess(TheEnumDecl->getAccess());
16933   PushOnScopeChains(New, S);
16934 
16935   ActOnDocumentableDecl(New);
16936 
16937   return New;
16938 }
16939 
16940 // Returns true when the enum initial expression does not trigger the
16941 // duplicate enum warning.  A few common cases are exempted as follows:
16942 // Element2 = Element1
16943 // Element2 = Element1 + 1
16944 // Element2 = Element1 - 1
16945 // Where Element2 and Element1 are from the same enum.
16946 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
16947   Expr *InitExpr = ECD->getInitExpr();
16948   if (!InitExpr)
16949     return true;
16950   InitExpr = InitExpr->IgnoreImpCasts();
16951 
16952   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
16953     if (!BO->isAdditiveOp())
16954       return true;
16955     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
16956     if (!IL)
16957       return true;
16958     if (IL->getValue() != 1)
16959       return true;
16960 
16961     InitExpr = BO->getLHS();
16962   }
16963 
16964   // This checks if the elements are from the same enum.
16965   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
16966   if (!DRE)
16967     return true;
16968 
16969   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
16970   if (!EnumConstant)
16971     return true;
16972 
16973   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
16974       Enum)
16975     return true;
16976 
16977   return false;
16978 }
16979 
16980 // Emits a warning when an element is implicitly set a value that
16981 // a previous element has already been set to.
16982 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
16983                                         EnumDecl *Enum, QualType EnumType) {
16984   // Avoid anonymous enums
16985   if (!Enum->getIdentifier())
16986     return;
16987 
16988   // Only check for small enums.
16989   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
16990     return;
16991 
16992   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
16993     return;
16994 
16995   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
16996   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
16997 
16998   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
16999   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
17000 
17001   // Use int64_t as a key to avoid needing special handling for DenseMap keys.
17002   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
17003     llvm::APSInt Val = D->getInitVal();
17004     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
17005   };
17006 
17007   DuplicatesVector DupVector;
17008   ValueToVectorMap EnumMap;
17009 
17010   // Populate the EnumMap with all values represented by enum constants without
17011   // an initializer.
17012   for (auto *Element : Elements) {
17013     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
17014 
17015     // Null EnumConstantDecl means a previous diagnostic has been emitted for
17016     // this constant.  Skip this enum since it may be ill-formed.
17017     if (!ECD) {
17018       return;
17019     }
17020 
17021     // Constants with initalizers are handled in the next loop.
17022     if (ECD->getInitExpr())
17023       continue;
17024 
17025     // Duplicate values are handled in the next loop.
17026     EnumMap.insert({EnumConstantToKey(ECD), ECD});
17027   }
17028 
17029   if (EnumMap.size() == 0)
17030     return;
17031 
17032   // Create vectors for any values that has duplicates.
17033   for (auto *Element : Elements) {
17034     // The last loop returned if any constant was null.
17035     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
17036     if (!ValidDuplicateEnum(ECD, Enum))
17037       continue;
17038 
17039     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
17040     if (Iter == EnumMap.end())
17041       continue;
17042 
17043     DeclOrVector& Entry = Iter->second;
17044     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
17045       // Ensure constants are different.
17046       if (D == ECD)
17047         continue;
17048 
17049       // Create new vector and push values onto it.
17050       auto Vec = llvm::make_unique<ECDVector>();
17051       Vec->push_back(D);
17052       Vec->push_back(ECD);
17053 
17054       // Update entry to point to the duplicates vector.
17055       Entry = Vec.get();
17056 
17057       // Store the vector somewhere we can consult later for quick emission of
17058       // diagnostics.
17059       DupVector.emplace_back(std::move(Vec));
17060       continue;
17061     }
17062 
17063     ECDVector *Vec = Entry.get<ECDVector*>();
17064     // Make sure constants are not added more than once.
17065     if (*Vec->begin() == ECD)
17066       continue;
17067 
17068     Vec->push_back(ECD);
17069   }
17070 
17071   // Emit diagnostics.
17072   for (const auto &Vec : DupVector) {
17073     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
17074 
17075     // Emit warning for one enum constant.
17076     auto *FirstECD = Vec->front();
17077     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
17078       << FirstECD << FirstECD->getInitVal().toString(10)
17079       << FirstECD->getSourceRange();
17080 
17081     // Emit one note for each of the remaining enum constants with
17082     // the same value.
17083     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
17084       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
17085         << ECD << ECD->getInitVal().toString(10)
17086         << ECD->getSourceRange();
17087   }
17088 }
17089 
17090 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
17091                              bool AllowMask) const {
17092   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
17093   assert(ED->isCompleteDefinition() && "expected enum definition");
17094 
17095   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
17096   llvm::APInt &FlagBits = R.first->second;
17097 
17098   if (R.second) {
17099     for (auto *E : ED->enumerators()) {
17100       const auto &EVal = E->getInitVal();
17101       // Only single-bit enumerators introduce new flag values.
17102       if (EVal.isPowerOf2())
17103         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
17104     }
17105   }
17106 
17107   // A value is in a flag enum if either its bits are a subset of the enum's
17108   // flag bits (the first condition) or we are allowing masks and the same is
17109   // true of its complement (the second condition). When masks are allowed, we
17110   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
17111   //
17112   // While it's true that any value could be used as a mask, the assumption is
17113   // that a mask will have all of the insignificant bits set. Anything else is
17114   // likely a logic error.
17115   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
17116   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
17117 }
17118 
17119 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
17120                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
17121                          const ParsedAttributesView &Attrs) {
17122   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
17123   QualType EnumType = Context.getTypeDeclType(Enum);
17124 
17125   ProcessDeclAttributeList(S, Enum, Attrs);
17126 
17127   if (Enum->isDependentType()) {
17128     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17129       EnumConstantDecl *ECD =
17130         cast_or_null<EnumConstantDecl>(Elements[i]);
17131       if (!ECD) continue;
17132 
17133       ECD->setType(EnumType);
17134     }
17135 
17136     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
17137     return;
17138   }
17139 
17140   // TODO: If the result value doesn't fit in an int, it must be a long or long
17141   // long value.  ISO C does not support this, but GCC does as an extension,
17142   // emit a warning.
17143   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17144   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
17145   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
17146 
17147   // Verify that all the values are okay, compute the size of the values, and
17148   // reverse the list.
17149   unsigned NumNegativeBits = 0;
17150   unsigned NumPositiveBits = 0;
17151 
17152   // Keep track of whether all elements have type int.
17153   bool AllElementsInt = true;
17154 
17155   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17156     EnumConstantDecl *ECD =
17157       cast_or_null<EnumConstantDecl>(Elements[i]);
17158     if (!ECD) continue;  // Already issued a diagnostic.
17159 
17160     const llvm::APSInt &InitVal = ECD->getInitVal();
17161 
17162     // Keep track of the size of positive and negative values.
17163     if (InitVal.isUnsigned() || InitVal.isNonNegative())
17164       NumPositiveBits = std::max(NumPositiveBits,
17165                                  (unsigned)InitVal.getActiveBits());
17166     else
17167       NumNegativeBits = std::max(NumNegativeBits,
17168                                  (unsigned)InitVal.getMinSignedBits());
17169 
17170     // Keep track of whether every enum element has type int (very common).
17171     if (AllElementsInt)
17172       AllElementsInt = ECD->getType() == Context.IntTy;
17173   }
17174 
17175   // Figure out the type that should be used for this enum.
17176   QualType BestType;
17177   unsigned BestWidth;
17178 
17179   // C++0x N3000 [conv.prom]p3:
17180   //   An rvalue of an unscoped enumeration type whose underlying
17181   //   type is not fixed can be converted to an rvalue of the first
17182   //   of the following types that can represent all the values of
17183   //   the enumeration: int, unsigned int, long int, unsigned long
17184   //   int, long long int, or unsigned long long int.
17185   // C99 6.4.4.3p2:
17186   //   An identifier declared as an enumeration constant has type int.
17187   // The C99 rule is modified by a gcc extension
17188   QualType BestPromotionType;
17189 
17190   bool Packed = Enum->hasAttr<PackedAttr>();
17191   // -fshort-enums is the equivalent to specifying the packed attribute on all
17192   // enum definitions.
17193   if (LangOpts.ShortEnums)
17194     Packed = true;
17195 
17196   // If the enum already has a type because it is fixed or dictated by the
17197   // target, promote that type instead of analyzing the enumerators.
17198   if (Enum->isComplete()) {
17199     BestType = Enum->getIntegerType();
17200     if (BestType->isPromotableIntegerType())
17201       BestPromotionType = Context.getPromotedIntegerType(BestType);
17202     else
17203       BestPromotionType = BestType;
17204 
17205     BestWidth = Context.getIntWidth(BestType);
17206   }
17207   else if (NumNegativeBits) {
17208     // If there is a negative value, figure out the smallest integer type (of
17209     // int/long/longlong) that fits.
17210     // If it's packed, check also if it fits a char or a short.
17211     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
17212       BestType = Context.SignedCharTy;
17213       BestWidth = CharWidth;
17214     } else if (Packed && NumNegativeBits <= ShortWidth &&
17215                NumPositiveBits < ShortWidth) {
17216       BestType = Context.ShortTy;
17217       BestWidth = ShortWidth;
17218     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
17219       BestType = Context.IntTy;
17220       BestWidth = IntWidth;
17221     } else {
17222       BestWidth = Context.getTargetInfo().getLongWidth();
17223 
17224       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
17225         BestType = Context.LongTy;
17226       } else {
17227         BestWidth = Context.getTargetInfo().getLongLongWidth();
17228 
17229         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
17230           Diag(Enum->getLocation(), diag::ext_enum_too_large);
17231         BestType = Context.LongLongTy;
17232       }
17233     }
17234     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
17235   } else {
17236     // If there is no negative value, figure out the smallest type that fits
17237     // all of the enumerator values.
17238     // If it's packed, check also if it fits a char or a short.
17239     if (Packed && NumPositiveBits <= CharWidth) {
17240       BestType = Context.UnsignedCharTy;
17241       BestPromotionType = Context.IntTy;
17242       BestWidth = CharWidth;
17243     } else if (Packed && NumPositiveBits <= ShortWidth) {
17244       BestType = Context.UnsignedShortTy;
17245       BestPromotionType = Context.IntTy;
17246       BestWidth = ShortWidth;
17247     } else if (NumPositiveBits <= IntWidth) {
17248       BestType = Context.UnsignedIntTy;
17249       BestWidth = IntWidth;
17250       BestPromotionType
17251         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17252                            ? Context.UnsignedIntTy : Context.IntTy;
17253     } else if (NumPositiveBits <=
17254                (BestWidth = Context.getTargetInfo().getLongWidth())) {
17255       BestType = Context.UnsignedLongTy;
17256       BestPromotionType
17257         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17258                            ? Context.UnsignedLongTy : Context.LongTy;
17259     } else {
17260       BestWidth = Context.getTargetInfo().getLongLongWidth();
17261       assert(NumPositiveBits <= BestWidth &&
17262              "How could an initializer get larger than ULL?");
17263       BestType = Context.UnsignedLongLongTy;
17264       BestPromotionType
17265         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17266                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
17267     }
17268   }
17269 
17270   // Loop over all of the enumerator constants, changing their types to match
17271   // the type of the enum if needed.
17272   for (auto *D : Elements) {
17273     auto *ECD = cast_or_null<EnumConstantDecl>(D);
17274     if (!ECD) continue;  // Already issued a diagnostic.
17275 
17276     // Standard C says the enumerators have int type, but we allow, as an
17277     // extension, the enumerators to be larger than int size.  If each
17278     // enumerator value fits in an int, type it as an int, otherwise type it the
17279     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
17280     // that X has type 'int', not 'unsigned'.
17281 
17282     // Determine whether the value fits into an int.
17283     llvm::APSInt InitVal = ECD->getInitVal();
17284 
17285     // If it fits into an integer type, force it.  Otherwise force it to match
17286     // the enum decl type.
17287     QualType NewTy;
17288     unsigned NewWidth;
17289     bool NewSign;
17290     if (!getLangOpts().CPlusPlus &&
17291         !Enum->isFixed() &&
17292         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
17293       NewTy = Context.IntTy;
17294       NewWidth = IntWidth;
17295       NewSign = true;
17296     } else if (ECD->getType() == BestType) {
17297       // Already the right type!
17298       if (getLangOpts().CPlusPlus)
17299         // C++ [dcl.enum]p4: Following the closing brace of an
17300         // enum-specifier, each enumerator has the type of its
17301         // enumeration.
17302         ECD->setType(EnumType);
17303       continue;
17304     } else {
17305       NewTy = BestType;
17306       NewWidth = BestWidth;
17307       NewSign = BestType->isSignedIntegerOrEnumerationType();
17308     }
17309 
17310     // Adjust the APSInt value.
17311     InitVal = InitVal.extOrTrunc(NewWidth);
17312     InitVal.setIsSigned(NewSign);
17313     ECD->setInitVal(InitVal);
17314 
17315     // Adjust the Expr initializer and type.
17316     if (ECD->getInitExpr() &&
17317         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
17318       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
17319                                                 CK_IntegralCast,
17320                                                 ECD->getInitExpr(),
17321                                                 /*base paths*/ nullptr,
17322                                                 VK_RValue));
17323     if (getLangOpts().CPlusPlus)
17324       // C++ [dcl.enum]p4: Following the closing brace of an
17325       // enum-specifier, each enumerator has the type of its
17326       // enumeration.
17327       ECD->setType(EnumType);
17328     else
17329       ECD->setType(NewTy);
17330   }
17331 
17332   Enum->completeDefinition(BestType, BestPromotionType,
17333                            NumPositiveBits, NumNegativeBits);
17334 
17335   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
17336 
17337   if (Enum->isClosedFlag()) {
17338     for (Decl *D : Elements) {
17339       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
17340       if (!ECD) continue;  // Already issued a diagnostic.
17341 
17342       llvm::APSInt InitVal = ECD->getInitVal();
17343       if (InitVal != 0 && !InitVal.isPowerOf2() &&
17344           !IsValueInFlagEnum(Enum, InitVal, true))
17345         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
17346           << ECD << Enum;
17347     }
17348   }
17349 
17350   // Now that the enum type is defined, ensure it's not been underaligned.
17351   if (Enum->hasAttrs())
17352     CheckAlignasUnderalignment(Enum);
17353 }
17354 
17355 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
17356                                   SourceLocation StartLoc,
17357                                   SourceLocation EndLoc) {
17358   StringLiteral *AsmString = cast<StringLiteral>(expr);
17359 
17360   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
17361                                                    AsmString, StartLoc,
17362                                                    EndLoc);
17363   CurContext->addDecl(New);
17364   return New;
17365 }
17366 
17367 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
17368                                       IdentifierInfo* AliasName,
17369                                       SourceLocation PragmaLoc,
17370                                       SourceLocation NameLoc,
17371                                       SourceLocation AliasNameLoc) {
17372   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
17373                                          LookupOrdinaryName);
17374   AsmLabelAttr *Attr =
17375       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
17376 
17377   // If a declaration that:
17378   // 1) declares a function or a variable
17379   // 2) has external linkage
17380   // already exists, add a label attribute to it.
17381   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17382     if (isDeclExternC(PrevDecl))
17383       PrevDecl->addAttr(Attr);
17384     else
17385       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
17386           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
17387   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
17388   } else
17389     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
17390 }
17391 
17392 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
17393                              SourceLocation PragmaLoc,
17394                              SourceLocation NameLoc) {
17395   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
17396 
17397   if (PrevDecl) {
17398     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
17399   } else {
17400     (void)WeakUndeclaredIdentifiers.insert(
17401       std::pair<IdentifierInfo*,WeakInfo>
17402         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
17403   }
17404 }
17405 
17406 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
17407                                 IdentifierInfo* AliasName,
17408                                 SourceLocation PragmaLoc,
17409                                 SourceLocation NameLoc,
17410                                 SourceLocation AliasNameLoc) {
17411   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
17412                                     LookupOrdinaryName);
17413   WeakInfo W = WeakInfo(Name, NameLoc);
17414 
17415   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17416     if (!PrevDecl->hasAttr<AliasAttr>())
17417       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
17418         DeclApplyPragmaWeak(TUScope, ND, W);
17419   } else {
17420     (void)WeakUndeclaredIdentifiers.insert(
17421       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
17422   }
17423 }
17424 
17425 Decl *Sema::getObjCDeclContext() const {
17426   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
17427 }
17428