1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for declarations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/CommentDiagnostic.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/NonTrivialTypeVisitor.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/Basic/Builtins.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
32 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
33 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
34 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
35 #include "clang/Sema/CXXFieldCollector.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/DelayedDiagnostic.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaInternal.h"
44 #include "clang/Sema/Template.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/Triple.h"
47 #include <algorithm>
48 #include <cstring>
49 #include <functional>
50 
51 using namespace clang;
52 using namespace sema;
53 
54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
55   if (OwnedType) {
56     Decl *Group[2] = { OwnedType, Ptr };
57     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
58   }
59 
60   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
61 }
62 
63 namespace {
64 
65 class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
66  public:
67    TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
68                         bool AllowTemplates = false,
69                         bool AllowNonTemplates = true)
70        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
71          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
72      WantExpressionKeywords = false;
73      WantCXXNamedCasts = false;
74      WantRemainingKeywords = false;
75   }
76 
77   bool ValidateCandidate(const TypoCorrection &candidate) override {
78     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
79       if (!AllowInvalidDecl && ND->isInvalidDecl())
80         return false;
81 
82       if (getAsTypeTemplateDecl(ND))
83         return AllowTemplates;
84 
85       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
86       if (!IsType)
87         return false;
88 
89       if (AllowNonTemplates)
90         return true;
91 
92       // An injected-class-name of a class template (specialization) is valid
93       // as a template or as a non-template.
94       if (AllowTemplates) {
95         auto *RD = dyn_cast<CXXRecordDecl>(ND);
96         if (!RD || !RD->isInjectedClassName())
97           return false;
98         RD = cast<CXXRecordDecl>(RD->getDeclContext());
99         return RD->getDescribedClassTemplate() ||
100                isa<ClassTemplateSpecializationDecl>(RD);
101       }
102 
103       return false;
104     }
105 
106     return !WantClassName && candidate.isKeyword();
107   }
108 
109   std::unique_ptr<CorrectionCandidateCallback> clone() override {
110     return std::make_unique<TypeNameValidatorCCC>(*this);
111   }
112 
113  private:
114   bool AllowInvalidDecl;
115   bool WantClassName;
116   bool AllowTemplates;
117   bool AllowNonTemplates;
118 };
119 
120 } // end anonymous namespace
121 
122 /// Determine whether the token kind starts a simple-type-specifier.
123 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
124   switch (Kind) {
125   // FIXME: Take into account the current language when deciding whether a
126   // token kind is a valid type specifier
127   case tok::kw_short:
128   case tok::kw_long:
129   case tok::kw___int64:
130   case tok::kw___int128:
131   case tok::kw_signed:
132   case tok::kw_unsigned:
133   case tok::kw_void:
134   case tok::kw_char:
135   case tok::kw_int:
136   case tok::kw_half:
137   case tok::kw_float:
138   case tok::kw_double:
139   case tok::kw__Float16:
140   case tok::kw___float128:
141   case tok::kw_wchar_t:
142   case tok::kw_bool:
143   case tok::kw___underlying_type:
144   case tok::kw___auto_type:
145     return true;
146 
147   case tok::annot_typename:
148   case tok::kw_char16_t:
149   case tok::kw_char32_t:
150   case tok::kw_typeof:
151   case tok::annot_decltype:
152   case tok::kw_decltype:
153     return getLangOpts().CPlusPlus;
154 
155   case tok::kw_char8_t:
156     return getLangOpts().Char8;
157 
158   default:
159     break;
160   }
161 
162   return false;
163 }
164 
165 namespace {
166 enum class UnqualifiedTypeNameLookupResult {
167   NotFound,
168   FoundNonType,
169   FoundType
170 };
171 } // end anonymous namespace
172 
173 /// Tries to perform unqualified lookup of the type decls in bases for
174 /// dependent class.
175 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
176 /// type decl, \a FoundType if only type decls are found.
177 static UnqualifiedTypeNameLookupResult
178 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
179                                 SourceLocation NameLoc,
180                                 const CXXRecordDecl *RD) {
181   if (!RD->hasDefinition())
182     return UnqualifiedTypeNameLookupResult::NotFound;
183   // Look for type decls in base classes.
184   UnqualifiedTypeNameLookupResult FoundTypeDecl =
185       UnqualifiedTypeNameLookupResult::NotFound;
186   for (const auto &Base : RD->bases()) {
187     const CXXRecordDecl *BaseRD = nullptr;
188     if (auto *BaseTT = Base.getType()->getAs<TagType>())
189       BaseRD = BaseTT->getAsCXXRecordDecl();
190     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
191       // Look for type decls in dependent base classes that have known primary
192       // templates.
193       if (!TST || !TST->isDependentType())
194         continue;
195       auto *TD = TST->getTemplateName().getAsTemplateDecl();
196       if (!TD)
197         continue;
198       if (auto *BasePrimaryTemplate =
199           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
200         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
201           BaseRD = BasePrimaryTemplate;
202         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
203           if (const ClassTemplatePartialSpecializationDecl *PS =
204                   CTD->findPartialSpecialization(Base.getType()))
205             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
206               BaseRD = PS;
207         }
208       }
209     }
210     if (BaseRD) {
211       for (NamedDecl *ND : BaseRD->lookup(&II)) {
212         if (!isa<TypeDecl>(ND))
213           return UnqualifiedTypeNameLookupResult::FoundNonType;
214         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
215       }
216       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
217         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
218         case UnqualifiedTypeNameLookupResult::FoundNonType:
219           return UnqualifiedTypeNameLookupResult::FoundNonType;
220         case UnqualifiedTypeNameLookupResult::FoundType:
221           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
222           break;
223         case UnqualifiedTypeNameLookupResult::NotFound:
224           break;
225         }
226       }
227     }
228   }
229 
230   return FoundTypeDecl;
231 }
232 
233 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
234                                                       const IdentifierInfo &II,
235                                                       SourceLocation NameLoc) {
236   // Lookup in the parent class template context, if any.
237   const CXXRecordDecl *RD = nullptr;
238   UnqualifiedTypeNameLookupResult FoundTypeDecl =
239       UnqualifiedTypeNameLookupResult::NotFound;
240   for (DeclContext *DC = S.CurContext;
241        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
242        DC = DC->getParent()) {
243     // Look for type decls in dependent base classes that have known primary
244     // templates.
245     RD = dyn_cast<CXXRecordDecl>(DC);
246     if (RD && RD->getDescribedClassTemplate())
247       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
248   }
249   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
250     return nullptr;
251 
252   // We found some types in dependent base classes.  Recover as if the user
253   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
254   // lookup during template instantiation.
255   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
256 
257   ASTContext &Context = S.Context;
258   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
259                                           cast<Type>(Context.getRecordType(RD)));
260   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
261 
262   CXXScopeSpec SS;
263   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
264 
265   TypeLocBuilder Builder;
266   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
267   DepTL.setNameLoc(NameLoc);
268   DepTL.setElaboratedKeywordLoc(SourceLocation());
269   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
270   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
271 }
272 
273 /// If the identifier refers to a type name within this scope,
274 /// return the declaration of that type.
275 ///
276 /// This routine performs ordinary name lookup of the identifier II
277 /// within the given scope, with optional C++ scope specifier SS, to
278 /// determine whether the name refers to a type. If so, returns an
279 /// opaque pointer (actually a QualType) corresponding to that
280 /// type. Otherwise, returns NULL.
281 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
282                              Scope *S, CXXScopeSpec *SS,
283                              bool isClassName, bool HasTrailingDot,
284                              ParsedType ObjectTypePtr,
285                              bool IsCtorOrDtorName,
286                              bool WantNontrivialTypeSourceInfo,
287                              bool IsClassTemplateDeductionContext,
288                              IdentifierInfo **CorrectedII) {
289   // FIXME: Consider allowing this outside C++1z mode as an extension.
290   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
291                               getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
292                               !isClassName && !HasTrailingDot;
293 
294   // Determine where we will perform name lookup.
295   DeclContext *LookupCtx = nullptr;
296   if (ObjectTypePtr) {
297     QualType ObjectType = ObjectTypePtr.get();
298     if (ObjectType->isRecordType())
299       LookupCtx = computeDeclContext(ObjectType);
300   } else if (SS && SS->isNotEmpty()) {
301     LookupCtx = computeDeclContext(*SS, false);
302 
303     if (!LookupCtx) {
304       if (isDependentScopeSpecifier(*SS)) {
305         // C++ [temp.res]p3:
306         //   A qualified-id that refers to a type and in which the
307         //   nested-name-specifier depends on a template-parameter (14.6.2)
308         //   shall be prefixed by the keyword typename to indicate that the
309         //   qualified-id denotes a type, forming an
310         //   elaborated-type-specifier (7.1.5.3).
311         //
312         // We therefore do not perform any name lookup if the result would
313         // refer to a member of an unknown specialization.
314         if (!isClassName && !IsCtorOrDtorName)
315           return nullptr;
316 
317         // We know from the grammar that this name refers to a type,
318         // so build a dependent node to describe the type.
319         if (WantNontrivialTypeSourceInfo)
320           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
321 
322         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
323         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
324                                        II, NameLoc);
325         return ParsedType::make(T);
326       }
327 
328       return nullptr;
329     }
330 
331     if (!LookupCtx->isDependentContext() &&
332         RequireCompleteDeclContext(*SS, LookupCtx))
333       return nullptr;
334   }
335 
336   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
337   // lookup for class-names.
338   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
339                                       LookupOrdinaryName;
340   LookupResult Result(*this, &II, NameLoc, Kind);
341   if (LookupCtx) {
342     // Perform "qualified" name lookup into the declaration context we
343     // computed, which is either the type of the base of a member access
344     // expression or the declaration context associated with a prior
345     // nested-name-specifier.
346     LookupQualifiedName(Result, LookupCtx);
347 
348     if (ObjectTypePtr && Result.empty()) {
349       // C++ [basic.lookup.classref]p3:
350       //   If the unqualified-id is ~type-name, the type-name is looked up
351       //   in the context of the entire postfix-expression. If the type T of
352       //   the object expression is of a class type C, the type-name is also
353       //   looked up in the scope of class C. At least one of the lookups shall
354       //   find a name that refers to (possibly cv-qualified) T.
355       LookupName(Result, S);
356     }
357   } else {
358     // Perform unqualified name lookup.
359     LookupName(Result, S);
360 
361     // For unqualified lookup in a class template in MSVC mode, look into
362     // dependent base classes where the primary class template is known.
363     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
364       if (ParsedType TypeInBase =
365               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
366         return TypeInBase;
367     }
368   }
369 
370   NamedDecl *IIDecl = nullptr;
371   switch (Result.getResultKind()) {
372   case LookupResult::NotFound:
373   case LookupResult::NotFoundInCurrentInstantiation:
374     if (CorrectedII) {
375       TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
376                                AllowDeducedTemplate);
377       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
378                                               S, SS, CCC, CTK_ErrorRecovery);
379       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
380       TemplateTy Template;
381       bool MemberOfUnknownSpecialization;
382       UnqualifiedId TemplateName;
383       TemplateName.setIdentifier(NewII, NameLoc);
384       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
385       CXXScopeSpec NewSS, *NewSSPtr = SS;
386       if (SS && NNS) {
387         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
388         NewSSPtr = &NewSS;
389       }
390       if (Correction && (NNS || NewII != &II) &&
391           // Ignore a correction to a template type as the to-be-corrected
392           // identifier is not a template (typo correction for template names
393           // is handled elsewhere).
394           !(getLangOpts().CPlusPlus && NewSSPtr &&
395             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
396                            Template, MemberOfUnknownSpecialization))) {
397         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
398                                     isClassName, HasTrailingDot, ObjectTypePtr,
399                                     IsCtorOrDtorName,
400                                     WantNontrivialTypeSourceInfo,
401                                     IsClassTemplateDeductionContext);
402         if (Ty) {
403           diagnoseTypo(Correction,
404                        PDiag(diag::err_unknown_type_or_class_name_suggest)
405                          << Result.getLookupName() << isClassName);
406           if (SS && NNS)
407             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
408           *CorrectedII = NewII;
409           return Ty;
410         }
411       }
412     }
413     // If typo correction failed or was not performed, fall through
414     LLVM_FALLTHROUGH;
415   case LookupResult::FoundOverloaded:
416   case LookupResult::FoundUnresolvedValue:
417     Result.suppressDiagnostics();
418     return nullptr;
419 
420   case LookupResult::Ambiguous:
421     // Recover from type-hiding ambiguities by hiding the type.  We'll
422     // do the lookup again when looking for an object, and we can
423     // diagnose the error then.  If we don't do this, then the error
424     // about hiding the type will be immediately followed by an error
425     // that only makes sense if the identifier was treated like a type.
426     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
427       Result.suppressDiagnostics();
428       return nullptr;
429     }
430 
431     // Look to see if we have a type anywhere in the list of results.
432     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
433          Res != ResEnd; ++Res) {
434       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
435           (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
436         if (!IIDecl ||
437             (*Res)->getLocation().getRawEncoding() <
438               IIDecl->getLocation().getRawEncoding())
439           IIDecl = *Res;
440       }
441     }
442 
443     if (!IIDecl) {
444       // None of the entities we found is a type, so there is no way
445       // to even assume that the result is a type. In this case, don't
446       // complain about the ambiguity. The parser will either try to
447       // perform this lookup again (e.g., as an object name), which
448       // will produce the ambiguity, or will complain that it expected
449       // a type name.
450       Result.suppressDiagnostics();
451       return nullptr;
452     }
453 
454     // We found a type within the ambiguous lookup; diagnose the
455     // ambiguity and then return that type. This might be the right
456     // answer, or it might not be, but it suppresses any attempt to
457     // perform the name lookup again.
458     break;
459 
460   case LookupResult::Found:
461     IIDecl = Result.getFoundDecl();
462     break;
463   }
464 
465   assert(IIDecl && "Didn't find decl");
466 
467   QualType T;
468   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
469     // C++ [class.qual]p2: A lookup that would find the injected-class-name
470     // instead names the constructors of the class, except when naming a class.
471     // This is ill-formed when we're not actually forming a ctor or dtor name.
472     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
473     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
474     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
475         FoundRD->isInjectedClassName() &&
476         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
477       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
478           << &II << /*Type*/1;
479 
480     DiagnoseUseOfDecl(IIDecl, NameLoc);
481 
482     T = Context.getTypeDeclType(TD);
483     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
484   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
485     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
486     if (!HasTrailingDot)
487       T = Context.getObjCInterfaceType(IDecl);
488   } else if (AllowDeducedTemplate) {
489     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
490       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
491                                                        QualType(), false);
492   }
493 
494   if (T.isNull()) {
495     // If it's not plausibly a type, suppress diagnostics.
496     Result.suppressDiagnostics();
497     return nullptr;
498   }
499 
500   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
501   // constructor or destructor name (in such a case, the scope specifier
502   // will be attached to the enclosing Expr or Decl node).
503   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
504       !isa<ObjCInterfaceDecl>(IIDecl)) {
505     if (WantNontrivialTypeSourceInfo) {
506       // Construct a type with type-source information.
507       TypeLocBuilder Builder;
508       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
509 
510       T = getElaboratedType(ETK_None, *SS, T);
511       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
512       ElabTL.setElaboratedKeywordLoc(SourceLocation());
513       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
514       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
515     } else {
516       T = getElaboratedType(ETK_None, *SS, T);
517     }
518   }
519 
520   return ParsedType::make(T);
521 }
522 
523 // Builds a fake NNS for the given decl context.
524 static NestedNameSpecifier *
525 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
526   for (;; DC = DC->getLookupParent()) {
527     DC = DC->getPrimaryContext();
528     auto *ND = dyn_cast<NamespaceDecl>(DC);
529     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
530       return NestedNameSpecifier::Create(Context, nullptr, ND);
531     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
532       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
533                                          RD->getTypeForDecl());
534     else if (isa<TranslationUnitDecl>(DC))
535       return NestedNameSpecifier::GlobalSpecifier(Context);
536   }
537   llvm_unreachable("something isn't in TU scope?");
538 }
539 
540 /// Find the parent class with dependent bases of the innermost enclosing method
541 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
542 /// up allowing unqualified dependent type names at class-level, which MSVC
543 /// correctly rejects.
544 static const CXXRecordDecl *
545 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
546   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
547     DC = DC->getPrimaryContext();
548     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
549       if (MD->getParent()->hasAnyDependentBases())
550         return MD->getParent();
551   }
552   return nullptr;
553 }
554 
555 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
556                                           SourceLocation NameLoc,
557                                           bool IsTemplateTypeArg) {
558   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
559 
560   NestedNameSpecifier *NNS = nullptr;
561   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
562     // If we weren't able to parse a default template argument, delay lookup
563     // until instantiation time by making a non-dependent DependentTypeName. We
564     // pretend we saw a NestedNameSpecifier referring to the current scope, and
565     // lookup is retried.
566     // FIXME: This hurts our diagnostic quality, since we get errors like "no
567     // type named 'Foo' in 'current_namespace'" when the user didn't write any
568     // name specifiers.
569     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
570     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
571   } else if (const CXXRecordDecl *RD =
572                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
573     // Build a DependentNameType that will perform lookup into RD at
574     // instantiation time.
575     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
576                                       RD->getTypeForDecl());
577 
578     // Diagnose that this identifier was undeclared, and retry the lookup during
579     // template instantiation.
580     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
581                                                                       << RD;
582   } else {
583     // This is not a situation that we should recover from.
584     return ParsedType();
585   }
586 
587   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
588 
589   // Build type location information.  We synthesized the qualifier, so we have
590   // to build a fake NestedNameSpecifierLoc.
591   NestedNameSpecifierLocBuilder NNSLocBuilder;
592   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
593   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
594 
595   TypeLocBuilder Builder;
596   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
597   DepTL.setNameLoc(NameLoc);
598   DepTL.setElaboratedKeywordLoc(SourceLocation());
599   DepTL.setQualifierLoc(QualifierLoc);
600   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
601 }
602 
603 /// isTagName() - This method is called *for error recovery purposes only*
604 /// to determine if the specified name is a valid tag name ("struct foo").  If
605 /// so, this returns the TST for the tag corresponding to it (TST_enum,
606 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
607 /// cases in C where the user forgot to specify the tag.
608 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
609   // Do a tag name lookup in this scope.
610   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
611   LookupName(R, S, false);
612   R.suppressDiagnostics();
613   if (R.getResultKind() == LookupResult::Found)
614     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
615       switch (TD->getTagKind()) {
616       case TTK_Struct: return DeclSpec::TST_struct;
617       case TTK_Interface: return DeclSpec::TST_interface;
618       case TTK_Union:  return DeclSpec::TST_union;
619       case TTK_Class:  return DeclSpec::TST_class;
620       case TTK_Enum:   return DeclSpec::TST_enum;
621       }
622     }
623 
624   return DeclSpec::TST_unspecified;
625 }
626 
627 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
628 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
629 /// then downgrade the missing typename error to a warning.
630 /// This is needed for MSVC compatibility; Example:
631 /// @code
632 /// template<class T> class A {
633 /// public:
634 ///   typedef int TYPE;
635 /// };
636 /// template<class T> class B : public A<T> {
637 /// public:
638 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
639 /// };
640 /// @endcode
641 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
642   if (CurContext->isRecord()) {
643     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
644       return true;
645 
646     const Type *Ty = SS->getScopeRep()->getAsType();
647 
648     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
649     for (const auto &Base : RD->bases())
650       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
651         return true;
652     return S->isFunctionPrototypeScope();
653   }
654   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
655 }
656 
657 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
658                                    SourceLocation IILoc,
659                                    Scope *S,
660                                    CXXScopeSpec *SS,
661                                    ParsedType &SuggestedType,
662                                    bool IsTemplateName) {
663   // Don't report typename errors for editor placeholders.
664   if (II->isEditorPlaceholder())
665     return;
666   // We don't have anything to suggest (yet).
667   SuggestedType = nullptr;
668 
669   // There may have been a typo in the name of the type. Look up typo
670   // results, in case we have something that we can suggest.
671   TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
672                            /*AllowTemplates=*/IsTemplateName,
673                            /*AllowNonTemplates=*/!IsTemplateName);
674   if (TypoCorrection Corrected =
675           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
676                       CCC, CTK_ErrorRecovery)) {
677     // FIXME: Support error recovery for the template-name case.
678     bool CanRecover = !IsTemplateName;
679     if (Corrected.isKeyword()) {
680       // We corrected to a keyword.
681       diagnoseTypo(Corrected,
682                    PDiag(IsTemplateName ? diag::err_no_template_suggest
683                                         : diag::err_unknown_typename_suggest)
684                        << II);
685       II = Corrected.getCorrectionAsIdentifierInfo();
686     } else {
687       // We found a similarly-named type or interface; suggest that.
688       if (!SS || !SS->isSet()) {
689         diagnoseTypo(Corrected,
690                      PDiag(IsTemplateName ? diag::err_no_template_suggest
691                                           : diag::err_unknown_typename_suggest)
692                          << II, CanRecover);
693       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
694         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
695         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
696                                 II->getName().equals(CorrectedStr);
697         diagnoseTypo(Corrected,
698                      PDiag(IsTemplateName
699                                ? diag::err_no_member_template_suggest
700                                : diag::err_unknown_nested_typename_suggest)
701                          << II << DC << DroppedSpecifier << SS->getRange(),
702                      CanRecover);
703       } else {
704         llvm_unreachable("could not have corrected a typo here");
705       }
706 
707       if (!CanRecover)
708         return;
709 
710       CXXScopeSpec tmpSS;
711       if (Corrected.getCorrectionSpecifier())
712         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
713                           SourceRange(IILoc));
714       // FIXME: Support class template argument deduction here.
715       SuggestedType =
716           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
717                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
718                       /*IsCtorOrDtorName=*/false,
719                       /*WantNontrivialTypeSourceInfo=*/true);
720     }
721     return;
722   }
723 
724   if (getLangOpts().CPlusPlus && !IsTemplateName) {
725     // See if II is a class template that the user forgot to pass arguments to.
726     UnqualifiedId Name;
727     Name.setIdentifier(II, IILoc);
728     CXXScopeSpec EmptySS;
729     TemplateTy TemplateResult;
730     bool MemberOfUnknownSpecialization;
731     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
732                        Name, nullptr, true, TemplateResult,
733                        MemberOfUnknownSpecialization) == TNK_Type_template) {
734       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
735       return;
736     }
737   }
738 
739   // FIXME: Should we move the logic that tries to recover from a missing tag
740   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
741 
742   if (!SS || (!SS->isSet() && !SS->isInvalid()))
743     Diag(IILoc, IsTemplateName ? diag::err_no_template
744                                : diag::err_unknown_typename)
745         << II;
746   else if (DeclContext *DC = computeDeclContext(*SS, false))
747     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
748                                : diag::err_typename_nested_not_found)
749         << II << DC << SS->getRange();
750   else if (isDependentScopeSpecifier(*SS)) {
751     unsigned DiagID = diag::err_typename_missing;
752     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
753       DiagID = diag::ext_typename_missing;
754 
755     Diag(SS->getRange().getBegin(), DiagID)
756       << SS->getScopeRep() << II->getName()
757       << SourceRange(SS->getRange().getBegin(), IILoc)
758       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
759     SuggestedType = ActOnTypenameType(S, SourceLocation(),
760                                       *SS, *II, IILoc).get();
761   } else {
762     assert(SS && SS->isInvalid() &&
763            "Invalid scope specifier has already been diagnosed");
764   }
765 }
766 
767 /// Determine whether the given result set contains either a type name
768 /// or
769 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
770   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
771                        NextToken.is(tok::less);
772 
773   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
774     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
775       return true;
776 
777     if (CheckTemplate && isa<TemplateDecl>(*I))
778       return true;
779   }
780 
781   return false;
782 }
783 
784 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
785                                     Scope *S, CXXScopeSpec &SS,
786                                     IdentifierInfo *&Name,
787                                     SourceLocation NameLoc) {
788   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
789   SemaRef.LookupParsedName(R, S, &SS);
790   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
791     StringRef FixItTagName;
792     switch (Tag->getTagKind()) {
793       case TTK_Class:
794         FixItTagName = "class ";
795         break;
796 
797       case TTK_Enum:
798         FixItTagName = "enum ";
799         break;
800 
801       case TTK_Struct:
802         FixItTagName = "struct ";
803         break;
804 
805       case TTK_Interface:
806         FixItTagName = "__interface ";
807         break;
808 
809       case TTK_Union:
810         FixItTagName = "union ";
811         break;
812     }
813 
814     StringRef TagName = FixItTagName.drop_back();
815     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
816       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
817       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
818 
819     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
820          I != IEnd; ++I)
821       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
822         << Name << TagName;
823 
824     // Replace lookup results with just the tag decl.
825     Result.clear(Sema::LookupTagName);
826     SemaRef.LookupParsedName(Result, S, &SS);
827     return true;
828   }
829 
830   return false;
831 }
832 
833 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
834 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
835                                   QualType T, SourceLocation NameLoc) {
836   ASTContext &Context = S.Context;
837 
838   TypeLocBuilder Builder;
839   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
840 
841   T = S.getElaboratedType(ETK_None, SS, T);
842   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
843   ElabTL.setElaboratedKeywordLoc(SourceLocation());
844   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
845   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
846 }
847 
848 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
849                                             IdentifierInfo *&Name,
850                                             SourceLocation NameLoc,
851                                             const Token &NextToken,
852                                             CorrectionCandidateCallback *CCC) {
853   DeclarationNameInfo NameInfo(Name, NameLoc);
854   ObjCMethodDecl *CurMethod = getCurMethodDecl();
855 
856   assert(NextToken.isNot(tok::coloncolon) &&
857          "parse nested name specifiers before calling ClassifyName");
858   if (getLangOpts().CPlusPlus && SS.isSet() &&
859       isCurrentClassName(*Name, S, &SS)) {
860     // Per [class.qual]p2, this names the constructors of SS, not the
861     // injected-class-name. We don't have a classification for that.
862     // There's not much point caching this result, since the parser
863     // will reject it later.
864     return NameClassification::Unknown();
865   }
866 
867   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
868   LookupParsedName(Result, S, &SS, !CurMethod);
869 
870   // 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     DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
884     if (Ivar.isInvalid())
885       return NameClassification::Error();
886     if (Ivar.isUsable())
887       return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
888 
889     // We defer builtin creation until after ivar lookup inside ObjC methods.
890     if (Result.empty())
891       LookupBuiltin(Result);
892   }
893 
894   bool SecondTry = false;
895   bool IsFilteredTemplateName = false;
896 
897 Corrected:
898   switch (Result.getResultKind()) {
899   case LookupResult::NotFound:
900     // If an unqualified-id is followed by a '(', then we have a function
901     // call.
902     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
903       // In C++, this is an ADL-only call.
904       // FIXME: Reference?
905       if (getLangOpts().CPlusPlus)
906         return NameClassification::UndeclaredNonType();
907 
908       // C90 6.3.2.2:
909       //   If the expression that precedes the parenthesized argument list in a
910       //   function call consists solely of an identifier, and if no
911       //   declaration is visible for this identifier, the identifier is
912       //   implicitly declared exactly as if, in the innermost block containing
913       //   the function call, the declaration
914       //
915       //     extern int identifier ();
916       //
917       //   appeared.
918       //
919       // We also allow this in C99 as an extension.
920       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
921         return NameClassification::NonType(D);
922     }
923 
924     if (getLangOpts().CPlusPlus2a && !SS.isSet() && NextToken.is(tok::less)) {
925       // In C++20 onwards, this could be an ADL-only call to a function
926       // template, and we're required to assume that this is a template name.
927       //
928       // FIXME: Find a way to still do typo correction in this case.
929       TemplateName Template =
930           Context.getAssumedTemplateName(NameInfo.getName());
931       return NameClassification::UndeclaredTemplate(Template);
932     }
933 
934     // In C, we first see whether there is a tag type by the same name, in
935     // which case it's likely that the user just forgot to write "enum",
936     // "struct", or "union".
937     if (!getLangOpts().CPlusPlus && !SecondTry &&
938         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
939       break;
940     }
941 
942     // Perform typo correction to determine if there is another name that is
943     // close to this name.
944     if (!SecondTry && CCC) {
945       SecondTry = true;
946       if (TypoCorrection Corrected =
947               CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
948                           &SS, *CCC, CTK_ErrorRecovery)) {
949         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
950         unsigned QualifiedDiag = diag::err_no_member_suggest;
951 
952         NamedDecl *FirstDecl = Corrected.getFoundDecl();
953         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
954         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
955             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
956           UnqualifiedDiag = diag::err_no_template_suggest;
957           QualifiedDiag = diag::err_no_member_template_suggest;
958         } else if (UnderlyingFirstDecl &&
959                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
960                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
961                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
962           UnqualifiedDiag = diag::err_unknown_typename_suggest;
963           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
964         }
965 
966         if (SS.isEmpty()) {
967           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
968         } else {// FIXME: is this even reachable? Test it.
969           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
970           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
971                                   Name->getName().equals(CorrectedStr);
972           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
973                                     << Name << computeDeclContext(SS, false)
974                                     << DroppedSpecifier << SS.getRange());
975         }
976 
977         // Update the name, so that the caller has the new name.
978         Name = Corrected.getCorrectionAsIdentifierInfo();
979 
980         // Typo correction corrected to a keyword.
981         if (Corrected.isKeyword())
982           return Name;
983 
984         // Also update the LookupResult...
985         // FIXME: This should probably go away at some point
986         Result.clear();
987         Result.setLookupName(Corrected.getCorrection());
988         if (FirstDecl)
989           Result.addDecl(FirstDecl);
990 
991         // If we found an Objective-C instance variable, let
992         // LookupInObjCMethod build the appropriate expression to
993         // reference the ivar.
994         // FIXME: This is a gross hack.
995         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
996           DeclResult R =
997               LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
998           if (R.isInvalid())
999             return NameClassification::Error();
1000           if (R.isUsable())
1001             return NameClassification::NonType(Ivar);
1002         }
1003 
1004         goto Corrected;
1005       }
1006     }
1007 
1008     // We failed to correct; just fall through and let the parser deal with it.
1009     Result.suppressDiagnostics();
1010     return NameClassification::Unknown();
1011 
1012   case LookupResult::NotFoundInCurrentInstantiation: {
1013     // We performed name lookup into the current instantiation, and there were
1014     // dependent bases, so we treat this result the same way as any other
1015     // dependent nested-name-specifier.
1016 
1017     // C++ [temp.res]p2:
1018     //   A name used in a template declaration or definition and that is
1019     //   dependent on a template-parameter is assumed not to name a type
1020     //   unless the applicable name lookup finds a type name or the name is
1021     //   qualified by the keyword typename.
1022     //
1023     // FIXME: If the next token is '<', we might want to ask the parser to
1024     // perform some heroics to see if we actually have a
1025     // template-argument-list, which would indicate a missing 'template'
1026     // keyword here.
1027     return NameClassification::DependentNonType();
1028   }
1029 
1030   case LookupResult::Found:
1031   case LookupResult::FoundOverloaded:
1032   case LookupResult::FoundUnresolvedValue:
1033     break;
1034 
1035   case LookupResult::Ambiguous:
1036     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1037         hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1038                                       /*AllowDependent=*/false)) {
1039       // C++ [temp.local]p3:
1040       //   A lookup that finds an injected-class-name (10.2) can result in an
1041       //   ambiguity in certain cases (for example, if it is found in more than
1042       //   one base class). If all of the injected-class-names that are found
1043       //   refer to specializations of the same class template, and if the name
1044       //   is followed by a template-argument-list, the reference refers to the
1045       //   class template itself and not a specialization thereof, and is not
1046       //   ambiguous.
1047       //
1048       // This filtering can make an ambiguous result into an unambiguous one,
1049       // so try again after filtering out template names.
1050       FilterAcceptableTemplateNames(Result);
1051       if (!Result.isAmbiguous()) {
1052         IsFilteredTemplateName = true;
1053         break;
1054       }
1055     }
1056 
1057     // Diagnose the ambiguity and return an error.
1058     return NameClassification::Error();
1059   }
1060 
1061   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1062       (IsFilteredTemplateName ||
1063        hasAnyAcceptableTemplateNames(
1064            Result, /*AllowFunctionTemplates=*/true,
1065            /*AllowDependent=*/false,
1066            /*AllowNonTemplateFunctions*/ !SS.isSet() &&
1067                getLangOpts().CPlusPlus2a))) {
1068     // C++ [temp.names]p3:
1069     //   After name lookup (3.4) finds that a name is a template-name or that
1070     //   an operator-function-id or a literal- operator-id refers to a set of
1071     //   overloaded functions any member of which is a function template if
1072     //   this is followed by a <, the < is always taken as the delimiter of a
1073     //   template-argument-list and never as the less-than operator.
1074     // C++2a [temp.names]p2:
1075     //   A name is also considered to refer to a template if it is an
1076     //   unqualified-id followed by a < and name lookup finds either one
1077     //   or more functions or finds nothing.
1078     if (!IsFilteredTemplateName)
1079       FilterAcceptableTemplateNames(Result);
1080 
1081     bool IsFunctionTemplate;
1082     bool IsVarTemplate;
1083     TemplateName Template;
1084     if (Result.end() - Result.begin() > 1) {
1085       IsFunctionTemplate = true;
1086       Template = Context.getOverloadedTemplateName(Result.begin(),
1087                                                    Result.end());
1088     } else if (!Result.empty()) {
1089       auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1090           *Result.begin(), /*AllowFunctionTemplates=*/true,
1091           /*AllowDependent=*/false));
1092       IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1093       IsVarTemplate = isa<VarTemplateDecl>(TD);
1094 
1095       if (SS.isSet() && !SS.isInvalid())
1096         Template =
1097             Context.getQualifiedTemplateName(SS.getScopeRep(),
1098                                              /*TemplateKeyword=*/false, TD);
1099       else
1100         Template = TemplateName(TD);
1101     } else {
1102       // All results were non-template functions. This is a function template
1103       // name.
1104       IsFunctionTemplate = true;
1105       Template = Context.getAssumedTemplateName(NameInfo.getName());
1106     }
1107 
1108     if (IsFunctionTemplate) {
1109       // Function templates always go through overload resolution, at which
1110       // point we'll perform the various checks (e.g., accessibility) we need
1111       // to based on which function we selected.
1112       Result.suppressDiagnostics();
1113 
1114       return NameClassification::FunctionTemplate(Template);
1115     }
1116 
1117     return IsVarTemplate ? NameClassification::VarTemplate(Template)
1118                          : NameClassification::TypeTemplate(Template);
1119   }
1120 
1121   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1122   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1123     DiagnoseUseOfDecl(Type, NameLoc);
1124     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1125     QualType T = Context.getTypeDeclType(Type);
1126     if (SS.isNotEmpty())
1127       return buildNestedType(*this, SS, T, NameLoc);
1128     return ParsedType::make(T);
1129   }
1130 
1131   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1132   if (!Class) {
1133     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1134     if (ObjCCompatibleAliasDecl *Alias =
1135             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1136       Class = Alias->getClassInterface();
1137   }
1138 
1139   if (Class) {
1140     DiagnoseUseOfDecl(Class, NameLoc);
1141 
1142     if (NextToken.is(tok::period)) {
1143       // Interface. <something> is parsed as a property reference expression.
1144       // Just return "unknown" as a fall-through for now.
1145       Result.suppressDiagnostics();
1146       return NameClassification::Unknown();
1147     }
1148 
1149     QualType T = Context.getObjCInterfaceType(Class);
1150     return ParsedType::make(T);
1151   }
1152 
1153   // We can have a type template here if we're classifying a template argument.
1154   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1155       !isa<VarTemplateDecl>(FirstDecl))
1156     return NameClassification::TypeTemplate(
1157         TemplateName(cast<TemplateDecl>(FirstDecl)));
1158 
1159   // Check for a tag type hidden by a non-type decl in a few cases where it
1160   // seems likely a type is wanted instead of the non-type that was found.
1161   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1162   if ((NextToken.is(tok::identifier) ||
1163        (NextIsOp &&
1164         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1165       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1166     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1167     DiagnoseUseOfDecl(Type, NameLoc);
1168     QualType T = Context.getTypeDeclType(Type);
1169     if (SS.isNotEmpty())
1170       return buildNestedType(*this, SS, T, NameLoc);
1171     return ParsedType::make(T);
1172   }
1173 
1174   // FIXME: This is context-dependent. We need to defer building the member
1175   // expression until the classification is consumed.
1176   if (FirstDecl->isCXXClassMember())
1177     return NameClassification::ContextIndependentExpr(
1178         BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, nullptr,
1179                                         S));
1180 
1181   // If we already know which single declaration is referenced, just annotate
1182   // that declaration directly.
1183   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1184   if (Result.isSingleResult() && !ADL)
1185     return NameClassification::NonType(Result.getRepresentativeDecl());
1186 
1187   // Build an UnresolvedLookupExpr. Note that this doesn't depend on the
1188   // context in which we performed classification, so it's safe to do now.
1189   return NameClassification::ContextIndependentExpr(
1190       BuildDeclarationNameExpr(SS, Result, ADL));
1191 }
1192 
1193 ExprResult
1194 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1195                                              SourceLocation NameLoc) {
1196   assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1197   CXXScopeSpec SS;
1198   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1199   return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1200 }
1201 
1202 ExprResult
1203 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1204                                             IdentifierInfo *Name,
1205                                             SourceLocation NameLoc,
1206                                             bool IsAddressOfOperand) {
1207   DeclarationNameInfo NameInfo(Name, NameLoc);
1208   return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1209                                     NameInfo, IsAddressOfOperand,
1210                                     /*TemplateArgs=*/nullptr);
1211 }
1212 
1213 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1214                                               NamedDecl *Found,
1215                                               SourceLocation NameLoc,
1216                                               const Token &NextToken) {
1217   if (getCurMethodDecl() && SS.isEmpty())
1218     if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1219       return BuildIvarRefExpr(S, NameLoc, Ivar);
1220 
1221   // Reconstruct the lookup result.
1222   LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1223   Result.addDecl(Found);
1224   Result.resolveKind();
1225 
1226   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1227   return BuildDeclarationNameExpr(SS, Result, ADL);
1228 }
1229 
1230 Sema::TemplateNameKindForDiagnostics
1231 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1232   auto *TD = Name.getAsTemplateDecl();
1233   if (!TD)
1234     return TemplateNameKindForDiagnostics::DependentTemplate;
1235   if (isa<ClassTemplateDecl>(TD))
1236     return TemplateNameKindForDiagnostics::ClassTemplate;
1237   if (isa<FunctionTemplateDecl>(TD))
1238     return TemplateNameKindForDiagnostics::FunctionTemplate;
1239   if (isa<VarTemplateDecl>(TD))
1240     return TemplateNameKindForDiagnostics::VarTemplate;
1241   if (isa<TypeAliasTemplateDecl>(TD))
1242     return TemplateNameKindForDiagnostics::AliasTemplate;
1243   if (isa<TemplateTemplateParmDecl>(TD))
1244     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1245   if (isa<ConceptDecl>(TD))
1246     return TemplateNameKindForDiagnostics::Concept;
1247   return TemplateNameKindForDiagnostics::DependentTemplate;
1248 }
1249 
1250 // Determines the context to return to after temporarily entering a
1251 // context.  This depends in an unnecessarily complicated way on the
1252 // exact ordering of callbacks from the parser.
1253 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1254 
1255   // Functions defined inline within classes aren't parsed until we've
1256   // finished parsing the top-level class, so the top-level class is
1257   // the context we'll need to return to.
1258   // A Lambda call operator whose parent is a class must not be treated
1259   // as an inline member function.  A Lambda can be used legally
1260   // either as an in-class member initializer or a default argument.  These
1261   // are parsed once the class has been marked complete and so the containing
1262   // context would be the nested class (when the lambda is defined in one);
1263   // If the class is not complete, then the lambda is being used in an
1264   // ill-formed fashion (such as to specify the width of a bit-field, or
1265   // in an array-bound) - in which case we still want to return the
1266   // lexically containing DC (which could be a nested class).
1267   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1268     DC = DC->getLexicalParent();
1269 
1270     // A function not defined within a class will always return to its
1271     // lexical context.
1272     if (!isa<CXXRecordDecl>(DC))
1273       return DC;
1274 
1275     // A C++ inline method/friend is parsed *after* the topmost class
1276     // it was declared in is fully parsed ("complete");  the topmost
1277     // class is the context we need to return to.
1278     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1279       DC = RD;
1280 
1281     // Return the declaration context of the topmost class the inline method is
1282     // declared in.
1283     return DC;
1284   }
1285 
1286   return DC->getLexicalParent();
1287 }
1288 
1289 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1290   assert(getContainingDC(DC) == CurContext &&
1291       "The next DeclContext should be lexically contained in the current one.");
1292   CurContext = DC;
1293   S->setEntity(DC);
1294 }
1295 
1296 void Sema::PopDeclContext() {
1297   assert(CurContext && "DeclContext imbalance!");
1298 
1299   CurContext = getContainingDC(CurContext);
1300   assert(CurContext && "Popped translation unit!");
1301 }
1302 
1303 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1304                                                                     Decl *D) {
1305   // Unlike PushDeclContext, the context to which we return is not necessarily
1306   // the containing DC of TD, because the new context will be some pre-existing
1307   // TagDecl definition instead of a fresh one.
1308   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1309   CurContext = cast<TagDecl>(D)->getDefinition();
1310   assert(CurContext && "skipping definition of undefined tag");
1311   // Start lookups from the parent of the current context; we don't want to look
1312   // into the pre-existing complete definition.
1313   S->setEntity(CurContext->getLookupParent());
1314   return Result;
1315 }
1316 
1317 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1318   CurContext = static_cast<decltype(CurContext)>(Context);
1319 }
1320 
1321 /// EnterDeclaratorContext - Used when we must lookup names in the context
1322 /// of a declarator's nested name specifier.
1323 ///
1324 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1325   // C++0x [basic.lookup.unqual]p13:
1326   //   A name used in the definition of a static data member of class
1327   //   X (after the qualified-id of the static member) is looked up as
1328   //   if the name was used in a member function of X.
1329   // C++0x [basic.lookup.unqual]p14:
1330   //   If a variable member of a namespace is defined outside of the
1331   //   scope of its namespace then any name used in the definition of
1332   //   the variable member (after the declarator-id) is looked up as
1333   //   if the definition of the variable member occurred in its
1334   //   namespace.
1335   // Both of these imply that we should push a scope whose context
1336   // is the semantic context of the declaration.  We can't use
1337   // PushDeclContext here because that context is not necessarily
1338   // lexically contained in the current context.  Fortunately,
1339   // the containing scope should have the appropriate information.
1340 
1341   assert(!S->getEntity() && "scope already has entity");
1342 
1343 #ifndef NDEBUG
1344   Scope *Ancestor = S->getParent();
1345   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1346   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1347 #endif
1348 
1349   CurContext = DC;
1350   S->setEntity(DC);
1351 }
1352 
1353 void Sema::ExitDeclaratorContext(Scope *S) {
1354   assert(S->getEntity() == CurContext && "Context imbalance!");
1355 
1356   // Switch back to the lexical context.  The safety of this is
1357   // enforced by an assert in EnterDeclaratorContext.
1358   Scope *Ancestor = S->getParent();
1359   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1360   CurContext = Ancestor->getEntity();
1361 
1362   // We don't need to do anything with the scope, which is going to
1363   // disappear.
1364 }
1365 
1366 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1367   // We assume that the caller has already called
1368   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1369   FunctionDecl *FD = D->getAsFunction();
1370   if (!FD)
1371     return;
1372 
1373   // Same implementation as PushDeclContext, but enters the context
1374   // from the lexical parent, rather than the top-level class.
1375   assert(CurContext == FD->getLexicalParent() &&
1376     "The next DeclContext should be lexically contained in the current one.");
1377   CurContext = FD;
1378   S->setEntity(CurContext);
1379 
1380   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1381     ParmVarDecl *Param = FD->getParamDecl(P);
1382     // If the parameter has an identifier, then add it to the scope
1383     if (Param->getIdentifier()) {
1384       S->AddDecl(Param);
1385       IdResolver.AddDecl(Param);
1386     }
1387   }
1388 }
1389 
1390 void Sema::ActOnExitFunctionContext() {
1391   // Same implementation as PopDeclContext, but returns to the lexical parent,
1392   // rather than the top-level class.
1393   assert(CurContext && "DeclContext imbalance!");
1394   CurContext = CurContext->getLexicalParent();
1395   assert(CurContext && "Popped translation unit!");
1396 }
1397 
1398 /// Determine whether we allow overloading of the function
1399 /// PrevDecl with another declaration.
1400 ///
1401 /// This routine determines whether overloading is possible, not
1402 /// whether some new function is actually an overload. It will return
1403 /// true in C++ (where we can always provide overloads) or, as an
1404 /// extension, in C when the previous function is already an
1405 /// overloaded function declaration or has the "overloadable"
1406 /// attribute.
1407 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1408                                        ASTContext &Context,
1409                                        const FunctionDecl *New) {
1410   if (Context.getLangOpts().CPlusPlus)
1411     return true;
1412 
1413   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1414     return true;
1415 
1416   return Previous.getResultKind() == LookupResult::Found &&
1417          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1418           New->hasAttr<OverloadableAttr>());
1419 }
1420 
1421 /// Add this decl to the scope shadowed decl chains.
1422 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1423   // Move up the scope chain until we find the nearest enclosing
1424   // non-transparent context. The declaration will be introduced into this
1425   // scope.
1426   while (S->getEntity() && S->getEntity()->isTransparentContext())
1427     S = S->getParent();
1428 
1429   // Add scoped declarations into their context, so that they can be
1430   // found later. Declarations without a context won't be inserted
1431   // into any context.
1432   if (AddToContext)
1433     CurContext->addDecl(D);
1434 
1435   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1436   // are function-local declarations.
1437   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1438       !D->getDeclContext()->getRedeclContext()->Equals(
1439         D->getLexicalDeclContext()->getRedeclContext()) &&
1440       !D->getLexicalDeclContext()->isFunctionOrMethod())
1441     return;
1442 
1443   // Template instantiations should also not be pushed into scope.
1444   if (isa<FunctionDecl>(D) &&
1445       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1446     return;
1447 
1448   // If this replaces anything in the current scope,
1449   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1450                                IEnd = IdResolver.end();
1451   for (; I != IEnd; ++I) {
1452     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1453       S->RemoveDecl(*I);
1454       IdResolver.RemoveDecl(*I);
1455 
1456       // Should only need to replace one decl.
1457       break;
1458     }
1459   }
1460 
1461   S->AddDecl(D);
1462 
1463   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1464     // Implicitly-generated labels may end up getting generated in an order that
1465     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1466     // the label at the appropriate place in the identifier chain.
1467     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1468       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1469       if (IDC == CurContext) {
1470         if (!S->isDeclScope(*I))
1471           continue;
1472       } else if (IDC->Encloses(CurContext))
1473         break;
1474     }
1475 
1476     IdResolver.InsertDeclAfter(I, D);
1477   } else {
1478     IdResolver.AddDecl(D);
1479   }
1480 }
1481 
1482 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1483                          bool AllowInlineNamespace) {
1484   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1485 }
1486 
1487 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1488   DeclContext *TargetDC = DC->getPrimaryContext();
1489   do {
1490     if (DeclContext *ScopeDC = S->getEntity())
1491       if (ScopeDC->getPrimaryContext() == TargetDC)
1492         return S;
1493   } while ((S = S->getParent()));
1494 
1495   return nullptr;
1496 }
1497 
1498 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1499                                             DeclContext*,
1500                                             ASTContext&);
1501 
1502 /// Filters out lookup results that don't fall within the given scope
1503 /// as determined by isDeclInScope.
1504 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1505                                 bool ConsiderLinkage,
1506                                 bool AllowInlineNamespace) {
1507   LookupResult::Filter F = R.makeFilter();
1508   while (F.hasNext()) {
1509     NamedDecl *D = F.next();
1510 
1511     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1512       continue;
1513 
1514     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1515       continue;
1516 
1517     F.erase();
1518   }
1519 
1520   F.done();
1521 }
1522 
1523 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1524 /// have compatible owning modules.
1525 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1526   // FIXME: The Modules TS is not clear about how friend declarations are
1527   // to be treated. It's not meaningful to have different owning modules for
1528   // linkage in redeclarations of the same entity, so for now allow the
1529   // redeclaration and change the owning modules to match.
1530   if (New->getFriendObjectKind() &&
1531       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1532     New->setLocalOwningModule(Old->getOwningModule());
1533     makeMergedDefinitionVisible(New);
1534     return false;
1535   }
1536 
1537   Module *NewM = New->getOwningModule();
1538   Module *OldM = Old->getOwningModule();
1539 
1540   if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1541     NewM = NewM->Parent;
1542   if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1543     OldM = OldM->Parent;
1544 
1545   if (NewM == OldM)
1546     return false;
1547 
1548   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1549   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1550   if (NewIsModuleInterface || OldIsModuleInterface) {
1551     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1552     //   if a declaration of D [...] appears in the purview of a module, all
1553     //   other such declarations shall appear in the purview of the same module
1554     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1555       << New
1556       << NewIsModuleInterface
1557       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1558       << OldIsModuleInterface
1559       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1560     Diag(Old->getLocation(), diag::note_previous_declaration);
1561     New->setInvalidDecl();
1562     return true;
1563   }
1564 
1565   return false;
1566 }
1567 
1568 static bool isUsingDecl(NamedDecl *D) {
1569   return isa<UsingShadowDecl>(D) ||
1570          isa<UnresolvedUsingTypenameDecl>(D) ||
1571          isa<UnresolvedUsingValueDecl>(D);
1572 }
1573 
1574 /// Removes using shadow declarations from the lookup results.
1575 static void RemoveUsingDecls(LookupResult &R) {
1576   LookupResult::Filter F = R.makeFilter();
1577   while (F.hasNext())
1578     if (isUsingDecl(F.next()))
1579       F.erase();
1580 
1581   F.done();
1582 }
1583 
1584 /// Check for this common pattern:
1585 /// @code
1586 /// class S {
1587 ///   S(const S&); // DO NOT IMPLEMENT
1588 ///   void operator=(const S&); // DO NOT IMPLEMENT
1589 /// };
1590 /// @endcode
1591 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1592   // FIXME: Should check for private access too but access is set after we get
1593   // the decl here.
1594   if (D->doesThisDeclarationHaveABody())
1595     return false;
1596 
1597   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1598     return CD->isCopyConstructor();
1599   return D->isCopyAssignmentOperator();
1600 }
1601 
1602 // We need this to handle
1603 //
1604 // typedef struct {
1605 //   void *foo() { return 0; }
1606 // } A;
1607 //
1608 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1609 // for example. If 'A', foo will have external linkage. If we have '*A',
1610 // foo will have no linkage. Since we can't know until we get to the end
1611 // of the typedef, this function finds out if D might have non-external linkage.
1612 // Callers should verify at the end of the TU if it D has external linkage or
1613 // not.
1614 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1615   const DeclContext *DC = D->getDeclContext();
1616   while (!DC->isTranslationUnit()) {
1617     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1618       if (!RD->hasNameForLinkage())
1619         return true;
1620     }
1621     DC = DC->getParent();
1622   }
1623 
1624   return !D->isExternallyVisible();
1625 }
1626 
1627 // FIXME: This needs to be refactored; some other isInMainFile users want
1628 // these semantics.
1629 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1630   if (S.TUKind != TU_Complete)
1631     return false;
1632   return S.SourceMgr.isInMainFile(Loc);
1633 }
1634 
1635 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1636   assert(D);
1637 
1638   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1639     return false;
1640 
1641   // Ignore all entities declared within templates, and out-of-line definitions
1642   // of members of class templates.
1643   if (D->getDeclContext()->isDependentContext() ||
1644       D->getLexicalDeclContext()->isDependentContext())
1645     return false;
1646 
1647   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1648     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1649       return false;
1650     // A non-out-of-line declaration of a member specialization was implicitly
1651     // instantiated; it's the out-of-line declaration that we're interested in.
1652     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1653         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1654       return false;
1655 
1656     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1657       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1658         return false;
1659     } else {
1660       // 'static inline' functions are defined in headers; don't warn.
1661       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1662         return false;
1663     }
1664 
1665     if (FD->doesThisDeclarationHaveABody() &&
1666         Context.DeclMustBeEmitted(FD))
1667       return false;
1668   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1669     // Constants and utility variables are defined in headers with internal
1670     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1671     // like "inline".)
1672     if (!isMainFileLoc(*this, VD->getLocation()))
1673       return false;
1674 
1675     if (Context.DeclMustBeEmitted(VD))
1676       return false;
1677 
1678     if (VD->isStaticDataMember() &&
1679         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1680       return false;
1681     if (VD->isStaticDataMember() &&
1682         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1683         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1684       return false;
1685 
1686     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1687       return false;
1688   } else {
1689     return false;
1690   }
1691 
1692   // Only warn for unused decls internal to the translation unit.
1693   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1694   // for inline functions defined in the main source file, for instance.
1695   return mightHaveNonExternalLinkage(D);
1696 }
1697 
1698 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1699   if (!D)
1700     return;
1701 
1702   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1703     const FunctionDecl *First = FD->getFirstDecl();
1704     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1705       return; // First should already be in the vector.
1706   }
1707 
1708   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1709     const VarDecl *First = VD->getFirstDecl();
1710     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1711       return; // First should already be in the vector.
1712   }
1713 
1714   if (ShouldWarnIfUnusedFileScopedDecl(D))
1715     UnusedFileScopedDecls.push_back(D);
1716 }
1717 
1718 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1719   if (D->isInvalidDecl())
1720     return false;
1721 
1722   bool Referenced = false;
1723   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1724     // For a decomposition declaration, warn if none of the bindings are
1725     // referenced, instead of if the variable itself is referenced (which
1726     // it is, by the bindings' expressions).
1727     for (auto *BD : DD->bindings()) {
1728       if (BD->isReferenced()) {
1729         Referenced = true;
1730         break;
1731       }
1732     }
1733   } else if (!D->getDeclName()) {
1734     return false;
1735   } else if (D->isReferenced() || D->isUsed()) {
1736     Referenced = true;
1737   }
1738 
1739   if (Referenced || D->hasAttr<UnusedAttr>() ||
1740       D->hasAttr<ObjCPreciseLifetimeAttr>())
1741     return false;
1742 
1743   if (isa<LabelDecl>(D))
1744     return true;
1745 
1746   // Except for labels, we only care about unused decls that are local to
1747   // functions.
1748   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1749   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1750     // For dependent types, the diagnostic is deferred.
1751     WithinFunction =
1752         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1753   if (!WithinFunction)
1754     return false;
1755 
1756   if (isa<TypedefNameDecl>(D))
1757     return true;
1758 
1759   // White-list anything that isn't a local variable.
1760   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1761     return false;
1762 
1763   // Types of valid local variables should be complete, so this should succeed.
1764   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1765 
1766     // White-list anything with an __attribute__((unused)) type.
1767     const auto *Ty = VD->getType().getTypePtr();
1768 
1769     // Only look at the outermost level of typedef.
1770     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1771       if (TT->getDecl()->hasAttr<UnusedAttr>())
1772         return false;
1773     }
1774 
1775     // If we failed to complete the type for some reason, or if the type is
1776     // dependent, don't diagnose the variable.
1777     if (Ty->isIncompleteType() || Ty->isDependentType())
1778       return false;
1779 
1780     // Look at the element type to ensure that the warning behaviour is
1781     // consistent for both scalars and arrays.
1782     Ty = Ty->getBaseElementTypeUnsafe();
1783 
1784     if (const TagType *TT = Ty->getAs<TagType>()) {
1785       const TagDecl *Tag = TT->getDecl();
1786       if (Tag->hasAttr<UnusedAttr>())
1787         return false;
1788 
1789       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1790         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1791           return false;
1792 
1793         if (const Expr *Init = VD->getInit()) {
1794           if (const ExprWithCleanups *Cleanups =
1795                   dyn_cast<ExprWithCleanups>(Init))
1796             Init = Cleanups->getSubExpr();
1797           const CXXConstructExpr *Construct =
1798             dyn_cast<CXXConstructExpr>(Init);
1799           if (Construct && !Construct->isElidable()) {
1800             CXXConstructorDecl *CD = Construct->getConstructor();
1801             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1802                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1803               return false;
1804           }
1805         }
1806       }
1807     }
1808 
1809     // TODO: __attribute__((unused)) templates?
1810   }
1811 
1812   return true;
1813 }
1814 
1815 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1816                                      FixItHint &Hint) {
1817   if (isa<LabelDecl>(D)) {
1818     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1819         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1820         true);
1821     if (AfterColon.isInvalid())
1822       return;
1823     Hint = FixItHint::CreateRemoval(
1824         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1825   }
1826 }
1827 
1828 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1829   if (D->getTypeForDecl()->isDependentType())
1830     return;
1831 
1832   for (auto *TmpD : D->decls()) {
1833     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1834       DiagnoseUnusedDecl(T);
1835     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1836       DiagnoseUnusedNestedTypedefs(R);
1837   }
1838 }
1839 
1840 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1841 /// unless they are marked attr(unused).
1842 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1843   if (!ShouldDiagnoseUnusedDecl(D))
1844     return;
1845 
1846   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1847     // typedefs can be referenced later on, so the diagnostics are emitted
1848     // at end-of-translation-unit.
1849     UnusedLocalTypedefNameCandidates.insert(TD);
1850     return;
1851   }
1852 
1853   FixItHint Hint;
1854   GenerateFixForUnusedDecl(D, Context, Hint);
1855 
1856   unsigned DiagID;
1857   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1858     DiagID = diag::warn_unused_exception_param;
1859   else if (isa<LabelDecl>(D))
1860     DiagID = diag::warn_unused_label;
1861   else
1862     DiagID = diag::warn_unused_variable;
1863 
1864   Diag(D->getLocation(), DiagID) << D << Hint;
1865 }
1866 
1867 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1868   // Verify that we have no forward references left.  If so, there was a goto
1869   // or address of a label taken, but no definition of it.  Label fwd
1870   // definitions are indicated with a null substmt which is also not a resolved
1871   // MS inline assembly label name.
1872   bool Diagnose = false;
1873   if (L->isMSAsmLabel())
1874     Diagnose = !L->isResolvedMSAsmLabel();
1875   else
1876     Diagnose = L->getStmt() == nullptr;
1877   if (Diagnose)
1878     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1879 }
1880 
1881 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1882   S->mergeNRVOIntoParent();
1883 
1884   if (S->decl_empty()) return;
1885   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1886          "Scope shouldn't contain decls!");
1887 
1888   for (auto *TmpD : S->decls()) {
1889     assert(TmpD && "This decl didn't get pushed??");
1890 
1891     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1892     NamedDecl *D = cast<NamedDecl>(TmpD);
1893 
1894     // Diagnose unused variables in this scope.
1895     if (!S->hasUnrecoverableErrorOccurred()) {
1896       DiagnoseUnusedDecl(D);
1897       if (const auto *RD = dyn_cast<RecordDecl>(D))
1898         DiagnoseUnusedNestedTypedefs(RD);
1899     }
1900 
1901     if (!D->getDeclName()) continue;
1902 
1903     // If this was a forward reference to a label, verify it was defined.
1904     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1905       CheckPoppedLabel(LD, *this);
1906 
1907     // Remove this name from our lexical scope, and warn on it if we haven't
1908     // already.
1909     IdResolver.RemoveDecl(D);
1910     auto ShadowI = ShadowingDecls.find(D);
1911     if (ShadowI != ShadowingDecls.end()) {
1912       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1913         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1914             << D << FD << FD->getParent();
1915         Diag(FD->getLocation(), diag::note_previous_declaration);
1916       }
1917       ShadowingDecls.erase(ShadowI);
1918     }
1919   }
1920 }
1921 
1922 /// Look for an Objective-C class in the translation unit.
1923 ///
1924 /// \param Id The name of the Objective-C class we're looking for. If
1925 /// typo-correction fixes this name, the Id will be updated
1926 /// to the fixed name.
1927 ///
1928 /// \param IdLoc The location of the name in the translation unit.
1929 ///
1930 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1931 /// if there is no class with the given name.
1932 ///
1933 /// \returns The declaration of the named Objective-C class, or NULL if the
1934 /// class could not be found.
1935 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1936                                               SourceLocation IdLoc,
1937                                               bool DoTypoCorrection) {
1938   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1939   // creation from this context.
1940   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1941 
1942   if (!IDecl && DoTypoCorrection) {
1943     // Perform typo correction at the given location, but only if we
1944     // find an Objective-C class name.
1945     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
1946     if (TypoCorrection C =
1947             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
1948                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
1949       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1950       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1951       Id = IDecl->getIdentifier();
1952     }
1953   }
1954   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1955   // This routine must always return a class definition, if any.
1956   if (Def && Def->getDefinition())
1957       Def = Def->getDefinition();
1958   return Def;
1959 }
1960 
1961 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1962 /// from S, where a non-field would be declared. This routine copes
1963 /// with the difference between C and C++ scoping rules in structs and
1964 /// unions. For example, the following code is well-formed in C but
1965 /// ill-formed in C++:
1966 /// @code
1967 /// struct S6 {
1968 ///   enum { BAR } e;
1969 /// };
1970 ///
1971 /// void test_S6() {
1972 ///   struct S6 a;
1973 ///   a.e = BAR;
1974 /// }
1975 /// @endcode
1976 /// For the declaration of BAR, this routine will return a different
1977 /// scope. The scope S will be the scope of the unnamed enumeration
1978 /// within S6. In C++, this routine will return the scope associated
1979 /// with S6, because the enumeration's scope is a transparent
1980 /// context but structures can contain non-field names. In C, this
1981 /// routine will return the translation unit scope, since the
1982 /// enumeration's scope is a transparent context and structures cannot
1983 /// contain non-field names.
1984 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1985   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1986          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1987          (S->isClassScope() && !getLangOpts().CPlusPlus))
1988     S = S->getParent();
1989   return S;
1990 }
1991 
1992 /// Looks up the declaration of "struct objc_super" and
1993 /// saves it for later use in building builtin declaration of
1994 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1995 /// pre-existing declaration exists no action takes place.
1996 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1997                                         IdentifierInfo *II) {
1998   if (!II->isStr("objc_msgSendSuper"))
1999     return;
2000   ASTContext &Context = ThisSema.Context;
2001 
2002   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
2003                       SourceLocation(), Sema::LookupTagName);
2004   ThisSema.LookupName(Result, S);
2005   if (Result.getResultKind() == LookupResult::Found)
2006     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
2007       Context.setObjCSuperType(Context.getTagDeclType(TD));
2008 }
2009 
2010 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2011                                ASTContext::GetBuiltinTypeError Error) {
2012   switch (Error) {
2013   case ASTContext::GE_None:
2014     return "";
2015   case ASTContext::GE_Missing_type:
2016     return BuiltinInfo.getHeaderName(ID);
2017   case ASTContext::GE_Missing_stdio:
2018     return "stdio.h";
2019   case ASTContext::GE_Missing_setjmp:
2020     return "setjmp.h";
2021   case ASTContext::GE_Missing_ucontext:
2022     return "ucontext.h";
2023   }
2024   llvm_unreachable("unhandled error kind");
2025 }
2026 
2027 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2028 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2029 /// if we're creating this built-in in anticipation of redeclaring the
2030 /// built-in.
2031 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2032                                      Scope *S, bool ForRedeclaration,
2033                                      SourceLocation Loc) {
2034   LookupPredefedObjCSuperType(*this, S, II);
2035 
2036   ASTContext::GetBuiltinTypeError Error;
2037   QualType R = Context.GetBuiltinType(ID, Error);
2038   if (Error) {
2039     if (!ForRedeclaration)
2040       return nullptr;
2041 
2042     // If we have a builtin without an associated type we should not emit a
2043     // warning when we were not able to find a type for it.
2044     if (Error == ASTContext::GE_Missing_type)
2045       return nullptr;
2046 
2047     // If we could not find a type for setjmp it is because the jmp_buf type was
2048     // not defined prior to the setjmp declaration.
2049     if (Error == ASTContext::GE_Missing_setjmp) {
2050       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2051           << Context.BuiltinInfo.getName(ID);
2052       return nullptr;
2053     }
2054 
2055     // Generally, we emit a warning that the declaration requires the
2056     // appropriate header.
2057     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2058         << getHeaderName(Context.BuiltinInfo, ID, Error)
2059         << Context.BuiltinInfo.getName(ID);
2060     return nullptr;
2061   }
2062 
2063   if (!ForRedeclaration &&
2064       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2065        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2066     Diag(Loc, diag::ext_implicit_lib_function_decl)
2067         << Context.BuiltinInfo.getName(ID) << R;
2068     if (Context.BuiltinInfo.getHeaderName(ID) &&
2069         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
2070       Diag(Loc, diag::note_include_header_or_declare)
2071           << Context.BuiltinInfo.getHeaderName(ID)
2072           << Context.BuiltinInfo.getName(ID);
2073   }
2074 
2075   if (R.isNull())
2076     return nullptr;
2077 
2078   DeclContext *Parent = Context.getTranslationUnitDecl();
2079   if (getLangOpts().CPlusPlus) {
2080     LinkageSpecDecl *CLinkageDecl =
2081         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
2082                                 LinkageSpecDecl::lang_c, false);
2083     CLinkageDecl->setImplicit();
2084     Parent->addDecl(CLinkageDecl);
2085     Parent = CLinkageDecl;
2086   }
2087 
2088   FunctionDecl *New = FunctionDecl::Create(Context,
2089                                            Parent,
2090                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
2091                                            SC_Extern,
2092                                            false,
2093                                            R->isFunctionProtoType());
2094   New->setImplicit();
2095 
2096   // Create Decl objects for each parameter, adding them to the
2097   // FunctionDecl.
2098   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
2099     SmallVector<ParmVarDecl*, 16> Params;
2100     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2101       ParmVarDecl *parm =
2102           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2103                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2104                               SC_None, nullptr);
2105       parm->setScopeInfo(0, i);
2106       Params.push_back(parm);
2107     }
2108     New->setParams(Params);
2109   }
2110 
2111   AddKnownFunctionAttributes(New);
2112   RegisterLocallyScopedExternCDecl(New, S);
2113 
2114   // TUScope is the translation-unit scope to insert this function into.
2115   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2116   // relate Scopes to DeclContexts, and probably eliminate CurContext
2117   // entirely, but we're not there yet.
2118   DeclContext *SavedContext = CurContext;
2119   CurContext = Parent;
2120   PushOnScopeChains(New, TUScope);
2121   CurContext = SavedContext;
2122   return New;
2123 }
2124 
2125 /// Typedef declarations don't have linkage, but they still denote the same
2126 /// entity if their types are the same.
2127 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2128 /// isSameEntity.
2129 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2130                                                      TypedefNameDecl *Decl,
2131                                                      LookupResult &Previous) {
2132   // This is only interesting when modules are enabled.
2133   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2134     return;
2135 
2136   // Empty sets are uninteresting.
2137   if (Previous.empty())
2138     return;
2139 
2140   LookupResult::Filter Filter = Previous.makeFilter();
2141   while (Filter.hasNext()) {
2142     NamedDecl *Old = Filter.next();
2143 
2144     // Non-hidden declarations are never ignored.
2145     if (S.isVisible(Old))
2146       continue;
2147 
2148     // Declarations of the same entity are not ignored, even if they have
2149     // different linkages.
2150     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2151       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2152                                 Decl->getUnderlyingType()))
2153         continue;
2154 
2155       // If both declarations give a tag declaration a typedef name for linkage
2156       // purposes, then they declare the same entity.
2157       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2158           Decl->getAnonDeclWithTypedefName())
2159         continue;
2160     }
2161 
2162     Filter.erase();
2163   }
2164 
2165   Filter.done();
2166 }
2167 
2168 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2169   QualType OldType;
2170   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2171     OldType = OldTypedef->getUnderlyingType();
2172   else
2173     OldType = Context.getTypeDeclType(Old);
2174   QualType NewType = New->getUnderlyingType();
2175 
2176   if (NewType->isVariablyModifiedType()) {
2177     // Must not redefine a typedef with a variably-modified type.
2178     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2179     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2180       << Kind << NewType;
2181     if (Old->getLocation().isValid())
2182       notePreviousDefinition(Old, New->getLocation());
2183     New->setInvalidDecl();
2184     return true;
2185   }
2186 
2187   if (OldType != NewType &&
2188       !OldType->isDependentType() &&
2189       !NewType->isDependentType() &&
2190       !Context.hasSameType(OldType, NewType)) {
2191     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2192     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2193       << Kind << NewType << OldType;
2194     if (Old->getLocation().isValid())
2195       notePreviousDefinition(Old, New->getLocation());
2196     New->setInvalidDecl();
2197     return true;
2198   }
2199   return false;
2200 }
2201 
2202 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2203 /// same name and scope as a previous declaration 'Old'.  Figure out
2204 /// how to resolve this situation, merging decls or emitting
2205 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2206 ///
2207 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2208                                 LookupResult &OldDecls) {
2209   // If the new decl is known invalid already, don't bother doing any
2210   // merging checks.
2211   if (New->isInvalidDecl()) return;
2212 
2213   // Allow multiple definitions for ObjC built-in typedefs.
2214   // FIXME: Verify the underlying types are equivalent!
2215   if (getLangOpts().ObjC) {
2216     const IdentifierInfo *TypeID = New->getIdentifier();
2217     switch (TypeID->getLength()) {
2218     default: break;
2219     case 2:
2220       {
2221         if (!TypeID->isStr("id"))
2222           break;
2223         QualType T = New->getUnderlyingType();
2224         if (!T->isPointerType())
2225           break;
2226         if (!T->isVoidPointerType()) {
2227           QualType PT = T->castAs<PointerType>()->getPointeeType();
2228           if (!PT->isStructureType())
2229             break;
2230         }
2231         Context.setObjCIdRedefinitionType(T);
2232         // Install the built-in type for 'id', ignoring the current definition.
2233         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2234         return;
2235       }
2236     case 5:
2237       if (!TypeID->isStr("Class"))
2238         break;
2239       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2240       // Install the built-in type for 'Class', ignoring the current definition.
2241       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2242       return;
2243     case 3:
2244       if (!TypeID->isStr("SEL"))
2245         break;
2246       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2247       // Install the built-in type for 'SEL', ignoring the current definition.
2248       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2249       return;
2250     }
2251     // Fall through - the typedef name was not a builtin type.
2252   }
2253 
2254   // Verify the old decl was also a type.
2255   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2256   if (!Old) {
2257     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2258       << New->getDeclName();
2259 
2260     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2261     if (OldD->getLocation().isValid())
2262       notePreviousDefinition(OldD, New->getLocation());
2263 
2264     return New->setInvalidDecl();
2265   }
2266 
2267   // If the old declaration is invalid, just give up here.
2268   if (Old->isInvalidDecl())
2269     return New->setInvalidDecl();
2270 
2271   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2272     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2273     auto *NewTag = New->getAnonDeclWithTypedefName();
2274     NamedDecl *Hidden = nullptr;
2275     if (OldTag && NewTag &&
2276         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2277         !hasVisibleDefinition(OldTag, &Hidden)) {
2278       // There is a definition of this tag, but it is not visible. Use it
2279       // instead of our tag.
2280       New->setTypeForDecl(OldTD->getTypeForDecl());
2281       if (OldTD->isModed())
2282         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2283                                     OldTD->getUnderlyingType());
2284       else
2285         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2286 
2287       // Make the old tag definition visible.
2288       makeMergedDefinitionVisible(Hidden);
2289 
2290       // If this was an unscoped enumeration, yank all of its enumerators
2291       // out of the scope.
2292       if (isa<EnumDecl>(NewTag)) {
2293         Scope *EnumScope = getNonFieldDeclScope(S);
2294         for (auto *D : NewTag->decls()) {
2295           auto *ED = cast<EnumConstantDecl>(D);
2296           assert(EnumScope->isDeclScope(ED));
2297           EnumScope->RemoveDecl(ED);
2298           IdResolver.RemoveDecl(ED);
2299           ED->getLexicalDeclContext()->removeDecl(ED);
2300         }
2301       }
2302     }
2303   }
2304 
2305   // If the typedef types are not identical, reject them in all languages and
2306   // with any extensions enabled.
2307   if (isIncompatibleTypedef(Old, New))
2308     return;
2309 
2310   // The types match.  Link up the redeclaration chain and merge attributes if
2311   // the old declaration was a typedef.
2312   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2313     New->setPreviousDecl(Typedef);
2314     mergeDeclAttributes(New, Old);
2315   }
2316 
2317   if (getLangOpts().MicrosoftExt)
2318     return;
2319 
2320   if (getLangOpts().CPlusPlus) {
2321     // C++ [dcl.typedef]p2:
2322     //   In a given non-class scope, a typedef specifier can be used to
2323     //   redefine the name of any type declared in that scope to refer
2324     //   to the type to which it already refers.
2325     if (!isa<CXXRecordDecl>(CurContext))
2326       return;
2327 
2328     // C++0x [dcl.typedef]p4:
2329     //   In a given class scope, a typedef specifier can be used to redefine
2330     //   any class-name declared in that scope that is not also a typedef-name
2331     //   to refer to the type to which it already refers.
2332     //
2333     // This wording came in via DR424, which was a correction to the
2334     // wording in DR56, which accidentally banned code like:
2335     //
2336     //   struct S {
2337     //     typedef struct A { } A;
2338     //   };
2339     //
2340     // in the C++03 standard. We implement the C++0x semantics, which
2341     // allow the above but disallow
2342     //
2343     //   struct S {
2344     //     typedef int I;
2345     //     typedef int I;
2346     //   };
2347     //
2348     // since that was the intent of DR56.
2349     if (!isa<TypedefNameDecl>(Old))
2350       return;
2351 
2352     Diag(New->getLocation(), diag::err_redefinition)
2353       << New->getDeclName();
2354     notePreviousDefinition(Old, New->getLocation());
2355     return New->setInvalidDecl();
2356   }
2357 
2358   // Modules always permit redefinition of typedefs, as does C11.
2359   if (getLangOpts().Modules || getLangOpts().C11)
2360     return;
2361 
2362   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2363   // is normally mapped to an error, but can be controlled with
2364   // -Wtypedef-redefinition.  If either the original or the redefinition is
2365   // in a system header, don't emit this for compatibility with GCC.
2366   if (getDiagnostics().getSuppressSystemWarnings() &&
2367       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2368       (Old->isImplicit() ||
2369        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2370        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2371     return;
2372 
2373   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2374     << New->getDeclName();
2375   notePreviousDefinition(Old, New->getLocation());
2376 }
2377 
2378 /// DeclhasAttr - returns true if decl Declaration already has the target
2379 /// attribute.
2380 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2381   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2382   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2383   for (const auto *i : D->attrs())
2384     if (i->getKind() == A->getKind()) {
2385       if (Ann) {
2386         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2387           return true;
2388         continue;
2389       }
2390       // FIXME: Don't hardcode this check
2391       if (OA && isa<OwnershipAttr>(i))
2392         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2393       return true;
2394     }
2395 
2396   return false;
2397 }
2398 
2399 static bool isAttributeTargetADefinition(Decl *D) {
2400   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2401     return VD->isThisDeclarationADefinition();
2402   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2403     return TD->isCompleteDefinition() || TD->isBeingDefined();
2404   return true;
2405 }
2406 
2407 /// Merge alignment attributes from \p Old to \p New, taking into account the
2408 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2409 ///
2410 /// \return \c true if any attributes were added to \p New.
2411 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2412   // Look for alignas attributes on Old, and pick out whichever attribute
2413   // specifies the strictest alignment requirement.
2414   AlignedAttr *OldAlignasAttr = nullptr;
2415   AlignedAttr *OldStrictestAlignAttr = nullptr;
2416   unsigned OldAlign = 0;
2417   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2418     // FIXME: We have no way of representing inherited dependent alignments
2419     // in a case like:
2420     //   template<int A, int B> struct alignas(A) X;
2421     //   template<int A, int B> struct alignas(B) X {};
2422     // For now, we just ignore any alignas attributes which are not on the
2423     // definition in such a case.
2424     if (I->isAlignmentDependent())
2425       return false;
2426 
2427     if (I->isAlignas())
2428       OldAlignasAttr = I;
2429 
2430     unsigned Align = I->getAlignment(S.Context);
2431     if (Align > OldAlign) {
2432       OldAlign = Align;
2433       OldStrictestAlignAttr = I;
2434     }
2435   }
2436 
2437   // Look for alignas attributes on New.
2438   AlignedAttr *NewAlignasAttr = nullptr;
2439   unsigned NewAlign = 0;
2440   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2441     if (I->isAlignmentDependent())
2442       return false;
2443 
2444     if (I->isAlignas())
2445       NewAlignasAttr = I;
2446 
2447     unsigned Align = I->getAlignment(S.Context);
2448     if (Align > NewAlign)
2449       NewAlign = Align;
2450   }
2451 
2452   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2453     // Both declarations have 'alignas' attributes. We require them to match.
2454     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2455     // fall short. (If two declarations both have alignas, they must both match
2456     // every definition, and so must match each other if there is a definition.)
2457 
2458     // If either declaration only contains 'alignas(0)' specifiers, then it
2459     // specifies the natural alignment for the type.
2460     if (OldAlign == 0 || NewAlign == 0) {
2461       QualType Ty;
2462       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2463         Ty = VD->getType();
2464       else
2465         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2466 
2467       if (OldAlign == 0)
2468         OldAlign = S.Context.getTypeAlign(Ty);
2469       if (NewAlign == 0)
2470         NewAlign = S.Context.getTypeAlign(Ty);
2471     }
2472 
2473     if (OldAlign != NewAlign) {
2474       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2475         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2476         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2477       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2478     }
2479   }
2480 
2481   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2482     // C++11 [dcl.align]p6:
2483     //   if any declaration of an entity has an alignment-specifier,
2484     //   every defining declaration of that entity shall specify an
2485     //   equivalent alignment.
2486     // C11 6.7.5/7:
2487     //   If the definition of an object does not have an alignment
2488     //   specifier, any other declaration of that object shall also
2489     //   have no alignment specifier.
2490     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2491       << OldAlignasAttr;
2492     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2493       << OldAlignasAttr;
2494   }
2495 
2496   bool AnyAdded = false;
2497 
2498   // Ensure we have an attribute representing the strictest alignment.
2499   if (OldAlign > NewAlign) {
2500     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2501     Clone->setInherited(true);
2502     New->addAttr(Clone);
2503     AnyAdded = true;
2504   }
2505 
2506   // Ensure we have an alignas attribute if the old declaration had one.
2507   if (OldAlignasAttr && !NewAlignasAttr &&
2508       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2509     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2510     Clone->setInherited(true);
2511     New->addAttr(Clone);
2512     AnyAdded = true;
2513   }
2514 
2515   return AnyAdded;
2516 }
2517 
2518 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2519                                const InheritableAttr *Attr,
2520                                Sema::AvailabilityMergeKind AMK) {
2521   // This function copies an attribute Attr from a previous declaration to the
2522   // new declaration D if the new declaration doesn't itself have that attribute
2523   // yet or if that attribute allows duplicates.
2524   // If you're adding a new attribute that requires logic different from
2525   // "use explicit attribute on decl if present, else use attribute from
2526   // previous decl", for example if the attribute needs to be consistent
2527   // between redeclarations, you need to call a custom merge function here.
2528   InheritableAttr *NewAttr = nullptr;
2529   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2530     NewAttr = S.mergeAvailabilityAttr(
2531         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2532         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2533         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2534         AA->getPriority());
2535   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2536     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2537   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2538     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2539   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2540     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2541   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2542     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2543   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2544     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2545                                 FA->getFirstArg());
2546   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2547     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2548   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2549     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2550   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2551     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2552                                        IA->getInheritanceModel());
2553   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2554     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2555                                       &S.Context.Idents.get(AA->getSpelling()));
2556   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2557            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2558             isa<CUDAGlobalAttr>(Attr))) {
2559     // CUDA target attributes are part of function signature for
2560     // overloading purposes and must not be merged.
2561     return false;
2562   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2563     NewAttr = S.mergeMinSizeAttr(D, *MA);
2564   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2565     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2566   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2567     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2568   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2569     NewAttr = S.mergeCommonAttr(D, *CommonA);
2570   else if (isa<AlignedAttr>(Attr))
2571     // AlignedAttrs are handled separately, because we need to handle all
2572     // such attributes on a declaration at the same time.
2573     NewAttr = nullptr;
2574   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2575            (AMK == Sema::AMK_Override ||
2576             AMK == Sema::AMK_ProtocolImplementation))
2577     NewAttr = nullptr;
2578   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2579     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid());
2580   else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
2581     NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
2582   else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
2583     NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
2584   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2585     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2586 
2587   if (NewAttr) {
2588     NewAttr->setInherited(true);
2589     D->addAttr(NewAttr);
2590     if (isa<MSInheritanceAttr>(NewAttr))
2591       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2592     return true;
2593   }
2594 
2595   return false;
2596 }
2597 
2598 static const NamedDecl *getDefinition(const Decl *D) {
2599   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2600     return TD->getDefinition();
2601   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2602     const VarDecl *Def = VD->getDefinition();
2603     if (Def)
2604       return Def;
2605     return VD->getActingDefinition();
2606   }
2607   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2608     return FD->getDefinition();
2609   return nullptr;
2610 }
2611 
2612 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2613   for (const auto *Attribute : D->attrs())
2614     if (Attribute->getKind() == Kind)
2615       return true;
2616   return false;
2617 }
2618 
2619 /// checkNewAttributesAfterDef - If we already have a definition, check that
2620 /// there are no new attributes in this declaration.
2621 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2622   if (!New->hasAttrs())
2623     return;
2624 
2625   const NamedDecl *Def = getDefinition(Old);
2626   if (!Def || Def == New)
2627     return;
2628 
2629   AttrVec &NewAttributes = New->getAttrs();
2630   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2631     const Attr *NewAttribute = NewAttributes[I];
2632 
2633     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2634       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2635         Sema::SkipBodyInfo SkipBody;
2636         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2637 
2638         // If we're skipping this definition, drop the "alias" attribute.
2639         if (SkipBody.ShouldSkip) {
2640           NewAttributes.erase(NewAttributes.begin() + I);
2641           --E;
2642           continue;
2643         }
2644       } else {
2645         VarDecl *VD = cast<VarDecl>(New);
2646         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2647                                 VarDecl::TentativeDefinition
2648                             ? diag::err_alias_after_tentative
2649                             : diag::err_redefinition;
2650         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2651         if (Diag == diag::err_redefinition)
2652           S.notePreviousDefinition(Def, VD->getLocation());
2653         else
2654           S.Diag(Def->getLocation(), diag::note_previous_definition);
2655         VD->setInvalidDecl();
2656       }
2657       ++I;
2658       continue;
2659     }
2660 
2661     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2662       // Tentative definitions are only interesting for the alias check above.
2663       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2664         ++I;
2665         continue;
2666       }
2667     }
2668 
2669     if (hasAttribute(Def, NewAttribute->getKind())) {
2670       ++I;
2671       continue; // regular attr merging will take care of validating this.
2672     }
2673 
2674     if (isa<C11NoReturnAttr>(NewAttribute)) {
2675       // C's _Noreturn is allowed to be added to a function after it is defined.
2676       ++I;
2677       continue;
2678     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2679       if (AA->isAlignas()) {
2680         // C++11 [dcl.align]p6:
2681         //   if any declaration of an entity has an alignment-specifier,
2682         //   every defining declaration of that entity shall specify an
2683         //   equivalent alignment.
2684         // C11 6.7.5/7:
2685         //   If the definition of an object does not have an alignment
2686         //   specifier, any other declaration of that object shall also
2687         //   have no alignment specifier.
2688         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2689           << AA;
2690         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2691           << AA;
2692         NewAttributes.erase(NewAttributes.begin() + I);
2693         --E;
2694         continue;
2695       }
2696     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2697                cast<VarDecl>(New)->isInline() &&
2698                !cast<VarDecl>(New)->isInlineSpecified()) {
2699       // Don't warn about applying selectany to implicitly inline variables.
2700       // Older compilers and language modes would require the use of selectany
2701       // to make such variables inline, and it would have no effect if we
2702       // honored it.
2703       ++I;
2704       continue;
2705     }
2706 
2707     S.Diag(NewAttribute->getLocation(),
2708            diag::warn_attribute_precede_definition);
2709     S.Diag(Def->getLocation(), diag::note_previous_definition);
2710     NewAttributes.erase(NewAttributes.begin() + I);
2711     --E;
2712   }
2713 }
2714 
2715 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2716                                      const ConstInitAttr *CIAttr,
2717                                      bool AttrBeforeInit) {
2718   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2719 
2720   // Figure out a good way to write this specifier on the old declaration.
2721   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2722   // enough of the attribute list spelling information to extract that without
2723   // heroics.
2724   std::string SuitableSpelling;
2725   if (S.getLangOpts().CPlusPlus2a)
2726     SuitableSpelling =
2727         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit});
2728   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2729     SuitableSpelling = S.PP.getLastMacroWithSpelling(
2730         InsertLoc,
2731         {tok::l_square, tok::l_square, S.PP.getIdentifierInfo("clang"),
2732          tok::coloncolon,
2733          S.PP.getIdentifierInfo("require_constant_initialization"),
2734          tok::r_square, tok::r_square});
2735   if (SuitableSpelling.empty())
2736     SuitableSpelling = S.PP.getLastMacroWithSpelling(
2737         InsertLoc,
2738         {tok::kw___attribute, tok::l_paren, tok::r_paren,
2739          S.PP.getIdentifierInfo("require_constant_initialization"),
2740          tok::r_paren, tok::r_paren});
2741   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus2a)
2742     SuitableSpelling = "constinit";
2743   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2744     SuitableSpelling = "[[clang::require_constant_initialization]]";
2745   if (SuitableSpelling.empty())
2746     SuitableSpelling = "__attribute__((require_constant_initialization))";
2747   SuitableSpelling += " ";
2748 
2749   if (AttrBeforeInit) {
2750     // extern constinit int a;
2751     // int a = 0; // error (missing 'constinit'), accepted as extension
2752     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
2753     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2754         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2755     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2756   } else {
2757     // int a = 0;
2758     // constinit extern int a; // error (missing 'constinit')
2759     S.Diag(CIAttr->getLocation(),
2760            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2761                                  : diag::warn_require_const_init_added_too_late)
2762         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2763     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2764         << CIAttr->isConstinit()
2765         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2766   }
2767 }
2768 
2769 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2770 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2771                                AvailabilityMergeKind AMK) {
2772   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2773     UsedAttr *NewAttr = OldAttr->clone(Context);
2774     NewAttr->setInherited(true);
2775     New->addAttr(NewAttr);
2776   }
2777 
2778   if (!Old->hasAttrs() && !New->hasAttrs())
2779     return;
2780 
2781   // [dcl.constinit]p1:
2782   //   If the [constinit] specifier is applied to any declaration of a
2783   //   variable, it shall be applied to the initializing declaration.
2784   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2785   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2786   if (bool(OldConstInit) != bool(NewConstInit)) {
2787     const auto *OldVD = cast<VarDecl>(Old);
2788     auto *NewVD = cast<VarDecl>(New);
2789 
2790     // Find the initializing declaration. Note that we might not have linked
2791     // the new declaration into the redeclaration chain yet.
2792     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2793     if (!InitDecl &&
2794         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2795       InitDecl = NewVD;
2796 
2797     if (InitDecl == NewVD) {
2798       // This is the initializing declaration. If it would inherit 'constinit',
2799       // that's ill-formed. (Note that we do not apply this to the attribute
2800       // form).
2801       if (OldConstInit && OldConstInit->isConstinit())
2802         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2803                                  /*AttrBeforeInit=*/true);
2804     } else if (NewConstInit) {
2805       // This is the first time we've been told that this declaration should
2806       // have a constant initializer. If we already saw the initializing
2807       // declaration, this is too late.
2808       if (InitDecl && InitDecl != NewVD) {
2809         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2810                                  /*AttrBeforeInit=*/false);
2811         NewVD->dropAttr<ConstInitAttr>();
2812       }
2813     }
2814   }
2815 
2816   // Attributes declared post-definition are currently ignored.
2817   checkNewAttributesAfterDef(*this, New, Old);
2818 
2819   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2820     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2821       if (!OldA->isEquivalent(NewA)) {
2822         // This redeclaration changes __asm__ label.
2823         Diag(New->getLocation(), diag::err_different_asm_label);
2824         Diag(OldA->getLocation(), diag::note_previous_declaration);
2825       }
2826     } else if (Old->isUsed()) {
2827       // This redeclaration adds an __asm__ label to a declaration that has
2828       // already been ODR-used.
2829       Diag(New->getLocation(), diag::err_late_asm_label_name)
2830         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2831     }
2832   }
2833 
2834   // Re-declaration cannot add abi_tag's.
2835   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2836     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2837       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2838         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2839                       NewTag) == OldAbiTagAttr->tags_end()) {
2840           Diag(NewAbiTagAttr->getLocation(),
2841                diag::err_new_abi_tag_on_redeclaration)
2842               << NewTag;
2843           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2844         }
2845       }
2846     } else {
2847       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2848       Diag(Old->getLocation(), diag::note_previous_declaration);
2849     }
2850   }
2851 
2852   // This redeclaration adds a section attribute.
2853   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2854     if (auto *VD = dyn_cast<VarDecl>(New)) {
2855       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2856         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2857         Diag(Old->getLocation(), diag::note_previous_declaration);
2858       }
2859     }
2860   }
2861 
2862   // Redeclaration adds code-seg attribute.
2863   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2864   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2865       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2866     Diag(New->getLocation(), diag::warn_mismatched_section)
2867          << 0 /*codeseg*/;
2868     Diag(Old->getLocation(), diag::note_previous_declaration);
2869   }
2870 
2871   if (!Old->hasAttrs())
2872     return;
2873 
2874   bool foundAny = New->hasAttrs();
2875 
2876   // Ensure that any moving of objects within the allocated map is done before
2877   // we process them.
2878   if (!foundAny) New->setAttrs(AttrVec());
2879 
2880   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2881     // Ignore deprecated/unavailable/availability attributes if requested.
2882     AvailabilityMergeKind LocalAMK = AMK_None;
2883     if (isa<DeprecatedAttr>(I) ||
2884         isa<UnavailableAttr>(I) ||
2885         isa<AvailabilityAttr>(I)) {
2886       switch (AMK) {
2887       case AMK_None:
2888         continue;
2889 
2890       case AMK_Redeclaration:
2891       case AMK_Override:
2892       case AMK_ProtocolImplementation:
2893         LocalAMK = AMK;
2894         break;
2895       }
2896     }
2897 
2898     // Already handled.
2899     if (isa<UsedAttr>(I))
2900       continue;
2901 
2902     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2903       foundAny = true;
2904   }
2905 
2906   if (mergeAlignedAttrs(*this, New, Old))
2907     foundAny = true;
2908 
2909   if (!foundAny) New->dropAttrs();
2910 }
2911 
2912 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2913 /// to the new one.
2914 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2915                                      const ParmVarDecl *oldDecl,
2916                                      Sema &S) {
2917   // C++11 [dcl.attr.depend]p2:
2918   //   The first declaration of a function shall specify the
2919   //   carries_dependency attribute for its declarator-id if any declaration
2920   //   of the function specifies the carries_dependency attribute.
2921   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2922   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2923     S.Diag(CDA->getLocation(),
2924            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2925     // Find the first declaration of the parameter.
2926     // FIXME: Should we build redeclaration chains for function parameters?
2927     const FunctionDecl *FirstFD =
2928       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2929     const ParmVarDecl *FirstVD =
2930       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2931     S.Diag(FirstVD->getLocation(),
2932            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2933   }
2934 
2935   if (!oldDecl->hasAttrs())
2936     return;
2937 
2938   bool foundAny = newDecl->hasAttrs();
2939 
2940   // Ensure that any moving of objects within the allocated map is
2941   // done before we process them.
2942   if (!foundAny) newDecl->setAttrs(AttrVec());
2943 
2944   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2945     if (!DeclHasAttr(newDecl, I)) {
2946       InheritableAttr *newAttr =
2947         cast<InheritableParamAttr>(I->clone(S.Context));
2948       newAttr->setInherited(true);
2949       newDecl->addAttr(newAttr);
2950       foundAny = true;
2951     }
2952   }
2953 
2954   if (!foundAny) newDecl->dropAttrs();
2955 }
2956 
2957 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2958                                 const ParmVarDecl *OldParam,
2959                                 Sema &S) {
2960   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2961     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2962       if (*Oldnullability != *Newnullability) {
2963         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2964           << DiagNullabilityKind(
2965                *Newnullability,
2966                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2967                 != 0))
2968           << DiagNullabilityKind(
2969                *Oldnullability,
2970                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2971                 != 0));
2972         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2973       }
2974     } else {
2975       QualType NewT = NewParam->getType();
2976       NewT = S.Context.getAttributedType(
2977                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2978                          NewT, NewT);
2979       NewParam->setType(NewT);
2980     }
2981   }
2982 }
2983 
2984 namespace {
2985 
2986 /// Used in MergeFunctionDecl to keep track of function parameters in
2987 /// C.
2988 struct GNUCompatibleParamWarning {
2989   ParmVarDecl *OldParm;
2990   ParmVarDecl *NewParm;
2991   QualType PromotedType;
2992 };
2993 
2994 } // end anonymous namespace
2995 
2996 // Determine whether the previous declaration was a definition, implicit
2997 // declaration, or a declaration.
2998 template <typename T>
2999 static std::pair<diag::kind, SourceLocation>
3000 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3001   diag::kind PrevDiag;
3002   SourceLocation OldLocation = Old->getLocation();
3003   if (Old->isThisDeclarationADefinition())
3004     PrevDiag = diag::note_previous_definition;
3005   else if (Old->isImplicit()) {
3006     PrevDiag = diag::note_previous_implicit_declaration;
3007     if (OldLocation.isInvalid())
3008       OldLocation = New->getLocation();
3009   } else
3010     PrevDiag = diag::note_previous_declaration;
3011   return std::make_pair(PrevDiag, OldLocation);
3012 }
3013 
3014 /// canRedefineFunction - checks if a function can be redefined. Currently,
3015 /// only extern inline functions can be redefined, and even then only in
3016 /// GNU89 mode.
3017 static bool canRedefineFunction(const FunctionDecl *FD,
3018                                 const LangOptions& LangOpts) {
3019   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3020           !LangOpts.CPlusPlus &&
3021           FD->isInlineSpecified() &&
3022           FD->getStorageClass() == SC_Extern);
3023 }
3024 
3025 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3026   const AttributedType *AT = T->getAs<AttributedType>();
3027   while (AT && !AT->isCallingConv())
3028     AT = AT->getModifiedType()->getAs<AttributedType>();
3029   return AT;
3030 }
3031 
3032 template <typename T>
3033 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3034   const DeclContext *DC = Old->getDeclContext();
3035   if (DC->isRecord())
3036     return false;
3037 
3038   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3039   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3040     return true;
3041   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3042     return true;
3043   return false;
3044 }
3045 
3046 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3047 static bool isExternC(VarTemplateDecl *) { return false; }
3048 
3049 /// Check whether a redeclaration of an entity introduced by a
3050 /// using-declaration is valid, given that we know it's not an overload
3051 /// (nor a hidden tag declaration).
3052 template<typename ExpectedDecl>
3053 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3054                                    ExpectedDecl *New) {
3055   // C++11 [basic.scope.declarative]p4:
3056   //   Given a set of declarations in a single declarative region, each of
3057   //   which specifies the same unqualified name,
3058   //   -- they shall all refer to the same entity, or all refer to functions
3059   //      and function templates; or
3060   //   -- exactly one declaration shall declare a class name or enumeration
3061   //      name that is not a typedef name and the other declarations shall all
3062   //      refer to the same variable or enumerator, or all refer to functions
3063   //      and function templates; in this case the class name or enumeration
3064   //      name is hidden (3.3.10).
3065 
3066   // C++11 [namespace.udecl]p14:
3067   //   If a function declaration in namespace scope or block scope has the
3068   //   same name and the same parameter-type-list as a function introduced
3069   //   by a using-declaration, and the declarations do not declare the same
3070   //   function, the program is ill-formed.
3071 
3072   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3073   if (Old &&
3074       !Old->getDeclContext()->getRedeclContext()->Equals(
3075           New->getDeclContext()->getRedeclContext()) &&
3076       !(isExternC(Old) && isExternC(New)))
3077     Old = nullptr;
3078 
3079   if (!Old) {
3080     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3081     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3082     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
3083     return true;
3084   }
3085   return false;
3086 }
3087 
3088 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3089                                             const FunctionDecl *B) {
3090   assert(A->getNumParams() == B->getNumParams());
3091 
3092   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3093     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3094     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3095     if (AttrA == AttrB)
3096       return true;
3097     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3098            AttrA->isDynamic() == AttrB->isDynamic();
3099   };
3100 
3101   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3102 }
3103 
3104 /// If necessary, adjust the semantic declaration context for a qualified
3105 /// declaration to name the correct inline namespace within the qualifier.
3106 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3107                                                DeclaratorDecl *OldD) {
3108   // The only case where we need to update the DeclContext is when
3109   // redeclaration lookup for a qualified name finds a declaration
3110   // in an inline namespace within the context named by the qualifier:
3111   //
3112   //   inline namespace N { int f(); }
3113   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3114   //
3115   // For unqualified declarations, the semantic context *can* change
3116   // along the redeclaration chain (for local extern declarations,
3117   // extern "C" declarations, and friend declarations in particular).
3118   if (!NewD->getQualifier())
3119     return;
3120 
3121   // NewD is probably already in the right context.
3122   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3123   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3124   if (NamedDC->Equals(SemaDC))
3125     return;
3126 
3127   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3128           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3129          "unexpected context for redeclaration");
3130 
3131   auto *LexDC = NewD->getLexicalDeclContext();
3132   auto FixSemaDC = [=](NamedDecl *D) {
3133     if (!D)
3134       return;
3135     D->setDeclContext(SemaDC);
3136     D->setLexicalDeclContext(LexDC);
3137   };
3138 
3139   FixSemaDC(NewD);
3140   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3141     FixSemaDC(FD->getDescribedFunctionTemplate());
3142   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3143     FixSemaDC(VD->getDescribedVarTemplate());
3144 }
3145 
3146 /// MergeFunctionDecl - We just parsed a function 'New' from
3147 /// declarator D which has the same name and scope as a previous
3148 /// declaration 'Old'.  Figure out how to resolve this situation,
3149 /// merging decls or emitting diagnostics as appropriate.
3150 ///
3151 /// In C++, New and Old must be declarations that are not
3152 /// overloaded. Use IsOverload to determine whether New and Old are
3153 /// overloaded, and to select the Old declaration that New should be
3154 /// merged with.
3155 ///
3156 /// Returns true if there was an error, false otherwise.
3157 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3158                              Scope *S, bool MergeTypeWithOld) {
3159   // Verify the old decl was also a function.
3160   FunctionDecl *Old = OldD->getAsFunction();
3161   if (!Old) {
3162     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3163       if (New->getFriendObjectKind()) {
3164         Diag(New->getLocation(), diag::err_using_decl_friend);
3165         Diag(Shadow->getTargetDecl()->getLocation(),
3166              diag::note_using_decl_target);
3167         Diag(Shadow->getUsingDecl()->getLocation(),
3168              diag::note_using_decl) << 0;
3169         return true;
3170       }
3171 
3172       // Check whether the two declarations might declare the same function.
3173       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3174         return true;
3175       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3176     } else {
3177       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3178         << New->getDeclName();
3179       notePreviousDefinition(OldD, New->getLocation());
3180       return true;
3181     }
3182   }
3183 
3184   // If the old declaration is invalid, just give up here.
3185   if (Old->isInvalidDecl())
3186     return true;
3187 
3188   // Disallow redeclaration of some builtins.
3189   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3190     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3191     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3192         << Old << Old->getType();
3193     return true;
3194   }
3195 
3196   diag::kind PrevDiag;
3197   SourceLocation OldLocation;
3198   std::tie(PrevDiag, OldLocation) =
3199       getNoteDiagForInvalidRedeclaration(Old, New);
3200 
3201   // Don't complain about this if we're in GNU89 mode and the old function
3202   // is an extern inline function.
3203   // Don't complain about specializations. They are not supposed to have
3204   // storage classes.
3205   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3206       New->getStorageClass() == SC_Static &&
3207       Old->hasExternalFormalLinkage() &&
3208       !New->getTemplateSpecializationInfo() &&
3209       !canRedefineFunction(Old, getLangOpts())) {
3210     if (getLangOpts().MicrosoftExt) {
3211       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3212       Diag(OldLocation, PrevDiag);
3213     } else {
3214       Diag(New->getLocation(), diag::err_static_non_static) << New;
3215       Diag(OldLocation, PrevDiag);
3216       return true;
3217     }
3218   }
3219 
3220   if (New->hasAttr<InternalLinkageAttr>() &&
3221       !Old->hasAttr<InternalLinkageAttr>()) {
3222     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3223         << New->getDeclName();
3224     notePreviousDefinition(Old, New->getLocation());
3225     New->dropAttr<InternalLinkageAttr>();
3226   }
3227 
3228   if (CheckRedeclarationModuleOwnership(New, Old))
3229     return true;
3230 
3231   if (!getLangOpts().CPlusPlus) {
3232     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3233     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3234       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3235         << New << OldOvl;
3236 
3237       // Try our best to find a decl that actually has the overloadable
3238       // attribute for the note. In most cases (e.g. programs with only one
3239       // broken declaration/definition), this won't matter.
3240       //
3241       // FIXME: We could do this if we juggled some extra state in
3242       // OverloadableAttr, rather than just removing it.
3243       const Decl *DiagOld = Old;
3244       if (OldOvl) {
3245         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3246           const auto *A = D->getAttr<OverloadableAttr>();
3247           return A && !A->isImplicit();
3248         });
3249         // If we've implicitly added *all* of the overloadable attrs to this
3250         // chain, emitting a "previous redecl" note is pointless.
3251         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3252       }
3253 
3254       if (DiagOld)
3255         Diag(DiagOld->getLocation(),
3256              diag::note_attribute_overloadable_prev_overload)
3257           << OldOvl;
3258 
3259       if (OldOvl)
3260         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3261       else
3262         New->dropAttr<OverloadableAttr>();
3263     }
3264   }
3265 
3266   // If a function is first declared with a calling convention, but is later
3267   // declared or defined without one, all following decls assume the calling
3268   // convention of the first.
3269   //
3270   // It's OK if a function is first declared without a calling convention,
3271   // but is later declared or defined with the default calling convention.
3272   //
3273   // To test if either decl has an explicit calling convention, we look for
3274   // AttributedType sugar nodes on the type as written.  If they are missing or
3275   // were canonicalized away, we assume the calling convention was implicit.
3276   //
3277   // Note also that we DO NOT return at this point, because we still have
3278   // other tests to run.
3279   QualType OldQType = Context.getCanonicalType(Old->getType());
3280   QualType NewQType = Context.getCanonicalType(New->getType());
3281   const FunctionType *OldType = cast<FunctionType>(OldQType);
3282   const FunctionType *NewType = cast<FunctionType>(NewQType);
3283   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3284   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3285   bool RequiresAdjustment = false;
3286 
3287   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3288     FunctionDecl *First = Old->getFirstDecl();
3289     const FunctionType *FT =
3290         First->getType().getCanonicalType()->castAs<FunctionType>();
3291     FunctionType::ExtInfo FI = FT->getExtInfo();
3292     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3293     if (!NewCCExplicit) {
3294       // Inherit the CC from the previous declaration if it was specified
3295       // there but not here.
3296       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3297       RequiresAdjustment = true;
3298     } else if (New->getBuiltinID()) {
3299       // Calling Conventions on a Builtin aren't really useful and setting a
3300       // default calling convention and cdecl'ing some builtin redeclarations is
3301       // common, so warn and ignore the calling convention on the redeclaration.
3302       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3303           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3304           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3305       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3306       RequiresAdjustment = true;
3307     } else {
3308       // Calling conventions aren't compatible, so complain.
3309       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3310       Diag(New->getLocation(), diag::err_cconv_change)
3311         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3312         << !FirstCCExplicit
3313         << (!FirstCCExplicit ? "" :
3314             FunctionType::getNameForCallConv(FI.getCC()));
3315 
3316       // Put the note on the first decl, since it is the one that matters.
3317       Diag(First->getLocation(), diag::note_previous_declaration);
3318       return true;
3319     }
3320   }
3321 
3322   // FIXME: diagnose the other way around?
3323   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3324     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3325     RequiresAdjustment = true;
3326   }
3327 
3328   // Merge regparm attribute.
3329   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3330       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3331     if (NewTypeInfo.getHasRegParm()) {
3332       Diag(New->getLocation(), diag::err_regparm_mismatch)
3333         << NewType->getRegParmType()
3334         << OldType->getRegParmType();
3335       Diag(OldLocation, diag::note_previous_declaration);
3336       return true;
3337     }
3338 
3339     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3340     RequiresAdjustment = true;
3341   }
3342 
3343   // Merge ns_returns_retained attribute.
3344   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3345     if (NewTypeInfo.getProducesResult()) {
3346       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3347           << "'ns_returns_retained'";
3348       Diag(OldLocation, diag::note_previous_declaration);
3349       return true;
3350     }
3351 
3352     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3353     RequiresAdjustment = true;
3354   }
3355 
3356   if (OldTypeInfo.getNoCallerSavedRegs() !=
3357       NewTypeInfo.getNoCallerSavedRegs()) {
3358     if (NewTypeInfo.getNoCallerSavedRegs()) {
3359       AnyX86NoCallerSavedRegistersAttr *Attr =
3360         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3361       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3362       Diag(OldLocation, diag::note_previous_declaration);
3363       return true;
3364     }
3365 
3366     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3367     RequiresAdjustment = true;
3368   }
3369 
3370   if (RequiresAdjustment) {
3371     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3372     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3373     New->setType(QualType(AdjustedType, 0));
3374     NewQType = Context.getCanonicalType(New->getType());
3375   }
3376 
3377   // If this redeclaration makes the function inline, we may need to add it to
3378   // UndefinedButUsed.
3379   if (!Old->isInlined() && New->isInlined() &&
3380       !New->hasAttr<GNUInlineAttr>() &&
3381       !getLangOpts().GNUInline &&
3382       Old->isUsed(false) &&
3383       !Old->isDefined() && !New->isThisDeclarationADefinition())
3384     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3385                                            SourceLocation()));
3386 
3387   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3388   // about it.
3389   if (New->hasAttr<GNUInlineAttr>() &&
3390       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3391     UndefinedButUsed.erase(Old->getCanonicalDecl());
3392   }
3393 
3394   // If pass_object_size params don't match up perfectly, this isn't a valid
3395   // redeclaration.
3396   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3397       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3398     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3399         << New->getDeclName();
3400     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3401     return true;
3402   }
3403 
3404   if (getLangOpts().CPlusPlus) {
3405     // C++1z [over.load]p2
3406     //   Certain function declarations cannot be overloaded:
3407     //     -- Function declarations that differ only in the return type,
3408     //        the exception specification, or both cannot be overloaded.
3409 
3410     // Check the exception specifications match. This may recompute the type of
3411     // both Old and New if it resolved exception specifications, so grab the
3412     // types again after this. Because this updates the type, we do this before
3413     // any of the other checks below, which may update the "de facto" NewQType
3414     // but do not necessarily update the type of New.
3415     if (CheckEquivalentExceptionSpec(Old, New))
3416       return true;
3417     OldQType = Context.getCanonicalType(Old->getType());
3418     NewQType = Context.getCanonicalType(New->getType());
3419 
3420     // Go back to the type source info to compare the declared return types,
3421     // per C++1y [dcl.type.auto]p13:
3422     //   Redeclarations or specializations of a function or function template
3423     //   with a declared return type that uses a placeholder type shall also
3424     //   use that placeholder, not a deduced type.
3425     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3426     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3427     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3428         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3429                                        OldDeclaredReturnType)) {
3430       QualType ResQT;
3431       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3432           OldDeclaredReturnType->isObjCObjectPointerType())
3433         // FIXME: This does the wrong thing for a deduced return type.
3434         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3435       if (ResQT.isNull()) {
3436         if (New->isCXXClassMember() && New->isOutOfLine())
3437           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3438               << New << New->getReturnTypeSourceRange();
3439         else
3440           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3441               << New->getReturnTypeSourceRange();
3442         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3443                                     << Old->getReturnTypeSourceRange();
3444         return true;
3445       }
3446       else
3447         NewQType = ResQT;
3448     }
3449 
3450     QualType OldReturnType = OldType->getReturnType();
3451     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3452     if (OldReturnType != NewReturnType) {
3453       // If this function has a deduced return type and has already been
3454       // defined, copy the deduced value from the old declaration.
3455       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3456       if (OldAT && OldAT->isDeduced()) {
3457         New->setType(
3458             SubstAutoType(New->getType(),
3459                           OldAT->isDependentType() ? Context.DependentTy
3460                                                    : OldAT->getDeducedType()));
3461         NewQType = Context.getCanonicalType(
3462             SubstAutoType(NewQType,
3463                           OldAT->isDependentType() ? Context.DependentTy
3464                                                    : OldAT->getDeducedType()));
3465       }
3466     }
3467 
3468     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3469     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3470     if (OldMethod && NewMethod) {
3471       // Preserve triviality.
3472       NewMethod->setTrivial(OldMethod->isTrivial());
3473 
3474       // MSVC allows explicit template specialization at class scope:
3475       // 2 CXXMethodDecls referring to the same function will be injected.
3476       // We don't want a redeclaration error.
3477       bool IsClassScopeExplicitSpecialization =
3478                               OldMethod->isFunctionTemplateSpecialization() &&
3479                               NewMethod->isFunctionTemplateSpecialization();
3480       bool isFriend = NewMethod->getFriendObjectKind();
3481 
3482       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3483           !IsClassScopeExplicitSpecialization) {
3484         //    -- Member function declarations with the same name and the
3485         //       same parameter types cannot be overloaded if any of them
3486         //       is a static member function declaration.
3487         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3488           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3489           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3490           return true;
3491         }
3492 
3493         // C++ [class.mem]p1:
3494         //   [...] A member shall not be declared twice in the
3495         //   member-specification, except that a nested class or member
3496         //   class template can be declared and then later defined.
3497         if (!inTemplateInstantiation()) {
3498           unsigned NewDiag;
3499           if (isa<CXXConstructorDecl>(OldMethod))
3500             NewDiag = diag::err_constructor_redeclared;
3501           else if (isa<CXXDestructorDecl>(NewMethod))
3502             NewDiag = diag::err_destructor_redeclared;
3503           else if (isa<CXXConversionDecl>(NewMethod))
3504             NewDiag = diag::err_conv_function_redeclared;
3505           else
3506             NewDiag = diag::err_member_redeclared;
3507 
3508           Diag(New->getLocation(), NewDiag);
3509         } else {
3510           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3511             << New << New->getType();
3512         }
3513         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3514         return true;
3515 
3516       // Complain if this is an explicit declaration of a special
3517       // member that was initially declared implicitly.
3518       //
3519       // As an exception, it's okay to befriend such methods in order
3520       // to permit the implicit constructor/destructor/operator calls.
3521       } else if (OldMethod->isImplicit()) {
3522         if (isFriend) {
3523           NewMethod->setImplicit();
3524         } else {
3525           Diag(NewMethod->getLocation(),
3526                diag::err_definition_of_implicitly_declared_member)
3527             << New << getSpecialMember(OldMethod);
3528           return true;
3529         }
3530       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3531         Diag(NewMethod->getLocation(),
3532              diag::err_definition_of_explicitly_defaulted_member)
3533           << getSpecialMember(OldMethod);
3534         return true;
3535       }
3536     }
3537 
3538     // C++11 [dcl.attr.noreturn]p1:
3539     //   The first declaration of a function shall specify the noreturn
3540     //   attribute if any declaration of that function specifies the noreturn
3541     //   attribute.
3542     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3543     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3544       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3545       Diag(Old->getFirstDecl()->getLocation(),
3546            diag::note_noreturn_missing_first_decl);
3547     }
3548 
3549     // C++11 [dcl.attr.depend]p2:
3550     //   The first declaration of a function shall specify the
3551     //   carries_dependency attribute for its declarator-id if any declaration
3552     //   of the function specifies the carries_dependency attribute.
3553     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3554     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3555       Diag(CDA->getLocation(),
3556            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3557       Diag(Old->getFirstDecl()->getLocation(),
3558            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3559     }
3560 
3561     // (C++98 8.3.5p3):
3562     //   All declarations for a function shall agree exactly in both the
3563     //   return type and the parameter-type-list.
3564     // We also want to respect all the extended bits except noreturn.
3565 
3566     // noreturn should now match unless the old type info didn't have it.
3567     QualType OldQTypeForComparison = OldQType;
3568     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3569       auto *OldType = OldQType->castAs<FunctionProtoType>();
3570       const FunctionType *OldTypeForComparison
3571         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3572       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3573       assert(OldQTypeForComparison.isCanonical());
3574     }
3575 
3576     if (haveIncompatibleLanguageLinkages(Old, New)) {
3577       // As a special case, retain the language linkage from previous
3578       // declarations of a friend function as an extension.
3579       //
3580       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3581       // and is useful because there's otherwise no way to specify language
3582       // linkage within class scope.
3583       //
3584       // Check cautiously as the friend object kind isn't yet complete.
3585       if (New->getFriendObjectKind() != Decl::FOK_None) {
3586         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3587         Diag(OldLocation, PrevDiag);
3588       } else {
3589         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3590         Diag(OldLocation, PrevDiag);
3591         return true;
3592       }
3593     }
3594 
3595     // If the function types are compatible, merge the declarations. Ignore the
3596     // exception specifier because it was already checked above in
3597     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3598     // about incompatible types under -fms-compatibility.
3599     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3600                                                          NewQType))
3601       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3602 
3603     // If the types are imprecise (due to dependent constructs in friends or
3604     // local extern declarations), it's OK if they differ. We'll check again
3605     // during instantiation.
3606     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3607       return false;
3608 
3609     // Fall through for conflicting redeclarations and redefinitions.
3610   }
3611 
3612   // C: Function types need to be compatible, not identical. This handles
3613   // duplicate function decls like "void f(int); void f(enum X);" properly.
3614   if (!getLangOpts().CPlusPlus &&
3615       Context.typesAreCompatible(OldQType, NewQType)) {
3616     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3617     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3618     const FunctionProtoType *OldProto = nullptr;
3619     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3620         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3621       // The old declaration provided a function prototype, but the
3622       // new declaration does not. Merge in the prototype.
3623       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3624       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3625       NewQType =
3626           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3627                                   OldProto->getExtProtoInfo());
3628       New->setType(NewQType);
3629       New->setHasInheritedPrototype();
3630 
3631       // Synthesize parameters with the same types.
3632       SmallVector<ParmVarDecl*, 16> Params;
3633       for (const auto &ParamType : OldProto->param_types()) {
3634         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3635                                                  SourceLocation(), nullptr,
3636                                                  ParamType, /*TInfo=*/nullptr,
3637                                                  SC_None, nullptr);
3638         Param->setScopeInfo(0, Params.size());
3639         Param->setImplicit();
3640         Params.push_back(Param);
3641       }
3642 
3643       New->setParams(Params);
3644     }
3645 
3646     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3647   }
3648 
3649   // GNU C permits a K&R definition to follow a prototype declaration
3650   // if the declared types of the parameters in the K&R definition
3651   // match the types in the prototype declaration, even when the
3652   // promoted types of the parameters from the K&R definition differ
3653   // from the types in the prototype. GCC then keeps the types from
3654   // the prototype.
3655   //
3656   // If a variadic prototype is followed by a non-variadic K&R definition,
3657   // the K&R definition becomes variadic.  This is sort of an edge case, but
3658   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3659   // C99 6.9.1p8.
3660   if (!getLangOpts().CPlusPlus &&
3661       Old->hasPrototype() && !New->hasPrototype() &&
3662       New->getType()->getAs<FunctionProtoType>() &&
3663       Old->getNumParams() == New->getNumParams()) {
3664     SmallVector<QualType, 16> ArgTypes;
3665     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3666     const FunctionProtoType *OldProto
3667       = Old->getType()->getAs<FunctionProtoType>();
3668     const FunctionProtoType *NewProto
3669       = New->getType()->getAs<FunctionProtoType>();
3670 
3671     // Determine whether this is the GNU C extension.
3672     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3673                                                NewProto->getReturnType());
3674     bool LooseCompatible = !MergedReturn.isNull();
3675     for (unsigned Idx = 0, End = Old->getNumParams();
3676          LooseCompatible && Idx != End; ++Idx) {
3677       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3678       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3679       if (Context.typesAreCompatible(OldParm->getType(),
3680                                      NewProto->getParamType(Idx))) {
3681         ArgTypes.push_back(NewParm->getType());
3682       } else if (Context.typesAreCompatible(OldParm->getType(),
3683                                             NewParm->getType(),
3684                                             /*CompareUnqualified=*/true)) {
3685         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3686                                            NewProto->getParamType(Idx) };
3687         Warnings.push_back(Warn);
3688         ArgTypes.push_back(NewParm->getType());
3689       } else
3690         LooseCompatible = false;
3691     }
3692 
3693     if (LooseCompatible) {
3694       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3695         Diag(Warnings[Warn].NewParm->getLocation(),
3696              diag::ext_param_promoted_not_compatible_with_prototype)
3697           << Warnings[Warn].PromotedType
3698           << Warnings[Warn].OldParm->getType();
3699         if (Warnings[Warn].OldParm->getLocation().isValid())
3700           Diag(Warnings[Warn].OldParm->getLocation(),
3701                diag::note_previous_declaration);
3702       }
3703 
3704       if (MergeTypeWithOld)
3705         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3706                                              OldProto->getExtProtoInfo()));
3707       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3708     }
3709 
3710     // Fall through to diagnose conflicting types.
3711   }
3712 
3713   // A function that has already been declared has been redeclared or
3714   // defined with a different type; show an appropriate diagnostic.
3715 
3716   // If the previous declaration was an implicitly-generated builtin
3717   // declaration, then at the very least we should use a specialized note.
3718   unsigned BuiltinID;
3719   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3720     // If it's actually a library-defined builtin function like 'malloc'
3721     // or 'printf', just warn about the incompatible redeclaration.
3722     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3723       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3724       Diag(OldLocation, diag::note_previous_builtin_declaration)
3725         << Old << Old->getType();
3726 
3727       // If this is a global redeclaration, just forget hereafter
3728       // about the "builtin-ness" of the function.
3729       //
3730       // Doing this for local extern declarations is problematic.  If
3731       // the builtin declaration remains visible, a second invalid
3732       // local declaration will produce a hard error; if it doesn't
3733       // remain visible, a single bogus local redeclaration (which is
3734       // actually only a warning) could break all the downstream code.
3735       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3736         New->getIdentifier()->revertBuiltin();
3737 
3738       return false;
3739     }
3740 
3741     PrevDiag = diag::note_previous_builtin_declaration;
3742   }
3743 
3744   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3745   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3746   return true;
3747 }
3748 
3749 /// Completes the merge of two function declarations that are
3750 /// known to be compatible.
3751 ///
3752 /// This routine handles the merging of attributes and other
3753 /// properties of function declarations from the old declaration to
3754 /// the new declaration, once we know that New is in fact a
3755 /// redeclaration of Old.
3756 ///
3757 /// \returns false
3758 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3759                                         Scope *S, bool MergeTypeWithOld) {
3760   // Merge the attributes
3761   mergeDeclAttributes(New, Old);
3762 
3763   // Merge "pure" flag.
3764   if (Old->isPure())
3765     New->setPure();
3766 
3767   // Merge "used" flag.
3768   if (Old->getMostRecentDecl()->isUsed(false))
3769     New->setIsUsed();
3770 
3771   // Merge attributes from the parameters.  These can mismatch with K&R
3772   // declarations.
3773   if (New->getNumParams() == Old->getNumParams())
3774       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3775         ParmVarDecl *NewParam = New->getParamDecl(i);
3776         ParmVarDecl *OldParam = Old->getParamDecl(i);
3777         mergeParamDeclAttributes(NewParam, OldParam, *this);
3778         mergeParamDeclTypes(NewParam, OldParam, *this);
3779       }
3780 
3781   if (getLangOpts().CPlusPlus)
3782     return MergeCXXFunctionDecl(New, Old, S);
3783 
3784   // Merge the function types so the we get the composite types for the return
3785   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3786   // was visible.
3787   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3788   if (!Merged.isNull() && MergeTypeWithOld)
3789     New->setType(Merged);
3790 
3791   return false;
3792 }
3793 
3794 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3795                                 ObjCMethodDecl *oldMethod) {
3796   // Merge the attributes, including deprecated/unavailable
3797   AvailabilityMergeKind MergeKind =
3798     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3799       ? AMK_ProtocolImplementation
3800       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3801                                                        : AMK_Override;
3802 
3803   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3804 
3805   // Merge attributes from the parameters.
3806   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3807                                        oe = oldMethod->param_end();
3808   for (ObjCMethodDecl::param_iterator
3809          ni = newMethod->param_begin(), ne = newMethod->param_end();
3810        ni != ne && oi != oe; ++ni, ++oi)
3811     mergeParamDeclAttributes(*ni, *oi, *this);
3812 
3813   CheckObjCMethodOverride(newMethod, oldMethod);
3814 }
3815 
3816 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3817   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3818 
3819   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3820          ? diag::err_redefinition_different_type
3821          : diag::err_redeclaration_different_type)
3822     << New->getDeclName() << New->getType() << Old->getType();
3823 
3824   diag::kind PrevDiag;
3825   SourceLocation OldLocation;
3826   std::tie(PrevDiag, OldLocation)
3827     = getNoteDiagForInvalidRedeclaration(Old, New);
3828   S.Diag(OldLocation, PrevDiag);
3829   New->setInvalidDecl();
3830 }
3831 
3832 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3833 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3834 /// emitting diagnostics as appropriate.
3835 ///
3836 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3837 /// to here in AddInitializerToDecl. We can't check them before the initializer
3838 /// is attached.
3839 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3840                              bool MergeTypeWithOld) {
3841   if (New->isInvalidDecl() || Old->isInvalidDecl())
3842     return;
3843 
3844   QualType MergedT;
3845   if (getLangOpts().CPlusPlus) {
3846     if (New->getType()->isUndeducedType()) {
3847       // We don't know what the new type is until the initializer is attached.
3848       return;
3849     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3850       // These could still be something that needs exception specs checked.
3851       return MergeVarDeclExceptionSpecs(New, Old);
3852     }
3853     // C++ [basic.link]p10:
3854     //   [...] the types specified by all declarations referring to a given
3855     //   object or function shall be identical, except that declarations for an
3856     //   array object can specify array types that differ by the presence or
3857     //   absence of a major array bound (8.3.4).
3858     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3859       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3860       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3861 
3862       // We are merging a variable declaration New into Old. If it has an array
3863       // bound, and that bound differs from Old's bound, we should diagnose the
3864       // mismatch.
3865       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3866         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3867              PrevVD = PrevVD->getPreviousDecl()) {
3868           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3869           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3870             continue;
3871 
3872           if (!Context.hasSameType(NewArray, PrevVDTy))
3873             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3874         }
3875       }
3876 
3877       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3878         if (Context.hasSameType(OldArray->getElementType(),
3879                                 NewArray->getElementType()))
3880           MergedT = New->getType();
3881       }
3882       // FIXME: Check visibility. New is hidden but has a complete type. If New
3883       // has no array bound, it should not inherit one from Old, if Old is not
3884       // visible.
3885       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3886         if (Context.hasSameType(OldArray->getElementType(),
3887                                 NewArray->getElementType()))
3888           MergedT = Old->getType();
3889       }
3890     }
3891     else if (New->getType()->isObjCObjectPointerType() &&
3892                Old->getType()->isObjCObjectPointerType()) {
3893       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3894                                               Old->getType());
3895     }
3896   } else {
3897     // C 6.2.7p2:
3898     //   All declarations that refer to the same object or function shall have
3899     //   compatible type.
3900     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3901   }
3902   if (MergedT.isNull()) {
3903     // It's OK if we couldn't merge types if either type is dependent, for a
3904     // block-scope variable. In other cases (static data members of class
3905     // templates, variable templates, ...), we require the types to be
3906     // equivalent.
3907     // FIXME: The C++ standard doesn't say anything about this.
3908     if ((New->getType()->isDependentType() ||
3909          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3910       // If the old type was dependent, we can't merge with it, so the new type
3911       // becomes dependent for now. We'll reproduce the original type when we
3912       // instantiate the TypeSourceInfo for the variable.
3913       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3914         New->setType(Context.DependentTy);
3915       return;
3916     }
3917     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3918   }
3919 
3920   // Don't actually update the type on the new declaration if the old
3921   // declaration was an extern declaration in a different scope.
3922   if (MergeTypeWithOld)
3923     New->setType(MergedT);
3924 }
3925 
3926 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3927                                   LookupResult &Previous) {
3928   // C11 6.2.7p4:
3929   //   For an identifier with internal or external linkage declared
3930   //   in a scope in which a prior declaration of that identifier is
3931   //   visible, if the prior declaration specifies internal or
3932   //   external linkage, the type of the identifier at the later
3933   //   declaration becomes the composite type.
3934   //
3935   // If the variable isn't visible, we do not merge with its type.
3936   if (Previous.isShadowed())
3937     return false;
3938 
3939   if (S.getLangOpts().CPlusPlus) {
3940     // C++11 [dcl.array]p3:
3941     //   If there is a preceding declaration of the entity in the same
3942     //   scope in which the bound was specified, an omitted array bound
3943     //   is taken to be the same as in that earlier declaration.
3944     return NewVD->isPreviousDeclInSameBlockScope() ||
3945            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3946             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3947   } else {
3948     // If the old declaration was function-local, don't merge with its
3949     // type unless we're in the same function.
3950     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3951            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3952   }
3953 }
3954 
3955 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3956 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3957 /// situation, merging decls or emitting diagnostics as appropriate.
3958 ///
3959 /// Tentative definition rules (C99 6.9.2p2) are checked by
3960 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3961 /// definitions here, since the initializer hasn't been attached.
3962 ///
3963 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3964   // If the new decl is already invalid, don't do any other checking.
3965   if (New->isInvalidDecl())
3966     return;
3967 
3968   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3969     return;
3970 
3971   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3972 
3973   // Verify the old decl was also a variable or variable template.
3974   VarDecl *Old = nullptr;
3975   VarTemplateDecl *OldTemplate = nullptr;
3976   if (Previous.isSingleResult()) {
3977     if (NewTemplate) {
3978       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3979       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3980 
3981       if (auto *Shadow =
3982               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3983         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3984           return New->setInvalidDecl();
3985     } else {
3986       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3987 
3988       if (auto *Shadow =
3989               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3990         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3991           return New->setInvalidDecl();
3992     }
3993   }
3994   if (!Old) {
3995     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3996         << New->getDeclName();
3997     notePreviousDefinition(Previous.getRepresentativeDecl(),
3998                            New->getLocation());
3999     return New->setInvalidDecl();
4000   }
4001 
4002   // Ensure the template parameters are compatible.
4003   if (NewTemplate &&
4004       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4005                                       OldTemplate->getTemplateParameters(),
4006                                       /*Complain=*/true, TPL_TemplateMatch))
4007     return New->setInvalidDecl();
4008 
4009   // C++ [class.mem]p1:
4010   //   A member shall not be declared twice in the member-specification [...]
4011   //
4012   // Here, we need only consider static data members.
4013   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4014     Diag(New->getLocation(), diag::err_duplicate_member)
4015       << New->getIdentifier();
4016     Diag(Old->getLocation(), diag::note_previous_declaration);
4017     New->setInvalidDecl();
4018   }
4019 
4020   mergeDeclAttributes(New, Old);
4021   // Warn if an already-declared variable is made a weak_import in a subsequent
4022   // declaration
4023   if (New->hasAttr<WeakImportAttr>() &&
4024       Old->getStorageClass() == SC_None &&
4025       !Old->hasAttr<WeakImportAttr>()) {
4026     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4027     notePreviousDefinition(Old, New->getLocation());
4028     // Remove weak_import attribute on new declaration.
4029     New->dropAttr<WeakImportAttr>();
4030   }
4031 
4032   if (New->hasAttr<InternalLinkageAttr>() &&
4033       !Old->hasAttr<InternalLinkageAttr>()) {
4034     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
4035         << New->getDeclName();
4036     notePreviousDefinition(Old, New->getLocation());
4037     New->dropAttr<InternalLinkageAttr>();
4038   }
4039 
4040   // Merge the types.
4041   VarDecl *MostRecent = Old->getMostRecentDecl();
4042   if (MostRecent != Old) {
4043     MergeVarDeclTypes(New, MostRecent,
4044                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4045     if (New->isInvalidDecl())
4046       return;
4047   }
4048 
4049   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4050   if (New->isInvalidDecl())
4051     return;
4052 
4053   diag::kind PrevDiag;
4054   SourceLocation OldLocation;
4055   std::tie(PrevDiag, OldLocation) =
4056       getNoteDiagForInvalidRedeclaration(Old, New);
4057 
4058   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4059   if (New->getStorageClass() == SC_Static &&
4060       !New->isStaticDataMember() &&
4061       Old->hasExternalFormalLinkage()) {
4062     if (getLangOpts().MicrosoftExt) {
4063       Diag(New->getLocation(), diag::ext_static_non_static)
4064           << New->getDeclName();
4065       Diag(OldLocation, PrevDiag);
4066     } else {
4067       Diag(New->getLocation(), diag::err_static_non_static)
4068           << New->getDeclName();
4069       Diag(OldLocation, PrevDiag);
4070       return New->setInvalidDecl();
4071     }
4072   }
4073   // C99 6.2.2p4:
4074   //   For an identifier declared with the storage-class specifier
4075   //   extern in a scope in which a prior declaration of that
4076   //   identifier is visible,23) if the prior declaration specifies
4077   //   internal or external linkage, the linkage of the identifier at
4078   //   the later declaration is the same as the linkage specified at
4079   //   the prior declaration. If no prior declaration is visible, or
4080   //   if the prior declaration specifies no linkage, then the
4081   //   identifier has external linkage.
4082   if (New->hasExternalStorage() && Old->hasLinkage())
4083     /* Okay */;
4084   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4085            !New->isStaticDataMember() &&
4086            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4087     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4088     Diag(OldLocation, PrevDiag);
4089     return New->setInvalidDecl();
4090   }
4091 
4092   // Check if extern is followed by non-extern and vice-versa.
4093   if (New->hasExternalStorage() &&
4094       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4095     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4096     Diag(OldLocation, PrevDiag);
4097     return New->setInvalidDecl();
4098   }
4099   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4100       !New->hasExternalStorage()) {
4101     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4102     Diag(OldLocation, PrevDiag);
4103     return New->setInvalidDecl();
4104   }
4105 
4106   if (CheckRedeclarationModuleOwnership(New, Old))
4107     return;
4108 
4109   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4110 
4111   // FIXME: The test for external storage here seems wrong? We still
4112   // need to check for mismatches.
4113   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4114       // Don't complain about out-of-line definitions of static members.
4115       !(Old->getLexicalDeclContext()->isRecord() &&
4116         !New->getLexicalDeclContext()->isRecord())) {
4117     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4118     Diag(OldLocation, PrevDiag);
4119     return New->setInvalidDecl();
4120   }
4121 
4122   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4123     if (VarDecl *Def = Old->getDefinition()) {
4124       // C++1z [dcl.fcn.spec]p4:
4125       //   If the definition of a variable appears in a translation unit before
4126       //   its first declaration as inline, the program is ill-formed.
4127       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4128       Diag(Def->getLocation(), diag::note_previous_definition);
4129     }
4130   }
4131 
4132   // If this redeclaration makes the variable inline, we may need to add it to
4133   // UndefinedButUsed.
4134   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4135       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4136     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4137                                            SourceLocation()));
4138 
4139   if (New->getTLSKind() != Old->getTLSKind()) {
4140     if (!Old->getTLSKind()) {
4141       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4142       Diag(OldLocation, PrevDiag);
4143     } else if (!New->getTLSKind()) {
4144       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4145       Diag(OldLocation, PrevDiag);
4146     } else {
4147       // Do not allow redeclaration to change the variable between requiring
4148       // static and dynamic initialization.
4149       // FIXME: GCC allows this, but uses the TLS keyword on the first
4150       // declaration to determine the kind. Do we need to be compatible here?
4151       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4152         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4153       Diag(OldLocation, PrevDiag);
4154     }
4155   }
4156 
4157   // C++ doesn't have tentative definitions, so go right ahead and check here.
4158   if (getLangOpts().CPlusPlus &&
4159       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4160     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4161         Old->getCanonicalDecl()->isConstexpr()) {
4162       // This definition won't be a definition any more once it's been merged.
4163       Diag(New->getLocation(),
4164            diag::warn_deprecated_redundant_constexpr_static_def);
4165     } else if (VarDecl *Def = Old->getDefinition()) {
4166       if (checkVarDeclRedefinition(Def, New))
4167         return;
4168     }
4169   }
4170 
4171   if (haveIncompatibleLanguageLinkages(Old, New)) {
4172     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4173     Diag(OldLocation, PrevDiag);
4174     New->setInvalidDecl();
4175     return;
4176   }
4177 
4178   // Merge "used" flag.
4179   if (Old->getMostRecentDecl()->isUsed(false))
4180     New->setIsUsed();
4181 
4182   // Keep a chain of previous declarations.
4183   New->setPreviousDecl(Old);
4184   if (NewTemplate)
4185     NewTemplate->setPreviousDecl(OldTemplate);
4186   adjustDeclContextForDeclaratorDecl(New, Old);
4187 
4188   // Inherit access appropriately.
4189   New->setAccess(Old->getAccess());
4190   if (NewTemplate)
4191     NewTemplate->setAccess(New->getAccess());
4192 
4193   if (Old->isInline())
4194     New->setImplicitlyInline();
4195 }
4196 
4197 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4198   SourceManager &SrcMgr = getSourceManager();
4199   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4200   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4201   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4202   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4203   auto &HSI = PP.getHeaderSearchInfo();
4204   StringRef HdrFilename =
4205       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4206 
4207   auto noteFromModuleOrInclude = [&](Module *Mod,
4208                                      SourceLocation IncLoc) -> bool {
4209     // Redefinition errors with modules are common with non modular mapped
4210     // headers, example: a non-modular header H in module A that also gets
4211     // included directly in a TU. Pointing twice to the same header/definition
4212     // is confusing, try to get better diagnostics when modules is on.
4213     if (IncLoc.isValid()) {
4214       if (Mod) {
4215         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4216             << HdrFilename.str() << Mod->getFullModuleName();
4217         if (!Mod->DefinitionLoc.isInvalid())
4218           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4219               << Mod->getFullModuleName();
4220       } else {
4221         Diag(IncLoc, diag::note_redefinition_include_same_file)
4222             << HdrFilename.str();
4223       }
4224       return true;
4225     }
4226 
4227     return false;
4228   };
4229 
4230   // Is it the same file and same offset? Provide more information on why
4231   // this leads to a redefinition error.
4232   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4233     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4234     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4235     bool EmittedDiag =
4236         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4237     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4238 
4239     // If the header has no guards, emit a note suggesting one.
4240     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4241       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4242 
4243     if (EmittedDiag)
4244       return;
4245   }
4246 
4247   // Redefinition coming from different files or couldn't do better above.
4248   if (Old->getLocation().isValid())
4249     Diag(Old->getLocation(), diag::note_previous_definition);
4250 }
4251 
4252 /// We've just determined that \p Old and \p New both appear to be definitions
4253 /// of the same variable. Either diagnose or fix the problem.
4254 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4255   if (!hasVisibleDefinition(Old) &&
4256       (New->getFormalLinkage() == InternalLinkage ||
4257        New->isInline() ||
4258        New->getDescribedVarTemplate() ||
4259        New->getNumTemplateParameterLists() ||
4260        New->getDeclContext()->isDependentContext())) {
4261     // The previous definition is hidden, and multiple definitions are
4262     // permitted (in separate TUs). Demote this to a declaration.
4263     New->demoteThisDefinitionToDeclaration();
4264 
4265     // Make the canonical definition visible.
4266     if (auto *OldTD = Old->getDescribedVarTemplate())
4267       makeMergedDefinitionVisible(OldTD);
4268     makeMergedDefinitionVisible(Old);
4269     return false;
4270   } else {
4271     Diag(New->getLocation(), diag::err_redefinition) << New;
4272     notePreviousDefinition(Old, New->getLocation());
4273     New->setInvalidDecl();
4274     return true;
4275   }
4276 }
4277 
4278 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4279 /// no declarator (e.g. "struct foo;") is parsed.
4280 Decl *
4281 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4282                                  RecordDecl *&AnonRecord) {
4283   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4284                                     AnonRecord);
4285 }
4286 
4287 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4288 // disambiguate entities defined in different scopes.
4289 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4290 // compatibility.
4291 // We will pick our mangling number depending on which version of MSVC is being
4292 // targeted.
4293 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4294   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4295              ? S->getMSCurManglingNumber()
4296              : S->getMSLastManglingNumber();
4297 }
4298 
4299 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4300   if (!Context.getLangOpts().CPlusPlus)
4301     return;
4302 
4303   if (isa<CXXRecordDecl>(Tag->getParent())) {
4304     // If this tag is the direct child of a class, number it if
4305     // it is anonymous.
4306     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4307       return;
4308     MangleNumberingContext &MCtx =
4309         Context.getManglingNumberContext(Tag->getParent());
4310     Context.setManglingNumber(
4311         Tag, MCtx.getManglingNumber(
4312                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4313     return;
4314   }
4315 
4316   // If this tag isn't a direct child of a class, number it if it is local.
4317   MangleNumberingContext *MCtx;
4318   Decl *ManglingContextDecl;
4319   std::tie(MCtx, ManglingContextDecl) =
4320       getCurrentMangleNumberContext(Tag->getDeclContext());
4321   if (MCtx) {
4322     Context.setManglingNumber(
4323         Tag, MCtx->getManglingNumber(
4324                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4325   }
4326 }
4327 
4328 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4329                                         TypedefNameDecl *NewTD) {
4330   if (TagFromDeclSpec->isInvalidDecl())
4331     return;
4332 
4333   // Do nothing if the tag already has a name for linkage purposes.
4334   if (TagFromDeclSpec->hasNameForLinkage())
4335     return;
4336 
4337   // A well-formed anonymous tag must always be a TUK_Definition.
4338   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4339 
4340   // The type must match the tag exactly;  no qualifiers allowed.
4341   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4342                            Context.getTagDeclType(TagFromDeclSpec))) {
4343     if (getLangOpts().CPlusPlus)
4344       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4345     return;
4346   }
4347 
4348   // If we've already computed linkage for the anonymous tag, then
4349   // adding a typedef name for the anonymous decl can change that
4350   // linkage, which might be a serious problem.  Diagnose this as
4351   // unsupported and ignore the typedef name.  TODO: we should
4352   // pursue this as a language defect and establish a formal rule
4353   // for how to handle it.
4354   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4355     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4356 
4357     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4358     tagLoc = getLocForEndOfToken(tagLoc);
4359 
4360     llvm::SmallString<40> textToInsert;
4361     textToInsert += ' ';
4362     textToInsert += NewTD->getIdentifier()->getName();
4363     Diag(tagLoc, diag::note_typedef_changes_linkage)
4364         << FixItHint::CreateInsertion(tagLoc, textToInsert);
4365     return;
4366   }
4367 
4368   // Otherwise, set this is the anon-decl typedef for the tag.
4369   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4370 }
4371 
4372 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4373   switch (T) {
4374   case DeclSpec::TST_class:
4375     return 0;
4376   case DeclSpec::TST_struct:
4377     return 1;
4378   case DeclSpec::TST_interface:
4379     return 2;
4380   case DeclSpec::TST_union:
4381     return 3;
4382   case DeclSpec::TST_enum:
4383     return 4;
4384   default:
4385     llvm_unreachable("unexpected type specifier");
4386   }
4387 }
4388 
4389 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4390 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4391 /// parameters to cope with template friend declarations.
4392 Decl *
4393 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4394                                  MultiTemplateParamsArg TemplateParams,
4395                                  bool IsExplicitInstantiation,
4396                                  RecordDecl *&AnonRecord) {
4397   Decl *TagD = nullptr;
4398   TagDecl *Tag = nullptr;
4399   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4400       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4401       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4402       DS.getTypeSpecType() == DeclSpec::TST_union ||
4403       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4404     TagD = DS.getRepAsDecl();
4405 
4406     if (!TagD) // We probably had an error
4407       return nullptr;
4408 
4409     // Note that the above type specs guarantee that the
4410     // type rep is a Decl, whereas in many of the others
4411     // it's a Type.
4412     if (isa<TagDecl>(TagD))
4413       Tag = cast<TagDecl>(TagD);
4414     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4415       Tag = CTD->getTemplatedDecl();
4416   }
4417 
4418   if (Tag) {
4419     handleTagNumbering(Tag, S);
4420     Tag->setFreeStanding();
4421     if (Tag->isInvalidDecl())
4422       return Tag;
4423   }
4424 
4425   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4426     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4427     // or incomplete types shall not be restrict-qualified."
4428     if (TypeQuals & DeclSpec::TQ_restrict)
4429       Diag(DS.getRestrictSpecLoc(),
4430            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4431            << DS.getSourceRange();
4432   }
4433 
4434   if (DS.isInlineSpecified())
4435     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4436         << getLangOpts().CPlusPlus17;
4437 
4438   if (DS.hasConstexprSpecifier()) {
4439     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4440     // and definitions of functions and variables.
4441     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4442     // the declaration of a function or function template
4443     if (Tag)
4444       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4445           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4446           << DS.getConstexprSpecifier();
4447     else
4448       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4449           << DS.getConstexprSpecifier();
4450     // Don't emit warnings after this error.
4451     return TagD;
4452   }
4453 
4454   DiagnoseFunctionSpecifiers(DS);
4455 
4456   if (DS.isFriendSpecified()) {
4457     // If we're dealing with a decl but not a TagDecl, assume that
4458     // whatever routines created it handled the friendship aspect.
4459     if (TagD && !Tag)
4460       return nullptr;
4461     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4462   }
4463 
4464   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4465   bool IsExplicitSpecialization =
4466     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4467   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4468       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4469       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4470     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4471     // nested-name-specifier unless it is an explicit instantiation
4472     // or an explicit specialization.
4473     //
4474     // FIXME: We allow class template partial specializations here too, per the
4475     // obvious intent of DR1819.
4476     //
4477     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4478     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4479         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4480     return nullptr;
4481   }
4482 
4483   // Track whether this decl-specifier declares anything.
4484   bool DeclaresAnything = true;
4485 
4486   // Handle anonymous struct definitions.
4487   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4488     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4489         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4490       if (getLangOpts().CPlusPlus ||
4491           Record->getDeclContext()->isRecord()) {
4492         // If CurContext is a DeclContext that can contain statements,
4493         // RecursiveASTVisitor won't visit the decls that
4494         // BuildAnonymousStructOrUnion() will put into CurContext.
4495         // Also store them here so that they can be part of the
4496         // DeclStmt that gets created in this case.
4497         // FIXME: Also return the IndirectFieldDecls created by
4498         // BuildAnonymousStructOr union, for the same reason?
4499         if (CurContext->isFunctionOrMethod())
4500           AnonRecord = Record;
4501         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4502                                            Context.getPrintingPolicy());
4503       }
4504 
4505       DeclaresAnything = false;
4506     }
4507   }
4508 
4509   // C11 6.7.2.1p2:
4510   //   A struct-declaration that does not declare an anonymous structure or
4511   //   anonymous union shall contain a struct-declarator-list.
4512   //
4513   // This rule also existed in C89 and C99; the grammar for struct-declaration
4514   // did not permit a struct-declaration without a struct-declarator-list.
4515   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4516       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4517     // Check for Microsoft C extension: anonymous struct/union member.
4518     // Handle 2 kinds of anonymous struct/union:
4519     //   struct STRUCT;
4520     //   union UNION;
4521     // and
4522     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4523     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4524     if ((Tag && Tag->getDeclName()) ||
4525         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4526       RecordDecl *Record = nullptr;
4527       if (Tag)
4528         Record = dyn_cast<RecordDecl>(Tag);
4529       else if (const RecordType *RT =
4530                    DS.getRepAsType().get()->getAsStructureType())
4531         Record = RT->getDecl();
4532       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4533         Record = UT->getDecl();
4534 
4535       if (Record && getLangOpts().MicrosoftExt) {
4536         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4537             << Record->isUnion() << DS.getSourceRange();
4538         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4539       }
4540 
4541       DeclaresAnything = false;
4542     }
4543   }
4544 
4545   // Skip all the checks below if we have a type error.
4546   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4547       (TagD && TagD->isInvalidDecl()))
4548     return TagD;
4549 
4550   if (getLangOpts().CPlusPlus &&
4551       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4552     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4553       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4554           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4555         DeclaresAnything = false;
4556 
4557   if (!DS.isMissingDeclaratorOk()) {
4558     // Customize diagnostic for a typedef missing a name.
4559     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4560       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4561           << DS.getSourceRange();
4562     else
4563       DeclaresAnything = false;
4564   }
4565 
4566   if (DS.isModulePrivateSpecified() &&
4567       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4568     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4569       << Tag->getTagKind()
4570       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4571 
4572   ActOnDocumentableDecl(TagD);
4573 
4574   // C 6.7/2:
4575   //   A declaration [...] shall declare at least a declarator [...], a tag,
4576   //   or the members of an enumeration.
4577   // C++ [dcl.dcl]p3:
4578   //   [If there are no declarators], and except for the declaration of an
4579   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4580   //   names into the program, or shall redeclare a name introduced by a
4581   //   previous declaration.
4582   if (!DeclaresAnything) {
4583     // In C, we allow this as a (popular) extension / bug. Don't bother
4584     // producing further diagnostics for redundant qualifiers after this.
4585     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4586     return TagD;
4587   }
4588 
4589   // C++ [dcl.stc]p1:
4590   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4591   //   init-declarator-list of the declaration shall not be empty.
4592   // C++ [dcl.fct.spec]p1:
4593   //   If a cv-qualifier appears in a decl-specifier-seq, the
4594   //   init-declarator-list of the declaration shall not be empty.
4595   //
4596   // Spurious qualifiers here appear to be valid in C.
4597   unsigned DiagID = diag::warn_standalone_specifier;
4598   if (getLangOpts().CPlusPlus)
4599     DiagID = diag::ext_standalone_specifier;
4600 
4601   // Note that a linkage-specification sets a storage class, but
4602   // 'extern "C" struct foo;' is actually valid and not theoretically
4603   // useless.
4604   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4605     if (SCS == DeclSpec::SCS_mutable)
4606       // Since mutable is not a viable storage class specifier in C, there is
4607       // no reason to treat it as an extension. Instead, diagnose as an error.
4608       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4609     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4610       Diag(DS.getStorageClassSpecLoc(), DiagID)
4611         << DeclSpec::getSpecifierName(SCS);
4612   }
4613 
4614   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4615     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4616       << DeclSpec::getSpecifierName(TSCS);
4617   if (DS.getTypeQualifiers()) {
4618     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4619       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4620     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4621       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4622     // Restrict is covered above.
4623     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4624       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4625     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4626       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4627   }
4628 
4629   // Warn about ignored type attributes, for example:
4630   // __attribute__((aligned)) struct A;
4631   // Attributes should be placed after tag to apply to type declaration.
4632   if (!DS.getAttributes().empty()) {
4633     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4634     if (TypeSpecType == DeclSpec::TST_class ||
4635         TypeSpecType == DeclSpec::TST_struct ||
4636         TypeSpecType == DeclSpec::TST_interface ||
4637         TypeSpecType == DeclSpec::TST_union ||
4638         TypeSpecType == DeclSpec::TST_enum) {
4639       for (const ParsedAttr &AL : DS.getAttributes())
4640         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4641             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4642     }
4643   }
4644 
4645   return TagD;
4646 }
4647 
4648 /// We are trying to inject an anonymous member into the given scope;
4649 /// check if there's an existing declaration that can't be overloaded.
4650 ///
4651 /// \return true if this is a forbidden redeclaration
4652 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4653                                          Scope *S,
4654                                          DeclContext *Owner,
4655                                          DeclarationName Name,
4656                                          SourceLocation NameLoc,
4657                                          bool IsUnion) {
4658   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4659                  Sema::ForVisibleRedeclaration);
4660   if (!SemaRef.LookupName(R, S)) return false;
4661 
4662   // Pick a representative declaration.
4663   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4664   assert(PrevDecl && "Expected a non-null Decl");
4665 
4666   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4667     return false;
4668 
4669   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4670     << IsUnion << Name;
4671   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4672 
4673   return true;
4674 }
4675 
4676 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4677 /// anonymous struct or union AnonRecord into the owning context Owner
4678 /// and scope S. This routine will be invoked just after we realize
4679 /// that an unnamed union or struct is actually an anonymous union or
4680 /// struct, e.g.,
4681 ///
4682 /// @code
4683 /// union {
4684 ///   int i;
4685 ///   float f;
4686 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4687 ///    // f into the surrounding scope.x
4688 /// @endcode
4689 ///
4690 /// This routine is recursive, injecting the names of nested anonymous
4691 /// structs/unions into the owning context and scope as well.
4692 static bool
4693 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4694                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4695                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4696   bool Invalid = false;
4697 
4698   // Look every FieldDecl and IndirectFieldDecl with a name.
4699   for (auto *D : AnonRecord->decls()) {
4700     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4701         cast<NamedDecl>(D)->getDeclName()) {
4702       ValueDecl *VD = cast<ValueDecl>(D);
4703       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4704                                        VD->getLocation(),
4705                                        AnonRecord->isUnion())) {
4706         // C++ [class.union]p2:
4707         //   The names of the members of an anonymous union shall be
4708         //   distinct from the names of any other entity in the
4709         //   scope in which the anonymous union is declared.
4710         Invalid = true;
4711       } else {
4712         // C++ [class.union]p2:
4713         //   For the purpose of name lookup, after the anonymous union
4714         //   definition, the members of the anonymous union are
4715         //   considered to have been defined in the scope in which the
4716         //   anonymous union is declared.
4717         unsigned OldChainingSize = Chaining.size();
4718         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4719           Chaining.append(IF->chain_begin(), IF->chain_end());
4720         else
4721           Chaining.push_back(VD);
4722 
4723         assert(Chaining.size() >= 2);
4724         NamedDecl **NamedChain =
4725           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4726         for (unsigned i = 0; i < Chaining.size(); i++)
4727           NamedChain[i] = Chaining[i];
4728 
4729         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4730             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4731             VD->getType(), {NamedChain, Chaining.size()});
4732 
4733         for (const auto *Attr : VD->attrs())
4734           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4735 
4736         IndirectField->setAccess(AS);
4737         IndirectField->setImplicit();
4738         SemaRef.PushOnScopeChains(IndirectField, S);
4739 
4740         // That includes picking up the appropriate access specifier.
4741         if (AS != AS_none) IndirectField->setAccess(AS);
4742 
4743         Chaining.resize(OldChainingSize);
4744       }
4745     }
4746   }
4747 
4748   return Invalid;
4749 }
4750 
4751 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4752 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4753 /// illegal input values are mapped to SC_None.
4754 static StorageClass
4755 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4756   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4757   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4758          "Parser allowed 'typedef' as storage class VarDecl.");
4759   switch (StorageClassSpec) {
4760   case DeclSpec::SCS_unspecified:    return SC_None;
4761   case DeclSpec::SCS_extern:
4762     if (DS.isExternInLinkageSpec())
4763       return SC_None;
4764     return SC_Extern;
4765   case DeclSpec::SCS_static:         return SC_Static;
4766   case DeclSpec::SCS_auto:           return SC_Auto;
4767   case DeclSpec::SCS_register:       return SC_Register;
4768   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4769     // Illegal SCSs map to None: error reporting is up to the caller.
4770   case DeclSpec::SCS_mutable:        // Fall through.
4771   case DeclSpec::SCS_typedef:        return SC_None;
4772   }
4773   llvm_unreachable("unknown storage class specifier");
4774 }
4775 
4776 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4777   assert(Record->hasInClassInitializer());
4778 
4779   for (const auto *I : Record->decls()) {
4780     const auto *FD = dyn_cast<FieldDecl>(I);
4781     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4782       FD = IFD->getAnonField();
4783     if (FD && FD->hasInClassInitializer())
4784       return FD->getLocation();
4785   }
4786 
4787   llvm_unreachable("couldn't find in-class initializer");
4788 }
4789 
4790 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4791                                       SourceLocation DefaultInitLoc) {
4792   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4793     return;
4794 
4795   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4796   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4797 }
4798 
4799 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4800                                       CXXRecordDecl *AnonUnion) {
4801   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4802     return;
4803 
4804   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4805 }
4806 
4807 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4808 /// anonymous structure or union. Anonymous unions are a C++ feature
4809 /// (C++ [class.union]) and a C11 feature; anonymous structures
4810 /// are a C11 feature and GNU C++ extension.
4811 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4812                                         AccessSpecifier AS,
4813                                         RecordDecl *Record,
4814                                         const PrintingPolicy &Policy) {
4815   DeclContext *Owner = Record->getDeclContext();
4816 
4817   // Diagnose whether this anonymous struct/union is an extension.
4818   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4819     Diag(Record->getLocation(), diag::ext_anonymous_union);
4820   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4821     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4822   else if (!Record->isUnion() && !getLangOpts().C11)
4823     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4824 
4825   // C and C++ require different kinds of checks for anonymous
4826   // structs/unions.
4827   bool Invalid = false;
4828   if (getLangOpts().CPlusPlus) {
4829     const char *PrevSpec = nullptr;
4830     if (Record->isUnion()) {
4831       // C++ [class.union]p6:
4832       // C++17 [class.union.anon]p2:
4833       //   Anonymous unions declared in a named namespace or in the
4834       //   global namespace shall be declared static.
4835       unsigned DiagID;
4836       DeclContext *OwnerScope = Owner->getRedeclContext();
4837       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4838           (OwnerScope->isTranslationUnit() ||
4839            (OwnerScope->isNamespace() &&
4840             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
4841         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4842           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4843 
4844         // Recover by adding 'static'.
4845         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4846                                PrevSpec, DiagID, Policy);
4847       }
4848       // C++ [class.union]p6:
4849       //   A storage class is not allowed in a declaration of an
4850       //   anonymous union in a class scope.
4851       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4852                isa<RecordDecl>(Owner)) {
4853         Diag(DS.getStorageClassSpecLoc(),
4854              diag::err_anonymous_union_with_storage_spec)
4855           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4856 
4857         // Recover by removing the storage specifier.
4858         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4859                                SourceLocation(),
4860                                PrevSpec, DiagID, Context.getPrintingPolicy());
4861       }
4862     }
4863 
4864     // Ignore const/volatile/restrict qualifiers.
4865     if (DS.getTypeQualifiers()) {
4866       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4867         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4868           << Record->isUnion() << "const"
4869           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4870       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4871         Diag(DS.getVolatileSpecLoc(),
4872              diag::ext_anonymous_struct_union_qualified)
4873           << Record->isUnion() << "volatile"
4874           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4875       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4876         Diag(DS.getRestrictSpecLoc(),
4877              diag::ext_anonymous_struct_union_qualified)
4878           << Record->isUnion() << "restrict"
4879           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4880       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4881         Diag(DS.getAtomicSpecLoc(),
4882              diag::ext_anonymous_struct_union_qualified)
4883           << Record->isUnion() << "_Atomic"
4884           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4885       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4886         Diag(DS.getUnalignedSpecLoc(),
4887              diag::ext_anonymous_struct_union_qualified)
4888           << Record->isUnion() << "__unaligned"
4889           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4890 
4891       DS.ClearTypeQualifiers();
4892     }
4893 
4894     // C++ [class.union]p2:
4895     //   The member-specification of an anonymous union shall only
4896     //   define non-static data members. [Note: nested types and
4897     //   functions cannot be declared within an anonymous union. ]
4898     for (auto *Mem : Record->decls()) {
4899       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4900         // C++ [class.union]p3:
4901         //   An anonymous union shall not have private or protected
4902         //   members (clause 11).
4903         assert(FD->getAccess() != AS_none);
4904         if (FD->getAccess() != AS_public) {
4905           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4906             << Record->isUnion() << (FD->getAccess() == AS_protected);
4907           Invalid = true;
4908         }
4909 
4910         // C++ [class.union]p1
4911         //   An object of a class with a non-trivial constructor, a non-trivial
4912         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4913         //   assignment operator cannot be a member of a union, nor can an
4914         //   array of such objects.
4915         if (CheckNontrivialField(FD))
4916           Invalid = true;
4917       } else if (Mem->isImplicit()) {
4918         // Any implicit members are fine.
4919       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4920         // This is a type that showed up in an
4921         // elaborated-type-specifier inside the anonymous struct or
4922         // union, but which actually declares a type outside of the
4923         // anonymous struct or union. It's okay.
4924       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4925         if (!MemRecord->isAnonymousStructOrUnion() &&
4926             MemRecord->getDeclName()) {
4927           // Visual C++ allows type definition in anonymous struct or union.
4928           if (getLangOpts().MicrosoftExt)
4929             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4930               << Record->isUnion();
4931           else {
4932             // This is a nested type declaration.
4933             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4934               << Record->isUnion();
4935             Invalid = true;
4936           }
4937         } else {
4938           // This is an anonymous type definition within another anonymous type.
4939           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4940           // not part of standard C++.
4941           Diag(MemRecord->getLocation(),
4942                diag::ext_anonymous_record_with_anonymous_type)
4943             << Record->isUnion();
4944         }
4945       } else if (isa<AccessSpecDecl>(Mem)) {
4946         // Any access specifier is fine.
4947       } else if (isa<StaticAssertDecl>(Mem)) {
4948         // In C++1z, static_assert declarations are also fine.
4949       } else {
4950         // We have something that isn't a non-static data
4951         // member. Complain about it.
4952         unsigned DK = diag::err_anonymous_record_bad_member;
4953         if (isa<TypeDecl>(Mem))
4954           DK = diag::err_anonymous_record_with_type;
4955         else if (isa<FunctionDecl>(Mem))
4956           DK = diag::err_anonymous_record_with_function;
4957         else if (isa<VarDecl>(Mem))
4958           DK = diag::err_anonymous_record_with_static;
4959 
4960         // Visual C++ allows type definition in anonymous struct or union.
4961         if (getLangOpts().MicrosoftExt &&
4962             DK == diag::err_anonymous_record_with_type)
4963           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4964             << Record->isUnion();
4965         else {
4966           Diag(Mem->getLocation(), DK) << Record->isUnion();
4967           Invalid = true;
4968         }
4969       }
4970     }
4971 
4972     // C++11 [class.union]p8 (DR1460):
4973     //   At most one variant member of a union may have a
4974     //   brace-or-equal-initializer.
4975     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4976         Owner->isRecord())
4977       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4978                                 cast<CXXRecordDecl>(Record));
4979   }
4980 
4981   if (!Record->isUnion() && !Owner->isRecord()) {
4982     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4983       << getLangOpts().CPlusPlus;
4984     Invalid = true;
4985   }
4986 
4987   // C++ [dcl.dcl]p3:
4988   //   [If there are no declarators], and except for the declaration of an
4989   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4990   //   names into the program
4991   // C++ [class.mem]p2:
4992   //   each such member-declaration shall either declare at least one member
4993   //   name of the class or declare at least one unnamed bit-field
4994   //
4995   // For C this is an error even for a named struct, and is diagnosed elsewhere.
4996   if (getLangOpts().CPlusPlus && Record->field_empty())
4997     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4998 
4999   // Mock up a declarator.
5000   Declarator Dc(DS, DeclaratorContext::MemberContext);
5001   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5002   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5003 
5004   // Create a declaration for this anonymous struct/union.
5005   NamedDecl *Anon = nullptr;
5006   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5007     Anon = FieldDecl::Create(
5008         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5009         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5010         /*BitWidth=*/nullptr, /*Mutable=*/false,
5011         /*InitStyle=*/ICIS_NoInit);
5012     Anon->setAccess(AS);
5013     if (getLangOpts().CPlusPlus)
5014       FieldCollector->Add(cast<FieldDecl>(Anon));
5015   } else {
5016     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5017     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5018     if (SCSpec == DeclSpec::SCS_mutable) {
5019       // mutable can only appear on non-static class members, so it's always
5020       // an error here
5021       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5022       Invalid = true;
5023       SC = SC_None;
5024     }
5025 
5026     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5027                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5028                            Context.getTypeDeclType(Record), TInfo, SC);
5029 
5030     // Default-initialize the implicit variable. This initialization will be
5031     // trivial in almost all cases, except if a union member has an in-class
5032     // initializer:
5033     //   union { int n = 0; };
5034     ActOnUninitializedDecl(Anon);
5035   }
5036   Anon->setImplicit();
5037 
5038   // Mark this as an anonymous struct/union type.
5039   Record->setAnonymousStructOrUnion(true);
5040 
5041   // Add the anonymous struct/union object to the current
5042   // context. We'll be referencing this object when we refer to one of
5043   // its members.
5044   Owner->addDecl(Anon);
5045 
5046   // Inject the members of the anonymous struct/union into the owning
5047   // context and into the identifier resolver chain for name lookup
5048   // purposes.
5049   SmallVector<NamedDecl*, 2> Chain;
5050   Chain.push_back(Anon);
5051 
5052   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5053     Invalid = true;
5054 
5055   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5056     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5057       MangleNumberingContext *MCtx;
5058       Decl *ManglingContextDecl;
5059       std::tie(MCtx, ManglingContextDecl) =
5060           getCurrentMangleNumberContext(NewVD->getDeclContext());
5061       if (MCtx) {
5062         Context.setManglingNumber(
5063             NewVD, MCtx->getManglingNumber(
5064                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5065         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5066       }
5067     }
5068   }
5069 
5070   if (Invalid)
5071     Anon->setInvalidDecl();
5072 
5073   return Anon;
5074 }
5075 
5076 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5077 /// Microsoft C anonymous structure.
5078 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5079 /// Example:
5080 ///
5081 /// struct A { int a; };
5082 /// struct B { struct A; int b; };
5083 ///
5084 /// void foo() {
5085 ///   B var;
5086 ///   var.a = 3;
5087 /// }
5088 ///
5089 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5090                                            RecordDecl *Record) {
5091   assert(Record && "expected a record!");
5092 
5093   // Mock up a declarator.
5094   Declarator Dc(DS, DeclaratorContext::TypeNameContext);
5095   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5096   assert(TInfo && "couldn't build declarator info for anonymous struct");
5097 
5098   auto *ParentDecl = cast<RecordDecl>(CurContext);
5099   QualType RecTy = Context.getTypeDeclType(Record);
5100 
5101   // Create a declaration for this anonymous struct.
5102   NamedDecl *Anon =
5103       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5104                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5105                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5106                         /*InitStyle=*/ICIS_NoInit);
5107   Anon->setImplicit();
5108 
5109   // Add the anonymous struct object to the current context.
5110   CurContext->addDecl(Anon);
5111 
5112   // Inject the members of the anonymous struct into the current
5113   // context and into the identifier resolver chain for name lookup
5114   // purposes.
5115   SmallVector<NamedDecl*, 2> Chain;
5116   Chain.push_back(Anon);
5117 
5118   RecordDecl *RecordDef = Record->getDefinition();
5119   if (RequireCompleteType(Anon->getLocation(), RecTy,
5120                           diag::err_field_incomplete) ||
5121       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5122                                           AS_none, Chain)) {
5123     Anon->setInvalidDecl();
5124     ParentDecl->setInvalidDecl();
5125   }
5126 
5127   return Anon;
5128 }
5129 
5130 /// GetNameForDeclarator - Determine the full declaration name for the
5131 /// given Declarator.
5132 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5133   return GetNameFromUnqualifiedId(D.getName());
5134 }
5135 
5136 /// Retrieves the declaration name from a parsed unqualified-id.
5137 DeclarationNameInfo
5138 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5139   DeclarationNameInfo NameInfo;
5140   NameInfo.setLoc(Name.StartLocation);
5141 
5142   switch (Name.getKind()) {
5143 
5144   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5145   case UnqualifiedIdKind::IK_Identifier:
5146     NameInfo.setName(Name.Identifier);
5147     return NameInfo;
5148 
5149   case UnqualifiedIdKind::IK_DeductionGuideName: {
5150     // C++ [temp.deduct.guide]p3:
5151     //   The simple-template-id shall name a class template specialization.
5152     //   The template-name shall be the same identifier as the template-name
5153     //   of the simple-template-id.
5154     // These together intend to imply that the template-name shall name a
5155     // class template.
5156     // FIXME: template<typename T> struct X {};
5157     //        template<typename T> using Y = X<T>;
5158     //        Y(int) -> Y<int>;
5159     //   satisfies these rules but does not name a class template.
5160     TemplateName TN = Name.TemplateName.get().get();
5161     auto *Template = TN.getAsTemplateDecl();
5162     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5163       Diag(Name.StartLocation,
5164            diag::err_deduction_guide_name_not_class_template)
5165         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5166       if (Template)
5167         Diag(Template->getLocation(), diag::note_template_decl_here);
5168       return DeclarationNameInfo();
5169     }
5170 
5171     NameInfo.setName(
5172         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5173     return NameInfo;
5174   }
5175 
5176   case UnqualifiedIdKind::IK_OperatorFunctionId:
5177     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5178                                            Name.OperatorFunctionId.Operator));
5179     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
5180       = Name.OperatorFunctionId.SymbolLocations[0];
5181     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
5182       = Name.EndLocation.getRawEncoding();
5183     return NameInfo;
5184 
5185   case UnqualifiedIdKind::IK_LiteralOperatorId:
5186     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5187                                                            Name.Identifier));
5188     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5189     return NameInfo;
5190 
5191   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5192     TypeSourceInfo *TInfo;
5193     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5194     if (Ty.isNull())
5195       return DeclarationNameInfo();
5196     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5197                                                Context.getCanonicalType(Ty)));
5198     NameInfo.setNamedTypeInfo(TInfo);
5199     return NameInfo;
5200   }
5201 
5202   case UnqualifiedIdKind::IK_ConstructorName: {
5203     TypeSourceInfo *TInfo;
5204     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5205     if (Ty.isNull())
5206       return DeclarationNameInfo();
5207     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5208                                               Context.getCanonicalType(Ty)));
5209     NameInfo.setNamedTypeInfo(TInfo);
5210     return NameInfo;
5211   }
5212 
5213   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5214     // In well-formed code, we can only have a constructor
5215     // template-id that refers to the current context, so go there
5216     // to find the actual type being constructed.
5217     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5218     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5219       return DeclarationNameInfo();
5220 
5221     // Determine the type of the class being constructed.
5222     QualType CurClassType = Context.getTypeDeclType(CurClass);
5223 
5224     // FIXME: Check two things: that the template-id names the same type as
5225     // CurClassType, and that the template-id does not occur when the name
5226     // was qualified.
5227 
5228     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5229                                     Context.getCanonicalType(CurClassType)));
5230     // FIXME: should we retrieve TypeSourceInfo?
5231     NameInfo.setNamedTypeInfo(nullptr);
5232     return NameInfo;
5233   }
5234 
5235   case UnqualifiedIdKind::IK_DestructorName: {
5236     TypeSourceInfo *TInfo;
5237     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5238     if (Ty.isNull())
5239       return DeclarationNameInfo();
5240     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5241                                               Context.getCanonicalType(Ty)));
5242     NameInfo.setNamedTypeInfo(TInfo);
5243     return NameInfo;
5244   }
5245 
5246   case UnqualifiedIdKind::IK_TemplateId: {
5247     TemplateName TName = Name.TemplateId->Template.get();
5248     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5249     return Context.getNameForTemplate(TName, TNameLoc);
5250   }
5251 
5252   } // switch (Name.getKind())
5253 
5254   llvm_unreachable("Unknown name kind");
5255 }
5256 
5257 static QualType getCoreType(QualType Ty) {
5258   do {
5259     if (Ty->isPointerType() || Ty->isReferenceType())
5260       Ty = Ty->getPointeeType();
5261     else if (Ty->isArrayType())
5262       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5263     else
5264       return Ty.withoutLocalFastQualifiers();
5265   } while (true);
5266 }
5267 
5268 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5269 /// and Definition have "nearly" matching parameters. This heuristic is
5270 /// used to improve diagnostics in the case where an out-of-line function
5271 /// definition doesn't match any declaration within the class or namespace.
5272 /// Also sets Params to the list of indices to the parameters that differ
5273 /// between the declaration and the definition. If hasSimilarParameters
5274 /// returns true and Params is empty, then all of the parameters match.
5275 static bool hasSimilarParameters(ASTContext &Context,
5276                                      FunctionDecl *Declaration,
5277                                      FunctionDecl *Definition,
5278                                      SmallVectorImpl<unsigned> &Params) {
5279   Params.clear();
5280   if (Declaration->param_size() != Definition->param_size())
5281     return false;
5282   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5283     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5284     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5285 
5286     // The parameter types are identical
5287     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5288       continue;
5289 
5290     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5291     QualType DefParamBaseTy = getCoreType(DefParamTy);
5292     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5293     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5294 
5295     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5296         (DeclTyName && DeclTyName == DefTyName))
5297       Params.push_back(Idx);
5298     else  // The two parameters aren't even close
5299       return false;
5300   }
5301 
5302   return true;
5303 }
5304 
5305 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5306 /// declarator needs to be rebuilt in the current instantiation.
5307 /// Any bits of declarator which appear before the name are valid for
5308 /// consideration here.  That's specifically the type in the decl spec
5309 /// and the base type in any member-pointer chunks.
5310 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5311                                                     DeclarationName Name) {
5312   // The types we specifically need to rebuild are:
5313   //   - typenames, typeofs, and decltypes
5314   //   - types which will become injected class names
5315   // Of course, we also need to rebuild any type referencing such a
5316   // type.  It's safest to just say "dependent", but we call out a
5317   // few cases here.
5318 
5319   DeclSpec &DS = D.getMutableDeclSpec();
5320   switch (DS.getTypeSpecType()) {
5321   case DeclSpec::TST_typename:
5322   case DeclSpec::TST_typeofType:
5323   case DeclSpec::TST_underlyingType:
5324   case DeclSpec::TST_atomic: {
5325     // Grab the type from the parser.
5326     TypeSourceInfo *TSI = nullptr;
5327     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5328     if (T.isNull() || !T->isDependentType()) break;
5329 
5330     // Make sure there's a type source info.  This isn't really much
5331     // of a waste; most dependent types should have type source info
5332     // attached already.
5333     if (!TSI)
5334       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5335 
5336     // Rebuild the type in the current instantiation.
5337     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5338     if (!TSI) return true;
5339 
5340     // Store the new type back in the decl spec.
5341     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5342     DS.UpdateTypeRep(LocType);
5343     break;
5344   }
5345 
5346   case DeclSpec::TST_decltype:
5347   case DeclSpec::TST_typeofExpr: {
5348     Expr *E = DS.getRepAsExpr();
5349     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5350     if (Result.isInvalid()) return true;
5351     DS.UpdateExprRep(Result.get());
5352     break;
5353   }
5354 
5355   default:
5356     // Nothing to do for these decl specs.
5357     break;
5358   }
5359 
5360   // It doesn't matter what order we do this in.
5361   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5362     DeclaratorChunk &Chunk = D.getTypeObject(I);
5363 
5364     // The only type information in the declarator which can come
5365     // before the declaration name is the base type of a member
5366     // pointer.
5367     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5368       continue;
5369 
5370     // Rebuild the scope specifier in-place.
5371     CXXScopeSpec &SS = Chunk.Mem.Scope();
5372     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5373       return true;
5374   }
5375 
5376   return false;
5377 }
5378 
5379 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5380   D.setFunctionDefinitionKind(FDK_Declaration);
5381   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5382 
5383   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5384       Dcl && Dcl->getDeclContext()->isFileContext())
5385     Dcl->setTopLevelDeclInObjCContainer();
5386 
5387   if (getLangOpts().OpenCL)
5388     setCurrentOpenCLExtensionForDecl(Dcl);
5389 
5390   return Dcl;
5391 }
5392 
5393 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5394 ///   If T is the name of a class, then each of the following shall have a
5395 ///   name different from T:
5396 ///     - every static data member of class T;
5397 ///     - every member function of class T
5398 ///     - every member of class T that is itself a type;
5399 /// \returns true if the declaration name violates these rules.
5400 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5401                                    DeclarationNameInfo NameInfo) {
5402   DeclarationName Name = NameInfo.getName();
5403 
5404   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5405   while (Record && Record->isAnonymousStructOrUnion())
5406     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5407   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5408     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5409     return true;
5410   }
5411 
5412   return false;
5413 }
5414 
5415 /// Diagnose a declaration whose declarator-id has the given
5416 /// nested-name-specifier.
5417 ///
5418 /// \param SS The nested-name-specifier of the declarator-id.
5419 ///
5420 /// \param DC The declaration context to which the nested-name-specifier
5421 /// resolves.
5422 ///
5423 /// \param Name The name of the entity being declared.
5424 ///
5425 /// \param Loc The location of the name of the entity being declared.
5426 ///
5427 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5428 /// we're declaring an explicit / partial specialization / instantiation.
5429 ///
5430 /// \returns true if we cannot safely recover from this error, false otherwise.
5431 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5432                                         DeclarationName Name,
5433                                         SourceLocation Loc, bool IsTemplateId) {
5434   DeclContext *Cur = CurContext;
5435   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5436     Cur = Cur->getParent();
5437 
5438   // If the user provided a superfluous scope specifier that refers back to the
5439   // class in which the entity is already declared, diagnose and ignore it.
5440   //
5441   // class X {
5442   //   void X::f();
5443   // };
5444   //
5445   // Note, it was once ill-formed to give redundant qualification in all
5446   // contexts, but that rule was removed by DR482.
5447   if (Cur->Equals(DC)) {
5448     if (Cur->isRecord()) {
5449       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5450                                       : diag::err_member_extra_qualification)
5451         << Name << FixItHint::CreateRemoval(SS.getRange());
5452       SS.clear();
5453     } else {
5454       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5455     }
5456     return false;
5457   }
5458 
5459   // Check whether the qualifying scope encloses the scope of the original
5460   // declaration. For a template-id, we perform the checks in
5461   // CheckTemplateSpecializationScope.
5462   if (!Cur->Encloses(DC) && !IsTemplateId) {
5463     if (Cur->isRecord())
5464       Diag(Loc, diag::err_member_qualification)
5465         << Name << SS.getRange();
5466     else if (isa<TranslationUnitDecl>(DC))
5467       Diag(Loc, diag::err_invalid_declarator_global_scope)
5468         << Name << SS.getRange();
5469     else if (isa<FunctionDecl>(Cur))
5470       Diag(Loc, diag::err_invalid_declarator_in_function)
5471         << Name << SS.getRange();
5472     else if (isa<BlockDecl>(Cur))
5473       Diag(Loc, diag::err_invalid_declarator_in_block)
5474         << Name << SS.getRange();
5475     else
5476       Diag(Loc, diag::err_invalid_declarator_scope)
5477       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5478 
5479     return true;
5480   }
5481 
5482   if (Cur->isRecord()) {
5483     // Cannot qualify members within a class.
5484     Diag(Loc, diag::err_member_qualification)
5485       << Name << SS.getRange();
5486     SS.clear();
5487 
5488     // C++ constructors and destructors with incorrect scopes can break
5489     // our AST invariants by having the wrong underlying types. If
5490     // that's the case, then drop this declaration entirely.
5491     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5492          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5493         !Context.hasSameType(Name.getCXXNameType(),
5494                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5495       return true;
5496 
5497     return false;
5498   }
5499 
5500   // C++11 [dcl.meaning]p1:
5501   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5502   //   not begin with a decltype-specifer"
5503   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5504   while (SpecLoc.getPrefix())
5505     SpecLoc = SpecLoc.getPrefix();
5506   if (dyn_cast_or_null<DecltypeType>(
5507         SpecLoc.getNestedNameSpecifier()->getAsType()))
5508     Diag(Loc, diag::err_decltype_in_declarator)
5509       << SpecLoc.getTypeLoc().getSourceRange();
5510 
5511   return false;
5512 }
5513 
5514 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5515                                   MultiTemplateParamsArg TemplateParamLists) {
5516   // TODO: consider using NameInfo for diagnostic.
5517   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5518   DeclarationName Name = NameInfo.getName();
5519 
5520   // All of these full declarators require an identifier.  If it doesn't have
5521   // one, the ParsedFreeStandingDeclSpec action should be used.
5522   if (D.isDecompositionDeclarator()) {
5523     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5524   } else if (!Name) {
5525     if (!D.isInvalidType())  // Reject this if we think it is valid.
5526       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5527           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5528     return nullptr;
5529   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5530     return nullptr;
5531 
5532   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5533   // we find one that is.
5534   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5535          (S->getFlags() & Scope::TemplateParamScope) != 0)
5536     S = S->getParent();
5537 
5538   DeclContext *DC = CurContext;
5539   if (D.getCXXScopeSpec().isInvalid())
5540     D.setInvalidType();
5541   else if (D.getCXXScopeSpec().isSet()) {
5542     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5543                                         UPPC_DeclarationQualifier))
5544       return nullptr;
5545 
5546     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5547     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5548     if (!DC || isa<EnumDecl>(DC)) {
5549       // If we could not compute the declaration context, it's because the
5550       // declaration context is dependent but does not refer to a class,
5551       // class template, or class template partial specialization. Complain
5552       // and return early, to avoid the coming semantic disaster.
5553       Diag(D.getIdentifierLoc(),
5554            diag::err_template_qualified_declarator_no_match)
5555         << D.getCXXScopeSpec().getScopeRep()
5556         << D.getCXXScopeSpec().getRange();
5557       return nullptr;
5558     }
5559     bool IsDependentContext = DC->isDependentContext();
5560 
5561     if (!IsDependentContext &&
5562         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5563       return nullptr;
5564 
5565     // If a class is incomplete, do not parse entities inside it.
5566     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5567       Diag(D.getIdentifierLoc(),
5568            diag::err_member_def_undefined_record)
5569         << Name << DC << D.getCXXScopeSpec().getRange();
5570       return nullptr;
5571     }
5572     if (!D.getDeclSpec().isFriendSpecified()) {
5573       if (diagnoseQualifiedDeclaration(
5574               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5575               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5576         if (DC->isRecord())
5577           return nullptr;
5578 
5579         D.setInvalidType();
5580       }
5581     }
5582 
5583     // Check whether we need to rebuild the type of the given
5584     // declaration in the current instantiation.
5585     if (EnteringContext && IsDependentContext &&
5586         TemplateParamLists.size() != 0) {
5587       ContextRAII SavedContext(*this, DC);
5588       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5589         D.setInvalidType();
5590     }
5591   }
5592 
5593   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5594   QualType R = TInfo->getType();
5595 
5596   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5597                                       UPPC_DeclarationType))
5598     D.setInvalidType();
5599 
5600   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5601                         forRedeclarationInCurContext());
5602 
5603   // See if this is a redefinition of a variable in the same scope.
5604   if (!D.getCXXScopeSpec().isSet()) {
5605     bool IsLinkageLookup = false;
5606     bool CreateBuiltins = false;
5607 
5608     // If the declaration we're planning to build will be a function
5609     // or object with linkage, then look for another declaration with
5610     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5611     //
5612     // If the declaration we're planning to build will be declared with
5613     // external linkage in the translation unit, create any builtin with
5614     // the same name.
5615     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5616       /* Do nothing*/;
5617     else if (CurContext->isFunctionOrMethod() &&
5618              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5619               R->isFunctionType())) {
5620       IsLinkageLookup = true;
5621       CreateBuiltins =
5622           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5623     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5624                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5625       CreateBuiltins = true;
5626 
5627     if (IsLinkageLookup) {
5628       Previous.clear(LookupRedeclarationWithLinkage);
5629       Previous.setRedeclarationKind(ForExternalRedeclaration);
5630     }
5631 
5632     LookupName(Previous, S, CreateBuiltins);
5633   } else { // Something like "int foo::x;"
5634     LookupQualifiedName(Previous, DC);
5635 
5636     // C++ [dcl.meaning]p1:
5637     //   When the declarator-id is qualified, the declaration shall refer to a
5638     //  previously declared member of the class or namespace to which the
5639     //  qualifier refers (or, in the case of a namespace, of an element of the
5640     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5641     //  thereof; [...]
5642     //
5643     // Note that we already checked the context above, and that we do not have
5644     // enough information to make sure that Previous contains the declaration
5645     // we want to match. For example, given:
5646     //
5647     //   class X {
5648     //     void f();
5649     //     void f(float);
5650     //   };
5651     //
5652     //   void X::f(int) { } // ill-formed
5653     //
5654     // In this case, Previous will point to the overload set
5655     // containing the two f's declared in X, but neither of them
5656     // matches.
5657 
5658     // C++ [dcl.meaning]p1:
5659     //   [...] the member shall not merely have been introduced by a
5660     //   using-declaration in the scope of the class or namespace nominated by
5661     //   the nested-name-specifier of the declarator-id.
5662     RemoveUsingDecls(Previous);
5663   }
5664 
5665   if (Previous.isSingleResult() &&
5666       Previous.getFoundDecl()->isTemplateParameter()) {
5667     // Maybe we will complain about the shadowed template parameter.
5668     if (!D.isInvalidType())
5669       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5670                                       Previous.getFoundDecl());
5671 
5672     // Just pretend that we didn't see the previous declaration.
5673     Previous.clear();
5674   }
5675 
5676   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5677     // Forget that the previous declaration is the injected-class-name.
5678     Previous.clear();
5679 
5680   // In C++, the previous declaration we find might be a tag type
5681   // (class or enum). In this case, the new declaration will hide the
5682   // tag type. Note that this applies to functions, function templates, and
5683   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5684   if (Previous.isSingleTagDecl() &&
5685       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5686       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5687     Previous.clear();
5688 
5689   // Check that there are no default arguments other than in the parameters
5690   // of a function declaration (C++ only).
5691   if (getLangOpts().CPlusPlus)
5692     CheckExtraCXXDefaultArguments(D);
5693 
5694   NamedDecl *New;
5695 
5696   bool AddToScope = true;
5697   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5698     if (TemplateParamLists.size()) {
5699       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5700       return nullptr;
5701     }
5702 
5703     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5704   } else if (R->isFunctionType()) {
5705     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5706                                   TemplateParamLists,
5707                                   AddToScope);
5708   } else {
5709     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5710                                   AddToScope);
5711   }
5712 
5713   if (!New)
5714     return nullptr;
5715 
5716   // If this has an identifier and is not a function template specialization,
5717   // add it to the scope stack.
5718   if (New->getDeclName() && AddToScope)
5719     PushOnScopeChains(New, S);
5720 
5721   if (isInOpenMPDeclareTargetContext())
5722     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5723 
5724   return New;
5725 }
5726 
5727 /// Helper method to turn variable array types into constant array
5728 /// types in certain situations which would otherwise be errors (for
5729 /// GCC compatibility).
5730 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5731                                                     ASTContext &Context,
5732                                                     bool &SizeIsNegative,
5733                                                     llvm::APSInt &Oversized) {
5734   // This method tries to turn a variable array into a constant
5735   // array even when the size isn't an ICE.  This is necessary
5736   // for compatibility with code that depends on gcc's buggy
5737   // constant expression folding, like struct {char x[(int)(char*)2];}
5738   SizeIsNegative = false;
5739   Oversized = 0;
5740 
5741   if (T->isDependentType())
5742     return QualType();
5743 
5744   QualifierCollector Qs;
5745   const Type *Ty = Qs.strip(T);
5746 
5747   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5748     QualType Pointee = PTy->getPointeeType();
5749     QualType FixedType =
5750         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5751                                             Oversized);
5752     if (FixedType.isNull()) return FixedType;
5753     FixedType = Context.getPointerType(FixedType);
5754     return Qs.apply(Context, FixedType);
5755   }
5756   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5757     QualType Inner = PTy->getInnerType();
5758     QualType FixedType =
5759         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5760                                             Oversized);
5761     if (FixedType.isNull()) return FixedType;
5762     FixedType = Context.getParenType(FixedType);
5763     return Qs.apply(Context, FixedType);
5764   }
5765 
5766   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5767   if (!VLATy)
5768     return QualType();
5769   // FIXME: We should probably handle this case
5770   if (VLATy->getElementType()->isVariablyModifiedType())
5771     return QualType();
5772 
5773   Expr::EvalResult Result;
5774   if (!VLATy->getSizeExpr() ||
5775       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5776     return QualType();
5777 
5778   llvm::APSInt Res = Result.Val.getInt();
5779 
5780   // Check whether the array size is negative.
5781   if (Res.isSigned() && Res.isNegative()) {
5782     SizeIsNegative = true;
5783     return QualType();
5784   }
5785 
5786   // Check whether the array is too large to be addressed.
5787   unsigned ActiveSizeBits
5788     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5789                                               Res);
5790   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5791     Oversized = Res;
5792     return QualType();
5793   }
5794 
5795   return Context.getConstantArrayType(
5796       VLATy->getElementType(), Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
5797 }
5798 
5799 static void
5800 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5801   SrcTL = SrcTL.getUnqualifiedLoc();
5802   DstTL = DstTL.getUnqualifiedLoc();
5803   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5804     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5805     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5806                                       DstPTL.getPointeeLoc());
5807     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5808     return;
5809   }
5810   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5811     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5812     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5813                                       DstPTL.getInnerLoc());
5814     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5815     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5816     return;
5817   }
5818   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5819   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5820   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5821   TypeLoc DstElemTL = DstATL.getElementLoc();
5822   DstElemTL.initializeFullCopy(SrcElemTL);
5823   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5824   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5825   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5826 }
5827 
5828 /// Helper method to turn variable array types into constant array
5829 /// types in certain situations which would otherwise be errors (for
5830 /// GCC compatibility).
5831 static TypeSourceInfo*
5832 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5833                                               ASTContext &Context,
5834                                               bool &SizeIsNegative,
5835                                               llvm::APSInt &Oversized) {
5836   QualType FixedTy
5837     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5838                                           SizeIsNegative, Oversized);
5839   if (FixedTy.isNull())
5840     return nullptr;
5841   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5842   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5843                                     FixedTInfo->getTypeLoc());
5844   return FixedTInfo;
5845 }
5846 
5847 /// Register the given locally-scoped extern "C" declaration so
5848 /// that it can be found later for redeclarations. We include any extern "C"
5849 /// declaration that is not visible in the translation unit here, not just
5850 /// function-scope declarations.
5851 void
5852 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5853   if (!getLangOpts().CPlusPlus &&
5854       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5855     // Don't need to track declarations in the TU in C.
5856     return;
5857 
5858   // Note that we have a locally-scoped external with this name.
5859   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5860 }
5861 
5862 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5863   // FIXME: We can have multiple results via __attribute__((overloadable)).
5864   auto Result = Context.getExternCContextDecl()->lookup(Name);
5865   return Result.empty() ? nullptr : *Result.begin();
5866 }
5867 
5868 /// Diagnose function specifiers on a declaration of an identifier that
5869 /// does not identify a function.
5870 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5871   // FIXME: We should probably indicate the identifier in question to avoid
5872   // confusion for constructs like "virtual int a(), b;"
5873   if (DS.isVirtualSpecified())
5874     Diag(DS.getVirtualSpecLoc(),
5875          diag::err_virtual_non_function);
5876 
5877   if (DS.hasExplicitSpecifier())
5878     Diag(DS.getExplicitSpecLoc(),
5879          diag::err_explicit_non_function);
5880 
5881   if (DS.isNoreturnSpecified())
5882     Diag(DS.getNoreturnSpecLoc(),
5883          diag::err_noreturn_non_function);
5884 }
5885 
5886 NamedDecl*
5887 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5888                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5889   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5890   if (D.getCXXScopeSpec().isSet()) {
5891     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5892       << D.getCXXScopeSpec().getRange();
5893     D.setInvalidType();
5894     // Pretend we didn't see the scope specifier.
5895     DC = CurContext;
5896     Previous.clear();
5897   }
5898 
5899   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5900 
5901   if (D.getDeclSpec().isInlineSpecified())
5902     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5903         << getLangOpts().CPlusPlus17;
5904   if (D.getDeclSpec().hasConstexprSpecifier())
5905     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5906         << 1 << D.getDeclSpec().getConstexprSpecifier();
5907 
5908   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
5909     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
5910       Diag(D.getName().StartLocation,
5911            diag::err_deduction_guide_invalid_specifier)
5912           << "typedef";
5913     else
5914       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5915           << D.getName().getSourceRange();
5916     return nullptr;
5917   }
5918 
5919   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5920   if (!NewTD) return nullptr;
5921 
5922   // Handle attributes prior to checking for duplicates in MergeVarDecl
5923   ProcessDeclAttributes(S, NewTD, D);
5924 
5925   CheckTypedefForVariablyModifiedType(S, NewTD);
5926 
5927   bool Redeclaration = D.isRedeclaration();
5928   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5929   D.setRedeclaration(Redeclaration);
5930   return ND;
5931 }
5932 
5933 void
5934 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5935   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5936   // then it shall have block scope.
5937   // Note that variably modified types must be fixed before merging the decl so
5938   // that redeclarations will match.
5939   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5940   QualType T = TInfo->getType();
5941   if (T->isVariablyModifiedType()) {
5942     setFunctionHasBranchProtectedScope();
5943 
5944     if (S->getFnParent() == nullptr) {
5945       bool SizeIsNegative;
5946       llvm::APSInt Oversized;
5947       TypeSourceInfo *FixedTInfo =
5948         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5949                                                       SizeIsNegative,
5950                                                       Oversized);
5951       if (FixedTInfo) {
5952         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5953         NewTD->setTypeSourceInfo(FixedTInfo);
5954       } else {
5955         if (SizeIsNegative)
5956           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5957         else if (T->isVariableArrayType())
5958           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5959         else if (Oversized.getBoolValue())
5960           Diag(NewTD->getLocation(), diag::err_array_too_large)
5961             << Oversized.toString(10);
5962         else
5963           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5964         NewTD->setInvalidDecl();
5965       }
5966     }
5967   }
5968 }
5969 
5970 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5971 /// declares a typedef-name, either using the 'typedef' type specifier or via
5972 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5973 NamedDecl*
5974 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5975                            LookupResult &Previous, bool &Redeclaration) {
5976 
5977   // Find the shadowed declaration before filtering for scope.
5978   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5979 
5980   // Merge the decl with the existing one if appropriate. If the decl is
5981   // in an outer scope, it isn't the same thing.
5982   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5983                        /*AllowInlineNamespace*/false);
5984   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5985   if (!Previous.empty()) {
5986     Redeclaration = true;
5987     MergeTypedefNameDecl(S, NewTD, Previous);
5988   } else {
5989     inferGslPointerAttribute(NewTD);
5990   }
5991 
5992   if (ShadowedDecl && !Redeclaration)
5993     CheckShadow(NewTD, ShadowedDecl, Previous);
5994 
5995   // If this is the C FILE type, notify the AST context.
5996   if (IdentifierInfo *II = NewTD->getIdentifier())
5997     if (!NewTD->isInvalidDecl() &&
5998         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5999       if (II->isStr("FILE"))
6000         Context.setFILEDecl(NewTD);
6001       else if (II->isStr("jmp_buf"))
6002         Context.setjmp_bufDecl(NewTD);
6003       else if (II->isStr("sigjmp_buf"))
6004         Context.setsigjmp_bufDecl(NewTD);
6005       else if (II->isStr("ucontext_t"))
6006         Context.setucontext_tDecl(NewTD);
6007     }
6008 
6009   return NewTD;
6010 }
6011 
6012 /// Determines whether the given declaration is an out-of-scope
6013 /// previous declaration.
6014 ///
6015 /// This routine should be invoked when name lookup has found a
6016 /// previous declaration (PrevDecl) that is not in the scope where a
6017 /// new declaration by the same name is being introduced. If the new
6018 /// declaration occurs in a local scope, previous declarations with
6019 /// linkage may still be considered previous declarations (C99
6020 /// 6.2.2p4-5, C++ [basic.link]p6).
6021 ///
6022 /// \param PrevDecl the previous declaration found by name
6023 /// lookup
6024 ///
6025 /// \param DC the context in which the new declaration is being
6026 /// declared.
6027 ///
6028 /// \returns true if PrevDecl is an out-of-scope previous declaration
6029 /// for a new delcaration with the same name.
6030 static bool
6031 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6032                                 ASTContext &Context) {
6033   if (!PrevDecl)
6034     return false;
6035 
6036   if (!PrevDecl->hasLinkage())
6037     return false;
6038 
6039   if (Context.getLangOpts().CPlusPlus) {
6040     // C++ [basic.link]p6:
6041     //   If there is a visible declaration of an entity with linkage
6042     //   having the same name and type, ignoring entities declared
6043     //   outside the innermost enclosing namespace scope, the block
6044     //   scope declaration declares that same entity and receives the
6045     //   linkage of the previous declaration.
6046     DeclContext *OuterContext = DC->getRedeclContext();
6047     if (!OuterContext->isFunctionOrMethod())
6048       // This rule only applies to block-scope declarations.
6049       return false;
6050 
6051     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6052     if (PrevOuterContext->isRecord())
6053       // We found a member function: ignore it.
6054       return false;
6055 
6056     // Find the innermost enclosing namespace for the new and
6057     // previous declarations.
6058     OuterContext = OuterContext->getEnclosingNamespaceContext();
6059     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6060 
6061     // The previous declaration is in a different namespace, so it
6062     // isn't the same function.
6063     if (!OuterContext->Equals(PrevOuterContext))
6064       return false;
6065   }
6066 
6067   return true;
6068 }
6069 
6070 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6071   CXXScopeSpec &SS = D.getCXXScopeSpec();
6072   if (!SS.isSet()) return;
6073   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6074 }
6075 
6076 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6077   QualType type = decl->getType();
6078   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6079   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6080     // Various kinds of declaration aren't allowed to be __autoreleasing.
6081     unsigned kind = -1U;
6082     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6083       if (var->hasAttr<BlocksAttr>())
6084         kind = 0; // __block
6085       else if (!var->hasLocalStorage())
6086         kind = 1; // global
6087     } else if (isa<ObjCIvarDecl>(decl)) {
6088       kind = 3; // ivar
6089     } else if (isa<FieldDecl>(decl)) {
6090       kind = 2; // field
6091     }
6092 
6093     if (kind != -1U) {
6094       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6095         << kind;
6096     }
6097   } else if (lifetime == Qualifiers::OCL_None) {
6098     // Try to infer lifetime.
6099     if (!type->isObjCLifetimeType())
6100       return false;
6101 
6102     lifetime = type->getObjCARCImplicitLifetime();
6103     type = Context.getLifetimeQualifiedType(type, lifetime);
6104     decl->setType(type);
6105   }
6106 
6107   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6108     // Thread-local variables cannot have lifetime.
6109     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6110         var->getTLSKind()) {
6111       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6112         << var->getType();
6113       return true;
6114     }
6115   }
6116 
6117   return false;
6118 }
6119 
6120 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6121   if (Decl->getType().getQualifiers().hasAddressSpace())
6122     return;
6123   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6124     QualType Type = Var->getType();
6125     if (Type->isSamplerT() || Type->isVoidType())
6126       return;
6127     LangAS ImplAS = LangAS::opencl_private;
6128     if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) &&
6129         Var->hasGlobalStorage())
6130       ImplAS = LangAS::opencl_global;
6131     // If the original type from a decayed type is an array type and that array
6132     // type has no address space yet, deduce it now.
6133     if (auto DT = dyn_cast<DecayedType>(Type)) {
6134       auto OrigTy = DT->getOriginalType();
6135       if (!OrigTy.getQualifiers().hasAddressSpace() && OrigTy->isArrayType()) {
6136         // Add the address space to the original array type and then propagate
6137         // that to the element type through `getAsArrayType`.
6138         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6139         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6140         // Re-generate the decayed type.
6141         Type = Context.getDecayedType(OrigTy);
6142       }
6143     }
6144     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6145     // Apply any qualifiers (including address space) from the array type to
6146     // the element type. This implements C99 6.7.3p8: "If the specification of
6147     // an array type includes any type qualifiers, the element type is so
6148     // qualified, not the array type."
6149     if (Type->isArrayType())
6150       Type = QualType(Context.getAsArrayType(Type), 0);
6151     Decl->setType(Type);
6152   }
6153 }
6154 
6155 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6156   // Ensure that an auto decl is deduced otherwise the checks below might cache
6157   // the wrong linkage.
6158   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6159 
6160   // 'weak' only applies to declarations with external linkage.
6161   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6162     if (!ND.isExternallyVisible()) {
6163       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6164       ND.dropAttr<WeakAttr>();
6165     }
6166   }
6167   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6168     if (ND.isExternallyVisible()) {
6169       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6170       ND.dropAttr<WeakRefAttr>();
6171       ND.dropAttr<AliasAttr>();
6172     }
6173   }
6174 
6175   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6176     if (VD->hasInit()) {
6177       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6178         assert(VD->isThisDeclarationADefinition() &&
6179                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6180         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6181         VD->dropAttr<AliasAttr>();
6182       }
6183     }
6184   }
6185 
6186   // 'selectany' only applies to externally visible variable declarations.
6187   // It does not apply to functions.
6188   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6189     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6190       S.Diag(Attr->getLocation(),
6191              diag::err_attribute_selectany_non_extern_data);
6192       ND.dropAttr<SelectAnyAttr>();
6193     }
6194   }
6195 
6196   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6197     auto *VD = dyn_cast<VarDecl>(&ND);
6198     bool IsAnonymousNS = false;
6199     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6200     if (VD) {
6201       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6202       while (NS && !IsAnonymousNS) {
6203         IsAnonymousNS = NS->isAnonymousNamespace();
6204         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6205       }
6206     }
6207     // dll attributes require external linkage. Static locals may have external
6208     // linkage but still cannot be explicitly imported or exported.
6209     // In Microsoft mode, a variable defined in anonymous namespace must have
6210     // external linkage in order to be exported.
6211     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6212     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6213         (!AnonNSInMicrosoftMode &&
6214          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6215       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6216         << &ND << Attr;
6217       ND.setInvalidDecl();
6218     }
6219   }
6220 
6221   // Virtual functions cannot be marked as 'notail'.
6222   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
6223     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
6224       if (MD->isVirtual()) {
6225         S.Diag(ND.getLocation(),
6226                diag::err_invalid_attribute_on_virtual_function)
6227             << Attr;
6228         ND.dropAttr<NotTailCalledAttr>();
6229       }
6230 
6231   // Check the attributes on the function type, if any.
6232   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6233     // Don't declare this variable in the second operand of the for-statement;
6234     // GCC miscompiles that by ending its lifetime before evaluating the
6235     // third operand. See gcc.gnu.org/PR86769.
6236     AttributedTypeLoc ATL;
6237     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6238          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6239          TL = ATL.getModifiedLoc()) {
6240       // The [[lifetimebound]] attribute can be applied to the implicit object
6241       // parameter of a non-static member function (other than a ctor or dtor)
6242       // by applying it to the function type.
6243       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6244         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6245         if (!MD || MD->isStatic()) {
6246           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6247               << !MD << A->getRange();
6248         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6249           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6250               << isa<CXXDestructorDecl>(MD) << A->getRange();
6251         }
6252       }
6253     }
6254   }
6255 }
6256 
6257 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6258                                            NamedDecl *NewDecl,
6259                                            bool IsSpecialization,
6260                                            bool IsDefinition) {
6261   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6262     return;
6263 
6264   bool IsTemplate = false;
6265   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6266     OldDecl = OldTD->getTemplatedDecl();
6267     IsTemplate = true;
6268     if (!IsSpecialization)
6269       IsDefinition = false;
6270   }
6271   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6272     NewDecl = NewTD->getTemplatedDecl();
6273     IsTemplate = true;
6274   }
6275 
6276   if (!OldDecl || !NewDecl)
6277     return;
6278 
6279   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6280   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6281   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6282   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6283 
6284   // dllimport and dllexport are inheritable attributes so we have to exclude
6285   // inherited attribute instances.
6286   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6287                     (NewExportAttr && !NewExportAttr->isInherited());
6288 
6289   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6290   // the only exception being explicit specializations.
6291   // Implicitly generated declarations are also excluded for now because there
6292   // is no other way to switch these to use dllimport or dllexport.
6293   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6294 
6295   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6296     // Allow with a warning for free functions and global variables.
6297     bool JustWarn = false;
6298     if (!OldDecl->isCXXClassMember()) {
6299       auto *VD = dyn_cast<VarDecl>(OldDecl);
6300       if (VD && !VD->getDescribedVarTemplate())
6301         JustWarn = true;
6302       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6303       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6304         JustWarn = true;
6305     }
6306 
6307     // We cannot change a declaration that's been used because IR has already
6308     // been emitted. Dllimported functions will still work though (modulo
6309     // address equality) as they can use the thunk.
6310     if (OldDecl->isUsed())
6311       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6312         JustWarn = false;
6313 
6314     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6315                                : diag::err_attribute_dll_redeclaration;
6316     S.Diag(NewDecl->getLocation(), DiagID)
6317         << NewDecl
6318         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6319     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6320     if (!JustWarn) {
6321       NewDecl->setInvalidDecl();
6322       return;
6323     }
6324   }
6325 
6326   // A redeclaration is not allowed to drop a dllimport attribute, the only
6327   // exceptions being inline function definitions (except for function
6328   // templates), local extern declarations, qualified friend declarations or
6329   // special MSVC extension: in the last case, the declaration is treated as if
6330   // it were marked dllexport.
6331   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6332   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6333   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6334     // Ignore static data because out-of-line definitions are diagnosed
6335     // separately.
6336     IsStaticDataMember = VD->isStaticDataMember();
6337     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6338                    VarDecl::DeclarationOnly;
6339   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6340     IsInline = FD->isInlined();
6341     IsQualifiedFriend = FD->getQualifier() &&
6342                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6343   }
6344 
6345   if (OldImportAttr && !HasNewAttr &&
6346       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6347       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6348     if (IsMicrosoft && IsDefinition) {
6349       S.Diag(NewDecl->getLocation(),
6350              diag::warn_redeclaration_without_import_attribute)
6351           << NewDecl;
6352       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6353       NewDecl->dropAttr<DLLImportAttr>();
6354       NewDecl->addAttr(
6355           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6356     } else {
6357       S.Diag(NewDecl->getLocation(),
6358              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6359           << NewDecl << OldImportAttr;
6360       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6361       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6362       OldDecl->dropAttr<DLLImportAttr>();
6363       NewDecl->dropAttr<DLLImportAttr>();
6364     }
6365   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6366     // In MinGW, seeing a function declared inline drops the dllimport
6367     // attribute.
6368     OldDecl->dropAttr<DLLImportAttr>();
6369     NewDecl->dropAttr<DLLImportAttr>();
6370     S.Diag(NewDecl->getLocation(),
6371            diag::warn_dllimport_dropped_from_inline_function)
6372         << NewDecl << OldImportAttr;
6373   }
6374 
6375   // A specialization of a class template member function is processed here
6376   // since it's a redeclaration. If the parent class is dllexport, the
6377   // specialization inherits that attribute. This doesn't happen automatically
6378   // since the parent class isn't instantiated until later.
6379   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6380     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6381         !NewImportAttr && !NewExportAttr) {
6382       if (const DLLExportAttr *ParentExportAttr =
6383               MD->getParent()->getAttr<DLLExportAttr>()) {
6384         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6385         NewAttr->setInherited(true);
6386         NewDecl->addAttr(NewAttr);
6387       }
6388     }
6389   }
6390 }
6391 
6392 /// Given that we are within the definition of the given function,
6393 /// will that definition behave like C99's 'inline', where the
6394 /// definition is discarded except for optimization purposes?
6395 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6396   // Try to avoid calling GetGVALinkageForFunction.
6397 
6398   // All cases of this require the 'inline' keyword.
6399   if (!FD->isInlined()) return false;
6400 
6401   // This is only possible in C++ with the gnu_inline attribute.
6402   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6403     return false;
6404 
6405   // Okay, go ahead and call the relatively-more-expensive function.
6406   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6407 }
6408 
6409 /// Determine whether a variable is extern "C" prior to attaching
6410 /// an initializer. We can't just call isExternC() here, because that
6411 /// will also compute and cache whether the declaration is externally
6412 /// visible, which might change when we attach the initializer.
6413 ///
6414 /// This can only be used if the declaration is known to not be a
6415 /// redeclaration of an internal linkage declaration.
6416 ///
6417 /// For instance:
6418 ///
6419 ///   auto x = []{};
6420 ///
6421 /// Attaching the initializer here makes this declaration not externally
6422 /// visible, because its type has internal linkage.
6423 ///
6424 /// FIXME: This is a hack.
6425 template<typename T>
6426 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6427   if (S.getLangOpts().CPlusPlus) {
6428     // In C++, the overloadable attribute negates the effects of extern "C".
6429     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6430       return false;
6431 
6432     // So do CUDA's host/device attributes.
6433     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6434                                  D->template hasAttr<CUDAHostAttr>()))
6435       return false;
6436   }
6437   return D->isExternC();
6438 }
6439 
6440 static bool shouldConsiderLinkage(const VarDecl *VD) {
6441   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6442   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6443       isa<OMPDeclareMapperDecl>(DC))
6444     return VD->hasExternalStorage();
6445   if (DC->isFileContext())
6446     return true;
6447   if (DC->isRecord())
6448     return false;
6449   llvm_unreachable("Unexpected context");
6450 }
6451 
6452 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6453   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6454   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6455       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6456     return true;
6457   if (DC->isRecord())
6458     return false;
6459   llvm_unreachable("Unexpected context");
6460 }
6461 
6462 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6463                           ParsedAttr::Kind Kind) {
6464   // Check decl attributes on the DeclSpec.
6465   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6466     return true;
6467 
6468   // Walk the declarator structure, checking decl attributes that were in a type
6469   // position to the decl itself.
6470   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6471     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6472       return true;
6473   }
6474 
6475   // Finally, check attributes on the decl itself.
6476   return PD.getAttributes().hasAttribute(Kind);
6477 }
6478 
6479 /// Adjust the \c DeclContext for a function or variable that might be a
6480 /// function-local external declaration.
6481 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6482   if (!DC->isFunctionOrMethod())
6483     return false;
6484 
6485   // If this is a local extern function or variable declared within a function
6486   // template, don't add it into the enclosing namespace scope until it is
6487   // instantiated; it might have a dependent type right now.
6488   if (DC->isDependentContext())
6489     return true;
6490 
6491   // C++11 [basic.link]p7:
6492   //   When a block scope declaration of an entity with linkage is not found to
6493   //   refer to some other declaration, then that entity is a member of the
6494   //   innermost enclosing namespace.
6495   //
6496   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6497   // semantically-enclosing namespace, not a lexically-enclosing one.
6498   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6499     DC = DC->getParent();
6500   return true;
6501 }
6502 
6503 /// Returns true if given declaration has external C language linkage.
6504 static bool isDeclExternC(const Decl *D) {
6505   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6506     return FD->isExternC();
6507   if (const auto *VD = dyn_cast<VarDecl>(D))
6508     return VD->isExternC();
6509 
6510   llvm_unreachable("Unknown type of decl!");
6511 }
6512 /// Returns true if there hasn't been any invalid type diagnosed.
6513 static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D,
6514                                 DeclContext *DC, QualType R) {
6515   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6516   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6517   // argument.
6518   if (R->isImageType() || R->isPipeType()) {
6519     Se.Diag(D.getIdentifierLoc(),
6520             diag::err_opencl_type_can_only_be_used_as_function_parameter)
6521         << R;
6522     D.setInvalidType();
6523     return false;
6524   }
6525 
6526   // OpenCL v1.2 s6.9.r:
6527   // The event type cannot be used to declare a program scope variable.
6528   // OpenCL v2.0 s6.9.q:
6529   // The clk_event_t and reserve_id_t types cannot be declared in program
6530   // scope.
6531   if (NULL == S->getParent()) {
6532     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6533       Se.Diag(D.getIdentifierLoc(),
6534               diag::err_invalid_type_for_program_scope_var)
6535           << R;
6536       D.setInvalidType();
6537       return false;
6538     }
6539   }
6540 
6541   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6542   QualType NR = R;
6543   while (NR->isPointerType()) {
6544     if (NR->isFunctionPointerType()) {
6545       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6546       D.setInvalidType();
6547       return false;
6548     }
6549     NR = NR->getPointeeType();
6550   }
6551 
6552   if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6553     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6554     // half array type (unless the cl_khr_fp16 extension is enabled).
6555     if (Se.Context.getBaseElementType(R)->isHalfType()) {
6556       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6557       D.setInvalidType();
6558       return false;
6559     }
6560   }
6561 
6562   // OpenCL v1.2 s6.9.r:
6563   // The event type cannot be used with the __local, __constant and __global
6564   // address space qualifiers.
6565   if (R->isEventT()) {
6566     if (R.getAddressSpace() != LangAS::opencl_private) {
6567       Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6568       D.setInvalidType();
6569       return false;
6570     }
6571   }
6572 
6573   // C++ for OpenCL does not allow the thread_local storage qualifier.
6574   // OpenCL C does not support thread_local either, and
6575   // also reject all other thread storage class specifiers.
6576   DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6577   if (TSC != TSCS_unspecified) {
6578     bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus;
6579     Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6580             diag::err_opencl_unknown_type_specifier)
6581         << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString()
6582         << DeclSpec::getSpecifierName(TSC) << 1;
6583     D.setInvalidType();
6584     return false;
6585   }
6586 
6587   if (R->isSamplerT()) {
6588     // OpenCL v1.2 s6.9.b p4:
6589     // The sampler type cannot be used with the __local and __global address
6590     // space qualifiers.
6591     if (R.getAddressSpace() == LangAS::opencl_local ||
6592         R.getAddressSpace() == LangAS::opencl_global) {
6593       Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6594       D.setInvalidType();
6595     }
6596 
6597     // OpenCL v1.2 s6.12.14.1:
6598     // A global sampler must be declared with either the constant address
6599     // space qualifier or with the const qualifier.
6600     if (DC->isTranslationUnit() &&
6601         !(R.getAddressSpace() == LangAS::opencl_constant ||
6602           R.isConstQualified())) {
6603       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6604       D.setInvalidType();
6605     }
6606     if (D.isInvalidType())
6607       return false;
6608   }
6609   return true;
6610 }
6611 
6612 NamedDecl *Sema::ActOnVariableDeclarator(
6613     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6614     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6615     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6616   QualType R = TInfo->getType();
6617   DeclarationName Name = GetNameForDeclarator(D).getName();
6618 
6619   IdentifierInfo *II = Name.getAsIdentifierInfo();
6620 
6621   if (D.isDecompositionDeclarator()) {
6622     // Take the name of the first declarator as our name for diagnostic
6623     // purposes.
6624     auto &Decomp = D.getDecompositionDeclarator();
6625     if (!Decomp.bindings().empty()) {
6626       II = Decomp.bindings()[0].Name;
6627       Name = II;
6628     }
6629   } else if (!II) {
6630     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6631     return nullptr;
6632   }
6633 
6634 
6635   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6636   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6637 
6638   // dllimport globals without explicit storage class are treated as extern. We
6639   // have to change the storage class this early to get the right DeclContext.
6640   if (SC == SC_None && !DC->isRecord() &&
6641       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6642       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6643     SC = SC_Extern;
6644 
6645   DeclContext *OriginalDC = DC;
6646   bool IsLocalExternDecl = SC == SC_Extern &&
6647                            adjustContextForLocalExternDecl(DC);
6648 
6649   if (SCSpec == DeclSpec::SCS_mutable) {
6650     // mutable can only appear on non-static class members, so it's always
6651     // an error here
6652     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6653     D.setInvalidType();
6654     SC = SC_None;
6655   }
6656 
6657   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6658       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6659                               D.getDeclSpec().getStorageClassSpecLoc())) {
6660     // In C++11, the 'register' storage class specifier is deprecated.
6661     // Suppress the warning in system macros, it's used in macros in some
6662     // popular C system headers, such as in glibc's htonl() macro.
6663     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6664          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6665                                    : diag::warn_deprecated_register)
6666       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6667   }
6668 
6669   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6670 
6671   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6672     // C99 6.9p2: The storage-class specifiers auto and register shall not
6673     // appear in the declaration specifiers in an external declaration.
6674     // Global Register+Asm is a GNU extension we support.
6675     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6676       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6677       D.setInvalidType();
6678     }
6679   }
6680 
6681   bool IsMemberSpecialization = false;
6682   bool IsVariableTemplateSpecialization = false;
6683   bool IsPartialSpecialization = false;
6684   bool IsVariableTemplate = false;
6685   VarDecl *NewVD = nullptr;
6686   VarTemplateDecl *NewTemplate = nullptr;
6687   TemplateParameterList *TemplateParams = nullptr;
6688   if (!getLangOpts().CPlusPlus) {
6689     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6690                             II, R, TInfo, SC);
6691 
6692     if (R->getContainedDeducedType())
6693       ParsingInitForAutoVars.insert(NewVD);
6694 
6695     if (D.isInvalidType())
6696       NewVD->setInvalidDecl();
6697 
6698     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
6699         NewVD->hasLocalStorage())
6700       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
6701                             NTCUC_AutoVar, NTCUK_Destruct);
6702   } else {
6703     bool Invalid = false;
6704 
6705     if (DC->isRecord() && !CurContext->isRecord()) {
6706       // This is an out-of-line definition of a static data member.
6707       switch (SC) {
6708       case SC_None:
6709         break;
6710       case SC_Static:
6711         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6712              diag::err_static_out_of_line)
6713           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6714         break;
6715       case SC_Auto:
6716       case SC_Register:
6717       case SC_Extern:
6718         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6719         // to names of variables declared in a block or to function parameters.
6720         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6721         // of class members
6722 
6723         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6724              diag::err_storage_class_for_static_member)
6725           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6726         break;
6727       case SC_PrivateExtern:
6728         llvm_unreachable("C storage class in c++!");
6729       }
6730     }
6731 
6732     if (SC == SC_Static && CurContext->isRecord()) {
6733       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6734         if (RD->isLocalClass())
6735           Diag(D.getIdentifierLoc(),
6736                diag::err_static_data_member_not_allowed_in_local_class)
6737             << Name << RD->getDeclName();
6738 
6739         // C++98 [class.union]p1: If a union contains a static data member,
6740         // the program is ill-formed. C++11 drops this restriction.
6741         if (RD->isUnion())
6742           Diag(D.getIdentifierLoc(),
6743                getLangOpts().CPlusPlus11
6744                  ? diag::warn_cxx98_compat_static_data_member_in_union
6745                  : diag::ext_static_data_member_in_union) << Name;
6746         // We conservatively disallow static data members in anonymous structs.
6747         else if (!RD->getDeclName())
6748           Diag(D.getIdentifierLoc(),
6749                diag::err_static_data_member_not_allowed_in_anon_struct)
6750             << Name << RD->isUnion();
6751       }
6752     }
6753 
6754     // Match up the template parameter lists with the scope specifier, then
6755     // determine whether we have a template or a template specialization.
6756     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6757         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6758         D.getCXXScopeSpec(),
6759         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6760             ? D.getName().TemplateId
6761             : nullptr,
6762         TemplateParamLists,
6763         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6764 
6765     if (TemplateParams) {
6766       if (!TemplateParams->size() &&
6767           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6768         // There is an extraneous 'template<>' for this variable. Complain
6769         // about it, but allow the declaration of the variable.
6770         Diag(TemplateParams->getTemplateLoc(),
6771              diag::err_template_variable_noparams)
6772           << II
6773           << SourceRange(TemplateParams->getTemplateLoc(),
6774                          TemplateParams->getRAngleLoc());
6775         TemplateParams = nullptr;
6776       } else {
6777         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6778           // This is an explicit specialization or a partial specialization.
6779           // FIXME: Check that we can declare a specialization here.
6780           IsVariableTemplateSpecialization = true;
6781           IsPartialSpecialization = TemplateParams->size() > 0;
6782         } else { // if (TemplateParams->size() > 0)
6783           // This is a template declaration.
6784           IsVariableTemplate = true;
6785 
6786           // Check that we can declare a template here.
6787           if (CheckTemplateDeclScope(S, TemplateParams))
6788             return nullptr;
6789 
6790           // Only C++1y supports variable templates (N3651).
6791           Diag(D.getIdentifierLoc(),
6792                getLangOpts().CPlusPlus14
6793                    ? diag::warn_cxx11_compat_variable_template
6794                    : diag::ext_variable_template);
6795         }
6796       }
6797     } else {
6798       assert((Invalid ||
6799               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
6800              "should have a 'template<>' for this decl");
6801     }
6802 
6803     if (IsVariableTemplateSpecialization) {
6804       SourceLocation TemplateKWLoc =
6805           TemplateParamLists.size() > 0
6806               ? TemplateParamLists[0]->getTemplateLoc()
6807               : SourceLocation();
6808       DeclResult Res = ActOnVarTemplateSpecialization(
6809           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6810           IsPartialSpecialization);
6811       if (Res.isInvalid())
6812         return nullptr;
6813       NewVD = cast<VarDecl>(Res.get());
6814       AddToScope = false;
6815     } else if (D.isDecompositionDeclarator()) {
6816       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
6817                                         D.getIdentifierLoc(), R, TInfo, SC,
6818                                         Bindings);
6819     } else
6820       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
6821                               D.getIdentifierLoc(), II, R, TInfo, SC);
6822 
6823     // If this is supposed to be a variable template, create it as such.
6824     if (IsVariableTemplate) {
6825       NewTemplate =
6826           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6827                                   TemplateParams, NewVD);
6828       NewVD->setDescribedVarTemplate(NewTemplate);
6829     }
6830 
6831     // If this decl has an auto type in need of deduction, make a note of the
6832     // Decl so we can diagnose uses of it in its own initializer.
6833     if (R->getContainedDeducedType())
6834       ParsingInitForAutoVars.insert(NewVD);
6835 
6836     if (D.isInvalidType() || Invalid) {
6837       NewVD->setInvalidDecl();
6838       if (NewTemplate)
6839         NewTemplate->setInvalidDecl();
6840     }
6841 
6842     SetNestedNameSpecifier(*this, NewVD, D);
6843 
6844     // If we have any template parameter lists that don't directly belong to
6845     // the variable (matching the scope specifier), store them.
6846     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6847     if (TemplateParamLists.size() > VDTemplateParamLists)
6848       NewVD->setTemplateParameterListsInfo(
6849           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6850   }
6851 
6852   if (D.getDeclSpec().isInlineSpecified()) {
6853     if (!getLangOpts().CPlusPlus) {
6854       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6855           << 0;
6856     } else if (CurContext->isFunctionOrMethod()) {
6857       // 'inline' is not allowed on block scope variable declaration.
6858       Diag(D.getDeclSpec().getInlineSpecLoc(),
6859            diag::err_inline_declaration_block_scope) << Name
6860         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6861     } else {
6862       Diag(D.getDeclSpec().getInlineSpecLoc(),
6863            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
6864                                      : diag::ext_inline_variable);
6865       NewVD->setInlineSpecified();
6866     }
6867   }
6868 
6869   // Set the lexical context. If the declarator has a C++ scope specifier, the
6870   // lexical context will be different from the semantic context.
6871   NewVD->setLexicalDeclContext(CurContext);
6872   if (NewTemplate)
6873     NewTemplate->setLexicalDeclContext(CurContext);
6874 
6875   if (IsLocalExternDecl) {
6876     if (D.isDecompositionDeclarator())
6877       for (auto *B : Bindings)
6878         B->setLocalExternDecl();
6879     else
6880       NewVD->setLocalExternDecl();
6881   }
6882 
6883   bool EmitTLSUnsupportedError = false;
6884   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6885     // C++11 [dcl.stc]p4:
6886     //   When thread_local is applied to a variable of block scope the
6887     //   storage-class-specifier static is implied if it does not appear
6888     //   explicitly.
6889     // Core issue: 'static' is not implied if the variable is declared
6890     //   'extern'.
6891     if (NewVD->hasLocalStorage() &&
6892         (SCSpec != DeclSpec::SCS_unspecified ||
6893          TSCS != DeclSpec::TSCS_thread_local ||
6894          !DC->isFunctionOrMethod()))
6895       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6896            diag::err_thread_non_global)
6897         << DeclSpec::getSpecifierName(TSCS);
6898     else if (!Context.getTargetInfo().isTLSSupported()) {
6899       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6900         // Postpone error emission until we've collected attributes required to
6901         // figure out whether it's a host or device variable and whether the
6902         // error should be ignored.
6903         EmitTLSUnsupportedError = true;
6904         // We still need to mark the variable as TLS so it shows up in AST with
6905         // proper storage class for other tools to use even if we're not going
6906         // to emit any code for it.
6907         NewVD->setTSCSpec(TSCS);
6908       } else
6909         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6910              diag::err_thread_unsupported);
6911     } else
6912       NewVD->setTSCSpec(TSCS);
6913   }
6914 
6915   switch (D.getDeclSpec().getConstexprSpecifier()) {
6916   case CSK_unspecified:
6917     break;
6918 
6919   case CSK_consteval:
6920     Diag(D.getDeclSpec().getConstexprSpecLoc(),
6921         diag::err_constexpr_wrong_decl_kind)
6922       << D.getDeclSpec().getConstexprSpecifier();
6923     LLVM_FALLTHROUGH;
6924 
6925   case CSK_constexpr:
6926     NewVD->setConstexpr(true);
6927     // C++1z [dcl.spec.constexpr]p1:
6928     //   A static data member declared with the constexpr specifier is
6929     //   implicitly an inline variable.
6930     if (NewVD->isStaticDataMember() &&
6931         (getLangOpts().CPlusPlus17 ||
6932          Context.getTargetInfo().getCXXABI().isMicrosoft()))
6933       NewVD->setImplicitlyInline();
6934     break;
6935 
6936   case CSK_constinit:
6937     if (!NewVD->hasGlobalStorage())
6938       Diag(D.getDeclSpec().getConstexprSpecLoc(),
6939            diag::err_constinit_local_variable);
6940     else
6941       NewVD->addAttr(ConstInitAttr::Create(
6942           Context, D.getDeclSpec().getConstexprSpecLoc(),
6943           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
6944     break;
6945   }
6946 
6947   // C99 6.7.4p3
6948   //   An inline definition of a function with external linkage shall
6949   //   not contain a definition of a modifiable object with static or
6950   //   thread storage duration...
6951   // We only apply this when the function is required to be defined
6952   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6953   // that a local variable with thread storage duration still has to
6954   // be marked 'static'.  Also note that it's possible to get these
6955   // semantics in C++ using __attribute__((gnu_inline)).
6956   if (SC == SC_Static && S->getFnParent() != nullptr &&
6957       !NewVD->getType().isConstQualified()) {
6958     FunctionDecl *CurFD = getCurFunctionDecl();
6959     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6960       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6961            diag::warn_static_local_in_extern_inline);
6962       MaybeSuggestAddingStaticToDecl(CurFD);
6963     }
6964   }
6965 
6966   if (D.getDeclSpec().isModulePrivateSpecified()) {
6967     if (IsVariableTemplateSpecialization)
6968       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6969           << (IsPartialSpecialization ? 1 : 0)
6970           << FixItHint::CreateRemoval(
6971                  D.getDeclSpec().getModulePrivateSpecLoc());
6972     else if (IsMemberSpecialization)
6973       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6974         << 2
6975         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6976     else if (NewVD->hasLocalStorage())
6977       Diag(NewVD->getLocation(), diag::err_module_private_local)
6978         << 0 << NewVD->getDeclName()
6979         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6980         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6981     else {
6982       NewVD->setModulePrivate();
6983       if (NewTemplate)
6984         NewTemplate->setModulePrivate();
6985       for (auto *B : Bindings)
6986         B->setModulePrivate();
6987     }
6988   }
6989 
6990   if (getLangOpts().OpenCL) {
6991 
6992     deduceOpenCLAddressSpace(NewVD);
6993 
6994     diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType());
6995   }
6996 
6997   // Handle attributes prior to checking for duplicates in MergeVarDecl
6998   ProcessDeclAttributes(S, NewVD, D);
6999 
7000   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
7001     if (EmitTLSUnsupportedError &&
7002         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7003          (getLangOpts().OpenMPIsDevice &&
7004           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7005       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7006            diag::err_thread_unsupported);
7007     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7008     // storage [duration]."
7009     if (SC == SC_None && S->getFnParent() != nullptr &&
7010         (NewVD->hasAttr<CUDASharedAttr>() ||
7011          NewVD->hasAttr<CUDAConstantAttr>())) {
7012       NewVD->setStorageClass(SC_Static);
7013     }
7014   }
7015 
7016   // Ensure that dllimport globals without explicit storage class are treated as
7017   // extern. The storage class is set above using parsed attributes. Now we can
7018   // check the VarDecl itself.
7019   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7020          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7021          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7022 
7023   // In auto-retain/release, infer strong retension for variables of
7024   // retainable type.
7025   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7026     NewVD->setInvalidDecl();
7027 
7028   // Handle GNU asm-label extension (encoded as an attribute).
7029   if (Expr *E = (Expr*)D.getAsmLabel()) {
7030     // The parser guarantees this is a string.
7031     StringLiteral *SE = cast<StringLiteral>(E);
7032     StringRef Label = SE->getString();
7033     if (S->getFnParent() != nullptr) {
7034       switch (SC) {
7035       case SC_None:
7036       case SC_Auto:
7037         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7038         break;
7039       case SC_Register:
7040         // Local Named register
7041         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7042             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7043           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7044         break;
7045       case SC_Static:
7046       case SC_Extern:
7047       case SC_PrivateExtern:
7048         break;
7049       }
7050     } else if (SC == SC_Register) {
7051       // Global Named register
7052       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7053         const auto &TI = Context.getTargetInfo();
7054         bool HasSizeMismatch;
7055 
7056         if (!TI.isValidGCCRegisterName(Label))
7057           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7058         else if (!TI.validateGlobalRegisterVariable(Label,
7059                                                     Context.getTypeSize(R),
7060                                                     HasSizeMismatch))
7061           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7062         else if (HasSizeMismatch)
7063           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7064       }
7065 
7066       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7067         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7068         NewVD->setInvalidDecl(true);
7069       }
7070     }
7071 
7072     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7073                                         /*IsLiteralLabel=*/true,
7074                                         SE->getStrTokenLoc(0)));
7075   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7076     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7077       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7078     if (I != ExtnameUndeclaredIdentifiers.end()) {
7079       if (isDeclExternC(NewVD)) {
7080         NewVD->addAttr(I->second);
7081         ExtnameUndeclaredIdentifiers.erase(I);
7082       } else
7083         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7084             << /*Variable*/1 << NewVD;
7085     }
7086   }
7087 
7088   // Find the shadowed declaration before filtering for scope.
7089   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7090                                 ? getShadowedDeclaration(NewVD, Previous)
7091                                 : nullptr;
7092 
7093   // Don't consider existing declarations that are in a different
7094   // scope and are out-of-semantic-context declarations (if the new
7095   // declaration has linkage).
7096   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7097                        D.getCXXScopeSpec().isNotEmpty() ||
7098                        IsMemberSpecialization ||
7099                        IsVariableTemplateSpecialization);
7100 
7101   // Check whether the previous declaration is in the same block scope. This
7102   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7103   if (getLangOpts().CPlusPlus &&
7104       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7105     NewVD->setPreviousDeclInSameBlockScope(
7106         Previous.isSingleResult() && !Previous.isShadowed() &&
7107         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7108 
7109   if (!getLangOpts().CPlusPlus) {
7110     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7111   } else {
7112     // If this is an explicit specialization of a static data member, check it.
7113     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7114         CheckMemberSpecialization(NewVD, Previous))
7115       NewVD->setInvalidDecl();
7116 
7117     // Merge the decl with the existing one if appropriate.
7118     if (!Previous.empty()) {
7119       if (Previous.isSingleResult() &&
7120           isa<FieldDecl>(Previous.getFoundDecl()) &&
7121           D.getCXXScopeSpec().isSet()) {
7122         // The user tried to define a non-static data member
7123         // out-of-line (C++ [dcl.meaning]p1).
7124         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7125           << D.getCXXScopeSpec().getRange();
7126         Previous.clear();
7127         NewVD->setInvalidDecl();
7128       }
7129     } else if (D.getCXXScopeSpec().isSet()) {
7130       // No previous declaration in the qualifying scope.
7131       Diag(D.getIdentifierLoc(), diag::err_no_member)
7132         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7133         << D.getCXXScopeSpec().getRange();
7134       NewVD->setInvalidDecl();
7135     }
7136 
7137     if (!IsVariableTemplateSpecialization)
7138       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7139 
7140     if (NewTemplate) {
7141       VarTemplateDecl *PrevVarTemplate =
7142           NewVD->getPreviousDecl()
7143               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7144               : nullptr;
7145 
7146       // Check the template parameter list of this declaration, possibly
7147       // merging in the template parameter list from the previous variable
7148       // template declaration.
7149       if (CheckTemplateParameterList(
7150               TemplateParams,
7151               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7152                               : nullptr,
7153               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7154                DC->isDependentContext())
7155                   ? TPC_ClassTemplateMember
7156                   : TPC_VarTemplate))
7157         NewVD->setInvalidDecl();
7158 
7159       // If we are providing an explicit specialization of a static variable
7160       // template, make a note of that.
7161       if (PrevVarTemplate &&
7162           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7163         PrevVarTemplate->setMemberSpecialization();
7164     }
7165   }
7166 
7167   // Diagnose shadowed variables iff this isn't a redeclaration.
7168   if (ShadowedDecl && !D.isRedeclaration())
7169     CheckShadow(NewVD, ShadowedDecl, Previous);
7170 
7171   ProcessPragmaWeak(S, NewVD);
7172 
7173   // If this is the first declaration of an extern C variable, update
7174   // the map of such variables.
7175   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7176       isIncompleteDeclExternC(*this, NewVD))
7177     RegisterLocallyScopedExternCDecl(NewVD, S);
7178 
7179   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7180     MangleNumberingContext *MCtx;
7181     Decl *ManglingContextDecl;
7182     std::tie(MCtx, ManglingContextDecl) =
7183         getCurrentMangleNumberContext(NewVD->getDeclContext());
7184     if (MCtx) {
7185       Context.setManglingNumber(
7186           NewVD, MCtx->getManglingNumber(
7187                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7188       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7189     }
7190   }
7191 
7192   // Special handling of variable named 'main'.
7193   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7194       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7195       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7196 
7197     // C++ [basic.start.main]p3
7198     // A program that declares a variable main at global scope is ill-formed.
7199     if (getLangOpts().CPlusPlus)
7200       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7201 
7202     // In C, and external-linkage variable named main results in undefined
7203     // behavior.
7204     else if (NewVD->hasExternalFormalLinkage())
7205       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7206   }
7207 
7208   if (D.isRedeclaration() && !Previous.empty()) {
7209     NamedDecl *Prev = Previous.getRepresentativeDecl();
7210     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7211                                    D.isFunctionDefinition());
7212   }
7213 
7214   if (NewTemplate) {
7215     if (NewVD->isInvalidDecl())
7216       NewTemplate->setInvalidDecl();
7217     ActOnDocumentableDecl(NewTemplate);
7218     return NewTemplate;
7219   }
7220 
7221   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7222     CompleteMemberSpecialization(NewVD, Previous);
7223 
7224   return NewVD;
7225 }
7226 
7227 /// Enum describing the %select options in diag::warn_decl_shadow.
7228 enum ShadowedDeclKind {
7229   SDK_Local,
7230   SDK_Global,
7231   SDK_StaticMember,
7232   SDK_Field,
7233   SDK_Typedef,
7234   SDK_Using
7235 };
7236 
7237 /// Determine what kind of declaration we're shadowing.
7238 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7239                                                 const DeclContext *OldDC) {
7240   if (isa<TypeAliasDecl>(ShadowedDecl))
7241     return SDK_Using;
7242   else if (isa<TypedefDecl>(ShadowedDecl))
7243     return SDK_Typedef;
7244   else if (isa<RecordDecl>(OldDC))
7245     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7246 
7247   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7248 }
7249 
7250 /// Return the location of the capture if the given lambda captures the given
7251 /// variable \p VD, or an invalid source location otherwise.
7252 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7253                                          const VarDecl *VD) {
7254   for (const Capture &Capture : LSI->Captures) {
7255     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7256       return Capture.getLocation();
7257   }
7258   return SourceLocation();
7259 }
7260 
7261 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7262                                      const LookupResult &R) {
7263   // Only diagnose if we're shadowing an unambiguous field or variable.
7264   if (R.getResultKind() != LookupResult::Found)
7265     return false;
7266 
7267   // Return false if warning is ignored.
7268   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7269 }
7270 
7271 /// Return the declaration shadowed by the given variable \p D, or null
7272 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7273 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7274                                         const LookupResult &R) {
7275   if (!shouldWarnIfShadowedDecl(Diags, R))
7276     return nullptr;
7277 
7278   // Don't diagnose declarations at file scope.
7279   if (D->hasGlobalStorage())
7280     return nullptr;
7281 
7282   NamedDecl *ShadowedDecl = R.getFoundDecl();
7283   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
7284              ? ShadowedDecl
7285              : nullptr;
7286 }
7287 
7288 /// Return the declaration shadowed by the given typedef \p D, or null
7289 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7290 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7291                                         const LookupResult &R) {
7292   // Don't warn if typedef declaration is part of a class
7293   if (D->getDeclContext()->isRecord())
7294     return nullptr;
7295 
7296   if (!shouldWarnIfShadowedDecl(Diags, R))
7297     return nullptr;
7298 
7299   NamedDecl *ShadowedDecl = R.getFoundDecl();
7300   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7301 }
7302 
7303 /// Diagnose variable or built-in function shadowing.  Implements
7304 /// -Wshadow.
7305 ///
7306 /// This method is called whenever a VarDecl is added to a "useful"
7307 /// scope.
7308 ///
7309 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7310 /// \param R the lookup of the name
7311 ///
7312 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7313                        const LookupResult &R) {
7314   DeclContext *NewDC = D->getDeclContext();
7315 
7316   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7317     // Fields are not shadowed by variables in C++ static methods.
7318     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7319       if (MD->isStatic())
7320         return;
7321 
7322     // Fields shadowed by constructor parameters are a special case. Usually
7323     // the constructor initializes the field with the parameter.
7324     if (isa<CXXConstructorDecl>(NewDC))
7325       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7326         // Remember that this was shadowed so we can either warn about its
7327         // modification or its existence depending on warning settings.
7328         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7329         return;
7330       }
7331   }
7332 
7333   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7334     if (shadowedVar->isExternC()) {
7335       // For shadowing external vars, make sure that we point to the global
7336       // declaration, not a locally scoped extern declaration.
7337       for (auto I : shadowedVar->redecls())
7338         if (I->isFileVarDecl()) {
7339           ShadowedDecl = I;
7340           break;
7341         }
7342     }
7343 
7344   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7345 
7346   unsigned WarningDiag = diag::warn_decl_shadow;
7347   SourceLocation CaptureLoc;
7348   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7349       isa<CXXMethodDecl>(NewDC)) {
7350     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7351       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7352         if (RD->getLambdaCaptureDefault() == LCD_None) {
7353           // Try to avoid warnings for lambdas with an explicit capture list.
7354           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7355           // Warn only when the lambda captures the shadowed decl explicitly.
7356           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7357           if (CaptureLoc.isInvalid())
7358             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7359         } else {
7360           // Remember that this was shadowed so we can avoid the warning if the
7361           // shadowed decl isn't captured and the warning settings allow it.
7362           cast<LambdaScopeInfo>(getCurFunction())
7363               ->ShadowingDecls.push_back(
7364                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7365           return;
7366         }
7367       }
7368 
7369       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7370         // A variable can't shadow a local variable in an enclosing scope, if
7371         // they are separated by a non-capturing declaration context.
7372         for (DeclContext *ParentDC = NewDC;
7373              ParentDC && !ParentDC->Equals(OldDC);
7374              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7375           // Only block literals, captured statements, and lambda expressions
7376           // can capture; other scopes don't.
7377           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7378               !isLambdaCallOperator(ParentDC)) {
7379             return;
7380           }
7381         }
7382       }
7383     }
7384   }
7385 
7386   // Only warn about certain kinds of shadowing for class members.
7387   if (NewDC && NewDC->isRecord()) {
7388     // In particular, don't warn about shadowing non-class members.
7389     if (!OldDC->isRecord())
7390       return;
7391 
7392     // TODO: should we warn about static data members shadowing
7393     // static data members from base classes?
7394 
7395     // TODO: don't diagnose for inaccessible shadowed members.
7396     // This is hard to do perfectly because we might friend the
7397     // shadowing context, but that's just a false negative.
7398   }
7399 
7400 
7401   DeclarationName Name = R.getLookupName();
7402 
7403   // Emit warning and note.
7404   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7405     return;
7406   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7407   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7408   if (!CaptureLoc.isInvalid())
7409     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7410         << Name << /*explicitly*/ 1;
7411   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7412 }
7413 
7414 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7415 /// when these variables are captured by the lambda.
7416 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7417   for (const auto &Shadow : LSI->ShadowingDecls) {
7418     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7419     // Try to avoid the warning when the shadowed decl isn't captured.
7420     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7421     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7422     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7423                                        ? diag::warn_decl_shadow_uncaptured_local
7424                                        : diag::warn_decl_shadow)
7425         << Shadow.VD->getDeclName()
7426         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7427     if (!CaptureLoc.isInvalid())
7428       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7429           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7430     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7431   }
7432 }
7433 
7434 /// Check -Wshadow without the advantage of a previous lookup.
7435 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7436   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7437     return;
7438 
7439   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7440                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7441   LookupName(R, S);
7442   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7443     CheckShadow(D, ShadowedDecl, R);
7444 }
7445 
7446 /// Check if 'E', which is an expression that is about to be modified, refers
7447 /// to a constructor parameter that shadows a field.
7448 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7449   // Quickly ignore expressions that can't be shadowing ctor parameters.
7450   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7451     return;
7452   E = E->IgnoreParenImpCasts();
7453   auto *DRE = dyn_cast<DeclRefExpr>(E);
7454   if (!DRE)
7455     return;
7456   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7457   auto I = ShadowingDecls.find(D);
7458   if (I == ShadowingDecls.end())
7459     return;
7460   const NamedDecl *ShadowedDecl = I->second;
7461   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7462   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7463   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7464   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7465 
7466   // Avoid issuing multiple warnings about the same decl.
7467   ShadowingDecls.erase(I);
7468 }
7469 
7470 /// Check for conflict between this global or extern "C" declaration and
7471 /// previous global or extern "C" declarations. This is only used in C++.
7472 template<typename T>
7473 static bool checkGlobalOrExternCConflict(
7474     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7475   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7476   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7477 
7478   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7479     // The common case: this global doesn't conflict with any extern "C"
7480     // declaration.
7481     return false;
7482   }
7483 
7484   if (Prev) {
7485     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7486       // Both the old and new declarations have C language linkage. This is a
7487       // redeclaration.
7488       Previous.clear();
7489       Previous.addDecl(Prev);
7490       return true;
7491     }
7492 
7493     // This is a global, non-extern "C" declaration, and there is a previous
7494     // non-global extern "C" declaration. Diagnose if this is a variable
7495     // declaration.
7496     if (!isa<VarDecl>(ND))
7497       return false;
7498   } else {
7499     // The declaration is extern "C". Check for any declaration in the
7500     // translation unit which might conflict.
7501     if (IsGlobal) {
7502       // We have already performed the lookup into the translation unit.
7503       IsGlobal = false;
7504       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7505            I != E; ++I) {
7506         if (isa<VarDecl>(*I)) {
7507           Prev = *I;
7508           break;
7509         }
7510       }
7511     } else {
7512       DeclContext::lookup_result R =
7513           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7514       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7515            I != E; ++I) {
7516         if (isa<VarDecl>(*I)) {
7517           Prev = *I;
7518           break;
7519         }
7520         // FIXME: If we have any other entity with this name in global scope,
7521         // the declaration is ill-formed, but that is a defect: it breaks the
7522         // 'stat' hack, for instance. Only variables can have mangled name
7523         // clashes with extern "C" declarations, so only they deserve a
7524         // diagnostic.
7525       }
7526     }
7527 
7528     if (!Prev)
7529       return false;
7530   }
7531 
7532   // Use the first declaration's location to ensure we point at something which
7533   // is lexically inside an extern "C" linkage-spec.
7534   assert(Prev && "should have found a previous declaration to diagnose");
7535   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7536     Prev = FD->getFirstDecl();
7537   else
7538     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7539 
7540   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7541     << IsGlobal << ND;
7542   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7543     << IsGlobal;
7544   return false;
7545 }
7546 
7547 /// Apply special rules for handling extern "C" declarations. Returns \c true
7548 /// if we have found that this is a redeclaration of some prior entity.
7549 ///
7550 /// Per C++ [dcl.link]p6:
7551 ///   Two declarations [for a function or variable] with C language linkage
7552 ///   with the same name that appear in different scopes refer to the same
7553 ///   [entity]. An entity with C language linkage shall not be declared with
7554 ///   the same name as an entity in global scope.
7555 template<typename T>
7556 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7557                                                   LookupResult &Previous) {
7558   if (!S.getLangOpts().CPlusPlus) {
7559     // In C, when declaring a global variable, look for a corresponding 'extern'
7560     // variable declared in function scope. We don't need this in C++, because
7561     // we find local extern decls in the surrounding file-scope DeclContext.
7562     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7563       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7564         Previous.clear();
7565         Previous.addDecl(Prev);
7566         return true;
7567       }
7568     }
7569     return false;
7570   }
7571 
7572   // A declaration in the translation unit can conflict with an extern "C"
7573   // declaration.
7574   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7575     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7576 
7577   // An extern "C" declaration can conflict with a declaration in the
7578   // translation unit or can be a redeclaration of an extern "C" declaration
7579   // in another scope.
7580   if (isIncompleteDeclExternC(S,ND))
7581     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7582 
7583   // Neither global nor extern "C": nothing to do.
7584   return false;
7585 }
7586 
7587 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7588   // If the decl is already known invalid, don't check it.
7589   if (NewVD->isInvalidDecl())
7590     return;
7591 
7592   QualType T = NewVD->getType();
7593 
7594   // Defer checking an 'auto' type until its initializer is attached.
7595   if (T->isUndeducedType())
7596     return;
7597 
7598   if (NewVD->hasAttrs())
7599     CheckAlignasUnderalignment(NewVD);
7600 
7601   if (T->isObjCObjectType()) {
7602     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7603       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7604     T = Context.getObjCObjectPointerType(T);
7605     NewVD->setType(T);
7606   }
7607 
7608   // Emit an error if an address space was applied to decl with local storage.
7609   // This includes arrays of objects with address space qualifiers, but not
7610   // automatic variables that point to other address spaces.
7611   // ISO/IEC TR 18037 S5.1.2
7612   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7613       T.getAddressSpace() != LangAS::Default) {
7614     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7615     NewVD->setInvalidDecl();
7616     return;
7617   }
7618 
7619   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7620   // scope.
7621   if (getLangOpts().OpenCLVersion == 120 &&
7622       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7623       NewVD->isStaticLocal()) {
7624     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7625     NewVD->setInvalidDecl();
7626     return;
7627   }
7628 
7629   if (getLangOpts().OpenCL) {
7630     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7631     if (NewVD->hasAttr<BlocksAttr>()) {
7632       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7633       return;
7634     }
7635 
7636     if (T->isBlockPointerType()) {
7637       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7638       // can't use 'extern' storage class.
7639       if (!T.isConstQualified()) {
7640         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7641             << 0 /*const*/;
7642         NewVD->setInvalidDecl();
7643         return;
7644       }
7645       if (NewVD->hasExternalStorage()) {
7646         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7647         NewVD->setInvalidDecl();
7648         return;
7649       }
7650     }
7651     // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7652     // __constant address space.
7653     // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7654     // variables inside a function can also be declared in the global
7655     // address space.
7656     // C++ for OpenCL inherits rule from OpenCL C v2.0.
7657     // FIXME: Adding local AS in C++ for OpenCL might make sense.
7658     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7659         NewVD->hasExternalStorage()) {
7660       if (!T->isSamplerT() &&
7661           !(T.getAddressSpace() == LangAS::opencl_constant ||
7662             (T.getAddressSpace() == LangAS::opencl_global &&
7663              (getLangOpts().OpenCLVersion == 200 ||
7664               getLangOpts().OpenCLCPlusPlus)))) {
7665         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7666         if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7667           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7668               << Scope << "global or constant";
7669         else
7670           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7671               << Scope << "constant";
7672         NewVD->setInvalidDecl();
7673         return;
7674       }
7675     } else {
7676       if (T.getAddressSpace() == LangAS::opencl_global) {
7677         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7678             << 1 /*is any function*/ << "global";
7679         NewVD->setInvalidDecl();
7680         return;
7681       }
7682       if (T.getAddressSpace() == LangAS::opencl_constant ||
7683           T.getAddressSpace() == LangAS::opencl_local) {
7684         FunctionDecl *FD = getCurFunctionDecl();
7685         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7686         // in functions.
7687         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7688           if (T.getAddressSpace() == LangAS::opencl_constant)
7689             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7690                 << 0 /*non-kernel only*/ << "constant";
7691           else
7692             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7693                 << 0 /*non-kernel only*/ << "local";
7694           NewVD->setInvalidDecl();
7695           return;
7696         }
7697         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7698         // in the outermost scope of a kernel function.
7699         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7700           if (!getCurScope()->isFunctionScope()) {
7701             if (T.getAddressSpace() == LangAS::opencl_constant)
7702               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7703                   << "constant";
7704             else
7705               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7706                   << "local";
7707             NewVD->setInvalidDecl();
7708             return;
7709           }
7710         }
7711       } else if (T.getAddressSpace() != LangAS::opencl_private &&
7712                  // If we are parsing a template we didn't deduce an addr
7713                  // space yet.
7714                  T.getAddressSpace() != LangAS::Default) {
7715         // Do not allow other address spaces on automatic variable.
7716         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7717         NewVD->setInvalidDecl();
7718         return;
7719       }
7720     }
7721   }
7722 
7723   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7724       && !NewVD->hasAttr<BlocksAttr>()) {
7725     if (getLangOpts().getGC() != LangOptions::NonGC)
7726       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7727     else {
7728       assert(!getLangOpts().ObjCAutoRefCount);
7729       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7730     }
7731   }
7732 
7733   bool isVM = T->isVariablyModifiedType();
7734   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7735       NewVD->hasAttr<BlocksAttr>())
7736     setFunctionHasBranchProtectedScope();
7737 
7738   if ((isVM && NewVD->hasLinkage()) ||
7739       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7740     bool SizeIsNegative;
7741     llvm::APSInt Oversized;
7742     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7743         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7744     QualType FixedT;
7745     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
7746       FixedT = FixedTInfo->getType();
7747     else if (FixedTInfo) {
7748       // Type and type-as-written are canonically different. We need to fix up
7749       // both types separately.
7750       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7751                                                    Oversized);
7752     }
7753     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7754       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7755       // FIXME: This won't give the correct result for
7756       // int a[10][n];
7757       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7758 
7759       if (NewVD->isFileVarDecl())
7760         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7761         << SizeRange;
7762       else if (NewVD->isStaticLocal())
7763         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7764         << SizeRange;
7765       else
7766         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7767         << SizeRange;
7768       NewVD->setInvalidDecl();
7769       return;
7770     }
7771 
7772     if (!FixedTInfo) {
7773       if (NewVD->isFileVarDecl())
7774         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7775       else
7776         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7777       NewVD->setInvalidDecl();
7778       return;
7779     }
7780 
7781     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7782     NewVD->setType(FixedT);
7783     NewVD->setTypeSourceInfo(FixedTInfo);
7784   }
7785 
7786   if (T->isVoidType()) {
7787     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7788     //                    of objects and functions.
7789     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7790       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7791         << T;
7792       NewVD->setInvalidDecl();
7793       return;
7794     }
7795   }
7796 
7797   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7798     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7799     NewVD->setInvalidDecl();
7800     return;
7801   }
7802 
7803   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7804     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7805     NewVD->setInvalidDecl();
7806     return;
7807   }
7808 
7809   if (NewVD->isConstexpr() && !T->isDependentType() &&
7810       RequireLiteralType(NewVD->getLocation(), T,
7811                          diag::err_constexpr_var_non_literal)) {
7812     NewVD->setInvalidDecl();
7813     return;
7814   }
7815 }
7816 
7817 /// Perform semantic checking on a newly-created variable
7818 /// declaration.
7819 ///
7820 /// This routine performs all of the type-checking required for a
7821 /// variable declaration once it has been built. It is used both to
7822 /// check variables after they have been parsed and their declarators
7823 /// have been translated into a declaration, and to check variables
7824 /// that have been instantiated from a template.
7825 ///
7826 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7827 ///
7828 /// Returns true if the variable declaration is a redeclaration.
7829 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7830   CheckVariableDeclarationType(NewVD);
7831 
7832   // If the decl is already known invalid, don't check it.
7833   if (NewVD->isInvalidDecl())
7834     return false;
7835 
7836   // If we did not find anything by this name, look for a non-visible
7837   // extern "C" declaration with the same name.
7838   if (Previous.empty() &&
7839       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7840     Previous.setShadowed();
7841 
7842   if (!Previous.empty()) {
7843     MergeVarDecl(NewVD, Previous);
7844     return true;
7845   }
7846   return false;
7847 }
7848 
7849 namespace {
7850 struct FindOverriddenMethod {
7851   Sema *S;
7852   CXXMethodDecl *Method;
7853 
7854   /// Member lookup function that determines whether a given C++
7855   /// method overrides a method in a base class, to be used with
7856   /// CXXRecordDecl::lookupInBases().
7857   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7858     RecordDecl *BaseRecord =
7859         Specifier->getType()->castAs<RecordType>()->getDecl();
7860 
7861     DeclarationName Name = Method->getDeclName();
7862 
7863     // FIXME: Do we care about other names here too?
7864     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7865       // We really want to find the base class destructor here.
7866       QualType T = S->Context.getTypeDeclType(BaseRecord);
7867       CanQualType CT = S->Context.getCanonicalType(T);
7868 
7869       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7870     }
7871 
7872     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7873          Path.Decls = Path.Decls.slice(1)) {
7874       NamedDecl *D = Path.Decls.front();
7875       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7876         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7877           return true;
7878       }
7879     }
7880 
7881     return false;
7882   }
7883 };
7884 
7885 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7886 } // end anonymous namespace
7887 
7888 /// Report an error regarding overriding, along with any relevant
7889 /// overridden methods.
7890 ///
7891 /// \param DiagID the primary error to report.
7892 /// \param MD the overriding method.
7893 /// \param OEK which overrides to include as notes.
7894 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7895                             OverrideErrorKind OEK = OEK_All) {
7896   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7897   for (const CXXMethodDecl *O : MD->overridden_methods()) {
7898     // This check (& the OEK parameter) could be replaced by a predicate, but
7899     // without lambdas that would be overkill. This is still nicer than writing
7900     // out the diag loop 3 times.
7901     if ((OEK == OEK_All) ||
7902         (OEK == OEK_NonDeleted && !O->isDeleted()) ||
7903         (OEK == OEK_Deleted && O->isDeleted()))
7904       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7905   }
7906 }
7907 
7908 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7909 /// and if so, check that it's a valid override and remember it.
7910 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7911   // Look for methods in base classes that this method might override.
7912   CXXBasePaths Paths;
7913   FindOverriddenMethod FOM;
7914   FOM.Method = MD;
7915   FOM.S = this;
7916   bool hasDeletedOverridenMethods = false;
7917   bool hasNonDeletedOverridenMethods = false;
7918   bool AddedAny = false;
7919   if (DC->lookupInBases(FOM, Paths)) {
7920     for (auto *I : Paths.found_decls()) {
7921       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7922         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7923         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7924             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7925             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7926             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7927           hasDeletedOverridenMethods |= OldMD->isDeleted();
7928           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7929           AddedAny = true;
7930         }
7931       }
7932     }
7933   }
7934 
7935   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7936     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7937   }
7938   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7939     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7940   }
7941 
7942   return AddedAny;
7943 }
7944 
7945 namespace {
7946   // Struct for holding all of the extra arguments needed by
7947   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7948   struct ActOnFDArgs {
7949     Scope *S;
7950     Declarator &D;
7951     MultiTemplateParamsArg TemplateParamLists;
7952     bool AddToScope;
7953   };
7954 } // end anonymous namespace
7955 
7956 namespace {
7957 
7958 // Callback to only accept typo corrections that have a non-zero edit distance.
7959 // Also only accept corrections that have the same parent decl.
7960 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
7961  public:
7962   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7963                             CXXRecordDecl *Parent)
7964       : Context(Context), OriginalFD(TypoFD),
7965         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7966 
7967   bool ValidateCandidate(const TypoCorrection &candidate) override {
7968     if (candidate.getEditDistance() == 0)
7969       return false;
7970 
7971     SmallVector<unsigned, 1> MismatchedParams;
7972     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7973                                           CDeclEnd = candidate.end();
7974          CDecl != CDeclEnd; ++CDecl) {
7975       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7976 
7977       if (FD && !FD->hasBody() &&
7978           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7979         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7980           CXXRecordDecl *Parent = MD->getParent();
7981           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7982             return true;
7983         } else if (!ExpectedParent) {
7984           return true;
7985         }
7986       }
7987     }
7988 
7989     return false;
7990   }
7991 
7992   std::unique_ptr<CorrectionCandidateCallback> clone() override {
7993     return std::make_unique<DifferentNameValidatorCCC>(*this);
7994   }
7995 
7996  private:
7997   ASTContext &Context;
7998   FunctionDecl *OriginalFD;
7999   CXXRecordDecl *ExpectedParent;
8000 };
8001 
8002 } // end anonymous namespace
8003 
8004 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8005   TypoCorrectedFunctionDefinitions.insert(F);
8006 }
8007 
8008 /// Generate diagnostics for an invalid function redeclaration.
8009 ///
8010 /// This routine handles generating the diagnostic messages for an invalid
8011 /// function redeclaration, including finding possible similar declarations
8012 /// or performing typo correction if there are no previous declarations with
8013 /// the same name.
8014 ///
8015 /// Returns a NamedDecl iff typo correction was performed and substituting in
8016 /// the new declaration name does not cause new errors.
8017 static NamedDecl *DiagnoseInvalidRedeclaration(
8018     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8019     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8020   DeclarationName Name = NewFD->getDeclName();
8021   DeclContext *NewDC = NewFD->getDeclContext();
8022   SmallVector<unsigned, 1> MismatchedParams;
8023   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8024   TypoCorrection Correction;
8025   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8026   unsigned DiagMsg =
8027     IsLocalFriend ? diag::err_no_matching_local_friend :
8028     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8029     diag::err_member_decl_does_not_match;
8030   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8031                     IsLocalFriend ? Sema::LookupLocalFriendName
8032                                   : Sema::LookupOrdinaryName,
8033                     Sema::ForVisibleRedeclaration);
8034 
8035   NewFD->setInvalidDecl();
8036   if (IsLocalFriend)
8037     SemaRef.LookupName(Prev, S);
8038   else
8039     SemaRef.LookupQualifiedName(Prev, NewDC);
8040   assert(!Prev.isAmbiguous() &&
8041          "Cannot have an ambiguity in previous-declaration lookup");
8042   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8043   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8044                                 MD ? MD->getParent() : nullptr);
8045   if (!Prev.empty()) {
8046     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8047          Func != FuncEnd; ++Func) {
8048       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8049       if (FD &&
8050           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8051         // Add 1 to the index so that 0 can mean the mismatch didn't
8052         // involve a parameter
8053         unsigned ParamNum =
8054             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8055         NearMatches.push_back(std::make_pair(FD, ParamNum));
8056       }
8057     }
8058   // If the qualified name lookup yielded nothing, try typo correction
8059   } else if ((Correction = SemaRef.CorrectTypo(
8060                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8061                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8062                   IsLocalFriend ? nullptr : NewDC))) {
8063     // Set up everything for the call to ActOnFunctionDeclarator
8064     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8065                               ExtraArgs.D.getIdentifierLoc());
8066     Previous.clear();
8067     Previous.setLookupName(Correction.getCorrection());
8068     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8069                                     CDeclEnd = Correction.end();
8070          CDecl != CDeclEnd; ++CDecl) {
8071       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8072       if (FD && !FD->hasBody() &&
8073           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8074         Previous.addDecl(FD);
8075       }
8076     }
8077     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8078 
8079     NamedDecl *Result;
8080     // Retry building the function declaration with the new previous
8081     // declarations, and with errors suppressed.
8082     {
8083       // Trap errors.
8084       Sema::SFINAETrap Trap(SemaRef);
8085 
8086       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8087       // pieces need to verify the typo-corrected C++ declaration and hopefully
8088       // eliminate the need for the parameter pack ExtraArgs.
8089       Result = SemaRef.ActOnFunctionDeclarator(
8090           ExtraArgs.S, ExtraArgs.D,
8091           Correction.getCorrectionDecl()->getDeclContext(),
8092           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8093           ExtraArgs.AddToScope);
8094 
8095       if (Trap.hasErrorOccurred())
8096         Result = nullptr;
8097     }
8098 
8099     if (Result) {
8100       // Determine which correction we picked.
8101       Decl *Canonical = Result->getCanonicalDecl();
8102       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8103            I != E; ++I)
8104         if ((*I)->getCanonicalDecl() == Canonical)
8105           Correction.setCorrectionDecl(*I);
8106 
8107       // Let Sema know about the correction.
8108       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8109       SemaRef.diagnoseTypo(
8110           Correction,
8111           SemaRef.PDiag(IsLocalFriend
8112                           ? diag::err_no_matching_local_friend_suggest
8113                           : diag::err_member_decl_does_not_match_suggest)
8114             << Name << NewDC << IsDefinition);
8115       return Result;
8116     }
8117 
8118     // Pretend the typo correction never occurred
8119     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8120                               ExtraArgs.D.getIdentifierLoc());
8121     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8122     Previous.clear();
8123     Previous.setLookupName(Name);
8124   }
8125 
8126   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8127       << Name << NewDC << IsDefinition << NewFD->getLocation();
8128 
8129   bool NewFDisConst = false;
8130   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8131     NewFDisConst = NewMD->isConst();
8132 
8133   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8134        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8135        NearMatch != NearMatchEnd; ++NearMatch) {
8136     FunctionDecl *FD = NearMatch->first;
8137     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8138     bool FDisConst = MD && MD->isConst();
8139     bool IsMember = MD || !IsLocalFriend;
8140 
8141     // FIXME: These notes are poorly worded for the local friend case.
8142     if (unsigned Idx = NearMatch->second) {
8143       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8144       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8145       if (Loc.isInvalid()) Loc = FD->getLocation();
8146       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8147                                  : diag::note_local_decl_close_param_match)
8148         << Idx << FDParam->getType()
8149         << NewFD->getParamDecl(Idx - 1)->getType();
8150     } else if (FDisConst != NewFDisConst) {
8151       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8152           << NewFDisConst << FD->getSourceRange().getEnd();
8153     } else
8154       SemaRef.Diag(FD->getLocation(),
8155                    IsMember ? diag::note_member_def_close_match
8156                             : diag::note_local_decl_close_match);
8157   }
8158   return nullptr;
8159 }
8160 
8161 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8162   switch (D.getDeclSpec().getStorageClassSpec()) {
8163   default: llvm_unreachable("Unknown storage class!");
8164   case DeclSpec::SCS_auto:
8165   case DeclSpec::SCS_register:
8166   case DeclSpec::SCS_mutable:
8167     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8168                  diag::err_typecheck_sclass_func);
8169     D.getMutableDeclSpec().ClearStorageClassSpecs();
8170     D.setInvalidType();
8171     break;
8172   case DeclSpec::SCS_unspecified: break;
8173   case DeclSpec::SCS_extern:
8174     if (D.getDeclSpec().isExternInLinkageSpec())
8175       return SC_None;
8176     return SC_Extern;
8177   case DeclSpec::SCS_static: {
8178     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8179       // C99 6.7.1p5:
8180       //   The declaration of an identifier for a function that has
8181       //   block scope shall have no explicit storage-class specifier
8182       //   other than extern
8183       // See also (C++ [dcl.stc]p4).
8184       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8185                    diag::err_static_block_func);
8186       break;
8187     } else
8188       return SC_Static;
8189   }
8190   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8191   }
8192 
8193   // No explicit storage class has already been returned
8194   return SC_None;
8195 }
8196 
8197 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8198                                            DeclContext *DC, QualType &R,
8199                                            TypeSourceInfo *TInfo,
8200                                            StorageClass SC,
8201                                            bool &IsVirtualOkay) {
8202   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8203   DeclarationName Name = NameInfo.getName();
8204 
8205   FunctionDecl *NewFD = nullptr;
8206   bool isInline = D.getDeclSpec().isInlineSpecified();
8207 
8208   if (!SemaRef.getLangOpts().CPlusPlus) {
8209     // Determine whether the function was written with a
8210     // prototype. This true when:
8211     //   - there is a prototype in the declarator, or
8212     //   - the type R of the function is some kind of typedef or other non-
8213     //     attributed reference to a type name (which eventually refers to a
8214     //     function type).
8215     bool HasPrototype =
8216       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8217       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8218 
8219     NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8220                                  R, TInfo, SC, isInline, HasPrototype,
8221                                  CSK_unspecified);
8222     if (D.isInvalidType())
8223       NewFD->setInvalidDecl();
8224 
8225     return NewFD;
8226   }
8227 
8228   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8229 
8230   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8231   if (ConstexprKind == CSK_constinit) {
8232     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8233                  diag::err_constexpr_wrong_decl_kind)
8234         << ConstexprKind;
8235     ConstexprKind = CSK_unspecified;
8236     D.getMutableDeclSpec().ClearConstexprSpec();
8237   }
8238 
8239   // Check that the return type is not an abstract class type.
8240   // For record types, this is done by the AbstractClassUsageDiagnoser once
8241   // the class has been completely parsed.
8242   if (!DC->isRecord() &&
8243       SemaRef.RequireNonAbstractType(
8244           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8245           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8246     D.setInvalidType();
8247 
8248   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8249     // This is a C++ constructor declaration.
8250     assert(DC->isRecord() &&
8251            "Constructors can only be declared in a member context");
8252 
8253     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8254     return CXXConstructorDecl::Create(
8255         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8256         TInfo, ExplicitSpecifier, isInline,
8257         /*isImplicitlyDeclared=*/false, ConstexprKind);
8258 
8259   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8260     // This is a C++ destructor declaration.
8261     if (DC->isRecord()) {
8262       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8263       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8264       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8265           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8266           isInline,
8267           /*isImplicitlyDeclared=*/false, ConstexprKind);
8268 
8269       // If the destructor needs an implicit exception specification, set it
8270       // now. FIXME: It'd be nice to be able to create the right type to start
8271       // with, but the type needs to reference the destructor declaration.
8272       if (SemaRef.getLangOpts().CPlusPlus11)
8273         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8274 
8275       IsVirtualOkay = true;
8276       return NewDD;
8277 
8278     } else {
8279       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8280       D.setInvalidType();
8281 
8282       // Create a FunctionDecl to satisfy the function definition parsing
8283       // code path.
8284       return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8285                                   D.getIdentifierLoc(), Name, R, TInfo, SC,
8286                                   isInline,
8287                                   /*hasPrototype=*/true, ConstexprKind);
8288     }
8289 
8290   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8291     if (!DC->isRecord()) {
8292       SemaRef.Diag(D.getIdentifierLoc(),
8293            diag::err_conv_function_not_member);
8294       return nullptr;
8295     }
8296 
8297     SemaRef.CheckConversionDeclarator(D, R, SC);
8298     if (D.isInvalidType())
8299       return nullptr;
8300 
8301     IsVirtualOkay = true;
8302     return CXXConversionDecl::Create(
8303         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8304         TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation());
8305 
8306   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8307     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8308 
8309     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8310                                          ExplicitSpecifier, NameInfo, R, TInfo,
8311                                          D.getEndLoc());
8312   } else if (DC->isRecord()) {
8313     // If the name of the function is the same as the name of the record,
8314     // then this must be an invalid constructor that has a return type.
8315     // (The parser checks for a return type and makes the declarator a
8316     // constructor if it has no return type).
8317     if (Name.getAsIdentifierInfo() &&
8318         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8319       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8320         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8321         << SourceRange(D.getIdentifierLoc());
8322       return nullptr;
8323     }
8324 
8325     // This is a C++ method declaration.
8326     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8327         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8328         TInfo, SC, isInline, ConstexprKind, SourceLocation());
8329     IsVirtualOkay = !Ret->isStatic();
8330     return Ret;
8331   } else {
8332     bool isFriend =
8333         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8334     if (!isFriend && SemaRef.CurContext->isRecord())
8335       return nullptr;
8336 
8337     // Determine whether the function was written with a
8338     // prototype. This true when:
8339     //   - we're in C++ (where every function has a prototype),
8340     return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8341                                 R, TInfo, SC, isInline, true /*HasPrototype*/,
8342                                 ConstexprKind);
8343   }
8344 }
8345 
8346 enum OpenCLParamType {
8347   ValidKernelParam,
8348   PtrPtrKernelParam,
8349   PtrKernelParam,
8350   InvalidAddrSpacePtrKernelParam,
8351   InvalidKernelParam,
8352   RecordKernelParam
8353 };
8354 
8355 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8356   // Size dependent types are just typedefs to normal integer types
8357   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8358   // integers other than by their names.
8359   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8360 
8361   // Remove typedefs one by one until we reach a typedef
8362   // for a size dependent type.
8363   QualType DesugaredTy = Ty;
8364   do {
8365     ArrayRef<StringRef> Names(SizeTypeNames);
8366     auto Match = llvm::find(Names, DesugaredTy.getAsString());
8367     if (Names.end() != Match)
8368       return true;
8369 
8370     Ty = DesugaredTy;
8371     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8372   } while (DesugaredTy != Ty);
8373 
8374   return false;
8375 }
8376 
8377 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8378   if (PT->isPointerType()) {
8379     QualType PointeeType = PT->getPointeeType();
8380     if (PointeeType->isPointerType())
8381       return PtrPtrKernelParam;
8382     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8383         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8384         PointeeType.getAddressSpace() == LangAS::Default)
8385       return InvalidAddrSpacePtrKernelParam;
8386     return PtrKernelParam;
8387   }
8388 
8389   // OpenCL v1.2 s6.9.k:
8390   // Arguments to kernel functions in a program cannot be declared with the
8391   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8392   // uintptr_t or a struct and/or union that contain fields declared to be one
8393   // of these built-in scalar types.
8394   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8395     return InvalidKernelParam;
8396 
8397   if (PT->isImageType())
8398     return PtrKernelParam;
8399 
8400   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8401     return InvalidKernelParam;
8402 
8403   // OpenCL extension spec v1.2 s9.5:
8404   // This extension adds support for half scalar and vector types as built-in
8405   // types that can be used for arithmetic operations, conversions etc.
8406   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8407     return InvalidKernelParam;
8408 
8409   if (PT->isRecordType())
8410     return RecordKernelParam;
8411 
8412   // Look into an array argument to check if it has a forbidden type.
8413   if (PT->isArrayType()) {
8414     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8415     // Call ourself to check an underlying type of an array. Since the
8416     // getPointeeOrArrayElementType returns an innermost type which is not an
8417     // array, this recursive call only happens once.
8418     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8419   }
8420 
8421   return ValidKernelParam;
8422 }
8423 
8424 static void checkIsValidOpenCLKernelParameter(
8425   Sema &S,
8426   Declarator &D,
8427   ParmVarDecl *Param,
8428   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8429   QualType PT = Param->getType();
8430 
8431   // Cache the valid types we encounter to avoid rechecking structs that are
8432   // used again
8433   if (ValidTypes.count(PT.getTypePtr()))
8434     return;
8435 
8436   switch (getOpenCLKernelParameterType(S, PT)) {
8437   case PtrPtrKernelParam:
8438     // OpenCL v1.2 s6.9.a:
8439     // A kernel function argument cannot be declared as a
8440     // pointer to a pointer type.
8441     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8442     D.setInvalidType();
8443     return;
8444 
8445   case InvalidAddrSpacePtrKernelParam:
8446     // OpenCL v1.0 s6.5:
8447     // __kernel function arguments declared to be a pointer of a type can point
8448     // to one of the following address spaces only : __global, __local or
8449     // __constant.
8450     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8451     D.setInvalidType();
8452     return;
8453 
8454     // OpenCL v1.2 s6.9.k:
8455     // Arguments to kernel functions in a program cannot be declared with the
8456     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8457     // uintptr_t or a struct and/or union that contain fields declared to be
8458     // one of these built-in scalar types.
8459 
8460   case InvalidKernelParam:
8461     // OpenCL v1.2 s6.8 n:
8462     // A kernel function argument cannot be declared
8463     // of event_t type.
8464     // Do not diagnose half type since it is diagnosed as invalid argument
8465     // type for any function elsewhere.
8466     if (!PT->isHalfType()) {
8467       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8468 
8469       // Explain what typedefs are involved.
8470       const TypedefType *Typedef = nullptr;
8471       while ((Typedef = PT->getAs<TypedefType>())) {
8472         SourceLocation Loc = Typedef->getDecl()->getLocation();
8473         // SourceLocation may be invalid for a built-in type.
8474         if (Loc.isValid())
8475           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8476         PT = Typedef->desugar();
8477       }
8478     }
8479 
8480     D.setInvalidType();
8481     return;
8482 
8483   case PtrKernelParam:
8484   case ValidKernelParam:
8485     ValidTypes.insert(PT.getTypePtr());
8486     return;
8487 
8488   case RecordKernelParam:
8489     break;
8490   }
8491 
8492   // Track nested structs we will inspect
8493   SmallVector<const Decl *, 4> VisitStack;
8494 
8495   // Track where we are in the nested structs. Items will migrate from
8496   // VisitStack to HistoryStack as we do the DFS for bad field.
8497   SmallVector<const FieldDecl *, 4> HistoryStack;
8498   HistoryStack.push_back(nullptr);
8499 
8500   // At this point we already handled everything except of a RecordType or
8501   // an ArrayType of a RecordType.
8502   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8503   const RecordType *RecTy =
8504       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8505   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8506 
8507   VisitStack.push_back(RecTy->getDecl());
8508   assert(VisitStack.back() && "First decl null?");
8509 
8510   do {
8511     const Decl *Next = VisitStack.pop_back_val();
8512     if (!Next) {
8513       assert(!HistoryStack.empty());
8514       // Found a marker, we have gone up a level
8515       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8516         ValidTypes.insert(Hist->getType().getTypePtr());
8517 
8518       continue;
8519     }
8520 
8521     // Adds everything except the original parameter declaration (which is not a
8522     // field itself) to the history stack.
8523     const RecordDecl *RD;
8524     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8525       HistoryStack.push_back(Field);
8526 
8527       QualType FieldTy = Field->getType();
8528       // Other field types (known to be valid or invalid) are handled while we
8529       // walk around RecordDecl::fields().
8530       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8531              "Unexpected type.");
8532       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8533 
8534       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8535     } else {
8536       RD = cast<RecordDecl>(Next);
8537     }
8538 
8539     // Add a null marker so we know when we've gone back up a level
8540     VisitStack.push_back(nullptr);
8541 
8542     for (const auto *FD : RD->fields()) {
8543       QualType QT = FD->getType();
8544 
8545       if (ValidTypes.count(QT.getTypePtr()))
8546         continue;
8547 
8548       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8549       if (ParamType == ValidKernelParam)
8550         continue;
8551 
8552       if (ParamType == RecordKernelParam) {
8553         VisitStack.push_back(FD);
8554         continue;
8555       }
8556 
8557       // OpenCL v1.2 s6.9.p:
8558       // Arguments to kernel functions that are declared to be a struct or union
8559       // do not allow OpenCL objects to be passed as elements of the struct or
8560       // union.
8561       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8562           ParamType == InvalidAddrSpacePtrKernelParam) {
8563         S.Diag(Param->getLocation(),
8564                diag::err_record_with_pointers_kernel_param)
8565           << PT->isUnionType()
8566           << PT;
8567       } else {
8568         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8569       }
8570 
8571       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8572           << OrigRecDecl->getDeclName();
8573 
8574       // We have an error, now let's go back up through history and show where
8575       // the offending field came from
8576       for (ArrayRef<const FieldDecl *>::const_iterator
8577                I = HistoryStack.begin() + 1,
8578                E = HistoryStack.end();
8579            I != E; ++I) {
8580         const FieldDecl *OuterField = *I;
8581         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8582           << OuterField->getType();
8583       }
8584 
8585       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8586         << QT->isPointerType()
8587         << QT;
8588       D.setInvalidType();
8589       return;
8590     }
8591   } while (!VisitStack.empty());
8592 }
8593 
8594 /// Find the DeclContext in which a tag is implicitly declared if we see an
8595 /// elaborated type specifier in the specified context, and lookup finds
8596 /// nothing.
8597 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8598   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8599     DC = DC->getParent();
8600   return DC;
8601 }
8602 
8603 /// Find the Scope in which a tag is implicitly declared if we see an
8604 /// elaborated type specifier in the specified context, and lookup finds
8605 /// nothing.
8606 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8607   while (S->isClassScope() ||
8608          (LangOpts.CPlusPlus &&
8609           S->isFunctionPrototypeScope()) ||
8610          ((S->getFlags() & Scope::DeclScope) == 0) ||
8611          (S->getEntity() && S->getEntity()->isTransparentContext()))
8612     S = S->getParent();
8613   return S;
8614 }
8615 
8616 NamedDecl*
8617 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8618                               TypeSourceInfo *TInfo, LookupResult &Previous,
8619                               MultiTemplateParamsArg TemplateParamLists,
8620                               bool &AddToScope) {
8621   QualType R = TInfo->getType();
8622 
8623   assert(R->isFunctionType());
8624 
8625   // TODO: consider using NameInfo for diagnostic.
8626   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8627   DeclarationName Name = NameInfo.getName();
8628   StorageClass SC = getFunctionStorageClass(*this, D);
8629 
8630   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8631     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8632          diag::err_invalid_thread)
8633       << DeclSpec::getSpecifierName(TSCS);
8634 
8635   if (D.isFirstDeclarationOfMember())
8636     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8637                            D.getIdentifierLoc());
8638 
8639   bool isFriend = false;
8640   FunctionTemplateDecl *FunctionTemplate = nullptr;
8641   bool isMemberSpecialization = false;
8642   bool isFunctionTemplateSpecialization = false;
8643 
8644   bool isDependentClassScopeExplicitSpecialization = false;
8645   bool HasExplicitTemplateArgs = false;
8646   TemplateArgumentListInfo TemplateArgs;
8647 
8648   bool isVirtualOkay = false;
8649 
8650   DeclContext *OriginalDC = DC;
8651   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8652 
8653   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8654                                               isVirtualOkay);
8655   if (!NewFD) return nullptr;
8656 
8657   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8658     NewFD->setTopLevelDeclInObjCContainer();
8659 
8660   // Set the lexical context. If this is a function-scope declaration, or has a
8661   // C++ scope specifier, or is the object of a friend declaration, the lexical
8662   // context will be different from the semantic context.
8663   NewFD->setLexicalDeclContext(CurContext);
8664 
8665   if (IsLocalExternDecl)
8666     NewFD->setLocalExternDecl();
8667 
8668   if (getLangOpts().CPlusPlus) {
8669     bool isInline = D.getDeclSpec().isInlineSpecified();
8670     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8671     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
8672     isFriend = D.getDeclSpec().isFriendSpecified();
8673     if (isFriend && !isInline && D.isFunctionDefinition()) {
8674       // C++ [class.friend]p5
8675       //   A function can be defined in a friend declaration of a
8676       //   class . . . . Such a function is implicitly inline.
8677       NewFD->setImplicitlyInline();
8678     }
8679 
8680     // If this is a method defined in an __interface, and is not a constructor
8681     // or an overloaded operator, then set the pure flag (isVirtual will already
8682     // return true).
8683     if (const CXXRecordDecl *Parent =
8684           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8685       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8686         NewFD->setPure(true);
8687 
8688       // C++ [class.union]p2
8689       //   A union can have member functions, but not virtual functions.
8690       if (isVirtual && Parent->isUnion())
8691         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8692     }
8693 
8694     SetNestedNameSpecifier(*this, NewFD, D);
8695     isMemberSpecialization = false;
8696     isFunctionTemplateSpecialization = false;
8697     if (D.isInvalidType())
8698       NewFD->setInvalidDecl();
8699 
8700     // Match up the template parameter lists with the scope specifier, then
8701     // determine whether we have a template or a template specialization.
8702     bool Invalid = false;
8703     if (TemplateParameterList *TemplateParams =
8704             MatchTemplateParametersToScopeSpecifier(
8705                 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8706                 D.getCXXScopeSpec(),
8707                 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8708                     ? D.getName().TemplateId
8709                     : nullptr,
8710                 TemplateParamLists, isFriend, isMemberSpecialization,
8711                 Invalid)) {
8712       if (TemplateParams->size() > 0) {
8713         // This is a function template
8714 
8715         // Check that we can declare a template here.
8716         if (CheckTemplateDeclScope(S, TemplateParams))
8717           NewFD->setInvalidDecl();
8718 
8719         // A destructor cannot be a template.
8720         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8721           Diag(NewFD->getLocation(), diag::err_destructor_template);
8722           NewFD->setInvalidDecl();
8723         }
8724 
8725         // If we're adding a template to a dependent context, we may need to
8726         // rebuilding some of the types used within the template parameter list,
8727         // now that we know what the current instantiation is.
8728         if (DC->isDependentContext()) {
8729           ContextRAII SavedContext(*this, DC);
8730           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8731             Invalid = true;
8732         }
8733 
8734         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8735                                                         NewFD->getLocation(),
8736                                                         Name, TemplateParams,
8737                                                         NewFD);
8738         FunctionTemplate->setLexicalDeclContext(CurContext);
8739         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8740 
8741         // For source fidelity, store the other template param lists.
8742         if (TemplateParamLists.size() > 1) {
8743           NewFD->setTemplateParameterListsInfo(Context,
8744                                                TemplateParamLists.drop_back(1));
8745         }
8746       } else {
8747         // This is a function template specialization.
8748         isFunctionTemplateSpecialization = true;
8749         // For source fidelity, store all the template param lists.
8750         if (TemplateParamLists.size() > 0)
8751           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8752 
8753         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8754         if (isFriend) {
8755           // We want to remove the "template<>", found here.
8756           SourceRange RemoveRange = TemplateParams->getSourceRange();
8757 
8758           // If we remove the template<> and the name is not a
8759           // template-id, we're actually silently creating a problem:
8760           // the friend declaration will refer to an untemplated decl,
8761           // and clearly the user wants a template specialization.  So
8762           // we need to insert '<>' after the name.
8763           SourceLocation InsertLoc;
8764           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8765             InsertLoc = D.getName().getSourceRange().getEnd();
8766             InsertLoc = getLocForEndOfToken(InsertLoc);
8767           }
8768 
8769           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8770             << Name << RemoveRange
8771             << FixItHint::CreateRemoval(RemoveRange)
8772             << FixItHint::CreateInsertion(InsertLoc, "<>");
8773         }
8774       }
8775     } else {
8776       // All template param lists were matched against the scope specifier:
8777       // this is NOT (an explicit specialization of) a template.
8778       if (TemplateParamLists.size() > 0)
8779         // For source fidelity, store all the template param lists.
8780         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8781     }
8782 
8783     if (Invalid) {
8784       NewFD->setInvalidDecl();
8785       if (FunctionTemplate)
8786         FunctionTemplate->setInvalidDecl();
8787     }
8788 
8789     // C++ [dcl.fct.spec]p5:
8790     //   The virtual specifier shall only be used in declarations of
8791     //   nonstatic class member functions that appear within a
8792     //   member-specification of a class declaration; see 10.3.
8793     //
8794     if (isVirtual && !NewFD->isInvalidDecl()) {
8795       if (!isVirtualOkay) {
8796         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8797              diag::err_virtual_non_function);
8798       } else if (!CurContext->isRecord()) {
8799         // 'virtual' was specified outside of the class.
8800         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8801              diag::err_virtual_out_of_class)
8802           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8803       } else if (NewFD->getDescribedFunctionTemplate()) {
8804         // C++ [temp.mem]p3:
8805         //  A member function template shall not be virtual.
8806         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8807              diag::err_virtual_member_function_template)
8808           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8809       } else {
8810         // Okay: Add virtual to the method.
8811         NewFD->setVirtualAsWritten(true);
8812       }
8813 
8814       if (getLangOpts().CPlusPlus14 &&
8815           NewFD->getReturnType()->isUndeducedType())
8816         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8817     }
8818 
8819     if (getLangOpts().CPlusPlus14 &&
8820         (NewFD->isDependentContext() ||
8821          (isFriend && CurContext->isDependentContext())) &&
8822         NewFD->getReturnType()->isUndeducedType()) {
8823       // If the function template is referenced directly (for instance, as a
8824       // member of the current instantiation), pretend it has a dependent type.
8825       // This is not really justified by the standard, but is the only sane
8826       // thing to do.
8827       // FIXME: For a friend function, we have not marked the function as being
8828       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8829       const FunctionProtoType *FPT =
8830           NewFD->getType()->castAs<FunctionProtoType>();
8831       QualType Result =
8832           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8833       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8834                                              FPT->getExtProtoInfo()));
8835     }
8836 
8837     // C++ [dcl.fct.spec]p3:
8838     //  The inline specifier shall not appear on a block scope function
8839     //  declaration.
8840     if (isInline && !NewFD->isInvalidDecl()) {
8841       if (CurContext->isFunctionOrMethod()) {
8842         // 'inline' is not allowed on block scope function declaration.
8843         Diag(D.getDeclSpec().getInlineSpecLoc(),
8844              diag::err_inline_declaration_block_scope) << Name
8845           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8846       }
8847     }
8848 
8849     // C++ [dcl.fct.spec]p6:
8850     //  The explicit specifier shall be used only in the declaration of a
8851     //  constructor or conversion function within its class definition;
8852     //  see 12.3.1 and 12.3.2.
8853     if (hasExplicit && !NewFD->isInvalidDecl() &&
8854         !isa<CXXDeductionGuideDecl>(NewFD)) {
8855       if (!CurContext->isRecord()) {
8856         // 'explicit' was specified outside of the class.
8857         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8858              diag::err_explicit_out_of_class)
8859             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
8860       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8861                  !isa<CXXConversionDecl>(NewFD)) {
8862         // 'explicit' was specified on a function that wasn't a constructor
8863         // or conversion function.
8864         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8865              diag::err_explicit_non_ctor_or_conv_function)
8866             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
8867       }
8868     }
8869 
8870     if (ConstexprSpecKind ConstexprKind =
8871             D.getDeclSpec().getConstexprSpecifier()) {
8872       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8873       // are implicitly inline.
8874       NewFD->setImplicitlyInline();
8875 
8876       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8877       // be either constructors or to return a literal type. Therefore,
8878       // destructors cannot be declared constexpr.
8879       if (isa<CXXDestructorDecl>(NewFD) && !getLangOpts().CPlusPlus2a) {
8880         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
8881             << ConstexprKind;
8882       }
8883     }
8884 
8885     // If __module_private__ was specified, mark the function accordingly.
8886     if (D.getDeclSpec().isModulePrivateSpecified()) {
8887       if (isFunctionTemplateSpecialization) {
8888         SourceLocation ModulePrivateLoc
8889           = D.getDeclSpec().getModulePrivateSpecLoc();
8890         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8891           << 0
8892           << FixItHint::CreateRemoval(ModulePrivateLoc);
8893       } else {
8894         NewFD->setModulePrivate();
8895         if (FunctionTemplate)
8896           FunctionTemplate->setModulePrivate();
8897       }
8898     }
8899 
8900     if (isFriend) {
8901       if (FunctionTemplate) {
8902         FunctionTemplate->setObjectOfFriendDecl();
8903         FunctionTemplate->setAccess(AS_public);
8904       }
8905       NewFD->setObjectOfFriendDecl();
8906       NewFD->setAccess(AS_public);
8907     }
8908 
8909     // If a function is defined as defaulted or deleted, mark it as such now.
8910     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8911     // definition kind to FDK_Definition.
8912     switch (D.getFunctionDefinitionKind()) {
8913       case FDK_Declaration:
8914       case FDK_Definition:
8915         break;
8916 
8917       case FDK_Defaulted:
8918         NewFD->setDefaulted();
8919         break;
8920 
8921       case FDK_Deleted:
8922         NewFD->setDeletedAsWritten();
8923         break;
8924     }
8925 
8926     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8927         D.isFunctionDefinition()) {
8928       // C++ [class.mfct]p2:
8929       //   A member function may be defined (8.4) in its class definition, in
8930       //   which case it is an inline member function (7.1.2)
8931       NewFD->setImplicitlyInline();
8932     }
8933 
8934     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8935         !CurContext->isRecord()) {
8936       // C++ [class.static]p1:
8937       //   A data or function member of a class may be declared static
8938       //   in a class definition, in which case it is a static member of
8939       //   the class.
8940 
8941       // Complain about the 'static' specifier if it's on an out-of-line
8942       // member function definition.
8943 
8944       // MSVC permits the use of a 'static' storage specifier on an out-of-line
8945       // member function template declaration and class member template
8946       // declaration (MSVC versions before 2015), warn about this.
8947       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8948            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
8949              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
8950            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
8951            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
8952         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8953     }
8954 
8955     // C++11 [except.spec]p15:
8956     //   A deallocation function with no exception-specification is treated
8957     //   as if it were specified with noexcept(true).
8958     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8959     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8960          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8961         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8962       NewFD->setType(Context.getFunctionType(
8963           FPT->getReturnType(), FPT->getParamTypes(),
8964           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8965   }
8966 
8967   // Filter out previous declarations that don't match the scope.
8968   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8969                        D.getCXXScopeSpec().isNotEmpty() ||
8970                        isMemberSpecialization ||
8971                        isFunctionTemplateSpecialization);
8972 
8973   // Handle GNU asm-label extension (encoded as an attribute).
8974   if (Expr *E = (Expr*) D.getAsmLabel()) {
8975     // The parser guarantees this is a string.
8976     StringLiteral *SE = cast<StringLiteral>(E);
8977     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
8978                                         /*IsLiteralLabel=*/true,
8979                                         SE->getStrTokenLoc(0)));
8980   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8981     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8982       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8983     if (I != ExtnameUndeclaredIdentifiers.end()) {
8984       if (isDeclExternC(NewFD)) {
8985         NewFD->addAttr(I->second);
8986         ExtnameUndeclaredIdentifiers.erase(I);
8987       } else
8988         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8989             << /*Variable*/0 << NewFD;
8990     }
8991   }
8992 
8993   // Copy the parameter declarations from the declarator D to the function
8994   // declaration NewFD, if they are available.  First scavenge them into Params.
8995   SmallVector<ParmVarDecl*, 16> Params;
8996   unsigned FTIIdx;
8997   if (D.isFunctionDeclarator(FTIIdx)) {
8998     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8999 
9000     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9001     // function that takes no arguments, not a function that takes a
9002     // single void argument.
9003     // We let through "const void" here because Sema::GetTypeForDeclarator
9004     // already checks for that case.
9005     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9006       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9007         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9008         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9009         Param->setDeclContext(NewFD);
9010         Params.push_back(Param);
9011 
9012         if (Param->isInvalidDecl())
9013           NewFD->setInvalidDecl();
9014       }
9015     }
9016 
9017     if (!getLangOpts().CPlusPlus) {
9018       // In C, find all the tag declarations from the prototype and move them
9019       // into the function DeclContext. Remove them from the surrounding tag
9020       // injection context of the function, which is typically but not always
9021       // the TU.
9022       DeclContext *PrototypeTagContext =
9023           getTagInjectionContext(NewFD->getLexicalDeclContext());
9024       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9025         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9026 
9027         // We don't want to reparent enumerators. Look at their parent enum
9028         // instead.
9029         if (!TD) {
9030           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9031             TD = cast<EnumDecl>(ECD->getDeclContext());
9032         }
9033         if (!TD)
9034           continue;
9035         DeclContext *TagDC = TD->getLexicalDeclContext();
9036         if (!TagDC->containsDecl(TD))
9037           continue;
9038         TagDC->removeDecl(TD);
9039         TD->setDeclContext(NewFD);
9040         NewFD->addDecl(TD);
9041 
9042         // Preserve the lexical DeclContext if it is not the surrounding tag
9043         // injection context of the FD. In this example, the semantic context of
9044         // E will be f and the lexical context will be S, while both the
9045         // semantic and lexical contexts of S will be f:
9046         //   void f(struct S { enum E { a } f; } s);
9047         if (TagDC != PrototypeTagContext)
9048           TD->setLexicalDeclContext(TagDC);
9049       }
9050     }
9051   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9052     // When we're declaring a function with a typedef, typeof, etc as in the
9053     // following example, we'll need to synthesize (unnamed)
9054     // parameters for use in the declaration.
9055     //
9056     // @code
9057     // typedef void fn(int);
9058     // fn f;
9059     // @endcode
9060 
9061     // Synthesize a parameter for each argument type.
9062     for (const auto &AI : FT->param_types()) {
9063       ParmVarDecl *Param =
9064           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9065       Param->setScopeInfo(0, Params.size());
9066       Params.push_back(Param);
9067     }
9068   } else {
9069     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9070            "Should not need args for typedef of non-prototype fn");
9071   }
9072 
9073   // Finally, we know we have the right number of parameters, install them.
9074   NewFD->setParams(Params);
9075 
9076   if (D.getDeclSpec().isNoreturnSpecified())
9077     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9078                                            D.getDeclSpec().getNoreturnSpecLoc(),
9079                                            AttributeCommonInfo::AS_Keyword));
9080 
9081   // Functions returning a variably modified type violate C99 6.7.5.2p2
9082   // because all functions have linkage.
9083   if (!NewFD->isInvalidDecl() &&
9084       NewFD->getReturnType()->isVariablyModifiedType()) {
9085     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9086     NewFD->setInvalidDecl();
9087   }
9088 
9089   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9090   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9091       !NewFD->hasAttr<SectionAttr>())
9092     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9093         Context, PragmaClangTextSection.SectionName,
9094         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9095 
9096   // Apply an implicit SectionAttr if #pragma code_seg is active.
9097   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9098       !NewFD->hasAttr<SectionAttr>()) {
9099     NewFD->addAttr(SectionAttr::CreateImplicit(
9100         Context, CodeSegStack.CurrentValue->getString(),
9101         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9102         SectionAttr::Declspec_allocate));
9103     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9104                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9105                          ASTContext::PSF_Read,
9106                      NewFD))
9107       NewFD->dropAttr<SectionAttr>();
9108   }
9109 
9110   // Apply an implicit CodeSegAttr from class declspec or
9111   // apply an implicit SectionAttr from #pragma code_seg if active.
9112   if (!NewFD->hasAttr<CodeSegAttr>()) {
9113     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9114                                                                  D.isFunctionDefinition())) {
9115       NewFD->addAttr(SAttr);
9116     }
9117   }
9118 
9119   // Handle attributes.
9120   ProcessDeclAttributes(S, NewFD, D);
9121 
9122   if (getLangOpts().OpenCL) {
9123     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9124     // type declaration will generate a compilation error.
9125     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9126     if (AddressSpace != LangAS::Default) {
9127       Diag(NewFD->getLocation(),
9128            diag::err_opencl_return_value_with_address_space);
9129       NewFD->setInvalidDecl();
9130     }
9131   }
9132 
9133   if (!getLangOpts().CPlusPlus) {
9134     // Perform semantic checking on the function declaration.
9135     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9136       CheckMain(NewFD, D.getDeclSpec());
9137 
9138     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9139       CheckMSVCRTEntryPoint(NewFD);
9140 
9141     if (!NewFD->isInvalidDecl())
9142       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9143                                                   isMemberSpecialization));
9144     else if (!Previous.empty())
9145       // Recover gracefully from an invalid redeclaration.
9146       D.setRedeclaration(true);
9147     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9148             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9149            "previous declaration set still overloaded");
9150 
9151     // Diagnose no-prototype function declarations with calling conventions that
9152     // don't support variadic calls. Only do this in C and do it after merging
9153     // possibly prototyped redeclarations.
9154     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9155     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9156       CallingConv CC = FT->getExtInfo().getCC();
9157       if (!supportsVariadicCall(CC)) {
9158         // Windows system headers sometimes accidentally use stdcall without
9159         // (void) parameters, so we relax this to a warning.
9160         int DiagID =
9161             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9162         Diag(NewFD->getLocation(), DiagID)
9163             << FunctionType::getNameForCallConv(CC);
9164       }
9165     }
9166 
9167    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9168        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9169      checkNonTrivialCUnion(NewFD->getReturnType(),
9170                            NewFD->getReturnTypeSourceRange().getBegin(),
9171                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9172   } else {
9173     // C++11 [replacement.functions]p3:
9174     //  The program's definitions shall not be specified as inline.
9175     //
9176     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9177     //
9178     // Suppress the diagnostic if the function is __attribute__((used)), since
9179     // that forces an external definition to be emitted.
9180     if (D.getDeclSpec().isInlineSpecified() &&
9181         NewFD->isReplaceableGlobalAllocationFunction() &&
9182         !NewFD->hasAttr<UsedAttr>())
9183       Diag(D.getDeclSpec().getInlineSpecLoc(),
9184            diag::ext_operator_new_delete_declared_inline)
9185         << NewFD->getDeclName();
9186 
9187     // If the declarator is a template-id, translate the parser's template
9188     // argument list into our AST format.
9189     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9190       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9191       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9192       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9193       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9194                                          TemplateId->NumArgs);
9195       translateTemplateArguments(TemplateArgsPtr,
9196                                  TemplateArgs);
9197 
9198       HasExplicitTemplateArgs = true;
9199 
9200       if (NewFD->isInvalidDecl()) {
9201         HasExplicitTemplateArgs = false;
9202       } else if (FunctionTemplate) {
9203         // Function template with explicit template arguments.
9204         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9205           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9206 
9207         HasExplicitTemplateArgs = false;
9208       } else {
9209         assert((isFunctionTemplateSpecialization ||
9210                 D.getDeclSpec().isFriendSpecified()) &&
9211                "should have a 'template<>' for this decl");
9212         // "friend void foo<>(int);" is an implicit specialization decl.
9213         isFunctionTemplateSpecialization = true;
9214       }
9215     } else if (isFriend && isFunctionTemplateSpecialization) {
9216       // This combination is only possible in a recovery case;  the user
9217       // wrote something like:
9218       //   template <> friend void foo(int);
9219       // which we're recovering from as if the user had written:
9220       //   friend void foo<>(int);
9221       // Go ahead and fake up a template id.
9222       HasExplicitTemplateArgs = true;
9223       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9224       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9225     }
9226 
9227     // We do not add HD attributes to specializations here because
9228     // they may have different constexpr-ness compared to their
9229     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9230     // may end up with different effective targets. Instead, a
9231     // specialization inherits its target attributes from its template
9232     // in the CheckFunctionTemplateSpecialization() call below.
9233     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9234       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9235 
9236     // If it's a friend (and only if it's a friend), it's possible
9237     // that either the specialized function type or the specialized
9238     // template is dependent, and therefore matching will fail.  In
9239     // this case, don't check the specialization yet.
9240     bool InstantiationDependent = false;
9241     if (isFunctionTemplateSpecialization && isFriend &&
9242         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9243          TemplateSpecializationType::anyDependentTemplateArguments(
9244             TemplateArgs,
9245             InstantiationDependent))) {
9246       assert(HasExplicitTemplateArgs &&
9247              "friend function specialization without template args");
9248       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9249                                                        Previous))
9250         NewFD->setInvalidDecl();
9251     } else if (isFunctionTemplateSpecialization) {
9252       if (CurContext->isDependentContext() && CurContext->isRecord()
9253           && !isFriend) {
9254         isDependentClassScopeExplicitSpecialization = true;
9255       } else if (!NewFD->isInvalidDecl() &&
9256                  CheckFunctionTemplateSpecialization(
9257                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9258                      Previous))
9259         NewFD->setInvalidDecl();
9260 
9261       // C++ [dcl.stc]p1:
9262       //   A storage-class-specifier shall not be specified in an explicit
9263       //   specialization (14.7.3)
9264       FunctionTemplateSpecializationInfo *Info =
9265           NewFD->getTemplateSpecializationInfo();
9266       if (Info && SC != SC_None) {
9267         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9268           Diag(NewFD->getLocation(),
9269                diag::err_explicit_specialization_inconsistent_storage_class)
9270             << SC
9271             << FixItHint::CreateRemoval(
9272                                       D.getDeclSpec().getStorageClassSpecLoc());
9273 
9274         else
9275           Diag(NewFD->getLocation(),
9276                diag::ext_explicit_specialization_storage_class)
9277             << FixItHint::CreateRemoval(
9278                                       D.getDeclSpec().getStorageClassSpecLoc());
9279       }
9280     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9281       if (CheckMemberSpecialization(NewFD, Previous))
9282           NewFD->setInvalidDecl();
9283     }
9284 
9285     // Perform semantic checking on the function declaration.
9286     if (!isDependentClassScopeExplicitSpecialization) {
9287       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9288         CheckMain(NewFD, D.getDeclSpec());
9289 
9290       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9291         CheckMSVCRTEntryPoint(NewFD);
9292 
9293       if (!NewFD->isInvalidDecl())
9294         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9295                                                     isMemberSpecialization));
9296       else if (!Previous.empty())
9297         // Recover gracefully from an invalid redeclaration.
9298         D.setRedeclaration(true);
9299     }
9300 
9301     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9302             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9303            "previous declaration set still overloaded");
9304 
9305     NamedDecl *PrincipalDecl = (FunctionTemplate
9306                                 ? cast<NamedDecl>(FunctionTemplate)
9307                                 : NewFD);
9308 
9309     if (isFriend && NewFD->getPreviousDecl()) {
9310       AccessSpecifier Access = AS_public;
9311       if (!NewFD->isInvalidDecl())
9312         Access = NewFD->getPreviousDecl()->getAccess();
9313 
9314       NewFD->setAccess(Access);
9315       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9316     }
9317 
9318     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9319         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9320       PrincipalDecl->setNonMemberOperator();
9321 
9322     // If we have a function template, check the template parameter
9323     // list. This will check and merge default template arguments.
9324     if (FunctionTemplate) {
9325       FunctionTemplateDecl *PrevTemplate =
9326                                      FunctionTemplate->getPreviousDecl();
9327       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9328                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9329                                     : nullptr,
9330                             D.getDeclSpec().isFriendSpecified()
9331                               ? (D.isFunctionDefinition()
9332                                    ? TPC_FriendFunctionTemplateDefinition
9333                                    : TPC_FriendFunctionTemplate)
9334                               : (D.getCXXScopeSpec().isSet() &&
9335                                  DC && DC->isRecord() &&
9336                                  DC->isDependentContext())
9337                                   ? TPC_ClassTemplateMember
9338                                   : TPC_FunctionTemplate);
9339     }
9340 
9341     if (NewFD->isInvalidDecl()) {
9342       // Ignore all the rest of this.
9343     } else if (!D.isRedeclaration()) {
9344       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9345                                        AddToScope };
9346       // Fake up an access specifier if it's supposed to be a class member.
9347       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9348         NewFD->setAccess(AS_public);
9349 
9350       // Qualified decls generally require a previous declaration.
9351       if (D.getCXXScopeSpec().isSet()) {
9352         // ...with the major exception of templated-scope or
9353         // dependent-scope friend declarations.
9354 
9355         // TODO: we currently also suppress this check in dependent
9356         // contexts because (1) the parameter depth will be off when
9357         // matching friend templates and (2) we might actually be
9358         // selecting a friend based on a dependent factor.  But there
9359         // are situations where these conditions don't apply and we
9360         // can actually do this check immediately.
9361         //
9362         // Unless the scope is dependent, it's always an error if qualified
9363         // redeclaration lookup found nothing at all. Diagnose that now;
9364         // nothing will diagnose that error later.
9365         if (isFriend &&
9366             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9367              (!Previous.empty() && CurContext->isDependentContext()))) {
9368           // ignore these
9369         } else {
9370           // The user tried to provide an out-of-line definition for a
9371           // function that is a member of a class or namespace, but there
9372           // was no such member function declared (C++ [class.mfct]p2,
9373           // C++ [namespace.memdef]p2). For example:
9374           //
9375           // class X {
9376           //   void f() const;
9377           // };
9378           //
9379           // void X::f() { } // ill-formed
9380           //
9381           // Complain about this problem, and attempt to suggest close
9382           // matches (e.g., those that differ only in cv-qualifiers and
9383           // whether the parameter types are references).
9384 
9385           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9386                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9387             AddToScope = ExtraArgs.AddToScope;
9388             return Result;
9389           }
9390         }
9391 
9392         // Unqualified local friend declarations are required to resolve
9393         // to something.
9394       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9395         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9396                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9397           AddToScope = ExtraArgs.AddToScope;
9398           return Result;
9399         }
9400       }
9401     } else if (!D.isFunctionDefinition() &&
9402                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9403                !isFriend && !isFunctionTemplateSpecialization &&
9404                !isMemberSpecialization) {
9405       // An out-of-line member function declaration must also be a
9406       // definition (C++ [class.mfct]p2).
9407       // Note that this is not the case for explicit specializations of
9408       // function templates or member functions of class templates, per
9409       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9410       // extension for compatibility with old SWIG code which likes to
9411       // generate them.
9412       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9413         << D.getCXXScopeSpec().getRange();
9414     }
9415   }
9416 
9417   ProcessPragmaWeak(S, NewFD);
9418   checkAttributesAfterMerging(*this, *NewFD);
9419 
9420   AddKnownFunctionAttributes(NewFD);
9421 
9422   if (NewFD->hasAttr<OverloadableAttr>() &&
9423       !NewFD->getType()->getAs<FunctionProtoType>()) {
9424     Diag(NewFD->getLocation(),
9425          diag::err_attribute_overloadable_no_prototype)
9426       << NewFD;
9427 
9428     // Turn this into a variadic function with no parameters.
9429     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9430     FunctionProtoType::ExtProtoInfo EPI(
9431         Context.getDefaultCallingConvention(true, false));
9432     EPI.Variadic = true;
9433     EPI.ExtInfo = FT->getExtInfo();
9434 
9435     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9436     NewFD->setType(R);
9437   }
9438 
9439   // If there's a #pragma GCC visibility in scope, and this isn't a class
9440   // member, set the visibility of this function.
9441   if (!DC->isRecord() && NewFD->isExternallyVisible())
9442     AddPushedVisibilityAttribute(NewFD);
9443 
9444   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9445   // marking the function.
9446   AddCFAuditedAttribute(NewFD);
9447 
9448   // If this is a function definition, check if we have to apply optnone due to
9449   // a pragma.
9450   if(D.isFunctionDefinition())
9451     AddRangeBasedOptnone(NewFD);
9452 
9453   // If this is the first declaration of an extern C variable, update
9454   // the map of such variables.
9455   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9456       isIncompleteDeclExternC(*this, NewFD))
9457     RegisterLocallyScopedExternCDecl(NewFD, S);
9458 
9459   // Set this FunctionDecl's range up to the right paren.
9460   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9461 
9462   if (D.isRedeclaration() && !Previous.empty()) {
9463     NamedDecl *Prev = Previous.getRepresentativeDecl();
9464     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9465                                    isMemberSpecialization ||
9466                                        isFunctionTemplateSpecialization,
9467                                    D.isFunctionDefinition());
9468   }
9469 
9470   if (getLangOpts().CUDA) {
9471     IdentifierInfo *II = NewFD->getIdentifier();
9472     if (II && II->isStr(getCudaConfigureFuncName()) &&
9473         !NewFD->isInvalidDecl() &&
9474         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9475       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9476         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9477             << getCudaConfigureFuncName();
9478       Context.setcudaConfigureCallDecl(NewFD);
9479     }
9480 
9481     // Variadic functions, other than a *declaration* of printf, are not allowed
9482     // in device-side CUDA code, unless someone passed
9483     // -fcuda-allow-variadic-functions.
9484     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9485         (NewFD->hasAttr<CUDADeviceAttr>() ||
9486          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9487         !(II && II->isStr("printf") && NewFD->isExternC() &&
9488           !D.isFunctionDefinition())) {
9489       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9490     }
9491   }
9492 
9493   MarkUnusedFileScopedDecl(NewFD);
9494 
9495 
9496 
9497   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9498     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9499     if ((getLangOpts().OpenCLVersion >= 120)
9500         && (SC == SC_Static)) {
9501       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9502       D.setInvalidType();
9503     }
9504 
9505     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9506     if (!NewFD->getReturnType()->isVoidType()) {
9507       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9508       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9509           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9510                                 : FixItHint());
9511       D.setInvalidType();
9512     }
9513 
9514     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9515     for (auto Param : NewFD->parameters())
9516       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9517 
9518     if (getLangOpts().OpenCLCPlusPlus) {
9519       if (DC->isRecord()) {
9520         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9521         D.setInvalidType();
9522       }
9523       if (FunctionTemplate) {
9524         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9525         D.setInvalidType();
9526       }
9527     }
9528   }
9529 
9530   if (getLangOpts().CPlusPlus) {
9531     if (FunctionTemplate) {
9532       if (NewFD->isInvalidDecl())
9533         FunctionTemplate->setInvalidDecl();
9534       return FunctionTemplate;
9535     }
9536 
9537     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9538       CompleteMemberSpecialization(NewFD, Previous);
9539   }
9540 
9541   for (const ParmVarDecl *Param : NewFD->parameters()) {
9542     QualType PT = Param->getType();
9543 
9544     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9545     // types.
9546     if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
9547       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9548         QualType ElemTy = PipeTy->getElementType();
9549           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9550             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9551             D.setInvalidType();
9552           }
9553       }
9554     }
9555   }
9556 
9557   // Here we have an function template explicit specialization at class scope.
9558   // The actual specialization will be postponed to template instatiation
9559   // time via the ClassScopeFunctionSpecializationDecl node.
9560   if (isDependentClassScopeExplicitSpecialization) {
9561     ClassScopeFunctionSpecializationDecl *NewSpec =
9562                          ClassScopeFunctionSpecializationDecl::Create(
9563                                 Context, CurContext, NewFD->getLocation(),
9564                                 cast<CXXMethodDecl>(NewFD),
9565                                 HasExplicitTemplateArgs, TemplateArgs);
9566     CurContext->addDecl(NewSpec);
9567     AddToScope = false;
9568   }
9569 
9570   // Diagnose availability attributes. Availability cannot be used on functions
9571   // that are run during load/unload.
9572   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9573     if (NewFD->hasAttr<ConstructorAttr>()) {
9574       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9575           << 1;
9576       NewFD->dropAttr<AvailabilityAttr>();
9577     }
9578     if (NewFD->hasAttr<DestructorAttr>()) {
9579       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9580           << 2;
9581       NewFD->dropAttr<AvailabilityAttr>();
9582     }
9583   }
9584 
9585   // Diagnose no_builtin attribute on function declaration that are not a
9586   // definition.
9587   // FIXME: We should really be doing this in
9588   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
9589   // the FunctionDecl and at this point of the code
9590   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
9591   // because Sema::ActOnStartOfFunctionDef has not been called yet.
9592   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
9593     switch (D.getFunctionDefinitionKind()) {
9594     case FDK_Defaulted:
9595     case FDK_Deleted:
9596       Diag(NBA->getLocation(),
9597            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
9598           << NBA->getSpelling();
9599       break;
9600     case FDK_Declaration:
9601       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
9602           << NBA->getSpelling();
9603       break;
9604     case FDK_Definition:
9605       break;
9606     }
9607 
9608   return NewFD;
9609 }
9610 
9611 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
9612 /// when __declspec(code_seg) "is applied to a class, all member functions of
9613 /// the class and nested classes -- this includes compiler-generated special
9614 /// member functions -- are put in the specified segment."
9615 /// The actual behavior is a little more complicated. The Microsoft compiler
9616 /// won't check outer classes if there is an active value from #pragma code_seg.
9617 /// The CodeSeg is always applied from the direct parent but only from outer
9618 /// classes when the #pragma code_seg stack is empty. See:
9619 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9620 /// available since MS has removed the page.
9621 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9622   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9623   if (!Method)
9624     return nullptr;
9625   const CXXRecordDecl *Parent = Method->getParent();
9626   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9627     Attr *NewAttr = SAttr->clone(S.getASTContext());
9628     NewAttr->setImplicit(true);
9629     return NewAttr;
9630   }
9631 
9632   // The Microsoft compiler won't check outer classes for the CodeSeg
9633   // when the #pragma code_seg stack is active.
9634   if (S.CodeSegStack.CurrentValue)
9635    return nullptr;
9636 
9637   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9638     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9639       Attr *NewAttr = SAttr->clone(S.getASTContext());
9640       NewAttr->setImplicit(true);
9641       return NewAttr;
9642     }
9643   }
9644   return nullptr;
9645 }
9646 
9647 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9648 /// containing class. Otherwise it will return implicit SectionAttr if the
9649 /// function is a definition and there is an active value on CodeSegStack
9650 /// (from the current #pragma code-seg value).
9651 ///
9652 /// \param FD Function being declared.
9653 /// \param IsDefinition Whether it is a definition or just a declarartion.
9654 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
9655 ///          nullptr if no attribute should be added.
9656 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9657                                                        bool IsDefinition) {
9658   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9659     return A;
9660   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9661       CodeSegStack.CurrentValue)
9662     return SectionAttr::CreateImplicit(
9663         getASTContext(), CodeSegStack.CurrentValue->getString(),
9664         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9665         SectionAttr::Declspec_allocate);
9666   return nullptr;
9667 }
9668 
9669 /// Determines if we can perform a correct type check for \p D as a
9670 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
9671 /// best-effort check.
9672 ///
9673 /// \param NewD The new declaration.
9674 /// \param OldD The old declaration.
9675 /// \param NewT The portion of the type of the new declaration to check.
9676 /// \param OldT The portion of the type of the old declaration to check.
9677 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
9678                                           QualType NewT, QualType OldT) {
9679   if (!NewD->getLexicalDeclContext()->isDependentContext())
9680     return true;
9681 
9682   // For dependently-typed local extern declarations and friends, we can't
9683   // perform a correct type check in general until instantiation:
9684   //
9685   //   int f();
9686   //   template<typename T> void g() { T f(); }
9687   //
9688   // (valid if g() is only instantiated with T = int).
9689   if (NewT->isDependentType() &&
9690       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
9691     return false;
9692 
9693   // Similarly, if the previous declaration was a dependent local extern
9694   // declaration, we don't really know its type yet.
9695   if (OldT->isDependentType() && OldD->isLocalExternDecl())
9696     return false;
9697 
9698   return true;
9699 }
9700 
9701 /// Checks if the new declaration declared in dependent context must be
9702 /// put in the same redeclaration chain as the specified declaration.
9703 ///
9704 /// \param D Declaration that is checked.
9705 /// \param PrevDecl Previous declaration found with proper lookup method for the
9706 ///                 same declaration name.
9707 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9708 ///          belongs to.
9709 ///
9710 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9711   if (!D->getLexicalDeclContext()->isDependentContext())
9712     return true;
9713 
9714   // Don't chain dependent friend function definitions until instantiation, to
9715   // permit cases like
9716   //
9717   //   void func();
9718   //   template<typename T> class C1 { friend void func() {} };
9719   //   template<typename T> class C2 { friend void func() {} };
9720   //
9721   // ... which is valid if only one of C1 and C2 is ever instantiated.
9722   //
9723   // FIXME: This need only apply to function definitions. For now, we proxy
9724   // this by checking for a file-scope function. We do not want this to apply
9725   // to friend declarations nominating member functions, because that gets in
9726   // the way of access checks.
9727   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
9728     return false;
9729 
9730   auto *VD = dyn_cast<ValueDecl>(D);
9731   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
9732   return !VD || !PrevVD ||
9733          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
9734                                         PrevVD->getType());
9735 }
9736 
9737 /// Check the target attribute of the function for MultiVersion
9738 /// validity.
9739 ///
9740 /// Returns true if there was an error, false otherwise.
9741 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9742   const auto *TA = FD->getAttr<TargetAttr>();
9743   assert(TA && "MultiVersion Candidate requires a target attribute");
9744   TargetAttr::ParsedTargetAttr ParseInfo = TA->parse();
9745   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9746   enum ErrType { Feature = 0, Architecture = 1 };
9747 
9748   if (!ParseInfo.Architecture.empty() &&
9749       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
9750     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9751         << Architecture << ParseInfo.Architecture;
9752     return true;
9753   }
9754 
9755   for (const auto &Feat : ParseInfo.Features) {
9756     auto BareFeat = StringRef{Feat}.substr(1);
9757     if (Feat[0] == '-') {
9758       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9759           << Feature << ("no-" + BareFeat).str();
9760       return true;
9761     }
9762 
9763     if (!TargetInfo.validateCpuSupports(BareFeat) ||
9764         !TargetInfo.isValidFeatureName(BareFeat)) {
9765       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9766           << Feature << BareFeat;
9767       return true;
9768     }
9769   }
9770   return false;
9771 }
9772 
9773 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD,
9774                                          MultiVersionKind MVType) {
9775   for (const Attr *A : FD->attrs()) {
9776     switch (A->getKind()) {
9777     case attr::CPUDispatch:
9778     case attr::CPUSpecific:
9779       if (MVType != MultiVersionKind::CPUDispatch &&
9780           MVType != MultiVersionKind::CPUSpecific)
9781         return true;
9782       break;
9783     case attr::Target:
9784       if (MVType != MultiVersionKind::Target)
9785         return true;
9786       break;
9787     default:
9788       return true;
9789     }
9790   }
9791   return false;
9792 }
9793 
9794 bool Sema::areMultiversionVariantFunctionsCompatible(
9795     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
9796     const PartialDiagnostic &NoProtoDiagID,
9797     const PartialDiagnosticAt &NoteCausedDiagIDAt,
9798     const PartialDiagnosticAt &NoSupportDiagIDAt,
9799     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
9800     bool ConstexprSupported, bool CLinkageMayDiffer) {
9801   enum DoesntSupport {
9802     FuncTemplates = 0,
9803     VirtFuncs = 1,
9804     DeducedReturn = 2,
9805     Constructors = 3,
9806     Destructors = 4,
9807     DeletedFuncs = 5,
9808     DefaultedFuncs = 6,
9809     ConstexprFuncs = 7,
9810     ConstevalFuncs = 8,
9811   };
9812   enum Different {
9813     CallingConv = 0,
9814     ReturnType = 1,
9815     ConstexprSpec = 2,
9816     InlineSpec = 3,
9817     StorageClass = 4,
9818     Linkage = 5,
9819   };
9820 
9821   if (OldFD && !OldFD->getType()->getAs<FunctionProtoType>()) {
9822     Diag(OldFD->getLocation(), NoProtoDiagID);
9823     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
9824     return true;
9825   }
9826 
9827   if (!NewFD->getType()->getAs<FunctionProtoType>())
9828     return Diag(NewFD->getLocation(), NoProtoDiagID);
9829 
9830   if (!TemplatesSupported &&
9831       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9832     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9833            << FuncTemplates;
9834 
9835   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
9836     if (NewCXXFD->isVirtual())
9837       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9838              << VirtFuncs;
9839 
9840     if (isa<CXXConstructorDecl>(NewCXXFD))
9841       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9842              << Constructors;
9843 
9844     if (isa<CXXDestructorDecl>(NewCXXFD))
9845       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9846              << Destructors;
9847   }
9848 
9849   if (NewFD->isDeleted())
9850     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9851            << DeletedFuncs;
9852 
9853   if (NewFD->isDefaulted())
9854     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9855            << DefaultedFuncs;
9856 
9857   if (!ConstexprSupported && NewFD->isConstexpr())
9858     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9859            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
9860 
9861   QualType NewQType = Context.getCanonicalType(NewFD->getType());
9862   const auto *NewType = cast<FunctionType>(NewQType);
9863   QualType NewReturnType = NewType->getReturnType();
9864 
9865   if (NewReturnType->isUndeducedType())
9866     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9867            << DeducedReturn;
9868 
9869   // Ensure the return type is identical.
9870   if (OldFD) {
9871     QualType OldQType = Context.getCanonicalType(OldFD->getType());
9872     const auto *OldType = cast<FunctionType>(OldQType);
9873     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
9874     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
9875 
9876     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
9877       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
9878 
9879     QualType OldReturnType = OldType->getReturnType();
9880 
9881     if (OldReturnType != NewReturnType)
9882       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
9883 
9884     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
9885       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
9886 
9887     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
9888       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
9889 
9890     if (OldFD->getStorageClass() != NewFD->getStorageClass())
9891       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass;
9892 
9893     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
9894       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
9895 
9896     if (CheckEquivalentExceptionSpec(
9897             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
9898             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
9899       return true;
9900   }
9901   return false;
9902 }
9903 
9904 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
9905                                              const FunctionDecl *NewFD,
9906                                              bool CausesMV,
9907                                              MultiVersionKind MVType) {
9908   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9909     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9910     if (OldFD)
9911       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9912     return true;
9913   }
9914 
9915   bool IsCPUSpecificCPUDispatchMVType =
9916       MVType == MultiVersionKind::CPUDispatch ||
9917       MVType == MultiVersionKind::CPUSpecific;
9918 
9919   // For now, disallow all other attributes.  These should be opt-in, but
9920   // an analysis of all of them is a future FIXME.
9921   if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) {
9922     S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
9923         << IsCPUSpecificCPUDispatchMVType;
9924     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9925     return true;
9926   }
9927 
9928   if (HasNonMultiVersionAttributes(NewFD, MVType))
9929     return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
9930            << IsCPUSpecificCPUDispatchMVType;
9931 
9932   // Only allow transition to MultiVersion if it hasn't been used.
9933   if (OldFD && CausesMV && OldFD->isUsed(false))
9934     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
9935 
9936   return S.areMultiversionVariantFunctionsCompatible(
9937       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
9938       PartialDiagnosticAt(NewFD->getLocation(),
9939                           S.PDiag(diag::note_multiversioning_caused_here)),
9940       PartialDiagnosticAt(NewFD->getLocation(),
9941                           S.PDiag(diag::err_multiversion_doesnt_support)
9942                               << IsCPUSpecificCPUDispatchMVType),
9943       PartialDiagnosticAt(NewFD->getLocation(),
9944                           S.PDiag(diag::err_multiversion_diff)),
9945       /*TemplatesSupported=*/false,
9946       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
9947       /*CLinkageMayDiffer=*/false);
9948 }
9949 
9950 /// Check the validity of a multiversion function declaration that is the
9951 /// first of its kind. Also sets the multiversion'ness' of the function itself.
9952 ///
9953 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9954 ///
9955 /// Returns true if there was an error, false otherwise.
9956 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
9957                                            MultiVersionKind MVType,
9958                                            const TargetAttr *TA) {
9959   assert(MVType != MultiVersionKind::None &&
9960          "Function lacks multiversion attribute");
9961 
9962   // Target only causes MV if it is default, otherwise this is a normal
9963   // function.
9964   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
9965     return false;
9966 
9967   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
9968     FD->setInvalidDecl();
9969     return true;
9970   }
9971 
9972   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
9973     FD->setInvalidDecl();
9974     return true;
9975   }
9976 
9977   FD->setIsMultiVersion();
9978   return false;
9979 }
9980 
9981 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
9982   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
9983     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
9984       return true;
9985   }
9986 
9987   return false;
9988 }
9989 
9990 static bool CheckTargetCausesMultiVersioning(
9991     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
9992     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
9993     LookupResult &Previous) {
9994   const auto *OldTA = OldFD->getAttr<TargetAttr>();
9995   TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse();
9996   // Sort order doesn't matter, it just needs to be consistent.
9997   llvm::sort(NewParsed.Features);
9998 
9999   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10000   // to change, this is a simple redeclaration.
10001   if (!NewTA->isDefaultVersion() &&
10002       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10003     return false;
10004 
10005   // Otherwise, this decl causes MultiVersioning.
10006   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10007     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10008     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10009     NewFD->setInvalidDecl();
10010     return true;
10011   }
10012 
10013   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10014                                        MultiVersionKind::Target)) {
10015     NewFD->setInvalidDecl();
10016     return true;
10017   }
10018 
10019   if (CheckMultiVersionValue(S, NewFD)) {
10020     NewFD->setInvalidDecl();
10021     return true;
10022   }
10023 
10024   // If this is 'default', permit the forward declaration.
10025   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10026     Redeclaration = true;
10027     OldDecl = OldFD;
10028     OldFD->setIsMultiVersion();
10029     NewFD->setIsMultiVersion();
10030     return false;
10031   }
10032 
10033   if (CheckMultiVersionValue(S, OldFD)) {
10034     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10035     NewFD->setInvalidDecl();
10036     return true;
10037   }
10038 
10039   TargetAttr::ParsedTargetAttr OldParsed =
10040       OldTA->parse(std::less<std::string>());
10041 
10042   if (OldParsed == NewParsed) {
10043     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10044     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10045     NewFD->setInvalidDecl();
10046     return true;
10047   }
10048 
10049   for (const auto *FD : OldFD->redecls()) {
10050     const auto *CurTA = FD->getAttr<TargetAttr>();
10051     // We allow forward declarations before ANY multiversioning attributes, but
10052     // nothing after the fact.
10053     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10054         (!CurTA || CurTA->isInherited())) {
10055       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10056           << 0;
10057       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10058       NewFD->setInvalidDecl();
10059       return true;
10060     }
10061   }
10062 
10063   OldFD->setIsMultiVersion();
10064   NewFD->setIsMultiVersion();
10065   Redeclaration = false;
10066   MergeTypeWithPrevious = false;
10067   OldDecl = nullptr;
10068   Previous.clear();
10069   return false;
10070 }
10071 
10072 /// Check the validity of a new function declaration being added to an existing
10073 /// multiversioned declaration collection.
10074 static bool CheckMultiVersionAdditionalDecl(
10075     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10076     MultiVersionKind NewMVType, const TargetAttr *NewTA,
10077     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10078     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10079     LookupResult &Previous) {
10080 
10081   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10082   // Disallow mixing of multiversioning types.
10083   if ((OldMVType == MultiVersionKind::Target &&
10084        NewMVType != MultiVersionKind::Target) ||
10085       (NewMVType == MultiVersionKind::Target &&
10086        OldMVType != MultiVersionKind::Target)) {
10087     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10088     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10089     NewFD->setInvalidDecl();
10090     return true;
10091   }
10092 
10093   TargetAttr::ParsedTargetAttr NewParsed;
10094   if (NewTA) {
10095     NewParsed = NewTA->parse();
10096     llvm::sort(NewParsed.Features);
10097   }
10098 
10099   bool UseMemberUsingDeclRules =
10100       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10101 
10102   // Next, check ALL non-overloads to see if this is a redeclaration of a
10103   // previous member of the MultiVersion set.
10104   for (NamedDecl *ND : Previous) {
10105     FunctionDecl *CurFD = ND->getAsFunction();
10106     if (!CurFD)
10107       continue;
10108     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10109       continue;
10110 
10111     if (NewMVType == MultiVersionKind::Target) {
10112       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10113       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10114         NewFD->setIsMultiVersion();
10115         Redeclaration = true;
10116         OldDecl = ND;
10117         return false;
10118       }
10119 
10120       TargetAttr::ParsedTargetAttr CurParsed =
10121           CurTA->parse(std::less<std::string>());
10122       if (CurParsed == NewParsed) {
10123         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10124         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10125         NewFD->setInvalidDecl();
10126         return true;
10127       }
10128     } else {
10129       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10130       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10131       // Handle CPUDispatch/CPUSpecific versions.
10132       // Only 1 CPUDispatch function is allowed, this will make it go through
10133       // the redeclaration errors.
10134       if (NewMVType == MultiVersionKind::CPUDispatch &&
10135           CurFD->hasAttr<CPUDispatchAttr>()) {
10136         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10137             std::equal(
10138                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10139                 NewCPUDisp->cpus_begin(),
10140                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10141                   return Cur->getName() == New->getName();
10142                 })) {
10143           NewFD->setIsMultiVersion();
10144           Redeclaration = true;
10145           OldDecl = ND;
10146           return false;
10147         }
10148 
10149         // If the declarations don't match, this is an error condition.
10150         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10151         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10152         NewFD->setInvalidDecl();
10153         return true;
10154       }
10155       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10156 
10157         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10158             std::equal(
10159                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10160                 NewCPUSpec->cpus_begin(),
10161                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10162                   return Cur->getName() == New->getName();
10163                 })) {
10164           NewFD->setIsMultiVersion();
10165           Redeclaration = true;
10166           OldDecl = ND;
10167           return false;
10168         }
10169 
10170         // Only 1 version of CPUSpecific is allowed for each CPU.
10171         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10172           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10173             if (CurII == NewII) {
10174               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10175                   << NewII;
10176               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10177               NewFD->setInvalidDecl();
10178               return true;
10179             }
10180           }
10181         }
10182       }
10183       // If the two decls aren't the same MVType, there is no possible error
10184       // condition.
10185     }
10186   }
10187 
10188   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10189   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10190   // handled in the attribute adding step.
10191   if (NewMVType == MultiVersionKind::Target &&
10192       CheckMultiVersionValue(S, NewFD)) {
10193     NewFD->setInvalidDecl();
10194     return true;
10195   }
10196 
10197   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10198                                        !OldFD->isMultiVersion(), NewMVType)) {
10199     NewFD->setInvalidDecl();
10200     return true;
10201   }
10202 
10203   // Permit forward declarations in the case where these two are compatible.
10204   if (!OldFD->isMultiVersion()) {
10205     OldFD->setIsMultiVersion();
10206     NewFD->setIsMultiVersion();
10207     Redeclaration = true;
10208     OldDecl = OldFD;
10209     return false;
10210   }
10211 
10212   NewFD->setIsMultiVersion();
10213   Redeclaration = false;
10214   MergeTypeWithPrevious = false;
10215   OldDecl = nullptr;
10216   Previous.clear();
10217   return false;
10218 }
10219 
10220 
10221 /// Check the validity of a mulitversion function declaration.
10222 /// Also sets the multiversion'ness' of the function itself.
10223 ///
10224 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10225 ///
10226 /// Returns true if there was an error, false otherwise.
10227 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10228                                       bool &Redeclaration, NamedDecl *&OldDecl,
10229                                       bool &MergeTypeWithPrevious,
10230                                       LookupResult &Previous) {
10231   const auto *NewTA = NewFD->getAttr<TargetAttr>();
10232   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10233   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10234 
10235   // Mixing Multiversioning types is prohibited.
10236   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
10237       (NewCPUDisp && NewCPUSpec)) {
10238     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10239     NewFD->setInvalidDecl();
10240     return true;
10241   }
10242 
10243   MultiVersionKind  MVType = NewFD->getMultiVersionKind();
10244 
10245   // Main isn't allowed to become a multiversion function, however it IS
10246   // permitted to have 'main' be marked with the 'target' optimization hint.
10247   if (NewFD->isMain()) {
10248     if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10249         MVType == MultiVersionKind::CPUDispatch ||
10250         MVType == MultiVersionKind::CPUSpecific) {
10251       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10252       NewFD->setInvalidDecl();
10253       return true;
10254     }
10255     return false;
10256   }
10257 
10258   if (!OldDecl || !OldDecl->getAsFunction() ||
10259       OldDecl->getDeclContext()->getRedeclContext() !=
10260           NewFD->getDeclContext()->getRedeclContext()) {
10261     // If there's no previous declaration, AND this isn't attempting to cause
10262     // multiversioning, this isn't an error condition.
10263     if (MVType == MultiVersionKind::None)
10264       return false;
10265     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10266   }
10267 
10268   FunctionDecl *OldFD = OldDecl->getAsFunction();
10269 
10270   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10271     return false;
10272 
10273   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10274     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10275         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10276     NewFD->setInvalidDecl();
10277     return true;
10278   }
10279 
10280   // Handle the target potentially causes multiversioning case.
10281   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10282     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10283                                             Redeclaration, OldDecl,
10284                                             MergeTypeWithPrevious, Previous);
10285 
10286   // At this point, we have a multiversion function decl (in OldFD) AND an
10287   // appropriate attribute in the current function decl.  Resolve that these are
10288   // still compatible with previous declarations.
10289   return CheckMultiVersionAdditionalDecl(
10290       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10291       OldDecl, MergeTypeWithPrevious, Previous);
10292 }
10293 
10294 /// Perform semantic checking of a new function declaration.
10295 ///
10296 /// Performs semantic analysis of the new function declaration
10297 /// NewFD. This routine performs all semantic checking that does not
10298 /// require the actual declarator involved in the declaration, and is
10299 /// used both for the declaration of functions as they are parsed
10300 /// (called via ActOnDeclarator) and for the declaration of functions
10301 /// that have been instantiated via C++ template instantiation (called
10302 /// via InstantiateDecl).
10303 ///
10304 /// \param IsMemberSpecialization whether this new function declaration is
10305 /// a member specialization (that replaces any definition provided by the
10306 /// previous declaration).
10307 ///
10308 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10309 ///
10310 /// \returns true if the function declaration is a redeclaration.
10311 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10312                                     LookupResult &Previous,
10313                                     bool IsMemberSpecialization) {
10314   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10315          "Variably modified return types are not handled here");
10316 
10317   // Determine whether the type of this function should be merged with
10318   // a previous visible declaration. This never happens for functions in C++,
10319   // and always happens in C if the previous declaration was visible.
10320   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10321                                !Previous.isShadowed();
10322 
10323   bool Redeclaration = false;
10324   NamedDecl *OldDecl = nullptr;
10325   bool MayNeedOverloadableChecks = false;
10326 
10327   // Merge or overload the declaration with an existing declaration of
10328   // the same name, if appropriate.
10329   if (!Previous.empty()) {
10330     // Determine whether NewFD is an overload of PrevDecl or
10331     // a declaration that requires merging. If it's an overload,
10332     // there's no more work to do here; we'll just add the new
10333     // function to the scope.
10334     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10335       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10336       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10337         Redeclaration = true;
10338         OldDecl = Candidate;
10339       }
10340     } else {
10341       MayNeedOverloadableChecks = true;
10342       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10343                             /*NewIsUsingDecl*/ false)) {
10344       case Ovl_Match:
10345         Redeclaration = true;
10346         break;
10347 
10348       case Ovl_NonFunction:
10349         Redeclaration = true;
10350         break;
10351 
10352       case Ovl_Overload:
10353         Redeclaration = false;
10354         break;
10355       }
10356     }
10357   }
10358 
10359   // Check for a previous extern "C" declaration with this name.
10360   if (!Redeclaration &&
10361       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10362     if (!Previous.empty()) {
10363       // This is an extern "C" declaration with the same name as a previous
10364       // declaration, and thus redeclares that entity...
10365       Redeclaration = true;
10366       OldDecl = Previous.getFoundDecl();
10367       MergeTypeWithPrevious = false;
10368 
10369       // ... except in the presence of __attribute__((overloadable)).
10370       if (OldDecl->hasAttr<OverloadableAttr>() ||
10371           NewFD->hasAttr<OverloadableAttr>()) {
10372         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10373           MayNeedOverloadableChecks = true;
10374           Redeclaration = false;
10375           OldDecl = nullptr;
10376         }
10377       }
10378     }
10379   }
10380 
10381   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10382                                 MergeTypeWithPrevious, Previous))
10383     return Redeclaration;
10384 
10385   // C++11 [dcl.constexpr]p8:
10386   //   A constexpr specifier for a non-static member function that is not
10387   //   a constructor declares that member function to be const.
10388   //
10389   // This needs to be delayed until we know whether this is an out-of-line
10390   // definition of a static member function.
10391   //
10392   // This rule is not present in C++1y, so we produce a backwards
10393   // compatibility warning whenever it happens in C++11.
10394   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10395   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10396       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10397       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10398     CXXMethodDecl *OldMD = nullptr;
10399     if (OldDecl)
10400       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10401     if (!OldMD || !OldMD->isStatic()) {
10402       const FunctionProtoType *FPT =
10403         MD->getType()->castAs<FunctionProtoType>();
10404       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10405       EPI.TypeQuals.addConst();
10406       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10407                                           FPT->getParamTypes(), EPI));
10408 
10409       // Warn that we did this, if we're not performing template instantiation.
10410       // In that case, we'll have warned already when the template was defined.
10411       if (!inTemplateInstantiation()) {
10412         SourceLocation AddConstLoc;
10413         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10414                 .IgnoreParens().getAs<FunctionTypeLoc>())
10415           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10416 
10417         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10418           << FixItHint::CreateInsertion(AddConstLoc, " const");
10419       }
10420     }
10421   }
10422 
10423   if (Redeclaration) {
10424     // NewFD and OldDecl represent declarations that need to be
10425     // merged.
10426     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10427       NewFD->setInvalidDecl();
10428       return Redeclaration;
10429     }
10430 
10431     Previous.clear();
10432     Previous.addDecl(OldDecl);
10433 
10434     if (FunctionTemplateDecl *OldTemplateDecl =
10435             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10436       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10437       FunctionTemplateDecl *NewTemplateDecl
10438         = NewFD->getDescribedFunctionTemplate();
10439       assert(NewTemplateDecl && "Template/non-template mismatch");
10440 
10441       // The call to MergeFunctionDecl above may have created some state in
10442       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10443       // can add it as a redeclaration.
10444       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10445 
10446       NewFD->setPreviousDeclaration(OldFD);
10447       adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10448       if (NewFD->isCXXClassMember()) {
10449         NewFD->setAccess(OldTemplateDecl->getAccess());
10450         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10451       }
10452 
10453       // If this is an explicit specialization of a member that is a function
10454       // template, mark it as a member specialization.
10455       if (IsMemberSpecialization &&
10456           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10457         NewTemplateDecl->setMemberSpecialization();
10458         assert(OldTemplateDecl->isMemberSpecialization());
10459         // Explicit specializations of a member template do not inherit deleted
10460         // status from the parent member template that they are specializing.
10461         if (OldFD->isDeleted()) {
10462           // FIXME: This assert will not hold in the presence of modules.
10463           assert(OldFD->getCanonicalDecl() == OldFD);
10464           // FIXME: We need an update record for this AST mutation.
10465           OldFD->setDeletedAsWritten(false);
10466         }
10467       }
10468 
10469     } else {
10470       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10471         auto *OldFD = cast<FunctionDecl>(OldDecl);
10472         // This needs to happen first so that 'inline' propagates.
10473         NewFD->setPreviousDeclaration(OldFD);
10474         adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10475         if (NewFD->isCXXClassMember())
10476           NewFD->setAccess(OldFD->getAccess());
10477       }
10478     }
10479   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10480              !NewFD->getAttr<OverloadableAttr>()) {
10481     assert((Previous.empty() ||
10482             llvm::any_of(Previous,
10483                          [](const NamedDecl *ND) {
10484                            return ND->hasAttr<OverloadableAttr>();
10485                          })) &&
10486            "Non-redecls shouldn't happen without overloadable present");
10487 
10488     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10489       const auto *FD = dyn_cast<FunctionDecl>(ND);
10490       return FD && !FD->hasAttr<OverloadableAttr>();
10491     });
10492 
10493     if (OtherUnmarkedIter != Previous.end()) {
10494       Diag(NewFD->getLocation(),
10495            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10496       Diag((*OtherUnmarkedIter)->getLocation(),
10497            diag::note_attribute_overloadable_prev_overload)
10498           << false;
10499 
10500       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10501     }
10502   }
10503 
10504   // Semantic checking for this function declaration (in isolation).
10505 
10506   if (getLangOpts().CPlusPlus) {
10507     // C++-specific checks.
10508     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10509       CheckConstructor(Constructor);
10510     } else if (CXXDestructorDecl *Destructor =
10511                 dyn_cast<CXXDestructorDecl>(NewFD)) {
10512       CXXRecordDecl *Record = Destructor->getParent();
10513       QualType ClassType = Context.getTypeDeclType(Record);
10514 
10515       // FIXME: Shouldn't we be able to perform this check even when the class
10516       // type is dependent? Both gcc and edg can handle that.
10517       if (!ClassType->isDependentType()) {
10518         DeclarationName Name
10519           = Context.DeclarationNames.getCXXDestructorName(
10520                                         Context.getCanonicalType(ClassType));
10521         if (NewFD->getDeclName() != Name) {
10522           Diag(NewFD->getLocation(), diag::err_destructor_name);
10523           NewFD->setInvalidDecl();
10524           return Redeclaration;
10525         }
10526       }
10527     } else if (CXXConversionDecl *Conversion
10528                = dyn_cast<CXXConversionDecl>(NewFD)) {
10529       ActOnConversionDeclarator(Conversion);
10530     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10531       if (auto *TD = Guide->getDescribedFunctionTemplate())
10532         CheckDeductionGuideTemplate(TD);
10533 
10534       // A deduction guide is not on the list of entities that can be
10535       // explicitly specialized.
10536       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10537         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10538             << /*explicit specialization*/ 1;
10539     }
10540 
10541     // Find any virtual functions that this function overrides.
10542     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10543       if (!Method->isFunctionTemplateSpecialization() &&
10544           !Method->getDescribedFunctionTemplate() &&
10545           Method->isCanonicalDecl()) {
10546         if (AddOverriddenMethods(Method->getParent(), Method)) {
10547           // If the function was marked as "static", we have a problem.
10548           if (NewFD->getStorageClass() == SC_Static) {
10549             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
10550           }
10551         }
10552       }
10553 
10554       if (Method->isStatic())
10555         checkThisInStaticMemberFunctionType(Method);
10556     }
10557 
10558     // Extra checking for C++ overloaded operators (C++ [over.oper]).
10559     if (NewFD->isOverloadedOperator() &&
10560         CheckOverloadedOperatorDeclaration(NewFD)) {
10561       NewFD->setInvalidDecl();
10562       return Redeclaration;
10563     }
10564 
10565     // Extra checking for C++0x literal operators (C++0x [over.literal]).
10566     if (NewFD->getLiteralIdentifier() &&
10567         CheckLiteralOperatorDeclaration(NewFD)) {
10568       NewFD->setInvalidDecl();
10569       return Redeclaration;
10570     }
10571 
10572     // In C++, check default arguments now that we have merged decls. Unless
10573     // the lexical context is the class, because in this case this is done
10574     // during delayed parsing anyway.
10575     if (!CurContext->isRecord())
10576       CheckCXXDefaultArguments(NewFD);
10577 
10578     // If this function declares a builtin function, check the type of this
10579     // declaration against the expected type for the builtin.
10580     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10581       ASTContext::GetBuiltinTypeError Error;
10582       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
10583       QualType T = Context.GetBuiltinType(BuiltinID, Error);
10584       // If the type of the builtin differs only in its exception
10585       // specification, that's OK.
10586       // FIXME: If the types do differ in this way, it would be better to
10587       // retain the 'noexcept' form of the type.
10588       if (!T.isNull() &&
10589           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10590                                                             NewFD->getType()))
10591         // The type of this function differs from the type of the builtin,
10592         // so forget about the builtin entirely.
10593         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10594     }
10595 
10596     // If this function is declared as being extern "C", then check to see if
10597     // the function returns a UDT (class, struct, or union type) that is not C
10598     // compatible, and if it does, warn the user.
10599     // But, issue any diagnostic on the first declaration only.
10600     if (Previous.empty() && NewFD->isExternC()) {
10601       QualType R = NewFD->getReturnType();
10602       if (R->isIncompleteType() && !R->isVoidType())
10603         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10604             << NewFD << R;
10605       else if (!R.isPODType(Context) && !R->isVoidType() &&
10606                !R->isObjCObjectPointerType())
10607         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10608     }
10609 
10610     // C++1z [dcl.fct]p6:
10611     //   [...] whether the function has a non-throwing exception-specification
10612     //   [is] part of the function type
10613     //
10614     // This results in an ABI break between C++14 and C++17 for functions whose
10615     // declared type includes an exception-specification in a parameter or
10616     // return type. (Exception specifications on the function itself are OK in
10617     // most cases, and exception specifications are not permitted in most other
10618     // contexts where they could make it into a mangling.)
10619     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10620       auto HasNoexcept = [&](QualType T) -> bool {
10621         // Strip off declarator chunks that could be between us and a function
10622         // type. We don't need to look far, exception specifications are very
10623         // restricted prior to C++17.
10624         if (auto *RT = T->getAs<ReferenceType>())
10625           T = RT->getPointeeType();
10626         else if (T->isAnyPointerType())
10627           T = T->getPointeeType();
10628         else if (auto *MPT = T->getAs<MemberPointerType>())
10629           T = MPT->getPointeeType();
10630         if (auto *FPT = T->getAs<FunctionProtoType>())
10631           if (FPT->isNothrow())
10632             return true;
10633         return false;
10634       };
10635 
10636       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10637       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10638       for (QualType T : FPT->param_types())
10639         AnyNoexcept |= HasNoexcept(T);
10640       if (AnyNoexcept)
10641         Diag(NewFD->getLocation(),
10642              diag::warn_cxx17_compat_exception_spec_in_signature)
10643             << NewFD;
10644     }
10645 
10646     if (!Redeclaration && LangOpts.CUDA)
10647       checkCUDATargetOverload(NewFD, Previous);
10648   }
10649   return Redeclaration;
10650 }
10651 
10652 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10653   // C++11 [basic.start.main]p3:
10654   //   A program that [...] declares main to be inline, static or
10655   //   constexpr is ill-formed.
10656   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
10657   //   appear in a declaration of main.
10658   // static main is not an error under C99, but we should warn about it.
10659   // We accept _Noreturn main as an extension.
10660   if (FD->getStorageClass() == SC_Static)
10661     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10662          ? diag::err_static_main : diag::warn_static_main)
10663       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10664   if (FD->isInlineSpecified())
10665     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10666       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10667   if (DS.isNoreturnSpecified()) {
10668     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10669     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10670     Diag(NoreturnLoc, diag::ext_noreturn_main);
10671     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10672       << FixItHint::CreateRemoval(NoreturnRange);
10673   }
10674   if (FD->isConstexpr()) {
10675     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10676         << FD->isConsteval()
10677         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10678     FD->setConstexprKind(CSK_unspecified);
10679   }
10680 
10681   if (getLangOpts().OpenCL) {
10682     Diag(FD->getLocation(), diag::err_opencl_no_main)
10683         << FD->hasAttr<OpenCLKernelAttr>();
10684     FD->setInvalidDecl();
10685     return;
10686   }
10687 
10688   QualType T = FD->getType();
10689   assert(T->isFunctionType() && "function decl is not of function type");
10690   const FunctionType* FT = T->castAs<FunctionType>();
10691 
10692   // Set default calling convention for main()
10693   if (FT->getCallConv() != CC_C) {
10694     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10695     FD->setType(QualType(FT, 0));
10696     T = Context.getCanonicalType(FD->getType());
10697   }
10698 
10699   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10700     // In C with GNU extensions we allow main() to have non-integer return
10701     // type, but we should warn about the extension, and we disable the
10702     // implicit-return-zero rule.
10703 
10704     // GCC in C mode accepts qualified 'int'.
10705     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
10706       FD->setHasImplicitReturnZero(true);
10707     else {
10708       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
10709       SourceRange RTRange = FD->getReturnTypeSourceRange();
10710       if (RTRange.isValid())
10711         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
10712             << FixItHint::CreateReplacement(RTRange, "int");
10713     }
10714   } else {
10715     // In C and C++, main magically returns 0 if you fall off the end;
10716     // set the flag which tells us that.
10717     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
10718 
10719     // All the standards say that main() should return 'int'.
10720     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
10721       FD->setHasImplicitReturnZero(true);
10722     else {
10723       // Otherwise, this is just a flat-out error.
10724       SourceRange RTRange = FD->getReturnTypeSourceRange();
10725       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
10726           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
10727                                 : FixItHint());
10728       FD->setInvalidDecl(true);
10729     }
10730   }
10731 
10732   // Treat protoless main() as nullary.
10733   if (isa<FunctionNoProtoType>(FT)) return;
10734 
10735   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
10736   unsigned nparams = FTP->getNumParams();
10737   assert(FD->getNumParams() == nparams);
10738 
10739   bool HasExtraParameters = (nparams > 3);
10740 
10741   if (FTP->isVariadic()) {
10742     Diag(FD->getLocation(), diag::ext_variadic_main);
10743     // FIXME: if we had information about the location of the ellipsis, we
10744     // could add a FixIt hint to remove it as a parameter.
10745   }
10746 
10747   // Darwin passes an undocumented fourth argument of type char**.  If
10748   // other platforms start sprouting these, the logic below will start
10749   // getting shifty.
10750   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
10751     HasExtraParameters = false;
10752 
10753   if (HasExtraParameters) {
10754     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
10755     FD->setInvalidDecl(true);
10756     nparams = 3;
10757   }
10758 
10759   // FIXME: a lot of the following diagnostics would be improved
10760   // if we had some location information about types.
10761 
10762   QualType CharPP =
10763     Context.getPointerType(Context.getPointerType(Context.CharTy));
10764   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
10765 
10766   for (unsigned i = 0; i < nparams; ++i) {
10767     QualType AT = FTP->getParamType(i);
10768 
10769     bool mismatch = true;
10770 
10771     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
10772       mismatch = false;
10773     else if (Expected[i] == CharPP) {
10774       // As an extension, the following forms are okay:
10775       //   char const **
10776       //   char const * const *
10777       //   char * const *
10778 
10779       QualifierCollector qs;
10780       const PointerType* PT;
10781       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
10782           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
10783           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
10784                               Context.CharTy)) {
10785         qs.removeConst();
10786         mismatch = !qs.empty();
10787       }
10788     }
10789 
10790     if (mismatch) {
10791       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
10792       // TODO: suggest replacing given type with expected type
10793       FD->setInvalidDecl(true);
10794     }
10795   }
10796 
10797   if (nparams == 1 && !FD->isInvalidDecl()) {
10798     Diag(FD->getLocation(), diag::warn_main_one_arg);
10799   }
10800 
10801   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10802     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10803     FD->setInvalidDecl();
10804   }
10805 }
10806 
10807 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
10808   QualType T = FD->getType();
10809   assert(T->isFunctionType() && "function decl is not of function type");
10810   const FunctionType *FT = T->castAs<FunctionType>();
10811 
10812   // Set an implicit return of 'zero' if the function can return some integral,
10813   // enumeration, pointer or nullptr type.
10814   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
10815       FT->getReturnType()->isAnyPointerType() ||
10816       FT->getReturnType()->isNullPtrType())
10817     // DllMain is exempt because a return value of zero means it failed.
10818     if (FD->getName() != "DllMain")
10819       FD->setHasImplicitReturnZero(true);
10820 
10821   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10822     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10823     FD->setInvalidDecl();
10824   }
10825 }
10826 
10827 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
10828   // FIXME: Need strict checking.  In C89, we need to check for
10829   // any assignment, increment, decrement, function-calls, or
10830   // commas outside of a sizeof.  In C99, it's the same list,
10831   // except that the aforementioned are allowed in unevaluated
10832   // expressions.  Everything else falls under the
10833   // "may accept other forms of constant expressions" exception.
10834   // (We never end up here for C++, so the constant expression
10835   // rules there don't matter.)
10836   const Expr *Culprit;
10837   if (Init->isConstantInitializer(Context, false, &Culprit))
10838     return false;
10839   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
10840     << Culprit->getSourceRange();
10841   return true;
10842 }
10843 
10844 namespace {
10845   // Visits an initialization expression to see if OrigDecl is evaluated in
10846   // its own initialization and throws a warning if it does.
10847   class SelfReferenceChecker
10848       : public EvaluatedExprVisitor<SelfReferenceChecker> {
10849     Sema &S;
10850     Decl *OrigDecl;
10851     bool isRecordType;
10852     bool isPODType;
10853     bool isReferenceType;
10854 
10855     bool isInitList;
10856     llvm::SmallVector<unsigned, 4> InitFieldIndex;
10857 
10858   public:
10859     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
10860 
10861     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
10862                                                     S(S), OrigDecl(OrigDecl) {
10863       isPODType = false;
10864       isRecordType = false;
10865       isReferenceType = false;
10866       isInitList = false;
10867       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
10868         isPODType = VD->getType().isPODType(S.Context);
10869         isRecordType = VD->getType()->isRecordType();
10870         isReferenceType = VD->getType()->isReferenceType();
10871       }
10872     }
10873 
10874     // For most expressions, just call the visitor.  For initializer lists,
10875     // track the index of the field being initialized since fields are
10876     // initialized in order allowing use of previously initialized fields.
10877     void CheckExpr(Expr *E) {
10878       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
10879       if (!InitList) {
10880         Visit(E);
10881         return;
10882       }
10883 
10884       // Track and increment the index here.
10885       isInitList = true;
10886       InitFieldIndex.push_back(0);
10887       for (auto Child : InitList->children()) {
10888         CheckExpr(cast<Expr>(Child));
10889         ++InitFieldIndex.back();
10890       }
10891       InitFieldIndex.pop_back();
10892     }
10893 
10894     // Returns true if MemberExpr is checked and no further checking is needed.
10895     // Returns false if additional checking is required.
10896     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
10897       llvm::SmallVector<FieldDecl*, 4> Fields;
10898       Expr *Base = E;
10899       bool ReferenceField = false;
10900 
10901       // Get the field members used.
10902       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10903         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
10904         if (!FD)
10905           return false;
10906         Fields.push_back(FD);
10907         if (FD->getType()->isReferenceType())
10908           ReferenceField = true;
10909         Base = ME->getBase()->IgnoreParenImpCasts();
10910       }
10911 
10912       // Keep checking only if the base Decl is the same.
10913       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
10914       if (!DRE || DRE->getDecl() != OrigDecl)
10915         return false;
10916 
10917       // A reference field can be bound to an unininitialized field.
10918       if (CheckReference && !ReferenceField)
10919         return true;
10920 
10921       // Convert FieldDecls to their index number.
10922       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
10923       for (const FieldDecl *I : llvm::reverse(Fields))
10924         UsedFieldIndex.push_back(I->getFieldIndex());
10925 
10926       // See if a warning is needed by checking the first difference in index
10927       // numbers.  If field being used has index less than the field being
10928       // initialized, then the use is safe.
10929       for (auto UsedIter = UsedFieldIndex.begin(),
10930                 UsedEnd = UsedFieldIndex.end(),
10931                 OrigIter = InitFieldIndex.begin(),
10932                 OrigEnd = InitFieldIndex.end();
10933            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
10934         if (*UsedIter < *OrigIter)
10935           return true;
10936         if (*UsedIter > *OrigIter)
10937           break;
10938       }
10939 
10940       // TODO: Add a different warning which will print the field names.
10941       HandleDeclRefExpr(DRE);
10942       return true;
10943     }
10944 
10945     // For most expressions, the cast is directly above the DeclRefExpr.
10946     // For conditional operators, the cast can be outside the conditional
10947     // operator if both expressions are DeclRefExpr's.
10948     void HandleValue(Expr *E) {
10949       E = E->IgnoreParens();
10950       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
10951         HandleDeclRefExpr(DRE);
10952         return;
10953       }
10954 
10955       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
10956         Visit(CO->getCond());
10957         HandleValue(CO->getTrueExpr());
10958         HandleValue(CO->getFalseExpr());
10959         return;
10960       }
10961 
10962       if (BinaryConditionalOperator *BCO =
10963               dyn_cast<BinaryConditionalOperator>(E)) {
10964         Visit(BCO->getCond());
10965         HandleValue(BCO->getFalseExpr());
10966         return;
10967       }
10968 
10969       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
10970         HandleValue(OVE->getSourceExpr());
10971         return;
10972       }
10973 
10974       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10975         if (BO->getOpcode() == BO_Comma) {
10976           Visit(BO->getLHS());
10977           HandleValue(BO->getRHS());
10978           return;
10979         }
10980       }
10981 
10982       if (isa<MemberExpr>(E)) {
10983         if (isInitList) {
10984           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
10985                                       false /*CheckReference*/))
10986             return;
10987         }
10988 
10989         Expr *Base = E->IgnoreParenImpCasts();
10990         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10991           // Check for static member variables and don't warn on them.
10992           if (!isa<FieldDecl>(ME->getMemberDecl()))
10993             return;
10994           Base = ME->getBase()->IgnoreParenImpCasts();
10995         }
10996         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
10997           HandleDeclRefExpr(DRE);
10998         return;
10999       }
11000 
11001       Visit(E);
11002     }
11003 
11004     // Reference types not handled in HandleValue are handled here since all
11005     // uses of references are bad, not just r-value uses.
11006     void VisitDeclRefExpr(DeclRefExpr *E) {
11007       if (isReferenceType)
11008         HandleDeclRefExpr(E);
11009     }
11010 
11011     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11012       if (E->getCastKind() == CK_LValueToRValue) {
11013         HandleValue(E->getSubExpr());
11014         return;
11015       }
11016 
11017       Inherited::VisitImplicitCastExpr(E);
11018     }
11019 
11020     void VisitMemberExpr(MemberExpr *E) {
11021       if (isInitList) {
11022         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11023           return;
11024       }
11025 
11026       // Don't warn on arrays since they can be treated as pointers.
11027       if (E->getType()->canDecayToPointerType()) return;
11028 
11029       // Warn when a non-static method call is followed by non-static member
11030       // field accesses, which is followed by a DeclRefExpr.
11031       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11032       bool Warn = (MD && !MD->isStatic());
11033       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11034       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11035         if (!isa<FieldDecl>(ME->getMemberDecl()))
11036           Warn = false;
11037         Base = ME->getBase()->IgnoreParenImpCasts();
11038       }
11039 
11040       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11041         if (Warn)
11042           HandleDeclRefExpr(DRE);
11043         return;
11044       }
11045 
11046       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11047       // Visit that expression.
11048       Visit(Base);
11049     }
11050 
11051     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11052       Expr *Callee = E->getCallee();
11053 
11054       if (isa<UnresolvedLookupExpr>(Callee))
11055         return Inherited::VisitCXXOperatorCallExpr(E);
11056 
11057       Visit(Callee);
11058       for (auto Arg: E->arguments())
11059         HandleValue(Arg->IgnoreParenImpCasts());
11060     }
11061 
11062     void VisitUnaryOperator(UnaryOperator *E) {
11063       // For POD record types, addresses of its own members are well-defined.
11064       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11065           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11066         if (!isPODType)
11067           HandleValue(E->getSubExpr());
11068         return;
11069       }
11070 
11071       if (E->isIncrementDecrementOp()) {
11072         HandleValue(E->getSubExpr());
11073         return;
11074       }
11075 
11076       Inherited::VisitUnaryOperator(E);
11077     }
11078 
11079     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11080 
11081     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11082       if (E->getConstructor()->isCopyConstructor()) {
11083         Expr *ArgExpr = E->getArg(0);
11084         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11085           if (ILE->getNumInits() == 1)
11086             ArgExpr = ILE->getInit(0);
11087         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11088           if (ICE->getCastKind() == CK_NoOp)
11089             ArgExpr = ICE->getSubExpr();
11090         HandleValue(ArgExpr);
11091         return;
11092       }
11093       Inherited::VisitCXXConstructExpr(E);
11094     }
11095 
11096     void VisitCallExpr(CallExpr *E) {
11097       // Treat std::move as a use.
11098       if (E->isCallToStdMove()) {
11099         HandleValue(E->getArg(0));
11100         return;
11101       }
11102 
11103       Inherited::VisitCallExpr(E);
11104     }
11105 
11106     void VisitBinaryOperator(BinaryOperator *E) {
11107       if (E->isCompoundAssignmentOp()) {
11108         HandleValue(E->getLHS());
11109         Visit(E->getRHS());
11110         return;
11111       }
11112 
11113       Inherited::VisitBinaryOperator(E);
11114     }
11115 
11116     // A custom visitor for BinaryConditionalOperator is needed because the
11117     // regular visitor would check the condition and true expression separately
11118     // but both point to the same place giving duplicate diagnostics.
11119     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11120       Visit(E->getCond());
11121       Visit(E->getFalseExpr());
11122     }
11123 
11124     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11125       Decl* ReferenceDecl = DRE->getDecl();
11126       if (OrigDecl != ReferenceDecl) return;
11127       unsigned diag;
11128       if (isReferenceType) {
11129         diag = diag::warn_uninit_self_reference_in_reference_init;
11130       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11131         diag = diag::warn_static_self_reference_in_init;
11132       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11133                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11134                  DRE->getDecl()->getType()->isRecordType()) {
11135         diag = diag::warn_uninit_self_reference_in_init;
11136       } else {
11137         // Local variables will be handled by the CFG analysis.
11138         return;
11139       }
11140 
11141       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11142                             S.PDiag(diag)
11143                                 << DRE->getDecl() << OrigDecl->getLocation()
11144                                 << DRE->getSourceRange());
11145     }
11146   };
11147 
11148   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11149   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11150                                  bool DirectInit) {
11151     // Parameters arguments are occassionially constructed with itself,
11152     // for instance, in recursive functions.  Skip them.
11153     if (isa<ParmVarDecl>(OrigDecl))
11154       return;
11155 
11156     E = E->IgnoreParens();
11157 
11158     // Skip checking T a = a where T is not a record or reference type.
11159     // Doing so is a way to silence uninitialized warnings.
11160     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11161       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11162         if (ICE->getCastKind() == CK_LValueToRValue)
11163           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11164             if (DRE->getDecl() == OrigDecl)
11165               return;
11166 
11167     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11168   }
11169 } // end anonymous namespace
11170 
11171 namespace {
11172   // Simple wrapper to add the name of a variable or (if no variable is
11173   // available) a DeclarationName into a diagnostic.
11174   struct VarDeclOrName {
11175     VarDecl *VDecl;
11176     DeclarationName Name;
11177 
11178     friend const Sema::SemaDiagnosticBuilder &
11179     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11180       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11181     }
11182   };
11183 } // end anonymous namespace
11184 
11185 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11186                                             DeclarationName Name, QualType Type,
11187                                             TypeSourceInfo *TSI,
11188                                             SourceRange Range, bool DirectInit,
11189                                             Expr *Init) {
11190   bool IsInitCapture = !VDecl;
11191   assert((!VDecl || !VDecl->isInitCapture()) &&
11192          "init captures are expected to be deduced prior to initialization");
11193 
11194   VarDeclOrName VN{VDecl, Name};
11195 
11196   DeducedType *Deduced = Type->getContainedDeducedType();
11197   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11198 
11199   // C++11 [dcl.spec.auto]p3
11200   if (!Init) {
11201     assert(VDecl && "no init for init capture deduction?");
11202 
11203     // Except for class argument deduction, and then for an initializing
11204     // declaration only, i.e. no static at class scope or extern.
11205     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11206         VDecl->hasExternalStorage() ||
11207         VDecl->isStaticDataMember()) {
11208       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11209         << VDecl->getDeclName() << Type;
11210       return QualType();
11211     }
11212   }
11213 
11214   ArrayRef<Expr*> DeduceInits;
11215   if (Init)
11216     DeduceInits = Init;
11217 
11218   if (DirectInit) {
11219     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11220       DeduceInits = PL->exprs();
11221   }
11222 
11223   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11224     assert(VDecl && "non-auto type for init capture deduction?");
11225     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11226     InitializationKind Kind = InitializationKind::CreateForInit(
11227         VDecl->getLocation(), DirectInit, Init);
11228     // FIXME: Initialization should not be taking a mutable list of inits.
11229     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11230     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11231                                                        InitsCopy);
11232   }
11233 
11234   if (DirectInit) {
11235     if (auto *IL = dyn_cast<InitListExpr>(Init))
11236       DeduceInits = IL->inits();
11237   }
11238 
11239   // Deduction only works if we have exactly one source expression.
11240   if (DeduceInits.empty()) {
11241     // It isn't possible to write this directly, but it is possible to
11242     // end up in this situation with "auto x(some_pack...);"
11243     Diag(Init->getBeginLoc(), IsInitCapture
11244                                   ? diag::err_init_capture_no_expression
11245                                   : diag::err_auto_var_init_no_expression)
11246         << VN << Type << Range;
11247     return QualType();
11248   }
11249 
11250   if (DeduceInits.size() > 1) {
11251     Diag(DeduceInits[1]->getBeginLoc(),
11252          IsInitCapture ? diag::err_init_capture_multiple_expressions
11253                        : diag::err_auto_var_init_multiple_expressions)
11254         << VN << Type << Range;
11255     return QualType();
11256   }
11257 
11258   Expr *DeduceInit = DeduceInits[0];
11259   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11260     Diag(Init->getBeginLoc(), IsInitCapture
11261                                   ? diag::err_init_capture_paren_braces
11262                                   : diag::err_auto_var_init_paren_braces)
11263         << isa<InitListExpr>(Init) << VN << Type << Range;
11264     return QualType();
11265   }
11266 
11267   // Expressions default to 'id' when we're in a debugger.
11268   bool DefaultedAnyToId = false;
11269   if (getLangOpts().DebuggerCastResultToId &&
11270       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11271     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11272     if (Result.isInvalid()) {
11273       return QualType();
11274     }
11275     Init = Result.get();
11276     DefaultedAnyToId = true;
11277   }
11278 
11279   // C++ [dcl.decomp]p1:
11280   //   If the assignment-expression [...] has array type A and no ref-qualifier
11281   //   is present, e has type cv A
11282   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11283       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11284       DeduceInit->getType()->isConstantArrayType())
11285     return Context.getQualifiedType(DeduceInit->getType(),
11286                                     Type.getQualifiers());
11287 
11288   QualType DeducedType;
11289   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11290     if (!IsInitCapture)
11291       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11292     else if (isa<InitListExpr>(Init))
11293       Diag(Range.getBegin(),
11294            diag::err_init_capture_deduction_failure_from_init_list)
11295           << VN
11296           << (DeduceInit->getType().isNull() ? TSI->getType()
11297                                              : DeduceInit->getType())
11298           << DeduceInit->getSourceRange();
11299     else
11300       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11301           << VN << TSI->getType()
11302           << (DeduceInit->getType().isNull() ? TSI->getType()
11303                                              : DeduceInit->getType())
11304           << DeduceInit->getSourceRange();
11305   }
11306 
11307   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11308   // 'id' instead of a specific object type prevents most of our usual
11309   // checks.
11310   // We only want to warn outside of template instantiations, though:
11311   // inside a template, the 'id' could have come from a parameter.
11312   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11313       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11314     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11315     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11316   }
11317 
11318   return DeducedType;
11319 }
11320 
11321 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11322                                          Expr *Init) {
11323   QualType DeducedType = deduceVarTypeFromInitializer(
11324       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11325       VDecl->getSourceRange(), DirectInit, Init);
11326   if (DeducedType.isNull()) {
11327     VDecl->setInvalidDecl();
11328     return true;
11329   }
11330 
11331   VDecl->setType(DeducedType);
11332   assert(VDecl->isLinkageValid());
11333 
11334   // In ARC, infer lifetime.
11335   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11336     VDecl->setInvalidDecl();
11337 
11338   if (getLangOpts().OpenCL)
11339     deduceOpenCLAddressSpace(VDecl);
11340 
11341   // If this is a redeclaration, check that the type we just deduced matches
11342   // the previously declared type.
11343   if (VarDecl *Old = VDecl->getPreviousDecl()) {
11344     // We never need to merge the type, because we cannot form an incomplete
11345     // array of auto, nor deduce such a type.
11346     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11347   }
11348 
11349   // Check the deduced type is valid for a variable declaration.
11350   CheckVariableDeclarationType(VDecl);
11351   return VDecl->isInvalidDecl();
11352 }
11353 
11354 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11355                                               SourceLocation Loc) {
11356   if (auto *CE = dyn_cast<ConstantExpr>(Init))
11357     Init = CE->getSubExpr();
11358 
11359   QualType InitType = Init->getType();
11360   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11361           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
11362          "shouldn't be called if type doesn't have a non-trivial C struct");
11363   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11364     for (auto I : ILE->inits()) {
11365       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11366           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11367         continue;
11368       SourceLocation SL = I->getExprLoc();
11369       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11370     }
11371     return;
11372   }
11373 
11374   if (isa<ImplicitValueInitExpr>(Init)) {
11375     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11376       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11377                             NTCUK_Init);
11378   } else {
11379     // Assume all other explicit initializers involving copying some existing
11380     // object.
11381     // TODO: ignore any explicit initializers where we can guarantee
11382     // copy-elision.
11383     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11384       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11385   }
11386 }
11387 
11388 namespace {
11389 
11390 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11391   // Ignore unavailable fields. A field can be marked as unavailable explicitly
11392   // in the source code or implicitly by the compiler if it is in a union
11393   // defined in a system header and has non-trivial ObjC ownership
11394   // qualifications. We don't want those fields to participate in determining
11395   // whether the containing union is non-trivial.
11396   return FD->hasAttr<UnavailableAttr>();
11397 }
11398 
11399 struct DiagNonTrivalCUnionDefaultInitializeVisitor
11400     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11401                                     void> {
11402   using Super =
11403       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11404                                     void>;
11405 
11406   DiagNonTrivalCUnionDefaultInitializeVisitor(
11407       QualType OrigTy, SourceLocation OrigLoc,
11408       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11409       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11410 
11411   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11412                      const FieldDecl *FD, bool InNonTrivialUnion) {
11413     if (const auto *AT = S.Context.getAsArrayType(QT))
11414       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11415                                      InNonTrivialUnion);
11416     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11417   }
11418 
11419   void visitARCStrong(QualType QT, const FieldDecl *FD,
11420                       bool InNonTrivialUnion) {
11421     if (InNonTrivialUnion)
11422       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11423           << 1 << 0 << QT << FD->getName();
11424   }
11425 
11426   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11427     if (InNonTrivialUnion)
11428       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11429           << 1 << 0 << QT << FD->getName();
11430   }
11431 
11432   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11433     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11434     if (RD->isUnion()) {
11435       if (OrigLoc.isValid()) {
11436         bool IsUnion = false;
11437         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11438           IsUnion = OrigRD->isUnion();
11439         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11440             << 0 << OrigTy << IsUnion << UseContext;
11441         // Reset OrigLoc so that this diagnostic is emitted only once.
11442         OrigLoc = SourceLocation();
11443       }
11444       InNonTrivialUnion = true;
11445     }
11446 
11447     if (InNonTrivialUnion)
11448       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11449           << 0 << 0 << QT.getUnqualifiedType() << "";
11450 
11451     for (const FieldDecl *FD : RD->fields())
11452       if (!shouldIgnoreForRecordTriviality(FD))
11453         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11454   }
11455 
11456   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11457 
11458   // The non-trivial C union type or the struct/union type that contains a
11459   // non-trivial C union.
11460   QualType OrigTy;
11461   SourceLocation OrigLoc;
11462   Sema::NonTrivialCUnionContext UseContext;
11463   Sema &S;
11464 };
11465 
11466 struct DiagNonTrivalCUnionDestructedTypeVisitor
11467     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
11468   using Super =
11469       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
11470 
11471   DiagNonTrivalCUnionDestructedTypeVisitor(
11472       QualType OrigTy, SourceLocation OrigLoc,
11473       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11474       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11475 
11476   void visitWithKind(QualType::DestructionKind DK, QualType QT,
11477                      const FieldDecl *FD, bool InNonTrivialUnion) {
11478     if (const auto *AT = S.Context.getAsArrayType(QT))
11479       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11480                                      InNonTrivialUnion);
11481     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
11482   }
11483 
11484   void visitARCStrong(QualType QT, const FieldDecl *FD,
11485                       bool InNonTrivialUnion) {
11486     if (InNonTrivialUnion)
11487       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11488           << 1 << 1 << QT << FD->getName();
11489   }
11490 
11491   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11492     if (InNonTrivialUnion)
11493       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11494           << 1 << 1 << QT << FD->getName();
11495   }
11496 
11497   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11498     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11499     if (RD->isUnion()) {
11500       if (OrigLoc.isValid()) {
11501         bool IsUnion = false;
11502         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11503           IsUnion = OrigRD->isUnion();
11504         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11505             << 1 << OrigTy << IsUnion << UseContext;
11506         // Reset OrigLoc so that this diagnostic is emitted only once.
11507         OrigLoc = SourceLocation();
11508       }
11509       InNonTrivialUnion = true;
11510     }
11511 
11512     if (InNonTrivialUnion)
11513       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11514           << 0 << 1 << QT.getUnqualifiedType() << "";
11515 
11516     for (const FieldDecl *FD : RD->fields())
11517       if (!shouldIgnoreForRecordTriviality(FD))
11518         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11519   }
11520 
11521   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11522   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
11523                           bool InNonTrivialUnion) {}
11524 
11525   // The non-trivial C union type or the struct/union type that contains a
11526   // non-trivial C union.
11527   QualType OrigTy;
11528   SourceLocation OrigLoc;
11529   Sema::NonTrivialCUnionContext UseContext;
11530   Sema &S;
11531 };
11532 
11533 struct DiagNonTrivalCUnionCopyVisitor
11534     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
11535   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
11536 
11537   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
11538                                  Sema::NonTrivialCUnionContext UseContext,
11539                                  Sema &S)
11540       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11541 
11542   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
11543                      const FieldDecl *FD, bool InNonTrivialUnion) {
11544     if (const auto *AT = S.Context.getAsArrayType(QT))
11545       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11546                                      InNonTrivialUnion);
11547     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
11548   }
11549 
11550   void visitARCStrong(QualType QT, const FieldDecl *FD,
11551                       bool InNonTrivialUnion) {
11552     if (InNonTrivialUnion)
11553       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11554           << 1 << 2 << QT << FD->getName();
11555   }
11556 
11557   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11558     if (InNonTrivialUnion)
11559       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11560           << 1 << 2 << QT << FD->getName();
11561   }
11562 
11563   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11564     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11565     if (RD->isUnion()) {
11566       if (OrigLoc.isValid()) {
11567         bool IsUnion = false;
11568         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11569           IsUnion = OrigRD->isUnion();
11570         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11571             << 2 << OrigTy << IsUnion << UseContext;
11572         // Reset OrigLoc so that this diagnostic is emitted only once.
11573         OrigLoc = SourceLocation();
11574       }
11575       InNonTrivialUnion = true;
11576     }
11577 
11578     if (InNonTrivialUnion)
11579       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11580           << 0 << 2 << QT.getUnqualifiedType() << "";
11581 
11582     for (const FieldDecl *FD : RD->fields())
11583       if (!shouldIgnoreForRecordTriviality(FD))
11584         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11585   }
11586 
11587   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
11588                 const FieldDecl *FD, bool InNonTrivialUnion) {}
11589   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11590   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
11591                             bool InNonTrivialUnion) {}
11592 
11593   // The non-trivial C union type or the struct/union type that contains a
11594   // non-trivial C union.
11595   QualType OrigTy;
11596   SourceLocation OrigLoc;
11597   Sema::NonTrivialCUnionContext UseContext;
11598   Sema &S;
11599 };
11600 
11601 } // namespace
11602 
11603 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
11604                                  NonTrivialCUnionContext UseContext,
11605                                  unsigned NonTrivialKind) {
11606   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11607           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
11608           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
11609          "shouldn't be called if type doesn't have a non-trivial C union");
11610 
11611   if ((NonTrivialKind & NTCUK_Init) &&
11612       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11613     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
11614         .visit(QT, nullptr, false);
11615   if ((NonTrivialKind & NTCUK_Destruct) &&
11616       QT.hasNonTrivialToPrimitiveDestructCUnion())
11617     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
11618         .visit(QT, nullptr, false);
11619   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
11620     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
11621         .visit(QT, nullptr, false);
11622 }
11623 
11624 /// AddInitializerToDecl - Adds the initializer Init to the
11625 /// declaration dcl. If DirectInit is true, this is C++ direct
11626 /// initialization rather than copy initialization.
11627 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
11628   // If there is no declaration, there was an error parsing it.  Just ignore
11629   // the initializer.
11630   if (!RealDecl || RealDecl->isInvalidDecl()) {
11631     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
11632     return;
11633   }
11634 
11635   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
11636     // Pure-specifiers are handled in ActOnPureSpecifier.
11637     Diag(Method->getLocation(), diag::err_member_function_initialization)
11638       << Method->getDeclName() << Init->getSourceRange();
11639     Method->setInvalidDecl();
11640     return;
11641   }
11642 
11643   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
11644   if (!VDecl) {
11645     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
11646     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
11647     RealDecl->setInvalidDecl();
11648     return;
11649   }
11650 
11651   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
11652   if (VDecl->getType()->isUndeducedType()) {
11653     // Attempt typo correction early so that the type of the init expression can
11654     // be deduced based on the chosen correction if the original init contains a
11655     // TypoExpr.
11656     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
11657     if (!Res.isUsable()) {
11658       RealDecl->setInvalidDecl();
11659       return;
11660     }
11661     Init = Res.get();
11662 
11663     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
11664       return;
11665   }
11666 
11667   // dllimport cannot be used on variable definitions.
11668   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
11669     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
11670     VDecl->setInvalidDecl();
11671     return;
11672   }
11673 
11674   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
11675     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
11676     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
11677     VDecl->setInvalidDecl();
11678     return;
11679   }
11680 
11681   if (!VDecl->getType()->isDependentType()) {
11682     // A definition must end up with a complete type, which means it must be
11683     // complete with the restriction that an array type might be completed by
11684     // the initializer; note that later code assumes this restriction.
11685     QualType BaseDeclType = VDecl->getType();
11686     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
11687       BaseDeclType = Array->getElementType();
11688     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
11689                             diag::err_typecheck_decl_incomplete_type)) {
11690       RealDecl->setInvalidDecl();
11691       return;
11692     }
11693 
11694     // The variable can not have an abstract class type.
11695     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
11696                                diag::err_abstract_type_in_decl,
11697                                AbstractVariableType))
11698       VDecl->setInvalidDecl();
11699   }
11700 
11701   // If adding the initializer will turn this declaration into a definition,
11702   // and we already have a definition for this variable, diagnose or otherwise
11703   // handle the situation.
11704   VarDecl *Def;
11705   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
11706       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
11707       !VDecl->isThisDeclarationADemotedDefinition() &&
11708       checkVarDeclRedefinition(Def, VDecl))
11709     return;
11710 
11711   if (getLangOpts().CPlusPlus) {
11712     // C++ [class.static.data]p4
11713     //   If a static data member is of const integral or const
11714     //   enumeration type, its declaration in the class definition can
11715     //   specify a constant-initializer which shall be an integral
11716     //   constant expression (5.19). In that case, the member can appear
11717     //   in integral constant expressions. The member shall still be
11718     //   defined in a namespace scope if it is used in the program and the
11719     //   namespace scope definition shall not contain an initializer.
11720     //
11721     // We already performed a redefinition check above, but for static
11722     // data members we also need to check whether there was an in-class
11723     // declaration with an initializer.
11724     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
11725       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
11726           << VDecl->getDeclName();
11727       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
11728            diag::note_previous_initializer)
11729           << 0;
11730       return;
11731     }
11732 
11733     if (VDecl->hasLocalStorage())
11734       setFunctionHasBranchProtectedScope();
11735 
11736     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
11737       VDecl->setInvalidDecl();
11738       return;
11739     }
11740   }
11741 
11742   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
11743   // a kernel function cannot be initialized."
11744   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
11745     Diag(VDecl->getLocation(), diag::err_local_cant_init);
11746     VDecl->setInvalidDecl();
11747     return;
11748   }
11749 
11750   // Get the decls type and save a reference for later, since
11751   // CheckInitializerTypes may change it.
11752   QualType DclT = VDecl->getType(), SavT = DclT;
11753 
11754   // Expressions default to 'id' when we're in a debugger
11755   // and we are assigning it to a variable of Objective-C pointer type.
11756   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
11757       Init->getType() == Context.UnknownAnyTy) {
11758     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11759     if (Result.isInvalid()) {
11760       VDecl->setInvalidDecl();
11761       return;
11762     }
11763     Init = Result.get();
11764   }
11765 
11766   // Perform the initialization.
11767   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
11768   if (!VDecl->isInvalidDecl()) {
11769     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11770     InitializationKind Kind = InitializationKind::CreateForInit(
11771         VDecl->getLocation(), DirectInit, Init);
11772 
11773     MultiExprArg Args = Init;
11774     if (CXXDirectInit)
11775       Args = MultiExprArg(CXXDirectInit->getExprs(),
11776                           CXXDirectInit->getNumExprs());
11777 
11778     // Try to correct any TypoExprs in the initialization arguments.
11779     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
11780       ExprResult Res = CorrectDelayedTyposInExpr(
11781           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
11782             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
11783             return Init.Failed() ? ExprError() : E;
11784           });
11785       if (Res.isInvalid()) {
11786         VDecl->setInvalidDecl();
11787       } else if (Res.get() != Args[Idx]) {
11788         Args[Idx] = Res.get();
11789       }
11790     }
11791     if (VDecl->isInvalidDecl())
11792       return;
11793 
11794     InitializationSequence InitSeq(*this, Entity, Kind, Args,
11795                                    /*TopLevelOfInitList=*/false,
11796                                    /*TreatUnavailableAsInvalid=*/false);
11797     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
11798     if (Result.isInvalid()) {
11799       VDecl->setInvalidDecl();
11800       return;
11801     }
11802 
11803     Init = Result.getAs<Expr>();
11804   }
11805 
11806   // Check for self-references within variable initializers.
11807   // Variables declared within a function/method body (except for references)
11808   // are handled by a dataflow analysis.
11809   // This is undefined behavior in C++, but valid in C.
11810   if (getLangOpts().CPlusPlus) {
11811     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
11812         VDecl->getType()->isReferenceType()) {
11813       CheckSelfReference(*this, RealDecl, Init, DirectInit);
11814     }
11815   }
11816 
11817   // If the type changed, it means we had an incomplete type that was
11818   // completed by the initializer. For example:
11819   //   int ary[] = { 1, 3, 5 };
11820   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
11821   if (!VDecl->isInvalidDecl() && (DclT != SavT))
11822     VDecl->setType(DclT);
11823 
11824   if (!VDecl->isInvalidDecl()) {
11825     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
11826 
11827     if (VDecl->hasAttr<BlocksAttr>())
11828       checkRetainCycles(VDecl, Init);
11829 
11830     // It is safe to assign a weak reference into a strong variable.
11831     // Although this code can still have problems:
11832     //   id x = self.weakProp;
11833     //   id y = self.weakProp;
11834     // we do not warn to warn spuriously when 'x' and 'y' are on separate
11835     // paths through the function. This should be revisited if
11836     // -Wrepeated-use-of-weak is made flow-sensitive.
11837     if (FunctionScopeInfo *FSI = getCurFunction())
11838       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
11839            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
11840           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11841                            Init->getBeginLoc()))
11842         FSI->markSafeWeakUse(Init);
11843   }
11844 
11845   // The initialization is usually a full-expression.
11846   //
11847   // FIXME: If this is a braced initialization of an aggregate, it is not
11848   // an expression, and each individual field initializer is a separate
11849   // full-expression. For instance, in:
11850   //
11851   //   struct Temp { ~Temp(); };
11852   //   struct S { S(Temp); };
11853   //   struct T { S a, b; } t = { Temp(), Temp() }
11854   //
11855   // we should destroy the first Temp before constructing the second.
11856   ExprResult Result =
11857       ActOnFinishFullExpr(Init, VDecl->getLocation(),
11858                           /*DiscardedValue*/ false, VDecl->isConstexpr());
11859   if (Result.isInvalid()) {
11860     VDecl->setInvalidDecl();
11861     return;
11862   }
11863   Init = Result.get();
11864 
11865   // Attach the initializer to the decl.
11866   VDecl->setInit(Init);
11867 
11868   if (VDecl->isLocalVarDecl()) {
11869     // Don't check the initializer if the declaration is malformed.
11870     if (VDecl->isInvalidDecl()) {
11871       // do nothing
11872 
11873     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
11874     // This is true even in C++ for OpenCL.
11875     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
11876       CheckForConstantInitializer(Init, DclT);
11877 
11878     // Otherwise, C++ does not restrict the initializer.
11879     } else if (getLangOpts().CPlusPlus) {
11880       // do nothing
11881 
11882     // C99 6.7.8p4: All the expressions in an initializer for an object that has
11883     // static storage duration shall be constant expressions or string literals.
11884     } else if (VDecl->getStorageClass() == SC_Static) {
11885       CheckForConstantInitializer(Init, DclT);
11886 
11887     // C89 is stricter than C99 for aggregate initializers.
11888     // C89 6.5.7p3: All the expressions [...] in an initializer list
11889     // for an object that has aggregate or union type shall be
11890     // constant expressions.
11891     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
11892                isa<InitListExpr>(Init)) {
11893       const Expr *Culprit;
11894       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
11895         Diag(Culprit->getExprLoc(),
11896              diag::ext_aggregate_init_not_constant)
11897           << Culprit->getSourceRange();
11898       }
11899     }
11900 
11901     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
11902       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
11903         if (VDecl->hasLocalStorage())
11904           BE->getBlockDecl()->setCanAvoidCopyToHeap();
11905   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
11906              VDecl->getLexicalDeclContext()->isRecord()) {
11907     // This is an in-class initialization for a static data member, e.g.,
11908     //
11909     // struct S {
11910     //   static const int value = 17;
11911     // };
11912 
11913     // C++ [class.mem]p4:
11914     //   A member-declarator can contain a constant-initializer only
11915     //   if it declares a static member (9.4) of const integral or
11916     //   const enumeration type, see 9.4.2.
11917     //
11918     // C++11 [class.static.data]p3:
11919     //   If a non-volatile non-inline const static data member is of integral
11920     //   or enumeration type, its declaration in the class definition can
11921     //   specify a brace-or-equal-initializer in which every initializer-clause
11922     //   that is an assignment-expression is a constant expression. A static
11923     //   data member of literal type can be declared in the class definition
11924     //   with the constexpr specifier; if so, its declaration shall specify a
11925     //   brace-or-equal-initializer in which every initializer-clause that is
11926     //   an assignment-expression is a constant expression.
11927 
11928     // Do nothing on dependent types.
11929     if (DclT->isDependentType()) {
11930 
11931     // Allow any 'static constexpr' members, whether or not they are of literal
11932     // type. We separately check that every constexpr variable is of literal
11933     // type.
11934     } else if (VDecl->isConstexpr()) {
11935 
11936     // Require constness.
11937     } else if (!DclT.isConstQualified()) {
11938       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
11939         << Init->getSourceRange();
11940       VDecl->setInvalidDecl();
11941 
11942     // We allow integer constant expressions in all cases.
11943     } else if (DclT->isIntegralOrEnumerationType()) {
11944       // Check whether the expression is a constant expression.
11945       SourceLocation Loc;
11946       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
11947         // In C++11, a non-constexpr const static data member with an
11948         // in-class initializer cannot be volatile.
11949         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
11950       else if (Init->isValueDependent())
11951         ; // Nothing to check.
11952       else if (Init->isIntegerConstantExpr(Context, &Loc))
11953         ; // Ok, it's an ICE!
11954       else if (Init->getType()->isScopedEnumeralType() &&
11955                Init->isCXX11ConstantExpr(Context))
11956         ; // Ok, it is a scoped-enum constant expression.
11957       else if (Init->isEvaluatable(Context)) {
11958         // If we can constant fold the initializer through heroics, accept it,
11959         // but report this as a use of an extension for -pedantic.
11960         Diag(Loc, diag::ext_in_class_initializer_non_constant)
11961           << Init->getSourceRange();
11962       } else {
11963         // Otherwise, this is some crazy unknown case.  Report the issue at the
11964         // location provided by the isIntegerConstantExpr failed check.
11965         Diag(Loc, diag::err_in_class_initializer_non_constant)
11966           << Init->getSourceRange();
11967         VDecl->setInvalidDecl();
11968       }
11969 
11970     // We allow foldable floating-point constants as an extension.
11971     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
11972       // In C++98, this is a GNU extension. In C++11, it is not, but we support
11973       // it anyway and provide a fixit to add the 'constexpr'.
11974       if (getLangOpts().CPlusPlus11) {
11975         Diag(VDecl->getLocation(),
11976              diag::ext_in_class_initializer_float_type_cxx11)
11977             << DclT << Init->getSourceRange();
11978         Diag(VDecl->getBeginLoc(),
11979              diag::note_in_class_initializer_float_type_cxx11)
11980             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11981       } else {
11982         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
11983           << DclT << Init->getSourceRange();
11984 
11985         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
11986           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
11987             << Init->getSourceRange();
11988           VDecl->setInvalidDecl();
11989         }
11990       }
11991 
11992     // Suggest adding 'constexpr' in C++11 for literal types.
11993     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
11994       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
11995           << DclT << Init->getSourceRange()
11996           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11997       VDecl->setConstexpr(true);
11998 
11999     } else {
12000       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12001         << DclT << Init->getSourceRange();
12002       VDecl->setInvalidDecl();
12003     }
12004   } else if (VDecl->isFileVarDecl()) {
12005     // In C, extern is typically used to avoid tentative definitions when
12006     // declaring variables in headers, but adding an intializer makes it a
12007     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12008     // In C++, extern is often used to give implictly static const variables
12009     // external linkage, so don't warn in that case. If selectany is present,
12010     // this might be header code intended for C and C++ inclusion, so apply the
12011     // C++ rules.
12012     if (VDecl->getStorageClass() == SC_Extern &&
12013         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12014          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12015         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12016         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12017       Diag(VDecl->getLocation(), diag::warn_extern_init);
12018 
12019     // In Microsoft C++ mode, a const variable defined in namespace scope has
12020     // external linkage by default if the variable is declared with
12021     // __declspec(dllexport).
12022     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12023         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12024         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12025       VDecl->setStorageClass(SC_Extern);
12026 
12027     // C99 6.7.8p4. All file scoped initializers need to be constant.
12028     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12029       CheckForConstantInitializer(Init, DclT);
12030   }
12031 
12032   QualType InitType = Init->getType();
12033   if (!InitType.isNull() &&
12034       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12035        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12036     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12037 
12038   // We will represent direct-initialization similarly to copy-initialization:
12039   //    int x(1);  -as-> int x = 1;
12040   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12041   //
12042   // Clients that want to distinguish between the two forms, can check for
12043   // direct initializer using VarDecl::getInitStyle().
12044   // A major benefit is that clients that don't particularly care about which
12045   // exactly form was it (like the CodeGen) can handle both cases without
12046   // special case code.
12047 
12048   // C++ 8.5p11:
12049   // The form of initialization (using parentheses or '=') is generally
12050   // insignificant, but does matter when the entity being initialized has a
12051   // class type.
12052   if (CXXDirectInit) {
12053     assert(DirectInit && "Call-style initializer must be direct init.");
12054     VDecl->setInitStyle(VarDecl::CallInit);
12055   } else if (DirectInit) {
12056     // This must be list-initialization. No other way is direct-initialization.
12057     VDecl->setInitStyle(VarDecl::ListInit);
12058   }
12059 
12060   CheckCompleteVariableDeclaration(VDecl);
12061 }
12062 
12063 /// ActOnInitializerError - Given that there was an error parsing an
12064 /// initializer for the given declaration, try to return to some form
12065 /// of sanity.
12066 void Sema::ActOnInitializerError(Decl *D) {
12067   // Our main concern here is re-establishing invariants like "a
12068   // variable's type is either dependent or complete".
12069   if (!D || D->isInvalidDecl()) return;
12070 
12071   VarDecl *VD = dyn_cast<VarDecl>(D);
12072   if (!VD) return;
12073 
12074   // Bindings are not usable if we can't make sense of the initializer.
12075   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12076     for (auto *BD : DD->bindings())
12077       BD->setInvalidDecl();
12078 
12079   // Auto types are meaningless if we can't make sense of the initializer.
12080   if (ParsingInitForAutoVars.count(D)) {
12081     D->setInvalidDecl();
12082     return;
12083   }
12084 
12085   QualType Ty = VD->getType();
12086   if (Ty->isDependentType()) return;
12087 
12088   // Require a complete type.
12089   if (RequireCompleteType(VD->getLocation(),
12090                           Context.getBaseElementType(Ty),
12091                           diag::err_typecheck_decl_incomplete_type)) {
12092     VD->setInvalidDecl();
12093     return;
12094   }
12095 
12096   // Require a non-abstract type.
12097   if (RequireNonAbstractType(VD->getLocation(), Ty,
12098                              diag::err_abstract_type_in_decl,
12099                              AbstractVariableType)) {
12100     VD->setInvalidDecl();
12101     return;
12102   }
12103 
12104   // Don't bother complaining about constructors or destructors,
12105   // though.
12106 }
12107 
12108 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12109   // If there is no declaration, there was an error parsing it. Just ignore it.
12110   if (!RealDecl)
12111     return;
12112 
12113   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12114     QualType Type = Var->getType();
12115 
12116     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12117     if (isa<DecompositionDecl>(RealDecl)) {
12118       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12119       Var->setInvalidDecl();
12120       return;
12121     }
12122 
12123     if (Type->isUndeducedType() &&
12124         DeduceVariableDeclarationType(Var, false, nullptr))
12125       return;
12126 
12127     // C++11 [class.static.data]p3: A static data member can be declared with
12128     // the constexpr specifier; if so, its declaration shall specify
12129     // a brace-or-equal-initializer.
12130     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12131     // the definition of a variable [...] or the declaration of a static data
12132     // member.
12133     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12134         !Var->isThisDeclarationADemotedDefinition()) {
12135       if (Var->isStaticDataMember()) {
12136         // C++1z removes the relevant rule; the in-class declaration is always
12137         // a definition there.
12138         if (!getLangOpts().CPlusPlus17 &&
12139             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12140           Diag(Var->getLocation(),
12141                diag::err_constexpr_static_mem_var_requires_init)
12142             << Var->getDeclName();
12143           Var->setInvalidDecl();
12144           return;
12145         }
12146       } else {
12147         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12148         Var->setInvalidDecl();
12149         return;
12150       }
12151     }
12152 
12153     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12154     // be initialized.
12155     if (!Var->isInvalidDecl() &&
12156         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12157         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12158       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12159       Var->setInvalidDecl();
12160       return;
12161     }
12162 
12163     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12164     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12165         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12166       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12167                             NTCUC_DefaultInitializedObject, NTCUK_Init);
12168 
12169 
12170     switch (DefKind) {
12171     case VarDecl::Definition:
12172       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12173         break;
12174 
12175       // We have an out-of-line definition of a static data member
12176       // that has an in-class initializer, so we type-check this like
12177       // a declaration.
12178       //
12179       LLVM_FALLTHROUGH;
12180 
12181     case VarDecl::DeclarationOnly:
12182       // It's only a declaration.
12183 
12184       // Block scope. C99 6.7p7: If an identifier for an object is
12185       // declared with no linkage (C99 6.2.2p6), the type for the
12186       // object shall be complete.
12187       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12188           !Var->hasLinkage() && !Var->isInvalidDecl() &&
12189           RequireCompleteType(Var->getLocation(), Type,
12190                               diag::err_typecheck_decl_incomplete_type))
12191         Var->setInvalidDecl();
12192 
12193       // Make sure that the type is not abstract.
12194       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12195           RequireNonAbstractType(Var->getLocation(), Type,
12196                                  diag::err_abstract_type_in_decl,
12197                                  AbstractVariableType))
12198         Var->setInvalidDecl();
12199       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12200           Var->getStorageClass() == SC_PrivateExtern) {
12201         Diag(Var->getLocation(), diag::warn_private_extern);
12202         Diag(Var->getLocation(), diag::note_private_extern);
12203       }
12204 
12205       return;
12206 
12207     case VarDecl::TentativeDefinition:
12208       // File scope. C99 6.9.2p2: A declaration of an identifier for an
12209       // object that has file scope without an initializer, and without a
12210       // storage-class specifier or with the storage-class specifier "static",
12211       // constitutes a tentative definition. Note: A tentative definition with
12212       // external linkage is valid (C99 6.2.2p5).
12213       if (!Var->isInvalidDecl()) {
12214         if (const IncompleteArrayType *ArrayT
12215                                     = Context.getAsIncompleteArrayType(Type)) {
12216           if (RequireCompleteType(Var->getLocation(),
12217                                   ArrayT->getElementType(),
12218                                   diag::err_illegal_decl_array_incomplete_type))
12219             Var->setInvalidDecl();
12220         } else if (Var->getStorageClass() == SC_Static) {
12221           // C99 6.9.2p3: If the declaration of an identifier for an object is
12222           // a tentative definition and has internal linkage (C99 6.2.2p3), the
12223           // declared type shall not be an incomplete type.
12224           // NOTE: code such as the following
12225           //     static struct s;
12226           //     struct s { int a; };
12227           // is accepted by gcc. Hence here we issue a warning instead of
12228           // an error and we do not invalidate the static declaration.
12229           // NOTE: to avoid multiple warnings, only check the first declaration.
12230           if (Var->isFirstDecl())
12231             RequireCompleteType(Var->getLocation(), Type,
12232                                 diag::ext_typecheck_decl_incomplete_type);
12233         }
12234       }
12235 
12236       // Record the tentative definition; we're done.
12237       if (!Var->isInvalidDecl())
12238         TentativeDefinitions.push_back(Var);
12239       return;
12240     }
12241 
12242     // Provide a specific diagnostic for uninitialized variable
12243     // definitions with incomplete array type.
12244     if (Type->isIncompleteArrayType()) {
12245       Diag(Var->getLocation(),
12246            diag::err_typecheck_incomplete_array_needs_initializer);
12247       Var->setInvalidDecl();
12248       return;
12249     }
12250 
12251     // Provide a specific diagnostic for uninitialized variable
12252     // definitions with reference type.
12253     if (Type->isReferenceType()) {
12254       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12255         << Var->getDeclName()
12256         << SourceRange(Var->getLocation(), Var->getLocation());
12257       Var->setInvalidDecl();
12258       return;
12259     }
12260 
12261     // Do not attempt to type-check the default initializer for a
12262     // variable with dependent type.
12263     if (Type->isDependentType())
12264       return;
12265 
12266     if (Var->isInvalidDecl())
12267       return;
12268 
12269     if (!Var->hasAttr<AliasAttr>()) {
12270       if (RequireCompleteType(Var->getLocation(),
12271                               Context.getBaseElementType(Type),
12272                               diag::err_typecheck_decl_incomplete_type)) {
12273         Var->setInvalidDecl();
12274         return;
12275       }
12276     } else {
12277       return;
12278     }
12279 
12280     // The variable can not have an abstract class type.
12281     if (RequireNonAbstractType(Var->getLocation(), Type,
12282                                diag::err_abstract_type_in_decl,
12283                                AbstractVariableType)) {
12284       Var->setInvalidDecl();
12285       return;
12286     }
12287 
12288     // Check for jumps past the implicit initializer.  C++0x
12289     // clarifies that this applies to a "variable with automatic
12290     // storage duration", not a "local variable".
12291     // C++11 [stmt.dcl]p3
12292     //   A program that jumps from a point where a variable with automatic
12293     //   storage duration is not in scope to a point where it is in scope is
12294     //   ill-formed unless the variable has scalar type, class type with a
12295     //   trivial default constructor and a trivial destructor, a cv-qualified
12296     //   version of one of these types, or an array of one of the preceding
12297     //   types and is declared without an initializer.
12298     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12299       if (const RecordType *Record
12300             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12301         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12302         // Mark the function (if we're in one) for further checking even if the
12303         // looser rules of C++11 do not require such checks, so that we can
12304         // diagnose incompatibilities with C++98.
12305         if (!CXXRecord->isPOD())
12306           setFunctionHasBranchProtectedScope();
12307       }
12308     }
12309     // In OpenCL, we can't initialize objects in the __local address space,
12310     // even implicitly, so don't synthesize an implicit initializer.
12311     if (getLangOpts().OpenCL &&
12312         Var->getType().getAddressSpace() == LangAS::opencl_local)
12313       return;
12314     // C++03 [dcl.init]p9:
12315     //   If no initializer is specified for an object, and the
12316     //   object is of (possibly cv-qualified) non-POD class type (or
12317     //   array thereof), the object shall be default-initialized; if
12318     //   the object is of const-qualified type, the underlying class
12319     //   type shall have a user-declared default
12320     //   constructor. Otherwise, if no initializer is specified for
12321     //   a non- static object, the object and its subobjects, if
12322     //   any, have an indeterminate initial value); if the object
12323     //   or any of its subobjects are of const-qualified type, the
12324     //   program is ill-formed.
12325     // C++0x [dcl.init]p11:
12326     //   If no initializer is specified for an object, the object is
12327     //   default-initialized; [...].
12328     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12329     InitializationKind Kind
12330       = InitializationKind::CreateDefault(Var->getLocation());
12331 
12332     InitializationSequence InitSeq(*this, Entity, Kind, None);
12333     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12334     if (Init.isInvalid())
12335       Var->setInvalidDecl();
12336     else if (Init.get()) {
12337       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12338       // This is important for template substitution.
12339       Var->setInitStyle(VarDecl::CallInit);
12340     }
12341 
12342     CheckCompleteVariableDeclaration(Var);
12343   }
12344 }
12345 
12346 void Sema::ActOnCXXForRangeDecl(Decl *D) {
12347   // If there is no declaration, there was an error parsing it. Ignore it.
12348   if (!D)
12349     return;
12350 
12351   VarDecl *VD = dyn_cast<VarDecl>(D);
12352   if (!VD) {
12353     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12354     D->setInvalidDecl();
12355     return;
12356   }
12357 
12358   VD->setCXXForRangeDecl(true);
12359 
12360   // for-range-declaration cannot be given a storage class specifier.
12361   int Error = -1;
12362   switch (VD->getStorageClass()) {
12363   case SC_None:
12364     break;
12365   case SC_Extern:
12366     Error = 0;
12367     break;
12368   case SC_Static:
12369     Error = 1;
12370     break;
12371   case SC_PrivateExtern:
12372     Error = 2;
12373     break;
12374   case SC_Auto:
12375     Error = 3;
12376     break;
12377   case SC_Register:
12378     Error = 4;
12379     break;
12380   }
12381   if (Error != -1) {
12382     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12383       << VD->getDeclName() << Error;
12384     D->setInvalidDecl();
12385   }
12386 }
12387 
12388 StmtResult
12389 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
12390                                  IdentifierInfo *Ident,
12391                                  ParsedAttributes &Attrs,
12392                                  SourceLocation AttrEnd) {
12393   // C++1y [stmt.iter]p1:
12394   //   A range-based for statement of the form
12395   //      for ( for-range-identifier : for-range-initializer ) statement
12396   //   is equivalent to
12397   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
12398   DeclSpec DS(Attrs.getPool().getFactory());
12399 
12400   const char *PrevSpec;
12401   unsigned DiagID;
12402   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
12403                      getPrintingPolicy());
12404 
12405   Declarator D(DS, DeclaratorContext::ForContext);
12406   D.SetIdentifier(Ident, IdentLoc);
12407   D.takeAttributes(Attrs, AttrEnd);
12408 
12409   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
12410                 IdentLoc);
12411   Decl *Var = ActOnDeclarator(S, D);
12412   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
12413   FinalizeDeclaration(Var);
12414   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
12415                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
12416 }
12417 
12418 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
12419   if (var->isInvalidDecl()) return;
12420 
12421   if (getLangOpts().OpenCL) {
12422     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
12423     // initialiser
12424     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
12425         !var->hasInit()) {
12426       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
12427           << 1 /*Init*/;
12428       var->setInvalidDecl();
12429       return;
12430     }
12431   }
12432 
12433   // In Objective-C, don't allow jumps past the implicit initialization of a
12434   // local retaining variable.
12435   if (getLangOpts().ObjC &&
12436       var->hasLocalStorage()) {
12437     switch (var->getType().getObjCLifetime()) {
12438     case Qualifiers::OCL_None:
12439     case Qualifiers::OCL_ExplicitNone:
12440     case Qualifiers::OCL_Autoreleasing:
12441       break;
12442 
12443     case Qualifiers::OCL_Weak:
12444     case Qualifiers::OCL_Strong:
12445       setFunctionHasBranchProtectedScope();
12446       break;
12447     }
12448   }
12449 
12450   if (var->hasLocalStorage() &&
12451       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
12452     setFunctionHasBranchProtectedScope();
12453 
12454   // Warn about externally-visible variables being defined without a
12455   // prior declaration.  We only want to do this for global
12456   // declarations, but we also specifically need to avoid doing it for
12457   // class members because the linkage of an anonymous class can
12458   // change if it's later given a typedef name.
12459   if (var->isThisDeclarationADefinition() &&
12460       var->getDeclContext()->getRedeclContext()->isFileContext() &&
12461       var->isExternallyVisible() && var->hasLinkage() &&
12462       !var->isInline() && !var->getDescribedVarTemplate() &&
12463       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
12464       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
12465                                   var->getLocation())) {
12466     // Find a previous declaration that's not a definition.
12467     VarDecl *prev = var->getPreviousDecl();
12468     while (prev && prev->isThisDeclarationADefinition())
12469       prev = prev->getPreviousDecl();
12470 
12471     if (!prev) {
12472       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
12473       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
12474           << /* variable */ 0;
12475     }
12476   }
12477 
12478   // Cache the result of checking for constant initialization.
12479   Optional<bool> CacheHasConstInit;
12480   const Expr *CacheCulprit = nullptr;
12481   auto checkConstInit = [&]() mutable {
12482     if (!CacheHasConstInit)
12483       CacheHasConstInit = var->getInit()->isConstantInitializer(
12484             Context, var->getType()->isReferenceType(), &CacheCulprit);
12485     return *CacheHasConstInit;
12486   };
12487 
12488   if (var->getTLSKind() == VarDecl::TLS_Static) {
12489     if (var->getType().isDestructedType()) {
12490       // GNU C++98 edits for __thread, [basic.start.term]p3:
12491       //   The type of an object with thread storage duration shall not
12492       //   have a non-trivial destructor.
12493       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
12494       if (getLangOpts().CPlusPlus11)
12495         Diag(var->getLocation(), diag::note_use_thread_local);
12496     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
12497       if (!checkConstInit()) {
12498         // GNU C++98 edits for __thread, [basic.start.init]p4:
12499         //   An object of thread storage duration shall not require dynamic
12500         //   initialization.
12501         // FIXME: Need strict checking here.
12502         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
12503           << CacheCulprit->getSourceRange();
12504         if (getLangOpts().CPlusPlus11)
12505           Diag(var->getLocation(), diag::note_use_thread_local);
12506       }
12507     }
12508   }
12509 
12510   // Apply section attributes and pragmas to global variables.
12511   bool GlobalStorage = var->hasGlobalStorage();
12512   if (GlobalStorage && var->isThisDeclarationADefinition() &&
12513       !inTemplateInstantiation()) {
12514     PragmaStack<StringLiteral *> *Stack = nullptr;
12515     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
12516     if (var->getType().isConstQualified())
12517       Stack = &ConstSegStack;
12518     else if (!var->getInit()) {
12519       Stack = &BSSSegStack;
12520       SectionFlags |= ASTContext::PSF_Write;
12521     } else {
12522       Stack = &DataSegStack;
12523       SectionFlags |= ASTContext::PSF_Write;
12524     }
12525     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>())
12526       var->addAttr(SectionAttr::CreateImplicit(
12527           Context, Stack->CurrentValue->getString(),
12528           Stack->CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
12529           SectionAttr::Declspec_allocate));
12530     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
12531       if (UnifySection(SA->getName(), SectionFlags, var))
12532         var->dropAttr<SectionAttr>();
12533 
12534     // Apply the init_seg attribute if this has an initializer.  If the
12535     // initializer turns out to not be dynamic, we'll end up ignoring this
12536     // attribute.
12537     if (CurInitSeg && var->getInit())
12538       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
12539                                                CurInitSegLoc,
12540                                                AttributeCommonInfo::AS_Pragma));
12541   }
12542 
12543   // All the following checks are C++ only.
12544   if (!getLangOpts().CPlusPlus) {
12545       // If this variable must be emitted, add it as an initializer for the
12546       // current module.
12547      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12548        Context.addModuleInitializer(ModuleScopes.back().Module, var);
12549      return;
12550   }
12551 
12552   if (auto *DD = dyn_cast<DecompositionDecl>(var))
12553     CheckCompleteDecompositionDeclaration(DD);
12554 
12555   QualType type = var->getType();
12556   if (type->isDependentType()) return;
12557 
12558   if (var->hasAttr<BlocksAttr>())
12559     getCurFunction()->addByrefBlockVar(var);
12560 
12561   Expr *Init = var->getInit();
12562   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
12563   QualType baseType = Context.getBaseElementType(type);
12564 
12565   if (Init && !Init->isValueDependent()) {
12566     if (var->isConstexpr()) {
12567       SmallVector<PartialDiagnosticAt, 8> Notes;
12568       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
12569         SourceLocation DiagLoc = var->getLocation();
12570         // If the note doesn't add any useful information other than a source
12571         // location, fold it into the primary diagnostic.
12572         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12573               diag::note_invalid_subexpr_in_const_expr) {
12574           DiagLoc = Notes[0].first;
12575           Notes.clear();
12576         }
12577         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
12578           << var << Init->getSourceRange();
12579         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
12580           Diag(Notes[I].first, Notes[I].second);
12581       }
12582     } else if (var->mightBeUsableInConstantExpressions(Context)) {
12583       // Check whether the initializer of a const variable of integral or
12584       // enumeration type is an ICE now, since we can't tell whether it was
12585       // initialized by a constant expression if we check later.
12586       var->checkInitIsICE();
12587     }
12588 
12589     // Don't emit further diagnostics about constexpr globals since they
12590     // were just diagnosed.
12591     if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) {
12592       // FIXME: Need strict checking in C++03 here.
12593       bool DiagErr = getLangOpts().CPlusPlus11
12594           ? !var->checkInitIsICE() : !checkConstInit();
12595       if (DiagErr) {
12596         auto *Attr = var->getAttr<ConstInitAttr>();
12597         Diag(var->getLocation(), diag::err_require_constant_init_failed)
12598           << Init->getSourceRange();
12599         Diag(Attr->getLocation(),
12600              diag::note_declared_required_constant_init_here)
12601             << Attr->getRange() << Attr->isConstinit();
12602         if (getLangOpts().CPlusPlus11) {
12603           APValue Value;
12604           SmallVector<PartialDiagnosticAt, 8> Notes;
12605           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
12606           for (auto &it : Notes)
12607             Diag(it.first, it.second);
12608         } else {
12609           Diag(CacheCulprit->getExprLoc(),
12610                diag::note_invalid_subexpr_in_const_expr)
12611               << CacheCulprit->getSourceRange();
12612         }
12613       }
12614     }
12615     else if (!var->isConstexpr() && IsGlobal &&
12616              !getDiagnostics().isIgnored(diag::warn_global_constructor,
12617                                     var->getLocation())) {
12618       // Warn about globals which don't have a constant initializer.  Don't
12619       // warn about globals with a non-trivial destructor because we already
12620       // warned about them.
12621       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
12622       if (!(RD && !RD->hasTrivialDestructor())) {
12623         if (!checkConstInit())
12624           Diag(var->getLocation(), diag::warn_global_constructor)
12625             << Init->getSourceRange();
12626       }
12627     }
12628   }
12629 
12630   // Require the destructor.
12631   if (const RecordType *recordType = baseType->getAs<RecordType>())
12632     FinalizeVarWithDestructor(var, recordType);
12633 
12634   // If this variable must be emitted, add it as an initializer for the current
12635   // module.
12636   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12637     Context.addModuleInitializer(ModuleScopes.back().Module, var);
12638 }
12639 
12640 /// Determines if a variable's alignment is dependent.
12641 static bool hasDependentAlignment(VarDecl *VD) {
12642   if (VD->getType()->isDependentType())
12643     return true;
12644   for (auto *I : VD->specific_attrs<AlignedAttr>())
12645     if (I->isAlignmentDependent())
12646       return true;
12647   return false;
12648 }
12649 
12650 /// Check if VD needs to be dllexport/dllimport due to being in a
12651 /// dllexport/import function.
12652 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
12653   assert(VD->isStaticLocal());
12654 
12655   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12656 
12657   // Find outermost function when VD is in lambda function.
12658   while (FD && !getDLLAttr(FD) &&
12659          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
12660          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
12661     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
12662   }
12663 
12664   if (!FD)
12665     return;
12666 
12667   // Static locals inherit dll attributes from their function.
12668   if (Attr *A = getDLLAttr(FD)) {
12669     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
12670     NewAttr->setInherited(true);
12671     VD->addAttr(NewAttr);
12672   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
12673     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
12674     NewAttr->setInherited(true);
12675     VD->addAttr(NewAttr);
12676 
12677     // Export this function to enforce exporting this static variable even
12678     // if it is not used in this compilation unit.
12679     if (!FD->hasAttr<DLLExportAttr>())
12680       FD->addAttr(NewAttr);
12681 
12682   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
12683     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
12684     NewAttr->setInherited(true);
12685     VD->addAttr(NewAttr);
12686   }
12687 }
12688 
12689 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
12690 /// any semantic actions necessary after any initializer has been attached.
12691 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
12692   // Note that we are no longer parsing the initializer for this declaration.
12693   ParsingInitForAutoVars.erase(ThisDecl);
12694 
12695   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
12696   if (!VD)
12697     return;
12698 
12699   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
12700   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
12701       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
12702     if (PragmaClangBSSSection.Valid)
12703       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
12704           Context, PragmaClangBSSSection.SectionName,
12705           PragmaClangBSSSection.PragmaLocation,
12706           AttributeCommonInfo::AS_Pragma));
12707     if (PragmaClangDataSection.Valid)
12708       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
12709           Context, PragmaClangDataSection.SectionName,
12710           PragmaClangDataSection.PragmaLocation,
12711           AttributeCommonInfo::AS_Pragma));
12712     if (PragmaClangRodataSection.Valid)
12713       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
12714           Context, PragmaClangRodataSection.SectionName,
12715           PragmaClangRodataSection.PragmaLocation,
12716           AttributeCommonInfo::AS_Pragma));
12717     if (PragmaClangRelroSection.Valid)
12718       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
12719           Context, PragmaClangRelroSection.SectionName,
12720           PragmaClangRelroSection.PragmaLocation,
12721           AttributeCommonInfo::AS_Pragma));
12722   }
12723 
12724   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
12725     for (auto *BD : DD->bindings()) {
12726       FinalizeDeclaration(BD);
12727     }
12728   }
12729 
12730   checkAttributesAfterMerging(*this, *VD);
12731 
12732   // Perform TLS alignment check here after attributes attached to the variable
12733   // which may affect the alignment have been processed. Only perform the check
12734   // if the target has a maximum TLS alignment (zero means no constraints).
12735   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
12736     // Protect the check so that it's not performed on dependent types and
12737     // dependent alignments (we can't determine the alignment in that case).
12738     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
12739         !VD->isInvalidDecl()) {
12740       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
12741       if (Context.getDeclAlign(VD) > MaxAlignChars) {
12742         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
12743           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
12744           << (unsigned)MaxAlignChars.getQuantity();
12745       }
12746     }
12747   }
12748 
12749   if (VD->isStaticLocal()) {
12750     CheckStaticLocalForDllExport(VD);
12751 
12752     if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
12753       // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
12754       // function, only __shared__ variables or variables without any device
12755       // memory qualifiers may be declared with static storage class.
12756       // Note: It is unclear how a function-scope non-const static variable
12757       // without device memory qualifier is implemented, therefore only static
12758       // const variable without device memory qualifier is allowed.
12759       [&]() {
12760         if (!getLangOpts().CUDA)
12761           return;
12762         if (VD->hasAttr<CUDASharedAttr>())
12763           return;
12764         if (VD->getType().isConstQualified() &&
12765             !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
12766           return;
12767         if (CUDADiagIfDeviceCode(VD->getLocation(),
12768                                  diag::err_device_static_local_var)
12769             << CurrentCUDATarget())
12770           VD->setInvalidDecl();
12771       }();
12772     }
12773   }
12774 
12775   // Perform check for initializers of device-side global variables.
12776   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
12777   // 7.5). We must also apply the same checks to all __shared__
12778   // variables whether they are local or not. CUDA also allows
12779   // constant initializers for __constant__ and __device__ variables.
12780   if (getLangOpts().CUDA)
12781     checkAllowedCUDAInitializer(VD);
12782 
12783   // Grab the dllimport or dllexport attribute off of the VarDecl.
12784   const InheritableAttr *DLLAttr = getDLLAttr(VD);
12785 
12786   // Imported static data members cannot be defined out-of-line.
12787   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
12788     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
12789         VD->isThisDeclarationADefinition()) {
12790       // We allow definitions of dllimport class template static data members
12791       // with a warning.
12792       CXXRecordDecl *Context =
12793         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
12794       bool IsClassTemplateMember =
12795           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
12796           Context->getDescribedClassTemplate();
12797 
12798       Diag(VD->getLocation(),
12799            IsClassTemplateMember
12800                ? diag::warn_attribute_dllimport_static_field_definition
12801                : diag::err_attribute_dllimport_static_field_definition);
12802       Diag(IA->getLocation(), diag::note_attribute);
12803       if (!IsClassTemplateMember)
12804         VD->setInvalidDecl();
12805     }
12806   }
12807 
12808   // dllimport/dllexport variables cannot be thread local, their TLS index
12809   // isn't exported with the variable.
12810   if (DLLAttr && VD->getTLSKind()) {
12811     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12812     if (F && getDLLAttr(F)) {
12813       assert(VD->isStaticLocal());
12814       // But if this is a static local in a dlimport/dllexport function, the
12815       // function will never be inlined, which means the var would never be
12816       // imported, so having it marked import/export is safe.
12817     } else {
12818       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
12819                                                                     << DLLAttr;
12820       VD->setInvalidDecl();
12821     }
12822   }
12823 
12824   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
12825     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
12826       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
12827       VD->dropAttr<UsedAttr>();
12828     }
12829   }
12830 
12831   const DeclContext *DC = VD->getDeclContext();
12832   // If there's a #pragma GCC visibility in scope, and this isn't a class
12833   // member, set the visibility of this variable.
12834   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
12835     AddPushedVisibilityAttribute(VD);
12836 
12837   // FIXME: Warn on unused var template partial specializations.
12838   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
12839     MarkUnusedFileScopedDecl(VD);
12840 
12841   // Now we have parsed the initializer and can update the table of magic
12842   // tag values.
12843   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
12844       !VD->getType()->isIntegralOrEnumerationType())
12845     return;
12846 
12847   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
12848     const Expr *MagicValueExpr = VD->getInit();
12849     if (!MagicValueExpr) {
12850       continue;
12851     }
12852     llvm::APSInt MagicValueInt;
12853     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
12854       Diag(I->getRange().getBegin(),
12855            diag::err_type_tag_for_datatype_not_ice)
12856         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12857       continue;
12858     }
12859     if (MagicValueInt.getActiveBits() > 64) {
12860       Diag(I->getRange().getBegin(),
12861            diag::err_type_tag_for_datatype_too_large)
12862         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12863       continue;
12864     }
12865     uint64_t MagicValue = MagicValueInt.getZExtValue();
12866     RegisterTypeTagForDatatype(I->getArgumentKind(),
12867                                MagicValue,
12868                                I->getMatchingCType(),
12869                                I->getLayoutCompatible(),
12870                                I->getMustBeNull());
12871   }
12872 }
12873 
12874 static bool hasDeducedAuto(DeclaratorDecl *DD) {
12875   auto *VD = dyn_cast<VarDecl>(DD);
12876   return VD && !VD->getType()->hasAutoForTrailingReturnType();
12877 }
12878 
12879 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
12880                                                    ArrayRef<Decl *> Group) {
12881   SmallVector<Decl*, 8> Decls;
12882 
12883   if (DS.isTypeSpecOwned())
12884     Decls.push_back(DS.getRepAsDecl());
12885 
12886   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
12887   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
12888   bool DiagnosedMultipleDecomps = false;
12889   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
12890   bool DiagnosedNonDeducedAuto = false;
12891 
12892   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12893     if (Decl *D = Group[i]) {
12894       // For declarators, there are some additional syntactic-ish checks we need
12895       // to perform.
12896       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
12897         if (!FirstDeclaratorInGroup)
12898           FirstDeclaratorInGroup = DD;
12899         if (!FirstDecompDeclaratorInGroup)
12900           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
12901         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
12902             !hasDeducedAuto(DD))
12903           FirstNonDeducedAutoInGroup = DD;
12904 
12905         if (FirstDeclaratorInGroup != DD) {
12906           // A decomposition declaration cannot be combined with any other
12907           // declaration in the same group.
12908           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
12909             Diag(FirstDecompDeclaratorInGroup->getLocation(),
12910                  diag::err_decomp_decl_not_alone)
12911                 << FirstDeclaratorInGroup->getSourceRange()
12912                 << DD->getSourceRange();
12913             DiagnosedMultipleDecomps = true;
12914           }
12915 
12916           // A declarator that uses 'auto' in any way other than to declare a
12917           // variable with a deduced type cannot be combined with any other
12918           // declarator in the same group.
12919           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
12920             Diag(FirstNonDeducedAutoInGroup->getLocation(),
12921                  diag::err_auto_non_deduced_not_alone)
12922                 << FirstNonDeducedAutoInGroup->getType()
12923                        ->hasAutoForTrailingReturnType()
12924                 << FirstDeclaratorInGroup->getSourceRange()
12925                 << DD->getSourceRange();
12926             DiagnosedNonDeducedAuto = true;
12927           }
12928         }
12929       }
12930 
12931       Decls.push_back(D);
12932     }
12933   }
12934 
12935   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
12936     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
12937       handleTagNumbering(Tag, S);
12938       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
12939           getLangOpts().CPlusPlus)
12940         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
12941     }
12942   }
12943 
12944   return BuildDeclaratorGroup(Decls);
12945 }
12946 
12947 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
12948 /// group, performing any necessary semantic checking.
12949 Sema::DeclGroupPtrTy
12950 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
12951   // C++14 [dcl.spec.auto]p7: (DR1347)
12952   //   If the type that replaces the placeholder type is not the same in each
12953   //   deduction, the program is ill-formed.
12954   if (Group.size() > 1) {
12955     QualType Deduced;
12956     VarDecl *DeducedDecl = nullptr;
12957     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12958       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
12959       if (!D || D->isInvalidDecl())
12960         break;
12961       DeducedType *DT = D->getType()->getContainedDeducedType();
12962       if (!DT || DT->getDeducedType().isNull())
12963         continue;
12964       if (Deduced.isNull()) {
12965         Deduced = DT->getDeducedType();
12966         DeducedDecl = D;
12967       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
12968         auto *AT = dyn_cast<AutoType>(DT);
12969         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
12970              diag::err_auto_different_deductions)
12971           << (AT ? (unsigned)AT->getKeyword() : 3)
12972           << Deduced << DeducedDecl->getDeclName()
12973           << DT->getDeducedType() << D->getDeclName()
12974           << DeducedDecl->getInit()->getSourceRange()
12975           << D->getInit()->getSourceRange();
12976         D->setInvalidDecl();
12977         break;
12978       }
12979     }
12980   }
12981 
12982   ActOnDocumentableDecls(Group);
12983 
12984   return DeclGroupPtrTy::make(
12985       DeclGroupRef::Create(Context, Group.data(), Group.size()));
12986 }
12987 
12988 void Sema::ActOnDocumentableDecl(Decl *D) {
12989   ActOnDocumentableDecls(D);
12990 }
12991 
12992 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
12993   // Don't parse the comment if Doxygen diagnostics are ignored.
12994   if (Group.empty() || !Group[0])
12995     return;
12996 
12997   if (Diags.isIgnored(diag::warn_doc_param_not_found,
12998                       Group[0]->getLocation()) &&
12999       Diags.isIgnored(diag::warn_unknown_comment_command_name,
13000                       Group[0]->getLocation()))
13001     return;
13002 
13003   if (Group.size() >= 2) {
13004     // This is a decl group.  Normally it will contain only declarations
13005     // produced from declarator list.  But in case we have any definitions or
13006     // additional declaration references:
13007     //   'typedef struct S {} S;'
13008     //   'typedef struct S *S;'
13009     //   'struct S *pS;'
13010     // FinalizeDeclaratorGroup adds these as separate declarations.
13011     Decl *MaybeTagDecl = Group[0];
13012     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13013       Group = Group.slice(1);
13014     }
13015   }
13016 
13017   // FIMXE: We assume every Decl in the group is in the same file.
13018   // This is false when preprocessor constructs the group from decls in
13019   // different files (e. g. macros or #include).
13020   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13021 }
13022 
13023 /// Common checks for a parameter-declaration that should apply to both function
13024 /// parameters and non-type template parameters.
13025 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13026   // Check that there are no default arguments inside the type of this
13027   // parameter.
13028   if (getLangOpts().CPlusPlus)
13029     CheckExtraCXXDefaultArguments(D);
13030 
13031   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13032   if (D.getCXXScopeSpec().isSet()) {
13033     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13034       << D.getCXXScopeSpec().getRange();
13035   }
13036 
13037   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13038   // simple identifier except [...irrelevant cases...].
13039   switch (D.getName().getKind()) {
13040   case UnqualifiedIdKind::IK_Identifier:
13041     break;
13042 
13043   case UnqualifiedIdKind::IK_OperatorFunctionId:
13044   case UnqualifiedIdKind::IK_ConversionFunctionId:
13045   case UnqualifiedIdKind::IK_LiteralOperatorId:
13046   case UnqualifiedIdKind::IK_ConstructorName:
13047   case UnqualifiedIdKind::IK_DestructorName:
13048   case UnqualifiedIdKind::IK_ImplicitSelfParam:
13049   case UnqualifiedIdKind::IK_DeductionGuideName:
13050     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13051       << GetNameForDeclarator(D).getName();
13052     break;
13053 
13054   case UnqualifiedIdKind::IK_TemplateId:
13055   case UnqualifiedIdKind::IK_ConstructorTemplateId:
13056     // GetNameForDeclarator would not produce a useful name in this case.
13057     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13058     break;
13059   }
13060 }
13061 
13062 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13063 /// to introduce parameters into function prototype scope.
13064 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13065   const DeclSpec &DS = D.getDeclSpec();
13066 
13067   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13068 
13069   // C++03 [dcl.stc]p2 also permits 'auto'.
13070   StorageClass SC = SC_None;
13071   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13072     SC = SC_Register;
13073     // In C++11, the 'register' storage class specifier is deprecated.
13074     // In C++17, it is not allowed, but we tolerate it as an extension.
13075     if (getLangOpts().CPlusPlus11) {
13076       Diag(DS.getStorageClassSpecLoc(),
13077            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13078                                      : diag::warn_deprecated_register)
13079         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13080     }
13081   } else if (getLangOpts().CPlusPlus &&
13082              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13083     SC = SC_Auto;
13084   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13085     Diag(DS.getStorageClassSpecLoc(),
13086          diag::err_invalid_storage_class_in_func_decl);
13087     D.getMutableDeclSpec().ClearStorageClassSpecs();
13088   }
13089 
13090   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13091     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13092       << DeclSpec::getSpecifierName(TSCS);
13093   if (DS.isInlineSpecified())
13094     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13095         << getLangOpts().CPlusPlus17;
13096   if (DS.hasConstexprSpecifier())
13097     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13098         << 0 << D.getDeclSpec().getConstexprSpecifier();
13099 
13100   DiagnoseFunctionSpecifiers(DS);
13101 
13102   CheckFunctionOrTemplateParamDeclarator(S, D);
13103 
13104   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13105   QualType parmDeclType = TInfo->getType();
13106 
13107   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13108   IdentifierInfo *II = D.getIdentifier();
13109   if (II) {
13110     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13111                    ForVisibleRedeclaration);
13112     LookupName(R, S);
13113     if (R.isSingleResult()) {
13114       NamedDecl *PrevDecl = R.getFoundDecl();
13115       if (PrevDecl->isTemplateParameter()) {
13116         // Maybe we will complain about the shadowed template parameter.
13117         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13118         // Just pretend that we didn't see the previous declaration.
13119         PrevDecl = nullptr;
13120       } else if (S->isDeclScope(PrevDecl)) {
13121         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13122         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13123 
13124         // Recover by removing the name
13125         II = nullptr;
13126         D.SetIdentifier(nullptr, D.getIdentifierLoc());
13127         D.setInvalidType(true);
13128       }
13129     }
13130   }
13131 
13132   // Temporarily put parameter variables in the translation unit, not
13133   // the enclosing context.  This prevents them from accidentally
13134   // looking like class members in C++.
13135   ParmVarDecl *New =
13136       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13137                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13138 
13139   if (D.isInvalidType())
13140     New->setInvalidDecl();
13141 
13142   assert(S->isFunctionPrototypeScope());
13143   assert(S->getFunctionPrototypeDepth() >= 1);
13144   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13145                     S->getNextFunctionPrototypeIndex());
13146 
13147   // Add the parameter declaration into this scope.
13148   S->AddDecl(New);
13149   if (II)
13150     IdResolver.AddDecl(New);
13151 
13152   ProcessDeclAttributes(S, New, D);
13153 
13154   if (D.getDeclSpec().isModulePrivateSpecified())
13155     Diag(New->getLocation(), diag::err_module_private_local)
13156       << 1 << New->getDeclName()
13157       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13158       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13159 
13160   if (New->hasAttr<BlocksAttr>()) {
13161     Diag(New->getLocation(), diag::err_block_on_nonlocal);
13162   }
13163 
13164   if (getLangOpts().OpenCL)
13165     deduceOpenCLAddressSpace(New);
13166 
13167   return New;
13168 }
13169 
13170 /// Synthesizes a variable for a parameter arising from a
13171 /// typedef.
13172 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13173                                               SourceLocation Loc,
13174                                               QualType T) {
13175   /* FIXME: setting StartLoc == Loc.
13176      Would it be worth to modify callers so as to provide proper source
13177      location for the unnamed parameters, embedding the parameter's type? */
13178   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13179                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
13180                                            SC_None, nullptr);
13181   Param->setImplicit();
13182   return Param;
13183 }
13184 
13185 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13186   // Don't diagnose unused-parameter errors in template instantiations; we
13187   // will already have done so in the template itself.
13188   if (inTemplateInstantiation())
13189     return;
13190 
13191   for (const ParmVarDecl *Parameter : Parameters) {
13192     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13193         !Parameter->hasAttr<UnusedAttr>()) {
13194       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13195         << Parameter->getDeclName();
13196     }
13197   }
13198 }
13199 
13200 void Sema::DiagnoseSizeOfParametersAndReturnValue(
13201     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13202   if (LangOpts.NumLargeByValueCopy == 0) // No check.
13203     return;
13204 
13205   // Warn if the return value is pass-by-value and larger than the specified
13206   // threshold.
13207   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13208     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13209     if (Size > LangOpts.NumLargeByValueCopy)
13210       Diag(D->getLocation(), diag::warn_return_value_size)
13211           << D->getDeclName() << Size;
13212   }
13213 
13214   // Warn if any parameter is pass-by-value and larger than the specified
13215   // threshold.
13216   for (const ParmVarDecl *Parameter : Parameters) {
13217     QualType T = Parameter->getType();
13218     if (T->isDependentType() || !T.isPODType(Context))
13219       continue;
13220     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13221     if (Size > LangOpts.NumLargeByValueCopy)
13222       Diag(Parameter->getLocation(), diag::warn_parameter_size)
13223           << Parameter->getDeclName() << Size;
13224   }
13225 }
13226 
13227 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13228                                   SourceLocation NameLoc, IdentifierInfo *Name,
13229                                   QualType T, TypeSourceInfo *TSInfo,
13230                                   StorageClass SC) {
13231   // In ARC, infer a lifetime qualifier for appropriate parameter types.
13232   if (getLangOpts().ObjCAutoRefCount &&
13233       T.getObjCLifetime() == Qualifiers::OCL_None &&
13234       T->isObjCLifetimeType()) {
13235 
13236     Qualifiers::ObjCLifetime lifetime;
13237 
13238     // Special cases for arrays:
13239     //   - if it's const, use __unsafe_unretained
13240     //   - otherwise, it's an error
13241     if (T->isArrayType()) {
13242       if (!T.isConstQualified()) {
13243         if (DelayedDiagnostics.shouldDelayDiagnostics())
13244           DelayedDiagnostics.add(
13245               sema::DelayedDiagnostic::makeForbiddenType(
13246               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13247         else
13248           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13249               << TSInfo->getTypeLoc().getSourceRange();
13250       }
13251       lifetime = Qualifiers::OCL_ExplicitNone;
13252     } else {
13253       lifetime = T->getObjCARCImplicitLifetime();
13254     }
13255     T = Context.getLifetimeQualifiedType(T, lifetime);
13256   }
13257 
13258   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13259                                          Context.getAdjustedParameterType(T),
13260                                          TSInfo, SC, nullptr);
13261 
13262   // Make a note if we created a new pack in the scope of a lambda, so that
13263   // we know that references to that pack must also be expanded within the
13264   // lambda scope.
13265   if (New->isParameterPack())
13266     if (auto *LSI = getEnclosingLambda())
13267       LSI->LocalPacks.push_back(New);
13268 
13269   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13270       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13271     checkNonTrivialCUnion(New->getType(), New->getLocation(),
13272                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13273 
13274   // Parameters can not be abstract class types.
13275   // For record types, this is done by the AbstractClassUsageDiagnoser once
13276   // the class has been completely parsed.
13277   if (!CurContext->isRecord() &&
13278       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13279                              AbstractParamType))
13280     New->setInvalidDecl();
13281 
13282   // Parameter declarators cannot be interface types. All ObjC objects are
13283   // passed by reference.
13284   if (T->isObjCObjectType()) {
13285     SourceLocation TypeEndLoc =
13286         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13287     Diag(NameLoc,
13288          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13289       << FixItHint::CreateInsertion(TypeEndLoc, "*");
13290     T = Context.getObjCObjectPointerType(T);
13291     New->setType(T);
13292   }
13293 
13294   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13295   // duration shall not be qualified by an address-space qualifier."
13296   // Since all parameters have automatic store duration, they can not have
13297   // an address space.
13298   if (T.getAddressSpace() != LangAS::Default &&
13299       // OpenCL allows function arguments declared to be an array of a type
13300       // to be qualified with an address space.
13301       !(getLangOpts().OpenCL &&
13302         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13303     Diag(NameLoc, diag::err_arg_with_address_space);
13304     New->setInvalidDecl();
13305   }
13306 
13307   return New;
13308 }
13309 
13310 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
13311                                            SourceLocation LocAfterDecls) {
13312   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
13313 
13314   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
13315   // for a K&R function.
13316   if (!FTI.hasPrototype) {
13317     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
13318       --i;
13319       if (FTI.Params[i].Param == nullptr) {
13320         SmallString<256> Code;
13321         llvm::raw_svector_ostream(Code)
13322             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
13323         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
13324             << FTI.Params[i].Ident
13325             << FixItHint::CreateInsertion(LocAfterDecls, Code);
13326 
13327         // Implicitly declare the argument as type 'int' for lack of a better
13328         // type.
13329         AttributeFactory attrs;
13330         DeclSpec DS(attrs);
13331         const char* PrevSpec; // unused
13332         unsigned DiagID; // unused
13333         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
13334                            DiagID, Context.getPrintingPolicy());
13335         // Use the identifier location for the type source range.
13336         DS.SetRangeStart(FTI.Params[i].IdentLoc);
13337         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
13338         Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
13339         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
13340         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
13341       }
13342     }
13343   }
13344 }
13345 
13346 Decl *
13347 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
13348                               MultiTemplateParamsArg TemplateParameterLists,
13349                               SkipBodyInfo *SkipBody) {
13350   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
13351   assert(D.isFunctionDeclarator() && "Not a function declarator!");
13352   Scope *ParentScope = FnBodyScope->getParent();
13353 
13354   D.setFunctionDefinitionKind(FDK_Definition);
13355   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
13356   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
13357 }
13358 
13359 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
13360   Consumer.HandleInlineFunctionDefinition(D);
13361 }
13362 
13363 static bool
13364 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
13365                                 const FunctionDecl *&PossiblePrototype) {
13366   // Don't warn about invalid declarations.
13367   if (FD->isInvalidDecl())
13368     return false;
13369 
13370   // Or declarations that aren't global.
13371   if (!FD->isGlobal())
13372     return false;
13373 
13374   // Don't warn about C++ member functions.
13375   if (isa<CXXMethodDecl>(FD))
13376     return false;
13377 
13378   // Don't warn about 'main'.
13379   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
13380     if (IdentifierInfo *II = FD->getIdentifier())
13381       if (II->isStr("main"))
13382         return false;
13383 
13384   // Don't warn about inline functions.
13385   if (FD->isInlined())
13386     return false;
13387 
13388   // Don't warn about function templates.
13389   if (FD->getDescribedFunctionTemplate())
13390     return false;
13391 
13392   // Don't warn about function template specializations.
13393   if (FD->isFunctionTemplateSpecialization())
13394     return false;
13395 
13396   // Don't warn for OpenCL kernels.
13397   if (FD->hasAttr<OpenCLKernelAttr>())
13398     return false;
13399 
13400   // Don't warn on explicitly deleted functions.
13401   if (FD->isDeleted())
13402     return false;
13403 
13404   for (const FunctionDecl *Prev = FD->getPreviousDecl();
13405        Prev; Prev = Prev->getPreviousDecl()) {
13406     // Ignore any declarations that occur in function or method
13407     // scope, because they aren't visible from the header.
13408     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
13409       continue;
13410 
13411     PossiblePrototype = Prev;
13412     return Prev->getType()->isFunctionNoProtoType();
13413   }
13414 
13415   return true;
13416 }
13417 
13418 void
13419 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
13420                                    const FunctionDecl *EffectiveDefinition,
13421                                    SkipBodyInfo *SkipBody) {
13422   const FunctionDecl *Definition = EffectiveDefinition;
13423   if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
13424     // If this is a friend function defined in a class template, it does not
13425     // have a body until it is used, nevertheless it is a definition, see
13426     // [temp.inst]p2:
13427     //
13428     // ... for the purpose of determining whether an instantiated redeclaration
13429     // is valid according to [basic.def.odr] and [class.mem], a declaration that
13430     // corresponds to a definition in the template is considered to be a
13431     // definition.
13432     //
13433     // The following code must produce redefinition error:
13434     //
13435     //     template<typename T> struct C20 { friend void func_20() {} };
13436     //     C20<int> c20i;
13437     //     void func_20() {}
13438     //
13439     for (auto I : FD->redecls()) {
13440       if (I != FD && !I->isInvalidDecl() &&
13441           I->getFriendObjectKind() != Decl::FOK_None) {
13442         if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
13443           if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
13444             // A merged copy of the same function, instantiated as a member of
13445             // the same class, is OK.
13446             if (declaresSameEntity(OrigFD, Original) &&
13447                 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
13448                                    cast<Decl>(FD->getLexicalDeclContext())))
13449               continue;
13450           }
13451 
13452           if (Original->isThisDeclarationADefinition()) {
13453             Definition = I;
13454             break;
13455           }
13456         }
13457       }
13458     }
13459   }
13460 
13461   if (!Definition)
13462     // Similar to friend functions a friend function template may be a
13463     // definition and do not have a body if it is instantiated in a class
13464     // template.
13465     if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
13466       for (auto I : FTD->redecls()) {
13467         auto D = cast<FunctionTemplateDecl>(I);
13468         if (D != FTD) {
13469           assert(!D->isThisDeclarationADefinition() &&
13470                  "More than one definition in redeclaration chain");
13471           if (D->getFriendObjectKind() != Decl::FOK_None)
13472             if (FunctionTemplateDecl *FT =
13473                                        D->getInstantiatedFromMemberTemplate()) {
13474               if (FT->isThisDeclarationADefinition()) {
13475                 Definition = D->getTemplatedDecl();
13476                 break;
13477               }
13478             }
13479         }
13480       }
13481     }
13482 
13483   if (!Definition)
13484     return;
13485 
13486   if (canRedefineFunction(Definition, getLangOpts()))
13487     return;
13488 
13489   // Don't emit an error when this is redefinition of a typo-corrected
13490   // definition.
13491   if (TypoCorrectedFunctionDefinitions.count(Definition))
13492     return;
13493 
13494   // If we don't have a visible definition of the function, and it's inline or
13495   // a template, skip the new definition.
13496   if (SkipBody && !hasVisibleDefinition(Definition) &&
13497       (Definition->getFormalLinkage() == InternalLinkage ||
13498        Definition->isInlined() ||
13499        Definition->getDescribedFunctionTemplate() ||
13500        Definition->getNumTemplateParameterLists())) {
13501     SkipBody->ShouldSkip = true;
13502     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
13503     if (auto *TD = Definition->getDescribedFunctionTemplate())
13504       makeMergedDefinitionVisible(TD);
13505     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
13506     return;
13507   }
13508 
13509   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
13510       Definition->getStorageClass() == SC_Extern)
13511     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
13512         << FD->getDeclName() << getLangOpts().CPlusPlus;
13513   else
13514     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
13515 
13516   Diag(Definition->getLocation(), diag::note_previous_definition);
13517   FD->setInvalidDecl();
13518 }
13519 
13520 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
13521                                    Sema &S) {
13522   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
13523 
13524   LambdaScopeInfo *LSI = S.PushLambdaScope();
13525   LSI->CallOperator = CallOperator;
13526   LSI->Lambda = LambdaClass;
13527   LSI->ReturnType = CallOperator->getReturnType();
13528   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
13529 
13530   if (LCD == LCD_None)
13531     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
13532   else if (LCD == LCD_ByCopy)
13533     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
13534   else if (LCD == LCD_ByRef)
13535     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
13536   DeclarationNameInfo DNI = CallOperator->getNameInfo();
13537 
13538   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
13539   LSI->Mutable = !CallOperator->isConst();
13540 
13541   // Add the captures to the LSI so they can be noted as already
13542   // captured within tryCaptureVar.
13543   auto I = LambdaClass->field_begin();
13544   for (const auto &C : LambdaClass->captures()) {
13545     if (C.capturesVariable()) {
13546       VarDecl *VD = C.getCapturedVar();
13547       if (VD->isInitCapture())
13548         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
13549       QualType CaptureType = VD->getType();
13550       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
13551       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
13552           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
13553           /*EllipsisLoc*/C.isPackExpansion()
13554                          ? C.getEllipsisLoc() : SourceLocation(),
13555           CaptureType, /*Invalid*/false);
13556 
13557     } else if (C.capturesThis()) {
13558       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
13559                           C.getCaptureKind() == LCK_StarThis);
13560     } else {
13561       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
13562                              I->getType());
13563     }
13564     ++I;
13565   }
13566 }
13567 
13568 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
13569                                     SkipBodyInfo *SkipBody) {
13570   if (!D) {
13571     // Parsing the function declaration failed in some way. Push on a fake scope
13572     // anyway so we can try to parse the function body.
13573     PushFunctionScope();
13574     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13575     return D;
13576   }
13577 
13578   FunctionDecl *FD = nullptr;
13579 
13580   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
13581     FD = FunTmpl->getTemplatedDecl();
13582   else
13583     FD = cast<FunctionDecl>(D);
13584 
13585   // Do not push if it is a lambda because one is already pushed when building
13586   // the lambda in ActOnStartOfLambdaDefinition().
13587   if (!isLambdaCallOperator(FD))
13588     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13589 
13590   // Check for defining attributes before the check for redefinition.
13591   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
13592     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
13593     FD->dropAttr<AliasAttr>();
13594     FD->setInvalidDecl();
13595   }
13596   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
13597     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
13598     FD->dropAttr<IFuncAttr>();
13599     FD->setInvalidDecl();
13600   }
13601 
13602   // See if this is a redefinition. If 'will have body' is already set, then
13603   // these checks were already performed when it was set.
13604   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
13605     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
13606 
13607     // If we're skipping the body, we're done. Don't enter the scope.
13608     if (SkipBody && SkipBody->ShouldSkip)
13609       return D;
13610   }
13611 
13612   // Mark this function as "will have a body eventually".  This lets users to
13613   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
13614   // this function.
13615   FD->setWillHaveBody();
13616 
13617   // If we are instantiating a generic lambda call operator, push
13618   // a LambdaScopeInfo onto the function stack.  But use the information
13619   // that's already been calculated (ActOnLambdaExpr) to prime the current
13620   // LambdaScopeInfo.
13621   // When the template operator is being specialized, the LambdaScopeInfo,
13622   // has to be properly restored so that tryCaptureVariable doesn't try
13623   // and capture any new variables. In addition when calculating potential
13624   // captures during transformation of nested lambdas, it is necessary to
13625   // have the LSI properly restored.
13626   if (isGenericLambdaCallOperatorSpecialization(FD)) {
13627     assert(inTemplateInstantiation() &&
13628            "There should be an active template instantiation on the stack "
13629            "when instantiating a generic lambda!");
13630     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
13631   } else {
13632     // Enter a new function scope
13633     PushFunctionScope();
13634   }
13635 
13636   // Builtin functions cannot be defined.
13637   if (unsigned BuiltinID = FD->getBuiltinID()) {
13638     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
13639         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
13640       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
13641       FD->setInvalidDecl();
13642     }
13643   }
13644 
13645   // The return type of a function definition must be complete
13646   // (C99 6.9.1p3, C++ [dcl.fct]p6).
13647   QualType ResultType = FD->getReturnType();
13648   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
13649       !FD->isInvalidDecl() &&
13650       RequireCompleteType(FD->getLocation(), ResultType,
13651                           diag::err_func_def_incomplete_result))
13652     FD->setInvalidDecl();
13653 
13654   if (FnBodyScope)
13655     PushDeclContext(FnBodyScope, FD);
13656 
13657   // Check the validity of our function parameters
13658   CheckParmsForFunctionDef(FD->parameters(),
13659                            /*CheckParameterNames=*/true);
13660 
13661   // Add non-parameter declarations already in the function to the current
13662   // scope.
13663   if (FnBodyScope) {
13664     for (Decl *NPD : FD->decls()) {
13665       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
13666       if (!NonParmDecl)
13667         continue;
13668       assert(!isa<ParmVarDecl>(NonParmDecl) &&
13669              "parameters should not be in newly created FD yet");
13670 
13671       // If the decl has a name, make it accessible in the current scope.
13672       if (NonParmDecl->getDeclName())
13673         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
13674 
13675       // Similarly, dive into enums and fish their constants out, making them
13676       // accessible in this scope.
13677       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
13678         for (auto *EI : ED->enumerators())
13679           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
13680       }
13681     }
13682   }
13683 
13684   // Introduce our parameters into the function scope
13685   for (auto Param : FD->parameters()) {
13686     Param->setOwningFunction(FD);
13687 
13688     // If this has an identifier, add it to the scope stack.
13689     if (Param->getIdentifier() && FnBodyScope) {
13690       CheckShadow(FnBodyScope, Param);
13691 
13692       PushOnScopeChains(Param, FnBodyScope);
13693     }
13694   }
13695 
13696   // Ensure that the function's exception specification is instantiated.
13697   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
13698     ResolveExceptionSpec(D->getLocation(), FPT);
13699 
13700   // dllimport cannot be applied to non-inline function definitions.
13701   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
13702       !FD->isTemplateInstantiation()) {
13703     assert(!FD->hasAttr<DLLExportAttr>());
13704     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
13705     FD->setInvalidDecl();
13706     return D;
13707   }
13708   // We want to attach documentation to original Decl (which might be
13709   // a function template).
13710   ActOnDocumentableDecl(D);
13711   if (getCurLexicalContext()->isObjCContainer() &&
13712       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
13713       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
13714     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
13715 
13716   return D;
13717 }
13718 
13719 /// Given the set of return statements within a function body,
13720 /// compute the variables that are subject to the named return value
13721 /// optimization.
13722 ///
13723 /// Each of the variables that is subject to the named return value
13724 /// optimization will be marked as NRVO variables in the AST, and any
13725 /// return statement that has a marked NRVO variable as its NRVO candidate can
13726 /// use the named return value optimization.
13727 ///
13728 /// This function applies a very simplistic algorithm for NRVO: if every return
13729 /// statement in the scope of a variable has the same NRVO candidate, that
13730 /// candidate is an NRVO variable.
13731 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
13732   ReturnStmt **Returns = Scope->Returns.data();
13733 
13734   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
13735     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
13736       if (!NRVOCandidate->isNRVOVariable())
13737         Returns[I]->setNRVOCandidate(nullptr);
13738     }
13739   }
13740 }
13741 
13742 bool Sema::canDelayFunctionBody(const Declarator &D) {
13743   // We can't delay parsing the body of a constexpr function template (yet).
13744   if (D.getDeclSpec().hasConstexprSpecifier())
13745     return false;
13746 
13747   // We can't delay parsing the body of a function template with a deduced
13748   // return type (yet).
13749   if (D.getDeclSpec().hasAutoTypeSpec()) {
13750     // If the placeholder introduces a non-deduced trailing return type,
13751     // we can still delay parsing it.
13752     if (D.getNumTypeObjects()) {
13753       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
13754       if (Outer.Kind == DeclaratorChunk::Function &&
13755           Outer.Fun.hasTrailingReturnType()) {
13756         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
13757         return Ty.isNull() || !Ty->isUndeducedType();
13758       }
13759     }
13760     return false;
13761   }
13762 
13763   return true;
13764 }
13765 
13766 bool Sema::canSkipFunctionBody(Decl *D) {
13767   // We cannot skip the body of a function (or function template) which is
13768   // constexpr, since we may need to evaluate its body in order to parse the
13769   // rest of the file.
13770   // We cannot skip the body of a function with an undeduced return type,
13771   // because any callers of that function need to know the type.
13772   if (const FunctionDecl *FD = D->getAsFunction()) {
13773     if (FD->isConstexpr())
13774       return false;
13775     // We can't simply call Type::isUndeducedType here, because inside template
13776     // auto can be deduced to a dependent type, which is not considered
13777     // "undeduced".
13778     if (FD->getReturnType()->getContainedDeducedType())
13779       return false;
13780   }
13781   return Consumer.shouldSkipFunctionBody(D);
13782 }
13783 
13784 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
13785   if (!Decl)
13786     return nullptr;
13787   if (FunctionDecl *FD = Decl->getAsFunction())
13788     FD->setHasSkippedBody();
13789   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
13790     MD->setHasSkippedBody();
13791   return Decl;
13792 }
13793 
13794 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
13795   return ActOnFinishFunctionBody(D, BodyArg, false);
13796 }
13797 
13798 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
13799 /// body.
13800 class ExitFunctionBodyRAII {
13801 public:
13802   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
13803   ~ExitFunctionBodyRAII() {
13804     if (!IsLambda)
13805       S.PopExpressionEvaluationContext();
13806   }
13807 
13808 private:
13809   Sema &S;
13810   bool IsLambda = false;
13811 };
13812 
13813 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
13814   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
13815 
13816   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
13817     if (EscapeInfo.count(BD))
13818       return EscapeInfo[BD];
13819 
13820     bool R = false;
13821     const BlockDecl *CurBD = BD;
13822 
13823     do {
13824       R = !CurBD->doesNotEscape();
13825       if (R)
13826         break;
13827       CurBD = CurBD->getParent()->getInnermostBlockDecl();
13828     } while (CurBD);
13829 
13830     return EscapeInfo[BD] = R;
13831   };
13832 
13833   // If the location where 'self' is implicitly retained is inside a escaping
13834   // block, emit a diagnostic.
13835   for (const std::pair<SourceLocation, const BlockDecl *> &P :
13836        S.ImplicitlyRetainedSelfLocs)
13837     if (IsOrNestedInEscapingBlock(P.second))
13838       S.Diag(P.first, diag::warn_implicitly_retains_self)
13839           << FixItHint::CreateInsertion(P.first, "self->");
13840 }
13841 
13842 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
13843                                     bool IsInstantiation) {
13844   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
13845 
13846   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13847   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
13848 
13849   if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
13850     CheckCompletedCoroutineBody(FD, Body);
13851 
13852   // Do not call PopExpressionEvaluationContext() if it is a lambda because one
13853   // is already popped when finishing the lambda in BuildLambdaExpr(). This is
13854   // meant to pop the context added in ActOnStartOfFunctionDef().
13855   ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
13856 
13857   if (FD) {
13858     FD->setBody(Body);
13859     FD->setWillHaveBody(false);
13860 
13861     if (getLangOpts().CPlusPlus14) {
13862       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
13863           FD->getReturnType()->isUndeducedType()) {
13864         // If the function has a deduced result type but contains no 'return'
13865         // statements, the result type as written must be exactly 'auto', and
13866         // the deduced result type is 'void'.
13867         if (!FD->getReturnType()->getAs<AutoType>()) {
13868           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
13869               << FD->getReturnType();
13870           FD->setInvalidDecl();
13871         } else {
13872           // Substitute 'void' for the 'auto' in the type.
13873           TypeLoc ResultType = getReturnTypeLoc(FD);
13874           Context.adjustDeducedFunctionResultType(
13875               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
13876         }
13877       }
13878     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
13879       // In C++11, we don't use 'auto' deduction rules for lambda call
13880       // operators because we don't support return type deduction.
13881       auto *LSI = getCurLambda();
13882       if (LSI->HasImplicitReturnType) {
13883         deduceClosureReturnType(*LSI);
13884 
13885         // C++11 [expr.prim.lambda]p4:
13886         //   [...] if there are no return statements in the compound-statement
13887         //   [the deduced type is] the type void
13888         QualType RetType =
13889             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
13890 
13891         // Update the return type to the deduced type.
13892         const FunctionProtoType *Proto =
13893             FD->getType()->getAs<FunctionProtoType>();
13894         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
13895                                             Proto->getExtProtoInfo()));
13896       }
13897     }
13898 
13899     // If the function implicitly returns zero (like 'main') or is naked,
13900     // don't complain about missing return statements.
13901     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
13902       WP.disableCheckFallThrough();
13903 
13904     // MSVC permits the use of pure specifier (=0) on function definition,
13905     // defined at class scope, warn about this non-standard construct.
13906     if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
13907       Diag(FD->getLocation(), diag::ext_pure_function_definition);
13908 
13909     if (!FD->isInvalidDecl()) {
13910       // Don't diagnose unused parameters of defaulted or deleted functions.
13911       if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
13912         DiagnoseUnusedParameters(FD->parameters());
13913       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
13914                                              FD->getReturnType(), FD);
13915 
13916       // If this is a structor, we need a vtable.
13917       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
13918         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
13919       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
13920         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
13921 
13922       // Try to apply the named return value optimization. We have to check
13923       // if we can do this here because lambdas keep return statements around
13924       // to deduce an implicit return type.
13925       if (FD->getReturnType()->isRecordType() &&
13926           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
13927         computeNRVO(Body, getCurFunction());
13928     }
13929 
13930     // GNU warning -Wmissing-prototypes:
13931     //   Warn if a global function is defined without a previous
13932     //   prototype declaration. This warning is issued even if the
13933     //   definition itself provides a prototype. The aim is to detect
13934     //   global functions that fail to be declared in header files.
13935     const FunctionDecl *PossiblePrototype = nullptr;
13936     if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
13937       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
13938 
13939       if (PossiblePrototype) {
13940         // We found a declaration that is not a prototype,
13941         // but that could be a zero-parameter prototype
13942         if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
13943           TypeLoc TL = TI->getTypeLoc();
13944           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
13945             Diag(PossiblePrototype->getLocation(),
13946                  diag::note_declaration_not_a_prototype)
13947                 << (FD->getNumParams() != 0)
13948                 << (FD->getNumParams() == 0
13949                         ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
13950                         : FixItHint{});
13951         }
13952       } else {
13953         Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13954             << /* function */ 1
13955             << (FD->getStorageClass() == SC_None
13956                     ? FixItHint::CreateInsertion(FD->getTypeSpecStartLoc(),
13957                                                  "static ")
13958                     : FixItHint{});
13959       }
13960 
13961       // GNU warning -Wstrict-prototypes
13962       //   Warn if K&R function is defined without a previous declaration.
13963       //   This warning is issued only if the definition itself does not provide
13964       //   a prototype. Only K&R definitions do not provide a prototype.
13965       //   An empty list in a function declarator that is part of a definition
13966       //   of that function specifies that the function has no parameters
13967       //   (C99 6.7.5.3p14)
13968       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
13969           !LangOpts.CPlusPlus) {
13970         TypeSourceInfo *TI = FD->getTypeSourceInfo();
13971         TypeLoc TL = TI->getTypeLoc();
13972         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
13973         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
13974       }
13975     }
13976 
13977     // Warn on CPUDispatch with an actual body.
13978     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
13979       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
13980         if (!CmpndBody->body_empty())
13981           Diag(CmpndBody->body_front()->getBeginLoc(),
13982                diag::warn_dispatch_body_ignored);
13983 
13984     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13985       const CXXMethodDecl *KeyFunction;
13986       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
13987           MD->isVirtual() &&
13988           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
13989           MD == KeyFunction->getCanonicalDecl()) {
13990         // Update the key-function state if necessary for this ABI.
13991         if (FD->isInlined() &&
13992             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13993           Context.setNonKeyFunction(MD);
13994 
13995           // If the newly-chosen key function is already defined, then we
13996           // need to mark the vtable as used retroactively.
13997           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
13998           const FunctionDecl *Definition;
13999           if (KeyFunction && KeyFunction->isDefined(Definition))
14000             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14001         } else {
14002           // We just defined they key function; mark the vtable as used.
14003           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14004         }
14005       }
14006     }
14007 
14008     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
14009            "Function parsing confused");
14010   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14011     assert(MD == getCurMethodDecl() && "Method parsing confused");
14012     MD->setBody(Body);
14013     if (!MD->isInvalidDecl()) {
14014       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14015                                              MD->getReturnType(), MD);
14016 
14017       if (Body)
14018         computeNRVO(Body, getCurFunction());
14019     }
14020     if (getCurFunction()->ObjCShouldCallSuper) {
14021       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14022           << MD->getSelector().getAsString();
14023       getCurFunction()->ObjCShouldCallSuper = false;
14024     }
14025     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
14026       const ObjCMethodDecl *InitMethod = nullptr;
14027       bool isDesignated =
14028           MD->isDesignatedInitializerForTheInterface(&InitMethod);
14029       assert(isDesignated && InitMethod);
14030       (void)isDesignated;
14031 
14032       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14033         auto IFace = MD->getClassInterface();
14034         if (!IFace)
14035           return false;
14036         auto SuperD = IFace->getSuperClass();
14037         if (!SuperD)
14038           return false;
14039         return SuperD->getIdentifier() ==
14040             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14041       };
14042       // Don't issue this warning for unavailable inits or direct subclasses
14043       // of NSObject.
14044       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14045         Diag(MD->getLocation(),
14046              diag::warn_objc_designated_init_missing_super_call);
14047         Diag(InitMethod->getLocation(),
14048              diag::note_objc_designated_init_marked_here);
14049       }
14050       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
14051     }
14052     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
14053       // Don't issue this warning for unavaialable inits.
14054       if (!MD->isUnavailable())
14055         Diag(MD->getLocation(),
14056              diag::warn_objc_secondary_init_missing_init_call);
14057       getCurFunction()->ObjCWarnForNoInitDelegation = false;
14058     }
14059 
14060     diagnoseImplicitlyRetainedSelf(*this);
14061   } else {
14062     // Parsing the function declaration failed in some way. Pop the fake scope
14063     // we pushed on.
14064     PopFunctionScopeInfo(ActivePolicy, dcl);
14065     return nullptr;
14066   }
14067 
14068   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
14069     DiagnoseUnguardedAvailabilityViolations(dcl);
14070 
14071   assert(!getCurFunction()->ObjCShouldCallSuper &&
14072          "This should only be set for ObjC methods, which should have been "
14073          "handled in the block above.");
14074 
14075   // Verify and clean out per-function state.
14076   if (Body && (!FD || !FD->isDefaulted())) {
14077     // C++ constructors that have function-try-blocks can't have return
14078     // statements in the handlers of that block. (C++ [except.handle]p14)
14079     // Verify this.
14080     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14081       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14082 
14083     // Verify that gotos and switch cases don't jump into scopes illegally.
14084     if (getCurFunction()->NeedsScopeChecking() &&
14085         !PP.isCodeCompletionEnabled())
14086       DiagnoseInvalidJumps(Body);
14087 
14088     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14089       if (!Destructor->getParent()->isDependentType())
14090         CheckDestructor(Destructor);
14091 
14092       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14093                                              Destructor->getParent());
14094     }
14095 
14096     // If any errors have occurred, clear out any temporaries that may have
14097     // been leftover. This ensures that these temporaries won't be picked up for
14098     // deletion in some later function.
14099     if (getDiagnostics().hasErrorOccurred() ||
14100         getDiagnostics().getSuppressAllDiagnostics()) {
14101       DiscardCleanupsInEvaluationContext();
14102     }
14103     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
14104         !isa<FunctionTemplateDecl>(dcl)) {
14105       // Since the body is valid, issue any analysis-based warnings that are
14106       // enabled.
14107       ActivePolicy = &WP;
14108     }
14109 
14110     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14111         !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14112       FD->setInvalidDecl();
14113 
14114     if (FD && FD->hasAttr<NakedAttr>()) {
14115       for (const Stmt *S : Body->children()) {
14116         // Allow local register variables without initializer as they don't
14117         // require prologue.
14118         bool RegisterVariables = false;
14119         if (auto *DS = dyn_cast<DeclStmt>(S)) {
14120           for (const auto *Decl : DS->decls()) {
14121             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14122               RegisterVariables =
14123                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14124               if (!RegisterVariables)
14125                 break;
14126             }
14127           }
14128         }
14129         if (RegisterVariables)
14130           continue;
14131         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14132           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14133           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14134           FD->setInvalidDecl();
14135           break;
14136         }
14137       }
14138     }
14139 
14140     assert(ExprCleanupObjects.size() ==
14141                ExprEvalContexts.back().NumCleanupObjects &&
14142            "Leftover temporaries in function");
14143     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
14144     assert(MaybeODRUseExprs.empty() &&
14145            "Leftover expressions for odr-use checking");
14146   }
14147 
14148   if (!IsInstantiation)
14149     PopDeclContext();
14150 
14151   PopFunctionScopeInfo(ActivePolicy, dcl);
14152   // If any errors have occurred, clear out any temporaries that may have
14153   // been leftover. This ensures that these temporaries won't be picked up for
14154   // deletion in some later function.
14155   if (getDiagnostics().hasErrorOccurred()) {
14156     DiscardCleanupsInEvaluationContext();
14157   }
14158 
14159   return dcl;
14160 }
14161 
14162 /// When we finish delayed parsing of an attribute, we must attach it to the
14163 /// relevant Decl.
14164 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14165                                        ParsedAttributes &Attrs) {
14166   // Always attach attributes to the underlying decl.
14167   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14168     D = TD->getTemplatedDecl();
14169   ProcessDeclAttributeList(S, D, Attrs);
14170 
14171   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14172     if (Method->isStatic())
14173       checkThisInStaticMemberFunctionAttributes(Method);
14174 }
14175 
14176 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14177 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
14178 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14179                                           IdentifierInfo &II, Scope *S) {
14180   // Find the scope in which the identifier is injected and the corresponding
14181   // DeclContext.
14182   // FIXME: C89 does not say what happens if there is no enclosing block scope.
14183   // In that case, we inject the declaration into the translation unit scope
14184   // instead.
14185   Scope *BlockScope = S;
14186   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14187     BlockScope = BlockScope->getParent();
14188 
14189   Scope *ContextScope = BlockScope;
14190   while (!ContextScope->getEntity())
14191     ContextScope = ContextScope->getParent();
14192   ContextRAII SavedContext(*this, ContextScope->getEntity());
14193 
14194   // Before we produce a declaration for an implicitly defined
14195   // function, see whether there was a locally-scoped declaration of
14196   // this name as a function or variable. If so, use that
14197   // (non-visible) declaration, and complain about it.
14198   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14199   if (ExternCPrev) {
14200     // We still need to inject the function into the enclosing block scope so
14201     // that later (non-call) uses can see it.
14202     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14203 
14204     // C89 footnote 38:
14205     //   If in fact it is not defined as having type "function returning int",
14206     //   the behavior is undefined.
14207     if (!isa<FunctionDecl>(ExternCPrev) ||
14208         !Context.typesAreCompatible(
14209             cast<FunctionDecl>(ExternCPrev)->getType(),
14210             Context.getFunctionNoProtoType(Context.IntTy))) {
14211       Diag(Loc, diag::ext_use_out_of_scope_declaration)
14212           << ExternCPrev << !getLangOpts().C99;
14213       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14214       return ExternCPrev;
14215     }
14216   }
14217 
14218   // Extension in C99.  Legal in C90, but warn about it.
14219   unsigned diag_id;
14220   if (II.getName().startswith("__builtin_"))
14221     diag_id = diag::warn_builtin_unknown;
14222   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14223   else if (getLangOpts().OpenCL)
14224     diag_id = diag::err_opencl_implicit_function_decl;
14225   else if (getLangOpts().C99)
14226     diag_id = diag::ext_implicit_function_decl;
14227   else
14228     diag_id = diag::warn_implicit_function_decl;
14229   Diag(Loc, diag_id) << &II;
14230 
14231   // If we found a prior declaration of this function, don't bother building
14232   // another one. We've already pushed that one into scope, so there's nothing
14233   // more to do.
14234   if (ExternCPrev)
14235     return ExternCPrev;
14236 
14237   // Because typo correction is expensive, only do it if the implicit
14238   // function declaration is going to be treated as an error.
14239   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
14240     TypoCorrection Corrected;
14241     DeclFilterCCC<FunctionDecl> CCC{};
14242     if (S && (Corrected =
14243                   CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
14244                               S, nullptr, CCC, CTK_NonError)))
14245       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
14246                    /*ErrorRecovery*/false);
14247   }
14248 
14249   // Set a Declarator for the implicit definition: int foo();
14250   const char *Dummy;
14251   AttributeFactory attrFactory;
14252   DeclSpec DS(attrFactory);
14253   unsigned DiagID;
14254   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
14255                                   Context.getPrintingPolicy());
14256   (void)Error; // Silence warning.
14257   assert(!Error && "Error setting up implicit decl!");
14258   SourceLocation NoLoc;
14259   Declarator D(DS, DeclaratorContext::BlockContext);
14260   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
14261                                              /*IsAmbiguous=*/false,
14262                                              /*LParenLoc=*/NoLoc,
14263                                              /*Params=*/nullptr,
14264                                              /*NumParams=*/0,
14265                                              /*EllipsisLoc=*/NoLoc,
14266                                              /*RParenLoc=*/NoLoc,
14267                                              /*RefQualifierIsLvalueRef=*/true,
14268                                              /*RefQualifierLoc=*/NoLoc,
14269                                              /*MutableLoc=*/NoLoc, EST_None,
14270                                              /*ESpecRange=*/SourceRange(),
14271                                              /*Exceptions=*/nullptr,
14272                                              /*ExceptionRanges=*/nullptr,
14273                                              /*NumExceptions=*/0,
14274                                              /*NoexceptExpr=*/nullptr,
14275                                              /*ExceptionSpecTokens=*/nullptr,
14276                                              /*DeclsInPrototype=*/None, Loc,
14277                                              Loc, D),
14278                 std::move(DS.getAttributes()), SourceLocation());
14279   D.SetIdentifier(&II, Loc);
14280 
14281   // Insert this function into the enclosing block scope.
14282   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
14283   FD->setImplicit();
14284 
14285   AddKnownFunctionAttributes(FD);
14286 
14287   return FD;
14288 }
14289 
14290 /// Adds any function attributes that we know a priori based on
14291 /// the declaration of this function.
14292 ///
14293 /// These attributes can apply both to implicitly-declared builtins
14294 /// (like __builtin___printf_chk) or to library-declared functions
14295 /// like NSLog or printf.
14296 ///
14297 /// We need to check for duplicate attributes both here and where user-written
14298 /// attributes are applied to declarations.
14299 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
14300   if (FD->isInvalidDecl())
14301     return;
14302 
14303   // If this is a built-in function, map its builtin attributes to
14304   // actual attributes.
14305   if (unsigned BuiltinID = FD->getBuiltinID()) {
14306     // Handle printf-formatting attributes.
14307     unsigned FormatIdx;
14308     bool HasVAListArg;
14309     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
14310       if (!FD->hasAttr<FormatAttr>()) {
14311         const char *fmt = "printf";
14312         unsigned int NumParams = FD->getNumParams();
14313         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
14314             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
14315           fmt = "NSString";
14316         FD->addAttr(FormatAttr::CreateImplicit(Context,
14317                                                &Context.Idents.get(fmt),
14318                                                FormatIdx+1,
14319                                                HasVAListArg ? 0 : FormatIdx+2,
14320                                                FD->getLocation()));
14321       }
14322     }
14323     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
14324                                              HasVAListArg)) {
14325      if (!FD->hasAttr<FormatAttr>())
14326        FD->addAttr(FormatAttr::CreateImplicit(Context,
14327                                               &Context.Idents.get("scanf"),
14328                                               FormatIdx+1,
14329                                               HasVAListArg ? 0 : FormatIdx+2,
14330                                               FD->getLocation()));
14331     }
14332 
14333     // Handle automatically recognized callbacks.
14334     SmallVector<int, 4> Encoding;
14335     if (!FD->hasAttr<CallbackAttr>() &&
14336         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
14337       FD->addAttr(CallbackAttr::CreateImplicit(
14338           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
14339 
14340     // Mark const if we don't care about errno and that is the only thing
14341     // preventing the function from being const. This allows IRgen to use LLVM
14342     // intrinsics for such functions.
14343     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
14344         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
14345       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14346 
14347     // We make "fma" on some platforms const because we know it does not set
14348     // errno in those environments even though it could set errno based on the
14349     // C standard.
14350     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
14351     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
14352         !FD->hasAttr<ConstAttr>()) {
14353       switch (BuiltinID) {
14354       case Builtin::BI__builtin_fma:
14355       case Builtin::BI__builtin_fmaf:
14356       case Builtin::BI__builtin_fmal:
14357       case Builtin::BIfma:
14358       case Builtin::BIfmaf:
14359       case Builtin::BIfmal:
14360         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14361         break;
14362       default:
14363         break;
14364       }
14365     }
14366 
14367     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
14368         !FD->hasAttr<ReturnsTwiceAttr>())
14369       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
14370                                          FD->getLocation()));
14371     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
14372       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14373     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
14374       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
14375     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
14376       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14377     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
14378         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
14379       // Add the appropriate attribute, depending on the CUDA compilation mode
14380       // and which target the builtin belongs to. For example, during host
14381       // compilation, aux builtins are __device__, while the rest are __host__.
14382       if (getLangOpts().CUDAIsDevice !=
14383           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
14384         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
14385       else
14386         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
14387     }
14388   }
14389 
14390   // If C++ exceptions are enabled but we are told extern "C" functions cannot
14391   // throw, add an implicit nothrow attribute to any extern "C" function we come
14392   // across.
14393   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
14394       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
14395     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
14396     if (!FPT || FPT->getExceptionSpecType() == EST_None)
14397       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14398   }
14399 
14400   IdentifierInfo *Name = FD->getIdentifier();
14401   if (!Name)
14402     return;
14403   if ((!getLangOpts().CPlusPlus &&
14404        FD->getDeclContext()->isTranslationUnit()) ||
14405       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
14406        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
14407        LinkageSpecDecl::lang_c)) {
14408     // Okay: this could be a libc/libm/Objective-C function we know
14409     // about.
14410   } else
14411     return;
14412 
14413   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
14414     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
14415     // target-specific builtins, perhaps?
14416     if (!FD->hasAttr<FormatAttr>())
14417       FD->addAttr(FormatAttr::CreateImplicit(Context,
14418                                              &Context.Idents.get("printf"), 2,
14419                                              Name->isStr("vasprintf") ? 0 : 3,
14420                                              FD->getLocation()));
14421   }
14422 
14423   if (Name->isStr("__CFStringMakeConstantString")) {
14424     // We already have a __builtin___CFStringMakeConstantString,
14425     // but builds that use -fno-constant-cfstrings don't go through that.
14426     if (!FD->hasAttr<FormatArgAttr>())
14427       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
14428                                                 FD->getLocation()));
14429   }
14430 }
14431 
14432 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
14433                                     TypeSourceInfo *TInfo) {
14434   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
14435   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
14436 
14437   if (!TInfo) {
14438     assert(D.isInvalidType() && "no declarator info for valid type");
14439     TInfo = Context.getTrivialTypeSourceInfo(T);
14440   }
14441 
14442   // Scope manipulation handled by caller.
14443   TypedefDecl *NewTD =
14444       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
14445                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
14446 
14447   // Bail out immediately if we have an invalid declaration.
14448   if (D.isInvalidType()) {
14449     NewTD->setInvalidDecl();
14450     return NewTD;
14451   }
14452 
14453   if (D.getDeclSpec().isModulePrivateSpecified()) {
14454     if (CurContext->isFunctionOrMethod())
14455       Diag(NewTD->getLocation(), diag::err_module_private_local)
14456         << 2 << NewTD->getDeclName()
14457         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14458         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
14459     else
14460       NewTD->setModulePrivate();
14461   }
14462 
14463   // C++ [dcl.typedef]p8:
14464   //   If the typedef declaration defines an unnamed class (or
14465   //   enum), the first typedef-name declared by the declaration
14466   //   to be that class type (or enum type) is used to denote the
14467   //   class type (or enum type) for linkage purposes only.
14468   // We need to check whether the type was declared in the declaration.
14469   switch (D.getDeclSpec().getTypeSpecType()) {
14470   case TST_enum:
14471   case TST_struct:
14472   case TST_interface:
14473   case TST_union:
14474   case TST_class: {
14475     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
14476     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
14477     break;
14478   }
14479 
14480   default:
14481     break;
14482   }
14483 
14484   return NewTD;
14485 }
14486 
14487 /// Check that this is a valid underlying type for an enum declaration.
14488 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
14489   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
14490   QualType T = TI->getType();
14491 
14492   if (T->isDependentType())
14493     return false;
14494 
14495   if (const BuiltinType *BT = T->getAs<BuiltinType>())
14496     if (BT->isInteger())
14497       return false;
14498 
14499   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
14500   return true;
14501 }
14502 
14503 /// Check whether this is a valid redeclaration of a previous enumeration.
14504 /// \return true if the redeclaration was invalid.
14505 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
14506                                   QualType EnumUnderlyingTy, bool IsFixed,
14507                                   const EnumDecl *Prev) {
14508   if (IsScoped != Prev->isScoped()) {
14509     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
14510       << Prev->isScoped();
14511     Diag(Prev->getLocation(), diag::note_previous_declaration);
14512     return true;
14513   }
14514 
14515   if (IsFixed && Prev->isFixed()) {
14516     if (!EnumUnderlyingTy->isDependentType() &&
14517         !Prev->getIntegerType()->isDependentType() &&
14518         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
14519                                         Prev->getIntegerType())) {
14520       // TODO: Highlight the underlying type of the redeclaration.
14521       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
14522         << EnumUnderlyingTy << Prev->getIntegerType();
14523       Diag(Prev->getLocation(), diag::note_previous_declaration)
14524           << Prev->getIntegerTypeRange();
14525       return true;
14526     }
14527   } else if (IsFixed != Prev->isFixed()) {
14528     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
14529       << Prev->isFixed();
14530     Diag(Prev->getLocation(), diag::note_previous_declaration);
14531     return true;
14532   }
14533 
14534   return false;
14535 }
14536 
14537 /// Get diagnostic %select index for tag kind for
14538 /// redeclaration diagnostic message.
14539 /// WARNING: Indexes apply to particular diagnostics only!
14540 ///
14541 /// \returns diagnostic %select index.
14542 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
14543   switch (Tag) {
14544   case TTK_Struct: return 0;
14545   case TTK_Interface: return 1;
14546   case TTK_Class:  return 2;
14547   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
14548   }
14549 }
14550 
14551 /// Determine if tag kind is a class-key compatible with
14552 /// class for redeclaration (class, struct, or __interface).
14553 ///
14554 /// \returns true iff the tag kind is compatible.
14555 static bool isClassCompatTagKind(TagTypeKind Tag)
14556 {
14557   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
14558 }
14559 
14560 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
14561                                              TagTypeKind TTK) {
14562   if (isa<TypedefDecl>(PrevDecl))
14563     return NTK_Typedef;
14564   else if (isa<TypeAliasDecl>(PrevDecl))
14565     return NTK_TypeAlias;
14566   else if (isa<ClassTemplateDecl>(PrevDecl))
14567     return NTK_Template;
14568   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
14569     return NTK_TypeAliasTemplate;
14570   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
14571     return NTK_TemplateTemplateArgument;
14572   switch (TTK) {
14573   case TTK_Struct:
14574   case TTK_Interface:
14575   case TTK_Class:
14576     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
14577   case TTK_Union:
14578     return NTK_NonUnion;
14579   case TTK_Enum:
14580     return NTK_NonEnum;
14581   }
14582   llvm_unreachable("invalid TTK");
14583 }
14584 
14585 /// Determine whether a tag with a given kind is acceptable
14586 /// as a redeclaration of the given tag declaration.
14587 ///
14588 /// \returns true if the new tag kind is acceptable, false otherwise.
14589 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
14590                                         TagTypeKind NewTag, bool isDefinition,
14591                                         SourceLocation NewTagLoc,
14592                                         const IdentifierInfo *Name) {
14593   // C++ [dcl.type.elab]p3:
14594   //   The class-key or enum keyword present in the
14595   //   elaborated-type-specifier shall agree in kind with the
14596   //   declaration to which the name in the elaborated-type-specifier
14597   //   refers. This rule also applies to the form of
14598   //   elaborated-type-specifier that declares a class-name or
14599   //   friend class since it can be construed as referring to the
14600   //   definition of the class. Thus, in any
14601   //   elaborated-type-specifier, the enum keyword shall be used to
14602   //   refer to an enumeration (7.2), the union class-key shall be
14603   //   used to refer to a union (clause 9), and either the class or
14604   //   struct class-key shall be used to refer to a class (clause 9)
14605   //   declared using the class or struct class-key.
14606   TagTypeKind OldTag = Previous->getTagKind();
14607   if (OldTag != NewTag &&
14608       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
14609     return false;
14610 
14611   // Tags are compatible, but we might still want to warn on mismatched tags.
14612   // Non-class tags can't be mismatched at this point.
14613   if (!isClassCompatTagKind(NewTag))
14614     return true;
14615 
14616   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
14617   // by our warning analysis. We don't want to warn about mismatches with (eg)
14618   // declarations in system headers that are designed to be specialized, but if
14619   // a user asks us to warn, we should warn if their code contains mismatched
14620   // declarations.
14621   auto IsIgnoredLoc = [&](SourceLocation Loc) {
14622     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
14623                                       Loc);
14624   };
14625   if (IsIgnoredLoc(NewTagLoc))
14626     return true;
14627 
14628   auto IsIgnored = [&](const TagDecl *Tag) {
14629     return IsIgnoredLoc(Tag->getLocation());
14630   };
14631   while (IsIgnored(Previous)) {
14632     Previous = Previous->getPreviousDecl();
14633     if (!Previous)
14634       return true;
14635     OldTag = Previous->getTagKind();
14636   }
14637 
14638   bool isTemplate = false;
14639   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
14640     isTemplate = Record->getDescribedClassTemplate();
14641 
14642   if (inTemplateInstantiation()) {
14643     if (OldTag != NewTag) {
14644       // In a template instantiation, do not offer fix-its for tag mismatches
14645       // since they usually mess up the template instead of fixing the problem.
14646       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14647         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14648         << getRedeclDiagFromTagKind(OldTag);
14649       // FIXME: Note previous location?
14650     }
14651     return true;
14652   }
14653 
14654   if (isDefinition) {
14655     // On definitions, check all previous tags and issue a fix-it for each
14656     // one that doesn't match the current tag.
14657     if (Previous->getDefinition()) {
14658       // Don't suggest fix-its for redefinitions.
14659       return true;
14660     }
14661 
14662     bool previousMismatch = false;
14663     for (const TagDecl *I : Previous->redecls()) {
14664       if (I->getTagKind() != NewTag) {
14665         // Ignore previous declarations for which the warning was disabled.
14666         if (IsIgnored(I))
14667           continue;
14668 
14669         if (!previousMismatch) {
14670           previousMismatch = true;
14671           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
14672             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14673             << getRedeclDiagFromTagKind(I->getTagKind());
14674         }
14675         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
14676           << getRedeclDiagFromTagKind(NewTag)
14677           << FixItHint::CreateReplacement(I->getInnerLocStart(),
14678                TypeWithKeyword::getTagTypeKindName(NewTag));
14679       }
14680     }
14681     return true;
14682   }
14683 
14684   // Identify the prevailing tag kind: this is the kind of the definition (if
14685   // there is a non-ignored definition), or otherwise the kind of the prior
14686   // (non-ignored) declaration.
14687   const TagDecl *PrevDef = Previous->getDefinition();
14688   if (PrevDef && IsIgnored(PrevDef))
14689     PrevDef = nullptr;
14690   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
14691   if (Redecl->getTagKind() != NewTag) {
14692     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14693       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14694       << getRedeclDiagFromTagKind(OldTag);
14695     Diag(Redecl->getLocation(), diag::note_previous_use);
14696 
14697     // If there is a previous definition, suggest a fix-it.
14698     if (PrevDef) {
14699       Diag(NewTagLoc, diag::note_struct_class_suggestion)
14700         << getRedeclDiagFromTagKind(Redecl->getTagKind())
14701         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
14702              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
14703     }
14704   }
14705 
14706   return true;
14707 }
14708 
14709 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
14710 /// from an outer enclosing namespace or file scope inside a friend declaration.
14711 /// This should provide the commented out code in the following snippet:
14712 ///   namespace N {
14713 ///     struct X;
14714 ///     namespace M {
14715 ///       struct Y { friend struct /*N::*/ X; };
14716 ///     }
14717 ///   }
14718 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
14719                                          SourceLocation NameLoc) {
14720   // While the decl is in a namespace, do repeated lookup of that name and see
14721   // if we get the same namespace back.  If we do not, continue until
14722   // translation unit scope, at which point we have a fully qualified NNS.
14723   SmallVector<IdentifierInfo *, 4> Namespaces;
14724   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14725   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
14726     // This tag should be declared in a namespace, which can only be enclosed by
14727     // other namespaces.  Bail if there's an anonymous namespace in the chain.
14728     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
14729     if (!Namespace || Namespace->isAnonymousNamespace())
14730       return FixItHint();
14731     IdentifierInfo *II = Namespace->getIdentifier();
14732     Namespaces.push_back(II);
14733     NamedDecl *Lookup = SemaRef.LookupSingleName(
14734         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
14735     if (Lookup == Namespace)
14736       break;
14737   }
14738 
14739   // Once we have all the namespaces, reverse them to go outermost first, and
14740   // build an NNS.
14741   SmallString<64> Insertion;
14742   llvm::raw_svector_ostream OS(Insertion);
14743   if (DC->isTranslationUnit())
14744     OS << "::";
14745   std::reverse(Namespaces.begin(), Namespaces.end());
14746   for (auto *II : Namespaces)
14747     OS << II->getName() << "::";
14748   return FixItHint::CreateInsertion(NameLoc, Insertion);
14749 }
14750 
14751 /// Determine whether a tag originally declared in context \p OldDC can
14752 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
14753 /// found a declaration in \p OldDC as a previous decl, perhaps through a
14754 /// using-declaration).
14755 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
14756                                          DeclContext *NewDC) {
14757   OldDC = OldDC->getRedeclContext();
14758   NewDC = NewDC->getRedeclContext();
14759 
14760   if (OldDC->Equals(NewDC))
14761     return true;
14762 
14763   // In MSVC mode, we allow a redeclaration if the contexts are related (either
14764   // encloses the other).
14765   if (S.getLangOpts().MSVCCompat &&
14766       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
14767     return true;
14768 
14769   return false;
14770 }
14771 
14772 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
14773 /// former case, Name will be non-null.  In the later case, Name will be null.
14774 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
14775 /// reference/declaration/definition of a tag.
14776 ///
14777 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
14778 /// trailing-type-specifier) other than one in an alias-declaration.
14779 ///
14780 /// \param SkipBody If non-null, will be set to indicate if the caller should
14781 /// skip the definition of this tag and treat it as if it were a declaration.
14782 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
14783                      SourceLocation KWLoc, CXXScopeSpec &SS,
14784                      IdentifierInfo *Name, SourceLocation NameLoc,
14785                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
14786                      SourceLocation ModulePrivateLoc,
14787                      MultiTemplateParamsArg TemplateParameterLists,
14788                      bool &OwnedDecl, bool &IsDependent,
14789                      SourceLocation ScopedEnumKWLoc,
14790                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
14791                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
14792                      SkipBodyInfo *SkipBody) {
14793   // If this is not a definition, it must have a name.
14794   IdentifierInfo *OrigName = Name;
14795   assert((Name != nullptr || TUK == TUK_Definition) &&
14796          "Nameless record must be a definition!");
14797   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
14798 
14799   OwnedDecl = false;
14800   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14801   bool ScopedEnum = ScopedEnumKWLoc.isValid();
14802 
14803   // FIXME: Check member specializations more carefully.
14804   bool isMemberSpecialization = false;
14805   bool Invalid = false;
14806 
14807   // We only need to do this matching if we have template parameters
14808   // or a scope specifier, which also conveniently avoids this work
14809   // for non-C++ cases.
14810   if (TemplateParameterLists.size() > 0 ||
14811       (SS.isNotEmpty() && TUK != TUK_Reference)) {
14812     if (TemplateParameterList *TemplateParams =
14813             MatchTemplateParametersToScopeSpecifier(
14814                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
14815                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
14816       if (Kind == TTK_Enum) {
14817         Diag(KWLoc, diag::err_enum_template);
14818         return nullptr;
14819       }
14820 
14821       if (TemplateParams->size() > 0) {
14822         // This is a declaration or definition of a class template (which may
14823         // be a member of another template).
14824 
14825         if (Invalid)
14826           return nullptr;
14827 
14828         OwnedDecl = false;
14829         DeclResult Result = CheckClassTemplate(
14830             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
14831             AS, ModulePrivateLoc,
14832             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
14833             TemplateParameterLists.data(), SkipBody);
14834         return Result.get();
14835       } else {
14836         // The "template<>" header is extraneous.
14837         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14838           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14839         isMemberSpecialization = true;
14840       }
14841     }
14842   }
14843 
14844   // Figure out the underlying type if this a enum declaration. We need to do
14845   // this early, because it's needed to detect if this is an incompatible
14846   // redeclaration.
14847   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
14848   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
14849 
14850   if (Kind == TTK_Enum) {
14851     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
14852       // No underlying type explicitly specified, or we failed to parse the
14853       // type, default to int.
14854       EnumUnderlying = Context.IntTy.getTypePtr();
14855     } else if (UnderlyingType.get()) {
14856       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
14857       // integral type; any cv-qualification is ignored.
14858       TypeSourceInfo *TI = nullptr;
14859       GetTypeFromParser(UnderlyingType.get(), &TI);
14860       EnumUnderlying = TI;
14861 
14862       if (CheckEnumUnderlyingType(TI))
14863         // Recover by falling back to int.
14864         EnumUnderlying = Context.IntTy.getTypePtr();
14865 
14866       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
14867                                           UPPC_FixedUnderlyingType))
14868         EnumUnderlying = Context.IntTy.getTypePtr();
14869 
14870     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
14871       // For MSVC ABI compatibility, unfixed enums must use an underlying type
14872       // of 'int'. However, if this is an unfixed forward declaration, don't set
14873       // the underlying type unless the user enables -fms-compatibility. This
14874       // makes unfixed forward declared enums incomplete and is more conforming.
14875       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
14876         EnumUnderlying = Context.IntTy.getTypePtr();
14877     }
14878   }
14879 
14880   DeclContext *SearchDC = CurContext;
14881   DeclContext *DC = CurContext;
14882   bool isStdBadAlloc = false;
14883   bool isStdAlignValT = false;
14884 
14885   RedeclarationKind Redecl = forRedeclarationInCurContext();
14886   if (TUK == TUK_Friend || TUK == TUK_Reference)
14887     Redecl = NotForRedeclaration;
14888 
14889   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
14890   /// implemented asks for structural equivalence checking, the returned decl
14891   /// here is passed back to the parser, allowing the tag body to be parsed.
14892   auto createTagFromNewDecl = [&]() -> TagDecl * {
14893     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
14894     // If there is an identifier, use the location of the identifier as the
14895     // location of the decl, otherwise use the location of the struct/union
14896     // keyword.
14897     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14898     TagDecl *New = nullptr;
14899 
14900     if (Kind == TTK_Enum) {
14901       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
14902                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
14903       // If this is an undefined enum, bail.
14904       if (TUK != TUK_Definition && !Invalid)
14905         return nullptr;
14906       if (EnumUnderlying) {
14907         EnumDecl *ED = cast<EnumDecl>(New);
14908         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
14909           ED->setIntegerTypeSourceInfo(TI);
14910         else
14911           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
14912         ED->setPromotionType(ED->getIntegerType());
14913       }
14914     } else { // struct/union
14915       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14916                                nullptr);
14917     }
14918 
14919     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14920       // Add alignment attributes if necessary; these attributes are checked
14921       // when the ASTContext lays out the structure.
14922       //
14923       // It is important for implementing the correct semantics that this
14924       // happen here (in ActOnTag). The #pragma pack stack is
14925       // maintained as a result of parser callbacks which can occur at
14926       // many points during the parsing of a struct declaration (because
14927       // the #pragma tokens are effectively skipped over during the
14928       // parsing of the struct).
14929       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
14930         AddAlignmentAttributesForRecord(RD);
14931         AddMsStructLayoutForRecord(RD);
14932       }
14933     }
14934     New->setLexicalDeclContext(CurContext);
14935     return New;
14936   };
14937 
14938   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
14939   if (Name && SS.isNotEmpty()) {
14940     // We have a nested-name tag ('struct foo::bar').
14941 
14942     // Check for invalid 'foo::'.
14943     if (SS.isInvalid()) {
14944       Name = nullptr;
14945       goto CreateNewDecl;
14946     }
14947 
14948     // If this is a friend or a reference to a class in a dependent
14949     // context, don't try to make a decl for it.
14950     if (TUK == TUK_Friend || TUK == TUK_Reference) {
14951       DC = computeDeclContext(SS, false);
14952       if (!DC) {
14953         IsDependent = true;
14954         return nullptr;
14955       }
14956     } else {
14957       DC = computeDeclContext(SS, true);
14958       if (!DC) {
14959         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
14960           << SS.getRange();
14961         return nullptr;
14962       }
14963     }
14964 
14965     if (RequireCompleteDeclContext(SS, DC))
14966       return nullptr;
14967 
14968     SearchDC = DC;
14969     // Look-up name inside 'foo::'.
14970     LookupQualifiedName(Previous, DC);
14971 
14972     if (Previous.isAmbiguous())
14973       return nullptr;
14974 
14975     if (Previous.empty()) {
14976       // Name lookup did not find anything. However, if the
14977       // nested-name-specifier refers to the current instantiation,
14978       // and that current instantiation has any dependent base
14979       // classes, we might find something at instantiation time: treat
14980       // this as a dependent elaborated-type-specifier.
14981       // But this only makes any sense for reference-like lookups.
14982       if (Previous.wasNotFoundInCurrentInstantiation() &&
14983           (TUK == TUK_Reference || TUK == TUK_Friend)) {
14984         IsDependent = true;
14985         return nullptr;
14986       }
14987 
14988       // A tag 'foo::bar' must already exist.
14989       Diag(NameLoc, diag::err_not_tag_in_scope)
14990         << Kind << Name << DC << SS.getRange();
14991       Name = nullptr;
14992       Invalid = true;
14993       goto CreateNewDecl;
14994     }
14995   } else if (Name) {
14996     // C++14 [class.mem]p14:
14997     //   If T is the name of a class, then each of the following shall have a
14998     //   name different from T:
14999     //    -- every member of class T that is itself a type
15000     if (TUK != TUK_Reference && TUK != TUK_Friend &&
15001         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15002       return nullptr;
15003 
15004     // If this is a named struct, check to see if there was a previous forward
15005     // declaration or definition.
15006     // FIXME: We're looking into outer scopes here, even when we
15007     // shouldn't be. Doing so can result in ambiguities that we
15008     // shouldn't be diagnosing.
15009     LookupName(Previous, S);
15010 
15011     // When declaring or defining a tag, ignore ambiguities introduced
15012     // by types using'ed into this scope.
15013     if (Previous.isAmbiguous() &&
15014         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
15015       LookupResult::Filter F = Previous.makeFilter();
15016       while (F.hasNext()) {
15017         NamedDecl *ND = F.next();
15018         if (!ND->getDeclContext()->getRedeclContext()->Equals(
15019                 SearchDC->getRedeclContext()))
15020           F.erase();
15021       }
15022       F.done();
15023     }
15024 
15025     // C++11 [namespace.memdef]p3:
15026     //   If the name in a friend declaration is neither qualified nor
15027     //   a template-id and the declaration is a function or an
15028     //   elaborated-type-specifier, the lookup to determine whether
15029     //   the entity has been previously declared shall not consider
15030     //   any scopes outside the innermost enclosing namespace.
15031     //
15032     // MSVC doesn't implement the above rule for types, so a friend tag
15033     // declaration may be a redeclaration of a type declared in an enclosing
15034     // scope.  They do implement this rule for friend functions.
15035     //
15036     // Does it matter that this should be by scope instead of by
15037     // semantic context?
15038     if (!Previous.empty() && TUK == TUK_Friend) {
15039       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
15040       LookupResult::Filter F = Previous.makeFilter();
15041       bool FriendSawTagOutsideEnclosingNamespace = false;
15042       while (F.hasNext()) {
15043         NamedDecl *ND = F.next();
15044         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15045         if (DC->isFileContext() &&
15046             !EnclosingNS->Encloses(ND->getDeclContext())) {
15047           if (getLangOpts().MSVCCompat)
15048             FriendSawTagOutsideEnclosingNamespace = true;
15049           else
15050             F.erase();
15051         }
15052       }
15053       F.done();
15054 
15055       // Diagnose this MSVC extension in the easy case where lookup would have
15056       // unambiguously found something outside the enclosing namespace.
15057       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
15058         NamedDecl *ND = Previous.getFoundDecl();
15059         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
15060             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
15061       }
15062     }
15063 
15064     // Note:  there used to be some attempt at recovery here.
15065     if (Previous.isAmbiguous())
15066       return nullptr;
15067 
15068     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
15069       // FIXME: This makes sure that we ignore the contexts associated
15070       // with C structs, unions, and enums when looking for a matching
15071       // tag declaration or definition. See the similar lookup tweak
15072       // in Sema::LookupName; is there a better way to deal with this?
15073       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
15074         SearchDC = SearchDC->getParent();
15075     }
15076   }
15077 
15078   if (Previous.isSingleResult() &&
15079       Previous.getFoundDecl()->isTemplateParameter()) {
15080     // Maybe we will complain about the shadowed template parameter.
15081     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
15082     // Just pretend that we didn't see the previous declaration.
15083     Previous.clear();
15084   }
15085 
15086   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
15087       DC->Equals(getStdNamespace())) {
15088     if (Name->isStr("bad_alloc")) {
15089       // This is a declaration of or a reference to "std::bad_alloc".
15090       isStdBadAlloc = true;
15091 
15092       // If std::bad_alloc has been implicitly declared (but made invisible to
15093       // name lookup), fill in this implicit declaration as the previous
15094       // declaration, so that the declarations get chained appropriately.
15095       if (Previous.empty() && StdBadAlloc)
15096         Previous.addDecl(getStdBadAlloc());
15097     } else if (Name->isStr("align_val_t")) {
15098       isStdAlignValT = true;
15099       if (Previous.empty() && StdAlignValT)
15100         Previous.addDecl(getStdAlignValT());
15101     }
15102   }
15103 
15104   // If we didn't find a previous declaration, and this is a reference
15105   // (or friend reference), move to the correct scope.  In C++, we
15106   // also need to do a redeclaration lookup there, just in case
15107   // there's a shadow friend decl.
15108   if (Name && Previous.empty() &&
15109       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
15110     if (Invalid) goto CreateNewDecl;
15111     assert(SS.isEmpty());
15112 
15113     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
15114       // C++ [basic.scope.pdecl]p5:
15115       //   -- for an elaborated-type-specifier of the form
15116       //
15117       //          class-key identifier
15118       //
15119       //      if the elaborated-type-specifier is used in the
15120       //      decl-specifier-seq or parameter-declaration-clause of a
15121       //      function defined in namespace scope, the identifier is
15122       //      declared as a class-name in the namespace that contains
15123       //      the declaration; otherwise, except as a friend
15124       //      declaration, the identifier is declared in the smallest
15125       //      non-class, non-function-prototype scope that contains the
15126       //      declaration.
15127       //
15128       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
15129       // C structs and unions.
15130       //
15131       // It is an error in C++ to declare (rather than define) an enum
15132       // type, including via an elaborated type specifier.  We'll
15133       // diagnose that later; for now, declare the enum in the same
15134       // scope as we would have picked for any other tag type.
15135       //
15136       // GNU C also supports this behavior as part of its incomplete
15137       // enum types extension, while GNU C++ does not.
15138       //
15139       // Find the context where we'll be declaring the tag.
15140       // FIXME: We would like to maintain the current DeclContext as the
15141       // lexical context,
15142       SearchDC = getTagInjectionContext(SearchDC);
15143 
15144       // Find the scope where we'll be declaring the tag.
15145       S = getTagInjectionScope(S, getLangOpts());
15146     } else {
15147       assert(TUK == TUK_Friend);
15148       // C++ [namespace.memdef]p3:
15149       //   If a friend declaration in a non-local class first declares a
15150       //   class or function, the friend class or function is a member of
15151       //   the innermost enclosing namespace.
15152       SearchDC = SearchDC->getEnclosingNamespaceContext();
15153     }
15154 
15155     // In C++, we need to do a redeclaration lookup to properly
15156     // diagnose some problems.
15157     // FIXME: redeclaration lookup is also used (with and without C++) to find a
15158     // hidden declaration so that we don't get ambiguity errors when using a
15159     // type declared by an elaborated-type-specifier.  In C that is not correct
15160     // and we should instead merge compatible types found by lookup.
15161     if (getLangOpts().CPlusPlus) {
15162       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15163       LookupQualifiedName(Previous, SearchDC);
15164     } else {
15165       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15166       LookupName(Previous, S);
15167     }
15168   }
15169 
15170   // If we have a known previous declaration to use, then use it.
15171   if (Previous.empty() && SkipBody && SkipBody->Previous)
15172     Previous.addDecl(SkipBody->Previous);
15173 
15174   if (!Previous.empty()) {
15175     NamedDecl *PrevDecl = Previous.getFoundDecl();
15176     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
15177 
15178     // It's okay to have a tag decl in the same scope as a typedef
15179     // which hides a tag decl in the same scope.  Finding this
15180     // insanity with a redeclaration lookup can only actually happen
15181     // in C++.
15182     //
15183     // This is also okay for elaborated-type-specifiers, which is
15184     // technically forbidden by the current standard but which is
15185     // okay according to the likely resolution of an open issue;
15186     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
15187     if (getLangOpts().CPlusPlus) {
15188       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15189         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
15190           TagDecl *Tag = TT->getDecl();
15191           if (Tag->getDeclName() == Name &&
15192               Tag->getDeclContext()->getRedeclContext()
15193                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
15194             PrevDecl = Tag;
15195             Previous.clear();
15196             Previous.addDecl(Tag);
15197             Previous.resolveKind();
15198           }
15199         }
15200       }
15201     }
15202 
15203     // If this is a redeclaration of a using shadow declaration, it must
15204     // declare a tag in the same context. In MSVC mode, we allow a
15205     // redefinition if either context is within the other.
15206     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
15207       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
15208       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
15209           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
15210           !(OldTag && isAcceptableTagRedeclContext(
15211                           *this, OldTag->getDeclContext(), SearchDC))) {
15212         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
15213         Diag(Shadow->getTargetDecl()->getLocation(),
15214              diag::note_using_decl_target);
15215         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
15216             << 0;
15217         // Recover by ignoring the old declaration.
15218         Previous.clear();
15219         goto CreateNewDecl;
15220       }
15221     }
15222 
15223     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
15224       // If this is a use of a previous tag, or if the tag is already declared
15225       // in the same scope (so that the definition/declaration completes or
15226       // rementions the tag), reuse the decl.
15227       if (TUK == TUK_Reference || TUK == TUK_Friend ||
15228           isDeclInScope(DirectPrevDecl, SearchDC, S,
15229                         SS.isNotEmpty() || isMemberSpecialization)) {
15230         // Make sure that this wasn't declared as an enum and now used as a
15231         // struct or something similar.
15232         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
15233                                           TUK == TUK_Definition, KWLoc,
15234                                           Name)) {
15235           bool SafeToContinue
15236             = (PrevTagDecl->getTagKind() != TTK_Enum &&
15237                Kind != TTK_Enum);
15238           if (SafeToContinue)
15239             Diag(KWLoc, diag::err_use_with_wrong_tag)
15240               << Name
15241               << FixItHint::CreateReplacement(SourceRange(KWLoc),
15242                                               PrevTagDecl->getKindName());
15243           else
15244             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
15245           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
15246 
15247           if (SafeToContinue)
15248             Kind = PrevTagDecl->getTagKind();
15249           else {
15250             // Recover by making this an anonymous redefinition.
15251             Name = nullptr;
15252             Previous.clear();
15253             Invalid = true;
15254           }
15255         }
15256 
15257         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
15258           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
15259 
15260           // If this is an elaborated-type-specifier for a scoped enumeration,
15261           // the 'class' keyword is not necessary and not permitted.
15262           if (TUK == TUK_Reference || TUK == TUK_Friend) {
15263             if (ScopedEnum)
15264               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
15265                 << PrevEnum->isScoped()
15266                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
15267             return PrevTagDecl;
15268           }
15269 
15270           QualType EnumUnderlyingTy;
15271           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15272             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
15273           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
15274             EnumUnderlyingTy = QualType(T, 0);
15275 
15276           // All conflicts with previous declarations are recovered by
15277           // returning the previous declaration, unless this is a definition,
15278           // in which case we want the caller to bail out.
15279           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
15280                                      ScopedEnum, EnumUnderlyingTy,
15281                                      IsFixed, PrevEnum))
15282             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
15283         }
15284 
15285         // C++11 [class.mem]p1:
15286         //   A member shall not be declared twice in the member-specification,
15287         //   except that a nested class or member class template can be declared
15288         //   and then later defined.
15289         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
15290             S->isDeclScope(PrevDecl)) {
15291           Diag(NameLoc, diag::ext_member_redeclared);
15292           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
15293         }
15294 
15295         if (!Invalid) {
15296           // If this is a use, just return the declaration we found, unless
15297           // we have attributes.
15298           if (TUK == TUK_Reference || TUK == TUK_Friend) {
15299             if (!Attrs.empty()) {
15300               // FIXME: Diagnose these attributes. For now, we create a new
15301               // declaration to hold them.
15302             } else if (TUK == TUK_Reference &&
15303                        (PrevTagDecl->getFriendObjectKind() ==
15304                             Decl::FOK_Undeclared ||
15305                         PrevDecl->getOwningModule() != getCurrentModule()) &&
15306                        SS.isEmpty()) {
15307               // This declaration is a reference to an existing entity, but
15308               // has different visibility from that entity: it either makes
15309               // a friend visible or it makes a type visible in a new module.
15310               // In either case, create a new declaration. We only do this if
15311               // the declaration would have meant the same thing if no prior
15312               // declaration were found, that is, if it was found in the same
15313               // scope where we would have injected a declaration.
15314               if (!getTagInjectionContext(CurContext)->getRedeclContext()
15315                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
15316                 return PrevTagDecl;
15317               // This is in the injected scope, create a new declaration in
15318               // that scope.
15319               S = getTagInjectionScope(S, getLangOpts());
15320             } else {
15321               return PrevTagDecl;
15322             }
15323           }
15324 
15325           // Diagnose attempts to redefine a tag.
15326           if (TUK == TUK_Definition) {
15327             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
15328               // If we're defining a specialization and the previous definition
15329               // is from an implicit instantiation, don't emit an error
15330               // here; we'll catch this in the general case below.
15331               bool IsExplicitSpecializationAfterInstantiation = false;
15332               if (isMemberSpecialization) {
15333                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
15334                   IsExplicitSpecializationAfterInstantiation =
15335                     RD->getTemplateSpecializationKind() !=
15336                     TSK_ExplicitSpecialization;
15337                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
15338                   IsExplicitSpecializationAfterInstantiation =
15339                     ED->getTemplateSpecializationKind() !=
15340                     TSK_ExplicitSpecialization;
15341               }
15342 
15343               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
15344               // not keep more that one definition around (merge them). However,
15345               // ensure the decl passes the structural compatibility check in
15346               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
15347               NamedDecl *Hidden = nullptr;
15348               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
15349                 // There is a definition of this tag, but it is not visible. We
15350                 // explicitly make use of C++'s one definition rule here, and
15351                 // assume that this definition is identical to the hidden one
15352                 // we already have. Make the existing definition visible and
15353                 // use it in place of this one.
15354                 if (!getLangOpts().CPlusPlus) {
15355                   // Postpone making the old definition visible until after we
15356                   // complete parsing the new one and do the structural
15357                   // comparison.
15358                   SkipBody->CheckSameAsPrevious = true;
15359                   SkipBody->New = createTagFromNewDecl();
15360                   SkipBody->Previous = Def;
15361                   return Def;
15362                 } else {
15363                   SkipBody->ShouldSkip = true;
15364                   SkipBody->Previous = Def;
15365                   makeMergedDefinitionVisible(Hidden);
15366                   // Carry on and handle it like a normal definition. We'll
15367                   // skip starting the definitiion later.
15368                 }
15369               } else if (!IsExplicitSpecializationAfterInstantiation) {
15370                 // A redeclaration in function prototype scope in C isn't
15371                 // visible elsewhere, so merely issue a warning.
15372                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
15373                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
15374                 else
15375                   Diag(NameLoc, diag::err_redefinition) << Name;
15376                 notePreviousDefinition(Def,
15377                                        NameLoc.isValid() ? NameLoc : KWLoc);
15378                 // If this is a redefinition, recover by making this
15379                 // struct be anonymous, which will make any later
15380                 // references get the previous definition.
15381                 Name = nullptr;
15382                 Previous.clear();
15383                 Invalid = true;
15384               }
15385             } else {
15386               // If the type is currently being defined, complain
15387               // about a nested redefinition.
15388               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
15389               if (TD->isBeingDefined()) {
15390                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
15391                 Diag(PrevTagDecl->getLocation(),
15392                      diag::note_previous_definition);
15393                 Name = nullptr;
15394                 Previous.clear();
15395                 Invalid = true;
15396               }
15397             }
15398 
15399             // Okay, this is definition of a previously declared or referenced
15400             // tag. We're going to create a new Decl for it.
15401           }
15402 
15403           // Okay, we're going to make a redeclaration.  If this is some kind
15404           // of reference, make sure we build the redeclaration in the same DC
15405           // as the original, and ignore the current access specifier.
15406           if (TUK == TUK_Friend || TUK == TUK_Reference) {
15407             SearchDC = PrevTagDecl->getDeclContext();
15408             AS = AS_none;
15409           }
15410         }
15411         // If we get here we have (another) forward declaration or we
15412         // have a definition.  Just create a new decl.
15413 
15414       } else {
15415         // If we get here, this is a definition of a new tag type in a nested
15416         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
15417         // new decl/type.  We set PrevDecl to NULL so that the entities
15418         // have distinct types.
15419         Previous.clear();
15420       }
15421       // If we get here, we're going to create a new Decl. If PrevDecl
15422       // is non-NULL, it's a definition of the tag declared by
15423       // PrevDecl. If it's NULL, we have a new definition.
15424 
15425     // Otherwise, PrevDecl is not a tag, but was found with tag
15426     // lookup.  This is only actually possible in C++, where a few
15427     // things like templates still live in the tag namespace.
15428     } else {
15429       // Use a better diagnostic if an elaborated-type-specifier
15430       // found the wrong kind of type on the first
15431       // (non-redeclaration) lookup.
15432       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
15433           !Previous.isForRedeclaration()) {
15434         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15435         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
15436                                                        << Kind;
15437         Diag(PrevDecl->getLocation(), diag::note_declared_at);
15438         Invalid = true;
15439 
15440       // Otherwise, only diagnose if the declaration is in scope.
15441       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
15442                                 SS.isNotEmpty() || isMemberSpecialization)) {
15443         // do nothing
15444 
15445       // Diagnose implicit declarations introduced by elaborated types.
15446       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
15447         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15448         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
15449         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15450         Invalid = true;
15451 
15452       // Otherwise it's a declaration.  Call out a particularly common
15453       // case here.
15454       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15455         unsigned Kind = 0;
15456         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
15457         Diag(NameLoc, diag::err_tag_definition_of_typedef)
15458           << Name << Kind << TND->getUnderlyingType();
15459         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15460         Invalid = true;
15461 
15462       // Otherwise, diagnose.
15463       } else {
15464         // The tag name clashes with something else in the target scope,
15465         // issue an error and recover by making this tag be anonymous.
15466         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
15467         notePreviousDefinition(PrevDecl, NameLoc);
15468         Name = nullptr;
15469         Invalid = true;
15470       }
15471 
15472       // The existing declaration isn't relevant to us; we're in a
15473       // new scope, so clear out the previous declaration.
15474       Previous.clear();
15475     }
15476   }
15477 
15478 CreateNewDecl:
15479 
15480   TagDecl *PrevDecl = nullptr;
15481   if (Previous.isSingleResult())
15482     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
15483 
15484   // If there is an identifier, use the location of the identifier as the
15485   // location of the decl, otherwise use the location of the struct/union
15486   // keyword.
15487   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15488 
15489   // Otherwise, create a new declaration. If there is a previous
15490   // declaration of the same entity, the two will be linked via
15491   // PrevDecl.
15492   TagDecl *New;
15493 
15494   if (Kind == TTK_Enum) {
15495     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15496     // enum X { A, B, C } D;    D should chain to X.
15497     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
15498                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
15499                            ScopedEnumUsesClassTag, IsFixed);
15500 
15501     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
15502       StdAlignValT = cast<EnumDecl>(New);
15503 
15504     // If this is an undefined enum, warn.
15505     if (TUK != TUK_Definition && !Invalid) {
15506       TagDecl *Def;
15507       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
15508         // C++0x: 7.2p2: opaque-enum-declaration.
15509         // Conflicts are diagnosed above. Do nothing.
15510       }
15511       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
15512         Diag(Loc, diag::ext_forward_ref_enum_def)
15513           << New;
15514         Diag(Def->getLocation(), diag::note_previous_definition);
15515       } else {
15516         unsigned DiagID = diag::ext_forward_ref_enum;
15517         if (getLangOpts().MSVCCompat)
15518           DiagID = diag::ext_ms_forward_ref_enum;
15519         else if (getLangOpts().CPlusPlus)
15520           DiagID = diag::err_forward_ref_enum;
15521         Diag(Loc, DiagID);
15522       }
15523     }
15524 
15525     if (EnumUnderlying) {
15526       EnumDecl *ED = cast<EnumDecl>(New);
15527       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15528         ED->setIntegerTypeSourceInfo(TI);
15529       else
15530         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
15531       ED->setPromotionType(ED->getIntegerType());
15532       assert(ED->isComplete() && "enum with type should be complete");
15533     }
15534   } else {
15535     // struct/union/class
15536 
15537     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15538     // struct X { int A; } D;    D should chain to X.
15539     if (getLangOpts().CPlusPlus) {
15540       // FIXME: Look for a way to use RecordDecl for simple structs.
15541       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15542                                   cast_or_null<CXXRecordDecl>(PrevDecl));
15543 
15544       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
15545         StdBadAlloc = cast<CXXRecordDecl>(New);
15546     } else
15547       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15548                                cast_or_null<RecordDecl>(PrevDecl));
15549   }
15550 
15551   // C++11 [dcl.type]p3:
15552   //   A type-specifier-seq shall not define a class or enumeration [...].
15553   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
15554       TUK == TUK_Definition) {
15555     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
15556       << Context.getTagDeclType(New);
15557     Invalid = true;
15558   }
15559 
15560   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
15561       DC->getDeclKind() == Decl::Enum) {
15562     Diag(New->getLocation(), diag::err_type_defined_in_enum)
15563       << Context.getTagDeclType(New);
15564     Invalid = true;
15565   }
15566 
15567   // Maybe add qualifier info.
15568   if (SS.isNotEmpty()) {
15569     if (SS.isSet()) {
15570       // If this is either a declaration or a definition, check the
15571       // nested-name-specifier against the current context.
15572       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
15573           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
15574                                        isMemberSpecialization))
15575         Invalid = true;
15576 
15577       New->setQualifierInfo(SS.getWithLocInContext(Context));
15578       if (TemplateParameterLists.size() > 0) {
15579         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
15580       }
15581     }
15582     else
15583       Invalid = true;
15584   }
15585 
15586   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15587     // Add alignment attributes if necessary; these attributes are checked when
15588     // the ASTContext lays out the structure.
15589     //
15590     // It is important for implementing the correct semantics that this
15591     // happen here (in ActOnTag). The #pragma pack stack is
15592     // maintained as a result of parser callbacks which can occur at
15593     // many points during the parsing of a struct declaration (because
15594     // the #pragma tokens are effectively skipped over during the
15595     // parsing of the struct).
15596     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15597       AddAlignmentAttributesForRecord(RD);
15598       AddMsStructLayoutForRecord(RD);
15599     }
15600   }
15601 
15602   if (ModulePrivateLoc.isValid()) {
15603     if (isMemberSpecialization)
15604       Diag(New->getLocation(), diag::err_module_private_specialization)
15605         << 2
15606         << FixItHint::CreateRemoval(ModulePrivateLoc);
15607     // __module_private__ does not apply to local classes. However, we only
15608     // diagnose this as an error when the declaration specifiers are
15609     // freestanding. Here, we just ignore the __module_private__.
15610     else if (!SearchDC->isFunctionOrMethod())
15611       New->setModulePrivate();
15612   }
15613 
15614   // If this is a specialization of a member class (of a class template),
15615   // check the specialization.
15616   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
15617     Invalid = true;
15618 
15619   // If we're declaring or defining a tag in function prototype scope in C,
15620   // note that this type can only be used within the function and add it to
15621   // the list of decls to inject into the function definition scope.
15622   if ((Name || Kind == TTK_Enum) &&
15623       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
15624     if (getLangOpts().CPlusPlus) {
15625       // C++ [dcl.fct]p6:
15626       //   Types shall not be defined in return or parameter types.
15627       if (TUK == TUK_Definition && !IsTypeSpecifier) {
15628         Diag(Loc, diag::err_type_defined_in_param_type)
15629             << Name;
15630         Invalid = true;
15631       }
15632     } else if (!PrevDecl) {
15633       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
15634     }
15635   }
15636 
15637   if (Invalid)
15638     New->setInvalidDecl();
15639 
15640   // Set the lexical context. If the tag has a C++ scope specifier, the
15641   // lexical context will be different from the semantic context.
15642   New->setLexicalDeclContext(CurContext);
15643 
15644   // Mark this as a friend decl if applicable.
15645   // In Microsoft mode, a friend declaration also acts as a forward
15646   // declaration so we always pass true to setObjectOfFriendDecl to make
15647   // the tag name visible.
15648   if (TUK == TUK_Friend)
15649     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
15650 
15651   // Set the access specifier.
15652   if (!Invalid && SearchDC->isRecord())
15653     SetMemberAccessSpecifier(New, PrevDecl, AS);
15654 
15655   if (PrevDecl)
15656     CheckRedeclarationModuleOwnership(New, PrevDecl);
15657 
15658   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
15659     New->startDefinition();
15660 
15661   ProcessDeclAttributeList(S, New, Attrs);
15662   AddPragmaAttributes(S, New);
15663 
15664   // If this has an identifier, add it to the scope stack.
15665   if (TUK == TUK_Friend) {
15666     // We might be replacing an existing declaration in the lookup tables;
15667     // if so, borrow its access specifier.
15668     if (PrevDecl)
15669       New->setAccess(PrevDecl->getAccess());
15670 
15671     DeclContext *DC = New->getDeclContext()->getRedeclContext();
15672     DC->makeDeclVisibleInContext(New);
15673     if (Name) // can be null along some error paths
15674       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
15675         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
15676   } else if (Name) {
15677     S = getNonFieldDeclScope(S);
15678     PushOnScopeChains(New, S, true);
15679   } else {
15680     CurContext->addDecl(New);
15681   }
15682 
15683   // If this is the C FILE type, notify the AST context.
15684   if (IdentifierInfo *II = New->getIdentifier())
15685     if (!New->isInvalidDecl() &&
15686         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
15687         II->isStr("FILE"))
15688       Context.setFILEDecl(New);
15689 
15690   if (PrevDecl)
15691     mergeDeclAttributes(New, PrevDecl);
15692 
15693   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
15694     inferGslOwnerPointerAttribute(CXXRD);
15695 
15696   // If there's a #pragma GCC visibility in scope, set the visibility of this
15697   // record.
15698   AddPushedVisibilityAttribute(New);
15699 
15700   if (isMemberSpecialization && !New->isInvalidDecl())
15701     CompleteMemberSpecialization(New, Previous);
15702 
15703   OwnedDecl = true;
15704   // In C++, don't return an invalid declaration. We can't recover well from
15705   // the cases where we make the type anonymous.
15706   if (Invalid && getLangOpts().CPlusPlus) {
15707     if (New->isBeingDefined())
15708       if (auto RD = dyn_cast<RecordDecl>(New))
15709         RD->completeDefinition();
15710     return nullptr;
15711   } else if (SkipBody && SkipBody->ShouldSkip) {
15712     return SkipBody->Previous;
15713   } else {
15714     return New;
15715   }
15716 }
15717 
15718 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
15719   AdjustDeclIfTemplate(TagD);
15720   TagDecl *Tag = cast<TagDecl>(TagD);
15721 
15722   // Enter the tag context.
15723   PushDeclContext(S, Tag);
15724 
15725   ActOnDocumentableDecl(TagD);
15726 
15727   // If there's a #pragma GCC visibility in scope, set the visibility of this
15728   // record.
15729   AddPushedVisibilityAttribute(Tag);
15730 }
15731 
15732 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
15733                                     SkipBodyInfo &SkipBody) {
15734   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
15735     return false;
15736 
15737   // Make the previous decl visible.
15738   makeMergedDefinitionVisible(SkipBody.Previous);
15739   return true;
15740 }
15741 
15742 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
15743   assert(isa<ObjCContainerDecl>(IDecl) &&
15744          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
15745   DeclContext *OCD = cast<DeclContext>(IDecl);
15746   assert(getContainingDC(OCD) == CurContext &&
15747       "The next DeclContext should be lexically contained in the current one.");
15748   CurContext = OCD;
15749   return IDecl;
15750 }
15751 
15752 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
15753                                            SourceLocation FinalLoc,
15754                                            bool IsFinalSpelledSealed,
15755                                            SourceLocation LBraceLoc) {
15756   AdjustDeclIfTemplate(TagD);
15757   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
15758 
15759   FieldCollector->StartClass();
15760 
15761   if (!Record->getIdentifier())
15762     return;
15763 
15764   if (FinalLoc.isValid())
15765     Record->addAttr(FinalAttr::Create(
15766         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
15767         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
15768 
15769   // C++ [class]p2:
15770   //   [...] The class-name is also inserted into the scope of the
15771   //   class itself; this is known as the injected-class-name. For
15772   //   purposes of access checking, the injected-class-name is treated
15773   //   as if it were a public member name.
15774   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
15775       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
15776       Record->getLocation(), Record->getIdentifier(),
15777       /*PrevDecl=*/nullptr,
15778       /*DelayTypeCreation=*/true);
15779   Context.getTypeDeclType(InjectedClassName, Record);
15780   InjectedClassName->setImplicit();
15781   InjectedClassName->setAccess(AS_public);
15782   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
15783       InjectedClassName->setDescribedClassTemplate(Template);
15784   PushOnScopeChains(InjectedClassName, S);
15785   assert(InjectedClassName->isInjectedClassName() &&
15786          "Broken injected-class-name");
15787 }
15788 
15789 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
15790                                     SourceRange BraceRange) {
15791   AdjustDeclIfTemplate(TagD);
15792   TagDecl *Tag = cast<TagDecl>(TagD);
15793   Tag->setBraceRange(BraceRange);
15794 
15795   // Make sure we "complete" the definition even it is invalid.
15796   if (Tag->isBeingDefined()) {
15797     assert(Tag->isInvalidDecl() && "We should already have completed it");
15798     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15799       RD->completeDefinition();
15800   }
15801 
15802   if (isa<CXXRecordDecl>(Tag)) {
15803     FieldCollector->FinishClass();
15804   }
15805 
15806   // Exit this scope of this tag's definition.
15807   PopDeclContext();
15808 
15809   if (getCurLexicalContext()->isObjCContainer() &&
15810       Tag->getDeclContext()->isFileContext())
15811     Tag->setTopLevelDeclInObjCContainer();
15812 
15813   // Notify the consumer that we've defined a tag.
15814   if (!Tag->isInvalidDecl())
15815     Consumer.HandleTagDeclDefinition(Tag);
15816 }
15817 
15818 void Sema::ActOnObjCContainerFinishDefinition() {
15819   // Exit this scope of this interface definition.
15820   PopDeclContext();
15821 }
15822 
15823 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
15824   assert(DC == CurContext && "Mismatch of container contexts");
15825   OriginalLexicalContext = DC;
15826   ActOnObjCContainerFinishDefinition();
15827 }
15828 
15829 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
15830   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
15831   OriginalLexicalContext = nullptr;
15832 }
15833 
15834 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
15835   AdjustDeclIfTemplate(TagD);
15836   TagDecl *Tag = cast<TagDecl>(TagD);
15837   Tag->setInvalidDecl();
15838 
15839   // Make sure we "complete" the definition even it is invalid.
15840   if (Tag->isBeingDefined()) {
15841     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15842       RD->completeDefinition();
15843   }
15844 
15845   // We're undoing ActOnTagStartDefinition here, not
15846   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
15847   // the FieldCollector.
15848 
15849   PopDeclContext();
15850 }
15851 
15852 // Note that FieldName may be null for anonymous bitfields.
15853 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
15854                                 IdentifierInfo *FieldName,
15855                                 QualType FieldTy, bool IsMsStruct,
15856                                 Expr *BitWidth, bool *ZeroWidth) {
15857   // Default to true; that shouldn't confuse checks for emptiness
15858   if (ZeroWidth)
15859     *ZeroWidth = true;
15860 
15861   // C99 6.7.2.1p4 - verify the field type.
15862   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
15863   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
15864     // Handle incomplete types with specific error.
15865     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
15866       return ExprError();
15867     if (FieldName)
15868       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
15869         << FieldName << FieldTy << BitWidth->getSourceRange();
15870     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
15871       << FieldTy << BitWidth->getSourceRange();
15872   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
15873                                              UPPC_BitFieldWidth))
15874     return ExprError();
15875 
15876   // If the bit-width is type- or value-dependent, don't try to check
15877   // it now.
15878   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
15879     return BitWidth;
15880 
15881   llvm::APSInt Value;
15882   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
15883   if (ICE.isInvalid())
15884     return ICE;
15885   BitWidth = ICE.get();
15886 
15887   if (Value != 0 && ZeroWidth)
15888     *ZeroWidth = false;
15889 
15890   // Zero-width bitfield is ok for anonymous field.
15891   if (Value == 0 && FieldName)
15892     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
15893 
15894   if (Value.isSigned() && Value.isNegative()) {
15895     if (FieldName)
15896       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
15897                << FieldName << Value.toString(10);
15898     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
15899       << Value.toString(10);
15900   }
15901 
15902   if (!FieldTy->isDependentType()) {
15903     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
15904     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
15905     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
15906 
15907     // Over-wide bitfields are an error in C or when using the MSVC bitfield
15908     // ABI.
15909     bool CStdConstraintViolation =
15910         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
15911     bool MSBitfieldViolation =
15912         Value.ugt(TypeStorageSize) &&
15913         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
15914     if (CStdConstraintViolation || MSBitfieldViolation) {
15915       unsigned DiagWidth =
15916           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
15917       if (FieldName)
15918         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
15919                << FieldName << (unsigned)Value.getZExtValue()
15920                << !CStdConstraintViolation << DiagWidth;
15921 
15922       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
15923              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
15924              << DiagWidth;
15925     }
15926 
15927     // Warn on types where the user might conceivably expect to get all
15928     // specified bits as value bits: that's all integral types other than
15929     // 'bool'.
15930     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
15931       if (FieldName)
15932         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
15933             << FieldName << (unsigned)Value.getZExtValue()
15934             << (unsigned)TypeWidth;
15935       else
15936         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
15937             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
15938     }
15939   }
15940 
15941   return BitWidth;
15942 }
15943 
15944 /// ActOnField - Each field of a C struct/union is passed into this in order
15945 /// to create a FieldDecl object for it.
15946 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
15947                        Declarator &D, Expr *BitfieldWidth) {
15948   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
15949                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
15950                                /*InitStyle=*/ICIS_NoInit, AS_public);
15951   return Res;
15952 }
15953 
15954 /// HandleField - Analyze a field of a C struct or a C++ data member.
15955 ///
15956 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
15957                              SourceLocation DeclStart,
15958                              Declarator &D, Expr *BitWidth,
15959                              InClassInitStyle InitStyle,
15960                              AccessSpecifier AS) {
15961   if (D.isDecompositionDeclarator()) {
15962     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
15963     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
15964       << Decomp.getSourceRange();
15965     return nullptr;
15966   }
15967 
15968   IdentifierInfo *II = D.getIdentifier();
15969   SourceLocation Loc = DeclStart;
15970   if (II) Loc = D.getIdentifierLoc();
15971 
15972   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15973   QualType T = TInfo->getType();
15974   if (getLangOpts().CPlusPlus) {
15975     CheckExtraCXXDefaultArguments(D);
15976 
15977     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15978                                         UPPC_DataMemberType)) {
15979       D.setInvalidType();
15980       T = Context.IntTy;
15981       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15982     }
15983   }
15984 
15985   DiagnoseFunctionSpecifiers(D.getDeclSpec());
15986 
15987   if (D.getDeclSpec().isInlineSpecified())
15988     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15989         << getLangOpts().CPlusPlus17;
15990   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15991     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15992          diag::err_invalid_thread)
15993       << DeclSpec::getSpecifierName(TSCS);
15994 
15995   // Check to see if this name was declared as a member previously
15996   NamedDecl *PrevDecl = nullptr;
15997   LookupResult Previous(*this, II, Loc, LookupMemberName,
15998                         ForVisibleRedeclaration);
15999   LookupName(Previous, S);
16000   switch (Previous.getResultKind()) {
16001     case LookupResult::Found:
16002     case LookupResult::FoundUnresolvedValue:
16003       PrevDecl = Previous.getAsSingle<NamedDecl>();
16004       break;
16005 
16006     case LookupResult::FoundOverloaded:
16007       PrevDecl = Previous.getRepresentativeDecl();
16008       break;
16009 
16010     case LookupResult::NotFound:
16011     case LookupResult::NotFoundInCurrentInstantiation:
16012     case LookupResult::Ambiguous:
16013       break;
16014   }
16015   Previous.suppressDiagnostics();
16016 
16017   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16018     // Maybe we will complain about the shadowed template parameter.
16019     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16020     // Just pretend that we didn't see the previous declaration.
16021     PrevDecl = nullptr;
16022   }
16023 
16024   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
16025     PrevDecl = nullptr;
16026 
16027   bool Mutable
16028     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
16029   SourceLocation TSSL = D.getBeginLoc();
16030   FieldDecl *NewFD
16031     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
16032                      TSSL, AS, PrevDecl, &D);
16033 
16034   if (NewFD->isInvalidDecl())
16035     Record->setInvalidDecl();
16036 
16037   if (D.getDeclSpec().isModulePrivateSpecified())
16038     NewFD->setModulePrivate();
16039 
16040   if (NewFD->isInvalidDecl() && PrevDecl) {
16041     // Don't introduce NewFD into scope; there's already something
16042     // with the same name in the same scope.
16043   } else if (II) {
16044     PushOnScopeChains(NewFD, S);
16045   } else
16046     Record->addDecl(NewFD);
16047 
16048   return NewFD;
16049 }
16050 
16051 /// Build a new FieldDecl and check its well-formedness.
16052 ///
16053 /// This routine builds a new FieldDecl given the fields name, type,
16054 /// record, etc. \p PrevDecl should refer to any previous declaration
16055 /// with the same name and in the same scope as the field to be
16056 /// created.
16057 ///
16058 /// \returns a new FieldDecl.
16059 ///
16060 /// \todo The Declarator argument is a hack. It will be removed once
16061 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
16062                                 TypeSourceInfo *TInfo,
16063                                 RecordDecl *Record, SourceLocation Loc,
16064                                 bool Mutable, Expr *BitWidth,
16065                                 InClassInitStyle InitStyle,
16066                                 SourceLocation TSSL,
16067                                 AccessSpecifier AS, NamedDecl *PrevDecl,
16068                                 Declarator *D) {
16069   IdentifierInfo *II = Name.getAsIdentifierInfo();
16070   bool InvalidDecl = false;
16071   if (D) InvalidDecl = D->isInvalidType();
16072 
16073   // If we receive a broken type, recover by assuming 'int' and
16074   // marking this declaration as invalid.
16075   if (T.isNull()) {
16076     InvalidDecl = true;
16077     T = Context.IntTy;
16078   }
16079 
16080   QualType EltTy = Context.getBaseElementType(T);
16081   if (!EltTy->isDependentType()) {
16082     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
16083       // Fields of incomplete type force their record to be invalid.
16084       Record->setInvalidDecl();
16085       InvalidDecl = true;
16086     } else {
16087       NamedDecl *Def;
16088       EltTy->isIncompleteType(&Def);
16089       if (Def && Def->isInvalidDecl()) {
16090         Record->setInvalidDecl();
16091         InvalidDecl = true;
16092       }
16093     }
16094   }
16095 
16096   // TR 18037 does not allow fields to be declared with address space
16097   if (T.getQualifiers().hasAddressSpace() || T->isDependentAddressSpaceType() ||
16098       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
16099     Diag(Loc, diag::err_field_with_address_space);
16100     Record->setInvalidDecl();
16101     InvalidDecl = true;
16102   }
16103 
16104   if (LangOpts.OpenCL) {
16105     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
16106     // used as structure or union field: image, sampler, event or block types.
16107     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
16108         T->isBlockPointerType()) {
16109       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
16110       Record->setInvalidDecl();
16111       InvalidDecl = true;
16112     }
16113     // OpenCL v1.2 s6.9.c: bitfields are not supported.
16114     if (BitWidth) {
16115       Diag(Loc, diag::err_opencl_bitfields);
16116       InvalidDecl = true;
16117     }
16118   }
16119 
16120   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
16121   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
16122       T.hasQualifiers()) {
16123     InvalidDecl = true;
16124     Diag(Loc, diag::err_anon_bitfield_qualifiers);
16125   }
16126 
16127   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16128   // than a variably modified type.
16129   if (!InvalidDecl && T->isVariablyModifiedType()) {
16130     bool SizeIsNegative;
16131     llvm::APSInt Oversized;
16132 
16133     TypeSourceInfo *FixedTInfo =
16134       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
16135                                                     SizeIsNegative,
16136                                                     Oversized);
16137     if (FixedTInfo) {
16138       Diag(Loc, diag::warn_illegal_constant_array_size);
16139       TInfo = FixedTInfo;
16140       T = FixedTInfo->getType();
16141     } else {
16142       if (SizeIsNegative)
16143         Diag(Loc, diag::err_typecheck_negative_array_size);
16144       else if (Oversized.getBoolValue())
16145         Diag(Loc, diag::err_array_too_large)
16146           << Oversized.toString(10);
16147       else
16148         Diag(Loc, diag::err_typecheck_field_variable_size);
16149       InvalidDecl = true;
16150     }
16151   }
16152 
16153   // Fields can not have abstract class types
16154   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
16155                                              diag::err_abstract_type_in_decl,
16156                                              AbstractFieldType))
16157     InvalidDecl = true;
16158 
16159   bool ZeroWidth = false;
16160   if (InvalidDecl)
16161     BitWidth = nullptr;
16162   // If this is declared as a bit-field, check the bit-field.
16163   if (BitWidth) {
16164     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
16165                               &ZeroWidth).get();
16166     if (!BitWidth) {
16167       InvalidDecl = true;
16168       BitWidth = nullptr;
16169       ZeroWidth = false;
16170     }
16171   }
16172 
16173   // Check that 'mutable' is consistent with the type of the declaration.
16174   if (!InvalidDecl && Mutable) {
16175     unsigned DiagID = 0;
16176     if (T->isReferenceType())
16177       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
16178                                         : diag::err_mutable_reference;
16179     else if (T.isConstQualified())
16180       DiagID = diag::err_mutable_const;
16181 
16182     if (DiagID) {
16183       SourceLocation ErrLoc = Loc;
16184       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
16185         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
16186       Diag(ErrLoc, DiagID);
16187       if (DiagID != diag::ext_mutable_reference) {
16188         Mutable = false;
16189         InvalidDecl = true;
16190       }
16191     }
16192   }
16193 
16194   // C++11 [class.union]p8 (DR1460):
16195   //   At most one variant member of a union may have a
16196   //   brace-or-equal-initializer.
16197   if (InitStyle != ICIS_NoInit)
16198     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
16199 
16200   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
16201                                        BitWidth, Mutable, InitStyle);
16202   if (InvalidDecl)
16203     NewFD->setInvalidDecl();
16204 
16205   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
16206     Diag(Loc, diag::err_duplicate_member) << II;
16207     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16208     NewFD->setInvalidDecl();
16209   }
16210 
16211   if (!InvalidDecl && getLangOpts().CPlusPlus) {
16212     if (Record->isUnion()) {
16213       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16214         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
16215         if (RDecl->getDefinition()) {
16216           // C++ [class.union]p1: An object of a class with a non-trivial
16217           // constructor, a non-trivial copy constructor, a non-trivial
16218           // destructor, or a non-trivial copy assignment operator
16219           // cannot be a member of a union, nor can an array of such
16220           // objects.
16221           if (CheckNontrivialField(NewFD))
16222             NewFD->setInvalidDecl();
16223         }
16224       }
16225 
16226       // C++ [class.union]p1: If a union contains a member of reference type,
16227       // the program is ill-formed, except when compiling with MSVC extensions
16228       // enabled.
16229       if (EltTy->isReferenceType()) {
16230         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
16231                                     diag::ext_union_member_of_reference_type :
16232                                     diag::err_union_member_of_reference_type)
16233           << NewFD->getDeclName() << EltTy;
16234         if (!getLangOpts().MicrosoftExt)
16235           NewFD->setInvalidDecl();
16236       }
16237     }
16238   }
16239 
16240   // FIXME: We need to pass in the attributes given an AST
16241   // representation, not a parser representation.
16242   if (D) {
16243     // FIXME: The current scope is almost... but not entirely... correct here.
16244     ProcessDeclAttributes(getCurScope(), NewFD, *D);
16245 
16246     if (NewFD->hasAttrs())
16247       CheckAlignasUnderalignment(NewFD);
16248   }
16249 
16250   // In auto-retain/release, infer strong retension for fields of
16251   // retainable type.
16252   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
16253     NewFD->setInvalidDecl();
16254 
16255   if (T.isObjCGCWeak())
16256     Diag(Loc, diag::warn_attribute_weak_on_field);
16257 
16258   NewFD->setAccess(AS);
16259   return NewFD;
16260 }
16261 
16262 bool Sema::CheckNontrivialField(FieldDecl *FD) {
16263   assert(FD);
16264   assert(getLangOpts().CPlusPlus && "valid check only for C++");
16265 
16266   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
16267     return false;
16268 
16269   QualType EltTy = Context.getBaseElementType(FD->getType());
16270   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16271     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
16272     if (RDecl->getDefinition()) {
16273       // We check for copy constructors before constructors
16274       // because otherwise we'll never get complaints about
16275       // copy constructors.
16276 
16277       CXXSpecialMember member = CXXInvalid;
16278       // We're required to check for any non-trivial constructors. Since the
16279       // implicit default constructor is suppressed if there are any
16280       // user-declared constructors, we just need to check that there is a
16281       // trivial default constructor and a trivial copy constructor. (We don't
16282       // worry about move constructors here, since this is a C++98 check.)
16283       if (RDecl->hasNonTrivialCopyConstructor())
16284         member = CXXCopyConstructor;
16285       else if (!RDecl->hasTrivialDefaultConstructor())
16286         member = CXXDefaultConstructor;
16287       else if (RDecl->hasNonTrivialCopyAssignment())
16288         member = CXXCopyAssignment;
16289       else if (RDecl->hasNonTrivialDestructor())
16290         member = CXXDestructor;
16291 
16292       if (member != CXXInvalid) {
16293         if (!getLangOpts().CPlusPlus11 &&
16294             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
16295           // Objective-C++ ARC: it is an error to have a non-trivial field of
16296           // a union. However, system headers in Objective-C programs
16297           // occasionally have Objective-C lifetime objects within unions,
16298           // and rather than cause the program to fail, we make those
16299           // members unavailable.
16300           SourceLocation Loc = FD->getLocation();
16301           if (getSourceManager().isInSystemHeader(Loc)) {
16302             if (!FD->hasAttr<UnavailableAttr>())
16303               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
16304                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
16305             return false;
16306           }
16307         }
16308 
16309         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
16310                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
16311                diag::err_illegal_union_or_anon_struct_member)
16312           << FD->getParent()->isUnion() << FD->getDeclName() << member;
16313         DiagnoseNontrivial(RDecl, member);
16314         return !getLangOpts().CPlusPlus11;
16315       }
16316     }
16317   }
16318 
16319   return false;
16320 }
16321 
16322 /// TranslateIvarVisibility - Translate visibility from a token ID to an
16323 ///  AST enum value.
16324 static ObjCIvarDecl::AccessControl
16325 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
16326   switch (ivarVisibility) {
16327   default: llvm_unreachable("Unknown visitibility kind");
16328   case tok::objc_private: return ObjCIvarDecl::Private;
16329   case tok::objc_public: return ObjCIvarDecl::Public;
16330   case tok::objc_protected: return ObjCIvarDecl::Protected;
16331   case tok::objc_package: return ObjCIvarDecl::Package;
16332   }
16333 }
16334 
16335 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
16336 /// in order to create an IvarDecl object for it.
16337 Decl *Sema::ActOnIvar(Scope *S,
16338                                 SourceLocation DeclStart,
16339                                 Declarator &D, Expr *BitfieldWidth,
16340                                 tok::ObjCKeywordKind Visibility) {
16341 
16342   IdentifierInfo *II = D.getIdentifier();
16343   Expr *BitWidth = (Expr*)BitfieldWidth;
16344   SourceLocation Loc = DeclStart;
16345   if (II) Loc = D.getIdentifierLoc();
16346 
16347   // FIXME: Unnamed fields can be handled in various different ways, for
16348   // example, unnamed unions inject all members into the struct namespace!
16349 
16350   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16351   QualType T = TInfo->getType();
16352 
16353   if (BitWidth) {
16354     // 6.7.2.1p3, 6.7.2.1p4
16355     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
16356     if (!BitWidth)
16357       D.setInvalidType();
16358   } else {
16359     // Not a bitfield.
16360 
16361     // validate II.
16362 
16363   }
16364   if (T->isReferenceType()) {
16365     Diag(Loc, diag::err_ivar_reference_type);
16366     D.setInvalidType();
16367   }
16368   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16369   // than a variably modified type.
16370   else if (T->isVariablyModifiedType()) {
16371     Diag(Loc, diag::err_typecheck_ivar_variable_size);
16372     D.setInvalidType();
16373   }
16374 
16375   // Get the visibility (access control) for this ivar.
16376   ObjCIvarDecl::AccessControl ac =
16377     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
16378                                         : ObjCIvarDecl::None;
16379   // Must set ivar's DeclContext to its enclosing interface.
16380   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
16381   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
16382     return nullptr;
16383   ObjCContainerDecl *EnclosingContext;
16384   if (ObjCImplementationDecl *IMPDecl =
16385       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16386     if (LangOpts.ObjCRuntime.isFragile()) {
16387     // Case of ivar declared in an implementation. Context is that of its class.
16388       EnclosingContext = IMPDecl->getClassInterface();
16389       assert(EnclosingContext && "Implementation has no class interface!");
16390     }
16391     else
16392       EnclosingContext = EnclosingDecl;
16393   } else {
16394     if (ObjCCategoryDecl *CDecl =
16395         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16396       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
16397         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
16398         return nullptr;
16399       }
16400     }
16401     EnclosingContext = EnclosingDecl;
16402   }
16403 
16404   // Construct the decl.
16405   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
16406                                              DeclStart, Loc, II, T,
16407                                              TInfo, ac, (Expr *)BitfieldWidth);
16408 
16409   if (II) {
16410     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
16411                                            ForVisibleRedeclaration);
16412     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
16413         && !isa<TagDecl>(PrevDecl)) {
16414       Diag(Loc, diag::err_duplicate_member) << II;
16415       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16416       NewID->setInvalidDecl();
16417     }
16418   }
16419 
16420   // Process attributes attached to the ivar.
16421   ProcessDeclAttributes(S, NewID, D);
16422 
16423   if (D.isInvalidType())
16424     NewID->setInvalidDecl();
16425 
16426   // In ARC, infer 'retaining' for ivars of retainable type.
16427   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
16428     NewID->setInvalidDecl();
16429 
16430   if (D.getDeclSpec().isModulePrivateSpecified())
16431     NewID->setModulePrivate();
16432 
16433   if (II) {
16434     // FIXME: When interfaces are DeclContexts, we'll need to add
16435     // these to the interface.
16436     S->AddDecl(NewID);
16437     IdResolver.AddDecl(NewID);
16438   }
16439 
16440   if (LangOpts.ObjCRuntime.isNonFragile() &&
16441       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
16442     Diag(Loc, diag::warn_ivars_in_interface);
16443 
16444   return NewID;
16445 }
16446 
16447 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
16448 /// class and class extensions. For every class \@interface and class
16449 /// extension \@interface, if the last ivar is a bitfield of any type,
16450 /// then add an implicit `char :0` ivar to the end of that interface.
16451 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
16452                              SmallVectorImpl<Decl *> &AllIvarDecls) {
16453   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
16454     return;
16455 
16456   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
16457   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
16458 
16459   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
16460     return;
16461   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
16462   if (!ID) {
16463     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
16464       if (!CD->IsClassExtension())
16465         return;
16466     }
16467     // No need to add this to end of @implementation.
16468     else
16469       return;
16470   }
16471   // All conditions are met. Add a new bitfield to the tail end of ivars.
16472   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
16473   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
16474 
16475   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
16476                               DeclLoc, DeclLoc, nullptr,
16477                               Context.CharTy,
16478                               Context.getTrivialTypeSourceInfo(Context.CharTy,
16479                                                                DeclLoc),
16480                               ObjCIvarDecl::Private, BW,
16481                               true);
16482   AllIvarDecls.push_back(Ivar);
16483 }
16484 
16485 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
16486                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
16487                        SourceLocation RBrac,
16488                        const ParsedAttributesView &Attrs) {
16489   assert(EnclosingDecl && "missing record or interface decl");
16490 
16491   // If this is an Objective-C @implementation or category and we have
16492   // new fields here we should reset the layout of the interface since
16493   // it will now change.
16494   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
16495     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
16496     switch (DC->getKind()) {
16497     default: break;
16498     case Decl::ObjCCategory:
16499       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
16500       break;
16501     case Decl::ObjCImplementation:
16502       Context.
16503         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
16504       break;
16505     }
16506   }
16507 
16508   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
16509   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
16510 
16511   // Start counting up the number of named members; make sure to include
16512   // members of anonymous structs and unions in the total.
16513   unsigned NumNamedMembers = 0;
16514   if (Record) {
16515     for (const auto *I : Record->decls()) {
16516       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
16517         if (IFD->getDeclName())
16518           ++NumNamedMembers;
16519     }
16520   }
16521 
16522   // Verify that all the fields are okay.
16523   SmallVector<FieldDecl*, 32> RecFields;
16524 
16525   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
16526        i != end; ++i) {
16527     FieldDecl *FD = cast<FieldDecl>(*i);
16528 
16529     // Get the type for the field.
16530     const Type *FDTy = FD->getType().getTypePtr();
16531 
16532     if (!FD->isAnonymousStructOrUnion()) {
16533       // Remember all fields written by the user.
16534       RecFields.push_back(FD);
16535     }
16536 
16537     // If the field is already invalid for some reason, don't emit more
16538     // diagnostics about it.
16539     if (FD->isInvalidDecl()) {
16540       EnclosingDecl->setInvalidDecl();
16541       continue;
16542     }
16543 
16544     // C99 6.7.2.1p2:
16545     //   A structure or union shall not contain a member with
16546     //   incomplete or function type (hence, a structure shall not
16547     //   contain an instance of itself, but may contain a pointer to
16548     //   an instance of itself), except that the last member of a
16549     //   structure with more than one named member may have incomplete
16550     //   array type; such a structure (and any union containing,
16551     //   possibly recursively, a member that is such a structure)
16552     //   shall not be a member of a structure or an element of an
16553     //   array.
16554     bool IsLastField = (i + 1 == Fields.end());
16555     if (FDTy->isFunctionType()) {
16556       // Field declared as a function.
16557       Diag(FD->getLocation(), diag::err_field_declared_as_function)
16558         << FD->getDeclName();
16559       FD->setInvalidDecl();
16560       EnclosingDecl->setInvalidDecl();
16561       continue;
16562     } else if (FDTy->isIncompleteArrayType() &&
16563                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
16564       if (Record) {
16565         // Flexible array member.
16566         // Microsoft and g++ is more permissive regarding flexible array.
16567         // It will accept flexible array in union and also
16568         // as the sole element of a struct/class.
16569         unsigned DiagID = 0;
16570         if (!Record->isUnion() && !IsLastField) {
16571           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
16572             << FD->getDeclName() << FD->getType() << Record->getTagKind();
16573           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
16574           FD->setInvalidDecl();
16575           EnclosingDecl->setInvalidDecl();
16576           continue;
16577         } else if (Record->isUnion())
16578           DiagID = getLangOpts().MicrosoftExt
16579                        ? diag::ext_flexible_array_union_ms
16580                        : getLangOpts().CPlusPlus
16581                              ? diag::ext_flexible_array_union_gnu
16582                              : diag::err_flexible_array_union;
16583         else if (NumNamedMembers < 1)
16584           DiagID = getLangOpts().MicrosoftExt
16585                        ? diag::ext_flexible_array_empty_aggregate_ms
16586                        : getLangOpts().CPlusPlus
16587                              ? diag::ext_flexible_array_empty_aggregate_gnu
16588                              : diag::err_flexible_array_empty_aggregate;
16589 
16590         if (DiagID)
16591           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
16592                                           << Record->getTagKind();
16593         // While the layout of types that contain virtual bases is not specified
16594         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
16595         // virtual bases after the derived members.  This would make a flexible
16596         // array member declared at the end of an object not adjacent to the end
16597         // of the type.
16598         if (CXXRecord && CXXRecord->getNumVBases() != 0)
16599           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
16600               << FD->getDeclName() << Record->getTagKind();
16601         if (!getLangOpts().C99)
16602           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
16603             << FD->getDeclName() << Record->getTagKind();
16604 
16605         // If the element type has a non-trivial destructor, we would not
16606         // implicitly destroy the elements, so disallow it for now.
16607         //
16608         // FIXME: GCC allows this. We should probably either implicitly delete
16609         // the destructor of the containing class, or just allow this.
16610         QualType BaseElem = Context.getBaseElementType(FD->getType());
16611         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
16612           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
16613             << FD->getDeclName() << FD->getType();
16614           FD->setInvalidDecl();
16615           EnclosingDecl->setInvalidDecl();
16616           continue;
16617         }
16618         // Okay, we have a legal flexible array member at the end of the struct.
16619         Record->setHasFlexibleArrayMember(true);
16620       } else {
16621         // In ObjCContainerDecl ivars with incomplete array type are accepted,
16622         // unless they are followed by another ivar. That check is done
16623         // elsewhere, after synthesized ivars are known.
16624       }
16625     } else if (!FDTy->isDependentType() &&
16626                RequireCompleteType(FD->getLocation(), FD->getType(),
16627                                    diag::err_field_incomplete)) {
16628       // Incomplete type
16629       FD->setInvalidDecl();
16630       EnclosingDecl->setInvalidDecl();
16631       continue;
16632     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
16633       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
16634         // A type which contains a flexible array member is considered to be a
16635         // flexible array member.
16636         Record->setHasFlexibleArrayMember(true);
16637         if (!Record->isUnion()) {
16638           // If this is a struct/class and this is not the last element, reject
16639           // it.  Note that GCC supports variable sized arrays in the middle of
16640           // structures.
16641           if (!IsLastField)
16642             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
16643               << FD->getDeclName() << FD->getType();
16644           else {
16645             // We support flexible arrays at the end of structs in
16646             // other structs as an extension.
16647             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
16648               << FD->getDeclName();
16649           }
16650         }
16651       }
16652       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
16653           RequireNonAbstractType(FD->getLocation(), FD->getType(),
16654                                  diag::err_abstract_type_in_decl,
16655                                  AbstractIvarType)) {
16656         // Ivars can not have abstract class types
16657         FD->setInvalidDecl();
16658       }
16659       if (Record && FDTTy->getDecl()->hasObjectMember())
16660         Record->setHasObjectMember(true);
16661       if (Record && FDTTy->getDecl()->hasVolatileMember())
16662         Record->setHasVolatileMember(true);
16663     } else if (FDTy->isObjCObjectType()) {
16664       /// A field cannot be an Objective-c object
16665       Diag(FD->getLocation(), diag::err_statically_allocated_object)
16666         << FixItHint::CreateInsertion(FD->getLocation(), "*");
16667       QualType T = Context.getObjCObjectPointerType(FD->getType());
16668       FD->setType(T);
16669     } else if (Record && Record->isUnion() &&
16670                FD->getType().hasNonTrivialObjCLifetime() &&
16671                getSourceManager().isInSystemHeader(FD->getLocation()) &&
16672                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
16673                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
16674                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
16675       // For backward compatibility, fields of C unions declared in system
16676       // headers that have non-trivial ObjC ownership qualifications are marked
16677       // as unavailable unless the qualifier is explicit and __strong. This can
16678       // break ABI compatibility between programs compiled with ARC and MRR, but
16679       // is a better option than rejecting programs using those unions under
16680       // ARC.
16681       FD->addAttr(UnavailableAttr::CreateImplicit(
16682           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
16683           FD->getLocation()));
16684     } else if (getLangOpts().ObjC &&
16685                getLangOpts().getGC() != LangOptions::NonGC &&
16686                Record && !Record->hasObjectMember()) {
16687       if (FD->getType()->isObjCObjectPointerType() ||
16688           FD->getType().isObjCGCStrong())
16689         Record->setHasObjectMember(true);
16690       else if (Context.getAsArrayType(FD->getType())) {
16691         QualType BaseType = Context.getBaseElementType(FD->getType());
16692         if (BaseType->isRecordType() &&
16693             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
16694           Record->setHasObjectMember(true);
16695         else if (BaseType->isObjCObjectPointerType() ||
16696                  BaseType.isObjCGCStrong())
16697                Record->setHasObjectMember(true);
16698       }
16699     }
16700 
16701     if (Record && !getLangOpts().CPlusPlus &&
16702         !shouldIgnoreForRecordTriviality(FD)) {
16703       QualType FT = FD->getType();
16704       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
16705         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
16706         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
16707             Record->isUnion())
16708           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
16709       }
16710       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
16711       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
16712         Record->setNonTrivialToPrimitiveCopy(true);
16713         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
16714           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
16715       }
16716       if (FT.isDestructedType()) {
16717         Record->setNonTrivialToPrimitiveDestroy(true);
16718         Record->setParamDestroyedInCallee(true);
16719         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
16720           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
16721       }
16722 
16723       if (const auto *RT = FT->getAs<RecordType>()) {
16724         if (RT->getDecl()->getArgPassingRestrictions() ==
16725             RecordDecl::APK_CanNeverPassInRegs)
16726           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16727       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
16728         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16729     }
16730 
16731     if (Record && FD->getType().isVolatileQualified())
16732       Record->setHasVolatileMember(true);
16733     // Keep track of the number of named members.
16734     if (FD->getIdentifier())
16735       ++NumNamedMembers;
16736   }
16737 
16738   // Okay, we successfully defined 'Record'.
16739   if (Record) {
16740     bool Completed = false;
16741     if (CXXRecord) {
16742       if (!CXXRecord->isInvalidDecl()) {
16743         // Set access bits correctly on the directly-declared conversions.
16744         for (CXXRecordDecl::conversion_iterator
16745                I = CXXRecord->conversion_begin(),
16746                E = CXXRecord->conversion_end(); I != E; ++I)
16747           I.setAccess((*I)->getAccess());
16748       }
16749 
16750       if (!CXXRecord->isDependentType()) {
16751         // Add any implicitly-declared members to this class.
16752         AddImplicitlyDeclaredMembersToClass(CXXRecord);
16753 
16754         if (!CXXRecord->isInvalidDecl()) {
16755           // If we have virtual base classes, we may end up finding multiple
16756           // final overriders for a given virtual function. Check for this
16757           // problem now.
16758           if (CXXRecord->getNumVBases()) {
16759             CXXFinalOverriderMap FinalOverriders;
16760             CXXRecord->getFinalOverriders(FinalOverriders);
16761 
16762             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
16763                                              MEnd = FinalOverriders.end();
16764                  M != MEnd; ++M) {
16765               for (OverridingMethods::iterator SO = M->second.begin(),
16766                                             SOEnd = M->second.end();
16767                    SO != SOEnd; ++SO) {
16768                 assert(SO->second.size() > 0 &&
16769                        "Virtual function without overriding functions?");
16770                 if (SO->second.size() == 1)
16771                   continue;
16772 
16773                 // C++ [class.virtual]p2:
16774                 //   In a derived class, if a virtual member function of a base
16775                 //   class subobject has more than one final overrider the
16776                 //   program is ill-formed.
16777                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
16778                   << (const NamedDecl *)M->first << Record;
16779                 Diag(M->first->getLocation(),
16780                      diag::note_overridden_virtual_function);
16781                 for (OverridingMethods::overriding_iterator
16782                           OM = SO->second.begin(),
16783                        OMEnd = SO->second.end();
16784                      OM != OMEnd; ++OM)
16785                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
16786                     << (const NamedDecl *)M->first << OM->Method->getParent();
16787 
16788                 Record->setInvalidDecl();
16789               }
16790             }
16791             CXXRecord->completeDefinition(&FinalOverriders);
16792             Completed = true;
16793           }
16794         }
16795       }
16796     }
16797 
16798     if (!Completed)
16799       Record->completeDefinition();
16800 
16801     // Handle attributes before checking the layout.
16802     ProcessDeclAttributeList(S, Record, Attrs);
16803 
16804     // We may have deferred checking for a deleted destructor. Check now.
16805     if (CXXRecord) {
16806       auto *Dtor = CXXRecord->getDestructor();
16807       if (Dtor && Dtor->isImplicit() &&
16808           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
16809         CXXRecord->setImplicitDestructorIsDeleted();
16810         SetDeclDeleted(Dtor, CXXRecord->getLocation());
16811       }
16812     }
16813 
16814     if (Record->hasAttrs()) {
16815       CheckAlignasUnderalignment(Record);
16816 
16817       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
16818         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
16819                                            IA->getRange(), IA->getBestCase(),
16820                                            IA->getInheritanceModel());
16821     }
16822 
16823     // Check if the structure/union declaration is a type that can have zero
16824     // size in C. For C this is a language extension, for C++ it may cause
16825     // compatibility problems.
16826     bool CheckForZeroSize;
16827     if (!getLangOpts().CPlusPlus) {
16828       CheckForZeroSize = true;
16829     } else {
16830       // For C++ filter out types that cannot be referenced in C code.
16831       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
16832       CheckForZeroSize =
16833           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
16834           !CXXRecord->isDependentType() &&
16835           CXXRecord->isCLike();
16836     }
16837     if (CheckForZeroSize) {
16838       bool ZeroSize = true;
16839       bool IsEmpty = true;
16840       unsigned NonBitFields = 0;
16841       for (RecordDecl::field_iterator I = Record->field_begin(),
16842                                       E = Record->field_end();
16843            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
16844         IsEmpty = false;
16845         if (I->isUnnamedBitfield()) {
16846           if (!I->isZeroLengthBitField(Context))
16847             ZeroSize = false;
16848         } else {
16849           ++NonBitFields;
16850           QualType FieldType = I->getType();
16851           if (FieldType->isIncompleteType() ||
16852               !Context.getTypeSizeInChars(FieldType).isZero())
16853             ZeroSize = false;
16854         }
16855       }
16856 
16857       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
16858       // allowed in C++, but warn if its declaration is inside
16859       // extern "C" block.
16860       if (ZeroSize) {
16861         Diag(RecLoc, getLangOpts().CPlusPlus ?
16862                          diag::warn_zero_size_struct_union_in_extern_c :
16863                          diag::warn_zero_size_struct_union_compat)
16864           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
16865       }
16866 
16867       // Structs without named members are extension in C (C99 6.7.2.1p7),
16868       // but are accepted by GCC.
16869       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
16870         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
16871                                diag::ext_no_named_members_in_struct_union)
16872           << Record->isUnion();
16873       }
16874     }
16875   } else {
16876     ObjCIvarDecl **ClsFields =
16877       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
16878     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
16879       ID->setEndOfDefinitionLoc(RBrac);
16880       // Add ivar's to class's DeclContext.
16881       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16882         ClsFields[i]->setLexicalDeclContext(ID);
16883         ID->addDecl(ClsFields[i]);
16884       }
16885       // Must enforce the rule that ivars in the base classes may not be
16886       // duplicates.
16887       if (ID->getSuperClass())
16888         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
16889     } else if (ObjCImplementationDecl *IMPDecl =
16890                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16891       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
16892       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
16893         // Ivar declared in @implementation never belongs to the implementation.
16894         // Only it is in implementation's lexical context.
16895         ClsFields[I]->setLexicalDeclContext(IMPDecl);
16896       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
16897       IMPDecl->setIvarLBraceLoc(LBrac);
16898       IMPDecl->setIvarRBraceLoc(RBrac);
16899     } else if (ObjCCategoryDecl *CDecl =
16900                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16901       // case of ivars in class extension; all other cases have been
16902       // reported as errors elsewhere.
16903       // FIXME. Class extension does not have a LocEnd field.
16904       // CDecl->setLocEnd(RBrac);
16905       // Add ivar's to class extension's DeclContext.
16906       // Diagnose redeclaration of private ivars.
16907       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
16908       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16909         if (IDecl) {
16910           if (const ObjCIvarDecl *ClsIvar =
16911               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
16912             Diag(ClsFields[i]->getLocation(),
16913                  diag::err_duplicate_ivar_declaration);
16914             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
16915             continue;
16916           }
16917           for (const auto *Ext : IDecl->known_extensions()) {
16918             if (const ObjCIvarDecl *ClsExtIvar
16919                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
16920               Diag(ClsFields[i]->getLocation(),
16921                    diag::err_duplicate_ivar_declaration);
16922               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
16923               continue;
16924             }
16925           }
16926         }
16927         ClsFields[i]->setLexicalDeclContext(CDecl);
16928         CDecl->addDecl(ClsFields[i]);
16929       }
16930       CDecl->setIvarLBraceLoc(LBrac);
16931       CDecl->setIvarRBraceLoc(RBrac);
16932     }
16933   }
16934 }
16935 
16936 /// Determine whether the given integral value is representable within
16937 /// the given type T.
16938 static bool isRepresentableIntegerValue(ASTContext &Context,
16939                                         llvm::APSInt &Value,
16940                                         QualType T) {
16941   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
16942          "Integral type required!");
16943   unsigned BitWidth = Context.getIntWidth(T);
16944 
16945   if (Value.isUnsigned() || Value.isNonNegative()) {
16946     if (T->isSignedIntegerOrEnumerationType())
16947       --BitWidth;
16948     return Value.getActiveBits() <= BitWidth;
16949   }
16950   return Value.getMinSignedBits() <= BitWidth;
16951 }
16952 
16953 // Given an integral type, return the next larger integral type
16954 // (or a NULL type of no such type exists).
16955 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
16956   // FIXME: Int128/UInt128 support, which also needs to be introduced into
16957   // enum checking below.
16958   assert((T->isIntegralType(Context) ||
16959          T->isEnumeralType()) && "Integral type required!");
16960   const unsigned NumTypes = 4;
16961   QualType SignedIntegralTypes[NumTypes] = {
16962     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
16963   };
16964   QualType UnsignedIntegralTypes[NumTypes] = {
16965     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
16966     Context.UnsignedLongLongTy
16967   };
16968 
16969   unsigned BitWidth = Context.getTypeSize(T);
16970   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
16971                                                         : UnsignedIntegralTypes;
16972   for (unsigned I = 0; I != NumTypes; ++I)
16973     if (Context.getTypeSize(Types[I]) > BitWidth)
16974       return Types[I];
16975 
16976   return QualType();
16977 }
16978 
16979 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
16980                                           EnumConstantDecl *LastEnumConst,
16981                                           SourceLocation IdLoc,
16982                                           IdentifierInfo *Id,
16983                                           Expr *Val) {
16984   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16985   llvm::APSInt EnumVal(IntWidth);
16986   QualType EltTy;
16987 
16988   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
16989     Val = nullptr;
16990 
16991   if (Val)
16992     Val = DefaultLvalueConversion(Val).get();
16993 
16994   if (Val) {
16995     if (Enum->isDependentType() || Val->isTypeDependent())
16996       EltTy = Context.DependentTy;
16997     else {
16998       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
16999         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
17000         // constant-expression in the enumerator-definition shall be a converted
17001         // constant expression of the underlying type.
17002         EltTy = Enum->getIntegerType();
17003         ExprResult Converted =
17004           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
17005                                            CCEK_Enumerator);
17006         if (Converted.isInvalid())
17007           Val = nullptr;
17008         else
17009           Val = Converted.get();
17010       } else if (!Val->isValueDependent() &&
17011                  !(Val = VerifyIntegerConstantExpression(Val,
17012                                                          &EnumVal).get())) {
17013         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
17014       } else {
17015         if (Enum->isComplete()) {
17016           EltTy = Enum->getIntegerType();
17017 
17018           // In Obj-C and Microsoft mode, require the enumeration value to be
17019           // representable in the underlying type of the enumeration. In C++11,
17020           // we perform a non-narrowing conversion as part of converted constant
17021           // expression checking.
17022           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17023             if (Context.getTargetInfo()
17024                     .getTriple()
17025                     .isWindowsMSVCEnvironment()) {
17026               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
17027             } else {
17028               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
17029             }
17030           }
17031 
17032           // Cast to the underlying type.
17033           Val = ImpCastExprToType(Val, EltTy,
17034                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
17035                                                          : CK_IntegralCast)
17036                     .get();
17037         } else if (getLangOpts().CPlusPlus) {
17038           // C++11 [dcl.enum]p5:
17039           //   If the underlying type is not fixed, the type of each enumerator
17040           //   is the type of its initializing value:
17041           //     - If an initializer is specified for an enumerator, the
17042           //       initializing value has the same type as the expression.
17043           EltTy = Val->getType();
17044         } else {
17045           // C99 6.7.2.2p2:
17046           //   The expression that defines the value of an enumeration constant
17047           //   shall be an integer constant expression that has a value
17048           //   representable as an int.
17049 
17050           // Complain if the value is not representable in an int.
17051           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
17052             Diag(IdLoc, diag::ext_enum_value_not_int)
17053               << EnumVal.toString(10) << Val->getSourceRange()
17054               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
17055           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
17056             // Force the type of the expression to 'int'.
17057             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
17058           }
17059           EltTy = Val->getType();
17060         }
17061       }
17062     }
17063   }
17064 
17065   if (!Val) {
17066     if (Enum->isDependentType())
17067       EltTy = Context.DependentTy;
17068     else if (!LastEnumConst) {
17069       // C++0x [dcl.enum]p5:
17070       //   If the underlying type is not fixed, the type of each enumerator
17071       //   is the type of its initializing value:
17072       //     - If no initializer is specified for the first enumerator, the
17073       //       initializing value has an unspecified integral type.
17074       //
17075       // GCC uses 'int' for its unspecified integral type, as does
17076       // C99 6.7.2.2p3.
17077       if (Enum->isFixed()) {
17078         EltTy = Enum->getIntegerType();
17079       }
17080       else {
17081         EltTy = Context.IntTy;
17082       }
17083     } else {
17084       // Assign the last value + 1.
17085       EnumVal = LastEnumConst->getInitVal();
17086       ++EnumVal;
17087       EltTy = LastEnumConst->getType();
17088 
17089       // Check for overflow on increment.
17090       if (EnumVal < LastEnumConst->getInitVal()) {
17091         // C++0x [dcl.enum]p5:
17092         //   If the underlying type is not fixed, the type of each enumerator
17093         //   is the type of its initializing value:
17094         //
17095         //     - Otherwise the type of the initializing value is the same as
17096         //       the type of the initializing value of the preceding enumerator
17097         //       unless the incremented value is not representable in that type,
17098         //       in which case the type is an unspecified integral type
17099         //       sufficient to contain the incremented value. If no such type
17100         //       exists, the program is ill-formed.
17101         QualType T = getNextLargerIntegralType(Context, EltTy);
17102         if (T.isNull() || Enum->isFixed()) {
17103           // There is no integral type larger enough to represent this
17104           // value. Complain, then allow the value to wrap around.
17105           EnumVal = LastEnumConst->getInitVal();
17106           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
17107           ++EnumVal;
17108           if (Enum->isFixed())
17109             // When the underlying type is fixed, this is ill-formed.
17110             Diag(IdLoc, diag::err_enumerator_wrapped)
17111               << EnumVal.toString(10)
17112               << EltTy;
17113           else
17114             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
17115               << EnumVal.toString(10);
17116         } else {
17117           EltTy = T;
17118         }
17119 
17120         // Retrieve the last enumerator's value, extent that type to the
17121         // type that is supposed to be large enough to represent the incremented
17122         // value, then increment.
17123         EnumVal = LastEnumConst->getInitVal();
17124         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17125         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
17126         ++EnumVal;
17127 
17128         // If we're not in C++, diagnose the overflow of enumerator values,
17129         // which in C99 means that the enumerator value is not representable in
17130         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
17131         // permits enumerator values that are representable in some larger
17132         // integral type.
17133         if (!getLangOpts().CPlusPlus && !T.isNull())
17134           Diag(IdLoc, diag::warn_enum_value_overflow);
17135       } else if (!getLangOpts().CPlusPlus &&
17136                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17137         // Enforce C99 6.7.2.2p2 even when we compute the next value.
17138         Diag(IdLoc, diag::ext_enum_value_not_int)
17139           << EnumVal.toString(10) << 1;
17140       }
17141     }
17142   }
17143 
17144   if (!EltTy->isDependentType()) {
17145     // Make the enumerator value match the signedness and size of the
17146     // enumerator's type.
17147     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
17148     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17149   }
17150 
17151   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
17152                                   Val, EnumVal);
17153 }
17154 
17155 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
17156                                                 SourceLocation IILoc) {
17157   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
17158       !getLangOpts().CPlusPlus)
17159     return SkipBodyInfo();
17160 
17161   // We have an anonymous enum definition. Look up the first enumerator to
17162   // determine if we should merge the definition with an existing one and
17163   // skip the body.
17164   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
17165                                          forRedeclarationInCurContext());
17166   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
17167   if (!PrevECD)
17168     return SkipBodyInfo();
17169 
17170   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
17171   NamedDecl *Hidden;
17172   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
17173     SkipBodyInfo Skip;
17174     Skip.Previous = Hidden;
17175     return Skip;
17176   }
17177 
17178   return SkipBodyInfo();
17179 }
17180 
17181 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
17182                               SourceLocation IdLoc, IdentifierInfo *Id,
17183                               const ParsedAttributesView &Attrs,
17184                               SourceLocation EqualLoc, Expr *Val) {
17185   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
17186   EnumConstantDecl *LastEnumConst =
17187     cast_or_null<EnumConstantDecl>(lastEnumConst);
17188 
17189   // The scope passed in may not be a decl scope.  Zip up the scope tree until
17190   // we find one that is.
17191   S = getNonFieldDeclScope(S);
17192 
17193   // Verify that there isn't already something declared with this name in this
17194   // scope.
17195   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
17196   LookupName(R, S);
17197   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
17198 
17199   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17200     // Maybe we will complain about the shadowed template parameter.
17201     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
17202     // Just pretend that we didn't see the previous declaration.
17203     PrevDecl = nullptr;
17204   }
17205 
17206   // C++ [class.mem]p15:
17207   // If T is the name of a class, then each of the following shall have a name
17208   // different from T:
17209   // - every enumerator of every member of class T that is an unscoped
17210   // enumerated type
17211   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
17212     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
17213                             DeclarationNameInfo(Id, IdLoc));
17214 
17215   EnumConstantDecl *New =
17216     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
17217   if (!New)
17218     return nullptr;
17219 
17220   if (PrevDecl) {
17221     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
17222       // Check for other kinds of shadowing not already handled.
17223       CheckShadow(New, PrevDecl, R);
17224     }
17225 
17226     // When in C++, we may get a TagDecl with the same name; in this case the
17227     // enum constant will 'hide' the tag.
17228     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
17229            "Received TagDecl when not in C++!");
17230     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
17231       if (isa<EnumConstantDecl>(PrevDecl))
17232         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
17233       else
17234         Diag(IdLoc, diag::err_redefinition) << Id;
17235       notePreviousDefinition(PrevDecl, IdLoc);
17236       return nullptr;
17237     }
17238   }
17239 
17240   // Process attributes.
17241   ProcessDeclAttributeList(S, New, Attrs);
17242   AddPragmaAttributes(S, New);
17243 
17244   // Register this decl in the current scope stack.
17245   New->setAccess(TheEnumDecl->getAccess());
17246   PushOnScopeChains(New, S);
17247 
17248   ActOnDocumentableDecl(New);
17249 
17250   return New;
17251 }
17252 
17253 // Returns true when the enum initial expression does not trigger the
17254 // duplicate enum warning.  A few common cases are exempted as follows:
17255 // Element2 = Element1
17256 // Element2 = Element1 + 1
17257 // Element2 = Element1 - 1
17258 // Where Element2 and Element1 are from the same enum.
17259 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
17260   Expr *InitExpr = ECD->getInitExpr();
17261   if (!InitExpr)
17262     return true;
17263   InitExpr = InitExpr->IgnoreImpCasts();
17264 
17265   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
17266     if (!BO->isAdditiveOp())
17267       return true;
17268     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
17269     if (!IL)
17270       return true;
17271     if (IL->getValue() != 1)
17272       return true;
17273 
17274     InitExpr = BO->getLHS();
17275   }
17276 
17277   // This checks if the elements are from the same enum.
17278   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
17279   if (!DRE)
17280     return true;
17281 
17282   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
17283   if (!EnumConstant)
17284     return true;
17285 
17286   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
17287       Enum)
17288     return true;
17289 
17290   return false;
17291 }
17292 
17293 // Emits a warning when an element is implicitly set a value that
17294 // a previous element has already been set to.
17295 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
17296                                         EnumDecl *Enum, QualType EnumType) {
17297   // Avoid anonymous enums
17298   if (!Enum->getIdentifier())
17299     return;
17300 
17301   // Only check for small enums.
17302   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
17303     return;
17304 
17305   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
17306     return;
17307 
17308   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
17309   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
17310 
17311   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
17312   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
17313 
17314   // Use int64_t as a key to avoid needing special handling for DenseMap keys.
17315   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
17316     llvm::APSInt Val = D->getInitVal();
17317     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
17318   };
17319 
17320   DuplicatesVector DupVector;
17321   ValueToVectorMap EnumMap;
17322 
17323   // Populate the EnumMap with all values represented by enum constants without
17324   // an initializer.
17325   for (auto *Element : Elements) {
17326     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
17327 
17328     // Null EnumConstantDecl means a previous diagnostic has been emitted for
17329     // this constant.  Skip this enum since it may be ill-formed.
17330     if (!ECD) {
17331       return;
17332     }
17333 
17334     // Constants with initalizers are handled in the next loop.
17335     if (ECD->getInitExpr())
17336       continue;
17337 
17338     // Duplicate values are handled in the next loop.
17339     EnumMap.insert({EnumConstantToKey(ECD), ECD});
17340   }
17341 
17342   if (EnumMap.size() == 0)
17343     return;
17344 
17345   // Create vectors for any values that has duplicates.
17346   for (auto *Element : Elements) {
17347     // The last loop returned if any constant was null.
17348     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
17349     if (!ValidDuplicateEnum(ECD, Enum))
17350       continue;
17351 
17352     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
17353     if (Iter == EnumMap.end())
17354       continue;
17355 
17356     DeclOrVector& Entry = Iter->second;
17357     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
17358       // Ensure constants are different.
17359       if (D == ECD)
17360         continue;
17361 
17362       // Create new vector and push values onto it.
17363       auto Vec = std::make_unique<ECDVector>();
17364       Vec->push_back(D);
17365       Vec->push_back(ECD);
17366 
17367       // Update entry to point to the duplicates vector.
17368       Entry = Vec.get();
17369 
17370       // Store the vector somewhere we can consult later for quick emission of
17371       // diagnostics.
17372       DupVector.emplace_back(std::move(Vec));
17373       continue;
17374     }
17375 
17376     ECDVector *Vec = Entry.get<ECDVector*>();
17377     // Make sure constants are not added more than once.
17378     if (*Vec->begin() == ECD)
17379       continue;
17380 
17381     Vec->push_back(ECD);
17382   }
17383 
17384   // Emit diagnostics.
17385   for (const auto &Vec : DupVector) {
17386     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
17387 
17388     // Emit warning for one enum constant.
17389     auto *FirstECD = Vec->front();
17390     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
17391       << FirstECD << FirstECD->getInitVal().toString(10)
17392       << FirstECD->getSourceRange();
17393 
17394     // Emit one note for each of the remaining enum constants with
17395     // the same value.
17396     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
17397       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
17398         << ECD << ECD->getInitVal().toString(10)
17399         << ECD->getSourceRange();
17400   }
17401 }
17402 
17403 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
17404                              bool AllowMask) const {
17405   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
17406   assert(ED->isCompleteDefinition() && "expected enum definition");
17407 
17408   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
17409   llvm::APInt &FlagBits = R.first->second;
17410 
17411   if (R.second) {
17412     for (auto *E : ED->enumerators()) {
17413       const auto &EVal = E->getInitVal();
17414       // Only single-bit enumerators introduce new flag values.
17415       if (EVal.isPowerOf2())
17416         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
17417     }
17418   }
17419 
17420   // A value is in a flag enum if either its bits are a subset of the enum's
17421   // flag bits (the first condition) or we are allowing masks and the same is
17422   // true of its complement (the second condition). When masks are allowed, we
17423   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
17424   //
17425   // While it's true that any value could be used as a mask, the assumption is
17426   // that a mask will have all of the insignificant bits set. Anything else is
17427   // likely a logic error.
17428   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
17429   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
17430 }
17431 
17432 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
17433                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
17434                          const ParsedAttributesView &Attrs) {
17435   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
17436   QualType EnumType = Context.getTypeDeclType(Enum);
17437 
17438   ProcessDeclAttributeList(S, Enum, Attrs);
17439 
17440   if (Enum->isDependentType()) {
17441     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17442       EnumConstantDecl *ECD =
17443         cast_or_null<EnumConstantDecl>(Elements[i]);
17444       if (!ECD) continue;
17445 
17446       ECD->setType(EnumType);
17447     }
17448 
17449     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
17450     return;
17451   }
17452 
17453   // TODO: If the result value doesn't fit in an int, it must be a long or long
17454   // long value.  ISO C does not support this, but GCC does as an extension,
17455   // emit a warning.
17456   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17457   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
17458   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
17459 
17460   // Verify that all the values are okay, compute the size of the values, and
17461   // reverse the list.
17462   unsigned NumNegativeBits = 0;
17463   unsigned NumPositiveBits = 0;
17464 
17465   // Keep track of whether all elements have type int.
17466   bool AllElementsInt = true;
17467 
17468   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17469     EnumConstantDecl *ECD =
17470       cast_or_null<EnumConstantDecl>(Elements[i]);
17471     if (!ECD) continue;  // Already issued a diagnostic.
17472 
17473     const llvm::APSInt &InitVal = ECD->getInitVal();
17474 
17475     // Keep track of the size of positive and negative values.
17476     if (InitVal.isUnsigned() || InitVal.isNonNegative())
17477       NumPositiveBits = std::max(NumPositiveBits,
17478                                  (unsigned)InitVal.getActiveBits());
17479     else
17480       NumNegativeBits = std::max(NumNegativeBits,
17481                                  (unsigned)InitVal.getMinSignedBits());
17482 
17483     // Keep track of whether every enum element has type int (very common).
17484     if (AllElementsInt)
17485       AllElementsInt = ECD->getType() == Context.IntTy;
17486   }
17487 
17488   // Figure out the type that should be used for this enum.
17489   QualType BestType;
17490   unsigned BestWidth;
17491 
17492   // C++0x N3000 [conv.prom]p3:
17493   //   An rvalue of an unscoped enumeration type whose underlying
17494   //   type is not fixed can be converted to an rvalue of the first
17495   //   of the following types that can represent all the values of
17496   //   the enumeration: int, unsigned int, long int, unsigned long
17497   //   int, long long int, or unsigned long long int.
17498   // C99 6.4.4.3p2:
17499   //   An identifier declared as an enumeration constant has type int.
17500   // The C99 rule is modified by a gcc extension
17501   QualType BestPromotionType;
17502 
17503   bool Packed = Enum->hasAttr<PackedAttr>();
17504   // -fshort-enums is the equivalent to specifying the packed attribute on all
17505   // enum definitions.
17506   if (LangOpts.ShortEnums)
17507     Packed = true;
17508 
17509   // If the enum already has a type because it is fixed or dictated by the
17510   // target, promote that type instead of analyzing the enumerators.
17511   if (Enum->isComplete()) {
17512     BestType = Enum->getIntegerType();
17513     if (BestType->isPromotableIntegerType())
17514       BestPromotionType = Context.getPromotedIntegerType(BestType);
17515     else
17516       BestPromotionType = BestType;
17517 
17518     BestWidth = Context.getIntWidth(BestType);
17519   }
17520   else if (NumNegativeBits) {
17521     // If there is a negative value, figure out the smallest integer type (of
17522     // int/long/longlong) that fits.
17523     // If it's packed, check also if it fits a char or a short.
17524     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
17525       BestType = Context.SignedCharTy;
17526       BestWidth = CharWidth;
17527     } else if (Packed && NumNegativeBits <= ShortWidth &&
17528                NumPositiveBits < ShortWidth) {
17529       BestType = Context.ShortTy;
17530       BestWidth = ShortWidth;
17531     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
17532       BestType = Context.IntTy;
17533       BestWidth = IntWidth;
17534     } else {
17535       BestWidth = Context.getTargetInfo().getLongWidth();
17536 
17537       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
17538         BestType = Context.LongTy;
17539       } else {
17540         BestWidth = Context.getTargetInfo().getLongLongWidth();
17541 
17542         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
17543           Diag(Enum->getLocation(), diag::ext_enum_too_large);
17544         BestType = Context.LongLongTy;
17545       }
17546     }
17547     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
17548   } else {
17549     // If there is no negative value, figure out the smallest type that fits
17550     // all of the enumerator values.
17551     // If it's packed, check also if it fits a char or a short.
17552     if (Packed && NumPositiveBits <= CharWidth) {
17553       BestType = Context.UnsignedCharTy;
17554       BestPromotionType = Context.IntTy;
17555       BestWidth = CharWidth;
17556     } else if (Packed && NumPositiveBits <= ShortWidth) {
17557       BestType = Context.UnsignedShortTy;
17558       BestPromotionType = Context.IntTy;
17559       BestWidth = ShortWidth;
17560     } else if (NumPositiveBits <= IntWidth) {
17561       BestType = Context.UnsignedIntTy;
17562       BestWidth = IntWidth;
17563       BestPromotionType
17564         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17565                            ? Context.UnsignedIntTy : Context.IntTy;
17566     } else if (NumPositiveBits <=
17567                (BestWidth = Context.getTargetInfo().getLongWidth())) {
17568       BestType = Context.UnsignedLongTy;
17569       BestPromotionType
17570         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17571                            ? Context.UnsignedLongTy : Context.LongTy;
17572     } else {
17573       BestWidth = Context.getTargetInfo().getLongLongWidth();
17574       assert(NumPositiveBits <= BestWidth &&
17575              "How could an initializer get larger than ULL?");
17576       BestType = Context.UnsignedLongLongTy;
17577       BestPromotionType
17578         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17579                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
17580     }
17581   }
17582 
17583   // Loop over all of the enumerator constants, changing their types to match
17584   // the type of the enum if needed.
17585   for (auto *D : Elements) {
17586     auto *ECD = cast_or_null<EnumConstantDecl>(D);
17587     if (!ECD) continue;  // Already issued a diagnostic.
17588 
17589     // Standard C says the enumerators have int type, but we allow, as an
17590     // extension, the enumerators to be larger than int size.  If each
17591     // enumerator value fits in an int, type it as an int, otherwise type it the
17592     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
17593     // that X has type 'int', not 'unsigned'.
17594 
17595     // Determine whether the value fits into an int.
17596     llvm::APSInt InitVal = ECD->getInitVal();
17597 
17598     // If it fits into an integer type, force it.  Otherwise force it to match
17599     // the enum decl type.
17600     QualType NewTy;
17601     unsigned NewWidth;
17602     bool NewSign;
17603     if (!getLangOpts().CPlusPlus &&
17604         !Enum->isFixed() &&
17605         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
17606       NewTy = Context.IntTy;
17607       NewWidth = IntWidth;
17608       NewSign = true;
17609     } else if (ECD->getType() == BestType) {
17610       // Already the right type!
17611       if (getLangOpts().CPlusPlus)
17612         // C++ [dcl.enum]p4: Following the closing brace of an
17613         // enum-specifier, each enumerator has the type of its
17614         // enumeration.
17615         ECD->setType(EnumType);
17616       continue;
17617     } else {
17618       NewTy = BestType;
17619       NewWidth = BestWidth;
17620       NewSign = BestType->isSignedIntegerOrEnumerationType();
17621     }
17622 
17623     // Adjust the APSInt value.
17624     InitVal = InitVal.extOrTrunc(NewWidth);
17625     InitVal.setIsSigned(NewSign);
17626     ECD->setInitVal(InitVal);
17627 
17628     // Adjust the Expr initializer and type.
17629     if (ECD->getInitExpr() &&
17630         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
17631       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
17632                                                 CK_IntegralCast,
17633                                                 ECD->getInitExpr(),
17634                                                 /*base paths*/ nullptr,
17635                                                 VK_RValue));
17636     if (getLangOpts().CPlusPlus)
17637       // C++ [dcl.enum]p4: Following the closing brace of an
17638       // enum-specifier, each enumerator has the type of its
17639       // enumeration.
17640       ECD->setType(EnumType);
17641     else
17642       ECD->setType(NewTy);
17643   }
17644 
17645   Enum->completeDefinition(BestType, BestPromotionType,
17646                            NumPositiveBits, NumNegativeBits);
17647 
17648   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
17649 
17650   if (Enum->isClosedFlag()) {
17651     for (Decl *D : Elements) {
17652       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
17653       if (!ECD) continue;  // Already issued a diagnostic.
17654 
17655       llvm::APSInt InitVal = ECD->getInitVal();
17656       if (InitVal != 0 && !InitVal.isPowerOf2() &&
17657           !IsValueInFlagEnum(Enum, InitVal, true))
17658         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
17659           << ECD << Enum;
17660     }
17661   }
17662 
17663   // Now that the enum type is defined, ensure it's not been underaligned.
17664   if (Enum->hasAttrs())
17665     CheckAlignasUnderalignment(Enum);
17666 }
17667 
17668 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
17669                                   SourceLocation StartLoc,
17670                                   SourceLocation EndLoc) {
17671   StringLiteral *AsmString = cast<StringLiteral>(expr);
17672 
17673   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
17674                                                    AsmString, StartLoc,
17675                                                    EndLoc);
17676   CurContext->addDecl(New);
17677   return New;
17678 }
17679 
17680 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
17681                                       IdentifierInfo* AliasName,
17682                                       SourceLocation PragmaLoc,
17683                                       SourceLocation NameLoc,
17684                                       SourceLocation AliasNameLoc) {
17685   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
17686                                          LookupOrdinaryName);
17687   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
17688                            AttributeCommonInfo::AS_Pragma);
17689   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
17690       Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
17691 
17692   // If a declaration that:
17693   // 1) declares a function or a variable
17694   // 2) has external linkage
17695   // already exists, add a label attribute to it.
17696   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17697     if (isDeclExternC(PrevDecl))
17698       PrevDecl->addAttr(Attr);
17699     else
17700       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
17701           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
17702   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
17703   } else
17704     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
17705 }
17706 
17707 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
17708                              SourceLocation PragmaLoc,
17709                              SourceLocation NameLoc) {
17710   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
17711 
17712   if (PrevDecl) {
17713     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
17714   } else {
17715     (void)WeakUndeclaredIdentifiers.insert(
17716       std::pair<IdentifierInfo*,WeakInfo>
17717         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
17718   }
17719 }
17720 
17721 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
17722                                 IdentifierInfo* AliasName,
17723                                 SourceLocation PragmaLoc,
17724                                 SourceLocation NameLoc,
17725                                 SourceLocation AliasNameLoc) {
17726   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
17727                                     LookupOrdinaryName);
17728   WeakInfo W = WeakInfo(Name, NameLoc);
17729 
17730   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17731     if (!PrevDecl->hasAttr<AliasAttr>())
17732       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
17733         DeclApplyPragmaWeak(TUScope, ND, W);
17734   } else {
17735     (void)WeakUndeclaredIdentifiers.insert(
17736       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
17737   }
17738 }
17739 
17740 Decl *Sema::getObjCDeclContext() const {
17741   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
17742 }
17743 
17744 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD) {
17745   // Templates are emitted when they're instantiated.
17746   if (FD->isDependentContext())
17747     return FunctionEmissionStatus::TemplateDiscarded;
17748 
17749   FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown;
17750   if (LangOpts.OpenMPIsDevice) {
17751     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
17752         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
17753     if (DevTy.hasValue()) {
17754       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
17755         OMPES = FunctionEmissionStatus::OMPDiscarded;
17756       else if (DeviceKnownEmittedFns.count(FD) > 0)
17757         OMPES = FunctionEmissionStatus::Emitted;
17758     }
17759   } else if (LangOpts.OpenMP) {
17760     // In OpenMP 4.5 all the functions are host functions.
17761     if (LangOpts.OpenMP <= 45) {
17762       OMPES = FunctionEmissionStatus::Emitted;
17763     } else {
17764       Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
17765           OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
17766       // In OpenMP 5.0 or above, DevTy may be changed later by
17767       // #pragma omp declare target to(*) device_type(*). Therefore DevTy
17768       // having no value does not imply host. The emission status will be
17769       // checked again at the end of compilation unit.
17770       if (DevTy.hasValue()) {
17771         if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
17772           OMPES = FunctionEmissionStatus::OMPDiscarded;
17773         } else if (DeviceKnownEmittedFns.count(FD) > 0) {
17774           OMPES = FunctionEmissionStatus::Emitted;
17775         }
17776       }
17777     }
17778   }
17779   if (OMPES == FunctionEmissionStatus::OMPDiscarded ||
17780       (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA))
17781     return OMPES;
17782 
17783   if (LangOpts.CUDA) {
17784     // When compiling for device, host functions are never emitted.  Similarly,
17785     // when compiling for host, device and global functions are never emitted.
17786     // (Technically, we do emit a host-side stub for global functions, but this
17787     // doesn't count for our purposes here.)
17788     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
17789     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
17790       return FunctionEmissionStatus::CUDADiscarded;
17791     if (!LangOpts.CUDAIsDevice &&
17792         (T == Sema::CFT_Device || T == Sema::CFT_Global))
17793       return FunctionEmissionStatus::CUDADiscarded;
17794 
17795     // Check whether this function is externally visible -- if so, it's
17796     // known-emitted.
17797     //
17798     // We have to check the GVA linkage of the function's *definition* -- if we
17799     // only have a declaration, we don't know whether or not the function will
17800     // be emitted, because (say) the definition could include "inline".
17801     FunctionDecl *Def = FD->getDefinition();
17802 
17803     if (Def &&
17804         !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def))
17805         && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted))
17806       return FunctionEmissionStatus::Emitted;
17807   }
17808 
17809   // Otherwise, the function is known-emitted if it's in our set of
17810   // known-emitted functions.
17811   return (DeviceKnownEmittedFns.count(FD) > 0)
17812              ? FunctionEmissionStatus::Emitted
17813              : FunctionEmissionStatus::Unknown;
17814 }
17815 
17816 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
17817   // Host-side references to a __global__ function refer to the stub, so the
17818   // function itself is never emitted and therefore should not be marked.
17819   // If we have host fn calls kernel fn calls host+device, the HD function
17820   // does not get instantiated on the host. We model this by omitting at the
17821   // call to the kernel from the callgraph. This ensures that, when compiling
17822   // for host, only HD functions actually called from the host get marked as
17823   // known-emitted.
17824   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
17825          IdentifyCUDATarget(Callee) == CFT_Global;
17826 }
17827