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/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/NonTrivialTypeVisitor.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/Basic/Builtins.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
36 #include "clang/Sema/CXXFieldCollector.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/DelayedDiagnostic.h"
39 #include "clang/Sema/Initialization.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
44 #include "clang/Sema/SemaInternal.h"
45 #include "clang/Sema/Template.h"
46 #include "llvm/ADT/SmallString.h"
47 #include "llvm/ADT/Triple.h"
48 #include <algorithm>
49 #include <cstring>
50 #include <functional>
51 #include <unordered_map>
52 
53 using namespace clang;
54 using namespace sema;
55 
56 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
57   if (OwnedType) {
58     Decl *Group[2] = { OwnedType, Ptr };
59     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
60   }
61 
62   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
63 }
64 
65 namespace {
66 
67 class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
68  public:
69    TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
70                         bool AllowTemplates = false,
71                         bool AllowNonTemplates = true)
72        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
73          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
74      WantExpressionKeywords = false;
75      WantCXXNamedCasts = false;
76      WantRemainingKeywords = false;
77   }
78 
79   bool ValidateCandidate(const TypoCorrection &candidate) override {
80     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
81       if (!AllowInvalidDecl && ND->isInvalidDecl())
82         return false;
83 
84       if (getAsTypeTemplateDecl(ND))
85         return AllowTemplates;
86 
87       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
88       if (!IsType)
89         return false;
90 
91       if (AllowNonTemplates)
92         return true;
93 
94       // An injected-class-name of a class template (specialization) is valid
95       // as a template or as a non-template.
96       if (AllowTemplates) {
97         auto *RD = dyn_cast<CXXRecordDecl>(ND);
98         if (!RD || !RD->isInjectedClassName())
99           return false;
100         RD = cast<CXXRecordDecl>(RD->getDeclContext());
101         return RD->getDescribedClassTemplate() ||
102                isa<ClassTemplateSpecializationDecl>(RD);
103       }
104 
105       return false;
106     }
107 
108     return !WantClassName && candidate.isKeyword();
109   }
110 
111   std::unique_ptr<CorrectionCandidateCallback> clone() override {
112     return std::make_unique<TypeNameValidatorCCC>(*this);
113   }
114 
115  private:
116   bool AllowInvalidDecl;
117   bool WantClassName;
118   bool AllowTemplates;
119   bool AllowNonTemplates;
120 };
121 
122 } // end anonymous namespace
123 
124 /// Determine whether the token kind starts a simple-type-specifier.
125 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
126   switch (Kind) {
127   // FIXME: Take into account the current language when deciding whether a
128   // token kind is a valid type specifier
129   case tok::kw_short:
130   case tok::kw_long:
131   case tok::kw___int64:
132   case tok::kw___int128:
133   case tok::kw_signed:
134   case tok::kw_unsigned:
135   case tok::kw_void:
136   case tok::kw_char:
137   case tok::kw_int:
138   case tok::kw_half:
139   case tok::kw_float:
140   case tok::kw_double:
141   case tok::kw___bf16:
142   case tok::kw__Float16:
143   case tok::kw___float128:
144   case tok::kw_wchar_t:
145   case tok::kw_bool:
146   case tok::kw___underlying_type:
147   case tok::kw___auto_type:
148     return true;
149 
150   case tok::annot_typename:
151   case tok::kw_char16_t:
152   case tok::kw_char32_t:
153   case tok::kw_typeof:
154   case tok::annot_decltype:
155   case tok::kw_decltype:
156     return getLangOpts().CPlusPlus;
157 
158   case tok::kw_char8_t:
159     return getLangOpts().Char8;
160 
161   default:
162     break;
163   }
164 
165   return false;
166 }
167 
168 namespace {
169 enum class UnqualifiedTypeNameLookupResult {
170   NotFound,
171   FoundNonType,
172   FoundType
173 };
174 } // end anonymous namespace
175 
176 /// Tries to perform unqualified lookup of the type decls in bases for
177 /// dependent class.
178 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
179 /// type decl, \a FoundType if only type decls are found.
180 static UnqualifiedTypeNameLookupResult
181 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
182                                 SourceLocation NameLoc,
183                                 const CXXRecordDecl *RD) {
184   if (!RD->hasDefinition())
185     return UnqualifiedTypeNameLookupResult::NotFound;
186   // Look for type decls in base classes.
187   UnqualifiedTypeNameLookupResult FoundTypeDecl =
188       UnqualifiedTypeNameLookupResult::NotFound;
189   for (const auto &Base : RD->bases()) {
190     const CXXRecordDecl *BaseRD = nullptr;
191     if (auto *BaseTT = Base.getType()->getAs<TagType>())
192       BaseRD = BaseTT->getAsCXXRecordDecl();
193     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
194       // Look for type decls in dependent base classes that have known primary
195       // templates.
196       if (!TST || !TST->isDependentType())
197         continue;
198       auto *TD = TST->getTemplateName().getAsTemplateDecl();
199       if (!TD)
200         continue;
201       if (auto *BasePrimaryTemplate =
202           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
203         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
204           BaseRD = BasePrimaryTemplate;
205         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
206           if (const ClassTemplatePartialSpecializationDecl *PS =
207                   CTD->findPartialSpecialization(Base.getType()))
208             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
209               BaseRD = PS;
210         }
211       }
212     }
213     if (BaseRD) {
214       for (NamedDecl *ND : BaseRD->lookup(&II)) {
215         if (!isa<TypeDecl>(ND))
216           return UnqualifiedTypeNameLookupResult::FoundNonType;
217         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
218       }
219       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
220         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
221         case UnqualifiedTypeNameLookupResult::FoundNonType:
222           return UnqualifiedTypeNameLookupResult::FoundNonType;
223         case UnqualifiedTypeNameLookupResult::FoundType:
224           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
225           break;
226         case UnqualifiedTypeNameLookupResult::NotFound:
227           break;
228         }
229       }
230     }
231   }
232 
233   return FoundTypeDecl;
234 }
235 
236 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
237                                                       const IdentifierInfo &II,
238                                                       SourceLocation NameLoc) {
239   // Lookup in the parent class template context, if any.
240   const CXXRecordDecl *RD = nullptr;
241   UnqualifiedTypeNameLookupResult FoundTypeDecl =
242       UnqualifiedTypeNameLookupResult::NotFound;
243   for (DeclContext *DC = S.CurContext;
244        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
245        DC = DC->getParent()) {
246     // Look for type decls in dependent base classes that have known primary
247     // templates.
248     RD = dyn_cast<CXXRecordDecl>(DC);
249     if (RD && RD->getDescribedClassTemplate())
250       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
251   }
252   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
253     return nullptr;
254 
255   // We found some types in dependent base classes.  Recover as if the user
256   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
257   // lookup during template instantiation.
258   S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
259 
260   ASTContext &Context = S.Context;
261   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
262                                           cast<Type>(Context.getRecordType(RD)));
263   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
264 
265   CXXScopeSpec SS;
266   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
267 
268   TypeLocBuilder Builder;
269   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
270   DepTL.setNameLoc(NameLoc);
271   DepTL.setElaboratedKeywordLoc(SourceLocation());
272   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
273   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
274 }
275 
276 /// If the identifier refers to a type name within this scope,
277 /// return the declaration of that type.
278 ///
279 /// This routine performs ordinary name lookup of the identifier II
280 /// within the given scope, with optional C++ scope specifier SS, to
281 /// determine whether the name refers to a type. If so, returns an
282 /// opaque pointer (actually a QualType) corresponding to that
283 /// type. Otherwise, returns NULL.
284 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
285                              Scope *S, CXXScopeSpec *SS,
286                              bool isClassName, bool HasTrailingDot,
287                              ParsedType ObjectTypePtr,
288                              bool IsCtorOrDtorName,
289                              bool WantNontrivialTypeSourceInfo,
290                              bool IsClassTemplateDeductionContext,
291                              IdentifierInfo **CorrectedII) {
292   // FIXME: Consider allowing this outside C++1z mode as an extension.
293   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
294                               getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
295                               !isClassName && !HasTrailingDot;
296 
297   // Determine where we will perform name lookup.
298   DeclContext *LookupCtx = nullptr;
299   if (ObjectTypePtr) {
300     QualType ObjectType = ObjectTypePtr.get();
301     if (ObjectType->isRecordType())
302       LookupCtx = computeDeclContext(ObjectType);
303   } else if (SS && SS->isNotEmpty()) {
304     LookupCtx = computeDeclContext(*SS, false);
305 
306     if (!LookupCtx) {
307       if (isDependentScopeSpecifier(*SS)) {
308         // C++ [temp.res]p3:
309         //   A qualified-id that refers to a type and in which the
310         //   nested-name-specifier depends on a template-parameter (14.6.2)
311         //   shall be prefixed by the keyword typename to indicate that the
312         //   qualified-id denotes a type, forming an
313         //   elaborated-type-specifier (7.1.5.3).
314         //
315         // We therefore do not perform any name lookup if the result would
316         // refer to a member of an unknown specialization.
317         if (!isClassName && !IsCtorOrDtorName)
318           return nullptr;
319 
320         // We know from the grammar that this name refers to a type,
321         // so build a dependent node to describe the type.
322         if (WantNontrivialTypeSourceInfo)
323           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
324 
325         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
326         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
327                                        II, NameLoc);
328         return ParsedType::make(T);
329       }
330 
331       return nullptr;
332     }
333 
334     if (!LookupCtx->isDependentContext() &&
335         RequireCompleteDeclContext(*SS, LookupCtx))
336       return nullptr;
337   }
338 
339   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
340   // lookup for class-names.
341   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
342                                       LookupOrdinaryName;
343   LookupResult Result(*this, &II, NameLoc, Kind);
344   if (LookupCtx) {
345     // Perform "qualified" name lookup into the declaration context we
346     // computed, which is either the type of the base of a member access
347     // expression or the declaration context associated with a prior
348     // nested-name-specifier.
349     LookupQualifiedName(Result, LookupCtx);
350 
351     if (ObjectTypePtr && Result.empty()) {
352       // C++ [basic.lookup.classref]p3:
353       //   If the unqualified-id is ~type-name, the type-name is looked up
354       //   in the context of the entire postfix-expression. If the type T of
355       //   the object expression is of a class type C, the type-name is also
356       //   looked up in the scope of class C. At least one of the lookups shall
357       //   find a name that refers to (possibly cv-qualified) T.
358       LookupName(Result, S);
359     }
360   } else {
361     // Perform unqualified name lookup.
362     LookupName(Result, S);
363 
364     // For unqualified lookup in a class template in MSVC mode, look into
365     // dependent base classes where the primary class template is known.
366     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
367       if (ParsedType TypeInBase =
368               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
369         return TypeInBase;
370     }
371   }
372 
373   NamedDecl *IIDecl = nullptr;
374   switch (Result.getResultKind()) {
375   case LookupResult::NotFound:
376   case LookupResult::NotFoundInCurrentInstantiation:
377     if (CorrectedII) {
378       TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
379                                AllowDeducedTemplate);
380       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
381                                               S, SS, CCC, CTK_ErrorRecovery);
382       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
383       TemplateTy Template;
384       bool MemberOfUnknownSpecialization;
385       UnqualifiedId TemplateName;
386       TemplateName.setIdentifier(NewII, NameLoc);
387       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
388       CXXScopeSpec NewSS, *NewSSPtr = SS;
389       if (SS && NNS) {
390         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
391         NewSSPtr = &NewSS;
392       }
393       if (Correction && (NNS || NewII != &II) &&
394           // Ignore a correction to a template type as the to-be-corrected
395           // identifier is not a template (typo correction for template names
396           // is handled elsewhere).
397           !(getLangOpts().CPlusPlus && NewSSPtr &&
398             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
399                            Template, MemberOfUnknownSpecialization))) {
400         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
401                                     isClassName, HasTrailingDot, ObjectTypePtr,
402                                     IsCtorOrDtorName,
403                                     WantNontrivialTypeSourceInfo,
404                                     IsClassTemplateDeductionContext);
405         if (Ty) {
406           diagnoseTypo(Correction,
407                        PDiag(diag::err_unknown_type_or_class_name_suggest)
408                          << Result.getLookupName() << isClassName);
409           if (SS && NNS)
410             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
411           *CorrectedII = NewII;
412           return Ty;
413         }
414       }
415     }
416     // If typo correction failed or was not performed, fall through
417     LLVM_FALLTHROUGH;
418   case LookupResult::FoundOverloaded:
419   case LookupResult::FoundUnresolvedValue:
420     Result.suppressDiagnostics();
421     return nullptr;
422 
423   case LookupResult::Ambiguous:
424     // Recover from type-hiding ambiguities by hiding the type.  We'll
425     // do the lookup again when looking for an object, and we can
426     // diagnose the error then.  If we don't do this, then the error
427     // about hiding the type will be immediately followed by an error
428     // that only makes sense if the identifier was treated like a type.
429     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
430       Result.suppressDiagnostics();
431       return nullptr;
432     }
433 
434     // Look to see if we have a type anywhere in the list of results.
435     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
436          Res != ResEnd; ++Res) {
437       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
438           (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
439         if (!IIDecl || (*Res)->getLocation() < IIDecl->getLocation())
440           IIDecl = *Res;
441       }
442     }
443 
444     if (!IIDecl) {
445       // None of the entities we found is a type, so there is no way
446       // to even assume that the result is a type. In this case, don't
447       // complain about the ambiguity. The parser will either try to
448       // perform this lookup again (e.g., as an object name), which
449       // will produce the ambiguity, or will complain that it expected
450       // a type name.
451       Result.suppressDiagnostics();
452       return nullptr;
453     }
454 
455     // We found a type within the ambiguous lookup; diagnose the
456     // ambiguity and then return that type. This might be the right
457     // answer, or it might not be, but it suppresses any attempt to
458     // perform the name lookup again.
459     break;
460 
461   case LookupResult::Found:
462     IIDecl = Result.getFoundDecl();
463     break;
464   }
465 
466   assert(IIDecl && "Didn't find decl");
467 
468   QualType T;
469   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
470     // C++ [class.qual]p2: A lookup that would find the injected-class-name
471     // instead names the constructors of the class, except when naming a class.
472     // This is ill-formed when we're not actually forming a ctor or dtor name.
473     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
474     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
475     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
476         FoundRD->isInjectedClassName() &&
477         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
478       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
479           << &II << /*Type*/1;
480 
481     DiagnoseUseOfDecl(IIDecl, NameLoc);
482 
483     T = Context.getTypeDeclType(TD);
484     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
485   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
486     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
487     if (!HasTrailingDot)
488       T = Context.getObjCInterfaceType(IDecl);
489   } else if (AllowDeducedTemplate) {
490     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
491       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
492                                                        QualType(), false);
493   }
494 
495   if (T.isNull()) {
496     // If it's not plausibly a type, suppress diagnostics.
497     Result.suppressDiagnostics();
498     return nullptr;
499   }
500 
501   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
502   // constructor or destructor name (in such a case, the scope specifier
503   // will be attached to the enclosing Expr or Decl node).
504   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
505       !isa<ObjCInterfaceDecl>(IIDecl)) {
506     if (WantNontrivialTypeSourceInfo) {
507       // Construct a type with type-source information.
508       TypeLocBuilder Builder;
509       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
510 
511       T = getElaboratedType(ETK_None, *SS, T);
512       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
513       ElabTL.setElaboratedKeywordLoc(SourceLocation());
514       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
515       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
516     } else {
517       T = getElaboratedType(ETK_None, *SS, T);
518     }
519   }
520 
521   return ParsedType::make(T);
522 }
523 
524 // Builds a fake NNS for the given decl context.
525 static NestedNameSpecifier *
526 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
527   for (;; DC = DC->getLookupParent()) {
528     DC = DC->getPrimaryContext();
529     auto *ND = dyn_cast<NamespaceDecl>(DC);
530     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
531       return NestedNameSpecifier::Create(Context, nullptr, ND);
532     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
533       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
534                                          RD->getTypeForDecl());
535     else if (isa<TranslationUnitDecl>(DC))
536       return NestedNameSpecifier::GlobalSpecifier(Context);
537   }
538   llvm_unreachable("something isn't in TU scope?");
539 }
540 
541 /// Find the parent class with dependent bases of the innermost enclosing method
542 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
543 /// up allowing unqualified dependent type names at class-level, which MSVC
544 /// correctly rejects.
545 static const CXXRecordDecl *
546 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
547   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
548     DC = DC->getPrimaryContext();
549     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
550       if (MD->getParent()->hasAnyDependentBases())
551         return MD->getParent();
552   }
553   return nullptr;
554 }
555 
556 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
557                                           SourceLocation NameLoc,
558                                           bool IsTemplateTypeArg) {
559   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
560 
561   NestedNameSpecifier *NNS = nullptr;
562   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
563     // If we weren't able to parse a default template argument, delay lookup
564     // until instantiation time by making a non-dependent DependentTypeName. We
565     // pretend we saw a NestedNameSpecifier referring to the current scope, and
566     // lookup is retried.
567     // FIXME: This hurts our diagnostic quality, since we get errors like "no
568     // type named 'Foo' in 'current_namespace'" when the user didn't write any
569     // name specifiers.
570     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
571     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
572   } else if (const CXXRecordDecl *RD =
573                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
574     // Build a DependentNameType that will perform lookup into RD at
575     // instantiation time.
576     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
577                                       RD->getTypeForDecl());
578 
579     // Diagnose that this identifier was undeclared, and retry the lookup during
580     // template instantiation.
581     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
582                                                                       << RD;
583   } else {
584     // This is not a situation that we should recover from.
585     return ParsedType();
586   }
587 
588   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
589 
590   // Build type location information.  We synthesized the qualifier, so we have
591   // to build a fake NestedNameSpecifierLoc.
592   NestedNameSpecifierLocBuilder NNSLocBuilder;
593   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
594   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
595 
596   TypeLocBuilder Builder;
597   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
598   DepTL.setNameLoc(NameLoc);
599   DepTL.setElaboratedKeywordLoc(SourceLocation());
600   DepTL.setQualifierLoc(QualifierLoc);
601   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
602 }
603 
604 /// isTagName() - This method is called *for error recovery purposes only*
605 /// to determine if the specified name is a valid tag name ("struct foo").  If
606 /// so, this returns the TST for the tag corresponding to it (TST_enum,
607 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
608 /// cases in C where the user forgot to specify the tag.
609 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
610   // Do a tag name lookup in this scope.
611   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
612   LookupName(R, S, false);
613   R.suppressDiagnostics();
614   if (R.getResultKind() == LookupResult::Found)
615     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
616       switch (TD->getTagKind()) {
617       case TTK_Struct: return DeclSpec::TST_struct;
618       case TTK_Interface: return DeclSpec::TST_interface;
619       case TTK_Union:  return DeclSpec::TST_union;
620       case TTK_Class:  return DeclSpec::TST_class;
621       case TTK_Enum:   return DeclSpec::TST_enum;
622       }
623     }
624 
625   return DeclSpec::TST_unspecified;
626 }
627 
628 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
629 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
630 /// then downgrade the missing typename error to a warning.
631 /// This is needed for MSVC compatibility; Example:
632 /// @code
633 /// template<class T> class A {
634 /// public:
635 ///   typedef int TYPE;
636 /// };
637 /// template<class T> class B : public A<T> {
638 /// public:
639 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
640 /// };
641 /// @endcode
642 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
643   if (CurContext->isRecord()) {
644     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
645       return true;
646 
647     const Type *Ty = SS->getScopeRep()->getAsType();
648 
649     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
650     for (const auto &Base : RD->bases())
651       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
652         return true;
653     return S->isFunctionPrototypeScope();
654   }
655   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
656 }
657 
658 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
659                                    SourceLocation IILoc,
660                                    Scope *S,
661                                    CXXScopeSpec *SS,
662                                    ParsedType &SuggestedType,
663                                    bool IsTemplateName) {
664   // Don't report typename errors for editor placeholders.
665   if (II->isEditorPlaceholder())
666     return;
667   // We don't have anything to suggest (yet).
668   SuggestedType = nullptr;
669 
670   // There may have been a typo in the name of the type. Look up typo
671   // results, in case we have something that we can suggest.
672   TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
673                            /*AllowTemplates=*/IsTemplateName,
674                            /*AllowNonTemplates=*/!IsTemplateName);
675   if (TypoCorrection Corrected =
676           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
677                       CCC, CTK_ErrorRecovery)) {
678     // FIXME: Support error recovery for the template-name case.
679     bool CanRecover = !IsTemplateName;
680     if (Corrected.isKeyword()) {
681       // We corrected to a keyword.
682       diagnoseTypo(Corrected,
683                    PDiag(IsTemplateName ? diag::err_no_template_suggest
684                                         : diag::err_unknown_typename_suggest)
685                        << II);
686       II = Corrected.getCorrectionAsIdentifierInfo();
687     } else {
688       // We found a similarly-named type or interface; suggest that.
689       if (!SS || !SS->isSet()) {
690         diagnoseTypo(Corrected,
691                      PDiag(IsTemplateName ? diag::err_no_template_suggest
692                                           : diag::err_unknown_typename_suggest)
693                          << II, CanRecover);
694       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
695         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
696         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
697                                 II->getName().equals(CorrectedStr);
698         diagnoseTypo(Corrected,
699                      PDiag(IsTemplateName
700                                ? diag::err_no_member_template_suggest
701                                : diag::err_unknown_nested_typename_suggest)
702                          << II << DC << DroppedSpecifier << SS->getRange(),
703                      CanRecover);
704       } else {
705         llvm_unreachable("could not have corrected a typo here");
706       }
707 
708       if (!CanRecover)
709         return;
710 
711       CXXScopeSpec tmpSS;
712       if (Corrected.getCorrectionSpecifier())
713         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
714                           SourceRange(IILoc));
715       // FIXME: Support class template argument deduction here.
716       SuggestedType =
717           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
718                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
719                       /*IsCtorOrDtorName=*/false,
720                       /*WantNontrivialTypeSourceInfo=*/true);
721     }
722     return;
723   }
724 
725   if (getLangOpts().CPlusPlus && !IsTemplateName) {
726     // See if II is a class template that the user forgot to pass arguments to.
727     UnqualifiedId Name;
728     Name.setIdentifier(II, IILoc);
729     CXXScopeSpec EmptySS;
730     TemplateTy TemplateResult;
731     bool MemberOfUnknownSpecialization;
732     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
733                        Name, nullptr, true, TemplateResult,
734                        MemberOfUnknownSpecialization) == TNK_Type_template) {
735       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
736       return;
737     }
738   }
739 
740   // FIXME: Should we move the logic that tries to recover from a missing tag
741   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
742 
743   if (!SS || (!SS->isSet() && !SS->isInvalid()))
744     Diag(IILoc, IsTemplateName ? diag::err_no_template
745                                : diag::err_unknown_typename)
746         << II;
747   else if (DeclContext *DC = computeDeclContext(*SS, false))
748     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
749                                : diag::err_typename_nested_not_found)
750         << II << DC << SS->getRange();
751   else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
752     SuggestedType =
753         ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
754   } else if (isDependentScopeSpecifier(*SS)) {
755     unsigned DiagID = diag::err_typename_missing;
756     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
757       DiagID = diag::ext_typename_missing;
758 
759     Diag(SS->getRange().getBegin(), DiagID)
760       << SS->getScopeRep() << II->getName()
761       << SourceRange(SS->getRange().getBegin(), IILoc)
762       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
763     SuggestedType = ActOnTypenameType(S, SourceLocation(),
764                                       *SS, *II, IILoc).get();
765   } else {
766     assert(SS && SS->isInvalid() &&
767            "Invalid scope specifier has already been diagnosed");
768   }
769 }
770 
771 /// Determine whether the given result set contains either a type name
772 /// or
773 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
774   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
775                        NextToken.is(tok::less);
776 
777   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
778     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
779       return true;
780 
781     if (CheckTemplate && isa<TemplateDecl>(*I))
782       return true;
783   }
784 
785   return false;
786 }
787 
788 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
789                                     Scope *S, CXXScopeSpec &SS,
790                                     IdentifierInfo *&Name,
791                                     SourceLocation NameLoc) {
792   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
793   SemaRef.LookupParsedName(R, S, &SS);
794   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
795     StringRef FixItTagName;
796     switch (Tag->getTagKind()) {
797       case TTK_Class:
798         FixItTagName = "class ";
799         break;
800 
801       case TTK_Enum:
802         FixItTagName = "enum ";
803         break;
804 
805       case TTK_Struct:
806         FixItTagName = "struct ";
807         break;
808 
809       case TTK_Interface:
810         FixItTagName = "__interface ";
811         break;
812 
813       case TTK_Union:
814         FixItTagName = "union ";
815         break;
816     }
817 
818     StringRef TagName = FixItTagName.drop_back();
819     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
820       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
821       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
822 
823     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
824          I != IEnd; ++I)
825       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
826         << Name << TagName;
827 
828     // Replace lookup results with just the tag decl.
829     Result.clear(Sema::LookupTagName);
830     SemaRef.LookupParsedName(Result, S, &SS);
831     return true;
832   }
833 
834   return false;
835 }
836 
837 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
838 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
839                                   QualType T, SourceLocation NameLoc) {
840   ASTContext &Context = S.Context;
841 
842   TypeLocBuilder Builder;
843   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
844 
845   T = S.getElaboratedType(ETK_None, SS, T);
846   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
847   ElabTL.setElaboratedKeywordLoc(SourceLocation());
848   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
849   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
850 }
851 
852 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
853                                             IdentifierInfo *&Name,
854                                             SourceLocation NameLoc,
855                                             const Token &NextToken,
856                                             CorrectionCandidateCallback *CCC) {
857   DeclarationNameInfo NameInfo(Name, NameLoc);
858   ObjCMethodDecl *CurMethod = getCurMethodDecl();
859 
860   assert(NextToken.isNot(tok::coloncolon) &&
861          "parse nested name specifiers before calling ClassifyName");
862   if (getLangOpts().CPlusPlus && SS.isSet() &&
863       isCurrentClassName(*Name, S, &SS)) {
864     // Per [class.qual]p2, this names the constructors of SS, not the
865     // injected-class-name. We don't have a classification for that.
866     // There's not much point caching this result, since the parser
867     // will reject it later.
868     return NameClassification::Unknown();
869   }
870 
871   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
872   LookupParsedName(Result, S, &SS, !CurMethod);
873 
874   if (SS.isInvalid())
875     return NameClassification::Error();
876 
877   // For unqualified lookup in a class template in MSVC mode, look into
878   // dependent base classes where the primary class template is known.
879   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
880     if (ParsedType TypeInBase =
881             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
882       return TypeInBase;
883   }
884 
885   // Perform lookup for Objective-C instance variables (including automatically
886   // synthesized instance variables), if we're in an Objective-C method.
887   // FIXME: This lookup really, really needs to be folded in to the normal
888   // unqualified lookup mechanism.
889   if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
890     DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
891     if (Ivar.isInvalid())
892       return NameClassification::Error();
893     if (Ivar.isUsable())
894       return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
895 
896     // We defer builtin creation until after ivar lookup inside ObjC methods.
897     if (Result.empty())
898       LookupBuiltin(Result);
899   }
900 
901   bool SecondTry = false;
902   bool IsFilteredTemplateName = false;
903 
904 Corrected:
905   switch (Result.getResultKind()) {
906   case LookupResult::NotFound:
907     // If an unqualified-id is followed by a '(', then we have a function
908     // call.
909     if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
910       // In C++, this is an ADL-only call.
911       // FIXME: Reference?
912       if (getLangOpts().CPlusPlus)
913         return NameClassification::UndeclaredNonType();
914 
915       // C90 6.3.2.2:
916       //   If the expression that precedes the parenthesized argument list in a
917       //   function call consists solely of an identifier, and if no
918       //   declaration is visible for this identifier, the identifier is
919       //   implicitly declared exactly as if, in the innermost block containing
920       //   the function call, the declaration
921       //
922       //     extern int identifier ();
923       //
924       //   appeared.
925       //
926       // We also allow this in C99 as an extension.
927       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
928         return NameClassification::NonType(D);
929     }
930 
931     if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
932       // In C++20 onwards, this could be an ADL-only call to a function
933       // template, and we're required to assume that this is a template name.
934       //
935       // FIXME: Find a way to still do typo correction in this case.
936       TemplateName Template =
937           Context.getAssumedTemplateName(NameInfo.getName());
938       return NameClassification::UndeclaredTemplate(Template);
939     }
940 
941     // In C, we first see whether there is a tag type by the same name, in
942     // which case it's likely that the user just forgot to write "enum",
943     // "struct", or "union".
944     if (!getLangOpts().CPlusPlus && !SecondTry &&
945         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
946       break;
947     }
948 
949     // Perform typo correction to determine if there is another name that is
950     // close to this name.
951     if (!SecondTry && CCC) {
952       SecondTry = true;
953       if (TypoCorrection Corrected =
954               CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
955                           &SS, *CCC, CTK_ErrorRecovery)) {
956         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
957         unsigned QualifiedDiag = diag::err_no_member_suggest;
958 
959         NamedDecl *FirstDecl = Corrected.getFoundDecl();
960         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
961         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
962             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
963           UnqualifiedDiag = diag::err_no_template_suggest;
964           QualifiedDiag = diag::err_no_member_template_suggest;
965         } else if (UnderlyingFirstDecl &&
966                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
967                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
968                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
969           UnqualifiedDiag = diag::err_unknown_typename_suggest;
970           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
971         }
972 
973         if (SS.isEmpty()) {
974           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
975         } else {// FIXME: is this even reachable? Test it.
976           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
977           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
978                                   Name->getName().equals(CorrectedStr);
979           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
980                                     << Name << computeDeclContext(SS, false)
981                                     << DroppedSpecifier << SS.getRange());
982         }
983 
984         // Update the name, so that the caller has the new name.
985         Name = Corrected.getCorrectionAsIdentifierInfo();
986 
987         // Typo correction corrected to a keyword.
988         if (Corrected.isKeyword())
989           return Name;
990 
991         // Also update the LookupResult...
992         // FIXME: This should probably go away at some point
993         Result.clear();
994         Result.setLookupName(Corrected.getCorrection());
995         if (FirstDecl)
996           Result.addDecl(FirstDecl);
997 
998         // If we found an Objective-C instance variable, let
999         // LookupInObjCMethod build the appropriate expression to
1000         // reference the ivar.
1001         // FIXME: This is a gross hack.
1002         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1003           DeclResult R =
1004               LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1005           if (R.isInvalid())
1006             return NameClassification::Error();
1007           if (R.isUsable())
1008             return NameClassification::NonType(Ivar);
1009         }
1010 
1011         goto Corrected;
1012       }
1013     }
1014 
1015     // We failed to correct; just fall through and let the parser deal with it.
1016     Result.suppressDiagnostics();
1017     return NameClassification::Unknown();
1018 
1019   case LookupResult::NotFoundInCurrentInstantiation: {
1020     // We performed name lookup into the current instantiation, and there were
1021     // dependent bases, so we treat this result the same way as any other
1022     // dependent nested-name-specifier.
1023 
1024     // C++ [temp.res]p2:
1025     //   A name used in a template declaration or definition and that is
1026     //   dependent on a template-parameter is assumed not to name a type
1027     //   unless the applicable name lookup finds a type name or the name is
1028     //   qualified by the keyword typename.
1029     //
1030     // FIXME: If the next token is '<', we might want to ask the parser to
1031     // perform some heroics to see if we actually have a
1032     // template-argument-list, which would indicate a missing 'template'
1033     // keyword here.
1034     return NameClassification::DependentNonType();
1035   }
1036 
1037   case LookupResult::Found:
1038   case LookupResult::FoundOverloaded:
1039   case LookupResult::FoundUnresolvedValue:
1040     break;
1041 
1042   case LookupResult::Ambiguous:
1043     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1044         hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1045                                       /*AllowDependent=*/false)) {
1046       // C++ [temp.local]p3:
1047       //   A lookup that finds an injected-class-name (10.2) can result in an
1048       //   ambiguity in certain cases (for example, if it is found in more than
1049       //   one base class). If all of the injected-class-names that are found
1050       //   refer to specializations of the same class template, and if the name
1051       //   is followed by a template-argument-list, the reference refers to the
1052       //   class template itself and not a specialization thereof, and is not
1053       //   ambiguous.
1054       //
1055       // This filtering can make an ambiguous result into an unambiguous one,
1056       // so try again after filtering out template names.
1057       FilterAcceptableTemplateNames(Result);
1058       if (!Result.isAmbiguous()) {
1059         IsFilteredTemplateName = true;
1060         break;
1061       }
1062     }
1063 
1064     // Diagnose the ambiguity and return an error.
1065     return NameClassification::Error();
1066   }
1067 
1068   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1069       (IsFilteredTemplateName ||
1070        hasAnyAcceptableTemplateNames(
1071            Result, /*AllowFunctionTemplates=*/true,
1072            /*AllowDependent=*/false,
1073            /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1074                getLangOpts().CPlusPlus20))) {
1075     // C++ [temp.names]p3:
1076     //   After name lookup (3.4) finds that a name is a template-name or that
1077     //   an operator-function-id or a literal- operator-id refers to a set of
1078     //   overloaded functions any member of which is a function template if
1079     //   this is followed by a <, the < is always taken as the delimiter of a
1080     //   template-argument-list and never as the less-than operator.
1081     // C++2a [temp.names]p2:
1082     //   A name is also considered to refer to a template if it is an
1083     //   unqualified-id followed by a < and name lookup finds either one
1084     //   or more functions or finds nothing.
1085     if (!IsFilteredTemplateName)
1086       FilterAcceptableTemplateNames(Result);
1087 
1088     bool IsFunctionTemplate;
1089     bool IsVarTemplate;
1090     TemplateName Template;
1091     if (Result.end() - Result.begin() > 1) {
1092       IsFunctionTemplate = true;
1093       Template = Context.getOverloadedTemplateName(Result.begin(),
1094                                                    Result.end());
1095     } else if (!Result.empty()) {
1096       auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1097           *Result.begin(), /*AllowFunctionTemplates=*/true,
1098           /*AllowDependent=*/false));
1099       IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1100       IsVarTemplate = isa<VarTemplateDecl>(TD);
1101 
1102       if (SS.isNotEmpty())
1103         Template =
1104             Context.getQualifiedTemplateName(SS.getScopeRep(),
1105                                              /*TemplateKeyword=*/false, TD);
1106       else
1107         Template = TemplateName(TD);
1108     } else {
1109       // All results were non-template functions. This is a function template
1110       // name.
1111       IsFunctionTemplate = true;
1112       Template = Context.getAssumedTemplateName(NameInfo.getName());
1113     }
1114 
1115     if (IsFunctionTemplate) {
1116       // Function templates always go through overload resolution, at which
1117       // point we'll perform the various checks (e.g., accessibility) we need
1118       // to based on which function we selected.
1119       Result.suppressDiagnostics();
1120 
1121       return NameClassification::FunctionTemplate(Template);
1122     }
1123 
1124     return IsVarTemplate ? NameClassification::VarTemplate(Template)
1125                          : NameClassification::TypeTemplate(Template);
1126   }
1127 
1128   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1129   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1130     DiagnoseUseOfDecl(Type, NameLoc);
1131     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1132     QualType T = Context.getTypeDeclType(Type);
1133     if (SS.isNotEmpty())
1134       return buildNestedType(*this, SS, T, NameLoc);
1135     return ParsedType::make(T);
1136   }
1137 
1138   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1139   if (!Class) {
1140     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1141     if (ObjCCompatibleAliasDecl *Alias =
1142             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1143       Class = Alias->getClassInterface();
1144   }
1145 
1146   if (Class) {
1147     DiagnoseUseOfDecl(Class, NameLoc);
1148 
1149     if (NextToken.is(tok::period)) {
1150       // Interface. <something> is parsed as a property reference expression.
1151       // Just return "unknown" as a fall-through for now.
1152       Result.suppressDiagnostics();
1153       return NameClassification::Unknown();
1154     }
1155 
1156     QualType T = Context.getObjCInterfaceType(Class);
1157     return ParsedType::make(T);
1158   }
1159 
1160   if (isa<ConceptDecl>(FirstDecl))
1161     return NameClassification::Concept(
1162         TemplateName(cast<TemplateDecl>(FirstDecl)));
1163 
1164   // We can have a type template here if we're classifying a template argument.
1165   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1166       !isa<VarTemplateDecl>(FirstDecl))
1167     return NameClassification::TypeTemplate(
1168         TemplateName(cast<TemplateDecl>(FirstDecl)));
1169 
1170   // Check for a tag type hidden by a non-type decl in a few cases where it
1171   // seems likely a type is wanted instead of the non-type that was found.
1172   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1173   if ((NextToken.is(tok::identifier) ||
1174        (NextIsOp &&
1175         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1176       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1177     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1178     DiagnoseUseOfDecl(Type, NameLoc);
1179     QualType T = Context.getTypeDeclType(Type);
1180     if (SS.isNotEmpty())
1181       return buildNestedType(*this, SS, T, NameLoc);
1182     return ParsedType::make(T);
1183   }
1184 
1185   // If we already know which single declaration is referenced, just annotate
1186   // that declaration directly. Defer resolving even non-overloaded class
1187   // member accesses, as we need to defer certain access checks until we know
1188   // the context.
1189   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1190   if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember())
1191     return NameClassification::NonType(Result.getRepresentativeDecl());
1192 
1193   // Otherwise, this is an overload set that we will need to resolve later.
1194   Result.suppressDiagnostics();
1195   return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1196       Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1197       Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1198       Result.begin(), Result.end()));
1199 }
1200 
1201 ExprResult
1202 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1203                                              SourceLocation NameLoc) {
1204   assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1205   CXXScopeSpec SS;
1206   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1207   return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1208 }
1209 
1210 ExprResult
1211 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1212                                             IdentifierInfo *Name,
1213                                             SourceLocation NameLoc,
1214                                             bool IsAddressOfOperand) {
1215   DeclarationNameInfo NameInfo(Name, NameLoc);
1216   return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1217                                     NameInfo, IsAddressOfOperand,
1218                                     /*TemplateArgs=*/nullptr);
1219 }
1220 
1221 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1222                                               NamedDecl *Found,
1223                                               SourceLocation NameLoc,
1224                                               const Token &NextToken) {
1225   if (getCurMethodDecl() && SS.isEmpty())
1226     if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1227       return BuildIvarRefExpr(S, NameLoc, Ivar);
1228 
1229   // Reconstruct the lookup result.
1230   LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1231   Result.addDecl(Found);
1232   Result.resolveKind();
1233 
1234   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1235   return BuildDeclarationNameExpr(SS, Result, ADL);
1236 }
1237 
1238 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1239   // For an implicit class member access, transform the result into a member
1240   // access expression if necessary.
1241   auto *ULE = cast<UnresolvedLookupExpr>(E);
1242   if ((*ULE->decls_begin())->isCXXClassMember()) {
1243     CXXScopeSpec SS;
1244     SS.Adopt(ULE->getQualifierLoc());
1245 
1246     // Reconstruct the lookup result.
1247     LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1248                         LookupOrdinaryName);
1249     Result.setNamingClass(ULE->getNamingClass());
1250     for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1251       Result.addDecl(*I, I.getAccess());
1252     Result.resolveKind();
1253     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1254                                            nullptr, S);
1255   }
1256 
1257   // Otherwise, this is already in the form we needed, and no further checks
1258   // are necessary.
1259   return ULE;
1260 }
1261 
1262 Sema::TemplateNameKindForDiagnostics
1263 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1264   auto *TD = Name.getAsTemplateDecl();
1265   if (!TD)
1266     return TemplateNameKindForDiagnostics::DependentTemplate;
1267   if (isa<ClassTemplateDecl>(TD))
1268     return TemplateNameKindForDiagnostics::ClassTemplate;
1269   if (isa<FunctionTemplateDecl>(TD))
1270     return TemplateNameKindForDiagnostics::FunctionTemplate;
1271   if (isa<VarTemplateDecl>(TD))
1272     return TemplateNameKindForDiagnostics::VarTemplate;
1273   if (isa<TypeAliasTemplateDecl>(TD))
1274     return TemplateNameKindForDiagnostics::AliasTemplate;
1275   if (isa<TemplateTemplateParmDecl>(TD))
1276     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1277   if (isa<ConceptDecl>(TD))
1278     return TemplateNameKindForDiagnostics::Concept;
1279   return TemplateNameKindForDiagnostics::DependentTemplate;
1280 }
1281 
1282 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1283   assert(DC->getLexicalParent() == CurContext &&
1284       "The next DeclContext should be lexically contained in the current one.");
1285   CurContext = DC;
1286   S->setEntity(DC);
1287 }
1288 
1289 void Sema::PopDeclContext() {
1290   assert(CurContext && "DeclContext imbalance!");
1291 
1292   CurContext = CurContext->getLexicalParent();
1293   assert(CurContext && "Popped translation unit!");
1294 }
1295 
1296 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1297                                                                     Decl *D) {
1298   // Unlike PushDeclContext, the context to which we return is not necessarily
1299   // the containing DC of TD, because the new context will be some pre-existing
1300   // TagDecl definition instead of a fresh one.
1301   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1302   CurContext = cast<TagDecl>(D)->getDefinition();
1303   assert(CurContext && "skipping definition of undefined tag");
1304   // Start lookups from the parent of the current context; we don't want to look
1305   // into the pre-existing complete definition.
1306   S->setEntity(CurContext->getLookupParent());
1307   return Result;
1308 }
1309 
1310 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1311   CurContext = static_cast<decltype(CurContext)>(Context);
1312 }
1313 
1314 /// EnterDeclaratorContext - Used when we must lookup names in the context
1315 /// of a declarator's nested name specifier.
1316 ///
1317 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1318   // C++0x [basic.lookup.unqual]p13:
1319   //   A name used in the definition of a static data member of class
1320   //   X (after the qualified-id of the static member) is looked up as
1321   //   if the name was used in a member function of X.
1322   // C++0x [basic.lookup.unqual]p14:
1323   //   If a variable member of a namespace is defined outside of the
1324   //   scope of its namespace then any name used in the definition of
1325   //   the variable member (after the declarator-id) is looked up as
1326   //   if the definition of the variable member occurred in its
1327   //   namespace.
1328   // Both of these imply that we should push a scope whose context
1329   // is the semantic context of the declaration.  We can't use
1330   // PushDeclContext here because that context is not necessarily
1331   // lexically contained in the current context.  Fortunately,
1332   // the containing scope should have the appropriate information.
1333 
1334   assert(!S->getEntity() && "scope already has entity");
1335 
1336 #ifndef NDEBUG
1337   Scope *Ancestor = S->getParent();
1338   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1339   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1340 #endif
1341 
1342   CurContext = DC;
1343   S->setEntity(DC);
1344 
1345   if (S->getParent()->isTemplateParamScope()) {
1346     // Also set the corresponding entities for all immediately-enclosing
1347     // template parameter scopes.
1348     EnterTemplatedContext(S->getParent(), DC);
1349   }
1350 }
1351 
1352 void Sema::ExitDeclaratorContext(Scope *S) {
1353   assert(S->getEntity() == CurContext && "Context imbalance!");
1354 
1355   // Switch back to the lexical context.  The safety of this is
1356   // enforced by an assert in EnterDeclaratorContext.
1357   Scope *Ancestor = S->getParent();
1358   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1359   CurContext = Ancestor->getEntity();
1360 
1361   // We don't need to do anything with the scope, which is going to
1362   // disappear.
1363 }
1364 
1365 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1366   assert(S->isTemplateParamScope() &&
1367          "expected to be initializing a template parameter scope");
1368 
1369   // C++20 [temp.local]p7:
1370   //   In the definition of a member of a class template that appears outside
1371   //   of the class template definition, the name of a member of the class
1372   //   template hides the name of a template-parameter of any enclosing class
1373   //   templates (but not a template-parameter of the member if the member is a
1374   //   class or function template).
1375   // C++20 [temp.local]p9:
1376   //   In the definition of a class template or in the definition of a member
1377   //   of such a template that appears outside of the template definition, for
1378   //   each non-dependent base class (13.8.2.1), if the name of the base class
1379   //   or the name of a member of the base class is the same as the name of a
1380   //   template-parameter, the base class name or member name hides the
1381   //   template-parameter name (6.4.10).
1382   //
1383   // This means that a template parameter scope should be searched immediately
1384   // after searching the DeclContext for which it is a template parameter
1385   // scope. For example, for
1386   //   template<typename T> template<typename U> template<typename V>
1387   //     void N::A<T>::B<U>::f(...)
1388   // we search V then B<U> (and base classes) then U then A<T> (and base
1389   // classes) then T then N then ::.
1390   unsigned ScopeDepth = getTemplateDepth(S);
1391   for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1392     DeclContext *SearchDCAfterScope = DC;
1393     for (; DC; DC = DC->getLookupParent()) {
1394       if (const TemplateParameterList *TPL =
1395               cast<Decl>(DC)->getDescribedTemplateParams()) {
1396         unsigned DCDepth = TPL->getDepth() + 1;
1397         if (DCDepth > ScopeDepth)
1398           continue;
1399         if (ScopeDepth == DCDepth)
1400           SearchDCAfterScope = DC = DC->getLookupParent();
1401         break;
1402       }
1403     }
1404     S->setLookupEntity(SearchDCAfterScope);
1405   }
1406 }
1407 
1408 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1409   // We assume that the caller has already called
1410   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1411   FunctionDecl *FD = D->getAsFunction();
1412   if (!FD)
1413     return;
1414 
1415   // Same implementation as PushDeclContext, but enters the context
1416   // from the lexical parent, rather than the top-level class.
1417   assert(CurContext == FD->getLexicalParent() &&
1418     "The next DeclContext should be lexically contained in the current one.");
1419   CurContext = FD;
1420   S->setEntity(CurContext);
1421 
1422   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1423     ParmVarDecl *Param = FD->getParamDecl(P);
1424     // If the parameter has an identifier, then add it to the scope
1425     if (Param->getIdentifier()) {
1426       S->AddDecl(Param);
1427       IdResolver.AddDecl(Param);
1428     }
1429   }
1430 }
1431 
1432 void Sema::ActOnExitFunctionContext() {
1433   // Same implementation as PopDeclContext, but returns to the lexical parent,
1434   // rather than the top-level class.
1435   assert(CurContext && "DeclContext imbalance!");
1436   CurContext = CurContext->getLexicalParent();
1437   assert(CurContext && "Popped translation unit!");
1438 }
1439 
1440 /// Determine whether we allow overloading of the function
1441 /// PrevDecl with another declaration.
1442 ///
1443 /// This routine determines whether overloading is possible, not
1444 /// whether some new function is actually an overload. It will return
1445 /// true in C++ (where we can always provide overloads) or, as an
1446 /// extension, in C when the previous function is already an
1447 /// overloaded function declaration or has the "overloadable"
1448 /// attribute.
1449 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1450                                        ASTContext &Context,
1451                                        const FunctionDecl *New) {
1452   if (Context.getLangOpts().CPlusPlus)
1453     return true;
1454 
1455   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1456     return true;
1457 
1458   return Previous.getResultKind() == LookupResult::Found &&
1459          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1460           New->hasAttr<OverloadableAttr>());
1461 }
1462 
1463 /// Add this decl to the scope shadowed decl chains.
1464 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1465   // Move up the scope chain until we find the nearest enclosing
1466   // non-transparent context. The declaration will be introduced into this
1467   // scope.
1468   while (S->getEntity() && S->getEntity()->isTransparentContext())
1469     S = S->getParent();
1470 
1471   // Add scoped declarations into their context, so that they can be
1472   // found later. Declarations without a context won't be inserted
1473   // into any context.
1474   if (AddToContext)
1475     CurContext->addDecl(D);
1476 
1477   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1478   // are function-local declarations.
1479   if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1480     return;
1481 
1482   // Template instantiations should also not be pushed into scope.
1483   if (isa<FunctionDecl>(D) &&
1484       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1485     return;
1486 
1487   // If this replaces anything in the current scope,
1488   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1489                                IEnd = IdResolver.end();
1490   for (; I != IEnd; ++I) {
1491     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1492       S->RemoveDecl(*I);
1493       IdResolver.RemoveDecl(*I);
1494 
1495       // Should only need to replace one decl.
1496       break;
1497     }
1498   }
1499 
1500   S->AddDecl(D);
1501 
1502   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1503     // Implicitly-generated labels may end up getting generated in an order that
1504     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1505     // the label at the appropriate place in the identifier chain.
1506     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1507       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1508       if (IDC == CurContext) {
1509         if (!S->isDeclScope(*I))
1510           continue;
1511       } else if (IDC->Encloses(CurContext))
1512         break;
1513     }
1514 
1515     IdResolver.InsertDeclAfter(I, D);
1516   } else {
1517     IdResolver.AddDecl(D);
1518   }
1519   warnOnReservedIdentifier(D);
1520 }
1521 
1522 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1523                          bool AllowInlineNamespace) {
1524   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1525 }
1526 
1527 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1528   DeclContext *TargetDC = DC->getPrimaryContext();
1529   do {
1530     if (DeclContext *ScopeDC = S->getEntity())
1531       if (ScopeDC->getPrimaryContext() == TargetDC)
1532         return S;
1533   } while ((S = S->getParent()));
1534 
1535   return nullptr;
1536 }
1537 
1538 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1539                                             DeclContext*,
1540                                             ASTContext&);
1541 
1542 /// Filters out lookup results that don't fall within the given scope
1543 /// as determined by isDeclInScope.
1544 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1545                                 bool ConsiderLinkage,
1546                                 bool AllowInlineNamespace) {
1547   LookupResult::Filter F = R.makeFilter();
1548   while (F.hasNext()) {
1549     NamedDecl *D = F.next();
1550 
1551     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1552       continue;
1553 
1554     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1555       continue;
1556 
1557     F.erase();
1558   }
1559 
1560   F.done();
1561 }
1562 
1563 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1564 /// have compatible owning modules.
1565 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1566   // FIXME: The Modules TS is not clear about how friend declarations are
1567   // to be treated. It's not meaningful to have different owning modules for
1568   // linkage in redeclarations of the same entity, so for now allow the
1569   // redeclaration and change the owning modules to match.
1570   if (New->getFriendObjectKind() &&
1571       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1572     New->setLocalOwningModule(Old->getOwningModule());
1573     makeMergedDefinitionVisible(New);
1574     return false;
1575   }
1576 
1577   Module *NewM = New->getOwningModule();
1578   Module *OldM = Old->getOwningModule();
1579 
1580   if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1581     NewM = NewM->Parent;
1582   if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1583     OldM = OldM->Parent;
1584 
1585   if (NewM == OldM)
1586     return false;
1587 
1588   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1589   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1590   if (NewIsModuleInterface || OldIsModuleInterface) {
1591     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1592     //   if a declaration of D [...] appears in the purview of a module, all
1593     //   other such declarations shall appear in the purview of the same module
1594     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1595       << New
1596       << NewIsModuleInterface
1597       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1598       << OldIsModuleInterface
1599       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1600     Diag(Old->getLocation(), diag::note_previous_declaration);
1601     New->setInvalidDecl();
1602     return true;
1603   }
1604 
1605   return false;
1606 }
1607 
1608 static bool isUsingDecl(NamedDecl *D) {
1609   return isa<UsingShadowDecl>(D) ||
1610          isa<UnresolvedUsingTypenameDecl>(D) ||
1611          isa<UnresolvedUsingValueDecl>(D);
1612 }
1613 
1614 /// Removes using shadow declarations from the lookup results.
1615 static void RemoveUsingDecls(LookupResult &R) {
1616   LookupResult::Filter F = R.makeFilter();
1617   while (F.hasNext())
1618     if (isUsingDecl(F.next()))
1619       F.erase();
1620 
1621   F.done();
1622 }
1623 
1624 /// Check for this common pattern:
1625 /// @code
1626 /// class S {
1627 ///   S(const S&); // DO NOT IMPLEMENT
1628 ///   void operator=(const S&); // DO NOT IMPLEMENT
1629 /// };
1630 /// @endcode
1631 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1632   // FIXME: Should check for private access too but access is set after we get
1633   // the decl here.
1634   if (D->doesThisDeclarationHaveABody())
1635     return false;
1636 
1637   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1638     return CD->isCopyConstructor();
1639   return D->isCopyAssignmentOperator();
1640 }
1641 
1642 // We need this to handle
1643 //
1644 // typedef struct {
1645 //   void *foo() { return 0; }
1646 // } A;
1647 //
1648 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1649 // for example. If 'A', foo will have external linkage. If we have '*A',
1650 // foo will have no linkage. Since we can't know until we get to the end
1651 // of the typedef, this function finds out if D might have non-external linkage.
1652 // Callers should verify at the end of the TU if it D has external linkage or
1653 // not.
1654 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1655   const DeclContext *DC = D->getDeclContext();
1656   while (!DC->isTranslationUnit()) {
1657     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1658       if (!RD->hasNameForLinkage())
1659         return true;
1660     }
1661     DC = DC->getParent();
1662   }
1663 
1664   return !D->isExternallyVisible();
1665 }
1666 
1667 // FIXME: This needs to be refactored; some other isInMainFile users want
1668 // these semantics.
1669 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1670   if (S.TUKind != TU_Complete)
1671     return false;
1672   return S.SourceMgr.isInMainFile(Loc);
1673 }
1674 
1675 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1676   assert(D);
1677 
1678   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1679     return false;
1680 
1681   // Ignore all entities declared within templates, and out-of-line definitions
1682   // of members of class templates.
1683   if (D->getDeclContext()->isDependentContext() ||
1684       D->getLexicalDeclContext()->isDependentContext())
1685     return false;
1686 
1687   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1688     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1689       return false;
1690     // A non-out-of-line declaration of a member specialization was implicitly
1691     // instantiated; it's the out-of-line declaration that we're interested in.
1692     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1693         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1694       return false;
1695 
1696     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1697       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1698         return false;
1699     } else {
1700       // 'static inline' functions are defined in headers; don't warn.
1701       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1702         return false;
1703     }
1704 
1705     if (FD->doesThisDeclarationHaveABody() &&
1706         Context.DeclMustBeEmitted(FD))
1707       return false;
1708   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1709     // Constants and utility variables are defined in headers with internal
1710     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1711     // like "inline".)
1712     if (!isMainFileLoc(*this, VD->getLocation()))
1713       return false;
1714 
1715     if (Context.DeclMustBeEmitted(VD))
1716       return false;
1717 
1718     if (VD->isStaticDataMember() &&
1719         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1720       return false;
1721     if (VD->isStaticDataMember() &&
1722         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1723         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1724       return false;
1725 
1726     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1727       return false;
1728   } else {
1729     return false;
1730   }
1731 
1732   // Only warn for unused decls internal to the translation unit.
1733   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1734   // for inline functions defined in the main source file, for instance.
1735   return mightHaveNonExternalLinkage(D);
1736 }
1737 
1738 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1739   if (!D)
1740     return;
1741 
1742   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1743     const FunctionDecl *First = FD->getFirstDecl();
1744     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1745       return; // First should already be in the vector.
1746   }
1747 
1748   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1749     const VarDecl *First = VD->getFirstDecl();
1750     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1751       return; // First should already be in the vector.
1752   }
1753 
1754   if (ShouldWarnIfUnusedFileScopedDecl(D))
1755     UnusedFileScopedDecls.push_back(D);
1756 }
1757 
1758 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1759   if (D->isInvalidDecl())
1760     return false;
1761 
1762   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1763     // For a decomposition declaration, warn if none of the bindings are
1764     // referenced, instead of if the variable itself is referenced (which
1765     // it is, by the bindings' expressions).
1766     for (auto *BD : DD->bindings())
1767       if (BD->isReferenced())
1768         return false;
1769   } else if (!D->getDeclName()) {
1770     return false;
1771   } else if (D->isReferenced() || D->isUsed()) {
1772     return false;
1773   }
1774 
1775   if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
1776     return false;
1777 
1778   if (isa<LabelDecl>(D))
1779     return true;
1780 
1781   // Except for labels, we only care about unused decls that are local to
1782   // functions.
1783   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1784   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1785     // For dependent types, the diagnostic is deferred.
1786     WithinFunction =
1787         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1788   if (!WithinFunction)
1789     return false;
1790 
1791   if (isa<TypedefNameDecl>(D))
1792     return true;
1793 
1794   // White-list anything that isn't a local variable.
1795   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1796     return false;
1797 
1798   // Types of valid local variables should be complete, so this should succeed.
1799   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1800 
1801     // White-list anything with an __attribute__((unused)) type.
1802     const auto *Ty = VD->getType().getTypePtr();
1803 
1804     // Only look at the outermost level of typedef.
1805     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1806       if (TT->getDecl()->hasAttr<UnusedAttr>())
1807         return false;
1808     }
1809 
1810     // If we failed to complete the type for some reason, or if the type is
1811     // dependent, don't diagnose the variable.
1812     if (Ty->isIncompleteType() || Ty->isDependentType())
1813       return false;
1814 
1815     // Look at the element type to ensure that the warning behaviour is
1816     // consistent for both scalars and arrays.
1817     Ty = Ty->getBaseElementTypeUnsafe();
1818 
1819     if (const TagType *TT = Ty->getAs<TagType>()) {
1820       const TagDecl *Tag = TT->getDecl();
1821       if (Tag->hasAttr<UnusedAttr>())
1822         return false;
1823 
1824       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1825         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1826           return false;
1827 
1828         if (const Expr *Init = VD->getInit()) {
1829           if (const ExprWithCleanups *Cleanups =
1830                   dyn_cast<ExprWithCleanups>(Init))
1831             Init = Cleanups->getSubExpr();
1832           const CXXConstructExpr *Construct =
1833             dyn_cast<CXXConstructExpr>(Init);
1834           if (Construct && !Construct->isElidable()) {
1835             CXXConstructorDecl *CD = Construct->getConstructor();
1836             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1837                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1838               return false;
1839           }
1840 
1841           // Suppress the warning if we don't know how this is constructed, and
1842           // it could possibly be non-trivial constructor.
1843           if (Init->isTypeDependent())
1844             for (const CXXConstructorDecl *Ctor : RD->ctors())
1845               if (!Ctor->isTrivial())
1846                 return false;
1847         }
1848       }
1849     }
1850 
1851     // TODO: __attribute__((unused)) templates?
1852   }
1853 
1854   return true;
1855 }
1856 
1857 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1858                                      FixItHint &Hint) {
1859   if (isa<LabelDecl>(D)) {
1860     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1861         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1862         true);
1863     if (AfterColon.isInvalid())
1864       return;
1865     Hint = FixItHint::CreateRemoval(
1866         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1867   }
1868 }
1869 
1870 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1871   if (D->getTypeForDecl()->isDependentType())
1872     return;
1873 
1874   for (auto *TmpD : D->decls()) {
1875     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1876       DiagnoseUnusedDecl(T);
1877     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1878       DiagnoseUnusedNestedTypedefs(R);
1879   }
1880 }
1881 
1882 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1883 /// unless they are marked attr(unused).
1884 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1885   if (!ShouldDiagnoseUnusedDecl(D))
1886     return;
1887 
1888   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1889     // typedefs can be referenced later on, so the diagnostics are emitted
1890     // at end-of-translation-unit.
1891     UnusedLocalTypedefNameCandidates.insert(TD);
1892     return;
1893   }
1894 
1895   FixItHint Hint;
1896   GenerateFixForUnusedDecl(D, Context, Hint);
1897 
1898   unsigned DiagID;
1899   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1900     DiagID = diag::warn_unused_exception_param;
1901   else if (isa<LabelDecl>(D))
1902     DiagID = diag::warn_unused_label;
1903   else
1904     DiagID = diag::warn_unused_variable;
1905 
1906   Diag(D->getLocation(), DiagID) << D << Hint;
1907 }
1908 
1909 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1910   // Verify that we have no forward references left.  If so, there was a goto
1911   // or address of a label taken, but no definition of it.  Label fwd
1912   // definitions are indicated with a null substmt which is also not a resolved
1913   // MS inline assembly label name.
1914   bool Diagnose = false;
1915   if (L->isMSAsmLabel())
1916     Diagnose = !L->isResolvedMSAsmLabel();
1917   else
1918     Diagnose = L->getStmt() == nullptr;
1919   if (Diagnose)
1920     S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
1921 }
1922 
1923 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1924   S->mergeNRVOIntoParent();
1925 
1926   if (S->decl_empty()) return;
1927   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1928          "Scope shouldn't contain decls!");
1929 
1930   for (auto *TmpD : S->decls()) {
1931     assert(TmpD && "This decl didn't get pushed??");
1932 
1933     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1934     NamedDecl *D = cast<NamedDecl>(TmpD);
1935 
1936     // Diagnose unused variables in this scope.
1937     if (!S->hasUnrecoverableErrorOccurred()) {
1938       DiagnoseUnusedDecl(D);
1939       if (const auto *RD = dyn_cast<RecordDecl>(D))
1940         DiagnoseUnusedNestedTypedefs(RD);
1941     }
1942 
1943     if (!D->getDeclName()) continue;
1944 
1945     // If this was a forward reference to a label, verify it was defined.
1946     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1947       CheckPoppedLabel(LD, *this);
1948 
1949     // Remove this name from our lexical scope, and warn on it if we haven't
1950     // already.
1951     IdResolver.RemoveDecl(D);
1952     auto ShadowI = ShadowingDecls.find(D);
1953     if (ShadowI != ShadowingDecls.end()) {
1954       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1955         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1956             << D << FD << FD->getParent();
1957         Diag(FD->getLocation(), diag::note_previous_declaration);
1958       }
1959       ShadowingDecls.erase(ShadowI);
1960     }
1961   }
1962 }
1963 
1964 /// Look for an Objective-C class in the translation unit.
1965 ///
1966 /// \param Id The name of the Objective-C class we're looking for. If
1967 /// typo-correction fixes this name, the Id will be updated
1968 /// to the fixed name.
1969 ///
1970 /// \param IdLoc The location of the name in the translation unit.
1971 ///
1972 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1973 /// if there is no class with the given name.
1974 ///
1975 /// \returns The declaration of the named Objective-C class, or NULL if the
1976 /// class could not be found.
1977 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1978                                               SourceLocation IdLoc,
1979                                               bool DoTypoCorrection) {
1980   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1981   // creation from this context.
1982   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1983 
1984   if (!IDecl && DoTypoCorrection) {
1985     // Perform typo correction at the given location, but only if we
1986     // find an Objective-C class name.
1987     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
1988     if (TypoCorrection C =
1989             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
1990                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
1991       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1992       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1993       Id = IDecl->getIdentifier();
1994     }
1995   }
1996   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1997   // This routine must always return a class definition, if any.
1998   if (Def && Def->getDefinition())
1999       Def = Def->getDefinition();
2000   return Def;
2001 }
2002 
2003 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
2004 /// from S, where a non-field would be declared. This routine copes
2005 /// with the difference between C and C++ scoping rules in structs and
2006 /// unions. For example, the following code is well-formed in C but
2007 /// ill-formed in C++:
2008 /// @code
2009 /// struct S6 {
2010 ///   enum { BAR } e;
2011 /// };
2012 ///
2013 /// void test_S6() {
2014 ///   struct S6 a;
2015 ///   a.e = BAR;
2016 /// }
2017 /// @endcode
2018 /// For the declaration of BAR, this routine will return a different
2019 /// scope. The scope S will be the scope of the unnamed enumeration
2020 /// within S6. In C++, this routine will return the scope associated
2021 /// with S6, because the enumeration's scope is a transparent
2022 /// context but structures can contain non-field names. In C, this
2023 /// routine will return the translation unit scope, since the
2024 /// enumeration's scope is a transparent context and structures cannot
2025 /// contain non-field names.
2026 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2027   while (((S->getFlags() & Scope::DeclScope) == 0) ||
2028          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2029          (S->isClassScope() && !getLangOpts().CPlusPlus))
2030     S = S->getParent();
2031   return S;
2032 }
2033 
2034 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2035                                ASTContext::GetBuiltinTypeError Error) {
2036   switch (Error) {
2037   case ASTContext::GE_None:
2038     return "";
2039   case ASTContext::GE_Missing_type:
2040     return BuiltinInfo.getHeaderName(ID);
2041   case ASTContext::GE_Missing_stdio:
2042     return "stdio.h";
2043   case ASTContext::GE_Missing_setjmp:
2044     return "setjmp.h";
2045   case ASTContext::GE_Missing_ucontext:
2046     return "ucontext.h";
2047   }
2048   llvm_unreachable("unhandled error kind");
2049 }
2050 
2051 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2052                                   unsigned ID, SourceLocation Loc) {
2053   DeclContext *Parent = Context.getTranslationUnitDecl();
2054 
2055   if (getLangOpts().CPlusPlus) {
2056     LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2057         Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2058     CLinkageDecl->setImplicit();
2059     Parent->addDecl(CLinkageDecl);
2060     Parent = CLinkageDecl;
2061   }
2062 
2063   FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2064                                            /*TInfo=*/nullptr, SC_Extern, false,
2065                                            Type->isFunctionProtoType());
2066   New->setImplicit();
2067   New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2068 
2069   // Create Decl objects for each parameter, adding them to the
2070   // FunctionDecl.
2071   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2072     SmallVector<ParmVarDecl *, 16> Params;
2073     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2074       ParmVarDecl *parm = ParmVarDecl::Create(
2075           Context, New, SourceLocation(), SourceLocation(), nullptr,
2076           FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2077       parm->setScopeInfo(0, i);
2078       Params.push_back(parm);
2079     }
2080     New->setParams(Params);
2081   }
2082 
2083   AddKnownFunctionAttributes(New);
2084   return New;
2085 }
2086 
2087 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2088 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2089 /// if we're creating this built-in in anticipation of redeclaring the
2090 /// built-in.
2091 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2092                                      Scope *S, bool ForRedeclaration,
2093                                      SourceLocation Loc) {
2094   LookupNecessaryTypesForBuiltin(S, ID);
2095 
2096   ASTContext::GetBuiltinTypeError Error;
2097   QualType R = Context.GetBuiltinType(ID, Error);
2098   if (Error) {
2099     if (!ForRedeclaration)
2100       return nullptr;
2101 
2102     // If we have a builtin without an associated type we should not emit a
2103     // warning when we were not able to find a type for it.
2104     if (Error == ASTContext::GE_Missing_type ||
2105         Context.BuiltinInfo.allowTypeMismatch(ID))
2106       return nullptr;
2107 
2108     // If we could not find a type for setjmp it is because the jmp_buf type was
2109     // not defined prior to the setjmp declaration.
2110     if (Error == ASTContext::GE_Missing_setjmp) {
2111       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2112           << Context.BuiltinInfo.getName(ID);
2113       return nullptr;
2114     }
2115 
2116     // Generally, we emit a warning that the declaration requires the
2117     // appropriate header.
2118     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2119         << getHeaderName(Context.BuiltinInfo, ID, Error)
2120         << Context.BuiltinInfo.getName(ID);
2121     return nullptr;
2122   }
2123 
2124   if (!ForRedeclaration &&
2125       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2126        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2127     Diag(Loc, diag::ext_implicit_lib_function_decl)
2128         << Context.BuiltinInfo.getName(ID) << R;
2129     if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2130       Diag(Loc, diag::note_include_header_or_declare)
2131           << Header << Context.BuiltinInfo.getName(ID);
2132   }
2133 
2134   if (R.isNull())
2135     return nullptr;
2136 
2137   FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2138   RegisterLocallyScopedExternCDecl(New, S);
2139 
2140   // TUScope is the translation-unit scope to insert this function into.
2141   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2142   // relate Scopes to DeclContexts, and probably eliminate CurContext
2143   // entirely, but we're not there yet.
2144   DeclContext *SavedContext = CurContext;
2145   CurContext = New->getDeclContext();
2146   PushOnScopeChains(New, TUScope);
2147   CurContext = SavedContext;
2148   return New;
2149 }
2150 
2151 /// Typedef declarations don't have linkage, but they still denote the same
2152 /// entity if their types are the same.
2153 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2154 /// isSameEntity.
2155 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2156                                                      TypedefNameDecl *Decl,
2157                                                      LookupResult &Previous) {
2158   // This is only interesting when modules are enabled.
2159   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2160     return;
2161 
2162   // Empty sets are uninteresting.
2163   if (Previous.empty())
2164     return;
2165 
2166   LookupResult::Filter Filter = Previous.makeFilter();
2167   while (Filter.hasNext()) {
2168     NamedDecl *Old = Filter.next();
2169 
2170     // Non-hidden declarations are never ignored.
2171     if (S.isVisible(Old))
2172       continue;
2173 
2174     // Declarations of the same entity are not ignored, even if they have
2175     // different linkages.
2176     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2177       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2178                                 Decl->getUnderlyingType()))
2179         continue;
2180 
2181       // If both declarations give a tag declaration a typedef name for linkage
2182       // purposes, then they declare the same entity.
2183       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2184           Decl->getAnonDeclWithTypedefName())
2185         continue;
2186     }
2187 
2188     Filter.erase();
2189   }
2190 
2191   Filter.done();
2192 }
2193 
2194 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2195   QualType OldType;
2196   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2197     OldType = OldTypedef->getUnderlyingType();
2198   else
2199     OldType = Context.getTypeDeclType(Old);
2200   QualType NewType = New->getUnderlyingType();
2201 
2202   if (NewType->isVariablyModifiedType()) {
2203     // Must not redefine a typedef with a variably-modified type.
2204     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2205     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2206       << Kind << NewType;
2207     if (Old->getLocation().isValid())
2208       notePreviousDefinition(Old, New->getLocation());
2209     New->setInvalidDecl();
2210     return true;
2211   }
2212 
2213   if (OldType != NewType &&
2214       !OldType->isDependentType() &&
2215       !NewType->isDependentType() &&
2216       !Context.hasSameType(OldType, NewType)) {
2217     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2218     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2219       << Kind << NewType << OldType;
2220     if (Old->getLocation().isValid())
2221       notePreviousDefinition(Old, New->getLocation());
2222     New->setInvalidDecl();
2223     return true;
2224   }
2225   return false;
2226 }
2227 
2228 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2229 /// same name and scope as a previous declaration 'Old'.  Figure out
2230 /// how to resolve this situation, merging decls or emitting
2231 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2232 ///
2233 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2234                                 LookupResult &OldDecls) {
2235   // If the new decl is known invalid already, don't bother doing any
2236   // merging checks.
2237   if (New->isInvalidDecl()) return;
2238 
2239   // Allow multiple definitions for ObjC built-in typedefs.
2240   // FIXME: Verify the underlying types are equivalent!
2241   if (getLangOpts().ObjC) {
2242     const IdentifierInfo *TypeID = New->getIdentifier();
2243     switch (TypeID->getLength()) {
2244     default: break;
2245     case 2:
2246       {
2247         if (!TypeID->isStr("id"))
2248           break;
2249         QualType T = New->getUnderlyingType();
2250         if (!T->isPointerType())
2251           break;
2252         if (!T->isVoidPointerType()) {
2253           QualType PT = T->castAs<PointerType>()->getPointeeType();
2254           if (!PT->isStructureType())
2255             break;
2256         }
2257         Context.setObjCIdRedefinitionType(T);
2258         // Install the built-in type for 'id', ignoring the current definition.
2259         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2260         return;
2261       }
2262     case 5:
2263       if (!TypeID->isStr("Class"))
2264         break;
2265       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2266       // Install the built-in type for 'Class', ignoring the current definition.
2267       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2268       return;
2269     case 3:
2270       if (!TypeID->isStr("SEL"))
2271         break;
2272       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2273       // Install the built-in type for 'SEL', ignoring the current definition.
2274       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2275       return;
2276     }
2277     // Fall through - the typedef name was not a builtin type.
2278   }
2279 
2280   // Verify the old decl was also a type.
2281   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2282   if (!Old) {
2283     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2284       << New->getDeclName();
2285 
2286     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2287     if (OldD->getLocation().isValid())
2288       notePreviousDefinition(OldD, New->getLocation());
2289 
2290     return New->setInvalidDecl();
2291   }
2292 
2293   // If the old declaration is invalid, just give up here.
2294   if (Old->isInvalidDecl())
2295     return New->setInvalidDecl();
2296 
2297   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2298     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2299     auto *NewTag = New->getAnonDeclWithTypedefName();
2300     NamedDecl *Hidden = nullptr;
2301     if (OldTag && NewTag &&
2302         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2303         !hasVisibleDefinition(OldTag, &Hidden)) {
2304       // There is a definition of this tag, but it is not visible. Use it
2305       // instead of our tag.
2306       New->setTypeForDecl(OldTD->getTypeForDecl());
2307       if (OldTD->isModed())
2308         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2309                                     OldTD->getUnderlyingType());
2310       else
2311         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2312 
2313       // Make the old tag definition visible.
2314       makeMergedDefinitionVisible(Hidden);
2315 
2316       // If this was an unscoped enumeration, yank all of its enumerators
2317       // out of the scope.
2318       if (isa<EnumDecl>(NewTag)) {
2319         Scope *EnumScope = getNonFieldDeclScope(S);
2320         for (auto *D : NewTag->decls()) {
2321           auto *ED = cast<EnumConstantDecl>(D);
2322           assert(EnumScope->isDeclScope(ED));
2323           EnumScope->RemoveDecl(ED);
2324           IdResolver.RemoveDecl(ED);
2325           ED->getLexicalDeclContext()->removeDecl(ED);
2326         }
2327       }
2328     }
2329   }
2330 
2331   // If the typedef types are not identical, reject them in all languages and
2332   // with any extensions enabled.
2333   if (isIncompatibleTypedef(Old, New))
2334     return;
2335 
2336   // The types match.  Link up the redeclaration chain and merge attributes if
2337   // the old declaration was a typedef.
2338   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2339     New->setPreviousDecl(Typedef);
2340     mergeDeclAttributes(New, Old);
2341   }
2342 
2343   if (getLangOpts().MicrosoftExt)
2344     return;
2345 
2346   if (getLangOpts().CPlusPlus) {
2347     // C++ [dcl.typedef]p2:
2348     //   In a given non-class scope, a typedef specifier can be used to
2349     //   redefine the name of any type declared in that scope to refer
2350     //   to the type to which it already refers.
2351     if (!isa<CXXRecordDecl>(CurContext))
2352       return;
2353 
2354     // C++0x [dcl.typedef]p4:
2355     //   In a given class scope, a typedef specifier can be used to redefine
2356     //   any class-name declared in that scope that is not also a typedef-name
2357     //   to refer to the type to which it already refers.
2358     //
2359     // This wording came in via DR424, which was a correction to the
2360     // wording in DR56, which accidentally banned code like:
2361     //
2362     //   struct S {
2363     //     typedef struct A { } A;
2364     //   };
2365     //
2366     // in the C++03 standard. We implement the C++0x semantics, which
2367     // allow the above but disallow
2368     //
2369     //   struct S {
2370     //     typedef int I;
2371     //     typedef int I;
2372     //   };
2373     //
2374     // since that was the intent of DR56.
2375     if (!isa<TypedefNameDecl>(Old))
2376       return;
2377 
2378     Diag(New->getLocation(), diag::err_redefinition)
2379       << New->getDeclName();
2380     notePreviousDefinition(Old, New->getLocation());
2381     return New->setInvalidDecl();
2382   }
2383 
2384   // Modules always permit redefinition of typedefs, as does C11.
2385   if (getLangOpts().Modules || getLangOpts().C11)
2386     return;
2387 
2388   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2389   // is normally mapped to an error, but can be controlled with
2390   // -Wtypedef-redefinition.  If either the original or the redefinition is
2391   // in a system header, don't emit this for compatibility with GCC.
2392   if (getDiagnostics().getSuppressSystemWarnings() &&
2393       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2394       (Old->isImplicit() ||
2395        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2396        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2397     return;
2398 
2399   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2400     << New->getDeclName();
2401   notePreviousDefinition(Old, New->getLocation());
2402 }
2403 
2404 /// DeclhasAttr - returns true if decl Declaration already has the target
2405 /// attribute.
2406 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2407   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2408   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2409   for (const auto *i : D->attrs())
2410     if (i->getKind() == A->getKind()) {
2411       if (Ann) {
2412         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2413           return true;
2414         continue;
2415       }
2416       // FIXME: Don't hardcode this check
2417       if (OA && isa<OwnershipAttr>(i))
2418         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2419       return true;
2420     }
2421 
2422   return false;
2423 }
2424 
2425 static bool isAttributeTargetADefinition(Decl *D) {
2426   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2427     return VD->isThisDeclarationADefinition();
2428   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2429     return TD->isCompleteDefinition() || TD->isBeingDefined();
2430   return true;
2431 }
2432 
2433 /// Merge alignment attributes from \p Old to \p New, taking into account the
2434 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2435 ///
2436 /// \return \c true if any attributes were added to \p New.
2437 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2438   // Look for alignas attributes on Old, and pick out whichever attribute
2439   // specifies the strictest alignment requirement.
2440   AlignedAttr *OldAlignasAttr = nullptr;
2441   AlignedAttr *OldStrictestAlignAttr = nullptr;
2442   unsigned OldAlign = 0;
2443   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2444     // FIXME: We have no way of representing inherited dependent alignments
2445     // in a case like:
2446     //   template<int A, int B> struct alignas(A) X;
2447     //   template<int A, int B> struct alignas(B) X {};
2448     // For now, we just ignore any alignas attributes which are not on the
2449     // definition in such a case.
2450     if (I->isAlignmentDependent())
2451       return false;
2452 
2453     if (I->isAlignas())
2454       OldAlignasAttr = I;
2455 
2456     unsigned Align = I->getAlignment(S.Context);
2457     if (Align > OldAlign) {
2458       OldAlign = Align;
2459       OldStrictestAlignAttr = I;
2460     }
2461   }
2462 
2463   // Look for alignas attributes on New.
2464   AlignedAttr *NewAlignasAttr = nullptr;
2465   unsigned NewAlign = 0;
2466   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2467     if (I->isAlignmentDependent())
2468       return false;
2469 
2470     if (I->isAlignas())
2471       NewAlignasAttr = I;
2472 
2473     unsigned Align = I->getAlignment(S.Context);
2474     if (Align > NewAlign)
2475       NewAlign = Align;
2476   }
2477 
2478   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2479     // Both declarations have 'alignas' attributes. We require them to match.
2480     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2481     // fall short. (If two declarations both have alignas, they must both match
2482     // every definition, and so must match each other if there is a definition.)
2483 
2484     // If either declaration only contains 'alignas(0)' specifiers, then it
2485     // specifies the natural alignment for the type.
2486     if (OldAlign == 0 || NewAlign == 0) {
2487       QualType Ty;
2488       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2489         Ty = VD->getType();
2490       else
2491         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2492 
2493       if (OldAlign == 0)
2494         OldAlign = S.Context.getTypeAlign(Ty);
2495       if (NewAlign == 0)
2496         NewAlign = S.Context.getTypeAlign(Ty);
2497     }
2498 
2499     if (OldAlign != NewAlign) {
2500       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2501         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2502         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2503       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2504     }
2505   }
2506 
2507   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2508     // C++11 [dcl.align]p6:
2509     //   if any declaration of an entity has an alignment-specifier,
2510     //   every defining declaration of that entity shall specify an
2511     //   equivalent alignment.
2512     // C11 6.7.5/7:
2513     //   If the definition of an object does not have an alignment
2514     //   specifier, any other declaration of that object shall also
2515     //   have no alignment specifier.
2516     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2517       << OldAlignasAttr;
2518     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2519       << OldAlignasAttr;
2520   }
2521 
2522   bool AnyAdded = false;
2523 
2524   // Ensure we have an attribute representing the strictest alignment.
2525   if (OldAlign > NewAlign) {
2526     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2527     Clone->setInherited(true);
2528     New->addAttr(Clone);
2529     AnyAdded = true;
2530   }
2531 
2532   // Ensure we have an alignas attribute if the old declaration had one.
2533   if (OldAlignasAttr && !NewAlignasAttr &&
2534       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2535     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2536     Clone->setInherited(true);
2537     New->addAttr(Clone);
2538     AnyAdded = true;
2539   }
2540 
2541   return AnyAdded;
2542 }
2543 
2544 #define WANT_DECL_MERGE_LOGIC
2545 #include "clang/Sema/AttrParsedAttrImpl.inc"
2546 #undef WANT_DECL_MERGE_LOGIC
2547 
2548 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2549                                const InheritableAttr *Attr,
2550                                Sema::AvailabilityMergeKind AMK) {
2551   // Diagnose any mutual exclusions between the attribute that we want to add
2552   // and attributes that already exist on the declaration.
2553   if (!DiagnoseMutualExclusions(S, D, Attr))
2554     return false;
2555 
2556   // This function copies an attribute Attr from a previous declaration to the
2557   // new declaration D if the new declaration doesn't itself have that attribute
2558   // yet or if that attribute allows duplicates.
2559   // If you're adding a new attribute that requires logic different from
2560   // "use explicit attribute on decl if present, else use attribute from
2561   // previous decl", for example if the attribute needs to be consistent
2562   // between redeclarations, you need to call a custom merge function here.
2563   InheritableAttr *NewAttr = nullptr;
2564   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2565     NewAttr = S.mergeAvailabilityAttr(
2566         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2567         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2568         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2569         AA->getPriority());
2570   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2571     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2572   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2573     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2574   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2575     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2576   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2577     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2578   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2579     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2580                                 FA->getFirstArg());
2581   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2582     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2583   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2584     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2585   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2586     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2587                                        IA->getInheritanceModel());
2588   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2589     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2590                                       &S.Context.Idents.get(AA->getSpelling()));
2591   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2592            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2593             isa<CUDAGlobalAttr>(Attr))) {
2594     // CUDA target attributes are part of function signature for
2595     // overloading purposes and must not be merged.
2596     return false;
2597   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2598     NewAttr = S.mergeMinSizeAttr(D, *MA);
2599   else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2600     NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2601   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2602     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2603   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2604     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2605   else if (isa<AlignedAttr>(Attr))
2606     // AlignedAttrs are handled separately, because we need to handle all
2607     // such attributes on a declaration at the same time.
2608     NewAttr = nullptr;
2609   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2610            (AMK == Sema::AMK_Override ||
2611             AMK == Sema::AMK_ProtocolImplementation))
2612     NewAttr = nullptr;
2613   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2614     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2615   else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2616     NewAttr = S.mergeImportModuleAttr(D, *IMA);
2617   else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2618     NewAttr = S.mergeImportNameAttr(D, *INA);
2619   else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2620     NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2621   else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2622     NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2623   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2624     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2625 
2626   if (NewAttr) {
2627     NewAttr->setInherited(true);
2628     D->addAttr(NewAttr);
2629     if (isa<MSInheritanceAttr>(NewAttr))
2630       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2631     return true;
2632   }
2633 
2634   return false;
2635 }
2636 
2637 static const NamedDecl *getDefinition(const Decl *D) {
2638   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2639     return TD->getDefinition();
2640   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2641     const VarDecl *Def = VD->getDefinition();
2642     if (Def)
2643       return Def;
2644     return VD->getActingDefinition();
2645   }
2646   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2647     const FunctionDecl *Def = nullptr;
2648     if (FD->isDefined(Def, true))
2649       return Def;
2650   }
2651   return nullptr;
2652 }
2653 
2654 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2655   for (const auto *Attribute : D->attrs())
2656     if (Attribute->getKind() == Kind)
2657       return true;
2658   return false;
2659 }
2660 
2661 /// checkNewAttributesAfterDef - If we already have a definition, check that
2662 /// there are no new attributes in this declaration.
2663 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2664   if (!New->hasAttrs())
2665     return;
2666 
2667   const NamedDecl *Def = getDefinition(Old);
2668   if (!Def || Def == New)
2669     return;
2670 
2671   AttrVec &NewAttributes = New->getAttrs();
2672   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2673     const Attr *NewAttribute = NewAttributes[I];
2674 
2675     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2676       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2677         Sema::SkipBodyInfo SkipBody;
2678         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2679 
2680         // If we're skipping this definition, drop the "alias" attribute.
2681         if (SkipBody.ShouldSkip) {
2682           NewAttributes.erase(NewAttributes.begin() + I);
2683           --E;
2684           continue;
2685         }
2686       } else {
2687         VarDecl *VD = cast<VarDecl>(New);
2688         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2689                                 VarDecl::TentativeDefinition
2690                             ? diag::err_alias_after_tentative
2691                             : diag::err_redefinition;
2692         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2693         if (Diag == diag::err_redefinition)
2694           S.notePreviousDefinition(Def, VD->getLocation());
2695         else
2696           S.Diag(Def->getLocation(), diag::note_previous_definition);
2697         VD->setInvalidDecl();
2698       }
2699       ++I;
2700       continue;
2701     }
2702 
2703     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2704       // Tentative definitions are only interesting for the alias check above.
2705       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2706         ++I;
2707         continue;
2708       }
2709     }
2710 
2711     if (hasAttribute(Def, NewAttribute->getKind())) {
2712       ++I;
2713       continue; // regular attr merging will take care of validating this.
2714     }
2715 
2716     if (isa<C11NoReturnAttr>(NewAttribute)) {
2717       // C's _Noreturn is allowed to be added to a function after it is defined.
2718       ++I;
2719       continue;
2720     } else if (isa<UuidAttr>(NewAttribute)) {
2721       // msvc will allow a subsequent definition to add an uuid to a class
2722       ++I;
2723       continue;
2724     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2725       if (AA->isAlignas()) {
2726         // C++11 [dcl.align]p6:
2727         //   if any declaration of an entity has an alignment-specifier,
2728         //   every defining declaration of that entity shall specify an
2729         //   equivalent alignment.
2730         // C11 6.7.5/7:
2731         //   If the definition of an object does not have an alignment
2732         //   specifier, any other declaration of that object shall also
2733         //   have no alignment specifier.
2734         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2735           << AA;
2736         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2737           << AA;
2738         NewAttributes.erase(NewAttributes.begin() + I);
2739         --E;
2740         continue;
2741       }
2742     } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2743       // If there is a C definition followed by a redeclaration with this
2744       // attribute then there are two different definitions. In C++, prefer the
2745       // standard diagnostics.
2746       if (!S.getLangOpts().CPlusPlus) {
2747         S.Diag(NewAttribute->getLocation(),
2748                diag::err_loader_uninitialized_redeclaration);
2749         S.Diag(Def->getLocation(), diag::note_previous_definition);
2750         NewAttributes.erase(NewAttributes.begin() + I);
2751         --E;
2752         continue;
2753       }
2754     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2755                cast<VarDecl>(New)->isInline() &&
2756                !cast<VarDecl>(New)->isInlineSpecified()) {
2757       // Don't warn about applying selectany to implicitly inline variables.
2758       // Older compilers and language modes would require the use of selectany
2759       // to make such variables inline, and it would have no effect if we
2760       // honored it.
2761       ++I;
2762       continue;
2763     } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2764       // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2765       // declarations after defintions.
2766       ++I;
2767       continue;
2768     }
2769 
2770     S.Diag(NewAttribute->getLocation(),
2771            diag::warn_attribute_precede_definition);
2772     S.Diag(Def->getLocation(), diag::note_previous_definition);
2773     NewAttributes.erase(NewAttributes.begin() + I);
2774     --E;
2775   }
2776 }
2777 
2778 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2779                                      const ConstInitAttr *CIAttr,
2780                                      bool AttrBeforeInit) {
2781   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2782 
2783   // Figure out a good way to write this specifier on the old declaration.
2784   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2785   // enough of the attribute list spelling information to extract that without
2786   // heroics.
2787   std::string SuitableSpelling;
2788   if (S.getLangOpts().CPlusPlus20)
2789     SuitableSpelling = std::string(
2790         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2791   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2792     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2793         InsertLoc, {tok::l_square, tok::l_square,
2794                     S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2795                     S.PP.getIdentifierInfo("require_constant_initialization"),
2796                     tok::r_square, tok::r_square}));
2797   if (SuitableSpelling.empty())
2798     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2799         InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2800                     S.PP.getIdentifierInfo("require_constant_initialization"),
2801                     tok::r_paren, tok::r_paren}));
2802   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2803     SuitableSpelling = "constinit";
2804   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2805     SuitableSpelling = "[[clang::require_constant_initialization]]";
2806   if (SuitableSpelling.empty())
2807     SuitableSpelling = "__attribute__((require_constant_initialization))";
2808   SuitableSpelling += " ";
2809 
2810   if (AttrBeforeInit) {
2811     // extern constinit int a;
2812     // int a = 0; // error (missing 'constinit'), accepted as extension
2813     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
2814     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2815         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2816     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2817   } else {
2818     // int a = 0;
2819     // constinit extern int a; // error (missing 'constinit')
2820     S.Diag(CIAttr->getLocation(),
2821            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2822                                  : diag::warn_require_const_init_added_too_late)
2823         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2824     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2825         << CIAttr->isConstinit()
2826         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2827   }
2828 }
2829 
2830 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2831 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2832                                AvailabilityMergeKind AMK) {
2833   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2834     UsedAttr *NewAttr = OldAttr->clone(Context);
2835     NewAttr->setInherited(true);
2836     New->addAttr(NewAttr);
2837   }
2838   if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
2839     RetainAttr *NewAttr = OldAttr->clone(Context);
2840     NewAttr->setInherited(true);
2841     New->addAttr(NewAttr);
2842   }
2843 
2844   if (!Old->hasAttrs() && !New->hasAttrs())
2845     return;
2846 
2847   // [dcl.constinit]p1:
2848   //   If the [constinit] specifier is applied to any declaration of a
2849   //   variable, it shall be applied to the initializing declaration.
2850   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2851   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2852   if (bool(OldConstInit) != bool(NewConstInit)) {
2853     const auto *OldVD = cast<VarDecl>(Old);
2854     auto *NewVD = cast<VarDecl>(New);
2855 
2856     // Find the initializing declaration. Note that we might not have linked
2857     // the new declaration into the redeclaration chain yet.
2858     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2859     if (!InitDecl &&
2860         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2861       InitDecl = NewVD;
2862 
2863     if (InitDecl == NewVD) {
2864       // This is the initializing declaration. If it would inherit 'constinit',
2865       // that's ill-formed. (Note that we do not apply this to the attribute
2866       // form).
2867       if (OldConstInit && OldConstInit->isConstinit())
2868         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2869                                  /*AttrBeforeInit=*/true);
2870     } else if (NewConstInit) {
2871       // This is the first time we've been told that this declaration should
2872       // have a constant initializer. If we already saw the initializing
2873       // declaration, this is too late.
2874       if (InitDecl && InitDecl != NewVD) {
2875         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2876                                  /*AttrBeforeInit=*/false);
2877         NewVD->dropAttr<ConstInitAttr>();
2878       }
2879     }
2880   }
2881 
2882   // Attributes declared post-definition are currently ignored.
2883   checkNewAttributesAfterDef(*this, New, Old);
2884 
2885   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2886     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2887       if (!OldA->isEquivalent(NewA)) {
2888         // This redeclaration changes __asm__ label.
2889         Diag(New->getLocation(), diag::err_different_asm_label);
2890         Diag(OldA->getLocation(), diag::note_previous_declaration);
2891       }
2892     } else if (Old->isUsed()) {
2893       // This redeclaration adds an __asm__ label to a declaration that has
2894       // already been ODR-used.
2895       Diag(New->getLocation(), diag::err_late_asm_label_name)
2896         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2897     }
2898   }
2899 
2900   // Re-declaration cannot add abi_tag's.
2901   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2902     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2903       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2904         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2905                       NewTag) == OldAbiTagAttr->tags_end()) {
2906           Diag(NewAbiTagAttr->getLocation(),
2907                diag::err_new_abi_tag_on_redeclaration)
2908               << NewTag;
2909           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2910         }
2911       }
2912     } else {
2913       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2914       Diag(Old->getLocation(), diag::note_previous_declaration);
2915     }
2916   }
2917 
2918   // This redeclaration adds a section attribute.
2919   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2920     if (auto *VD = dyn_cast<VarDecl>(New)) {
2921       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2922         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2923         Diag(Old->getLocation(), diag::note_previous_declaration);
2924       }
2925     }
2926   }
2927 
2928   // Redeclaration adds code-seg attribute.
2929   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2930   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2931       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2932     Diag(New->getLocation(), diag::warn_mismatched_section)
2933          << 0 /*codeseg*/;
2934     Diag(Old->getLocation(), diag::note_previous_declaration);
2935   }
2936 
2937   if (!Old->hasAttrs())
2938     return;
2939 
2940   bool foundAny = New->hasAttrs();
2941 
2942   // Ensure that any moving of objects within the allocated map is done before
2943   // we process them.
2944   if (!foundAny) New->setAttrs(AttrVec());
2945 
2946   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2947     // Ignore deprecated/unavailable/availability attributes if requested.
2948     AvailabilityMergeKind LocalAMK = AMK_None;
2949     if (isa<DeprecatedAttr>(I) ||
2950         isa<UnavailableAttr>(I) ||
2951         isa<AvailabilityAttr>(I)) {
2952       switch (AMK) {
2953       case AMK_None:
2954         continue;
2955 
2956       case AMK_Redeclaration:
2957       case AMK_Override:
2958       case AMK_ProtocolImplementation:
2959         LocalAMK = AMK;
2960         break;
2961       }
2962     }
2963 
2964     // Already handled.
2965     if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
2966       continue;
2967 
2968     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2969       foundAny = true;
2970   }
2971 
2972   if (mergeAlignedAttrs(*this, New, Old))
2973     foundAny = true;
2974 
2975   if (!foundAny) New->dropAttrs();
2976 }
2977 
2978 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2979 /// to the new one.
2980 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2981                                      const ParmVarDecl *oldDecl,
2982                                      Sema &S) {
2983   // C++11 [dcl.attr.depend]p2:
2984   //   The first declaration of a function shall specify the
2985   //   carries_dependency attribute for its declarator-id if any declaration
2986   //   of the function specifies the carries_dependency attribute.
2987   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2988   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2989     S.Diag(CDA->getLocation(),
2990            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2991     // Find the first declaration of the parameter.
2992     // FIXME: Should we build redeclaration chains for function parameters?
2993     const FunctionDecl *FirstFD =
2994       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2995     const ParmVarDecl *FirstVD =
2996       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2997     S.Diag(FirstVD->getLocation(),
2998            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2999   }
3000 
3001   if (!oldDecl->hasAttrs())
3002     return;
3003 
3004   bool foundAny = newDecl->hasAttrs();
3005 
3006   // Ensure that any moving of objects within the allocated map is
3007   // done before we process them.
3008   if (!foundAny) newDecl->setAttrs(AttrVec());
3009 
3010   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3011     if (!DeclHasAttr(newDecl, I)) {
3012       InheritableAttr *newAttr =
3013         cast<InheritableParamAttr>(I->clone(S.Context));
3014       newAttr->setInherited(true);
3015       newDecl->addAttr(newAttr);
3016       foundAny = true;
3017     }
3018   }
3019 
3020   if (!foundAny) newDecl->dropAttrs();
3021 }
3022 
3023 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3024                                 const ParmVarDecl *OldParam,
3025                                 Sema &S) {
3026   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3027     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3028       if (*Oldnullability != *Newnullability) {
3029         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3030           << DiagNullabilityKind(
3031                *Newnullability,
3032                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3033                 != 0))
3034           << DiagNullabilityKind(
3035                *Oldnullability,
3036                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3037                 != 0));
3038         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3039       }
3040     } else {
3041       QualType NewT = NewParam->getType();
3042       NewT = S.Context.getAttributedType(
3043                          AttributedType::getNullabilityAttrKind(*Oldnullability),
3044                          NewT, NewT);
3045       NewParam->setType(NewT);
3046     }
3047   }
3048 }
3049 
3050 namespace {
3051 
3052 /// Used in MergeFunctionDecl to keep track of function parameters in
3053 /// C.
3054 struct GNUCompatibleParamWarning {
3055   ParmVarDecl *OldParm;
3056   ParmVarDecl *NewParm;
3057   QualType PromotedType;
3058 };
3059 
3060 } // end anonymous namespace
3061 
3062 // Determine whether the previous declaration was a definition, implicit
3063 // declaration, or a declaration.
3064 template <typename T>
3065 static std::pair<diag::kind, SourceLocation>
3066 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3067   diag::kind PrevDiag;
3068   SourceLocation OldLocation = Old->getLocation();
3069   if (Old->isThisDeclarationADefinition())
3070     PrevDiag = diag::note_previous_definition;
3071   else if (Old->isImplicit()) {
3072     PrevDiag = diag::note_previous_implicit_declaration;
3073     if (OldLocation.isInvalid())
3074       OldLocation = New->getLocation();
3075   } else
3076     PrevDiag = diag::note_previous_declaration;
3077   return std::make_pair(PrevDiag, OldLocation);
3078 }
3079 
3080 /// canRedefineFunction - checks if a function can be redefined. Currently,
3081 /// only extern inline functions can be redefined, and even then only in
3082 /// GNU89 mode.
3083 static bool canRedefineFunction(const FunctionDecl *FD,
3084                                 const LangOptions& LangOpts) {
3085   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3086           !LangOpts.CPlusPlus &&
3087           FD->isInlineSpecified() &&
3088           FD->getStorageClass() == SC_Extern);
3089 }
3090 
3091 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3092   const AttributedType *AT = T->getAs<AttributedType>();
3093   while (AT && !AT->isCallingConv())
3094     AT = AT->getModifiedType()->getAs<AttributedType>();
3095   return AT;
3096 }
3097 
3098 template <typename T>
3099 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3100   const DeclContext *DC = Old->getDeclContext();
3101   if (DC->isRecord())
3102     return false;
3103 
3104   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3105   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3106     return true;
3107   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3108     return true;
3109   return false;
3110 }
3111 
3112 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3113 static bool isExternC(VarTemplateDecl *) { return false; }
3114 
3115 /// Check whether a redeclaration of an entity introduced by a
3116 /// using-declaration is valid, given that we know it's not an overload
3117 /// (nor a hidden tag declaration).
3118 template<typename ExpectedDecl>
3119 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3120                                    ExpectedDecl *New) {
3121   // C++11 [basic.scope.declarative]p4:
3122   //   Given a set of declarations in a single declarative region, each of
3123   //   which specifies the same unqualified name,
3124   //   -- they shall all refer to the same entity, or all refer to functions
3125   //      and function templates; or
3126   //   -- exactly one declaration shall declare a class name or enumeration
3127   //      name that is not a typedef name and the other declarations shall all
3128   //      refer to the same variable or enumerator, or all refer to functions
3129   //      and function templates; in this case the class name or enumeration
3130   //      name is hidden (3.3.10).
3131 
3132   // C++11 [namespace.udecl]p14:
3133   //   If a function declaration in namespace scope or block scope has the
3134   //   same name and the same parameter-type-list as a function introduced
3135   //   by a using-declaration, and the declarations do not declare the same
3136   //   function, the program is ill-formed.
3137 
3138   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3139   if (Old &&
3140       !Old->getDeclContext()->getRedeclContext()->Equals(
3141           New->getDeclContext()->getRedeclContext()) &&
3142       !(isExternC(Old) && isExternC(New)))
3143     Old = nullptr;
3144 
3145   if (!Old) {
3146     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3147     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3148     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
3149     return true;
3150   }
3151   return false;
3152 }
3153 
3154 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3155                                             const FunctionDecl *B) {
3156   assert(A->getNumParams() == B->getNumParams());
3157 
3158   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3159     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3160     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3161     if (AttrA == AttrB)
3162       return true;
3163     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3164            AttrA->isDynamic() == AttrB->isDynamic();
3165   };
3166 
3167   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3168 }
3169 
3170 /// If necessary, adjust the semantic declaration context for a qualified
3171 /// declaration to name the correct inline namespace within the qualifier.
3172 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3173                                                DeclaratorDecl *OldD) {
3174   // The only case where we need to update the DeclContext is when
3175   // redeclaration lookup for a qualified name finds a declaration
3176   // in an inline namespace within the context named by the qualifier:
3177   //
3178   //   inline namespace N { int f(); }
3179   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3180   //
3181   // For unqualified declarations, the semantic context *can* change
3182   // along the redeclaration chain (for local extern declarations,
3183   // extern "C" declarations, and friend declarations in particular).
3184   if (!NewD->getQualifier())
3185     return;
3186 
3187   // NewD is probably already in the right context.
3188   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3189   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3190   if (NamedDC->Equals(SemaDC))
3191     return;
3192 
3193   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3194           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3195          "unexpected context for redeclaration");
3196 
3197   auto *LexDC = NewD->getLexicalDeclContext();
3198   auto FixSemaDC = [=](NamedDecl *D) {
3199     if (!D)
3200       return;
3201     D->setDeclContext(SemaDC);
3202     D->setLexicalDeclContext(LexDC);
3203   };
3204 
3205   FixSemaDC(NewD);
3206   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3207     FixSemaDC(FD->getDescribedFunctionTemplate());
3208   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3209     FixSemaDC(VD->getDescribedVarTemplate());
3210 }
3211 
3212 /// MergeFunctionDecl - We just parsed a function 'New' from
3213 /// declarator D which has the same name and scope as a previous
3214 /// declaration 'Old'.  Figure out how to resolve this situation,
3215 /// merging decls or emitting diagnostics as appropriate.
3216 ///
3217 /// In C++, New and Old must be declarations that are not
3218 /// overloaded. Use IsOverload to determine whether New and Old are
3219 /// overloaded, and to select the Old declaration that New should be
3220 /// merged with.
3221 ///
3222 /// Returns true if there was an error, false otherwise.
3223 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3224                              Scope *S, bool MergeTypeWithOld) {
3225   // Verify the old decl was also a function.
3226   FunctionDecl *Old = OldD->getAsFunction();
3227   if (!Old) {
3228     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3229       if (New->getFriendObjectKind()) {
3230         Diag(New->getLocation(), diag::err_using_decl_friend);
3231         Diag(Shadow->getTargetDecl()->getLocation(),
3232              diag::note_using_decl_target);
3233         Diag(Shadow->getUsingDecl()->getLocation(),
3234              diag::note_using_decl) << 0;
3235         return true;
3236       }
3237 
3238       // Check whether the two declarations might declare the same function.
3239       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3240         return true;
3241       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3242     } else {
3243       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3244         << New->getDeclName();
3245       notePreviousDefinition(OldD, New->getLocation());
3246       return true;
3247     }
3248   }
3249 
3250   // If the old declaration was found in an inline namespace and the new
3251   // declaration was qualified, update the DeclContext to match.
3252   adjustDeclContextForDeclaratorDecl(New, Old);
3253 
3254   // If the old declaration is invalid, just give up here.
3255   if (Old->isInvalidDecl())
3256     return true;
3257 
3258   // Disallow redeclaration of some builtins.
3259   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3260     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3261     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3262         << Old << Old->getType();
3263     return true;
3264   }
3265 
3266   diag::kind PrevDiag;
3267   SourceLocation OldLocation;
3268   std::tie(PrevDiag, OldLocation) =
3269       getNoteDiagForInvalidRedeclaration(Old, New);
3270 
3271   // Don't complain about this if we're in GNU89 mode and the old function
3272   // is an extern inline function.
3273   // Don't complain about specializations. They are not supposed to have
3274   // storage classes.
3275   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3276       New->getStorageClass() == SC_Static &&
3277       Old->hasExternalFormalLinkage() &&
3278       !New->getTemplateSpecializationInfo() &&
3279       !canRedefineFunction(Old, getLangOpts())) {
3280     if (getLangOpts().MicrosoftExt) {
3281       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3282       Diag(OldLocation, PrevDiag);
3283     } else {
3284       Diag(New->getLocation(), diag::err_static_non_static) << New;
3285       Diag(OldLocation, PrevDiag);
3286       return true;
3287     }
3288   }
3289 
3290   if (New->hasAttr<InternalLinkageAttr>() &&
3291       !Old->hasAttr<InternalLinkageAttr>()) {
3292     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3293         << New->getDeclName();
3294     notePreviousDefinition(Old, New->getLocation());
3295     New->dropAttr<InternalLinkageAttr>();
3296   }
3297 
3298   if (CheckRedeclarationModuleOwnership(New, Old))
3299     return true;
3300 
3301   if (!getLangOpts().CPlusPlus) {
3302     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3303     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3304       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3305         << New << OldOvl;
3306 
3307       // Try our best to find a decl that actually has the overloadable
3308       // attribute for the note. In most cases (e.g. programs with only one
3309       // broken declaration/definition), this won't matter.
3310       //
3311       // FIXME: We could do this if we juggled some extra state in
3312       // OverloadableAttr, rather than just removing it.
3313       const Decl *DiagOld = Old;
3314       if (OldOvl) {
3315         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3316           const auto *A = D->getAttr<OverloadableAttr>();
3317           return A && !A->isImplicit();
3318         });
3319         // If we've implicitly added *all* of the overloadable attrs to this
3320         // chain, emitting a "previous redecl" note is pointless.
3321         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3322       }
3323 
3324       if (DiagOld)
3325         Diag(DiagOld->getLocation(),
3326              diag::note_attribute_overloadable_prev_overload)
3327           << OldOvl;
3328 
3329       if (OldOvl)
3330         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3331       else
3332         New->dropAttr<OverloadableAttr>();
3333     }
3334   }
3335 
3336   // If a function is first declared with a calling convention, but is later
3337   // declared or defined without one, all following decls assume the calling
3338   // convention of the first.
3339   //
3340   // It's OK if a function is first declared without a calling convention,
3341   // but is later declared or defined with the default calling convention.
3342   //
3343   // To test if either decl has an explicit calling convention, we look for
3344   // AttributedType sugar nodes on the type as written.  If they are missing or
3345   // were canonicalized away, we assume the calling convention was implicit.
3346   //
3347   // Note also that we DO NOT return at this point, because we still have
3348   // other tests to run.
3349   QualType OldQType = Context.getCanonicalType(Old->getType());
3350   QualType NewQType = Context.getCanonicalType(New->getType());
3351   const FunctionType *OldType = cast<FunctionType>(OldQType);
3352   const FunctionType *NewType = cast<FunctionType>(NewQType);
3353   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3354   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3355   bool RequiresAdjustment = false;
3356 
3357   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3358     FunctionDecl *First = Old->getFirstDecl();
3359     const FunctionType *FT =
3360         First->getType().getCanonicalType()->castAs<FunctionType>();
3361     FunctionType::ExtInfo FI = FT->getExtInfo();
3362     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3363     if (!NewCCExplicit) {
3364       // Inherit the CC from the previous declaration if it was specified
3365       // there but not here.
3366       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3367       RequiresAdjustment = true;
3368     } else if (Old->getBuiltinID()) {
3369       // Builtin attribute isn't propagated to the new one yet at this point,
3370       // so we check if the old one is a builtin.
3371 
3372       // Calling Conventions on a Builtin aren't really useful and setting a
3373       // default calling convention and cdecl'ing some builtin redeclarations is
3374       // common, so warn and ignore the calling convention on the redeclaration.
3375       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3376           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3377           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3378       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3379       RequiresAdjustment = true;
3380     } else {
3381       // Calling conventions aren't compatible, so complain.
3382       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3383       Diag(New->getLocation(), diag::err_cconv_change)
3384         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3385         << !FirstCCExplicit
3386         << (!FirstCCExplicit ? "" :
3387             FunctionType::getNameForCallConv(FI.getCC()));
3388 
3389       // Put the note on the first decl, since it is the one that matters.
3390       Diag(First->getLocation(), diag::note_previous_declaration);
3391       return true;
3392     }
3393   }
3394 
3395   // FIXME: diagnose the other way around?
3396   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3397     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3398     RequiresAdjustment = true;
3399   }
3400 
3401   // Merge regparm attribute.
3402   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3403       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3404     if (NewTypeInfo.getHasRegParm()) {
3405       Diag(New->getLocation(), diag::err_regparm_mismatch)
3406         << NewType->getRegParmType()
3407         << OldType->getRegParmType();
3408       Diag(OldLocation, diag::note_previous_declaration);
3409       return true;
3410     }
3411 
3412     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3413     RequiresAdjustment = true;
3414   }
3415 
3416   // Merge ns_returns_retained attribute.
3417   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3418     if (NewTypeInfo.getProducesResult()) {
3419       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3420           << "'ns_returns_retained'";
3421       Diag(OldLocation, diag::note_previous_declaration);
3422       return true;
3423     }
3424 
3425     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3426     RequiresAdjustment = true;
3427   }
3428 
3429   if (OldTypeInfo.getNoCallerSavedRegs() !=
3430       NewTypeInfo.getNoCallerSavedRegs()) {
3431     if (NewTypeInfo.getNoCallerSavedRegs()) {
3432       AnyX86NoCallerSavedRegistersAttr *Attr =
3433         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3434       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3435       Diag(OldLocation, diag::note_previous_declaration);
3436       return true;
3437     }
3438 
3439     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3440     RequiresAdjustment = true;
3441   }
3442 
3443   if (RequiresAdjustment) {
3444     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3445     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3446     New->setType(QualType(AdjustedType, 0));
3447     NewQType = Context.getCanonicalType(New->getType());
3448   }
3449 
3450   // If this redeclaration makes the function inline, we may need to add it to
3451   // UndefinedButUsed.
3452   if (!Old->isInlined() && New->isInlined() &&
3453       !New->hasAttr<GNUInlineAttr>() &&
3454       !getLangOpts().GNUInline &&
3455       Old->isUsed(false) &&
3456       !Old->isDefined() && !New->isThisDeclarationADefinition())
3457     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3458                                            SourceLocation()));
3459 
3460   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3461   // about it.
3462   if (New->hasAttr<GNUInlineAttr>() &&
3463       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3464     UndefinedButUsed.erase(Old->getCanonicalDecl());
3465   }
3466 
3467   // If pass_object_size params don't match up perfectly, this isn't a valid
3468   // redeclaration.
3469   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3470       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3471     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3472         << New->getDeclName();
3473     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3474     return true;
3475   }
3476 
3477   if (getLangOpts().CPlusPlus) {
3478     // C++1z [over.load]p2
3479     //   Certain function declarations cannot be overloaded:
3480     //     -- Function declarations that differ only in the return type,
3481     //        the exception specification, or both cannot be overloaded.
3482 
3483     // Check the exception specifications match. This may recompute the type of
3484     // both Old and New if it resolved exception specifications, so grab the
3485     // types again after this. Because this updates the type, we do this before
3486     // any of the other checks below, which may update the "de facto" NewQType
3487     // but do not necessarily update the type of New.
3488     if (CheckEquivalentExceptionSpec(Old, New))
3489       return true;
3490     OldQType = Context.getCanonicalType(Old->getType());
3491     NewQType = Context.getCanonicalType(New->getType());
3492 
3493     // Go back to the type source info to compare the declared return types,
3494     // per C++1y [dcl.type.auto]p13:
3495     //   Redeclarations or specializations of a function or function template
3496     //   with a declared return type that uses a placeholder type shall also
3497     //   use that placeholder, not a deduced type.
3498     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3499     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3500     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3501         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3502                                        OldDeclaredReturnType)) {
3503       QualType ResQT;
3504       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3505           OldDeclaredReturnType->isObjCObjectPointerType())
3506         // FIXME: This does the wrong thing for a deduced return type.
3507         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3508       if (ResQT.isNull()) {
3509         if (New->isCXXClassMember() && New->isOutOfLine())
3510           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3511               << New << New->getReturnTypeSourceRange();
3512         else
3513           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3514               << New->getReturnTypeSourceRange();
3515         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3516                                     << Old->getReturnTypeSourceRange();
3517         return true;
3518       }
3519       else
3520         NewQType = ResQT;
3521     }
3522 
3523     QualType OldReturnType = OldType->getReturnType();
3524     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3525     if (OldReturnType != NewReturnType) {
3526       // If this function has a deduced return type and has already been
3527       // defined, copy the deduced value from the old declaration.
3528       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3529       if (OldAT && OldAT->isDeduced()) {
3530         New->setType(
3531             SubstAutoType(New->getType(),
3532                           OldAT->isDependentType() ? Context.DependentTy
3533                                                    : OldAT->getDeducedType()));
3534         NewQType = Context.getCanonicalType(
3535             SubstAutoType(NewQType,
3536                           OldAT->isDependentType() ? Context.DependentTy
3537                                                    : OldAT->getDeducedType()));
3538       }
3539     }
3540 
3541     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3542     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3543     if (OldMethod && NewMethod) {
3544       // Preserve triviality.
3545       NewMethod->setTrivial(OldMethod->isTrivial());
3546 
3547       // MSVC allows explicit template specialization at class scope:
3548       // 2 CXXMethodDecls referring to the same function will be injected.
3549       // We don't want a redeclaration error.
3550       bool IsClassScopeExplicitSpecialization =
3551                               OldMethod->isFunctionTemplateSpecialization() &&
3552                               NewMethod->isFunctionTemplateSpecialization();
3553       bool isFriend = NewMethod->getFriendObjectKind();
3554 
3555       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3556           !IsClassScopeExplicitSpecialization) {
3557         //    -- Member function declarations with the same name and the
3558         //       same parameter types cannot be overloaded if any of them
3559         //       is a static member function declaration.
3560         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3561           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3562           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3563           return true;
3564         }
3565 
3566         // C++ [class.mem]p1:
3567         //   [...] A member shall not be declared twice in the
3568         //   member-specification, except that a nested class or member
3569         //   class template can be declared and then later defined.
3570         if (!inTemplateInstantiation()) {
3571           unsigned NewDiag;
3572           if (isa<CXXConstructorDecl>(OldMethod))
3573             NewDiag = diag::err_constructor_redeclared;
3574           else if (isa<CXXDestructorDecl>(NewMethod))
3575             NewDiag = diag::err_destructor_redeclared;
3576           else if (isa<CXXConversionDecl>(NewMethod))
3577             NewDiag = diag::err_conv_function_redeclared;
3578           else
3579             NewDiag = diag::err_member_redeclared;
3580 
3581           Diag(New->getLocation(), NewDiag);
3582         } else {
3583           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3584             << New << New->getType();
3585         }
3586         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3587         return true;
3588 
3589       // Complain if this is an explicit declaration of a special
3590       // member that was initially declared implicitly.
3591       //
3592       // As an exception, it's okay to befriend such methods in order
3593       // to permit the implicit constructor/destructor/operator calls.
3594       } else if (OldMethod->isImplicit()) {
3595         if (isFriend) {
3596           NewMethod->setImplicit();
3597         } else {
3598           Diag(NewMethod->getLocation(),
3599                diag::err_definition_of_implicitly_declared_member)
3600             << New << getSpecialMember(OldMethod);
3601           return true;
3602         }
3603       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3604         Diag(NewMethod->getLocation(),
3605              diag::err_definition_of_explicitly_defaulted_member)
3606           << getSpecialMember(OldMethod);
3607         return true;
3608       }
3609     }
3610 
3611     // C++11 [dcl.attr.noreturn]p1:
3612     //   The first declaration of a function shall specify the noreturn
3613     //   attribute if any declaration of that function specifies the noreturn
3614     //   attribute.
3615     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3616     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3617       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3618       Diag(Old->getFirstDecl()->getLocation(),
3619            diag::note_noreturn_missing_first_decl);
3620     }
3621 
3622     // C++11 [dcl.attr.depend]p2:
3623     //   The first declaration of a function shall specify the
3624     //   carries_dependency attribute for its declarator-id if any declaration
3625     //   of the function specifies the carries_dependency attribute.
3626     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3627     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3628       Diag(CDA->getLocation(),
3629            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3630       Diag(Old->getFirstDecl()->getLocation(),
3631            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3632     }
3633 
3634     // (C++98 8.3.5p3):
3635     //   All declarations for a function shall agree exactly in both the
3636     //   return type and the parameter-type-list.
3637     // We also want to respect all the extended bits except noreturn.
3638 
3639     // noreturn should now match unless the old type info didn't have it.
3640     QualType OldQTypeForComparison = OldQType;
3641     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3642       auto *OldType = OldQType->castAs<FunctionProtoType>();
3643       const FunctionType *OldTypeForComparison
3644         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3645       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3646       assert(OldQTypeForComparison.isCanonical());
3647     }
3648 
3649     if (haveIncompatibleLanguageLinkages(Old, New)) {
3650       // As a special case, retain the language linkage from previous
3651       // declarations of a friend function as an extension.
3652       //
3653       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3654       // and is useful because there's otherwise no way to specify language
3655       // linkage within class scope.
3656       //
3657       // Check cautiously as the friend object kind isn't yet complete.
3658       if (New->getFriendObjectKind() != Decl::FOK_None) {
3659         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3660         Diag(OldLocation, PrevDiag);
3661       } else {
3662         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3663         Diag(OldLocation, PrevDiag);
3664         return true;
3665       }
3666     }
3667 
3668     // If the function types are compatible, merge the declarations. Ignore the
3669     // exception specifier because it was already checked above in
3670     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3671     // about incompatible types under -fms-compatibility.
3672     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3673                                                          NewQType))
3674       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3675 
3676     // If the types are imprecise (due to dependent constructs in friends or
3677     // local extern declarations), it's OK if they differ. We'll check again
3678     // during instantiation.
3679     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3680       return false;
3681 
3682     // Fall through for conflicting redeclarations and redefinitions.
3683   }
3684 
3685   // C: Function types need to be compatible, not identical. This handles
3686   // duplicate function decls like "void f(int); void f(enum X);" properly.
3687   if (!getLangOpts().CPlusPlus &&
3688       Context.typesAreCompatible(OldQType, NewQType)) {
3689     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3690     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3691     const FunctionProtoType *OldProto = nullptr;
3692     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3693         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3694       // The old declaration provided a function prototype, but the
3695       // new declaration does not. Merge in the prototype.
3696       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3697       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3698       NewQType =
3699           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3700                                   OldProto->getExtProtoInfo());
3701       New->setType(NewQType);
3702       New->setHasInheritedPrototype();
3703 
3704       // Synthesize parameters with the same types.
3705       SmallVector<ParmVarDecl*, 16> Params;
3706       for (const auto &ParamType : OldProto->param_types()) {
3707         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3708                                                  SourceLocation(), nullptr,
3709                                                  ParamType, /*TInfo=*/nullptr,
3710                                                  SC_None, nullptr);
3711         Param->setScopeInfo(0, Params.size());
3712         Param->setImplicit();
3713         Params.push_back(Param);
3714       }
3715 
3716       New->setParams(Params);
3717     }
3718 
3719     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3720   }
3721 
3722   // Check if the function types are compatible when pointer size address
3723   // spaces are ignored.
3724   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3725     return false;
3726 
3727   // GNU C permits a K&R definition to follow a prototype declaration
3728   // if the declared types of the parameters in the K&R definition
3729   // match the types in the prototype declaration, even when the
3730   // promoted types of the parameters from the K&R definition differ
3731   // from the types in the prototype. GCC then keeps the types from
3732   // the prototype.
3733   //
3734   // If a variadic prototype is followed by a non-variadic K&R definition,
3735   // the K&R definition becomes variadic.  This is sort of an edge case, but
3736   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3737   // C99 6.9.1p8.
3738   if (!getLangOpts().CPlusPlus &&
3739       Old->hasPrototype() && !New->hasPrototype() &&
3740       New->getType()->getAs<FunctionProtoType>() &&
3741       Old->getNumParams() == New->getNumParams()) {
3742     SmallVector<QualType, 16> ArgTypes;
3743     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3744     const FunctionProtoType *OldProto
3745       = Old->getType()->getAs<FunctionProtoType>();
3746     const FunctionProtoType *NewProto
3747       = New->getType()->getAs<FunctionProtoType>();
3748 
3749     // Determine whether this is the GNU C extension.
3750     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3751                                                NewProto->getReturnType());
3752     bool LooseCompatible = !MergedReturn.isNull();
3753     for (unsigned Idx = 0, End = Old->getNumParams();
3754          LooseCompatible && Idx != End; ++Idx) {
3755       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3756       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3757       if (Context.typesAreCompatible(OldParm->getType(),
3758                                      NewProto->getParamType(Idx))) {
3759         ArgTypes.push_back(NewParm->getType());
3760       } else if (Context.typesAreCompatible(OldParm->getType(),
3761                                             NewParm->getType(),
3762                                             /*CompareUnqualified=*/true)) {
3763         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3764                                            NewProto->getParamType(Idx) };
3765         Warnings.push_back(Warn);
3766         ArgTypes.push_back(NewParm->getType());
3767       } else
3768         LooseCompatible = false;
3769     }
3770 
3771     if (LooseCompatible) {
3772       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3773         Diag(Warnings[Warn].NewParm->getLocation(),
3774              diag::ext_param_promoted_not_compatible_with_prototype)
3775           << Warnings[Warn].PromotedType
3776           << Warnings[Warn].OldParm->getType();
3777         if (Warnings[Warn].OldParm->getLocation().isValid())
3778           Diag(Warnings[Warn].OldParm->getLocation(),
3779                diag::note_previous_declaration);
3780       }
3781 
3782       if (MergeTypeWithOld)
3783         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3784                                              OldProto->getExtProtoInfo()));
3785       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3786     }
3787 
3788     // Fall through to diagnose conflicting types.
3789   }
3790 
3791   // A function that has already been declared has been redeclared or
3792   // defined with a different type; show an appropriate diagnostic.
3793 
3794   // If the previous declaration was an implicitly-generated builtin
3795   // declaration, then at the very least we should use a specialized note.
3796   unsigned BuiltinID;
3797   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3798     // If it's actually a library-defined builtin function like 'malloc'
3799     // or 'printf', just warn about the incompatible redeclaration.
3800     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3801       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3802       Diag(OldLocation, diag::note_previous_builtin_declaration)
3803         << Old << Old->getType();
3804       return false;
3805     }
3806 
3807     PrevDiag = diag::note_previous_builtin_declaration;
3808   }
3809 
3810   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3811   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3812   return true;
3813 }
3814 
3815 /// Completes the merge of two function declarations that are
3816 /// known to be compatible.
3817 ///
3818 /// This routine handles the merging of attributes and other
3819 /// properties of function declarations from the old declaration to
3820 /// the new declaration, once we know that New is in fact a
3821 /// redeclaration of Old.
3822 ///
3823 /// \returns false
3824 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3825                                         Scope *S, bool MergeTypeWithOld) {
3826   // Merge the attributes
3827   mergeDeclAttributes(New, Old);
3828 
3829   // Merge "pure" flag.
3830   if (Old->isPure())
3831     New->setPure();
3832 
3833   // Merge "used" flag.
3834   if (Old->getMostRecentDecl()->isUsed(false))
3835     New->setIsUsed();
3836 
3837   // Merge attributes from the parameters.  These can mismatch with K&R
3838   // declarations.
3839   if (New->getNumParams() == Old->getNumParams())
3840       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3841         ParmVarDecl *NewParam = New->getParamDecl(i);
3842         ParmVarDecl *OldParam = Old->getParamDecl(i);
3843         mergeParamDeclAttributes(NewParam, OldParam, *this);
3844         mergeParamDeclTypes(NewParam, OldParam, *this);
3845       }
3846 
3847   if (getLangOpts().CPlusPlus)
3848     return MergeCXXFunctionDecl(New, Old, S);
3849 
3850   // Merge the function types so the we get the composite types for the return
3851   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3852   // was visible.
3853   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3854   if (!Merged.isNull() && MergeTypeWithOld)
3855     New->setType(Merged);
3856 
3857   return false;
3858 }
3859 
3860 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3861                                 ObjCMethodDecl *oldMethod) {
3862   // Merge the attributes, including deprecated/unavailable
3863   AvailabilityMergeKind MergeKind =
3864     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3865       ? AMK_ProtocolImplementation
3866       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3867                                                        : AMK_Override;
3868 
3869   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3870 
3871   // Merge attributes from the parameters.
3872   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3873                                        oe = oldMethod->param_end();
3874   for (ObjCMethodDecl::param_iterator
3875          ni = newMethod->param_begin(), ne = newMethod->param_end();
3876        ni != ne && oi != oe; ++ni, ++oi)
3877     mergeParamDeclAttributes(*ni, *oi, *this);
3878 
3879   CheckObjCMethodOverride(newMethod, oldMethod);
3880 }
3881 
3882 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3883   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3884 
3885   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3886          ? diag::err_redefinition_different_type
3887          : diag::err_redeclaration_different_type)
3888     << New->getDeclName() << New->getType() << Old->getType();
3889 
3890   diag::kind PrevDiag;
3891   SourceLocation OldLocation;
3892   std::tie(PrevDiag, OldLocation)
3893     = getNoteDiagForInvalidRedeclaration(Old, New);
3894   S.Diag(OldLocation, PrevDiag);
3895   New->setInvalidDecl();
3896 }
3897 
3898 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3899 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3900 /// emitting diagnostics as appropriate.
3901 ///
3902 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3903 /// to here in AddInitializerToDecl. We can't check them before the initializer
3904 /// is attached.
3905 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3906                              bool MergeTypeWithOld) {
3907   if (New->isInvalidDecl() || Old->isInvalidDecl())
3908     return;
3909 
3910   QualType MergedT;
3911   if (getLangOpts().CPlusPlus) {
3912     if (New->getType()->isUndeducedType()) {
3913       // We don't know what the new type is until the initializer is attached.
3914       return;
3915     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3916       // These could still be something that needs exception specs checked.
3917       return MergeVarDeclExceptionSpecs(New, Old);
3918     }
3919     // C++ [basic.link]p10:
3920     //   [...] the types specified by all declarations referring to a given
3921     //   object or function shall be identical, except that declarations for an
3922     //   array object can specify array types that differ by the presence or
3923     //   absence of a major array bound (8.3.4).
3924     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3925       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3926       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3927 
3928       // We are merging a variable declaration New into Old. If it has an array
3929       // bound, and that bound differs from Old's bound, we should diagnose the
3930       // mismatch.
3931       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3932         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3933              PrevVD = PrevVD->getPreviousDecl()) {
3934           QualType PrevVDTy = PrevVD->getType();
3935           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3936             continue;
3937 
3938           if (!Context.hasSameType(New->getType(), PrevVDTy))
3939             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3940         }
3941       }
3942 
3943       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3944         if (Context.hasSameType(OldArray->getElementType(),
3945                                 NewArray->getElementType()))
3946           MergedT = New->getType();
3947       }
3948       // FIXME: Check visibility. New is hidden but has a complete type. If New
3949       // has no array bound, it should not inherit one from Old, if Old is not
3950       // visible.
3951       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3952         if (Context.hasSameType(OldArray->getElementType(),
3953                                 NewArray->getElementType()))
3954           MergedT = Old->getType();
3955       }
3956     }
3957     else if (New->getType()->isObjCObjectPointerType() &&
3958                Old->getType()->isObjCObjectPointerType()) {
3959       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3960                                               Old->getType());
3961     }
3962   } else {
3963     // C 6.2.7p2:
3964     //   All declarations that refer to the same object or function shall have
3965     //   compatible type.
3966     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3967   }
3968   if (MergedT.isNull()) {
3969     // It's OK if we couldn't merge types if either type is dependent, for a
3970     // block-scope variable. In other cases (static data members of class
3971     // templates, variable templates, ...), we require the types to be
3972     // equivalent.
3973     // FIXME: The C++ standard doesn't say anything about this.
3974     if ((New->getType()->isDependentType() ||
3975          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3976       // If the old type was dependent, we can't merge with it, so the new type
3977       // becomes dependent for now. We'll reproduce the original type when we
3978       // instantiate the TypeSourceInfo for the variable.
3979       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3980         New->setType(Context.DependentTy);
3981       return;
3982     }
3983     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3984   }
3985 
3986   // Don't actually update the type on the new declaration if the old
3987   // declaration was an extern declaration in a different scope.
3988   if (MergeTypeWithOld)
3989     New->setType(MergedT);
3990 }
3991 
3992 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3993                                   LookupResult &Previous) {
3994   // C11 6.2.7p4:
3995   //   For an identifier with internal or external linkage declared
3996   //   in a scope in which a prior declaration of that identifier is
3997   //   visible, if the prior declaration specifies internal or
3998   //   external linkage, the type of the identifier at the later
3999   //   declaration becomes the composite type.
4000   //
4001   // If the variable isn't visible, we do not merge with its type.
4002   if (Previous.isShadowed())
4003     return false;
4004 
4005   if (S.getLangOpts().CPlusPlus) {
4006     // C++11 [dcl.array]p3:
4007     //   If there is a preceding declaration of the entity in the same
4008     //   scope in which the bound was specified, an omitted array bound
4009     //   is taken to be the same as in that earlier declaration.
4010     return NewVD->isPreviousDeclInSameBlockScope() ||
4011            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4012             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4013   } else {
4014     // If the old declaration was function-local, don't merge with its
4015     // type unless we're in the same function.
4016     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4017            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4018   }
4019 }
4020 
4021 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4022 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4023 /// situation, merging decls or emitting diagnostics as appropriate.
4024 ///
4025 /// Tentative definition rules (C99 6.9.2p2) are checked by
4026 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4027 /// definitions here, since the initializer hasn't been attached.
4028 ///
4029 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4030   // If the new decl is already invalid, don't do any other checking.
4031   if (New->isInvalidDecl())
4032     return;
4033 
4034   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4035     return;
4036 
4037   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4038 
4039   // Verify the old decl was also a variable or variable template.
4040   VarDecl *Old = nullptr;
4041   VarTemplateDecl *OldTemplate = nullptr;
4042   if (Previous.isSingleResult()) {
4043     if (NewTemplate) {
4044       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4045       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4046 
4047       if (auto *Shadow =
4048               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4049         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4050           return New->setInvalidDecl();
4051     } else {
4052       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4053 
4054       if (auto *Shadow =
4055               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4056         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4057           return New->setInvalidDecl();
4058     }
4059   }
4060   if (!Old) {
4061     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4062         << New->getDeclName();
4063     notePreviousDefinition(Previous.getRepresentativeDecl(),
4064                            New->getLocation());
4065     return New->setInvalidDecl();
4066   }
4067 
4068   // If the old declaration was found in an inline namespace and the new
4069   // declaration was qualified, update the DeclContext to match.
4070   adjustDeclContextForDeclaratorDecl(New, Old);
4071 
4072   // Ensure the template parameters are compatible.
4073   if (NewTemplate &&
4074       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4075                                       OldTemplate->getTemplateParameters(),
4076                                       /*Complain=*/true, TPL_TemplateMatch))
4077     return New->setInvalidDecl();
4078 
4079   // C++ [class.mem]p1:
4080   //   A member shall not be declared twice in the member-specification [...]
4081   //
4082   // Here, we need only consider static data members.
4083   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4084     Diag(New->getLocation(), diag::err_duplicate_member)
4085       << New->getIdentifier();
4086     Diag(Old->getLocation(), diag::note_previous_declaration);
4087     New->setInvalidDecl();
4088   }
4089 
4090   mergeDeclAttributes(New, Old);
4091   // Warn if an already-declared variable is made a weak_import in a subsequent
4092   // declaration
4093   if (New->hasAttr<WeakImportAttr>() &&
4094       Old->getStorageClass() == SC_None &&
4095       !Old->hasAttr<WeakImportAttr>()) {
4096     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4097     notePreviousDefinition(Old, New->getLocation());
4098     // Remove weak_import attribute on new declaration.
4099     New->dropAttr<WeakImportAttr>();
4100   }
4101 
4102   if (New->hasAttr<InternalLinkageAttr>() &&
4103       !Old->hasAttr<InternalLinkageAttr>()) {
4104     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
4105         << New->getDeclName();
4106     notePreviousDefinition(Old, New->getLocation());
4107     New->dropAttr<InternalLinkageAttr>();
4108   }
4109 
4110   // Merge the types.
4111   VarDecl *MostRecent = Old->getMostRecentDecl();
4112   if (MostRecent != Old) {
4113     MergeVarDeclTypes(New, MostRecent,
4114                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4115     if (New->isInvalidDecl())
4116       return;
4117   }
4118 
4119   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4120   if (New->isInvalidDecl())
4121     return;
4122 
4123   diag::kind PrevDiag;
4124   SourceLocation OldLocation;
4125   std::tie(PrevDiag, OldLocation) =
4126       getNoteDiagForInvalidRedeclaration(Old, New);
4127 
4128   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4129   if (New->getStorageClass() == SC_Static &&
4130       !New->isStaticDataMember() &&
4131       Old->hasExternalFormalLinkage()) {
4132     if (getLangOpts().MicrosoftExt) {
4133       Diag(New->getLocation(), diag::ext_static_non_static)
4134           << New->getDeclName();
4135       Diag(OldLocation, PrevDiag);
4136     } else {
4137       Diag(New->getLocation(), diag::err_static_non_static)
4138           << New->getDeclName();
4139       Diag(OldLocation, PrevDiag);
4140       return New->setInvalidDecl();
4141     }
4142   }
4143   // C99 6.2.2p4:
4144   //   For an identifier declared with the storage-class specifier
4145   //   extern in a scope in which a prior declaration of that
4146   //   identifier is visible,23) if the prior declaration specifies
4147   //   internal or external linkage, the linkage of the identifier at
4148   //   the later declaration is the same as the linkage specified at
4149   //   the prior declaration. If no prior declaration is visible, or
4150   //   if the prior declaration specifies no linkage, then the
4151   //   identifier has external linkage.
4152   if (New->hasExternalStorage() && Old->hasLinkage())
4153     /* Okay */;
4154   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4155            !New->isStaticDataMember() &&
4156            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4157     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4158     Diag(OldLocation, PrevDiag);
4159     return New->setInvalidDecl();
4160   }
4161 
4162   // Check if extern is followed by non-extern and vice-versa.
4163   if (New->hasExternalStorage() &&
4164       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4165     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4166     Diag(OldLocation, PrevDiag);
4167     return New->setInvalidDecl();
4168   }
4169   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4170       !New->hasExternalStorage()) {
4171     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4172     Diag(OldLocation, PrevDiag);
4173     return New->setInvalidDecl();
4174   }
4175 
4176   if (CheckRedeclarationModuleOwnership(New, Old))
4177     return;
4178 
4179   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4180 
4181   // FIXME: The test for external storage here seems wrong? We still
4182   // need to check for mismatches.
4183   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4184       // Don't complain about out-of-line definitions of static members.
4185       !(Old->getLexicalDeclContext()->isRecord() &&
4186         !New->getLexicalDeclContext()->isRecord())) {
4187     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4188     Diag(OldLocation, PrevDiag);
4189     return New->setInvalidDecl();
4190   }
4191 
4192   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4193     if (VarDecl *Def = Old->getDefinition()) {
4194       // C++1z [dcl.fcn.spec]p4:
4195       //   If the definition of a variable appears in a translation unit before
4196       //   its first declaration as inline, the program is ill-formed.
4197       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4198       Diag(Def->getLocation(), diag::note_previous_definition);
4199     }
4200   }
4201 
4202   // If this redeclaration makes the variable inline, we may need to add it to
4203   // UndefinedButUsed.
4204   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4205       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4206     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4207                                            SourceLocation()));
4208 
4209   if (New->getTLSKind() != Old->getTLSKind()) {
4210     if (!Old->getTLSKind()) {
4211       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4212       Diag(OldLocation, PrevDiag);
4213     } else if (!New->getTLSKind()) {
4214       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4215       Diag(OldLocation, PrevDiag);
4216     } else {
4217       // Do not allow redeclaration to change the variable between requiring
4218       // static and dynamic initialization.
4219       // FIXME: GCC allows this, but uses the TLS keyword on the first
4220       // declaration to determine the kind. Do we need to be compatible here?
4221       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4222         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4223       Diag(OldLocation, PrevDiag);
4224     }
4225   }
4226 
4227   // C++ doesn't have tentative definitions, so go right ahead and check here.
4228   if (getLangOpts().CPlusPlus &&
4229       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4230     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4231         Old->getCanonicalDecl()->isConstexpr()) {
4232       // This definition won't be a definition any more once it's been merged.
4233       Diag(New->getLocation(),
4234            diag::warn_deprecated_redundant_constexpr_static_def);
4235     } else if (VarDecl *Def = Old->getDefinition()) {
4236       if (checkVarDeclRedefinition(Def, New))
4237         return;
4238     }
4239   }
4240 
4241   if (haveIncompatibleLanguageLinkages(Old, New)) {
4242     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4243     Diag(OldLocation, PrevDiag);
4244     New->setInvalidDecl();
4245     return;
4246   }
4247 
4248   // Merge "used" flag.
4249   if (Old->getMostRecentDecl()->isUsed(false))
4250     New->setIsUsed();
4251 
4252   // Keep a chain of previous declarations.
4253   New->setPreviousDecl(Old);
4254   if (NewTemplate)
4255     NewTemplate->setPreviousDecl(OldTemplate);
4256 
4257   // Inherit access appropriately.
4258   New->setAccess(Old->getAccess());
4259   if (NewTemplate)
4260     NewTemplate->setAccess(New->getAccess());
4261 
4262   if (Old->isInline())
4263     New->setImplicitlyInline();
4264 }
4265 
4266 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4267   SourceManager &SrcMgr = getSourceManager();
4268   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4269   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4270   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4271   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4272   auto &HSI = PP.getHeaderSearchInfo();
4273   StringRef HdrFilename =
4274       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4275 
4276   auto noteFromModuleOrInclude = [&](Module *Mod,
4277                                      SourceLocation IncLoc) -> bool {
4278     // Redefinition errors with modules are common with non modular mapped
4279     // headers, example: a non-modular header H in module A that also gets
4280     // included directly in a TU. Pointing twice to the same header/definition
4281     // is confusing, try to get better diagnostics when modules is on.
4282     if (IncLoc.isValid()) {
4283       if (Mod) {
4284         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4285             << HdrFilename.str() << Mod->getFullModuleName();
4286         if (!Mod->DefinitionLoc.isInvalid())
4287           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4288               << Mod->getFullModuleName();
4289       } else {
4290         Diag(IncLoc, diag::note_redefinition_include_same_file)
4291             << HdrFilename.str();
4292       }
4293       return true;
4294     }
4295 
4296     return false;
4297   };
4298 
4299   // Is it the same file and same offset? Provide more information on why
4300   // this leads to a redefinition error.
4301   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4302     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4303     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4304     bool EmittedDiag =
4305         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4306     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4307 
4308     // If the header has no guards, emit a note suggesting one.
4309     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4310       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4311 
4312     if (EmittedDiag)
4313       return;
4314   }
4315 
4316   // Redefinition coming from different files or couldn't do better above.
4317   if (Old->getLocation().isValid())
4318     Diag(Old->getLocation(), diag::note_previous_definition);
4319 }
4320 
4321 /// We've just determined that \p Old and \p New both appear to be definitions
4322 /// of the same variable. Either diagnose or fix the problem.
4323 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4324   if (!hasVisibleDefinition(Old) &&
4325       (New->getFormalLinkage() == InternalLinkage ||
4326        New->isInline() ||
4327        New->getDescribedVarTemplate() ||
4328        New->getNumTemplateParameterLists() ||
4329        New->getDeclContext()->isDependentContext())) {
4330     // The previous definition is hidden, and multiple definitions are
4331     // permitted (in separate TUs). Demote this to a declaration.
4332     New->demoteThisDefinitionToDeclaration();
4333 
4334     // Make the canonical definition visible.
4335     if (auto *OldTD = Old->getDescribedVarTemplate())
4336       makeMergedDefinitionVisible(OldTD);
4337     makeMergedDefinitionVisible(Old);
4338     return false;
4339   } else {
4340     Diag(New->getLocation(), diag::err_redefinition) << New;
4341     notePreviousDefinition(Old, New->getLocation());
4342     New->setInvalidDecl();
4343     return true;
4344   }
4345 }
4346 
4347 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4348 /// no declarator (e.g. "struct foo;") is parsed.
4349 Decl *
4350 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4351                                  RecordDecl *&AnonRecord) {
4352   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4353                                     AnonRecord);
4354 }
4355 
4356 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4357 // disambiguate entities defined in different scopes.
4358 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4359 // compatibility.
4360 // We will pick our mangling number depending on which version of MSVC is being
4361 // targeted.
4362 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4363   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4364              ? S->getMSCurManglingNumber()
4365              : S->getMSLastManglingNumber();
4366 }
4367 
4368 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4369   if (!Context.getLangOpts().CPlusPlus)
4370     return;
4371 
4372   if (isa<CXXRecordDecl>(Tag->getParent())) {
4373     // If this tag is the direct child of a class, number it if
4374     // it is anonymous.
4375     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4376       return;
4377     MangleNumberingContext &MCtx =
4378         Context.getManglingNumberContext(Tag->getParent());
4379     Context.setManglingNumber(
4380         Tag, MCtx.getManglingNumber(
4381                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4382     return;
4383   }
4384 
4385   // If this tag isn't a direct child of a class, number it if it is local.
4386   MangleNumberingContext *MCtx;
4387   Decl *ManglingContextDecl;
4388   std::tie(MCtx, ManglingContextDecl) =
4389       getCurrentMangleNumberContext(Tag->getDeclContext());
4390   if (MCtx) {
4391     Context.setManglingNumber(
4392         Tag, MCtx->getManglingNumber(
4393                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4394   }
4395 }
4396 
4397 namespace {
4398 struct NonCLikeKind {
4399   enum {
4400     None,
4401     BaseClass,
4402     DefaultMemberInit,
4403     Lambda,
4404     Friend,
4405     OtherMember,
4406     Invalid,
4407   } Kind = None;
4408   SourceRange Range;
4409 
4410   explicit operator bool() { return Kind != None; }
4411 };
4412 }
4413 
4414 /// Determine whether a class is C-like, according to the rules of C++
4415 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4416 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4417   if (RD->isInvalidDecl())
4418     return {NonCLikeKind::Invalid, {}};
4419 
4420   // C++ [dcl.typedef]p9: [P1766R1]
4421   //   An unnamed class with a typedef name for linkage purposes shall not
4422   //
4423   //    -- have any base classes
4424   if (RD->getNumBases())
4425     return {NonCLikeKind::BaseClass,
4426             SourceRange(RD->bases_begin()->getBeginLoc(),
4427                         RD->bases_end()[-1].getEndLoc())};
4428   bool Invalid = false;
4429   for (Decl *D : RD->decls()) {
4430     // Don't complain about things we already diagnosed.
4431     if (D->isInvalidDecl()) {
4432       Invalid = true;
4433       continue;
4434     }
4435 
4436     //  -- have any [...] default member initializers
4437     if (auto *FD = dyn_cast<FieldDecl>(D)) {
4438       if (FD->hasInClassInitializer()) {
4439         auto *Init = FD->getInClassInitializer();
4440         return {NonCLikeKind::DefaultMemberInit,
4441                 Init ? Init->getSourceRange() : D->getSourceRange()};
4442       }
4443       continue;
4444     }
4445 
4446     // FIXME: We don't allow friend declarations. This violates the wording of
4447     // P1766, but not the intent.
4448     if (isa<FriendDecl>(D))
4449       return {NonCLikeKind::Friend, D->getSourceRange()};
4450 
4451     //  -- declare any members other than non-static data members, member
4452     //     enumerations, or member classes,
4453     if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4454         isa<EnumDecl>(D))
4455       continue;
4456     auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4457     if (!MemberRD) {
4458       if (D->isImplicit())
4459         continue;
4460       return {NonCLikeKind::OtherMember, D->getSourceRange()};
4461     }
4462 
4463     //  -- contain a lambda-expression,
4464     if (MemberRD->isLambda())
4465       return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4466 
4467     //  and all member classes shall also satisfy these requirements
4468     //  (recursively).
4469     if (MemberRD->isThisDeclarationADefinition()) {
4470       if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4471         return Kind;
4472     }
4473   }
4474 
4475   return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4476 }
4477 
4478 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4479                                         TypedefNameDecl *NewTD) {
4480   if (TagFromDeclSpec->isInvalidDecl())
4481     return;
4482 
4483   // Do nothing if the tag already has a name for linkage purposes.
4484   if (TagFromDeclSpec->hasNameForLinkage())
4485     return;
4486 
4487   // A well-formed anonymous tag must always be a TUK_Definition.
4488   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4489 
4490   // The type must match the tag exactly;  no qualifiers allowed.
4491   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4492                            Context.getTagDeclType(TagFromDeclSpec))) {
4493     if (getLangOpts().CPlusPlus)
4494       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4495     return;
4496   }
4497 
4498   // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4499   //   An unnamed class with a typedef name for linkage purposes shall [be
4500   //   C-like].
4501   //
4502   // FIXME: Also diagnose if we've already computed the linkage. That ideally
4503   // shouldn't happen, but there are constructs that the language rule doesn't
4504   // disallow for which we can't reasonably avoid computing linkage early.
4505   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4506   NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4507                              : NonCLikeKind();
4508   bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4509   if (NonCLike || ChangesLinkage) {
4510     if (NonCLike.Kind == NonCLikeKind::Invalid)
4511       return;
4512 
4513     unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4514     if (ChangesLinkage) {
4515       // If the linkage changes, we can't accept this as an extension.
4516       if (NonCLike.Kind == NonCLikeKind::None)
4517         DiagID = diag::err_typedef_changes_linkage;
4518       else
4519         DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4520     }
4521 
4522     SourceLocation FixitLoc =
4523         getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4524     llvm::SmallString<40> TextToInsert;
4525     TextToInsert += ' ';
4526     TextToInsert += NewTD->getIdentifier()->getName();
4527 
4528     Diag(FixitLoc, DiagID)
4529       << isa<TypeAliasDecl>(NewTD)
4530       << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4531     if (NonCLike.Kind != NonCLikeKind::None) {
4532       Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4533         << NonCLike.Kind - 1 << NonCLike.Range;
4534     }
4535     Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4536       << NewTD << isa<TypeAliasDecl>(NewTD);
4537 
4538     if (ChangesLinkage)
4539       return;
4540   }
4541 
4542   // Otherwise, set this as the anon-decl typedef for the tag.
4543   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4544 }
4545 
4546 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4547   switch (T) {
4548   case DeclSpec::TST_class:
4549     return 0;
4550   case DeclSpec::TST_struct:
4551     return 1;
4552   case DeclSpec::TST_interface:
4553     return 2;
4554   case DeclSpec::TST_union:
4555     return 3;
4556   case DeclSpec::TST_enum:
4557     return 4;
4558   default:
4559     llvm_unreachable("unexpected type specifier");
4560   }
4561 }
4562 
4563 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4564 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4565 /// parameters to cope with template friend declarations.
4566 Decl *
4567 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4568                                  MultiTemplateParamsArg TemplateParams,
4569                                  bool IsExplicitInstantiation,
4570                                  RecordDecl *&AnonRecord) {
4571   Decl *TagD = nullptr;
4572   TagDecl *Tag = nullptr;
4573   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4574       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4575       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4576       DS.getTypeSpecType() == DeclSpec::TST_union ||
4577       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4578     TagD = DS.getRepAsDecl();
4579 
4580     if (!TagD) // We probably had an error
4581       return nullptr;
4582 
4583     // Note that the above type specs guarantee that the
4584     // type rep is a Decl, whereas in many of the others
4585     // it's a Type.
4586     if (isa<TagDecl>(TagD))
4587       Tag = cast<TagDecl>(TagD);
4588     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4589       Tag = CTD->getTemplatedDecl();
4590   }
4591 
4592   if (Tag) {
4593     handleTagNumbering(Tag, S);
4594     Tag->setFreeStanding();
4595     if (Tag->isInvalidDecl())
4596       return Tag;
4597   }
4598 
4599   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4600     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4601     // or incomplete types shall not be restrict-qualified."
4602     if (TypeQuals & DeclSpec::TQ_restrict)
4603       Diag(DS.getRestrictSpecLoc(),
4604            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4605            << DS.getSourceRange();
4606   }
4607 
4608   if (DS.isInlineSpecified())
4609     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4610         << getLangOpts().CPlusPlus17;
4611 
4612   if (DS.hasConstexprSpecifier()) {
4613     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4614     // and definitions of functions and variables.
4615     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4616     // the declaration of a function or function template
4617     if (Tag)
4618       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4619           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4620           << static_cast<int>(DS.getConstexprSpecifier());
4621     else
4622       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4623           << static_cast<int>(DS.getConstexprSpecifier());
4624     // Don't emit warnings after this error.
4625     return TagD;
4626   }
4627 
4628   DiagnoseFunctionSpecifiers(DS);
4629 
4630   if (DS.isFriendSpecified()) {
4631     // If we're dealing with a decl but not a TagDecl, assume that
4632     // whatever routines created it handled the friendship aspect.
4633     if (TagD && !Tag)
4634       return nullptr;
4635     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4636   }
4637 
4638   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4639   bool IsExplicitSpecialization =
4640     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4641   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4642       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4643       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4644     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4645     // nested-name-specifier unless it is an explicit instantiation
4646     // or an explicit specialization.
4647     //
4648     // FIXME: We allow class template partial specializations here too, per the
4649     // obvious intent of DR1819.
4650     //
4651     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4652     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4653         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4654     return nullptr;
4655   }
4656 
4657   // Track whether this decl-specifier declares anything.
4658   bool DeclaresAnything = true;
4659 
4660   // Handle anonymous struct definitions.
4661   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4662     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4663         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4664       if (getLangOpts().CPlusPlus ||
4665           Record->getDeclContext()->isRecord()) {
4666         // If CurContext is a DeclContext that can contain statements,
4667         // RecursiveASTVisitor won't visit the decls that
4668         // BuildAnonymousStructOrUnion() will put into CurContext.
4669         // Also store them here so that they can be part of the
4670         // DeclStmt that gets created in this case.
4671         // FIXME: Also return the IndirectFieldDecls created by
4672         // BuildAnonymousStructOr union, for the same reason?
4673         if (CurContext->isFunctionOrMethod())
4674           AnonRecord = Record;
4675         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4676                                            Context.getPrintingPolicy());
4677       }
4678 
4679       DeclaresAnything = false;
4680     }
4681   }
4682 
4683   // C11 6.7.2.1p2:
4684   //   A struct-declaration that does not declare an anonymous structure or
4685   //   anonymous union shall contain a struct-declarator-list.
4686   //
4687   // This rule also existed in C89 and C99; the grammar for struct-declaration
4688   // did not permit a struct-declaration without a struct-declarator-list.
4689   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4690       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4691     // Check for Microsoft C extension: anonymous struct/union member.
4692     // Handle 2 kinds of anonymous struct/union:
4693     //   struct STRUCT;
4694     //   union UNION;
4695     // and
4696     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4697     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4698     if ((Tag && Tag->getDeclName()) ||
4699         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4700       RecordDecl *Record = nullptr;
4701       if (Tag)
4702         Record = dyn_cast<RecordDecl>(Tag);
4703       else if (const RecordType *RT =
4704                    DS.getRepAsType().get()->getAsStructureType())
4705         Record = RT->getDecl();
4706       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4707         Record = UT->getDecl();
4708 
4709       if (Record && getLangOpts().MicrosoftExt) {
4710         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4711             << Record->isUnion() << DS.getSourceRange();
4712         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4713       }
4714 
4715       DeclaresAnything = false;
4716     }
4717   }
4718 
4719   // Skip all the checks below if we have a type error.
4720   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4721       (TagD && TagD->isInvalidDecl()))
4722     return TagD;
4723 
4724   if (getLangOpts().CPlusPlus &&
4725       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4726     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4727       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4728           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4729         DeclaresAnything = false;
4730 
4731   if (!DS.isMissingDeclaratorOk()) {
4732     // Customize diagnostic for a typedef missing a name.
4733     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4734       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4735           << DS.getSourceRange();
4736     else
4737       DeclaresAnything = false;
4738   }
4739 
4740   if (DS.isModulePrivateSpecified() &&
4741       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4742     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4743       << Tag->getTagKind()
4744       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4745 
4746   ActOnDocumentableDecl(TagD);
4747 
4748   // C 6.7/2:
4749   //   A declaration [...] shall declare at least a declarator [...], a tag,
4750   //   or the members of an enumeration.
4751   // C++ [dcl.dcl]p3:
4752   //   [If there are no declarators], and except for the declaration of an
4753   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4754   //   names into the program, or shall redeclare a name introduced by a
4755   //   previous declaration.
4756   if (!DeclaresAnything) {
4757     // In C, we allow this as a (popular) extension / bug. Don't bother
4758     // producing further diagnostics for redundant qualifiers after this.
4759     Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
4760                                ? diag::err_no_declarators
4761                                : diag::ext_no_declarators)
4762         << DS.getSourceRange();
4763     return TagD;
4764   }
4765 
4766   // C++ [dcl.stc]p1:
4767   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4768   //   init-declarator-list of the declaration shall not be empty.
4769   // C++ [dcl.fct.spec]p1:
4770   //   If a cv-qualifier appears in a decl-specifier-seq, the
4771   //   init-declarator-list of the declaration shall not be empty.
4772   //
4773   // Spurious qualifiers here appear to be valid in C.
4774   unsigned DiagID = diag::warn_standalone_specifier;
4775   if (getLangOpts().CPlusPlus)
4776     DiagID = diag::ext_standalone_specifier;
4777 
4778   // Note that a linkage-specification sets a storage class, but
4779   // 'extern "C" struct foo;' is actually valid and not theoretically
4780   // useless.
4781   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4782     if (SCS == DeclSpec::SCS_mutable)
4783       // Since mutable is not a viable storage class specifier in C, there is
4784       // no reason to treat it as an extension. Instead, diagnose as an error.
4785       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4786     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4787       Diag(DS.getStorageClassSpecLoc(), DiagID)
4788         << DeclSpec::getSpecifierName(SCS);
4789   }
4790 
4791   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4792     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4793       << DeclSpec::getSpecifierName(TSCS);
4794   if (DS.getTypeQualifiers()) {
4795     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4796       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4797     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4798       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4799     // Restrict is covered above.
4800     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4801       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4802     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4803       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4804   }
4805 
4806   // Warn about ignored type attributes, for example:
4807   // __attribute__((aligned)) struct A;
4808   // Attributes should be placed after tag to apply to type declaration.
4809   if (!DS.getAttributes().empty()) {
4810     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4811     if (TypeSpecType == DeclSpec::TST_class ||
4812         TypeSpecType == DeclSpec::TST_struct ||
4813         TypeSpecType == DeclSpec::TST_interface ||
4814         TypeSpecType == DeclSpec::TST_union ||
4815         TypeSpecType == DeclSpec::TST_enum) {
4816       for (const ParsedAttr &AL : DS.getAttributes())
4817         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4818             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4819     }
4820   }
4821 
4822   return TagD;
4823 }
4824 
4825 /// We are trying to inject an anonymous member into the given scope;
4826 /// check if there's an existing declaration that can't be overloaded.
4827 ///
4828 /// \return true if this is a forbidden redeclaration
4829 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4830                                          Scope *S,
4831                                          DeclContext *Owner,
4832                                          DeclarationName Name,
4833                                          SourceLocation NameLoc,
4834                                          bool IsUnion) {
4835   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4836                  Sema::ForVisibleRedeclaration);
4837   if (!SemaRef.LookupName(R, S)) return false;
4838 
4839   // Pick a representative declaration.
4840   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4841   assert(PrevDecl && "Expected a non-null Decl");
4842 
4843   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4844     return false;
4845 
4846   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4847     << IsUnion << Name;
4848   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4849 
4850   return true;
4851 }
4852 
4853 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4854 /// anonymous struct or union AnonRecord into the owning context Owner
4855 /// and scope S. This routine will be invoked just after we realize
4856 /// that an unnamed union or struct is actually an anonymous union or
4857 /// struct, e.g.,
4858 ///
4859 /// @code
4860 /// union {
4861 ///   int i;
4862 ///   float f;
4863 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4864 ///    // f into the surrounding scope.x
4865 /// @endcode
4866 ///
4867 /// This routine is recursive, injecting the names of nested anonymous
4868 /// structs/unions into the owning context and scope as well.
4869 static bool
4870 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4871                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4872                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4873   bool Invalid = false;
4874 
4875   // Look every FieldDecl and IndirectFieldDecl with a name.
4876   for (auto *D : AnonRecord->decls()) {
4877     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4878         cast<NamedDecl>(D)->getDeclName()) {
4879       ValueDecl *VD = cast<ValueDecl>(D);
4880       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4881                                        VD->getLocation(),
4882                                        AnonRecord->isUnion())) {
4883         // C++ [class.union]p2:
4884         //   The names of the members of an anonymous union shall be
4885         //   distinct from the names of any other entity in the
4886         //   scope in which the anonymous union is declared.
4887         Invalid = true;
4888       } else {
4889         // C++ [class.union]p2:
4890         //   For the purpose of name lookup, after the anonymous union
4891         //   definition, the members of the anonymous union are
4892         //   considered to have been defined in the scope in which the
4893         //   anonymous union is declared.
4894         unsigned OldChainingSize = Chaining.size();
4895         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4896           Chaining.append(IF->chain_begin(), IF->chain_end());
4897         else
4898           Chaining.push_back(VD);
4899 
4900         assert(Chaining.size() >= 2);
4901         NamedDecl **NamedChain =
4902           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4903         for (unsigned i = 0; i < Chaining.size(); i++)
4904           NamedChain[i] = Chaining[i];
4905 
4906         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4907             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4908             VD->getType(), {NamedChain, Chaining.size()});
4909 
4910         for (const auto *Attr : VD->attrs())
4911           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4912 
4913         IndirectField->setAccess(AS);
4914         IndirectField->setImplicit();
4915         SemaRef.PushOnScopeChains(IndirectField, S);
4916 
4917         // That includes picking up the appropriate access specifier.
4918         if (AS != AS_none) IndirectField->setAccess(AS);
4919 
4920         Chaining.resize(OldChainingSize);
4921       }
4922     }
4923   }
4924 
4925   return Invalid;
4926 }
4927 
4928 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4929 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4930 /// illegal input values are mapped to SC_None.
4931 static StorageClass
4932 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4933   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4934   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4935          "Parser allowed 'typedef' as storage class VarDecl.");
4936   switch (StorageClassSpec) {
4937   case DeclSpec::SCS_unspecified:    return SC_None;
4938   case DeclSpec::SCS_extern:
4939     if (DS.isExternInLinkageSpec())
4940       return SC_None;
4941     return SC_Extern;
4942   case DeclSpec::SCS_static:         return SC_Static;
4943   case DeclSpec::SCS_auto:           return SC_Auto;
4944   case DeclSpec::SCS_register:       return SC_Register;
4945   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4946     // Illegal SCSs map to None: error reporting is up to the caller.
4947   case DeclSpec::SCS_mutable:        // Fall through.
4948   case DeclSpec::SCS_typedef:        return SC_None;
4949   }
4950   llvm_unreachable("unknown storage class specifier");
4951 }
4952 
4953 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4954   assert(Record->hasInClassInitializer());
4955 
4956   for (const auto *I : Record->decls()) {
4957     const auto *FD = dyn_cast<FieldDecl>(I);
4958     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4959       FD = IFD->getAnonField();
4960     if (FD && FD->hasInClassInitializer())
4961       return FD->getLocation();
4962   }
4963 
4964   llvm_unreachable("couldn't find in-class initializer");
4965 }
4966 
4967 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4968                                       SourceLocation DefaultInitLoc) {
4969   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4970     return;
4971 
4972   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4973   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4974 }
4975 
4976 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4977                                       CXXRecordDecl *AnonUnion) {
4978   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4979     return;
4980 
4981   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4982 }
4983 
4984 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4985 /// anonymous structure or union. Anonymous unions are a C++ feature
4986 /// (C++ [class.union]) and a C11 feature; anonymous structures
4987 /// are a C11 feature and GNU C++ extension.
4988 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4989                                         AccessSpecifier AS,
4990                                         RecordDecl *Record,
4991                                         const PrintingPolicy &Policy) {
4992   DeclContext *Owner = Record->getDeclContext();
4993 
4994   // Diagnose whether this anonymous struct/union is an extension.
4995   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4996     Diag(Record->getLocation(), diag::ext_anonymous_union);
4997   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4998     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4999   else if (!Record->isUnion() && !getLangOpts().C11)
5000     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5001 
5002   // C and C++ require different kinds of checks for anonymous
5003   // structs/unions.
5004   bool Invalid = false;
5005   if (getLangOpts().CPlusPlus) {
5006     const char *PrevSpec = nullptr;
5007     if (Record->isUnion()) {
5008       // C++ [class.union]p6:
5009       // C++17 [class.union.anon]p2:
5010       //   Anonymous unions declared in a named namespace or in the
5011       //   global namespace shall be declared static.
5012       unsigned DiagID;
5013       DeclContext *OwnerScope = Owner->getRedeclContext();
5014       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5015           (OwnerScope->isTranslationUnit() ||
5016            (OwnerScope->isNamespace() &&
5017             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5018         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5019           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5020 
5021         // Recover by adding 'static'.
5022         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5023                                PrevSpec, DiagID, Policy);
5024       }
5025       // C++ [class.union]p6:
5026       //   A storage class is not allowed in a declaration of an
5027       //   anonymous union in a class scope.
5028       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5029                isa<RecordDecl>(Owner)) {
5030         Diag(DS.getStorageClassSpecLoc(),
5031              diag::err_anonymous_union_with_storage_spec)
5032           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5033 
5034         // Recover by removing the storage specifier.
5035         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5036                                SourceLocation(),
5037                                PrevSpec, DiagID, Context.getPrintingPolicy());
5038       }
5039     }
5040 
5041     // Ignore const/volatile/restrict qualifiers.
5042     if (DS.getTypeQualifiers()) {
5043       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5044         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5045           << Record->isUnion() << "const"
5046           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5047       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5048         Diag(DS.getVolatileSpecLoc(),
5049              diag::ext_anonymous_struct_union_qualified)
5050           << Record->isUnion() << "volatile"
5051           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5052       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5053         Diag(DS.getRestrictSpecLoc(),
5054              diag::ext_anonymous_struct_union_qualified)
5055           << Record->isUnion() << "restrict"
5056           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5057       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5058         Diag(DS.getAtomicSpecLoc(),
5059              diag::ext_anonymous_struct_union_qualified)
5060           << Record->isUnion() << "_Atomic"
5061           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5062       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5063         Diag(DS.getUnalignedSpecLoc(),
5064              diag::ext_anonymous_struct_union_qualified)
5065           << Record->isUnion() << "__unaligned"
5066           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5067 
5068       DS.ClearTypeQualifiers();
5069     }
5070 
5071     // C++ [class.union]p2:
5072     //   The member-specification of an anonymous union shall only
5073     //   define non-static data members. [Note: nested types and
5074     //   functions cannot be declared within an anonymous union. ]
5075     for (auto *Mem : Record->decls()) {
5076       // Ignore invalid declarations; we already diagnosed them.
5077       if (Mem->isInvalidDecl())
5078         continue;
5079 
5080       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5081         // C++ [class.union]p3:
5082         //   An anonymous union shall not have private or protected
5083         //   members (clause 11).
5084         assert(FD->getAccess() != AS_none);
5085         if (FD->getAccess() != AS_public) {
5086           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5087             << Record->isUnion() << (FD->getAccess() == AS_protected);
5088           Invalid = true;
5089         }
5090 
5091         // C++ [class.union]p1
5092         //   An object of a class with a non-trivial constructor, a non-trivial
5093         //   copy constructor, a non-trivial destructor, or a non-trivial copy
5094         //   assignment operator cannot be a member of a union, nor can an
5095         //   array of such objects.
5096         if (CheckNontrivialField(FD))
5097           Invalid = true;
5098       } else if (Mem->isImplicit()) {
5099         // Any implicit members are fine.
5100       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5101         // This is a type that showed up in an
5102         // elaborated-type-specifier inside the anonymous struct or
5103         // union, but which actually declares a type outside of the
5104         // anonymous struct or union. It's okay.
5105       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5106         if (!MemRecord->isAnonymousStructOrUnion() &&
5107             MemRecord->getDeclName()) {
5108           // Visual C++ allows type definition in anonymous struct or union.
5109           if (getLangOpts().MicrosoftExt)
5110             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5111               << Record->isUnion();
5112           else {
5113             // This is a nested type declaration.
5114             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5115               << Record->isUnion();
5116             Invalid = true;
5117           }
5118         } else {
5119           // This is an anonymous type definition within another anonymous type.
5120           // This is a popular extension, provided by Plan9, MSVC and GCC, but
5121           // not part of standard C++.
5122           Diag(MemRecord->getLocation(),
5123                diag::ext_anonymous_record_with_anonymous_type)
5124             << Record->isUnion();
5125         }
5126       } else if (isa<AccessSpecDecl>(Mem)) {
5127         // Any access specifier is fine.
5128       } else if (isa<StaticAssertDecl>(Mem)) {
5129         // In C++1z, static_assert declarations are also fine.
5130       } else {
5131         // We have something that isn't a non-static data
5132         // member. Complain about it.
5133         unsigned DK = diag::err_anonymous_record_bad_member;
5134         if (isa<TypeDecl>(Mem))
5135           DK = diag::err_anonymous_record_with_type;
5136         else if (isa<FunctionDecl>(Mem))
5137           DK = diag::err_anonymous_record_with_function;
5138         else if (isa<VarDecl>(Mem))
5139           DK = diag::err_anonymous_record_with_static;
5140 
5141         // Visual C++ allows type definition in anonymous struct or union.
5142         if (getLangOpts().MicrosoftExt &&
5143             DK == diag::err_anonymous_record_with_type)
5144           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5145             << Record->isUnion();
5146         else {
5147           Diag(Mem->getLocation(), DK) << Record->isUnion();
5148           Invalid = true;
5149         }
5150       }
5151     }
5152 
5153     // C++11 [class.union]p8 (DR1460):
5154     //   At most one variant member of a union may have a
5155     //   brace-or-equal-initializer.
5156     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5157         Owner->isRecord())
5158       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5159                                 cast<CXXRecordDecl>(Record));
5160   }
5161 
5162   if (!Record->isUnion() && !Owner->isRecord()) {
5163     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5164       << getLangOpts().CPlusPlus;
5165     Invalid = true;
5166   }
5167 
5168   // C++ [dcl.dcl]p3:
5169   //   [If there are no declarators], and except for the declaration of an
5170   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5171   //   names into the program
5172   // C++ [class.mem]p2:
5173   //   each such member-declaration shall either declare at least one member
5174   //   name of the class or declare at least one unnamed bit-field
5175   //
5176   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5177   if (getLangOpts().CPlusPlus && Record->field_empty())
5178     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5179 
5180   // Mock up a declarator.
5181   Declarator Dc(DS, DeclaratorContext::Member);
5182   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5183   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5184 
5185   // Create a declaration for this anonymous struct/union.
5186   NamedDecl *Anon = nullptr;
5187   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5188     Anon = FieldDecl::Create(
5189         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5190         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5191         /*BitWidth=*/nullptr, /*Mutable=*/false,
5192         /*InitStyle=*/ICIS_NoInit);
5193     Anon->setAccess(AS);
5194     ProcessDeclAttributes(S, Anon, Dc);
5195 
5196     if (getLangOpts().CPlusPlus)
5197       FieldCollector->Add(cast<FieldDecl>(Anon));
5198   } else {
5199     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5200     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5201     if (SCSpec == DeclSpec::SCS_mutable) {
5202       // mutable can only appear on non-static class members, so it's always
5203       // an error here
5204       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5205       Invalid = true;
5206       SC = SC_None;
5207     }
5208 
5209     assert(DS.getAttributes().empty() && "No attribute expected");
5210     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5211                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5212                            Context.getTypeDeclType(Record), TInfo, SC);
5213 
5214     // Default-initialize the implicit variable. This initialization will be
5215     // trivial in almost all cases, except if a union member has an in-class
5216     // initializer:
5217     //   union { int n = 0; };
5218     if (!Invalid)
5219       ActOnUninitializedDecl(Anon);
5220   }
5221   Anon->setImplicit();
5222 
5223   // Mark this as an anonymous struct/union type.
5224   Record->setAnonymousStructOrUnion(true);
5225 
5226   // Add the anonymous struct/union object to the current
5227   // context. We'll be referencing this object when we refer to one of
5228   // its members.
5229   Owner->addDecl(Anon);
5230 
5231   // Inject the members of the anonymous struct/union into the owning
5232   // context and into the identifier resolver chain for name lookup
5233   // purposes.
5234   SmallVector<NamedDecl*, 2> Chain;
5235   Chain.push_back(Anon);
5236 
5237   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5238     Invalid = true;
5239 
5240   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5241     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5242       MangleNumberingContext *MCtx;
5243       Decl *ManglingContextDecl;
5244       std::tie(MCtx, ManglingContextDecl) =
5245           getCurrentMangleNumberContext(NewVD->getDeclContext());
5246       if (MCtx) {
5247         Context.setManglingNumber(
5248             NewVD, MCtx->getManglingNumber(
5249                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5250         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5251       }
5252     }
5253   }
5254 
5255   if (Invalid)
5256     Anon->setInvalidDecl();
5257 
5258   return Anon;
5259 }
5260 
5261 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5262 /// Microsoft C anonymous structure.
5263 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5264 /// Example:
5265 ///
5266 /// struct A { int a; };
5267 /// struct B { struct A; int b; };
5268 ///
5269 /// void foo() {
5270 ///   B var;
5271 ///   var.a = 3;
5272 /// }
5273 ///
5274 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5275                                            RecordDecl *Record) {
5276   assert(Record && "expected a record!");
5277 
5278   // Mock up a declarator.
5279   Declarator Dc(DS, DeclaratorContext::TypeName);
5280   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5281   assert(TInfo && "couldn't build declarator info for anonymous struct");
5282 
5283   auto *ParentDecl = cast<RecordDecl>(CurContext);
5284   QualType RecTy = Context.getTypeDeclType(Record);
5285 
5286   // Create a declaration for this anonymous struct.
5287   NamedDecl *Anon =
5288       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5289                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5290                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5291                         /*InitStyle=*/ICIS_NoInit);
5292   Anon->setImplicit();
5293 
5294   // Add the anonymous struct object to the current context.
5295   CurContext->addDecl(Anon);
5296 
5297   // Inject the members of the anonymous struct into the current
5298   // context and into the identifier resolver chain for name lookup
5299   // purposes.
5300   SmallVector<NamedDecl*, 2> Chain;
5301   Chain.push_back(Anon);
5302 
5303   RecordDecl *RecordDef = Record->getDefinition();
5304   if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5305                                diag::err_field_incomplete_or_sizeless) ||
5306       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5307                                           AS_none, Chain)) {
5308     Anon->setInvalidDecl();
5309     ParentDecl->setInvalidDecl();
5310   }
5311 
5312   return Anon;
5313 }
5314 
5315 /// GetNameForDeclarator - Determine the full declaration name for the
5316 /// given Declarator.
5317 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5318   return GetNameFromUnqualifiedId(D.getName());
5319 }
5320 
5321 /// Retrieves the declaration name from a parsed unqualified-id.
5322 DeclarationNameInfo
5323 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5324   DeclarationNameInfo NameInfo;
5325   NameInfo.setLoc(Name.StartLocation);
5326 
5327   switch (Name.getKind()) {
5328 
5329   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5330   case UnqualifiedIdKind::IK_Identifier:
5331     NameInfo.setName(Name.Identifier);
5332     return NameInfo;
5333 
5334   case UnqualifiedIdKind::IK_DeductionGuideName: {
5335     // C++ [temp.deduct.guide]p3:
5336     //   The simple-template-id shall name a class template specialization.
5337     //   The template-name shall be the same identifier as the template-name
5338     //   of the simple-template-id.
5339     // These together intend to imply that the template-name shall name a
5340     // class template.
5341     // FIXME: template<typename T> struct X {};
5342     //        template<typename T> using Y = X<T>;
5343     //        Y(int) -> Y<int>;
5344     //   satisfies these rules but does not name a class template.
5345     TemplateName TN = Name.TemplateName.get().get();
5346     auto *Template = TN.getAsTemplateDecl();
5347     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5348       Diag(Name.StartLocation,
5349            diag::err_deduction_guide_name_not_class_template)
5350         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5351       if (Template)
5352         Diag(Template->getLocation(), diag::note_template_decl_here);
5353       return DeclarationNameInfo();
5354     }
5355 
5356     NameInfo.setName(
5357         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5358     return NameInfo;
5359   }
5360 
5361   case UnqualifiedIdKind::IK_OperatorFunctionId:
5362     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5363                                            Name.OperatorFunctionId.Operator));
5364     NameInfo.setCXXOperatorNameRange(SourceRange(
5365         Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5366     return NameInfo;
5367 
5368   case UnqualifiedIdKind::IK_LiteralOperatorId:
5369     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5370                                                            Name.Identifier));
5371     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5372     return NameInfo;
5373 
5374   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5375     TypeSourceInfo *TInfo;
5376     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5377     if (Ty.isNull())
5378       return DeclarationNameInfo();
5379     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5380                                                Context.getCanonicalType(Ty)));
5381     NameInfo.setNamedTypeInfo(TInfo);
5382     return NameInfo;
5383   }
5384 
5385   case UnqualifiedIdKind::IK_ConstructorName: {
5386     TypeSourceInfo *TInfo;
5387     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5388     if (Ty.isNull())
5389       return DeclarationNameInfo();
5390     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5391                                               Context.getCanonicalType(Ty)));
5392     NameInfo.setNamedTypeInfo(TInfo);
5393     return NameInfo;
5394   }
5395 
5396   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5397     // In well-formed code, we can only have a constructor
5398     // template-id that refers to the current context, so go there
5399     // to find the actual type being constructed.
5400     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5401     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5402       return DeclarationNameInfo();
5403 
5404     // Determine the type of the class being constructed.
5405     QualType CurClassType = Context.getTypeDeclType(CurClass);
5406 
5407     // FIXME: Check two things: that the template-id names the same type as
5408     // CurClassType, and that the template-id does not occur when the name
5409     // was qualified.
5410 
5411     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5412                                     Context.getCanonicalType(CurClassType)));
5413     // FIXME: should we retrieve TypeSourceInfo?
5414     NameInfo.setNamedTypeInfo(nullptr);
5415     return NameInfo;
5416   }
5417 
5418   case UnqualifiedIdKind::IK_DestructorName: {
5419     TypeSourceInfo *TInfo;
5420     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5421     if (Ty.isNull())
5422       return DeclarationNameInfo();
5423     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5424                                               Context.getCanonicalType(Ty)));
5425     NameInfo.setNamedTypeInfo(TInfo);
5426     return NameInfo;
5427   }
5428 
5429   case UnqualifiedIdKind::IK_TemplateId: {
5430     TemplateName TName = Name.TemplateId->Template.get();
5431     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5432     return Context.getNameForTemplate(TName, TNameLoc);
5433   }
5434 
5435   } // switch (Name.getKind())
5436 
5437   llvm_unreachable("Unknown name kind");
5438 }
5439 
5440 static QualType getCoreType(QualType Ty) {
5441   do {
5442     if (Ty->isPointerType() || Ty->isReferenceType())
5443       Ty = Ty->getPointeeType();
5444     else if (Ty->isArrayType())
5445       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5446     else
5447       return Ty.withoutLocalFastQualifiers();
5448   } while (true);
5449 }
5450 
5451 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5452 /// and Definition have "nearly" matching parameters. This heuristic is
5453 /// used to improve diagnostics in the case where an out-of-line function
5454 /// definition doesn't match any declaration within the class or namespace.
5455 /// Also sets Params to the list of indices to the parameters that differ
5456 /// between the declaration and the definition. If hasSimilarParameters
5457 /// returns true and Params is empty, then all of the parameters match.
5458 static bool hasSimilarParameters(ASTContext &Context,
5459                                      FunctionDecl *Declaration,
5460                                      FunctionDecl *Definition,
5461                                      SmallVectorImpl<unsigned> &Params) {
5462   Params.clear();
5463   if (Declaration->param_size() != Definition->param_size())
5464     return false;
5465   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5466     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5467     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5468 
5469     // The parameter types are identical
5470     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5471       continue;
5472 
5473     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5474     QualType DefParamBaseTy = getCoreType(DefParamTy);
5475     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5476     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5477 
5478     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5479         (DeclTyName && DeclTyName == DefTyName))
5480       Params.push_back(Idx);
5481     else  // The two parameters aren't even close
5482       return false;
5483   }
5484 
5485   return true;
5486 }
5487 
5488 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5489 /// declarator needs to be rebuilt in the current instantiation.
5490 /// Any bits of declarator which appear before the name are valid for
5491 /// consideration here.  That's specifically the type in the decl spec
5492 /// and the base type in any member-pointer chunks.
5493 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5494                                                     DeclarationName Name) {
5495   // The types we specifically need to rebuild are:
5496   //   - typenames, typeofs, and decltypes
5497   //   - types which will become injected class names
5498   // Of course, we also need to rebuild any type referencing such a
5499   // type.  It's safest to just say "dependent", but we call out a
5500   // few cases here.
5501 
5502   DeclSpec &DS = D.getMutableDeclSpec();
5503   switch (DS.getTypeSpecType()) {
5504   case DeclSpec::TST_typename:
5505   case DeclSpec::TST_typeofType:
5506   case DeclSpec::TST_underlyingType:
5507   case DeclSpec::TST_atomic: {
5508     // Grab the type from the parser.
5509     TypeSourceInfo *TSI = nullptr;
5510     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5511     if (T.isNull() || !T->isInstantiationDependentType()) break;
5512 
5513     // Make sure there's a type source info.  This isn't really much
5514     // of a waste; most dependent types should have type source info
5515     // attached already.
5516     if (!TSI)
5517       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5518 
5519     // Rebuild the type in the current instantiation.
5520     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5521     if (!TSI) return true;
5522 
5523     // Store the new type back in the decl spec.
5524     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5525     DS.UpdateTypeRep(LocType);
5526     break;
5527   }
5528 
5529   case DeclSpec::TST_decltype:
5530   case DeclSpec::TST_typeofExpr: {
5531     Expr *E = DS.getRepAsExpr();
5532     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5533     if (Result.isInvalid()) return true;
5534     DS.UpdateExprRep(Result.get());
5535     break;
5536   }
5537 
5538   default:
5539     // Nothing to do for these decl specs.
5540     break;
5541   }
5542 
5543   // It doesn't matter what order we do this in.
5544   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5545     DeclaratorChunk &Chunk = D.getTypeObject(I);
5546 
5547     // The only type information in the declarator which can come
5548     // before the declaration name is the base type of a member
5549     // pointer.
5550     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5551       continue;
5552 
5553     // Rebuild the scope specifier in-place.
5554     CXXScopeSpec &SS = Chunk.Mem.Scope();
5555     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5556       return true;
5557   }
5558 
5559   return false;
5560 }
5561 
5562 void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
5563   // Avoid warning twice on the same identifier, and don't warn on redeclaration
5564   // of system decl.
5565   if (D->getPreviousDecl() || D->isImplicit())
5566     return;
5567   ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
5568   if (Status != ReservedIdentifierStatus::NotReserved &&
5569       !Context.getSourceManager().isInSystemHeader(D->getLocation()))
5570     Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
5571         << D << static_cast<int>(Status);
5572 }
5573 
5574 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5575   D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
5576   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5577 
5578   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5579       Dcl && Dcl->getDeclContext()->isFileContext())
5580     Dcl->setTopLevelDeclInObjCContainer();
5581 
5582   if (getLangOpts().OpenCL)
5583     setCurrentOpenCLExtensionForDecl(Dcl);
5584 
5585   return Dcl;
5586 }
5587 
5588 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5589 ///   If T is the name of a class, then each of the following shall have a
5590 ///   name different from T:
5591 ///     - every static data member of class T;
5592 ///     - every member function of class T
5593 ///     - every member of class T that is itself a type;
5594 /// \returns true if the declaration name violates these rules.
5595 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5596                                    DeclarationNameInfo NameInfo) {
5597   DeclarationName Name = NameInfo.getName();
5598 
5599   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5600   while (Record && Record->isAnonymousStructOrUnion())
5601     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5602   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5603     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5604     return true;
5605   }
5606 
5607   return false;
5608 }
5609 
5610 /// Diagnose a declaration whose declarator-id has the given
5611 /// nested-name-specifier.
5612 ///
5613 /// \param SS The nested-name-specifier of the declarator-id.
5614 ///
5615 /// \param DC The declaration context to which the nested-name-specifier
5616 /// resolves.
5617 ///
5618 /// \param Name The name of the entity being declared.
5619 ///
5620 /// \param Loc The location of the name of the entity being declared.
5621 ///
5622 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5623 /// we're declaring an explicit / partial specialization / instantiation.
5624 ///
5625 /// \returns true if we cannot safely recover from this error, false otherwise.
5626 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5627                                         DeclarationName Name,
5628                                         SourceLocation Loc, bool IsTemplateId) {
5629   DeclContext *Cur = CurContext;
5630   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5631     Cur = Cur->getParent();
5632 
5633   // If the user provided a superfluous scope specifier that refers back to the
5634   // class in which the entity is already declared, diagnose and ignore it.
5635   //
5636   // class X {
5637   //   void X::f();
5638   // };
5639   //
5640   // Note, it was once ill-formed to give redundant qualification in all
5641   // contexts, but that rule was removed by DR482.
5642   if (Cur->Equals(DC)) {
5643     if (Cur->isRecord()) {
5644       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5645                                       : diag::err_member_extra_qualification)
5646         << Name << FixItHint::CreateRemoval(SS.getRange());
5647       SS.clear();
5648     } else {
5649       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5650     }
5651     return false;
5652   }
5653 
5654   // Check whether the qualifying scope encloses the scope of the original
5655   // declaration. For a template-id, we perform the checks in
5656   // CheckTemplateSpecializationScope.
5657   if (!Cur->Encloses(DC) && !IsTemplateId) {
5658     if (Cur->isRecord())
5659       Diag(Loc, diag::err_member_qualification)
5660         << Name << SS.getRange();
5661     else if (isa<TranslationUnitDecl>(DC))
5662       Diag(Loc, diag::err_invalid_declarator_global_scope)
5663         << Name << SS.getRange();
5664     else if (isa<FunctionDecl>(Cur))
5665       Diag(Loc, diag::err_invalid_declarator_in_function)
5666         << Name << SS.getRange();
5667     else if (isa<BlockDecl>(Cur))
5668       Diag(Loc, diag::err_invalid_declarator_in_block)
5669         << Name << SS.getRange();
5670     else
5671       Diag(Loc, diag::err_invalid_declarator_scope)
5672       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5673 
5674     return true;
5675   }
5676 
5677   if (Cur->isRecord()) {
5678     // Cannot qualify members within a class.
5679     Diag(Loc, diag::err_member_qualification)
5680       << Name << SS.getRange();
5681     SS.clear();
5682 
5683     // C++ constructors and destructors with incorrect scopes can break
5684     // our AST invariants by having the wrong underlying types. If
5685     // that's the case, then drop this declaration entirely.
5686     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5687          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5688         !Context.hasSameType(Name.getCXXNameType(),
5689                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5690       return true;
5691 
5692     return false;
5693   }
5694 
5695   // C++11 [dcl.meaning]p1:
5696   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5697   //   not begin with a decltype-specifer"
5698   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5699   while (SpecLoc.getPrefix())
5700     SpecLoc = SpecLoc.getPrefix();
5701   if (dyn_cast_or_null<DecltypeType>(
5702         SpecLoc.getNestedNameSpecifier()->getAsType()))
5703     Diag(Loc, diag::err_decltype_in_declarator)
5704       << SpecLoc.getTypeLoc().getSourceRange();
5705 
5706   return false;
5707 }
5708 
5709 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5710                                   MultiTemplateParamsArg TemplateParamLists) {
5711   // TODO: consider using NameInfo for diagnostic.
5712   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5713   DeclarationName Name = NameInfo.getName();
5714 
5715   // All of these full declarators require an identifier.  If it doesn't have
5716   // one, the ParsedFreeStandingDeclSpec action should be used.
5717   if (D.isDecompositionDeclarator()) {
5718     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5719   } else if (!Name) {
5720     if (!D.isInvalidType())  // Reject this if we think it is valid.
5721       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5722           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5723     return nullptr;
5724   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5725     return nullptr;
5726 
5727   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5728   // we find one that is.
5729   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5730          (S->getFlags() & Scope::TemplateParamScope) != 0)
5731     S = S->getParent();
5732 
5733   DeclContext *DC = CurContext;
5734   if (D.getCXXScopeSpec().isInvalid())
5735     D.setInvalidType();
5736   else if (D.getCXXScopeSpec().isSet()) {
5737     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5738                                         UPPC_DeclarationQualifier))
5739       return nullptr;
5740 
5741     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5742     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5743     if (!DC || isa<EnumDecl>(DC)) {
5744       // If we could not compute the declaration context, it's because the
5745       // declaration context is dependent but does not refer to a class,
5746       // class template, or class template partial specialization. Complain
5747       // and return early, to avoid the coming semantic disaster.
5748       Diag(D.getIdentifierLoc(),
5749            diag::err_template_qualified_declarator_no_match)
5750         << D.getCXXScopeSpec().getScopeRep()
5751         << D.getCXXScopeSpec().getRange();
5752       return nullptr;
5753     }
5754     bool IsDependentContext = DC->isDependentContext();
5755 
5756     if (!IsDependentContext &&
5757         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5758       return nullptr;
5759 
5760     // If a class is incomplete, do not parse entities inside it.
5761     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5762       Diag(D.getIdentifierLoc(),
5763            diag::err_member_def_undefined_record)
5764         << Name << DC << D.getCXXScopeSpec().getRange();
5765       return nullptr;
5766     }
5767     if (!D.getDeclSpec().isFriendSpecified()) {
5768       if (diagnoseQualifiedDeclaration(
5769               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5770               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5771         if (DC->isRecord())
5772           return nullptr;
5773 
5774         D.setInvalidType();
5775       }
5776     }
5777 
5778     // Check whether we need to rebuild the type of the given
5779     // declaration in the current instantiation.
5780     if (EnteringContext && IsDependentContext &&
5781         TemplateParamLists.size() != 0) {
5782       ContextRAII SavedContext(*this, DC);
5783       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5784         D.setInvalidType();
5785     }
5786   }
5787 
5788   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5789   QualType R = TInfo->getType();
5790 
5791   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5792                                       UPPC_DeclarationType))
5793     D.setInvalidType();
5794 
5795   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5796                         forRedeclarationInCurContext());
5797 
5798   // See if this is a redefinition of a variable in the same scope.
5799   if (!D.getCXXScopeSpec().isSet()) {
5800     bool IsLinkageLookup = false;
5801     bool CreateBuiltins = false;
5802 
5803     // If the declaration we're planning to build will be a function
5804     // or object with linkage, then look for another declaration with
5805     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5806     //
5807     // If the declaration we're planning to build will be declared with
5808     // external linkage in the translation unit, create any builtin with
5809     // the same name.
5810     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5811       /* Do nothing*/;
5812     else if (CurContext->isFunctionOrMethod() &&
5813              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5814               R->isFunctionType())) {
5815       IsLinkageLookup = true;
5816       CreateBuiltins =
5817           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5818     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5819                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5820       CreateBuiltins = true;
5821 
5822     if (IsLinkageLookup) {
5823       Previous.clear(LookupRedeclarationWithLinkage);
5824       Previous.setRedeclarationKind(ForExternalRedeclaration);
5825     }
5826 
5827     LookupName(Previous, S, CreateBuiltins);
5828   } else { // Something like "int foo::x;"
5829     LookupQualifiedName(Previous, DC);
5830 
5831     // C++ [dcl.meaning]p1:
5832     //   When the declarator-id is qualified, the declaration shall refer to a
5833     //  previously declared member of the class or namespace to which the
5834     //  qualifier refers (or, in the case of a namespace, of an element of the
5835     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5836     //  thereof; [...]
5837     //
5838     // Note that we already checked the context above, and that we do not have
5839     // enough information to make sure that Previous contains the declaration
5840     // we want to match. For example, given:
5841     //
5842     //   class X {
5843     //     void f();
5844     //     void f(float);
5845     //   };
5846     //
5847     //   void X::f(int) { } // ill-formed
5848     //
5849     // In this case, Previous will point to the overload set
5850     // containing the two f's declared in X, but neither of them
5851     // matches.
5852 
5853     // C++ [dcl.meaning]p1:
5854     //   [...] the member shall not merely have been introduced by a
5855     //   using-declaration in the scope of the class or namespace nominated by
5856     //   the nested-name-specifier of the declarator-id.
5857     RemoveUsingDecls(Previous);
5858   }
5859 
5860   if (Previous.isSingleResult() &&
5861       Previous.getFoundDecl()->isTemplateParameter()) {
5862     // Maybe we will complain about the shadowed template parameter.
5863     if (!D.isInvalidType())
5864       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5865                                       Previous.getFoundDecl());
5866 
5867     // Just pretend that we didn't see the previous declaration.
5868     Previous.clear();
5869   }
5870 
5871   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5872     // Forget that the previous declaration is the injected-class-name.
5873     Previous.clear();
5874 
5875   // In C++, the previous declaration we find might be a tag type
5876   // (class or enum). In this case, the new declaration will hide the
5877   // tag type. Note that this applies to functions, function templates, and
5878   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5879   if (Previous.isSingleTagDecl() &&
5880       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5881       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5882     Previous.clear();
5883 
5884   // Check that there are no default arguments other than in the parameters
5885   // of a function declaration (C++ only).
5886   if (getLangOpts().CPlusPlus)
5887     CheckExtraCXXDefaultArguments(D);
5888 
5889   NamedDecl *New;
5890 
5891   bool AddToScope = true;
5892   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5893     if (TemplateParamLists.size()) {
5894       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5895       return nullptr;
5896     }
5897 
5898     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5899   } else if (R->isFunctionType()) {
5900     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5901                                   TemplateParamLists,
5902                                   AddToScope);
5903   } else {
5904     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5905                                   AddToScope);
5906   }
5907 
5908   if (!New)
5909     return nullptr;
5910 
5911   // If this has an identifier and is not a function template specialization,
5912   // add it to the scope stack.
5913   if (New->getDeclName() && AddToScope)
5914     PushOnScopeChains(New, S);
5915 
5916   if (isInOpenMPDeclareTargetContext())
5917     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5918 
5919   return New;
5920 }
5921 
5922 /// Helper method to turn variable array types into constant array
5923 /// types in certain situations which would otherwise be errors (for
5924 /// GCC compatibility).
5925 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5926                                                     ASTContext &Context,
5927                                                     bool &SizeIsNegative,
5928                                                     llvm::APSInt &Oversized) {
5929   // This method tries to turn a variable array into a constant
5930   // array even when the size isn't an ICE.  This is necessary
5931   // for compatibility with code that depends on gcc's buggy
5932   // constant expression folding, like struct {char x[(int)(char*)2];}
5933   SizeIsNegative = false;
5934   Oversized = 0;
5935 
5936   if (T->isDependentType())
5937     return QualType();
5938 
5939   QualifierCollector Qs;
5940   const Type *Ty = Qs.strip(T);
5941 
5942   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5943     QualType Pointee = PTy->getPointeeType();
5944     QualType FixedType =
5945         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5946                                             Oversized);
5947     if (FixedType.isNull()) return FixedType;
5948     FixedType = Context.getPointerType(FixedType);
5949     return Qs.apply(Context, FixedType);
5950   }
5951   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5952     QualType Inner = PTy->getInnerType();
5953     QualType FixedType =
5954         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5955                                             Oversized);
5956     if (FixedType.isNull()) return FixedType;
5957     FixedType = Context.getParenType(FixedType);
5958     return Qs.apply(Context, FixedType);
5959   }
5960 
5961   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5962   if (!VLATy)
5963     return QualType();
5964 
5965   QualType ElemTy = VLATy->getElementType();
5966   if (ElemTy->isVariablyModifiedType()) {
5967     ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
5968                                                  SizeIsNegative, Oversized);
5969     if (ElemTy.isNull())
5970       return QualType();
5971   }
5972 
5973   Expr::EvalResult Result;
5974   if (!VLATy->getSizeExpr() ||
5975       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5976     return QualType();
5977 
5978   llvm::APSInt Res = Result.Val.getInt();
5979 
5980   // Check whether the array size is negative.
5981   if (Res.isSigned() && Res.isNegative()) {
5982     SizeIsNegative = true;
5983     return QualType();
5984   }
5985 
5986   // Check whether the array is too large to be addressed.
5987   unsigned ActiveSizeBits =
5988       (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
5989        !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
5990           ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
5991           : Res.getActiveBits();
5992   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5993     Oversized = Res;
5994     return QualType();
5995   }
5996 
5997   QualType FoldedArrayType = Context.getConstantArrayType(
5998       ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
5999   return Qs.apply(Context, FoldedArrayType);
6000 }
6001 
6002 static void
6003 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6004   SrcTL = SrcTL.getUnqualifiedLoc();
6005   DstTL = DstTL.getUnqualifiedLoc();
6006   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6007     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6008     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6009                                       DstPTL.getPointeeLoc());
6010     DstPTL.setStarLoc(SrcPTL.getStarLoc());
6011     return;
6012   }
6013   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6014     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6015     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6016                                       DstPTL.getInnerLoc());
6017     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6018     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6019     return;
6020   }
6021   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6022   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6023   TypeLoc SrcElemTL = SrcATL.getElementLoc();
6024   TypeLoc DstElemTL = DstATL.getElementLoc();
6025   if (VariableArrayTypeLoc SrcElemATL =
6026           SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6027     ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6028     FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6029   } else {
6030     DstElemTL.initializeFullCopy(SrcElemTL);
6031   }
6032   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6033   DstATL.setSizeExpr(SrcATL.getSizeExpr());
6034   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6035 }
6036 
6037 /// Helper method to turn variable array types into constant array
6038 /// types in certain situations which would otherwise be errors (for
6039 /// GCC compatibility).
6040 static TypeSourceInfo*
6041 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6042                                               ASTContext &Context,
6043                                               bool &SizeIsNegative,
6044                                               llvm::APSInt &Oversized) {
6045   QualType FixedTy
6046     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6047                                           SizeIsNegative, Oversized);
6048   if (FixedTy.isNull())
6049     return nullptr;
6050   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6051   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6052                                     FixedTInfo->getTypeLoc());
6053   return FixedTInfo;
6054 }
6055 
6056 /// Attempt to fold a variable-sized type to a constant-sized type, returning
6057 /// true if we were successful.
6058 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6059                                            QualType &T, SourceLocation Loc,
6060                                            unsigned FailedFoldDiagID) {
6061   bool SizeIsNegative;
6062   llvm::APSInt Oversized;
6063   TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6064       TInfo, Context, SizeIsNegative, Oversized);
6065   if (FixedTInfo) {
6066     Diag(Loc, diag::ext_vla_folded_to_constant);
6067     TInfo = FixedTInfo;
6068     T = FixedTInfo->getType();
6069     return true;
6070   }
6071 
6072   if (SizeIsNegative)
6073     Diag(Loc, diag::err_typecheck_negative_array_size);
6074   else if (Oversized.getBoolValue())
6075     Diag(Loc, diag::err_array_too_large) << Oversized.toString(10);
6076   else if (FailedFoldDiagID)
6077     Diag(Loc, FailedFoldDiagID);
6078   return false;
6079 }
6080 
6081 /// Register the given locally-scoped extern "C" declaration so
6082 /// that it can be found later for redeclarations. We include any extern "C"
6083 /// declaration that is not visible in the translation unit here, not just
6084 /// function-scope declarations.
6085 void
6086 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6087   if (!getLangOpts().CPlusPlus &&
6088       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6089     // Don't need to track declarations in the TU in C.
6090     return;
6091 
6092   // Note that we have a locally-scoped external with this name.
6093   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6094 }
6095 
6096 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6097   // FIXME: We can have multiple results via __attribute__((overloadable)).
6098   auto Result = Context.getExternCContextDecl()->lookup(Name);
6099   return Result.empty() ? nullptr : *Result.begin();
6100 }
6101 
6102 /// Diagnose function specifiers on a declaration of an identifier that
6103 /// does not identify a function.
6104 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6105   // FIXME: We should probably indicate the identifier in question to avoid
6106   // confusion for constructs like "virtual int a(), b;"
6107   if (DS.isVirtualSpecified())
6108     Diag(DS.getVirtualSpecLoc(),
6109          diag::err_virtual_non_function);
6110 
6111   if (DS.hasExplicitSpecifier())
6112     Diag(DS.getExplicitSpecLoc(),
6113          diag::err_explicit_non_function);
6114 
6115   if (DS.isNoreturnSpecified())
6116     Diag(DS.getNoreturnSpecLoc(),
6117          diag::err_noreturn_non_function);
6118 }
6119 
6120 NamedDecl*
6121 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6122                              TypeSourceInfo *TInfo, LookupResult &Previous) {
6123   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6124   if (D.getCXXScopeSpec().isSet()) {
6125     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6126       << D.getCXXScopeSpec().getRange();
6127     D.setInvalidType();
6128     // Pretend we didn't see the scope specifier.
6129     DC = CurContext;
6130     Previous.clear();
6131   }
6132 
6133   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6134 
6135   if (D.getDeclSpec().isInlineSpecified())
6136     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6137         << getLangOpts().CPlusPlus17;
6138   if (D.getDeclSpec().hasConstexprSpecifier())
6139     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6140         << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6141 
6142   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6143     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6144       Diag(D.getName().StartLocation,
6145            diag::err_deduction_guide_invalid_specifier)
6146           << "typedef";
6147     else
6148       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6149           << D.getName().getSourceRange();
6150     return nullptr;
6151   }
6152 
6153   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6154   if (!NewTD) return nullptr;
6155 
6156   // Handle attributes prior to checking for duplicates in MergeVarDecl
6157   ProcessDeclAttributes(S, NewTD, D);
6158 
6159   CheckTypedefForVariablyModifiedType(S, NewTD);
6160 
6161   bool Redeclaration = D.isRedeclaration();
6162   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6163   D.setRedeclaration(Redeclaration);
6164   return ND;
6165 }
6166 
6167 void
6168 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6169   // C99 6.7.7p2: If a typedef name specifies a variably modified type
6170   // then it shall have block scope.
6171   // Note that variably modified types must be fixed before merging the decl so
6172   // that redeclarations will match.
6173   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6174   QualType T = TInfo->getType();
6175   if (T->isVariablyModifiedType()) {
6176     setFunctionHasBranchProtectedScope();
6177 
6178     if (S->getFnParent() == nullptr) {
6179       bool SizeIsNegative;
6180       llvm::APSInt Oversized;
6181       TypeSourceInfo *FixedTInfo =
6182         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6183                                                       SizeIsNegative,
6184                                                       Oversized);
6185       if (FixedTInfo) {
6186         Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6187         NewTD->setTypeSourceInfo(FixedTInfo);
6188       } else {
6189         if (SizeIsNegative)
6190           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6191         else if (T->isVariableArrayType())
6192           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6193         else if (Oversized.getBoolValue())
6194           Diag(NewTD->getLocation(), diag::err_array_too_large)
6195             << Oversized.toString(10);
6196         else
6197           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6198         NewTD->setInvalidDecl();
6199       }
6200     }
6201   }
6202 }
6203 
6204 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6205 /// declares a typedef-name, either using the 'typedef' type specifier or via
6206 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6207 NamedDecl*
6208 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6209                            LookupResult &Previous, bool &Redeclaration) {
6210 
6211   // Find the shadowed declaration before filtering for scope.
6212   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6213 
6214   // Merge the decl with the existing one if appropriate. If the decl is
6215   // in an outer scope, it isn't the same thing.
6216   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6217                        /*AllowInlineNamespace*/false);
6218   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6219   if (!Previous.empty()) {
6220     Redeclaration = true;
6221     MergeTypedefNameDecl(S, NewTD, Previous);
6222   } else {
6223     inferGslPointerAttribute(NewTD);
6224   }
6225 
6226   if (ShadowedDecl && !Redeclaration)
6227     CheckShadow(NewTD, ShadowedDecl, Previous);
6228 
6229   // If this is the C FILE type, notify the AST context.
6230   if (IdentifierInfo *II = NewTD->getIdentifier())
6231     if (!NewTD->isInvalidDecl() &&
6232         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6233       if (II->isStr("FILE"))
6234         Context.setFILEDecl(NewTD);
6235       else if (II->isStr("jmp_buf"))
6236         Context.setjmp_bufDecl(NewTD);
6237       else if (II->isStr("sigjmp_buf"))
6238         Context.setsigjmp_bufDecl(NewTD);
6239       else if (II->isStr("ucontext_t"))
6240         Context.setucontext_tDecl(NewTD);
6241     }
6242 
6243   return NewTD;
6244 }
6245 
6246 /// Determines whether the given declaration is an out-of-scope
6247 /// previous declaration.
6248 ///
6249 /// This routine should be invoked when name lookup has found a
6250 /// previous declaration (PrevDecl) that is not in the scope where a
6251 /// new declaration by the same name is being introduced. If the new
6252 /// declaration occurs in a local scope, previous declarations with
6253 /// linkage may still be considered previous declarations (C99
6254 /// 6.2.2p4-5, C++ [basic.link]p6).
6255 ///
6256 /// \param PrevDecl the previous declaration found by name
6257 /// lookup
6258 ///
6259 /// \param DC the context in which the new declaration is being
6260 /// declared.
6261 ///
6262 /// \returns true if PrevDecl is an out-of-scope previous declaration
6263 /// for a new delcaration with the same name.
6264 static bool
6265 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6266                                 ASTContext &Context) {
6267   if (!PrevDecl)
6268     return false;
6269 
6270   if (!PrevDecl->hasLinkage())
6271     return false;
6272 
6273   if (Context.getLangOpts().CPlusPlus) {
6274     // C++ [basic.link]p6:
6275     //   If there is a visible declaration of an entity with linkage
6276     //   having the same name and type, ignoring entities declared
6277     //   outside the innermost enclosing namespace scope, the block
6278     //   scope declaration declares that same entity and receives the
6279     //   linkage of the previous declaration.
6280     DeclContext *OuterContext = DC->getRedeclContext();
6281     if (!OuterContext->isFunctionOrMethod())
6282       // This rule only applies to block-scope declarations.
6283       return false;
6284 
6285     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6286     if (PrevOuterContext->isRecord())
6287       // We found a member function: ignore it.
6288       return false;
6289 
6290     // Find the innermost enclosing namespace for the new and
6291     // previous declarations.
6292     OuterContext = OuterContext->getEnclosingNamespaceContext();
6293     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6294 
6295     // The previous declaration is in a different namespace, so it
6296     // isn't the same function.
6297     if (!OuterContext->Equals(PrevOuterContext))
6298       return false;
6299   }
6300 
6301   return true;
6302 }
6303 
6304 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6305   CXXScopeSpec &SS = D.getCXXScopeSpec();
6306   if (!SS.isSet()) return;
6307   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6308 }
6309 
6310 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6311   QualType type = decl->getType();
6312   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6313   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6314     // Various kinds of declaration aren't allowed to be __autoreleasing.
6315     unsigned kind = -1U;
6316     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6317       if (var->hasAttr<BlocksAttr>())
6318         kind = 0; // __block
6319       else if (!var->hasLocalStorage())
6320         kind = 1; // global
6321     } else if (isa<ObjCIvarDecl>(decl)) {
6322       kind = 3; // ivar
6323     } else if (isa<FieldDecl>(decl)) {
6324       kind = 2; // field
6325     }
6326 
6327     if (kind != -1U) {
6328       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6329         << kind;
6330     }
6331   } else if (lifetime == Qualifiers::OCL_None) {
6332     // Try to infer lifetime.
6333     if (!type->isObjCLifetimeType())
6334       return false;
6335 
6336     lifetime = type->getObjCARCImplicitLifetime();
6337     type = Context.getLifetimeQualifiedType(type, lifetime);
6338     decl->setType(type);
6339   }
6340 
6341   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6342     // Thread-local variables cannot have lifetime.
6343     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6344         var->getTLSKind()) {
6345       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6346         << var->getType();
6347       return true;
6348     }
6349   }
6350 
6351   return false;
6352 }
6353 
6354 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6355   if (Decl->getType().hasAddressSpace())
6356     return;
6357   if (Decl->getType()->isDependentType())
6358     return;
6359   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6360     QualType Type = Var->getType();
6361     if (Type->isSamplerT() || Type->isVoidType())
6362       return;
6363     LangAS ImplAS = LangAS::opencl_private;
6364     if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) &&
6365         Var->hasGlobalStorage())
6366       ImplAS = LangAS::opencl_global;
6367     // If the original type from a decayed type is an array type and that array
6368     // type has no address space yet, deduce it now.
6369     if (auto DT = dyn_cast<DecayedType>(Type)) {
6370       auto OrigTy = DT->getOriginalType();
6371       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6372         // Add the address space to the original array type and then propagate
6373         // that to the element type through `getAsArrayType`.
6374         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6375         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6376         // Re-generate the decayed type.
6377         Type = Context.getDecayedType(OrigTy);
6378       }
6379     }
6380     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6381     // Apply any qualifiers (including address space) from the array type to
6382     // the element type. This implements C99 6.7.3p8: "If the specification of
6383     // an array type includes any type qualifiers, the element type is so
6384     // qualified, not the array type."
6385     if (Type->isArrayType())
6386       Type = QualType(Context.getAsArrayType(Type), 0);
6387     Decl->setType(Type);
6388   }
6389 }
6390 
6391 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6392   // Ensure that an auto decl is deduced otherwise the checks below might cache
6393   // the wrong linkage.
6394   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6395 
6396   // 'weak' only applies to declarations with external linkage.
6397   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6398     if (!ND.isExternallyVisible()) {
6399       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6400       ND.dropAttr<WeakAttr>();
6401     }
6402   }
6403   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6404     if (ND.isExternallyVisible()) {
6405       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6406       ND.dropAttr<WeakRefAttr>();
6407       ND.dropAttr<AliasAttr>();
6408     }
6409   }
6410 
6411   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6412     if (VD->hasInit()) {
6413       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6414         assert(VD->isThisDeclarationADefinition() &&
6415                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6416         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6417         VD->dropAttr<AliasAttr>();
6418       }
6419     }
6420   }
6421 
6422   // 'selectany' only applies to externally visible variable declarations.
6423   // It does not apply to functions.
6424   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6425     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6426       S.Diag(Attr->getLocation(),
6427              diag::err_attribute_selectany_non_extern_data);
6428       ND.dropAttr<SelectAnyAttr>();
6429     }
6430   }
6431 
6432   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6433     auto *VD = dyn_cast<VarDecl>(&ND);
6434     bool IsAnonymousNS = false;
6435     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6436     if (VD) {
6437       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6438       while (NS && !IsAnonymousNS) {
6439         IsAnonymousNS = NS->isAnonymousNamespace();
6440         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6441       }
6442     }
6443     // dll attributes require external linkage. Static locals may have external
6444     // linkage but still cannot be explicitly imported or exported.
6445     // In Microsoft mode, a variable defined in anonymous namespace must have
6446     // external linkage in order to be exported.
6447     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6448     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6449         (!AnonNSInMicrosoftMode &&
6450          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6451       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6452         << &ND << Attr;
6453       ND.setInvalidDecl();
6454     }
6455   }
6456 
6457   // Check the attributes on the function type, if any.
6458   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6459     // Don't declare this variable in the second operand of the for-statement;
6460     // GCC miscompiles that by ending its lifetime before evaluating the
6461     // third operand. See gcc.gnu.org/PR86769.
6462     AttributedTypeLoc ATL;
6463     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6464          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6465          TL = ATL.getModifiedLoc()) {
6466       // The [[lifetimebound]] attribute can be applied to the implicit object
6467       // parameter of a non-static member function (other than a ctor or dtor)
6468       // by applying it to the function type.
6469       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6470         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6471         if (!MD || MD->isStatic()) {
6472           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6473               << !MD << A->getRange();
6474         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6475           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6476               << isa<CXXDestructorDecl>(MD) << A->getRange();
6477         }
6478       }
6479     }
6480   }
6481 }
6482 
6483 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6484                                            NamedDecl *NewDecl,
6485                                            bool IsSpecialization,
6486                                            bool IsDefinition) {
6487   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6488     return;
6489 
6490   bool IsTemplate = false;
6491   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6492     OldDecl = OldTD->getTemplatedDecl();
6493     IsTemplate = true;
6494     if (!IsSpecialization)
6495       IsDefinition = false;
6496   }
6497   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6498     NewDecl = NewTD->getTemplatedDecl();
6499     IsTemplate = true;
6500   }
6501 
6502   if (!OldDecl || !NewDecl)
6503     return;
6504 
6505   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6506   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6507   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6508   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6509 
6510   // dllimport and dllexport are inheritable attributes so we have to exclude
6511   // inherited attribute instances.
6512   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6513                     (NewExportAttr && !NewExportAttr->isInherited());
6514 
6515   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6516   // the only exception being explicit specializations.
6517   // Implicitly generated declarations are also excluded for now because there
6518   // is no other way to switch these to use dllimport or dllexport.
6519   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6520 
6521   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6522     // Allow with a warning for free functions and global variables.
6523     bool JustWarn = false;
6524     if (!OldDecl->isCXXClassMember()) {
6525       auto *VD = dyn_cast<VarDecl>(OldDecl);
6526       if (VD && !VD->getDescribedVarTemplate())
6527         JustWarn = true;
6528       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6529       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6530         JustWarn = true;
6531     }
6532 
6533     // We cannot change a declaration that's been used because IR has already
6534     // been emitted. Dllimported functions will still work though (modulo
6535     // address equality) as they can use the thunk.
6536     if (OldDecl->isUsed())
6537       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6538         JustWarn = false;
6539 
6540     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6541                                : diag::err_attribute_dll_redeclaration;
6542     S.Diag(NewDecl->getLocation(), DiagID)
6543         << NewDecl
6544         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6545     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6546     if (!JustWarn) {
6547       NewDecl->setInvalidDecl();
6548       return;
6549     }
6550   }
6551 
6552   // A redeclaration is not allowed to drop a dllimport attribute, the only
6553   // exceptions being inline function definitions (except for function
6554   // templates), local extern declarations, qualified friend declarations or
6555   // special MSVC extension: in the last case, the declaration is treated as if
6556   // it were marked dllexport.
6557   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6558   bool IsMicrosoftABI  = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
6559   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6560     // Ignore static data because out-of-line definitions are diagnosed
6561     // separately.
6562     IsStaticDataMember = VD->isStaticDataMember();
6563     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6564                    VarDecl::DeclarationOnly;
6565   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6566     IsInline = FD->isInlined();
6567     IsQualifiedFriend = FD->getQualifier() &&
6568                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6569   }
6570 
6571   if (OldImportAttr && !HasNewAttr &&
6572       (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
6573       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6574     if (IsMicrosoftABI && IsDefinition) {
6575       S.Diag(NewDecl->getLocation(),
6576              diag::warn_redeclaration_without_import_attribute)
6577           << NewDecl;
6578       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6579       NewDecl->dropAttr<DLLImportAttr>();
6580       NewDecl->addAttr(
6581           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6582     } else {
6583       S.Diag(NewDecl->getLocation(),
6584              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6585           << NewDecl << OldImportAttr;
6586       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6587       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6588       OldDecl->dropAttr<DLLImportAttr>();
6589       NewDecl->dropAttr<DLLImportAttr>();
6590     }
6591   } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
6592     // In MinGW, seeing a function declared inline drops the dllimport
6593     // attribute.
6594     OldDecl->dropAttr<DLLImportAttr>();
6595     NewDecl->dropAttr<DLLImportAttr>();
6596     S.Diag(NewDecl->getLocation(),
6597            diag::warn_dllimport_dropped_from_inline_function)
6598         << NewDecl << OldImportAttr;
6599   }
6600 
6601   // A specialization of a class template member function is processed here
6602   // since it's a redeclaration. If the parent class is dllexport, the
6603   // specialization inherits that attribute. This doesn't happen automatically
6604   // since the parent class isn't instantiated until later.
6605   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6606     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6607         !NewImportAttr && !NewExportAttr) {
6608       if (const DLLExportAttr *ParentExportAttr =
6609               MD->getParent()->getAttr<DLLExportAttr>()) {
6610         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6611         NewAttr->setInherited(true);
6612         NewDecl->addAttr(NewAttr);
6613       }
6614     }
6615   }
6616 }
6617 
6618 /// Given that we are within the definition of the given function,
6619 /// will that definition behave like C99's 'inline', where the
6620 /// definition is discarded except for optimization purposes?
6621 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6622   // Try to avoid calling GetGVALinkageForFunction.
6623 
6624   // All cases of this require the 'inline' keyword.
6625   if (!FD->isInlined()) return false;
6626 
6627   // This is only possible in C++ with the gnu_inline attribute.
6628   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6629     return false;
6630 
6631   // Okay, go ahead and call the relatively-more-expensive function.
6632   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6633 }
6634 
6635 /// Determine whether a variable is extern "C" prior to attaching
6636 /// an initializer. We can't just call isExternC() here, because that
6637 /// will also compute and cache whether the declaration is externally
6638 /// visible, which might change when we attach the initializer.
6639 ///
6640 /// This can only be used if the declaration is known to not be a
6641 /// redeclaration of an internal linkage declaration.
6642 ///
6643 /// For instance:
6644 ///
6645 ///   auto x = []{};
6646 ///
6647 /// Attaching the initializer here makes this declaration not externally
6648 /// visible, because its type has internal linkage.
6649 ///
6650 /// FIXME: This is a hack.
6651 template<typename T>
6652 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6653   if (S.getLangOpts().CPlusPlus) {
6654     // In C++, the overloadable attribute negates the effects of extern "C".
6655     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6656       return false;
6657 
6658     // So do CUDA's host/device attributes.
6659     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6660                                  D->template hasAttr<CUDAHostAttr>()))
6661       return false;
6662   }
6663   return D->isExternC();
6664 }
6665 
6666 static bool shouldConsiderLinkage(const VarDecl *VD) {
6667   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6668   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6669       isa<OMPDeclareMapperDecl>(DC))
6670     return VD->hasExternalStorage();
6671   if (DC->isFileContext())
6672     return true;
6673   if (DC->isRecord())
6674     return false;
6675   if (isa<RequiresExprBodyDecl>(DC))
6676     return false;
6677   llvm_unreachable("Unexpected context");
6678 }
6679 
6680 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6681   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6682   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6683       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6684     return true;
6685   if (DC->isRecord())
6686     return false;
6687   llvm_unreachable("Unexpected context");
6688 }
6689 
6690 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6691                           ParsedAttr::Kind Kind) {
6692   // Check decl attributes on the DeclSpec.
6693   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6694     return true;
6695 
6696   // Walk the declarator structure, checking decl attributes that were in a type
6697   // position to the decl itself.
6698   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6699     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6700       return true;
6701   }
6702 
6703   // Finally, check attributes on the decl itself.
6704   return PD.getAttributes().hasAttribute(Kind);
6705 }
6706 
6707 /// Adjust the \c DeclContext for a function or variable that might be a
6708 /// function-local external declaration.
6709 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6710   if (!DC->isFunctionOrMethod())
6711     return false;
6712 
6713   // If this is a local extern function or variable declared within a function
6714   // template, don't add it into the enclosing namespace scope until it is
6715   // instantiated; it might have a dependent type right now.
6716   if (DC->isDependentContext())
6717     return true;
6718 
6719   // C++11 [basic.link]p7:
6720   //   When a block scope declaration of an entity with linkage is not found to
6721   //   refer to some other declaration, then that entity is a member of the
6722   //   innermost enclosing namespace.
6723   //
6724   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6725   // semantically-enclosing namespace, not a lexically-enclosing one.
6726   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6727     DC = DC->getParent();
6728   return true;
6729 }
6730 
6731 /// Returns true if given declaration has external C language linkage.
6732 static bool isDeclExternC(const Decl *D) {
6733   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6734     return FD->isExternC();
6735   if (const auto *VD = dyn_cast<VarDecl>(D))
6736     return VD->isExternC();
6737 
6738   llvm_unreachable("Unknown type of decl!");
6739 }
6740 
6741 /// Returns true if there hasn't been any invalid type diagnosed.
6742 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
6743   DeclContext *DC = NewVD->getDeclContext();
6744   QualType R = NewVD->getType();
6745 
6746   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6747   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6748   // argument.
6749   if (R->isImageType() || R->isPipeType()) {
6750     Se.Diag(NewVD->getLocation(),
6751             diag::err_opencl_type_can_only_be_used_as_function_parameter)
6752         << R;
6753     NewVD->setInvalidDecl();
6754     return false;
6755   }
6756 
6757   // OpenCL v1.2 s6.9.r:
6758   // The event type cannot be used to declare a program scope variable.
6759   // OpenCL v2.0 s6.9.q:
6760   // The clk_event_t and reserve_id_t types cannot be declared in program
6761   // scope.
6762   if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
6763     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6764       Se.Diag(NewVD->getLocation(),
6765               diag::err_invalid_type_for_program_scope_var)
6766           << R;
6767       NewVD->setInvalidDecl();
6768       return false;
6769     }
6770   }
6771 
6772   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6773   if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
6774                                                Se.getLangOpts())) {
6775     QualType NR = R.getCanonicalType();
6776     while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
6777            NR->isReferenceType()) {
6778       if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
6779           NR->isFunctionReferenceType()) {
6780         Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
6781             << NR->isReferenceType();
6782         NewVD->setInvalidDecl();
6783         return false;
6784       }
6785       NR = NR->getPointeeType();
6786     }
6787   }
6788 
6789   if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
6790                                                Se.getLangOpts())) {
6791     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6792     // half array type (unless the cl_khr_fp16 extension is enabled).
6793     if (Se.Context.getBaseElementType(R)->isHalfType()) {
6794       Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
6795       NewVD->setInvalidDecl();
6796       return false;
6797     }
6798   }
6799 
6800   // OpenCL v1.2 s6.9.r:
6801   // The event type cannot be used with the __local, __constant and __global
6802   // address space qualifiers.
6803   if (R->isEventT()) {
6804     if (R.getAddressSpace() != LangAS::opencl_private) {
6805       Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
6806       NewVD->setInvalidDecl();
6807       return false;
6808     }
6809   }
6810 
6811   if (R->isSamplerT()) {
6812     // OpenCL v1.2 s6.9.b p4:
6813     // The sampler type cannot be used with the __local and __global address
6814     // space qualifiers.
6815     if (R.getAddressSpace() == LangAS::opencl_local ||
6816         R.getAddressSpace() == LangAS::opencl_global) {
6817       Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
6818       NewVD->setInvalidDecl();
6819     }
6820 
6821     // OpenCL v1.2 s6.12.14.1:
6822     // A global sampler must be declared with either the constant address
6823     // space qualifier or with the const qualifier.
6824     if (DC->isTranslationUnit() &&
6825         !(R.getAddressSpace() == LangAS::opencl_constant ||
6826           R.isConstQualified())) {
6827       Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
6828       NewVD->setInvalidDecl();
6829     }
6830     if (NewVD->isInvalidDecl())
6831       return false;
6832   }
6833 
6834   return true;
6835 }
6836 
6837 template <typename AttrTy>
6838 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
6839   const TypedefNameDecl *TND = TT->getDecl();
6840   if (const auto *Attribute = TND->getAttr<AttrTy>()) {
6841     AttrTy *Clone = Attribute->clone(S.Context);
6842     Clone->setInherited(true);
6843     D->addAttr(Clone);
6844   }
6845 }
6846 
6847 NamedDecl *Sema::ActOnVariableDeclarator(
6848     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6849     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6850     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6851   QualType R = TInfo->getType();
6852   DeclarationName Name = GetNameForDeclarator(D).getName();
6853 
6854   IdentifierInfo *II = Name.getAsIdentifierInfo();
6855 
6856   if (D.isDecompositionDeclarator()) {
6857     // Take the name of the first declarator as our name for diagnostic
6858     // purposes.
6859     auto &Decomp = D.getDecompositionDeclarator();
6860     if (!Decomp.bindings().empty()) {
6861       II = Decomp.bindings()[0].Name;
6862       Name = II;
6863     }
6864   } else if (!II) {
6865     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6866     return nullptr;
6867   }
6868 
6869 
6870   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6871   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6872 
6873   // dllimport globals without explicit storage class are treated as extern. We
6874   // have to change the storage class this early to get the right DeclContext.
6875   if (SC == SC_None && !DC->isRecord() &&
6876       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6877       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6878     SC = SC_Extern;
6879 
6880   DeclContext *OriginalDC = DC;
6881   bool IsLocalExternDecl = SC == SC_Extern &&
6882                            adjustContextForLocalExternDecl(DC);
6883 
6884   if (SCSpec == DeclSpec::SCS_mutable) {
6885     // mutable can only appear on non-static class members, so it's always
6886     // an error here
6887     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6888     D.setInvalidType();
6889     SC = SC_None;
6890   }
6891 
6892   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6893       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6894                               D.getDeclSpec().getStorageClassSpecLoc())) {
6895     // In C++11, the 'register' storage class specifier is deprecated.
6896     // Suppress the warning in system macros, it's used in macros in some
6897     // popular C system headers, such as in glibc's htonl() macro.
6898     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6899          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6900                                    : diag::warn_deprecated_register)
6901       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6902   }
6903 
6904   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6905 
6906   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6907     // C99 6.9p2: The storage-class specifiers auto and register shall not
6908     // appear in the declaration specifiers in an external declaration.
6909     // Global Register+Asm is a GNU extension we support.
6910     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6911       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6912       D.setInvalidType();
6913     }
6914   }
6915 
6916   // If this variable has a VLA type and an initializer, try to
6917   // fold to a constant-sized type. This is otherwise invalid.
6918   if (D.hasInitializer() && R->isVariableArrayType())
6919     tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
6920                                     /*DiagID=*/0);
6921 
6922   bool IsMemberSpecialization = false;
6923   bool IsVariableTemplateSpecialization = false;
6924   bool IsPartialSpecialization = false;
6925   bool IsVariableTemplate = false;
6926   VarDecl *NewVD = nullptr;
6927   VarTemplateDecl *NewTemplate = nullptr;
6928   TemplateParameterList *TemplateParams = nullptr;
6929   if (!getLangOpts().CPlusPlus) {
6930     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6931                             II, R, TInfo, SC);
6932 
6933     if (R->getContainedDeducedType())
6934       ParsingInitForAutoVars.insert(NewVD);
6935 
6936     if (D.isInvalidType())
6937       NewVD->setInvalidDecl();
6938 
6939     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
6940         NewVD->hasLocalStorage())
6941       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
6942                             NTCUC_AutoVar, NTCUK_Destruct);
6943   } else {
6944     bool Invalid = false;
6945 
6946     if (DC->isRecord() && !CurContext->isRecord()) {
6947       // This is an out-of-line definition of a static data member.
6948       switch (SC) {
6949       case SC_None:
6950         break;
6951       case SC_Static:
6952         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6953              diag::err_static_out_of_line)
6954           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6955         break;
6956       case SC_Auto:
6957       case SC_Register:
6958       case SC_Extern:
6959         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6960         // to names of variables declared in a block or to function parameters.
6961         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6962         // of class members
6963 
6964         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6965              diag::err_storage_class_for_static_member)
6966           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6967         break;
6968       case SC_PrivateExtern:
6969         llvm_unreachable("C storage class in c++!");
6970       }
6971     }
6972 
6973     if (SC == SC_Static && CurContext->isRecord()) {
6974       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6975         // Walk up the enclosing DeclContexts to check for any that are
6976         // incompatible with static data members.
6977         const DeclContext *FunctionOrMethod = nullptr;
6978         const CXXRecordDecl *AnonStruct = nullptr;
6979         for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
6980           if (Ctxt->isFunctionOrMethod()) {
6981             FunctionOrMethod = Ctxt;
6982             break;
6983           }
6984           const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
6985           if (ParentDecl && !ParentDecl->getDeclName()) {
6986             AnonStruct = ParentDecl;
6987             break;
6988           }
6989         }
6990         if (FunctionOrMethod) {
6991           // C++ [class.static.data]p5: A local class shall not have static data
6992           // members.
6993           Diag(D.getIdentifierLoc(),
6994                diag::err_static_data_member_not_allowed_in_local_class)
6995             << Name << RD->getDeclName() << RD->getTagKind();
6996         } else if (AnonStruct) {
6997           // C++ [class.static.data]p4: Unnamed classes and classes contained
6998           // directly or indirectly within unnamed classes shall not contain
6999           // static data members.
7000           Diag(D.getIdentifierLoc(),
7001                diag::err_static_data_member_not_allowed_in_anon_struct)
7002             << Name << AnonStruct->getTagKind();
7003           Invalid = true;
7004         } else if (RD->isUnion()) {
7005           // C++98 [class.union]p1: If a union contains a static data member,
7006           // the program is ill-formed. C++11 drops this restriction.
7007           Diag(D.getIdentifierLoc(),
7008                getLangOpts().CPlusPlus11
7009                  ? diag::warn_cxx98_compat_static_data_member_in_union
7010                  : diag::ext_static_data_member_in_union) << Name;
7011         }
7012       }
7013     }
7014 
7015     // Match up the template parameter lists with the scope specifier, then
7016     // determine whether we have a template or a template specialization.
7017     bool InvalidScope = false;
7018     TemplateParams = MatchTemplateParametersToScopeSpecifier(
7019         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7020         D.getCXXScopeSpec(),
7021         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7022             ? D.getName().TemplateId
7023             : nullptr,
7024         TemplateParamLists,
7025         /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7026     Invalid |= InvalidScope;
7027 
7028     if (TemplateParams) {
7029       if (!TemplateParams->size() &&
7030           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7031         // There is an extraneous 'template<>' for this variable. Complain
7032         // about it, but allow the declaration of the variable.
7033         Diag(TemplateParams->getTemplateLoc(),
7034              diag::err_template_variable_noparams)
7035           << II
7036           << SourceRange(TemplateParams->getTemplateLoc(),
7037                          TemplateParams->getRAngleLoc());
7038         TemplateParams = nullptr;
7039       } else {
7040         // Check that we can declare a template here.
7041         if (CheckTemplateDeclScope(S, TemplateParams))
7042           return nullptr;
7043 
7044         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7045           // This is an explicit specialization or a partial specialization.
7046           IsVariableTemplateSpecialization = true;
7047           IsPartialSpecialization = TemplateParams->size() > 0;
7048         } else { // if (TemplateParams->size() > 0)
7049           // This is a template declaration.
7050           IsVariableTemplate = true;
7051 
7052           // Only C++1y supports variable templates (N3651).
7053           Diag(D.getIdentifierLoc(),
7054                getLangOpts().CPlusPlus14
7055                    ? diag::warn_cxx11_compat_variable_template
7056                    : diag::ext_variable_template);
7057         }
7058       }
7059     } else {
7060       // Check that we can declare a member specialization here.
7061       if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7062           CheckTemplateDeclScope(S, TemplateParamLists.back()))
7063         return nullptr;
7064       assert((Invalid ||
7065               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7066              "should have a 'template<>' for this decl");
7067     }
7068 
7069     if (IsVariableTemplateSpecialization) {
7070       SourceLocation TemplateKWLoc =
7071           TemplateParamLists.size() > 0
7072               ? TemplateParamLists[0]->getTemplateLoc()
7073               : SourceLocation();
7074       DeclResult Res = ActOnVarTemplateSpecialization(
7075           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7076           IsPartialSpecialization);
7077       if (Res.isInvalid())
7078         return nullptr;
7079       NewVD = cast<VarDecl>(Res.get());
7080       AddToScope = false;
7081     } else if (D.isDecompositionDeclarator()) {
7082       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7083                                         D.getIdentifierLoc(), R, TInfo, SC,
7084                                         Bindings);
7085     } else
7086       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7087                               D.getIdentifierLoc(), II, R, TInfo, SC);
7088 
7089     // If this is supposed to be a variable template, create it as such.
7090     if (IsVariableTemplate) {
7091       NewTemplate =
7092           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7093                                   TemplateParams, NewVD);
7094       NewVD->setDescribedVarTemplate(NewTemplate);
7095     }
7096 
7097     // If this decl has an auto type in need of deduction, make a note of the
7098     // Decl so we can diagnose uses of it in its own initializer.
7099     if (R->getContainedDeducedType())
7100       ParsingInitForAutoVars.insert(NewVD);
7101 
7102     if (D.isInvalidType() || Invalid) {
7103       NewVD->setInvalidDecl();
7104       if (NewTemplate)
7105         NewTemplate->setInvalidDecl();
7106     }
7107 
7108     SetNestedNameSpecifier(*this, NewVD, D);
7109 
7110     // If we have any template parameter lists that don't directly belong to
7111     // the variable (matching the scope specifier), store them.
7112     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7113     if (TemplateParamLists.size() > VDTemplateParamLists)
7114       NewVD->setTemplateParameterListsInfo(
7115           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7116   }
7117 
7118   if (D.getDeclSpec().isInlineSpecified()) {
7119     if (!getLangOpts().CPlusPlus) {
7120       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7121           << 0;
7122     } else if (CurContext->isFunctionOrMethod()) {
7123       // 'inline' is not allowed on block scope variable declaration.
7124       Diag(D.getDeclSpec().getInlineSpecLoc(),
7125            diag::err_inline_declaration_block_scope) << Name
7126         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7127     } else {
7128       Diag(D.getDeclSpec().getInlineSpecLoc(),
7129            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7130                                      : diag::ext_inline_variable);
7131       NewVD->setInlineSpecified();
7132     }
7133   }
7134 
7135   // Set the lexical context. If the declarator has a C++ scope specifier, the
7136   // lexical context will be different from the semantic context.
7137   NewVD->setLexicalDeclContext(CurContext);
7138   if (NewTemplate)
7139     NewTemplate->setLexicalDeclContext(CurContext);
7140 
7141   if (IsLocalExternDecl) {
7142     if (D.isDecompositionDeclarator())
7143       for (auto *B : Bindings)
7144         B->setLocalExternDecl();
7145     else
7146       NewVD->setLocalExternDecl();
7147   }
7148 
7149   bool EmitTLSUnsupportedError = false;
7150   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7151     // C++11 [dcl.stc]p4:
7152     //   When thread_local is applied to a variable of block scope the
7153     //   storage-class-specifier static is implied if it does not appear
7154     //   explicitly.
7155     // Core issue: 'static' is not implied if the variable is declared
7156     //   'extern'.
7157     if (NewVD->hasLocalStorage() &&
7158         (SCSpec != DeclSpec::SCS_unspecified ||
7159          TSCS != DeclSpec::TSCS_thread_local ||
7160          !DC->isFunctionOrMethod()))
7161       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7162            diag::err_thread_non_global)
7163         << DeclSpec::getSpecifierName(TSCS);
7164     else if (!Context.getTargetInfo().isTLSSupported()) {
7165       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7166           getLangOpts().SYCLIsDevice) {
7167         // Postpone error emission until we've collected attributes required to
7168         // figure out whether it's a host or device variable and whether the
7169         // error should be ignored.
7170         EmitTLSUnsupportedError = true;
7171         // We still need to mark the variable as TLS so it shows up in AST with
7172         // proper storage class for other tools to use even if we're not going
7173         // to emit any code for it.
7174         NewVD->setTSCSpec(TSCS);
7175       } else
7176         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7177              diag::err_thread_unsupported);
7178     } else
7179       NewVD->setTSCSpec(TSCS);
7180   }
7181 
7182   switch (D.getDeclSpec().getConstexprSpecifier()) {
7183   case ConstexprSpecKind::Unspecified:
7184     break;
7185 
7186   case ConstexprSpecKind::Consteval:
7187     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7188          diag::err_constexpr_wrong_decl_kind)
7189         << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7190     LLVM_FALLTHROUGH;
7191 
7192   case ConstexprSpecKind::Constexpr:
7193     NewVD->setConstexpr(true);
7194     MaybeAddCUDAConstantAttr(NewVD);
7195     // C++1z [dcl.spec.constexpr]p1:
7196     //   A static data member declared with the constexpr specifier is
7197     //   implicitly an inline variable.
7198     if (NewVD->isStaticDataMember() &&
7199         (getLangOpts().CPlusPlus17 ||
7200          Context.getTargetInfo().getCXXABI().isMicrosoft()))
7201       NewVD->setImplicitlyInline();
7202     break;
7203 
7204   case ConstexprSpecKind::Constinit:
7205     if (!NewVD->hasGlobalStorage())
7206       Diag(D.getDeclSpec().getConstexprSpecLoc(),
7207            diag::err_constinit_local_variable);
7208     else
7209       NewVD->addAttr(ConstInitAttr::Create(
7210           Context, D.getDeclSpec().getConstexprSpecLoc(),
7211           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7212     break;
7213   }
7214 
7215   // C99 6.7.4p3
7216   //   An inline definition of a function with external linkage shall
7217   //   not contain a definition of a modifiable object with static or
7218   //   thread storage duration...
7219   // We only apply this when the function is required to be defined
7220   // elsewhere, i.e. when the function is not 'extern inline'.  Note
7221   // that a local variable with thread storage duration still has to
7222   // be marked 'static'.  Also note that it's possible to get these
7223   // semantics in C++ using __attribute__((gnu_inline)).
7224   if (SC == SC_Static && S->getFnParent() != nullptr &&
7225       !NewVD->getType().isConstQualified()) {
7226     FunctionDecl *CurFD = getCurFunctionDecl();
7227     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7228       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7229            diag::warn_static_local_in_extern_inline);
7230       MaybeSuggestAddingStaticToDecl(CurFD);
7231     }
7232   }
7233 
7234   if (D.getDeclSpec().isModulePrivateSpecified()) {
7235     if (IsVariableTemplateSpecialization)
7236       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7237           << (IsPartialSpecialization ? 1 : 0)
7238           << FixItHint::CreateRemoval(
7239                  D.getDeclSpec().getModulePrivateSpecLoc());
7240     else if (IsMemberSpecialization)
7241       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7242         << 2
7243         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7244     else if (NewVD->hasLocalStorage())
7245       Diag(NewVD->getLocation(), diag::err_module_private_local)
7246           << 0 << NewVD
7247           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7248           << FixItHint::CreateRemoval(
7249                  D.getDeclSpec().getModulePrivateSpecLoc());
7250     else {
7251       NewVD->setModulePrivate();
7252       if (NewTemplate)
7253         NewTemplate->setModulePrivate();
7254       for (auto *B : Bindings)
7255         B->setModulePrivate();
7256     }
7257   }
7258 
7259   if (getLangOpts().OpenCL) {
7260     deduceOpenCLAddressSpace(NewVD);
7261 
7262     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7263     if (TSC != TSCS_unspecified) {
7264       bool IsCXX = getLangOpts().OpenCLCPlusPlus;
7265       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7266            diag::err_opencl_unknown_type_specifier)
7267           << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString()
7268           << DeclSpec::getSpecifierName(TSC) << 1;
7269       NewVD->setInvalidDecl();
7270     }
7271   }
7272 
7273   // Handle attributes prior to checking for duplicates in MergeVarDecl
7274   ProcessDeclAttributes(S, NewVD, D);
7275 
7276   // FIXME: This is probably the wrong location to be doing this and we should
7277   // probably be doing this for more attributes (especially for function
7278   // pointer attributes such as format, warn_unused_result, etc.). Ideally
7279   // the code to copy attributes would be generated by TableGen.
7280   if (R->isFunctionPointerType())
7281     if (const auto *TT = R->getAs<TypedefType>())
7282       copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7283 
7284   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7285       getLangOpts().SYCLIsDevice) {
7286     if (EmitTLSUnsupportedError &&
7287         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7288          (getLangOpts().OpenMPIsDevice &&
7289           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7290       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7291            diag::err_thread_unsupported);
7292 
7293     if (EmitTLSUnsupportedError &&
7294         (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7295       targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7296     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7297     // storage [duration]."
7298     if (SC == SC_None && S->getFnParent() != nullptr &&
7299         (NewVD->hasAttr<CUDASharedAttr>() ||
7300          NewVD->hasAttr<CUDAConstantAttr>())) {
7301       NewVD->setStorageClass(SC_Static);
7302     }
7303   }
7304 
7305   // Ensure that dllimport globals without explicit storage class are treated as
7306   // extern. The storage class is set above using parsed attributes. Now we can
7307   // check the VarDecl itself.
7308   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7309          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7310          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7311 
7312   // In auto-retain/release, infer strong retension for variables of
7313   // retainable type.
7314   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7315     NewVD->setInvalidDecl();
7316 
7317   // Handle GNU asm-label extension (encoded as an attribute).
7318   if (Expr *E = (Expr*)D.getAsmLabel()) {
7319     // The parser guarantees this is a string.
7320     StringLiteral *SE = cast<StringLiteral>(E);
7321     StringRef Label = SE->getString();
7322     if (S->getFnParent() != nullptr) {
7323       switch (SC) {
7324       case SC_None:
7325       case SC_Auto:
7326         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7327         break;
7328       case SC_Register:
7329         // Local Named register
7330         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7331             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7332           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7333         break;
7334       case SC_Static:
7335       case SC_Extern:
7336       case SC_PrivateExtern:
7337         break;
7338       }
7339     } else if (SC == SC_Register) {
7340       // Global Named register
7341       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7342         const auto &TI = Context.getTargetInfo();
7343         bool HasSizeMismatch;
7344 
7345         if (!TI.isValidGCCRegisterName(Label))
7346           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7347         else if (!TI.validateGlobalRegisterVariable(Label,
7348                                                     Context.getTypeSize(R),
7349                                                     HasSizeMismatch))
7350           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7351         else if (HasSizeMismatch)
7352           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7353       }
7354 
7355       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7356         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7357         NewVD->setInvalidDecl(true);
7358       }
7359     }
7360 
7361     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7362                                         /*IsLiteralLabel=*/true,
7363                                         SE->getStrTokenLoc(0)));
7364   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7365     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7366       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7367     if (I != ExtnameUndeclaredIdentifiers.end()) {
7368       if (isDeclExternC(NewVD)) {
7369         NewVD->addAttr(I->second);
7370         ExtnameUndeclaredIdentifiers.erase(I);
7371       } else
7372         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7373             << /*Variable*/1 << NewVD;
7374     }
7375   }
7376 
7377   // Find the shadowed declaration before filtering for scope.
7378   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7379                                 ? getShadowedDeclaration(NewVD, Previous)
7380                                 : nullptr;
7381 
7382   // Don't consider existing declarations that are in a different
7383   // scope and are out-of-semantic-context declarations (if the new
7384   // declaration has linkage).
7385   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7386                        D.getCXXScopeSpec().isNotEmpty() ||
7387                        IsMemberSpecialization ||
7388                        IsVariableTemplateSpecialization);
7389 
7390   // Check whether the previous declaration is in the same block scope. This
7391   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7392   if (getLangOpts().CPlusPlus &&
7393       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7394     NewVD->setPreviousDeclInSameBlockScope(
7395         Previous.isSingleResult() && !Previous.isShadowed() &&
7396         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7397 
7398   if (!getLangOpts().CPlusPlus) {
7399     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7400   } else {
7401     // If this is an explicit specialization of a static data member, check it.
7402     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7403         CheckMemberSpecialization(NewVD, Previous))
7404       NewVD->setInvalidDecl();
7405 
7406     // Merge the decl with the existing one if appropriate.
7407     if (!Previous.empty()) {
7408       if (Previous.isSingleResult() &&
7409           isa<FieldDecl>(Previous.getFoundDecl()) &&
7410           D.getCXXScopeSpec().isSet()) {
7411         // The user tried to define a non-static data member
7412         // out-of-line (C++ [dcl.meaning]p1).
7413         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7414           << D.getCXXScopeSpec().getRange();
7415         Previous.clear();
7416         NewVD->setInvalidDecl();
7417       }
7418     } else if (D.getCXXScopeSpec().isSet()) {
7419       // No previous declaration in the qualifying scope.
7420       Diag(D.getIdentifierLoc(), diag::err_no_member)
7421         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7422         << D.getCXXScopeSpec().getRange();
7423       NewVD->setInvalidDecl();
7424     }
7425 
7426     if (!IsVariableTemplateSpecialization)
7427       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7428 
7429     if (NewTemplate) {
7430       VarTemplateDecl *PrevVarTemplate =
7431           NewVD->getPreviousDecl()
7432               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7433               : nullptr;
7434 
7435       // Check the template parameter list of this declaration, possibly
7436       // merging in the template parameter list from the previous variable
7437       // template declaration.
7438       if (CheckTemplateParameterList(
7439               TemplateParams,
7440               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7441                               : nullptr,
7442               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7443                DC->isDependentContext())
7444                   ? TPC_ClassTemplateMember
7445                   : TPC_VarTemplate))
7446         NewVD->setInvalidDecl();
7447 
7448       // If we are providing an explicit specialization of a static variable
7449       // template, make a note of that.
7450       if (PrevVarTemplate &&
7451           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7452         PrevVarTemplate->setMemberSpecialization();
7453     }
7454   }
7455 
7456   // Diagnose shadowed variables iff this isn't a redeclaration.
7457   if (ShadowedDecl && !D.isRedeclaration())
7458     CheckShadow(NewVD, ShadowedDecl, Previous);
7459 
7460   ProcessPragmaWeak(S, NewVD);
7461 
7462   // If this is the first declaration of an extern C variable, update
7463   // the map of such variables.
7464   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7465       isIncompleteDeclExternC(*this, NewVD))
7466     RegisterLocallyScopedExternCDecl(NewVD, S);
7467 
7468   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7469     MangleNumberingContext *MCtx;
7470     Decl *ManglingContextDecl;
7471     std::tie(MCtx, ManglingContextDecl) =
7472         getCurrentMangleNumberContext(NewVD->getDeclContext());
7473     if (MCtx) {
7474       Context.setManglingNumber(
7475           NewVD, MCtx->getManglingNumber(
7476                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7477       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7478     }
7479   }
7480 
7481   // Special handling of variable named 'main'.
7482   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7483       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7484       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7485 
7486     // C++ [basic.start.main]p3
7487     // A program that declares a variable main at global scope is ill-formed.
7488     if (getLangOpts().CPlusPlus)
7489       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7490 
7491     // In C, and external-linkage variable named main results in undefined
7492     // behavior.
7493     else if (NewVD->hasExternalFormalLinkage())
7494       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7495   }
7496 
7497   if (D.isRedeclaration() && !Previous.empty()) {
7498     NamedDecl *Prev = Previous.getRepresentativeDecl();
7499     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7500                                    D.isFunctionDefinition());
7501   }
7502 
7503   if (NewTemplate) {
7504     if (NewVD->isInvalidDecl())
7505       NewTemplate->setInvalidDecl();
7506     ActOnDocumentableDecl(NewTemplate);
7507     return NewTemplate;
7508   }
7509 
7510   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7511     CompleteMemberSpecialization(NewVD, Previous);
7512 
7513   return NewVD;
7514 }
7515 
7516 /// Enum describing the %select options in diag::warn_decl_shadow.
7517 enum ShadowedDeclKind {
7518   SDK_Local,
7519   SDK_Global,
7520   SDK_StaticMember,
7521   SDK_Field,
7522   SDK_Typedef,
7523   SDK_Using,
7524   SDK_StructuredBinding
7525 };
7526 
7527 /// Determine what kind of declaration we're shadowing.
7528 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7529                                                 const DeclContext *OldDC) {
7530   if (isa<TypeAliasDecl>(ShadowedDecl))
7531     return SDK_Using;
7532   else if (isa<TypedefDecl>(ShadowedDecl))
7533     return SDK_Typedef;
7534   else if (isa<BindingDecl>(ShadowedDecl))
7535     return SDK_StructuredBinding;
7536   else if (isa<RecordDecl>(OldDC))
7537     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7538 
7539   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7540 }
7541 
7542 /// Return the location of the capture if the given lambda captures the given
7543 /// variable \p VD, or an invalid source location otherwise.
7544 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7545                                          const VarDecl *VD) {
7546   for (const Capture &Capture : LSI->Captures) {
7547     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7548       return Capture.getLocation();
7549   }
7550   return SourceLocation();
7551 }
7552 
7553 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7554                                      const LookupResult &R) {
7555   // Only diagnose if we're shadowing an unambiguous field or variable.
7556   if (R.getResultKind() != LookupResult::Found)
7557     return false;
7558 
7559   // Return false if warning is ignored.
7560   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7561 }
7562 
7563 /// Return the declaration shadowed by the given variable \p D, or null
7564 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7565 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7566                                         const LookupResult &R) {
7567   if (!shouldWarnIfShadowedDecl(Diags, R))
7568     return nullptr;
7569 
7570   // Don't diagnose declarations at file scope.
7571   if (D->hasGlobalStorage())
7572     return nullptr;
7573 
7574   NamedDecl *ShadowedDecl = R.getFoundDecl();
7575   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7576                                                             : nullptr;
7577 }
7578 
7579 /// Return the declaration shadowed by the given typedef \p D, or null
7580 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7581 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7582                                         const LookupResult &R) {
7583   // Don't warn if typedef declaration is part of a class
7584   if (D->getDeclContext()->isRecord())
7585     return nullptr;
7586 
7587   if (!shouldWarnIfShadowedDecl(Diags, R))
7588     return nullptr;
7589 
7590   NamedDecl *ShadowedDecl = R.getFoundDecl();
7591   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7592 }
7593 
7594 /// Return the declaration shadowed by the given variable \p D, or null
7595 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7596 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
7597                                         const LookupResult &R) {
7598   if (!shouldWarnIfShadowedDecl(Diags, R))
7599     return nullptr;
7600 
7601   NamedDecl *ShadowedDecl = R.getFoundDecl();
7602   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7603                                                             : nullptr;
7604 }
7605 
7606 /// Diagnose variable or built-in function shadowing.  Implements
7607 /// -Wshadow.
7608 ///
7609 /// This method is called whenever a VarDecl is added to a "useful"
7610 /// scope.
7611 ///
7612 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7613 /// \param R the lookup of the name
7614 ///
7615 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7616                        const LookupResult &R) {
7617   DeclContext *NewDC = D->getDeclContext();
7618 
7619   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7620     // Fields are not shadowed by variables in C++ static methods.
7621     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7622       if (MD->isStatic())
7623         return;
7624 
7625     // Fields shadowed by constructor parameters are a special case. Usually
7626     // the constructor initializes the field with the parameter.
7627     if (isa<CXXConstructorDecl>(NewDC))
7628       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7629         // Remember that this was shadowed so we can either warn about its
7630         // modification or its existence depending on warning settings.
7631         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7632         return;
7633       }
7634   }
7635 
7636   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7637     if (shadowedVar->isExternC()) {
7638       // For shadowing external vars, make sure that we point to the global
7639       // declaration, not a locally scoped extern declaration.
7640       for (auto I : shadowedVar->redecls())
7641         if (I->isFileVarDecl()) {
7642           ShadowedDecl = I;
7643           break;
7644         }
7645     }
7646 
7647   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7648 
7649   unsigned WarningDiag = diag::warn_decl_shadow;
7650   SourceLocation CaptureLoc;
7651   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7652       isa<CXXMethodDecl>(NewDC)) {
7653     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7654       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7655         if (RD->getLambdaCaptureDefault() == LCD_None) {
7656           // Try to avoid warnings for lambdas with an explicit capture list.
7657           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7658           // Warn only when the lambda captures the shadowed decl explicitly.
7659           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7660           if (CaptureLoc.isInvalid())
7661             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7662         } else {
7663           // Remember that this was shadowed so we can avoid the warning if the
7664           // shadowed decl isn't captured and the warning settings allow it.
7665           cast<LambdaScopeInfo>(getCurFunction())
7666               ->ShadowingDecls.push_back(
7667                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7668           return;
7669         }
7670       }
7671 
7672       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7673         // A variable can't shadow a local variable in an enclosing scope, if
7674         // they are separated by a non-capturing declaration context.
7675         for (DeclContext *ParentDC = NewDC;
7676              ParentDC && !ParentDC->Equals(OldDC);
7677              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7678           // Only block literals, captured statements, and lambda expressions
7679           // can capture; other scopes don't.
7680           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7681               !isLambdaCallOperator(ParentDC)) {
7682             return;
7683           }
7684         }
7685       }
7686     }
7687   }
7688 
7689   // Only warn about certain kinds of shadowing for class members.
7690   if (NewDC && NewDC->isRecord()) {
7691     // In particular, don't warn about shadowing non-class members.
7692     if (!OldDC->isRecord())
7693       return;
7694 
7695     // TODO: should we warn about static data members shadowing
7696     // static data members from base classes?
7697 
7698     // TODO: don't diagnose for inaccessible shadowed members.
7699     // This is hard to do perfectly because we might friend the
7700     // shadowing context, but that's just a false negative.
7701   }
7702 
7703 
7704   DeclarationName Name = R.getLookupName();
7705 
7706   // Emit warning and note.
7707   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7708     return;
7709   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7710   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7711   if (!CaptureLoc.isInvalid())
7712     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7713         << Name << /*explicitly*/ 1;
7714   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7715 }
7716 
7717 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7718 /// when these variables are captured by the lambda.
7719 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7720   for (const auto &Shadow : LSI->ShadowingDecls) {
7721     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7722     // Try to avoid the warning when the shadowed decl isn't captured.
7723     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7724     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7725     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7726                                        ? diag::warn_decl_shadow_uncaptured_local
7727                                        : diag::warn_decl_shadow)
7728         << Shadow.VD->getDeclName()
7729         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7730     if (!CaptureLoc.isInvalid())
7731       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7732           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7733     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7734   }
7735 }
7736 
7737 /// Check -Wshadow without the advantage of a previous lookup.
7738 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7739   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7740     return;
7741 
7742   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7743                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7744   LookupName(R, S);
7745   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7746     CheckShadow(D, ShadowedDecl, R);
7747 }
7748 
7749 /// Check if 'E', which is an expression that is about to be modified, refers
7750 /// to a constructor parameter that shadows a field.
7751 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7752   // Quickly ignore expressions that can't be shadowing ctor parameters.
7753   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7754     return;
7755   E = E->IgnoreParenImpCasts();
7756   auto *DRE = dyn_cast<DeclRefExpr>(E);
7757   if (!DRE)
7758     return;
7759   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7760   auto I = ShadowingDecls.find(D);
7761   if (I == ShadowingDecls.end())
7762     return;
7763   const NamedDecl *ShadowedDecl = I->second;
7764   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7765   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7766   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7767   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7768 
7769   // Avoid issuing multiple warnings about the same decl.
7770   ShadowingDecls.erase(I);
7771 }
7772 
7773 /// Check for conflict between this global or extern "C" declaration and
7774 /// previous global or extern "C" declarations. This is only used in C++.
7775 template<typename T>
7776 static bool checkGlobalOrExternCConflict(
7777     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7778   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7779   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7780 
7781   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7782     // The common case: this global doesn't conflict with any extern "C"
7783     // declaration.
7784     return false;
7785   }
7786 
7787   if (Prev) {
7788     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7789       // Both the old and new declarations have C language linkage. This is a
7790       // redeclaration.
7791       Previous.clear();
7792       Previous.addDecl(Prev);
7793       return true;
7794     }
7795 
7796     // This is a global, non-extern "C" declaration, and there is a previous
7797     // non-global extern "C" declaration. Diagnose if this is a variable
7798     // declaration.
7799     if (!isa<VarDecl>(ND))
7800       return false;
7801   } else {
7802     // The declaration is extern "C". Check for any declaration in the
7803     // translation unit which might conflict.
7804     if (IsGlobal) {
7805       // We have already performed the lookup into the translation unit.
7806       IsGlobal = false;
7807       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7808            I != E; ++I) {
7809         if (isa<VarDecl>(*I)) {
7810           Prev = *I;
7811           break;
7812         }
7813       }
7814     } else {
7815       DeclContext::lookup_result R =
7816           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7817       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7818            I != E; ++I) {
7819         if (isa<VarDecl>(*I)) {
7820           Prev = *I;
7821           break;
7822         }
7823         // FIXME: If we have any other entity with this name in global scope,
7824         // the declaration is ill-formed, but that is a defect: it breaks the
7825         // 'stat' hack, for instance. Only variables can have mangled name
7826         // clashes with extern "C" declarations, so only they deserve a
7827         // diagnostic.
7828       }
7829     }
7830 
7831     if (!Prev)
7832       return false;
7833   }
7834 
7835   // Use the first declaration's location to ensure we point at something which
7836   // is lexically inside an extern "C" linkage-spec.
7837   assert(Prev && "should have found a previous declaration to diagnose");
7838   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7839     Prev = FD->getFirstDecl();
7840   else
7841     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7842 
7843   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7844     << IsGlobal << ND;
7845   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7846     << IsGlobal;
7847   return false;
7848 }
7849 
7850 /// Apply special rules for handling extern "C" declarations. Returns \c true
7851 /// if we have found that this is a redeclaration of some prior entity.
7852 ///
7853 /// Per C++ [dcl.link]p6:
7854 ///   Two declarations [for a function or variable] with C language linkage
7855 ///   with the same name that appear in different scopes refer to the same
7856 ///   [entity]. An entity with C language linkage shall not be declared with
7857 ///   the same name as an entity in global scope.
7858 template<typename T>
7859 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7860                                                   LookupResult &Previous) {
7861   if (!S.getLangOpts().CPlusPlus) {
7862     // In C, when declaring a global variable, look for a corresponding 'extern'
7863     // variable declared in function scope. We don't need this in C++, because
7864     // we find local extern decls in the surrounding file-scope DeclContext.
7865     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7866       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7867         Previous.clear();
7868         Previous.addDecl(Prev);
7869         return true;
7870       }
7871     }
7872     return false;
7873   }
7874 
7875   // A declaration in the translation unit can conflict with an extern "C"
7876   // declaration.
7877   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7878     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7879 
7880   // An extern "C" declaration can conflict with a declaration in the
7881   // translation unit or can be a redeclaration of an extern "C" declaration
7882   // in another scope.
7883   if (isIncompleteDeclExternC(S,ND))
7884     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7885 
7886   // Neither global nor extern "C": nothing to do.
7887   return false;
7888 }
7889 
7890 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7891   // If the decl is already known invalid, don't check it.
7892   if (NewVD->isInvalidDecl())
7893     return;
7894 
7895   QualType T = NewVD->getType();
7896 
7897   // Defer checking an 'auto' type until its initializer is attached.
7898   if (T->isUndeducedType())
7899     return;
7900 
7901   if (NewVD->hasAttrs())
7902     CheckAlignasUnderalignment(NewVD);
7903 
7904   if (T->isObjCObjectType()) {
7905     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7906       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7907     T = Context.getObjCObjectPointerType(T);
7908     NewVD->setType(T);
7909   }
7910 
7911   // Emit an error if an address space was applied to decl with local storage.
7912   // This includes arrays of objects with address space qualifiers, but not
7913   // automatic variables that point to other address spaces.
7914   // ISO/IEC TR 18037 S5.1.2
7915   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7916       T.getAddressSpace() != LangAS::Default) {
7917     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7918     NewVD->setInvalidDecl();
7919     return;
7920   }
7921 
7922   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7923   // scope.
7924   if (getLangOpts().OpenCLVersion == 120 &&
7925       !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
7926                                             getLangOpts()) &&
7927       NewVD->isStaticLocal()) {
7928     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7929     NewVD->setInvalidDecl();
7930     return;
7931   }
7932 
7933   if (getLangOpts().OpenCL) {
7934     if (!diagnoseOpenCLTypes(*this, NewVD))
7935       return;
7936 
7937     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7938     if (NewVD->hasAttr<BlocksAttr>()) {
7939       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7940       return;
7941     }
7942 
7943     if (T->isBlockPointerType()) {
7944       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7945       // can't use 'extern' storage class.
7946       if (!T.isConstQualified()) {
7947         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7948             << 0 /*const*/;
7949         NewVD->setInvalidDecl();
7950         return;
7951       }
7952       if (NewVD->hasExternalStorage()) {
7953         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7954         NewVD->setInvalidDecl();
7955         return;
7956       }
7957     }
7958 
7959     // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7960     // __constant address space.
7961     // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7962     // variables inside a function can also be declared in the global
7963     // address space.
7964     // C++ for OpenCL inherits rule from OpenCL C v2.0.
7965     // FIXME: Adding local AS in C++ for OpenCL might make sense.
7966     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7967         NewVD->hasExternalStorage()) {
7968       if (!T->isSamplerT() &&
7969           !T->isDependentType() &&
7970           !(T.getAddressSpace() == LangAS::opencl_constant ||
7971             (T.getAddressSpace() == LangAS::opencl_global &&
7972              (getLangOpts().OpenCLVersion == 200 ||
7973               getLangOpts().OpenCLCPlusPlus)))) {
7974         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7975         if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7976           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7977               << Scope << "global or constant";
7978         else
7979           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7980               << Scope << "constant";
7981         NewVD->setInvalidDecl();
7982         return;
7983       }
7984     } else {
7985       if (T.getAddressSpace() == LangAS::opencl_global) {
7986         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7987             << 1 /*is any function*/ << "global";
7988         NewVD->setInvalidDecl();
7989         return;
7990       }
7991       if (T.getAddressSpace() == LangAS::opencl_constant ||
7992           T.getAddressSpace() == LangAS::opencl_local) {
7993         FunctionDecl *FD = getCurFunctionDecl();
7994         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7995         // in functions.
7996         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7997           if (T.getAddressSpace() == LangAS::opencl_constant)
7998             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7999                 << 0 /*non-kernel only*/ << "constant";
8000           else
8001             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8002                 << 0 /*non-kernel only*/ << "local";
8003           NewVD->setInvalidDecl();
8004           return;
8005         }
8006         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8007         // in the outermost scope of a kernel function.
8008         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8009           if (!getCurScope()->isFunctionScope()) {
8010             if (T.getAddressSpace() == LangAS::opencl_constant)
8011               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8012                   << "constant";
8013             else
8014               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8015                   << "local";
8016             NewVD->setInvalidDecl();
8017             return;
8018           }
8019         }
8020       } else if (T.getAddressSpace() != LangAS::opencl_private &&
8021                  // If we are parsing a template we didn't deduce an addr
8022                  // space yet.
8023                  T.getAddressSpace() != LangAS::Default) {
8024         // Do not allow other address spaces on automatic variable.
8025         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8026         NewVD->setInvalidDecl();
8027         return;
8028       }
8029     }
8030   }
8031 
8032   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8033       && !NewVD->hasAttr<BlocksAttr>()) {
8034     if (getLangOpts().getGC() != LangOptions::NonGC)
8035       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8036     else {
8037       assert(!getLangOpts().ObjCAutoRefCount);
8038       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8039     }
8040   }
8041 
8042   bool isVM = T->isVariablyModifiedType();
8043   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8044       NewVD->hasAttr<BlocksAttr>())
8045     setFunctionHasBranchProtectedScope();
8046 
8047   if ((isVM && NewVD->hasLinkage()) ||
8048       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8049     bool SizeIsNegative;
8050     llvm::APSInt Oversized;
8051     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8052         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8053     QualType FixedT;
8054     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
8055       FixedT = FixedTInfo->getType();
8056     else if (FixedTInfo) {
8057       // Type and type-as-written are canonically different. We need to fix up
8058       // both types separately.
8059       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8060                                                    Oversized);
8061     }
8062     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8063       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8064       // FIXME: This won't give the correct result for
8065       // int a[10][n];
8066       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8067 
8068       if (NewVD->isFileVarDecl())
8069         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8070         << SizeRange;
8071       else if (NewVD->isStaticLocal())
8072         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8073         << SizeRange;
8074       else
8075         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8076         << SizeRange;
8077       NewVD->setInvalidDecl();
8078       return;
8079     }
8080 
8081     if (!FixedTInfo) {
8082       if (NewVD->isFileVarDecl())
8083         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8084       else
8085         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8086       NewVD->setInvalidDecl();
8087       return;
8088     }
8089 
8090     Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8091     NewVD->setType(FixedT);
8092     NewVD->setTypeSourceInfo(FixedTInfo);
8093   }
8094 
8095   if (T->isVoidType()) {
8096     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8097     //                    of objects and functions.
8098     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8099       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8100         << T;
8101       NewVD->setInvalidDecl();
8102       return;
8103     }
8104   }
8105 
8106   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8107     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8108     NewVD->setInvalidDecl();
8109     return;
8110   }
8111 
8112   if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8113     Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8114     NewVD->setInvalidDecl();
8115     return;
8116   }
8117 
8118   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8119     Diag(NewVD->getLocation(), diag::err_block_on_vm);
8120     NewVD->setInvalidDecl();
8121     return;
8122   }
8123 
8124   if (NewVD->isConstexpr() && !T->isDependentType() &&
8125       RequireLiteralType(NewVD->getLocation(), T,
8126                          diag::err_constexpr_var_non_literal)) {
8127     NewVD->setInvalidDecl();
8128     return;
8129   }
8130 
8131   // PPC MMA non-pointer types are not allowed as non-local variable types.
8132   if (Context.getTargetInfo().getTriple().isPPC64() &&
8133       !NewVD->isLocalVarDecl() &&
8134       CheckPPCMMAType(T, NewVD->getLocation())) {
8135     NewVD->setInvalidDecl();
8136     return;
8137   }
8138 }
8139 
8140 /// Perform semantic checking on a newly-created variable
8141 /// declaration.
8142 ///
8143 /// This routine performs all of the type-checking required for a
8144 /// variable declaration once it has been built. It is used both to
8145 /// check variables after they have been parsed and their declarators
8146 /// have been translated into a declaration, and to check variables
8147 /// that have been instantiated from a template.
8148 ///
8149 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8150 ///
8151 /// Returns true if the variable declaration is a redeclaration.
8152 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8153   CheckVariableDeclarationType(NewVD);
8154 
8155   // If the decl is already known invalid, don't check it.
8156   if (NewVD->isInvalidDecl())
8157     return false;
8158 
8159   // If we did not find anything by this name, look for a non-visible
8160   // extern "C" declaration with the same name.
8161   if (Previous.empty() &&
8162       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8163     Previous.setShadowed();
8164 
8165   if (!Previous.empty()) {
8166     MergeVarDecl(NewVD, Previous);
8167     return true;
8168   }
8169   return false;
8170 }
8171 
8172 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8173 /// and if so, check that it's a valid override and remember it.
8174 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8175   llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8176 
8177   // Look for methods in base classes that this method might override.
8178   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8179                      /*DetectVirtual=*/false);
8180   auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8181     CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8182     DeclarationName Name = MD->getDeclName();
8183 
8184     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8185       // We really want to find the base class destructor here.
8186       QualType T = Context.getTypeDeclType(BaseRecord);
8187       CanQualType CT = Context.getCanonicalType(T);
8188       Name = Context.DeclarationNames.getCXXDestructorName(CT);
8189     }
8190 
8191     for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8192       CXXMethodDecl *BaseMD =
8193           dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8194       if (!BaseMD || !BaseMD->isVirtual() ||
8195           IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8196                      /*ConsiderCudaAttrs=*/true,
8197                      // C++2a [class.virtual]p2 does not consider requires
8198                      // clauses when overriding.
8199                      /*ConsiderRequiresClauses=*/false))
8200         continue;
8201 
8202       if (Overridden.insert(BaseMD).second) {
8203         MD->addOverriddenMethod(BaseMD);
8204         CheckOverridingFunctionReturnType(MD, BaseMD);
8205         CheckOverridingFunctionAttributes(MD, BaseMD);
8206         CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8207         CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8208       }
8209 
8210       // A method can only override one function from each base class. We
8211       // don't track indirectly overridden methods from bases of bases.
8212       return true;
8213     }
8214 
8215     return false;
8216   };
8217 
8218   DC->lookupInBases(VisitBase, Paths);
8219   return !Overridden.empty();
8220 }
8221 
8222 namespace {
8223   // Struct for holding all of the extra arguments needed by
8224   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8225   struct ActOnFDArgs {
8226     Scope *S;
8227     Declarator &D;
8228     MultiTemplateParamsArg TemplateParamLists;
8229     bool AddToScope;
8230   };
8231 } // end anonymous namespace
8232 
8233 namespace {
8234 
8235 // Callback to only accept typo corrections that have a non-zero edit distance.
8236 // Also only accept corrections that have the same parent decl.
8237 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8238  public:
8239   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8240                             CXXRecordDecl *Parent)
8241       : Context(Context), OriginalFD(TypoFD),
8242         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8243 
8244   bool ValidateCandidate(const TypoCorrection &candidate) override {
8245     if (candidate.getEditDistance() == 0)
8246       return false;
8247 
8248     SmallVector<unsigned, 1> MismatchedParams;
8249     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8250                                           CDeclEnd = candidate.end();
8251          CDecl != CDeclEnd; ++CDecl) {
8252       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8253 
8254       if (FD && !FD->hasBody() &&
8255           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8256         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8257           CXXRecordDecl *Parent = MD->getParent();
8258           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8259             return true;
8260         } else if (!ExpectedParent) {
8261           return true;
8262         }
8263       }
8264     }
8265 
8266     return false;
8267   }
8268 
8269   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8270     return std::make_unique<DifferentNameValidatorCCC>(*this);
8271   }
8272 
8273  private:
8274   ASTContext &Context;
8275   FunctionDecl *OriginalFD;
8276   CXXRecordDecl *ExpectedParent;
8277 };
8278 
8279 } // end anonymous namespace
8280 
8281 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8282   TypoCorrectedFunctionDefinitions.insert(F);
8283 }
8284 
8285 /// Generate diagnostics for an invalid function redeclaration.
8286 ///
8287 /// This routine handles generating the diagnostic messages for an invalid
8288 /// function redeclaration, including finding possible similar declarations
8289 /// or performing typo correction if there are no previous declarations with
8290 /// the same name.
8291 ///
8292 /// Returns a NamedDecl iff typo correction was performed and substituting in
8293 /// the new declaration name does not cause new errors.
8294 static NamedDecl *DiagnoseInvalidRedeclaration(
8295     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8296     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8297   DeclarationName Name = NewFD->getDeclName();
8298   DeclContext *NewDC = NewFD->getDeclContext();
8299   SmallVector<unsigned, 1> MismatchedParams;
8300   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8301   TypoCorrection Correction;
8302   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8303   unsigned DiagMsg =
8304     IsLocalFriend ? diag::err_no_matching_local_friend :
8305     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8306     diag::err_member_decl_does_not_match;
8307   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8308                     IsLocalFriend ? Sema::LookupLocalFriendName
8309                                   : Sema::LookupOrdinaryName,
8310                     Sema::ForVisibleRedeclaration);
8311 
8312   NewFD->setInvalidDecl();
8313   if (IsLocalFriend)
8314     SemaRef.LookupName(Prev, S);
8315   else
8316     SemaRef.LookupQualifiedName(Prev, NewDC);
8317   assert(!Prev.isAmbiguous() &&
8318          "Cannot have an ambiguity in previous-declaration lookup");
8319   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8320   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8321                                 MD ? MD->getParent() : nullptr);
8322   if (!Prev.empty()) {
8323     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8324          Func != FuncEnd; ++Func) {
8325       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8326       if (FD &&
8327           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8328         // Add 1 to the index so that 0 can mean the mismatch didn't
8329         // involve a parameter
8330         unsigned ParamNum =
8331             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8332         NearMatches.push_back(std::make_pair(FD, ParamNum));
8333       }
8334     }
8335   // If the qualified name lookup yielded nothing, try typo correction
8336   } else if ((Correction = SemaRef.CorrectTypo(
8337                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8338                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8339                   IsLocalFriend ? nullptr : NewDC))) {
8340     // Set up everything for the call to ActOnFunctionDeclarator
8341     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8342                               ExtraArgs.D.getIdentifierLoc());
8343     Previous.clear();
8344     Previous.setLookupName(Correction.getCorrection());
8345     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8346                                     CDeclEnd = Correction.end();
8347          CDecl != CDeclEnd; ++CDecl) {
8348       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8349       if (FD && !FD->hasBody() &&
8350           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8351         Previous.addDecl(FD);
8352       }
8353     }
8354     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8355 
8356     NamedDecl *Result;
8357     // Retry building the function declaration with the new previous
8358     // declarations, and with errors suppressed.
8359     {
8360       // Trap errors.
8361       Sema::SFINAETrap Trap(SemaRef);
8362 
8363       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8364       // pieces need to verify the typo-corrected C++ declaration and hopefully
8365       // eliminate the need for the parameter pack ExtraArgs.
8366       Result = SemaRef.ActOnFunctionDeclarator(
8367           ExtraArgs.S, ExtraArgs.D,
8368           Correction.getCorrectionDecl()->getDeclContext(),
8369           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8370           ExtraArgs.AddToScope);
8371 
8372       if (Trap.hasErrorOccurred())
8373         Result = nullptr;
8374     }
8375 
8376     if (Result) {
8377       // Determine which correction we picked.
8378       Decl *Canonical = Result->getCanonicalDecl();
8379       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8380            I != E; ++I)
8381         if ((*I)->getCanonicalDecl() == Canonical)
8382           Correction.setCorrectionDecl(*I);
8383 
8384       // Let Sema know about the correction.
8385       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8386       SemaRef.diagnoseTypo(
8387           Correction,
8388           SemaRef.PDiag(IsLocalFriend
8389                           ? diag::err_no_matching_local_friend_suggest
8390                           : diag::err_member_decl_does_not_match_suggest)
8391             << Name << NewDC << IsDefinition);
8392       return Result;
8393     }
8394 
8395     // Pretend the typo correction never occurred
8396     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8397                               ExtraArgs.D.getIdentifierLoc());
8398     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8399     Previous.clear();
8400     Previous.setLookupName(Name);
8401   }
8402 
8403   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8404       << Name << NewDC << IsDefinition << NewFD->getLocation();
8405 
8406   bool NewFDisConst = false;
8407   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8408     NewFDisConst = NewMD->isConst();
8409 
8410   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8411        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8412        NearMatch != NearMatchEnd; ++NearMatch) {
8413     FunctionDecl *FD = NearMatch->first;
8414     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8415     bool FDisConst = MD && MD->isConst();
8416     bool IsMember = MD || !IsLocalFriend;
8417 
8418     // FIXME: These notes are poorly worded for the local friend case.
8419     if (unsigned Idx = NearMatch->second) {
8420       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8421       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8422       if (Loc.isInvalid()) Loc = FD->getLocation();
8423       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8424                                  : diag::note_local_decl_close_param_match)
8425         << Idx << FDParam->getType()
8426         << NewFD->getParamDecl(Idx - 1)->getType();
8427     } else if (FDisConst != NewFDisConst) {
8428       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8429           << NewFDisConst << FD->getSourceRange().getEnd();
8430     } else
8431       SemaRef.Diag(FD->getLocation(),
8432                    IsMember ? diag::note_member_def_close_match
8433                             : diag::note_local_decl_close_match);
8434   }
8435   return nullptr;
8436 }
8437 
8438 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8439   switch (D.getDeclSpec().getStorageClassSpec()) {
8440   default: llvm_unreachable("Unknown storage class!");
8441   case DeclSpec::SCS_auto:
8442   case DeclSpec::SCS_register:
8443   case DeclSpec::SCS_mutable:
8444     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8445                  diag::err_typecheck_sclass_func);
8446     D.getMutableDeclSpec().ClearStorageClassSpecs();
8447     D.setInvalidType();
8448     break;
8449   case DeclSpec::SCS_unspecified: break;
8450   case DeclSpec::SCS_extern:
8451     if (D.getDeclSpec().isExternInLinkageSpec())
8452       return SC_None;
8453     return SC_Extern;
8454   case DeclSpec::SCS_static: {
8455     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8456       // C99 6.7.1p5:
8457       //   The declaration of an identifier for a function that has
8458       //   block scope shall have no explicit storage-class specifier
8459       //   other than extern
8460       // See also (C++ [dcl.stc]p4).
8461       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8462                    diag::err_static_block_func);
8463       break;
8464     } else
8465       return SC_Static;
8466   }
8467   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8468   }
8469 
8470   // No explicit storage class has already been returned
8471   return SC_None;
8472 }
8473 
8474 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8475                                            DeclContext *DC, QualType &R,
8476                                            TypeSourceInfo *TInfo,
8477                                            StorageClass SC,
8478                                            bool &IsVirtualOkay) {
8479   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8480   DeclarationName Name = NameInfo.getName();
8481 
8482   FunctionDecl *NewFD = nullptr;
8483   bool isInline = D.getDeclSpec().isInlineSpecified();
8484 
8485   if (!SemaRef.getLangOpts().CPlusPlus) {
8486     // Determine whether the function was written with a
8487     // prototype. This true when:
8488     //   - there is a prototype in the declarator, or
8489     //   - the type R of the function is some kind of typedef or other non-
8490     //     attributed reference to a type name (which eventually refers to a
8491     //     function type).
8492     bool HasPrototype =
8493       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8494       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8495 
8496     NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8497                                  R, TInfo, SC, isInline, HasPrototype,
8498                                  ConstexprSpecKind::Unspecified,
8499                                  /*TrailingRequiresClause=*/nullptr);
8500     if (D.isInvalidType())
8501       NewFD->setInvalidDecl();
8502 
8503     return NewFD;
8504   }
8505 
8506   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8507 
8508   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8509   if (ConstexprKind == ConstexprSpecKind::Constinit) {
8510     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8511                  diag::err_constexpr_wrong_decl_kind)
8512         << static_cast<int>(ConstexprKind);
8513     ConstexprKind = ConstexprSpecKind::Unspecified;
8514     D.getMutableDeclSpec().ClearConstexprSpec();
8515   }
8516   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8517 
8518   // Check that the return type is not an abstract class type.
8519   // For record types, this is done by the AbstractClassUsageDiagnoser once
8520   // the class has been completely parsed.
8521   if (!DC->isRecord() &&
8522       SemaRef.RequireNonAbstractType(
8523           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8524           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8525     D.setInvalidType();
8526 
8527   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8528     // This is a C++ constructor declaration.
8529     assert(DC->isRecord() &&
8530            "Constructors can only be declared in a member context");
8531 
8532     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8533     return CXXConstructorDecl::Create(
8534         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8535         TInfo, ExplicitSpecifier, isInline,
8536         /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(),
8537         TrailingRequiresClause);
8538 
8539   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8540     // This is a C++ destructor declaration.
8541     if (DC->isRecord()) {
8542       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8543       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8544       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8545           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8546           isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8547           TrailingRequiresClause);
8548 
8549       // If the destructor needs an implicit exception specification, set it
8550       // now. FIXME: It'd be nice to be able to create the right type to start
8551       // with, but the type needs to reference the destructor declaration.
8552       if (SemaRef.getLangOpts().CPlusPlus11)
8553         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8554 
8555       IsVirtualOkay = true;
8556       return NewDD;
8557 
8558     } else {
8559       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8560       D.setInvalidType();
8561 
8562       // Create a FunctionDecl to satisfy the function definition parsing
8563       // code path.
8564       return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8565                                   D.getIdentifierLoc(), Name, R, TInfo, SC,
8566                                   isInline,
8567                                   /*hasPrototype=*/true, ConstexprKind,
8568                                   TrailingRequiresClause);
8569     }
8570 
8571   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8572     if (!DC->isRecord()) {
8573       SemaRef.Diag(D.getIdentifierLoc(),
8574            diag::err_conv_function_not_member);
8575       return nullptr;
8576     }
8577 
8578     SemaRef.CheckConversionDeclarator(D, R, SC);
8579     if (D.isInvalidType())
8580       return nullptr;
8581 
8582     IsVirtualOkay = true;
8583     return CXXConversionDecl::Create(
8584         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8585         TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(),
8586         TrailingRequiresClause);
8587 
8588   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8589     if (TrailingRequiresClause)
8590       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8591                    diag::err_trailing_requires_clause_on_deduction_guide)
8592           << TrailingRequiresClause->getSourceRange();
8593     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8594 
8595     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8596                                          ExplicitSpecifier, NameInfo, R, TInfo,
8597                                          D.getEndLoc());
8598   } else if (DC->isRecord()) {
8599     // If the name of the function is the same as the name of the record,
8600     // then this must be an invalid constructor that has a return type.
8601     // (The parser checks for a return type and makes the declarator a
8602     // constructor if it has no return type).
8603     if (Name.getAsIdentifierInfo() &&
8604         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8605       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8606         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8607         << SourceRange(D.getIdentifierLoc());
8608       return nullptr;
8609     }
8610 
8611     // This is a C++ method declaration.
8612     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8613         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8614         TInfo, SC, isInline, ConstexprKind, SourceLocation(),
8615         TrailingRequiresClause);
8616     IsVirtualOkay = !Ret->isStatic();
8617     return Ret;
8618   } else {
8619     bool isFriend =
8620         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8621     if (!isFriend && SemaRef.CurContext->isRecord())
8622       return nullptr;
8623 
8624     // Determine whether the function was written with a
8625     // prototype. This true when:
8626     //   - we're in C++ (where every function has a prototype),
8627     return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8628                                 R, TInfo, SC, isInline, true /*HasPrototype*/,
8629                                 ConstexprKind, TrailingRequiresClause);
8630   }
8631 }
8632 
8633 enum OpenCLParamType {
8634   ValidKernelParam,
8635   PtrPtrKernelParam,
8636   PtrKernelParam,
8637   InvalidAddrSpacePtrKernelParam,
8638   InvalidKernelParam,
8639   RecordKernelParam
8640 };
8641 
8642 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8643   // Size dependent types are just typedefs to normal integer types
8644   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8645   // integers other than by their names.
8646   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8647 
8648   // Remove typedefs one by one until we reach a typedef
8649   // for a size dependent type.
8650   QualType DesugaredTy = Ty;
8651   do {
8652     ArrayRef<StringRef> Names(SizeTypeNames);
8653     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8654     if (Names.end() != Match)
8655       return true;
8656 
8657     Ty = DesugaredTy;
8658     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8659   } while (DesugaredTy != Ty);
8660 
8661   return false;
8662 }
8663 
8664 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8665   if (PT->isDependentType())
8666     return InvalidKernelParam;
8667 
8668   if (PT->isPointerType() || PT->isReferenceType()) {
8669     QualType PointeeType = PT->getPointeeType();
8670     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8671         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8672         PointeeType.getAddressSpace() == LangAS::Default)
8673       return InvalidAddrSpacePtrKernelParam;
8674 
8675     if (PointeeType->isPointerType()) {
8676       // This is a pointer to pointer parameter.
8677       // Recursively check inner type.
8678       OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
8679       if (ParamKind == InvalidAddrSpacePtrKernelParam ||
8680           ParamKind == InvalidKernelParam)
8681         return ParamKind;
8682 
8683       return PtrPtrKernelParam;
8684     }
8685 
8686     // C++ for OpenCL v1.0 s2.4:
8687     // Moreover the types used in parameters of the kernel functions must be:
8688     // Standard layout types for pointer parameters. The same applies to
8689     // reference if an implementation supports them in kernel parameters.
8690     if (S.getLangOpts().OpenCLCPlusPlus &&
8691         !S.getOpenCLOptions().isAvailableOption(
8692             "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
8693         !PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
8694         !PointeeType->isStandardLayoutType())
8695       return InvalidKernelParam;
8696 
8697     return PtrKernelParam;
8698   }
8699 
8700   // OpenCL v1.2 s6.9.k:
8701   // Arguments to kernel functions in a program cannot be declared with the
8702   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8703   // uintptr_t or a struct and/or union that contain fields declared to be one
8704   // of these built-in scalar types.
8705   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8706     return InvalidKernelParam;
8707 
8708   if (PT->isImageType())
8709     return PtrKernelParam;
8710 
8711   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8712     return InvalidKernelParam;
8713 
8714   // OpenCL extension spec v1.2 s9.5:
8715   // This extension adds support for half scalar and vector types as built-in
8716   // types that can be used for arithmetic operations, conversions etc.
8717   if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
8718       PT->isHalfType())
8719     return InvalidKernelParam;
8720 
8721   // Look into an array argument to check if it has a forbidden type.
8722   if (PT->isArrayType()) {
8723     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8724     // Call ourself to check an underlying type of an array. Since the
8725     // getPointeeOrArrayElementType returns an innermost type which is not an
8726     // array, this recursive call only happens once.
8727     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8728   }
8729 
8730   // C++ for OpenCL v1.0 s2.4:
8731   // Moreover the types used in parameters of the kernel functions must be:
8732   // Trivial and standard-layout types C++17 [basic.types] (plain old data
8733   // types) for parameters passed by value;
8734   if (S.getLangOpts().OpenCLCPlusPlus &&
8735       !S.getOpenCLOptions().isAvailableOption(
8736           "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
8737       !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
8738     return InvalidKernelParam;
8739 
8740   if (PT->isRecordType())
8741     return RecordKernelParam;
8742 
8743   return ValidKernelParam;
8744 }
8745 
8746 static void checkIsValidOpenCLKernelParameter(
8747   Sema &S,
8748   Declarator &D,
8749   ParmVarDecl *Param,
8750   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8751   QualType PT = Param->getType();
8752 
8753   // Cache the valid types we encounter to avoid rechecking structs that are
8754   // used again
8755   if (ValidTypes.count(PT.getTypePtr()))
8756     return;
8757 
8758   switch (getOpenCLKernelParameterType(S, PT)) {
8759   case PtrPtrKernelParam:
8760     // OpenCL v3.0 s6.11.a:
8761     // A kernel function argument cannot be declared as a pointer to a pointer
8762     // type. [...] This restriction only applies to OpenCL C 1.2 or below.
8763     if (S.getLangOpts().OpenCLVersion < 120 &&
8764         !S.getLangOpts().OpenCLCPlusPlus) {
8765       S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8766       D.setInvalidType();
8767       return;
8768     }
8769 
8770     ValidTypes.insert(PT.getTypePtr());
8771     return;
8772 
8773   case InvalidAddrSpacePtrKernelParam:
8774     // OpenCL v1.0 s6.5:
8775     // __kernel function arguments declared to be a pointer of a type can point
8776     // to one of the following address spaces only : __global, __local or
8777     // __constant.
8778     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8779     D.setInvalidType();
8780     return;
8781 
8782     // OpenCL v1.2 s6.9.k:
8783     // Arguments to kernel functions in a program cannot be declared with the
8784     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8785     // uintptr_t or a struct and/or union that contain fields declared to be
8786     // one of these built-in scalar types.
8787 
8788   case InvalidKernelParam:
8789     // OpenCL v1.2 s6.8 n:
8790     // A kernel function argument cannot be declared
8791     // of event_t type.
8792     // Do not diagnose half type since it is diagnosed as invalid argument
8793     // type for any function elsewhere.
8794     if (!PT->isHalfType()) {
8795       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8796 
8797       // Explain what typedefs are involved.
8798       const TypedefType *Typedef = nullptr;
8799       while ((Typedef = PT->getAs<TypedefType>())) {
8800         SourceLocation Loc = Typedef->getDecl()->getLocation();
8801         // SourceLocation may be invalid for a built-in type.
8802         if (Loc.isValid())
8803           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8804         PT = Typedef->desugar();
8805       }
8806     }
8807 
8808     D.setInvalidType();
8809     return;
8810 
8811   case PtrKernelParam:
8812   case ValidKernelParam:
8813     ValidTypes.insert(PT.getTypePtr());
8814     return;
8815 
8816   case RecordKernelParam:
8817     break;
8818   }
8819 
8820   // Track nested structs we will inspect
8821   SmallVector<const Decl *, 4> VisitStack;
8822 
8823   // Track where we are in the nested structs. Items will migrate from
8824   // VisitStack to HistoryStack as we do the DFS for bad field.
8825   SmallVector<const FieldDecl *, 4> HistoryStack;
8826   HistoryStack.push_back(nullptr);
8827 
8828   // At this point we already handled everything except of a RecordType or
8829   // an ArrayType of a RecordType.
8830   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8831   const RecordType *RecTy =
8832       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8833   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8834 
8835   VisitStack.push_back(RecTy->getDecl());
8836   assert(VisitStack.back() && "First decl null?");
8837 
8838   do {
8839     const Decl *Next = VisitStack.pop_back_val();
8840     if (!Next) {
8841       assert(!HistoryStack.empty());
8842       // Found a marker, we have gone up a level
8843       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8844         ValidTypes.insert(Hist->getType().getTypePtr());
8845 
8846       continue;
8847     }
8848 
8849     // Adds everything except the original parameter declaration (which is not a
8850     // field itself) to the history stack.
8851     const RecordDecl *RD;
8852     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8853       HistoryStack.push_back(Field);
8854 
8855       QualType FieldTy = Field->getType();
8856       // Other field types (known to be valid or invalid) are handled while we
8857       // walk around RecordDecl::fields().
8858       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8859              "Unexpected type.");
8860       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8861 
8862       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8863     } else {
8864       RD = cast<RecordDecl>(Next);
8865     }
8866 
8867     // Add a null marker so we know when we've gone back up a level
8868     VisitStack.push_back(nullptr);
8869 
8870     for (const auto *FD : RD->fields()) {
8871       QualType QT = FD->getType();
8872 
8873       if (ValidTypes.count(QT.getTypePtr()))
8874         continue;
8875 
8876       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8877       if (ParamType == ValidKernelParam)
8878         continue;
8879 
8880       if (ParamType == RecordKernelParam) {
8881         VisitStack.push_back(FD);
8882         continue;
8883       }
8884 
8885       // OpenCL v1.2 s6.9.p:
8886       // Arguments to kernel functions that are declared to be a struct or union
8887       // do not allow OpenCL objects to be passed as elements of the struct or
8888       // union.
8889       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8890           ParamType == InvalidAddrSpacePtrKernelParam) {
8891         S.Diag(Param->getLocation(),
8892                diag::err_record_with_pointers_kernel_param)
8893           << PT->isUnionType()
8894           << PT;
8895       } else {
8896         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8897       }
8898 
8899       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8900           << OrigRecDecl->getDeclName();
8901 
8902       // We have an error, now let's go back up through history and show where
8903       // the offending field came from
8904       for (ArrayRef<const FieldDecl *>::const_iterator
8905                I = HistoryStack.begin() + 1,
8906                E = HistoryStack.end();
8907            I != E; ++I) {
8908         const FieldDecl *OuterField = *I;
8909         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8910           << OuterField->getType();
8911       }
8912 
8913       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8914         << QT->isPointerType()
8915         << QT;
8916       D.setInvalidType();
8917       return;
8918     }
8919   } while (!VisitStack.empty());
8920 }
8921 
8922 /// Find the DeclContext in which a tag is implicitly declared if we see an
8923 /// elaborated type specifier in the specified context, and lookup finds
8924 /// nothing.
8925 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8926   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8927     DC = DC->getParent();
8928   return DC;
8929 }
8930 
8931 /// Find the Scope in which a tag is implicitly declared if we see an
8932 /// elaborated type specifier in the specified context, and lookup finds
8933 /// nothing.
8934 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8935   while (S->isClassScope() ||
8936          (LangOpts.CPlusPlus &&
8937           S->isFunctionPrototypeScope()) ||
8938          ((S->getFlags() & Scope::DeclScope) == 0) ||
8939          (S->getEntity() && S->getEntity()->isTransparentContext()))
8940     S = S->getParent();
8941   return S;
8942 }
8943 
8944 NamedDecl*
8945 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8946                               TypeSourceInfo *TInfo, LookupResult &Previous,
8947                               MultiTemplateParamsArg TemplateParamListsRef,
8948                               bool &AddToScope) {
8949   QualType R = TInfo->getType();
8950 
8951   assert(R->isFunctionType());
8952   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
8953     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
8954 
8955   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
8956   for (TemplateParameterList *TPL : TemplateParamListsRef)
8957     TemplateParamLists.push_back(TPL);
8958   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
8959     if (!TemplateParamLists.empty() &&
8960         Invented->getDepth() == TemplateParamLists.back()->getDepth())
8961       TemplateParamLists.back() = Invented;
8962     else
8963       TemplateParamLists.push_back(Invented);
8964   }
8965 
8966   // TODO: consider using NameInfo for diagnostic.
8967   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8968   DeclarationName Name = NameInfo.getName();
8969   StorageClass SC = getFunctionStorageClass(*this, D);
8970 
8971   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8972     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8973          diag::err_invalid_thread)
8974       << DeclSpec::getSpecifierName(TSCS);
8975 
8976   if (D.isFirstDeclarationOfMember())
8977     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8978                            D.getIdentifierLoc());
8979 
8980   bool isFriend = false;
8981   FunctionTemplateDecl *FunctionTemplate = nullptr;
8982   bool isMemberSpecialization = false;
8983   bool isFunctionTemplateSpecialization = false;
8984 
8985   bool isDependentClassScopeExplicitSpecialization = false;
8986   bool HasExplicitTemplateArgs = false;
8987   TemplateArgumentListInfo TemplateArgs;
8988 
8989   bool isVirtualOkay = false;
8990 
8991   DeclContext *OriginalDC = DC;
8992   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8993 
8994   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8995                                               isVirtualOkay);
8996   if (!NewFD) return nullptr;
8997 
8998   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8999     NewFD->setTopLevelDeclInObjCContainer();
9000 
9001   // Set the lexical context. If this is a function-scope declaration, or has a
9002   // C++ scope specifier, or is the object of a friend declaration, the lexical
9003   // context will be different from the semantic context.
9004   NewFD->setLexicalDeclContext(CurContext);
9005 
9006   if (IsLocalExternDecl)
9007     NewFD->setLocalExternDecl();
9008 
9009   if (getLangOpts().CPlusPlus) {
9010     bool isInline = D.getDeclSpec().isInlineSpecified();
9011     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9012     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9013     isFriend = D.getDeclSpec().isFriendSpecified();
9014     if (isFriend && !isInline && D.isFunctionDefinition()) {
9015       // C++ [class.friend]p5
9016       //   A function can be defined in a friend declaration of a
9017       //   class . . . . Such a function is implicitly inline.
9018       NewFD->setImplicitlyInline();
9019     }
9020 
9021     // If this is a method defined in an __interface, and is not a constructor
9022     // or an overloaded operator, then set the pure flag (isVirtual will already
9023     // return true).
9024     if (const CXXRecordDecl *Parent =
9025           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9026       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9027         NewFD->setPure(true);
9028 
9029       // C++ [class.union]p2
9030       //   A union can have member functions, but not virtual functions.
9031       if (isVirtual && Parent->isUnion())
9032         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9033     }
9034 
9035     SetNestedNameSpecifier(*this, NewFD, D);
9036     isMemberSpecialization = false;
9037     isFunctionTemplateSpecialization = false;
9038     if (D.isInvalidType())
9039       NewFD->setInvalidDecl();
9040 
9041     // Match up the template parameter lists with the scope specifier, then
9042     // determine whether we have a template or a template specialization.
9043     bool Invalid = false;
9044     TemplateParameterList *TemplateParams =
9045         MatchTemplateParametersToScopeSpecifier(
9046             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9047             D.getCXXScopeSpec(),
9048             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9049                 ? D.getName().TemplateId
9050                 : nullptr,
9051             TemplateParamLists, isFriend, isMemberSpecialization,
9052             Invalid);
9053     if (TemplateParams) {
9054       // Check that we can declare a template here.
9055       if (CheckTemplateDeclScope(S, TemplateParams))
9056         NewFD->setInvalidDecl();
9057 
9058       if (TemplateParams->size() > 0) {
9059         // This is a function template
9060 
9061         // A destructor cannot be a template.
9062         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9063           Diag(NewFD->getLocation(), diag::err_destructor_template);
9064           NewFD->setInvalidDecl();
9065         }
9066 
9067         // If we're adding a template to a dependent context, we may need to
9068         // rebuilding some of the types used within the template parameter list,
9069         // now that we know what the current instantiation is.
9070         if (DC->isDependentContext()) {
9071           ContextRAII SavedContext(*this, DC);
9072           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9073             Invalid = true;
9074         }
9075 
9076         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9077                                                         NewFD->getLocation(),
9078                                                         Name, TemplateParams,
9079                                                         NewFD);
9080         FunctionTemplate->setLexicalDeclContext(CurContext);
9081         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9082 
9083         // For source fidelity, store the other template param lists.
9084         if (TemplateParamLists.size() > 1) {
9085           NewFD->setTemplateParameterListsInfo(Context,
9086               ArrayRef<TemplateParameterList *>(TemplateParamLists)
9087                   .drop_back(1));
9088         }
9089       } else {
9090         // This is a function template specialization.
9091         isFunctionTemplateSpecialization = true;
9092         // For source fidelity, store all the template param lists.
9093         if (TemplateParamLists.size() > 0)
9094           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9095 
9096         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9097         if (isFriend) {
9098           // We want to remove the "template<>", found here.
9099           SourceRange RemoveRange = TemplateParams->getSourceRange();
9100 
9101           // If we remove the template<> and the name is not a
9102           // template-id, we're actually silently creating a problem:
9103           // the friend declaration will refer to an untemplated decl,
9104           // and clearly the user wants a template specialization.  So
9105           // we need to insert '<>' after the name.
9106           SourceLocation InsertLoc;
9107           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9108             InsertLoc = D.getName().getSourceRange().getEnd();
9109             InsertLoc = getLocForEndOfToken(InsertLoc);
9110           }
9111 
9112           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9113             << Name << RemoveRange
9114             << FixItHint::CreateRemoval(RemoveRange)
9115             << FixItHint::CreateInsertion(InsertLoc, "<>");
9116         }
9117       }
9118     } else {
9119       // Check that we can declare a template here.
9120       if (!TemplateParamLists.empty() && isMemberSpecialization &&
9121           CheckTemplateDeclScope(S, TemplateParamLists.back()))
9122         NewFD->setInvalidDecl();
9123 
9124       // All template param lists were matched against the scope specifier:
9125       // this is NOT (an explicit specialization of) a template.
9126       if (TemplateParamLists.size() > 0)
9127         // For source fidelity, store all the template param lists.
9128         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9129     }
9130 
9131     if (Invalid) {
9132       NewFD->setInvalidDecl();
9133       if (FunctionTemplate)
9134         FunctionTemplate->setInvalidDecl();
9135     }
9136 
9137     // C++ [dcl.fct.spec]p5:
9138     //   The virtual specifier shall only be used in declarations of
9139     //   nonstatic class member functions that appear within a
9140     //   member-specification of a class declaration; see 10.3.
9141     //
9142     if (isVirtual && !NewFD->isInvalidDecl()) {
9143       if (!isVirtualOkay) {
9144         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9145              diag::err_virtual_non_function);
9146       } else if (!CurContext->isRecord()) {
9147         // 'virtual' was specified outside of the class.
9148         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9149              diag::err_virtual_out_of_class)
9150           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9151       } else if (NewFD->getDescribedFunctionTemplate()) {
9152         // C++ [temp.mem]p3:
9153         //  A member function template shall not be virtual.
9154         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9155              diag::err_virtual_member_function_template)
9156           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9157       } else {
9158         // Okay: Add virtual to the method.
9159         NewFD->setVirtualAsWritten(true);
9160       }
9161 
9162       if (getLangOpts().CPlusPlus14 &&
9163           NewFD->getReturnType()->isUndeducedType())
9164         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9165     }
9166 
9167     if (getLangOpts().CPlusPlus14 &&
9168         (NewFD->isDependentContext() ||
9169          (isFriend && CurContext->isDependentContext())) &&
9170         NewFD->getReturnType()->isUndeducedType()) {
9171       // If the function template is referenced directly (for instance, as a
9172       // member of the current instantiation), pretend it has a dependent type.
9173       // This is not really justified by the standard, but is the only sane
9174       // thing to do.
9175       // FIXME: For a friend function, we have not marked the function as being
9176       // a friend yet, so 'isDependentContext' on the FD doesn't work.
9177       const FunctionProtoType *FPT =
9178           NewFD->getType()->castAs<FunctionProtoType>();
9179       QualType Result =
9180           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
9181       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9182                                              FPT->getExtProtoInfo()));
9183     }
9184 
9185     // C++ [dcl.fct.spec]p3:
9186     //  The inline specifier shall not appear on a block scope function
9187     //  declaration.
9188     if (isInline && !NewFD->isInvalidDecl()) {
9189       if (CurContext->isFunctionOrMethod()) {
9190         // 'inline' is not allowed on block scope function declaration.
9191         Diag(D.getDeclSpec().getInlineSpecLoc(),
9192              diag::err_inline_declaration_block_scope) << Name
9193           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9194       }
9195     }
9196 
9197     // C++ [dcl.fct.spec]p6:
9198     //  The explicit specifier shall be used only in the declaration of a
9199     //  constructor or conversion function within its class definition;
9200     //  see 12.3.1 and 12.3.2.
9201     if (hasExplicit && !NewFD->isInvalidDecl() &&
9202         !isa<CXXDeductionGuideDecl>(NewFD)) {
9203       if (!CurContext->isRecord()) {
9204         // 'explicit' was specified outside of the class.
9205         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9206              diag::err_explicit_out_of_class)
9207             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9208       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9209                  !isa<CXXConversionDecl>(NewFD)) {
9210         // 'explicit' was specified on a function that wasn't a constructor
9211         // or conversion function.
9212         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9213              diag::err_explicit_non_ctor_or_conv_function)
9214             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9215       }
9216     }
9217 
9218     ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9219     if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9220       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9221       // are implicitly inline.
9222       NewFD->setImplicitlyInline();
9223 
9224       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9225       // be either constructors or to return a literal type. Therefore,
9226       // destructors cannot be declared constexpr.
9227       if (isa<CXXDestructorDecl>(NewFD) &&
9228           (!getLangOpts().CPlusPlus20 ||
9229            ConstexprKind == ConstexprSpecKind::Consteval)) {
9230         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9231             << static_cast<int>(ConstexprKind);
9232         NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9233                                     ? ConstexprSpecKind::Unspecified
9234                                     : ConstexprSpecKind::Constexpr);
9235       }
9236       // C++20 [dcl.constexpr]p2: An allocation function, or a
9237       // deallocation function shall not be declared with the consteval
9238       // specifier.
9239       if (ConstexprKind == ConstexprSpecKind::Consteval &&
9240           (NewFD->getOverloadedOperator() == OO_New ||
9241            NewFD->getOverloadedOperator() == OO_Array_New ||
9242            NewFD->getOverloadedOperator() == OO_Delete ||
9243            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9244         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9245              diag::err_invalid_consteval_decl_kind)
9246             << NewFD;
9247         NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
9248       }
9249     }
9250 
9251     // If __module_private__ was specified, mark the function accordingly.
9252     if (D.getDeclSpec().isModulePrivateSpecified()) {
9253       if (isFunctionTemplateSpecialization) {
9254         SourceLocation ModulePrivateLoc
9255           = D.getDeclSpec().getModulePrivateSpecLoc();
9256         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9257           << 0
9258           << FixItHint::CreateRemoval(ModulePrivateLoc);
9259       } else {
9260         NewFD->setModulePrivate();
9261         if (FunctionTemplate)
9262           FunctionTemplate->setModulePrivate();
9263       }
9264     }
9265 
9266     if (isFriend) {
9267       if (FunctionTemplate) {
9268         FunctionTemplate->setObjectOfFriendDecl();
9269         FunctionTemplate->setAccess(AS_public);
9270       }
9271       NewFD->setObjectOfFriendDecl();
9272       NewFD->setAccess(AS_public);
9273     }
9274 
9275     // If a function is defined as defaulted or deleted, mark it as such now.
9276     // We'll do the relevant checks on defaulted / deleted functions later.
9277     switch (D.getFunctionDefinitionKind()) {
9278     case FunctionDefinitionKind::Declaration:
9279     case FunctionDefinitionKind::Definition:
9280       break;
9281 
9282     case FunctionDefinitionKind::Defaulted:
9283       NewFD->setDefaulted();
9284       break;
9285 
9286     case FunctionDefinitionKind::Deleted:
9287       NewFD->setDeletedAsWritten();
9288       break;
9289     }
9290 
9291     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9292         D.isFunctionDefinition()) {
9293       // C++ [class.mfct]p2:
9294       //   A member function may be defined (8.4) in its class definition, in
9295       //   which case it is an inline member function (7.1.2)
9296       NewFD->setImplicitlyInline();
9297     }
9298 
9299     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9300         !CurContext->isRecord()) {
9301       // C++ [class.static]p1:
9302       //   A data or function member of a class may be declared static
9303       //   in a class definition, in which case it is a static member of
9304       //   the class.
9305 
9306       // Complain about the 'static' specifier if it's on an out-of-line
9307       // member function definition.
9308 
9309       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9310       // member function template declaration and class member template
9311       // declaration (MSVC versions before 2015), warn about this.
9312       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9313            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9314              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9315            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9316            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9317         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9318     }
9319 
9320     // C++11 [except.spec]p15:
9321     //   A deallocation function with no exception-specification is treated
9322     //   as if it were specified with noexcept(true).
9323     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9324     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9325          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9326         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9327       NewFD->setType(Context.getFunctionType(
9328           FPT->getReturnType(), FPT->getParamTypes(),
9329           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9330   }
9331 
9332   // Filter out previous declarations that don't match the scope.
9333   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9334                        D.getCXXScopeSpec().isNotEmpty() ||
9335                        isMemberSpecialization ||
9336                        isFunctionTemplateSpecialization);
9337 
9338   // Handle GNU asm-label extension (encoded as an attribute).
9339   if (Expr *E = (Expr*) D.getAsmLabel()) {
9340     // The parser guarantees this is a string.
9341     StringLiteral *SE = cast<StringLiteral>(E);
9342     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9343                                         /*IsLiteralLabel=*/true,
9344                                         SE->getStrTokenLoc(0)));
9345   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9346     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9347       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9348     if (I != ExtnameUndeclaredIdentifiers.end()) {
9349       if (isDeclExternC(NewFD)) {
9350         NewFD->addAttr(I->second);
9351         ExtnameUndeclaredIdentifiers.erase(I);
9352       } else
9353         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9354             << /*Variable*/0 << NewFD;
9355     }
9356   }
9357 
9358   // Copy the parameter declarations from the declarator D to the function
9359   // declaration NewFD, if they are available.  First scavenge them into Params.
9360   SmallVector<ParmVarDecl*, 16> Params;
9361   unsigned FTIIdx;
9362   if (D.isFunctionDeclarator(FTIIdx)) {
9363     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9364 
9365     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9366     // function that takes no arguments, not a function that takes a
9367     // single void argument.
9368     // We let through "const void" here because Sema::GetTypeForDeclarator
9369     // already checks for that case.
9370     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9371       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9372         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9373         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9374         Param->setDeclContext(NewFD);
9375         Params.push_back(Param);
9376 
9377         if (Param->isInvalidDecl())
9378           NewFD->setInvalidDecl();
9379       }
9380     }
9381 
9382     if (!getLangOpts().CPlusPlus) {
9383       // In C, find all the tag declarations from the prototype and move them
9384       // into the function DeclContext. Remove them from the surrounding tag
9385       // injection context of the function, which is typically but not always
9386       // the TU.
9387       DeclContext *PrototypeTagContext =
9388           getTagInjectionContext(NewFD->getLexicalDeclContext());
9389       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9390         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9391 
9392         // We don't want to reparent enumerators. Look at their parent enum
9393         // instead.
9394         if (!TD) {
9395           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9396             TD = cast<EnumDecl>(ECD->getDeclContext());
9397         }
9398         if (!TD)
9399           continue;
9400         DeclContext *TagDC = TD->getLexicalDeclContext();
9401         if (!TagDC->containsDecl(TD))
9402           continue;
9403         TagDC->removeDecl(TD);
9404         TD->setDeclContext(NewFD);
9405         NewFD->addDecl(TD);
9406 
9407         // Preserve the lexical DeclContext if it is not the surrounding tag
9408         // injection context of the FD. In this example, the semantic context of
9409         // E will be f and the lexical context will be S, while both the
9410         // semantic and lexical contexts of S will be f:
9411         //   void f(struct S { enum E { a } f; } s);
9412         if (TagDC != PrototypeTagContext)
9413           TD->setLexicalDeclContext(TagDC);
9414       }
9415     }
9416   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9417     // When we're declaring a function with a typedef, typeof, etc as in the
9418     // following example, we'll need to synthesize (unnamed)
9419     // parameters for use in the declaration.
9420     //
9421     // @code
9422     // typedef void fn(int);
9423     // fn f;
9424     // @endcode
9425 
9426     // Synthesize a parameter for each argument type.
9427     for (const auto &AI : FT->param_types()) {
9428       ParmVarDecl *Param =
9429           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9430       Param->setScopeInfo(0, Params.size());
9431       Params.push_back(Param);
9432     }
9433   } else {
9434     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9435            "Should not need args for typedef of non-prototype fn");
9436   }
9437 
9438   // Finally, we know we have the right number of parameters, install them.
9439   NewFD->setParams(Params);
9440 
9441   if (D.getDeclSpec().isNoreturnSpecified())
9442     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9443                                            D.getDeclSpec().getNoreturnSpecLoc(),
9444                                            AttributeCommonInfo::AS_Keyword));
9445 
9446   // Functions returning a variably modified type violate C99 6.7.5.2p2
9447   // because all functions have linkage.
9448   if (!NewFD->isInvalidDecl() &&
9449       NewFD->getReturnType()->isVariablyModifiedType()) {
9450     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9451     NewFD->setInvalidDecl();
9452   }
9453 
9454   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9455   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9456       !NewFD->hasAttr<SectionAttr>())
9457     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9458         Context, PragmaClangTextSection.SectionName,
9459         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9460 
9461   // Apply an implicit SectionAttr if #pragma code_seg is active.
9462   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9463       !NewFD->hasAttr<SectionAttr>()) {
9464     NewFD->addAttr(SectionAttr::CreateImplicit(
9465         Context, CodeSegStack.CurrentValue->getString(),
9466         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9467         SectionAttr::Declspec_allocate));
9468     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9469                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9470                          ASTContext::PSF_Read,
9471                      NewFD))
9472       NewFD->dropAttr<SectionAttr>();
9473   }
9474 
9475   // Apply an implicit CodeSegAttr from class declspec or
9476   // apply an implicit SectionAttr from #pragma code_seg if active.
9477   if (!NewFD->hasAttr<CodeSegAttr>()) {
9478     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9479                                                                  D.isFunctionDefinition())) {
9480       NewFD->addAttr(SAttr);
9481     }
9482   }
9483 
9484   // Handle attributes.
9485   ProcessDeclAttributes(S, NewFD, D);
9486 
9487   if (getLangOpts().OpenCL) {
9488     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9489     // type declaration will generate a compilation error.
9490     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9491     if (AddressSpace != LangAS::Default) {
9492       Diag(NewFD->getLocation(),
9493            diag::err_opencl_return_value_with_address_space);
9494       NewFD->setInvalidDecl();
9495     }
9496   }
9497 
9498   if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))
9499     checkDeviceDecl(NewFD, D.getBeginLoc());
9500 
9501   if (!getLangOpts().CPlusPlus) {
9502     // Perform semantic checking on the function declaration.
9503     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9504       CheckMain(NewFD, D.getDeclSpec());
9505 
9506     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9507       CheckMSVCRTEntryPoint(NewFD);
9508 
9509     if (!NewFD->isInvalidDecl())
9510       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9511                                                   isMemberSpecialization));
9512     else if (!Previous.empty())
9513       // Recover gracefully from an invalid redeclaration.
9514       D.setRedeclaration(true);
9515     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9516             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9517            "previous declaration set still overloaded");
9518 
9519     // Diagnose no-prototype function declarations with calling conventions that
9520     // don't support variadic calls. Only do this in C and do it after merging
9521     // possibly prototyped redeclarations.
9522     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9523     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9524       CallingConv CC = FT->getExtInfo().getCC();
9525       if (!supportsVariadicCall(CC)) {
9526         // Windows system headers sometimes accidentally use stdcall without
9527         // (void) parameters, so we relax this to a warning.
9528         int DiagID =
9529             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9530         Diag(NewFD->getLocation(), DiagID)
9531             << FunctionType::getNameForCallConv(CC);
9532       }
9533     }
9534 
9535    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9536        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9537      checkNonTrivialCUnion(NewFD->getReturnType(),
9538                            NewFD->getReturnTypeSourceRange().getBegin(),
9539                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9540   } else {
9541     // C++11 [replacement.functions]p3:
9542     //  The program's definitions shall not be specified as inline.
9543     //
9544     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9545     //
9546     // Suppress the diagnostic if the function is __attribute__((used)), since
9547     // that forces an external definition to be emitted.
9548     if (D.getDeclSpec().isInlineSpecified() &&
9549         NewFD->isReplaceableGlobalAllocationFunction() &&
9550         !NewFD->hasAttr<UsedAttr>())
9551       Diag(D.getDeclSpec().getInlineSpecLoc(),
9552            diag::ext_operator_new_delete_declared_inline)
9553         << NewFD->getDeclName();
9554 
9555     // If the declarator is a template-id, translate the parser's template
9556     // argument list into our AST format.
9557     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9558       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9559       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9560       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9561       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9562                                          TemplateId->NumArgs);
9563       translateTemplateArguments(TemplateArgsPtr,
9564                                  TemplateArgs);
9565 
9566       HasExplicitTemplateArgs = true;
9567 
9568       if (NewFD->isInvalidDecl()) {
9569         HasExplicitTemplateArgs = false;
9570       } else if (FunctionTemplate) {
9571         // Function template with explicit template arguments.
9572         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9573           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9574 
9575         HasExplicitTemplateArgs = false;
9576       } else {
9577         assert((isFunctionTemplateSpecialization ||
9578                 D.getDeclSpec().isFriendSpecified()) &&
9579                "should have a 'template<>' for this decl");
9580         // "friend void foo<>(int);" is an implicit specialization decl.
9581         isFunctionTemplateSpecialization = true;
9582       }
9583     } else if (isFriend && isFunctionTemplateSpecialization) {
9584       // This combination is only possible in a recovery case;  the user
9585       // wrote something like:
9586       //   template <> friend void foo(int);
9587       // which we're recovering from as if the user had written:
9588       //   friend void foo<>(int);
9589       // Go ahead and fake up a template id.
9590       HasExplicitTemplateArgs = true;
9591       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9592       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9593     }
9594 
9595     // We do not add HD attributes to specializations here because
9596     // they may have different constexpr-ness compared to their
9597     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9598     // may end up with different effective targets. Instead, a
9599     // specialization inherits its target attributes from its template
9600     // in the CheckFunctionTemplateSpecialization() call below.
9601     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9602       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9603 
9604     // If it's a friend (and only if it's a friend), it's possible
9605     // that either the specialized function type or the specialized
9606     // template is dependent, and therefore matching will fail.  In
9607     // this case, don't check the specialization yet.
9608     if (isFunctionTemplateSpecialization && isFriend &&
9609         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9610          TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
9611              TemplateArgs.arguments()))) {
9612       assert(HasExplicitTemplateArgs &&
9613              "friend function specialization without template args");
9614       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9615                                                        Previous))
9616         NewFD->setInvalidDecl();
9617     } else if (isFunctionTemplateSpecialization) {
9618       if (CurContext->isDependentContext() && CurContext->isRecord()
9619           && !isFriend) {
9620         isDependentClassScopeExplicitSpecialization = true;
9621       } else if (!NewFD->isInvalidDecl() &&
9622                  CheckFunctionTemplateSpecialization(
9623                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9624                      Previous))
9625         NewFD->setInvalidDecl();
9626 
9627       // C++ [dcl.stc]p1:
9628       //   A storage-class-specifier shall not be specified in an explicit
9629       //   specialization (14.7.3)
9630       FunctionTemplateSpecializationInfo *Info =
9631           NewFD->getTemplateSpecializationInfo();
9632       if (Info && SC != SC_None) {
9633         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9634           Diag(NewFD->getLocation(),
9635                diag::err_explicit_specialization_inconsistent_storage_class)
9636             << SC
9637             << FixItHint::CreateRemoval(
9638                                       D.getDeclSpec().getStorageClassSpecLoc());
9639 
9640         else
9641           Diag(NewFD->getLocation(),
9642                diag::ext_explicit_specialization_storage_class)
9643             << FixItHint::CreateRemoval(
9644                                       D.getDeclSpec().getStorageClassSpecLoc());
9645       }
9646     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9647       if (CheckMemberSpecialization(NewFD, Previous))
9648           NewFD->setInvalidDecl();
9649     }
9650 
9651     // Perform semantic checking on the function declaration.
9652     if (!isDependentClassScopeExplicitSpecialization) {
9653       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9654         CheckMain(NewFD, D.getDeclSpec());
9655 
9656       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9657         CheckMSVCRTEntryPoint(NewFD);
9658 
9659       if (!NewFD->isInvalidDecl())
9660         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9661                                                     isMemberSpecialization));
9662       else if (!Previous.empty())
9663         // Recover gracefully from an invalid redeclaration.
9664         D.setRedeclaration(true);
9665     }
9666 
9667     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9668             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9669            "previous declaration set still overloaded");
9670 
9671     NamedDecl *PrincipalDecl = (FunctionTemplate
9672                                 ? cast<NamedDecl>(FunctionTemplate)
9673                                 : NewFD);
9674 
9675     if (isFriend && NewFD->getPreviousDecl()) {
9676       AccessSpecifier Access = AS_public;
9677       if (!NewFD->isInvalidDecl())
9678         Access = NewFD->getPreviousDecl()->getAccess();
9679 
9680       NewFD->setAccess(Access);
9681       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9682     }
9683 
9684     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9685         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9686       PrincipalDecl->setNonMemberOperator();
9687 
9688     // If we have a function template, check the template parameter
9689     // list. This will check and merge default template arguments.
9690     if (FunctionTemplate) {
9691       FunctionTemplateDecl *PrevTemplate =
9692                                      FunctionTemplate->getPreviousDecl();
9693       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9694                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9695                                     : nullptr,
9696                             D.getDeclSpec().isFriendSpecified()
9697                               ? (D.isFunctionDefinition()
9698                                    ? TPC_FriendFunctionTemplateDefinition
9699                                    : TPC_FriendFunctionTemplate)
9700                               : (D.getCXXScopeSpec().isSet() &&
9701                                  DC && DC->isRecord() &&
9702                                  DC->isDependentContext())
9703                                   ? TPC_ClassTemplateMember
9704                                   : TPC_FunctionTemplate);
9705     }
9706 
9707     if (NewFD->isInvalidDecl()) {
9708       // Ignore all the rest of this.
9709     } else if (!D.isRedeclaration()) {
9710       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9711                                        AddToScope };
9712       // Fake up an access specifier if it's supposed to be a class member.
9713       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9714         NewFD->setAccess(AS_public);
9715 
9716       // Qualified decls generally require a previous declaration.
9717       if (D.getCXXScopeSpec().isSet()) {
9718         // ...with the major exception of templated-scope or
9719         // dependent-scope friend declarations.
9720 
9721         // TODO: we currently also suppress this check in dependent
9722         // contexts because (1) the parameter depth will be off when
9723         // matching friend templates and (2) we might actually be
9724         // selecting a friend based on a dependent factor.  But there
9725         // are situations where these conditions don't apply and we
9726         // can actually do this check immediately.
9727         //
9728         // Unless the scope is dependent, it's always an error if qualified
9729         // redeclaration lookup found nothing at all. Diagnose that now;
9730         // nothing will diagnose that error later.
9731         if (isFriend &&
9732             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9733              (!Previous.empty() && CurContext->isDependentContext()))) {
9734           // ignore these
9735         } else if (NewFD->isCPUDispatchMultiVersion() ||
9736                    NewFD->isCPUSpecificMultiVersion()) {
9737           // ignore this, we allow the redeclaration behavior here to create new
9738           // versions of the function.
9739         } else {
9740           // The user tried to provide an out-of-line definition for a
9741           // function that is a member of a class or namespace, but there
9742           // was no such member function declared (C++ [class.mfct]p2,
9743           // C++ [namespace.memdef]p2). For example:
9744           //
9745           // class X {
9746           //   void f() const;
9747           // };
9748           //
9749           // void X::f() { } // ill-formed
9750           //
9751           // Complain about this problem, and attempt to suggest close
9752           // matches (e.g., those that differ only in cv-qualifiers and
9753           // whether the parameter types are references).
9754 
9755           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9756                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9757             AddToScope = ExtraArgs.AddToScope;
9758             return Result;
9759           }
9760         }
9761 
9762         // Unqualified local friend declarations are required to resolve
9763         // to something.
9764       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9765         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9766                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9767           AddToScope = ExtraArgs.AddToScope;
9768           return Result;
9769         }
9770       }
9771     } else if (!D.isFunctionDefinition() &&
9772                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9773                !isFriend && !isFunctionTemplateSpecialization &&
9774                !isMemberSpecialization) {
9775       // An out-of-line member function declaration must also be a
9776       // definition (C++ [class.mfct]p2).
9777       // Note that this is not the case for explicit specializations of
9778       // function templates or member functions of class templates, per
9779       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9780       // extension for compatibility with old SWIG code which likes to
9781       // generate them.
9782       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9783         << D.getCXXScopeSpec().getRange();
9784     }
9785   }
9786 
9787   // If this is the first declaration of a library builtin function, add
9788   // attributes as appropriate.
9789   if (!D.isRedeclaration() &&
9790       NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
9791     if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
9792       if (unsigned BuiltinID = II->getBuiltinID()) {
9793         if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
9794           // Validate the type matches unless this builtin is specified as
9795           // matching regardless of its declared type.
9796           if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
9797             NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9798           } else {
9799             ASTContext::GetBuiltinTypeError Error;
9800             LookupNecessaryTypesForBuiltin(S, BuiltinID);
9801             QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
9802 
9803             if (!Error && !BuiltinType.isNull() &&
9804                 Context.hasSameFunctionTypeIgnoringExceptionSpec(
9805                     NewFD->getType(), BuiltinType))
9806               NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9807           }
9808         } else if (BuiltinID == Builtin::BI__GetExceptionInfo &&
9809                    Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9810           // FIXME: We should consider this a builtin only in the std namespace.
9811           NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9812         }
9813       }
9814     }
9815   }
9816 
9817   ProcessPragmaWeak(S, NewFD);
9818   checkAttributesAfterMerging(*this, *NewFD);
9819 
9820   AddKnownFunctionAttributes(NewFD);
9821 
9822   if (NewFD->hasAttr<OverloadableAttr>() &&
9823       !NewFD->getType()->getAs<FunctionProtoType>()) {
9824     Diag(NewFD->getLocation(),
9825          diag::err_attribute_overloadable_no_prototype)
9826       << NewFD;
9827 
9828     // Turn this into a variadic function with no parameters.
9829     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9830     FunctionProtoType::ExtProtoInfo EPI(
9831         Context.getDefaultCallingConvention(true, false));
9832     EPI.Variadic = true;
9833     EPI.ExtInfo = FT->getExtInfo();
9834 
9835     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9836     NewFD->setType(R);
9837   }
9838 
9839   // If there's a #pragma GCC visibility in scope, and this isn't a class
9840   // member, set the visibility of this function.
9841   if (!DC->isRecord() && NewFD->isExternallyVisible())
9842     AddPushedVisibilityAttribute(NewFD);
9843 
9844   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9845   // marking the function.
9846   AddCFAuditedAttribute(NewFD);
9847 
9848   // If this is a function definition, check if we have to apply optnone due to
9849   // a pragma.
9850   if(D.isFunctionDefinition())
9851     AddRangeBasedOptnone(NewFD);
9852 
9853   // If this is the first declaration of an extern C variable, update
9854   // the map of such variables.
9855   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9856       isIncompleteDeclExternC(*this, NewFD))
9857     RegisterLocallyScopedExternCDecl(NewFD, S);
9858 
9859   // Set this FunctionDecl's range up to the right paren.
9860   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9861 
9862   if (D.isRedeclaration() && !Previous.empty()) {
9863     NamedDecl *Prev = Previous.getRepresentativeDecl();
9864     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9865                                    isMemberSpecialization ||
9866                                        isFunctionTemplateSpecialization,
9867                                    D.isFunctionDefinition());
9868   }
9869 
9870   if (getLangOpts().CUDA) {
9871     IdentifierInfo *II = NewFD->getIdentifier();
9872     if (II && II->isStr(getCudaConfigureFuncName()) &&
9873         !NewFD->isInvalidDecl() &&
9874         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9875       if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
9876         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9877             << getCudaConfigureFuncName();
9878       Context.setcudaConfigureCallDecl(NewFD);
9879     }
9880 
9881     // Variadic functions, other than a *declaration* of printf, are not allowed
9882     // in device-side CUDA code, unless someone passed
9883     // -fcuda-allow-variadic-functions.
9884     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9885         (NewFD->hasAttr<CUDADeviceAttr>() ||
9886          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9887         !(II && II->isStr("printf") && NewFD->isExternC() &&
9888           !D.isFunctionDefinition())) {
9889       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9890     }
9891   }
9892 
9893   MarkUnusedFileScopedDecl(NewFD);
9894 
9895 
9896 
9897   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9898     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9899     if ((getLangOpts().OpenCLVersion >= 120)
9900         && (SC == SC_Static)) {
9901       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9902       D.setInvalidType();
9903     }
9904 
9905     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9906     if (!NewFD->getReturnType()->isVoidType()) {
9907       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9908       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9909           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9910                                 : FixItHint());
9911       D.setInvalidType();
9912     }
9913 
9914     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9915     for (auto Param : NewFD->parameters())
9916       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9917 
9918     if (getLangOpts().OpenCLCPlusPlus) {
9919       if (DC->isRecord()) {
9920         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9921         D.setInvalidType();
9922       }
9923       if (FunctionTemplate) {
9924         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9925         D.setInvalidType();
9926       }
9927     }
9928   }
9929 
9930   if (getLangOpts().CPlusPlus) {
9931     if (FunctionTemplate) {
9932       if (NewFD->isInvalidDecl())
9933         FunctionTemplate->setInvalidDecl();
9934       return FunctionTemplate;
9935     }
9936 
9937     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9938       CompleteMemberSpecialization(NewFD, Previous);
9939   }
9940 
9941   for (const ParmVarDecl *Param : NewFD->parameters()) {
9942     QualType PT = Param->getType();
9943 
9944     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9945     // types.
9946     if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
9947       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9948         QualType ElemTy = PipeTy->getElementType();
9949           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9950             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9951             D.setInvalidType();
9952           }
9953       }
9954     }
9955   }
9956 
9957   // Here we have an function template explicit specialization at class scope.
9958   // The actual specialization will be postponed to template instatiation
9959   // time via the ClassScopeFunctionSpecializationDecl node.
9960   if (isDependentClassScopeExplicitSpecialization) {
9961     ClassScopeFunctionSpecializationDecl *NewSpec =
9962                          ClassScopeFunctionSpecializationDecl::Create(
9963                                 Context, CurContext, NewFD->getLocation(),
9964                                 cast<CXXMethodDecl>(NewFD),
9965                                 HasExplicitTemplateArgs, TemplateArgs);
9966     CurContext->addDecl(NewSpec);
9967     AddToScope = false;
9968   }
9969 
9970   // Diagnose availability attributes. Availability cannot be used on functions
9971   // that are run during load/unload.
9972   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9973     if (NewFD->hasAttr<ConstructorAttr>()) {
9974       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9975           << 1;
9976       NewFD->dropAttr<AvailabilityAttr>();
9977     }
9978     if (NewFD->hasAttr<DestructorAttr>()) {
9979       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9980           << 2;
9981       NewFD->dropAttr<AvailabilityAttr>();
9982     }
9983   }
9984 
9985   // Diagnose no_builtin attribute on function declaration that are not a
9986   // definition.
9987   // FIXME: We should really be doing this in
9988   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
9989   // the FunctionDecl and at this point of the code
9990   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
9991   // because Sema::ActOnStartOfFunctionDef has not been called yet.
9992   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
9993     switch (D.getFunctionDefinitionKind()) {
9994     case FunctionDefinitionKind::Defaulted:
9995     case FunctionDefinitionKind::Deleted:
9996       Diag(NBA->getLocation(),
9997            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
9998           << NBA->getSpelling();
9999       break;
10000     case FunctionDefinitionKind::Declaration:
10001       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10002           << NBA->getSpelling();
10003       break;
10004     case FunctionDefinitionKind::Definition:
10005       break;
10006     }
10007 
10008   return NewFD;
10009 }
10010 
10011 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
10012 /// when __declspec(code_seg) "is applied to a class, all member functions of
10013 /// the class and nested classes -- this includes compiler-generated special
10014 /// member functions -- are put in the specified segment."
10015 /// The actual behavior is a little more complicated. The Microsoft compiler
10016 /// won't check outer classes if there is an active value from #pragma code_seg.
10017 /// The CodeSeg is always applied from the direct parent but only from outer
10018 /// classes when the #pragma code_seg stack is empty. See:
10019 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10020 /// available since MS has removed the page.
10021 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
10022   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10023   if (!Method)
10024     return nullptr;
10025   const CXXRecordDecl *Parent = Method->getParent();
10026   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10027     Attr *NewAttr = SAttr->clone(S.getASTContext());
10028     NewAttr->setImplicit(true);
10029     return NewAttr;
10030   }
10031 
10032   // The Microsoft compiler won't check outer classes for the CodeSeg
10033   // when the #pragma code_seg stack is active.
10034   if (S.CodeSegStack.CurrentValue)
10035    return nullptr;
10036 
10037   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10038     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10039       Attr *NewAttr = SAttr->clone(S.getASTContext());
10040       NewAttr->setImplicit(true);
10041       return NewAttr;
10042     }
10043   }
10044   return nullptr;
10045 }
10046 
10047 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10048 /// containing class. Otherwise it will return implicit SectionAttr if the
10049 /// function is a definition and there is an active value on CodeSegStack
10050 /// (from the current #pragma code-seg value).
10051 ///
10052 /// \param FD Function being declared.
10053 /// \param IsDefinition Whether it is a definition or just a declarartion.
10054 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
10055 ///          nullptr if no attribute should be added.
10056 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
10057                                                        bool IsDefinition) {
10058   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10059     return A;
10060   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10061       CodeSegStack.CurrentValue)
10062     return SectionAttr::CreateImplicit(
10063         getASTContext(), CodeSegStack.CurrentValue->getString(),
10064         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
10065         SectionAttr::Declspec_allocate);
10066   return nullptr;
10067 }
10068 
10069 /// Determines if we can perform a correct type check for \p D as a
10070 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
10071 /// best-effort check.
10072 ///
10073 /// \param NewD The new declaration.
10074 /// \param OldD The old declaration.
10075 /// \param NewT The portion of the type of the new declaration to check.
10076 /// \param OldT The portion of the type of the old declaration to check.
10077 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10078                                           QualType NewT, QualType OldT) {
10079   if (!NewD->getLexicalDeclContext()->isDependentContext())
10080     return true;
10081 
10082   // For dependently-typed local extern declarations and friends, we can't
10083   // perform a correct type check in general until instantiation:
10084   //
10085   //   int f();
10086   //   template<typename T> void g() { T f(); }
10087   //
10088   // (valid if g() is only instantiated with T = int).
10089   if (NewT->isDependentType() &&
10090       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10091     return false;
10092 
10093   // Similarly, if the previous declaration was a dependent local extern
10094   // declaration, we don't really know its type yet.
10095   if (OldT->isDependentType() && OldD->isLocalExternDecl())
10096     return false;
10097 
10098   return true;
10099 }
10100 
10101 /// Checks if the new declaration declared in dependent context must be
10102 /// put in the same redeclaration chain as the specified declaration.
10103 ///
10104 /// \param D Declaration that is checked.
10105 /// \param PrevDecl Previous declaration found with proper lookup method for the
10106 ///                 same declaration name.
10107 /// \returns True if D must be added to the redeclaration chain which PrevDecl
10108 ///          belongs to.
10109 ///
10110 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10111   if (!D->getLexicalDeclContext()->isDependentContext())
10112     return true;
10113 
10114   // Don't chain dependent friend function definitions until instantiation, to
10115   // permit cases like
10116   //
10117   //   void func();
10118   //   template<typename T> class C1 { friend void func() {} };
10119   //   template<typename T> class C2 { friend void func() {} };
10120   //
10121   // ... which is valid if only one of C1 and C2 is ever instantiated.
10122   //
10123   // FIXME: This need only apply to function definitions. For now, we proxy
10124   // this by checking for a file-scope function. We do not want this to apply
10125   // to friend declarations nominating member functions, because that gets in
10126   // the way of access checks.
10127   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10128     return false;
10129 
10130   auto *VD = dyn_cast<ValueDecl>(D);
10131   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10132   return !VD || !PrevVD ||
10133          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10134                                         PrevVD->getType());
10135 }
10136 
10137 /// Check the target attribute of the function for MultiVersion
10138 /// validity.
10139 ///
10140 /// Returns true if there was an error, false otherwise.
10141 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10142   const auto *TA = FD->getAttr<TargetAttr>();
10143   assert(TA && "MultiVersion Candidate requires a target attribute");
10144   ParsedTargetAttr ParseInfo = TA->parse();
10145   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10146   enum ErrType { Feature = 0, Architecture = 1 };
10147 
10148   if (!ParseInfo.Architecture.empty() &&
10149       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10150     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10151         << Architecture << ParseInfo.Architecture;
10152     return true;
10153   }
10154 
10155   for (const auto &Feat : ParseInfo.Features) {
10156     auto BareFeat = StringRef{Feat}.substr(1);
10157     if (Feat[0] == '-') {
10158       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10159           << Feature << ("no-" + BareFeat).str();
10160       return true;
10161     }
10162 
10163     if (!TargetInfo.validateCpuSupports(BareFeat) ||
10164         !TargetInfo.isValidFeatureName(BareFeat)) {
10165       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10166           << Feature << BareFeat;
10167       return true;
10168     }
10169   }
10170   return false;
10171 }
10172 
10173 // Provide a white-list of attributes that are allowed to be combined with
10174 // multiversion functions.
10175 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10176                                            MultiVersionKind MVType) {
10177   // Note: this list/diagnosis must match the list in
10178   // checkMultiversionAttributesAllSame.
10179   switch (Kind) {
10180   default:
10181     return false;
10182   case attr::Used:
10183     return MVType == MultiVersionKind::Target;
10184   case attr::NonNull:
10185   case attr::NoThrow:
10186     return true;
10187   }
10188 }
10189 
10190 static bool checkNonMultiVersionCompatAttributes(Sema &S,
10191                                                  const FunctionDecl *FD,
10192                                                  const FunctionDecl *CausedFD,
10193                                                  MultiVersionKind MVType) {
10194   bool IsCPUSpecificCPUDispatchMVType =
10195       MVType == MultiVersionKind::CPUDispatch ||
10196       MVType == MultiVersionKind::CPUSpecific;
10197   const auto Diagnose = [FD, CausedFD, IsCPUSpecificCPUDispatchMVType](
10198                             Sema &S, const Attr *A) {
10199     S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10200         << IsCPUSpecificCPUDispatchMVType << A;
10201     if (CausedFD)
10202       S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10203     return true;
10204   };
10205 
10206   for (const Attr *A : FD->attrs()) {
10207     switch (A->getKind()) {
10208     case attr::CPUDispatch:
10209     case attr::CPUSpecific:
10210       if (MVType != MultiVersionKind::CPUDispatch &&
10211           MVType != MultiVersionKind::CPUSpecific)
10212         return Diagnose(S, A);
10213       break;
10214     case attr::Target:
10215       if (MVType != MultiVersionKind::Target)
10216         return Diagnose(S, A);
10217       break;
10218     default:
10219       if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType))
10220         return Diagnose(S, A);
10221       break;
10222     }
10223   }
10224   return false;
10225 }
10226 
10227 bool Sema::areMultiversionVariantFunctionsCompatible(
10228     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10229     const PartialDiagnostic &NoProtoDiagID,
10230     const PartialDiagnosticAt &NoteCausedDiagIDAt,
10231     const PartialDiagnosticAt &NoSupportDiagIDAt,
10232     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10233     bool ConstexprSupported, bool CLinkageMayDiffer) {
10234   enum DoesntSupport {
10235     FuncTemplates = 0,
10236     VirtFuncs = 1,
10237     DeducedReturn = 2,
10238     Constructors = 3,
10239     Destructors = 4,
10240     DeletedFuncs = 5,
10241     DefaultedFuncs = 6,
10242     ConstexprFuncs = 7,
10243     ConstevalFuncs = 8,
10244   };
10245   enum Different {
10246     CallingConv = 0,
10247     ReturnType = 1,
10248     ConstexprSpec = 2,
10249     InlineSpec = 3,
10250     StorageClass = 4,
10251     Linkage = 5,
10252   };
10253 
10254   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10255       !OldFD->getType()->getAs<FunctionProtoType>()) {
10256     Diag(OldFD->getLocation(), NoProtoDiagID);
10257     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10258     return true;
10259   }
10260 
10261   if (NoProtoDiagID.getDiagID() != 0 &&
10262       !NewFD->getType()->getAs<FunctionProtoType>())
10263     return Diag(NewFD->getLocation(), NoProtoDiagID);
10264 
10265   if (!TemplatesSupported &&
10266       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10267     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10268            << FuncTemplates;
10269 
10270   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10271     if (NewCXXFD->isVirtual())
10272       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10273              << VirtFuncs;
10274 
10275     if (isa<CXXConstructorDecl>(NewCXXFD))
10276       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10277              << Constructors;
10278 
10279     if (isa<CXXDestructorDecl>(NewCXXFD))
10280       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10281              << Destructors;
10282   }
10283 
10284   if (NewFD->isDeleted())
10285     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10286            << DeletedFuncs;
10287 
10288   if (NewFD->isDefaulted())
10289     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10290            << DefaultedFuncs;
10291 
10292   if (!ConstexprSupported && NewFD->isConstexpr())
10293     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10294            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10295 
10296   QualType NewQType = Context.getCanonicalType(NewFD->getType());
10297   const auto *NewType = cast<FunctionType>(NewQType);
10298   QualType NewReturnType = NewType->getReturnType();
10299 
10300   if (NewReturnType->isUndeducedType())
10301     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10302            << DeducedReturn;
10303 
10304   // Ensure the return type is identical.
10305   if (OldFD) {
10306     QualType OldQType = Context.getCanonicalType(OldFD->getType());
10307     const auto *OldType = cast<FunctionType>(OldQType);
10308     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10309     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10310 
10311     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10312       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10313 
10314     QualType OldReturnType = OldType->getReturnType();
10315 
10316     if (OldReturnType != NewReturnType)
10317       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10318 
10319     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10320       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10321 
10322     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10323       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10324 
10325     if (OldFD->getStorageClass() != NewFD->getStorageClass())
10326       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass;
10327 
10328     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10329       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10330 
10331     if (CheckEquivalentExceptionSpec(
10332             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10333             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10334       return true;
10335   }
10336   return false;
10337 }
10338 
10339 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10340                                              const FunctionDecl *NewFD,
10341                                              bool CausesMV,
10342                                              MultiVersionKind MVType) {
10343   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10344     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10345     if (OldFD)
10346       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10347     return true;
10348   }
10349 
10350   bool IsCPUSpecificCPUDispatchMVType =
10351       MVType == MultiVersionKind::CPUDispatch ||
10352       MVType == MultiVersionKind::CPUSpecific;
10353 
10354   if (CausesMV && OldFD &&
10355       checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType))
10356     return true;
10357 
10358   if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType))
10359     return true;
10360 
10361   // Only allow transition to MultiVersion if it hasn't been used.
10362   if (OldFD && CausesMV && OldFD->isUsed(false))
10363     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10364 
10365   return S.areMultiversionVariantFunctionsCompatible(
10366       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10367       PartialDiagnosticAt(NewFD->getLocation(),
10368                           S.PDiag(diag::note_multiversioning_caused_here)),
10369       PartialDiagnosticAt(NewFD->getLocation(),
10370                           S.PDiag(diag::err_multiversion_doesnt_support)
10371                               << IsCPUSpecificCPUDispatchMVType),
10372       PartialDiagnosticAt(NewFD->getLocation(),
10373                           S.PDiag(diag::err_multiversion_diff)),
10374       /*TemplatesSupported=*/false,
10375       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
10376       /*CLinkageMayDiffer=*/false);
10377 }
10378 
10379 /// Check the validity of a multiversion function declaration that is the
10380 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10381 ///
10382 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10383 ///
10384 /// Returns true if there was an error, false otherwise.
10385 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10386                                            MultiVersionKind MVType,
10387                                            const TargetAttr *TA) {
10388   assert(MVType != MultiVersionKind::None &&
10389          "Function lacks multiversion attribute");
10390 
10391   // Target only causes MV if it is default, otherwise this is a normal
10392   // function.
10393   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
10394     return false;
10395 
10396   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10397     FD->setInvalidDecl();
10398     return true;
10399   }
10400 
10401   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
10402     FD->setInvalidDecl();
10403     return true;
10404   }
10405 
10406   FD->setIsMultiVersion();
10407   return false;
10408 }
10409 
10410 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10411   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10412     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10413       return true;
10414   }
10415 
10416   return false;
10417 }
10418 
10419 static bool CheckTargetCausesMultiVersioning(
10420     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10421     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10422     LookupResult &Previous) {
10423   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10424   ParsedTargetAttr NewParsed = NewTA->parse();
10425   // Sort order doesn't matter, it just needs to be consistent.
10426   llvm::sort(NewParsed.Features);
10427 
10428   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10429   // to change, this is a simple redeclaration.
10430   if (!NewTA->isDefaultVersion() &&
10431       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10432     return false;
10433 
10434   // Otherwise, this decl causes MultiVersioning.
10435   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10436     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10437     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10438     NewFD->setInvalidDecl();
10439     return true;
10440   }
10441 
10442   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10443                                        MultiVersionKind::Target)) {
10444     NewFD->setInvalidDecl();
10445     return true;
10446   }
10447 
10448   if (CheckMultiVersionValue(S, NewFD)) {
10449     NewFD->setInvalidDecl();
10450     return true;
10451   }
10452 
10453   // If this is 'default', permit the forward declaration.
10454   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10455     Redeclaration = true;
10456     OldDecl = OldFD;
10457     OldFD->setIsMultiVersion();
10458     NewFD->setIsMultiVersion();
10459     return false;
10460   }
10461 
10462   if (CheckMultiVersionValue(S, OldFD)) {
10463     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10464     NewFD->setInvalidDecl();
10465     return true;
10466   }
10467 
10468   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10469 
10470   if (OldParsed == NewParsed) {
10471     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10472     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10473     NewFD->setInvalidDecl();
10474     return true;
10475   }
10476 
10477   for (const auto *FD : OldFD->redecls()) {
10478     const auto *CurTA = FD->getAttr<TargetAttr>();
10479     // We allow forward declarations before ANY multiversioning attributes, but
10480     // nothing after the fact.
10481     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10482         (!CurTA || CurTA->isInherited())) {
10483       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10484           << 0;
10485       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10486       NewFD->setInvalidDecl();
10487       return true;
10488     }
10489   }
10490 
10491   OldFD->setIsMultiVersion();
10492   NewFD->setIsMultiVersion();
10493   Redeclaration = false;
10494   MergeTypeWithPrevious = false;
10495   OldDecl = nullptr;
10496   Previous.clear();
10497   return false;
10498 }
10499 
10500 /// Check the validity of a new function declaration being added to an existing
10501 /// multiversioned declaration collection.
10502 static bool CheckMultiVersionAdditionalDecl(
10503     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10504     MultiVersionKind NewMVType, const TargetAttr *NewTA,
10505     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10506     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10507     LookupResult &Previous) {
10508 
10509   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10510   // Disallow mixing of multiversioning types.
10511   if ((OldMVType == MultiVersionKind::Target &&
10512        NewMVType != MultiVersionKind::Target) ||
10513       (NewMVType == MultiVersionKind::Target &&
10514        OldMVType != MultiVersionKind::Target)) {
10515     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10516     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10517     NewFD->setInvalidDecl();
10518     return true;
10519   }
10520 
10521   ParsedTargetAttr NewParsed;
10522   if (NewTA) {
10523     NewParsed = NewTA->parse();
10524     llvm::sort(NewParsed.Features);
10525   }
10526 
10527   bool UseMemberUsingDeclRules =
10528       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10529 
10530   // Next, check ALL non-overloads to see if this is a redeclaration of a
10531   // previous member of the MultiVersion set.
10532   for (NamedDecl *ND : Previous) {
10533     FunctionDecl *CurFD = ND->getAsFunction();
10534     if (!CurFD)
10535       continue;
10536     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10537       continue;
10538 
10539     if (NewMVType == MultiVersionKind::Target) {
10540       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10541       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10542         NewFD->setIsMultiVersion();
10543         Redeclaration = true;
10544         OldDecl = ND;
10545         return false;
10546       }
10547 
10548       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10549       if (CurParsed == NewParsed) {
10550         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10551         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10552         NewFD->setInvalidDecl();
10553         return true;
10554       }
10555     } else {
10556       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10557       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10558       // Handle CPUDispatch/CPUSpecific versions.
10559       // Only 1 CPUDispatch function is allowed, this will make it go through
10560       // the redeclaration errors.
10561       if (NewMVType == MultiVersionKind::CPUDispatch &&
10562           CurFD->hasAttr<CPUDispatchAttr>()) {
10563         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10564             std::equal(
10565                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10566                 NewCPUDisp->cpus_begin(),
10567                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10568                   return Cur->getName() == New->getName();
10569                 })) {
10570           NewFD->setIsMultiVersion();
10571           Redeclaration = true;
10572           OldDecl = ND;
10573           return false;
10574         }
10575 
10576         // If the declarations don't match, this is an error condition.
10577         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10578         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10579         NewFD->setInvalidDecl();
10580         return true;
10581       }
10582       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10583 
10584         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10585             std::equal(
10586                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10587                 NewCPUSpec->cpus_begin(),
10588                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10589                   return Cur->getName() == New->getName();
10590                 })) {
10591           NewFD->setIsMultiVersion();
10592           Redeclaration = true;
10593           OldDecl = ND;
10594           return false;
10595         }
10596 
10597         // Only 1 version of CPUSpecific is allowed for each CPU.
10598         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10599           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10600             if (CurII == NewII) {
10601               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10602                   << NewII;
10603               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10604               NewFD->setInvalidDecl();
10605               return true;
10606             }
10607           }
10608         }
10609       }
10610       // If the two decls aren't the same MVType, there is no possible error
10611       // condition.
10612     }
10613   }
10614 
10615   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10616   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10617   // handled in the attribute adding step.
10618   if (NewMVType == MultiVersionKind::Target &&
10619       CheckMultiVersionValue(S, NewFD)) {
10620     NewFD->setInvalidDecl();
10621     return true;
10622   }
10623 
10624   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10625                                        !OldFD->isMultiVersion(), NewMVType)) {
10626     NewFD->setInvalidDecl();
10627     return true;
10628   }
10629 
10630   // Permit forward declarations in the case where these two are compatible.
10631   if (!OldFD->isMultiVersion()) {
10632     OldFD->setIsMultiVersion();
10633     NewFD->setIsMultiVersion();
10634     Redeclaration = true;
10635     OldDecl = OldFD;
10636     return false;
10637   }
10638 
10639   NewFD->setIsMultiVersion();
10640   Redeclaration = false;
10641   MergeTypeWithPrevious = false;
10642   OldDecl = nullptr;
10643   Previous.clear();
10644   return false;
10645 }
10646 
10647 
10648 /// Check the validity of a mulitversion function declaration.
10649 /// Also sets the multiversion'ness' of the function itself.
10650 ///
10651 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10652 ///
10653 /// Returns true if there was an error, false otherwise.
10654 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10655                                       bool &Redeclaration, NamedDecl *&OldDecl,
10656                                       bool &MergeTypeWithPrevious,
10657                                       LookupResult &Previous) {
10658   const auto *NewTA = NewFD->getAttr<TargetAttr>();
10659   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10660   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10661 
10662   // Mixing Multiversioning types is prohibited.
10663   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
10664       (NewCPUDisp && NewCPUSpec)) {
10665     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10666     NewFD->setInvalidDecl();
10667     return true;
10668   }
10669 
10670   MultiVersionKind  MVType = NewFD->getMultiVersionKind();
10671 
10672   // Main isn't allowed to become a multiversion function, however it IS
10673   // permitted to have 'main' be marked with the 'target' optimization hint.
10674   if (NewFD->isMain()) {
10675     if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10676         MVType == MultiVersionKind::CPUDispatch ||
10677         MVType == MultiVersionKind::CPUSpecific) {
10678       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10679       NewFD->setInvalidDecl();
10680       return true;
10681     }
10682     return false;
10683   }
10684 
10685   if (!OldDecl || !OldDecl->getAsFunction() ||
10686       OldDecl->getDeclContext()->getRedeclContext() !=
10687           NewFD->getDeclContext()->getRedeclContext()) {
10688     // If there's no previous declaration, AND this isn't attempting to cause
10689     // multiversioning, this isn't an error condition.
10690     if (MVType == MultiVersionKind::None)
10691       return false;
10692     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10693   }
10694 
10695   FunctionDecl *OldFD = OldDecl->getAsFunction();
10696 
10697   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10698     return false;
10699 
10700   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10701     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10702         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10703     NewFD->setInvalidDecl();
10704     return true;
10705   }
10706 
10707   // Handle the target potentially causes multiversioning case.
10708   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10709     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10710                                             Redeclaration, OldDecl,
10711                                             MergeTypeWithPrevious, Previous);
10712 
10713   // At this point, we have a multiversion function decl (in OldFD) AND an
10714   // appropriate attribute in the current function decl.  Resolve that these are
10715   // still compatible with previous declarations.
10716   return CheckMultiVersionAdditionalDecl(
10717       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10718       OldDecl, MergeTypeWithPrevious, Previous);
10719 }
10720 
10721 /// Perform semantic checking of a new function declaration.
10722 ///
10723 /// Performs semantic analysis of the new function declaration
10724 /// NewFD. This routine performs all semantic checking that does not
10725 /// require the actual declarator involved in the declaration, and is
10726 /// used both for the declaration of functions as they are parsed
10727 /// (called via ActOnDeclarator) and for the declaration of functions
10728 /// that have been instantiated via C++ template instantiation (called
10729 /// via InstantiateDecl).
10730 ///
10731 /// \param IsMemberSpecialization whether this new function declaration is
10732 /// a member specialization (that replaces any definition provided by the
10733 /// previous declaration).
10734 ///
10735 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10736 ///
10737 /// \returns true if the function declaration is a redeclaration.
10738 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10739                                     LookupResult &Previous,
10740                                     bool IsMemberSpecialization) {
10741   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10742          "Variably modified return types are not handled here");
10743 
10744   // Determine whether the type of this function should be merged with
10745   // a previous visible declaration. This never happens for functions in C++,
10746   // and always happens in C if the previous declaration was visible.
10747   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10748                                !Previous.isShadowed();
10749 
10750   bool Redeclaration = false;
10751   NamedDecl *OldDecl = nullptr;
10752   bool MayNeedOverloadableChecks = false;
10753 
10754   // Merge or overload the declaration with an existing declaration of
10755   // the same name, if appropriate.
10756   if (!Previous.empty()) {
10757     // Determine whether NewFD is an overload of PrevDecl or
10758     // a declaration that requires merging. If it's an overload,
10759     // there's no more work to do here; we'll just add the new
10760     // function to the scope.
10761     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10762       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10763       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10764         Redeclaration = true;
10765         OldDecl = Candidate;
10766       }
10767     } else {
10768       MayNeedOverloadableChecks = true;
10769       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10770                             /*NewIsUsingDecl*/ false)) {
10771       case Ovl_Match:
10772         Redeclaration = true;
10773         break;
10774 
10775       case Ovl_NonFunction:
10776         Redeclaration = true;
10777         break;
10778 
10779       case Ovl_Overload:
10780         Redeclaration = false;
10781         break;
10782       }
10783     }
10784   }
10785 
10786   // Check for a previous extern "C" declaration with this name.
10787   if (!Redeclaration &&
10788       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10789     if (!Previous.empty()) {
10790       // This is an extern "C" declaration with the same name as a previous
10791       // declaration, and thus redeclares that entity...
10792       Redeclaration = true;
10793       OldDecl = Previous.getFoundDecl();
10794       MergeTypeWithPrevious = false;
10795 
10796       // ... except in the presence of __attribute__((overloadable)).
10797       if (OldDecl->hasAttr<OverloadableAttr>() ||
10798           NewFD->hasAttr<OverloadableAttr>()) {
10799         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10800           MayNeedOverloadableChecks = true;
10801           Redeclaration = false;
10802           OldDecl = nullptr;
10803         }
10804       }
10805     }
10806   }
10807 
10808   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10809                                 MergeTypeWithPrevious, Previous))
10810     return Redeclaration;
10811 
10812   // PPC MMA non-pointer types are not allowed as function return types.
10813   if (Context.getTargetInfo().getTriple().isPPC64() &&
10814       CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
10815     NewFD->setInvalidDecl();
10816   }
10817 
10818   // C++11 [dcl.constexpr]p8:
10819   //   A constexpr specifier for a non-static member function that is not
10820   //   a constructor declares that member function to be const.
10821   //
10822   // This needs to be delayed until we know whether this is an out-of-line
10823   // definition of a static member function.
10824   //
10825   // This rule is not present in C++1y, so we produce a backwards
10826   // compatibility warning whenever it happens in C++11.
10827   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10828   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10829       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10830       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10831     CXXMethodDecl *OldMD = nullptr;
10832     if (OldDecl)
10833       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10834     if (!OldMD || !OldMD->isStatic()) {
10835       const FunctionProtoType *FPT =
10836         MD->getType()->castAs<FunctionProtoType>();
10837       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10838       EPI.TypeQuals.addConst();
10839       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10840                                           FPT->getParamTypes(), EPI));
10841 
10842       // Warn that we did this, if we're not performing template instantiation.
10843       // In that case, we'll have warned already when the template was defined.
10844       if (!inTemplateInstantiation()) {
10845         SourceLocation AddConstLoc;
10846         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10847                 .IgnoreParens().getAs<FunctionTypeLoc>())
10848           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10849 
10850         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10851           << FixItHint::CreateInsertion(AddConstLoc, " const");
10852       }
10853     }
10854   }
10855 
10856   if (Redeclaration) {
10857     // NewFD and OldDecl represent declarations that need to be
10858     // merged.
10859     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10860       NewFD->setInvalidDecl();
10861       return Redeclaration;
10862     }
10863 
10864     Previous.clear();
10865     Previous.addDecl(OldDecl);
10866 
10867     if (FunctionTemplateDecl *OldTemplateDecl =
10868             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10869       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10870       FunctionTemplateDecl *NewTemplateDecl
10871         = NewFD->getDescribedFunctionTemplate();
10872       assert(NewTemplateDecl && "Template/non-template mismatch");
10873 
10874       // The call to MergeFunctionDecl above may have created some state in
10875       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10876       // can add it as a redeclaration.
10877       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10878 
10879       NewFD->setPreviousDeclaration(OldFD);
10880       if (NewFD->isCXXClassMember()) {
10881         NewFD->setAccess(OldTemplateDecl->getAccess());
10882         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10883       }
10884 
10885       // If this is an explicit specialization of a member that is a function
10886       // template, mark it as a member specialization.
10887       if (IsMemberSpecialization &&
10888           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10889         NewTemplateDecl->setMemberSpecialization();
10890         assert(OldTemplateDecl->isMemberSpecialization());
10891         // Explicit specializations of a member template do not inherit deleted
10892         // status from the parent member template that they are specializing.
10893         if (OldFD->isDeleted()) {
10894           // FIXME: This assert will not hold in the presence of modules.
10895           assert(OldFD->getCanonicalDecl() == OldFD);
10896           // FIXME: We need an update record for this AST mutation.
10897           OldFD->setDeletedAsWritten(false);
10898         }
10899       }
10900 
10901     } else {
10902       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10903         auto *OldFD = cast<FunctionDecl>(OldDecl);
10904         // This needs to happen first so that 'inline' propagates.
10905         NewFD->setPreviousDeclaration(OldFD);
10906         if (NewFD->isCXXClassMember())
10907           NewFD->setAccess(OldFD->getAccess());
10908       }
10909     }
10910   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10911              !NewFD->getAttr<OverloadableAttr>()) {
10912     assert((Previous.empty() ||
10913             llvm::any_of(Previous,
10914                          [](const NamedDecl *ND) {
10915                            return ND->hasAttr<OverloadableAttr>();
10916                          })) &&
10917            "Non-redecls shouldn't happen without overloadable present");
10918 
10919     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10920       const auto *FD = dyn_cast<FunctionDecl>(ND);
10921       return FD && !FD->hasAttr<OverloadableAttr>();
10922     });
10923 
10924     if (OtherUnmarkedIter != Previous.end()) {
10925       Diag(NewFD->getLocation(),
10926            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10927       Diag((*OtherUnmarkedIter)->getLocation(),
10928            diag::note_attribute_overloadable_prev_overload)
10929           << false;
10930 
10931       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10932     }
10933   }
10934 
10935   if (LangOpts.OpenMP)
10936     ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
10937 
10938   // Semantic checking for this function declaration (in isolation).
10939 
10940   if (getLangOpts().CPlusPlus) {
10941     // C++-specific checks.
10942     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10943       CheckConstructor(Constructor);
10944     } else if (CXXDestructorDecl *Destructor =
10945                 dyn_cast<CXXDestructorDecl>(NewFD)) {
10946       CXXRecordDecl *Record = Destructor->getParent();
10947       QualType ClassType = Context.getTypeDeclType(Record);
10948 
10949       // FIXME: Shouldn't we be able to perform this check even when the class
10950       // type is dependent? Both gcc and edg can handle that.
10951       if (!ClassType->isDependentType()) {
10952         DeclarationName Name
10953           = Context.DeclarationNames.getCXXDestructorName(
10954                                         Context.getCanonicalType(ClassType));
10955         if (NewFD->getDeclName() != Name) {
10956           Diag(NewFD->getLocation(), diag::err_destructor_name);
10957           NewFD->setInvalidDecl();
10958           return Redeclaration;
10959         }
10960       }
10961     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10962       if (auto *TD = Guide->getDescribedFunctionTemplate())
10963         CheckDeductionGuideTemplate(TD);
10964 
10965       // A deduction guide is not on the list of entities that can be
10966       // explicitly specialized.
10967       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10968         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10969             << /*explicit specialization*/ 1;
10970     }
10971 
10972     // Find any virtual functions that this function overrides.
10973     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10974       if (!Method->isFunctionTemplateSpecialization() &&
10975           !Method->getDescribedFunctionTemplate() &&
10976           Method->isCanonicalDecl()) {
10977         AddOverriddenMethods(Method->getParent(), Method);
10978       }
10979       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
10980         // C++2a [class.virtual]p6
10981         // A virtual method shall not have a requires-clause.
10982         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
10983              diag::err_constrained_virtual_method);
10984 
10985       if (Method->isStatic())
10986         checkThisInStaticMemberFunctionType(Method);
10987     }
10988 
10989     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
10990       ActOnConversionDeclarator(Conversion);
10991 
10992     // Extra checking for C++ overloaded operators (C++ [over.oper]).
10993     if (NewFD->isOverloadedOperator() &&
10994         CheckOverloadedOperatorDeclaration(NewFD)) {
10995       NewFD->setInvalidDecl();
10996       return Redeclaration;
10997     }
10998 
10999     // Extra checking for C++0x literal operators (C++0x [over.literal]).
11000     if (NewFD->getLiteralIdentifier() &&
11001         CheckLiteralOperatorDeclaration(NewFD)) {
11002       NewFD->setInvalidDecl();
11003       return Redeclaration;
11004     }
11005 
11006     // In C++, check default arguments now that we have merged decls. Unless
11007     // the lexical context is the class, because in this case this is done
11008     // during delayed parsing anyway.
11009     if (!CurContext->isRecord())
11010       CheckCXXDefaultArguments(NewFD);
11011 
11012     // If this function is declared as being extern "C", then check to see if
11013     // the function returns a UDT (class, struct, or union type) that is not C
11014     // compatible, and if it does, warn the user.
11015     // But, issue any diagnostic on the first declaration only.
11016     if (Previous.empty() && NewFD->isExternC()) {
11017       QualType R = NewFD->getReturnType();
11018       if (R->isIncompleteType() && !R->isVoidType())
11019         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
11020             << NewFD << R;
11021       else if (!R.isPODType(Context) && !R->isVoidType() &&
11022                !R->isObjCObjectPointerType())
11023         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
11024     }
11025 
11026     // C++1z [dcl.fct]p6:
11027     //   [...] whether the function has a non-throwing exception-specification
11028     //   [is] part of the function type
11029     //
11030     // This results in an ABI break between C++14 and C++17 for functions whose
11031     // declared type includes an exception-specification in a parameter or
11032     // return type. (Exception specifications on the function itself are OK in
11033     // most cases, and exception specifications are not permitted in most other
11034     // contexts where they could make it into a mangling.)
11035     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
11036       auto HasNoexcept = [&](QualType T) -> bool {
11037         // Strip off declarator chunks that could be between us and a function
11038         // type. We don't need to look far, exception specifications are very
11039         // restricted prior to C++17.
11040         if (auto *RT = T->getAs<ReferenceType>())
11041           T = RT->getPointeeType();
11042         else if (T->isAnyPointerType())
11043           T = T->getPointeeType();
11044         else if (auto *MPT = T->getAs<MemberPointerType>())
11045           T = MPT->getPointeeType();
11046         if (auto *FPT = T->getAs<FunctionProtoType>())
11047           if (FPT->isNothrow())
11048             return true;
11049         return false;
11050       };
11051 
11052       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
11053       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
11054       for (QualType T : FPT->param_types())
11055         AnyNoexcept |= HasNoexcept(T);
11056       if (AnyNoexcept)
11057         Diag(NewFD->getLocation(),
11058              diag::warn_cxx17_compat_exception_spec_in_signature)
11059             << NewFD;
11060     }
11061 
11062     if (!Redeclaration && LangOpts.CUDA)
11063       checkCUDATargetOverload(NewFD, Previous);
11064   }
11065   return Redeclaration;
11066 }
11067 
11068 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
11069   // C++11 [basic.start.main]p3:
11070   //   A program that [...] declares main to be inline, static or
11071   //   constexpr is ill-formed.
11072   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
11073   //   appear in a declaration of main.
11074   // static main is not an error under C99, but we should warn about it.
11075   // We accept _Noreturn main as an extension.
11076   if (FD->getStorageClass() == SC_Static)
11077     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
11078          ? diag::err_static_main : diag::warn_static_main)
11079       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
11080   if (FD->isInlineSpecified())
11081     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
11082       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
11083   if (DS.isNoreturnSpecified()) {
11084     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
11085     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
11086     Diag(NoreturnLoc, diag::ext_noreturn_main);
11087     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
11088       << FixItHint::CreateRemoval(NoreturnRange);
11089   }
11090   if (FD->isConstexpr()) {
11091     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
11092         << FD->isConsteval()
11093         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
11094     FD->setConstexprKind(ConstexprSpecKind::Unspecified);
11095   }
11096 
11097   if (getLangOpts().OpenCL) {
11098     Diag(FD->getLocation(), diag::err_opencl_no_main)
11099         << FD->hasAttr<OpenCLKernelAttr>();
11100     FD->setInvalidDecl();
11101     return;
11102   }
11103 
11104   QualType T = FD->getType();
11105   assert(T->isFunctionType() && "function decl is not of function type");
11106   const FunctionType* FT = T->castAs<FunctionType>();
11107 
11108   // Set default calling convention for main()
11109   if (FT->getCallConv() != CC_C) {
11110     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
11111     FD->setType(QualType(FT, 0));
11112     T = Context.getCanonicalType(FD->getType());
11113   }
11114 
11115   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
11116     // In C with GNU extensions we allow main() to have non-integer return
11117     // type, but we should warn about the extension, and we disable the
11118     // implicit-return-zero rule.
11119 
11120     // GCC in C mode accepts qualified 'int'.
11121     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
11122       FD->setHasImplicitReturnZero(true);
11123     else {
11124       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
11125       SourceRange RTRange = FD->getReturnTypeSourceRange();
11126       if (RTRange.isValid())
11127         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
11128             << FixItHint::CreateReplacement(RTRange, "int");
11129     }
11130   } else {
11131     // In C and C++, main magically returns 0 if you fall off the end;
11132     // set the flag which tells us that.
11133     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11134 
11135     // All the standards say that main() should return 'int'.
11136     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
11137       FD->setHasImplicitReturnZero(true);
11138     else {
11139       // Otherwise, this is just a flat-out error.
11140       SourceRange RTRange = FD->getReturnTypeSourceRange();
11141       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11142           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11143                                 : FixItHint());
11144       FD->setInvalidDecl(true);
11145     }
11146   }
11147 
11148   // Treat protoless main() as nullary.
11149   if (isa<FunctionNoProtoType>(FT)) return;
11150 
11151   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11152   unsigned nparams = FTP->getNumParams();
11153   assert(FD->getNumParams() == nparams);
11154 
11155   bool HasExtraParameters = (nparams > 3);
11156 
11157   if (FTP->isVariadic()) {
11158     Diag(FD->getLocation(), diag::ext_variadic_main);
11159     // FIXME: if we had information about the location of the ellipsis, we
11160     // could add a FixIt hint to remove it as a parameter.
11161   }
11162 
11163   // Darwin passes an undocumented fourth argument of type char**.  If
11164   // other platforms start sprouting these, the logic below will start
11165   // getting shifty.
11166   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11167     HasExtraParameters = false;
11168 
11169   if (HasExtraParameters) {
11170     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11171     FD->setInvalidDecl(true);
11172     nparams = 3;
11173   }
11174 
11175   // FIXME: a lot of the following diagnostics would be improved
11176   // if we had some location information about types.
11177 
11178   QualType CharPP =
11179     Context.getPointerType(Context.getPointerType(Context.CharTy));
11180   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11181 
11182   for (unsigned i = 0; i < nparams; ++i) {
11183     QualType AT = FTP->getParamType(i);
11184 
11185     bool mismatch = true;
11186 
11187     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11188       mismatch = false;
11189     else if (Expected[i] == CharPP) {
11190       // As an extension, the following forms are okay:
11191       //   char const **
11192       //   char const * const *
11193       //   char * const *
11194 
11195       QualifierCollector qs;
11196       const PointerType* PT;
11197       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11198           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11199           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11200                               Context.CharTy)) {
11201         qs.removeConst();
11202         mismatch = !qs.empty();
11203       }
11204     }
11205 
11206     if (mismatch) {
11207       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11208       // TODO: suggest replacing given type with expected type
11209       FD->setInvalidDecl(true);
11210     }
11211   }
11212 
11213   if (nparams == 1 && !FD->isInvalidDecl()) {
11214     Diag(FD->getLocation(), diag::warn_main_one_arg);
11215   }
11216 
11217   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11218     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11219     FD->setInvalidDecl();
11220   }
11221 }
11222 
11223 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
11224 
11225   // Default calling convention for main and wmain is __cdecl
11226   if (FD->getName() == "main" || FD->getName() == "wmain")
11227     return false;
11228 
11229   // Default calling convention for MinGW is __cdecl
11230   const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
11231   if (T.isWindowsGNUEnvironment())
11232     return false;
11233 
11234   // Default calling convention for WinMain, wWinMain and DllMain
11235   // is __stdcall on 32 bit Windows
11236   if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
11237     return true;
11238 
11239   return false;
11240 }
11241 
11242 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11243   QualType T = FD->getType();
11244   assert(T->isFunctionType() && "function decl is not of function type");
11245   const FunctionType *FT = T->castAs<FunctionType>();
11246 
11247   // Set an implicit return of 'zero' if the function can return some integral,
11248   // enumeration, pointer or nullptr type.
11249   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11250       FT->getReturnType()->isAnyPointerType() ||
11251       FT->getReturnType()->isNullPtrType())
11252     // DllMain is exempt because a return value of zero means it failed.
11253     if (FD->getName() != "DllMain")
11254       FD->setHasImplicitReturnZero(true);
11255 
11256   // Explicity specified calling conventions are applied to MSVC entry points
11257   if (!hasExplicitCallingConv(T)) {
11258     if (isDefaultStdCall(FD, *this)) {
11259       if (FT->getCallConv() != CC_X86StdCall) {
11260         FT = Context.adjustFunctionType(
11261             FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
11262         FD->setType(QualType(FT, 0));
11263       }
11264     } else if (FT->getCallConv() != CC_C) {
11265       FT = Context.adjustFunctionType(FT,
11266                                       FT->getExtInfo().withCallingConv(CC_C));
11267       FD->setType(QualType(FT, 0));
11268     }
11269   }
11270 
11271   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11272     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11273     FD->setInvalidDecl();
11274   }
11275 }
11276 
11277 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11278   // FIXME: Need strict checking.  In C89, we need to check for
11279   // any assignment, increment, decrement, function-calls, or
11280   // commas outside of a sizeof.  In C99, it's the same list,
11281   // except that the aforementioned are allowed in unevaluated
11282   // expressions.  Everything else falls under the
11283   // "may accept other forms of constant expressions" exception.
11284   //
11285   // Regular C++ code will not end up here (exceptions: language extensions,
11286   // OpenCL C++ etc), so the constant expression rules there don't matter.
11287   if (Init->isValueDependent()) {
11288     assert(Init->containsErrors() &&
11289            "Dependent code should only occur in error-recovery path.");
11290     return true;
11291   }
11292   const Expr *Culprit;
11293   if (Init->isConstantInitializer(Context, false, &Culprit))
11294     return false;
11295   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11296     << Culprit->getSourceRange();
11297   return true;
11298 }
11299 
11300 namespace {
11301   // Visits an initialization expression to see if OrigDecl is evaluated in
11302   // its own initialization and throws a warning if it does.
11303   class SelfReferenceChecker
11304       : public EvaluatedExprVisitor<SelfReferenceChecker> {
11305     Sema &S;
11306     Decl *OrigDecl;
11307     bool isRecordType;
11308     bool isPODType;
11309     bool isReferenceType;
11310 
11311     bool isInitList;
11312     llvm::SmallVector<unsigned, 4> InitFieldIndex;
11313 
11314   public:
11315     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11316 
11317     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11318                                                     S(S), OrigDecl(OrigDecl) {
11319       isPODType = false;
11320       isRecordType = false;
11321       isReferenceType = false;
11322       isInitList = false;
11323       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11324         isPODType = VD->getType().isPODType(S.Context);
11325         isRecordType = VD->getType()->isRecordType();
11326         isReferenceType = VD->getType()->isReferenceType();
11327       }
11328     }
11329 
11330     // For most expressions, just call the visitor.  For initializer lists,
11331     // track the index of the field being initialized since fields are
11332     // initialized in order allowing use of previously initialized fields.
11333     void CheckExpr(Expr *E) {
11334       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11335       if (!InitList) {
11336         Visit(E);
11337         return;
11338       }
11339 
11340       // Track and increment the index here.
11341       isInitList = true;
11342       InitFieldIndex.push_back(0);
11343       for (auto Child : InitList->children()) {
11344         CheckExpr(cast<Expr>(Child));
11345         ++InitFieldIndex.back();
11346       }
11347       InitFieldIndex.pop_back();
11348     }
11349 
11350     // Returns true if MemberExpr is checked and no further checking is needed.
11351     // Returns false if additional checking is required.
11352     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11353       llvm::SmallVector<FieldDecl*, 4> Fields;
11354       Expr *Base = E;
11355       bool ReferenceField = false;
11356 
11357       // Get the field members used.
11358       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11359         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11360         if (!FD)
11361           return false;
11362         Fields.push_back(FD);
11363         if (FD->getType()->isReferenceType())
11364           ReferenceField = true;
11365         Base = ME->getBase()->IgnoreParenImpCasts();
11366       }
11367 
11368       // Keep checking only if the base Decl is the same.
11369       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11370       if (!DRE || DRE->getDecl() != OrigDecl)
11371         return false;
11372 
11373       // A reference field can be bound to an unininitialized field.
11374       if (CheckReference && !ReferenceField)
11375         return true;
11376 
11377       // Convert FieldDecls to their index number.
11378       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11379       for (const FieldDecl *I : llvm::reverse(Fields))
11380         UsedFieldIndex.push_back(I->getFieldIndex());
11381 
11382       // See if a warning is needed by checking the first difference in index
11383       // numbers.  If field being used has index less than the field being
11384       // initialized, then the use is safe.
11385       for (auto UsedIter = UsedFieldIndex.begin(),
11386                 UsedEnd = UsedFieldIndex.end(),
11387                 OrigIter = InitFieldIndex.begin(),
11388                 OrigEnd = InitFieldIndex.end();
11389            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11390         if (*UsedIter < *OrigIter)
11391           return true;
11392         if (*UsedIter > *OrigIter)
11393           break;
11394       }
11395 
11396       // TODO: Add a different warning which will print the field names.
11397       HandleDeclRefExpr(DRE);
11398       return true;
11399     }
11400 
11401     // For most expressions, the cast is directly above the DeclRefExpr.
11402     // For conditional operators, the cast can be outside the conditional
11403     // operator if both expressions are DeclRefExpr's.
11404     void HandleValue(Expr *E) {
11405       E = E->IgnoreParens();
11406       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11407         HandleDeclRefExpr(DRE);
11408         return;
11409       }
11410 
11411       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11412         Visit(CO->getCond());
11413         HandleValue(CO->getTrueExpr());
11414         HandleValue(CO->getFalseExpr());
11415         return;
11416       }
11417 
11418       if (BinaryConditionalOperator *BCO =
11419               dyn_cast<BinaryConditionalOperator>(E)) {
11420         Visit(BCO->getCond());
11421         HandleValue(BCO->getFalseExpr());
11422         return;
11423       }
11424 
11425       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11426         HandleValue(OVE->getSourceExpr());
11427         return;
11428       }
11429 
11430       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11431         if (BO->getOpcode() == BO_Comma) {
11432           Visit(BO->getLHS());
11433           HandleValue(BO->getRHS());
11434           return;
11435         }
11436       }
11437 
11438       if (isa<MemberExpr>(E)) {
11439         if (isInitList) {
11440           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11441                                       false /*CheckReference*/))
11442             return;
11443         }
11444 
11445         Expr *Base = E->IgnoreParenImpCasts();
11446         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11447           // Check for static member variables and don't warn on them.
11448           if (!isa<FieldDecl>(ME->getMemberDecl()))
11449             return;
11450           Base = ME->getBase()->IgnoreParenImpCasts();
11451         }
11452         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11453           HandleDeclRefExpr(DRE);
11454         return;
11455       }
11456 
11457       Visit(E);
11458     }
11459 
11460     // Reference types not handled in HandleValue are handled here since all
11461     // uses of references are bad, not just r-value uses.
11462     void VisitDeclRefExpr(DeclRefExpr *E) {
11463       if (isReferenceType)
11464         HandleDeclRefExpr(E);
11465     }
11466 
11467     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11468       if (E->getCastKind() == CK_LValueToRValue) {
11469         HandleValue(E->getSubExpr());
11470         return;
11471       }
11472 
11473       Inherited::VisitImplicitCastExpr(E);
11474     }
11475 
11476     void VisitMemberExpr(MemberExpr *E) {
11477       if (isInitList) {
11478         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11479           return;
11480       }
11481 
11482       // Don't warn on arrays since they can be treated as pointers.
11483       if (E->getType()->canDecayToPointerType()) return;
11484 
11485       // Warn when a non-static method call is followed by non-static member
11486       // field accesses, which is followed by a DeclRefExpr.
11487       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11488       bool Warn = (MD && !MD->isStatic());
11489       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11490       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11491         if (!isa<FieldDecl>(ME->getMemberDecl()))
11492           Warn = false;
11493         Base = ME->getBase()->IgnoreParenImpCasts();
11494       }
11495 
11496       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11497         if (Warn)
11498           HandleDeclRefExpr(DRE);
11499         return;
11500       }
11501 
11502       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11503       // Visit that expression.
11504       Visit(Base);
11505     }
11506 
11507     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11508       Expr *Callee = E->getCallee();
11509 
11510       if (isa<UnresolvedLookupExpr>(Callee))
11511         return Inherited::VisitCXXOperatorCallExpr(E);
11512 
11513       Visit(Callee);
11514       for (auto Arg: E->arguments())
11515         HandleValue(Arg->IgnoreParenImpCasts());
11516     }
11517 
11518     void VisitUnaryOperator(UnaryOperator *E) {
11519       // For POD record types, addresses of its own members are well-defined.
11520       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11521           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11522         if (!isPODType)
11523           HandleValue(E->getSubExpr());
11524         return;
11525       }
11526 
11527       if (E->isIncrementDecrementOp()) {
11528         HandleValue(E->getSubExpr());
11529         return;
11530       }
11531 
11532       Inherited::VisitUnaryOperator(E);
11533     }
11534 
11535     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11536 
11537     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11538       if (E->getConstructor()->isCopyConstructor()) {
11539         Expr *ArgExpr = E->getArg(0);
11540         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11541           if (ILE->getNumInits() == 1)
11542             ArgExpr = ILE->getInit(0);
11543         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11544           if (ICE->getCastKind() == CK_NoOp)
11545             ArgExpr = ICE->getSubExpr();
11546         HandleValue(ArgExpr);
11547         return;
11548       }
11549       Inherited::VisitCXXConstructExpr(E);
11550     }
11551 
11552     void VisitCallExpr(CallExpr *E) {
11553       // Treat std::move as a use.
11554       if (E->isCallToStdMove()) {
11555         HandleValue(E->getArg(0));
11556         return;
11557       }
11558 
11559       Inherited::VisitCallExpr(E);
11560     }
11561 
11562     void VisitBinaryOperator(BinaryOperator *E) {
11563       if (E->isCompoundAssignmentOp()) {
11564         HandleValue(E->getLHS());
11565         Visit(E->getRHS());
11566         return;
11567       }
11568 
11569       Inherited::VisitBinaryOperator(E);
11570     }
11571 
11572     // A custom visitor for BinaryConditionalOperator is needed because the
11573     // regular visitor would check the condition and true expression separately
11574     // but both point to the same place giving duplicate diagnostics.
11575     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11576       Visit(E->getCond());
11577       Visit(E->getFalseExpr());
11578     }
11579 
11580     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11581       Decl* ReferenceDecl = DRE->getDecl();
11582       if (OrigDecl != ReferenceDecl) return;
11583       unsigned diag;
11584       if (isReferenceType) {
11585         diag = diag::warn_uninit_self_reference_in_reference_init;
11586       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11587         diag = diag::warn_static_self_reference_in_init;
11588       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11589                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11590                  DRE->getDecl()->getType()->isRecordType()) {
11591         diag = diag::warn_uninit_self_reference_in_init;
11592       } else {
11593         // Local variables will be handled by the CFG analysis.
11594         return;
11595       }
11596 
11597       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11598                             S.PDiag(diag)
11599                                 << DRE->getDecl() << OrigDecl->getLocation()
11600                                 << DRE->getSourceRange());
11601     }
11602   };
11603 
11604   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11605   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11606                                  bool DirectInit) {
11607     // Parameters arguments are occassionially constructed with itself,
11608     // for instance, in recursive functions.  Skip them.
11609     if (isa<ParmVarDecl>(OrigDecl))
11610       return;
11611 
11612     E = E->IgnoreParens();
11613 
11614     // Skip checking T a = a where T is not a record or reference type.
11615     // Doing so is a way to silence uninitialized warnings.
11616     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11617       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11618         if (ICE->getCastKind() == CK_LValueToRValue)
11619           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11620             if (DRE->getDecl() == OrigDecl)
11621               return;
11622 
11623     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11624   }
11625 } // end anonymous namespace
11626 
11627 namespace {
11628   // Simple wrapper to add the name of a variable or (if no variable is
11629   // available) a DeclarationName into a diagnostic.
11630   struct VarDeclOrName {
11631     VarDecl *VDecl;
11632     DeclarationName Name;
11633 
11634     friend const Sema::SemaDiagnosticBuilder &
11635     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11636       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11637     }
11638   };
11639 } // end anonymous namespace
11640 
11641 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11642                                             DeclarationName Name, QualType Type,
11643                                             TypeSourceInfo *TSI,
11644                                             SourceRange Range, bool DirectInit,
11645                                             Expr *Init) {
11646   bool IsInitCapture = !VDecl;
11647   assert((!VDecl || !VDecl->isInitCapture()) &&
11648          "init captures are expected to be deduced prior to initialization");
11649 
11650   VarDeclOrName VN{VDecl, Name};
11651 
11652   DeducedType *Deduced = Type->getContainedDeducedType();
11653   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11654 
11655   // C++11 [dcl.spec.auto]p3
11656   if (!Init) {
11657     assert(VDecl && "no init for init capture deduction?");
11658 
11659     // Except for class argument deduction, and then for an initializing
11660     // declaration only, i.e. no static at class scope or extern.
11661     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11662         VDecl->hasExternalStorage() ||
11663         VDecl->isStaticDataMember()) {
11664       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11665         << VDecl->getDeclName() << Type;
11666       return QualType();
11667     }
11668   }
11669 
11670   ArrayRef<Expr*> DeduceInits;
11671   if (Init)
11672     DeduceInits = Init;
11673 
11674   if (DirectInit) {
11675     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11676       DeduceInits = PL->exprs();
11677   }
11678 
11679   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11680     assert(VDecl && "non-auto type for init capture deduction?");
11681     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11682     InitializationKind Kind = InitializationKind::CreateForInit(
11683         VDecl->getLocation(), DirectInit, Init);
11684     // FIXME: Initialization should not be taking a mutable list of inits.
11685     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11686     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11687                                                        InitsCopy);
11688   }
11689 
11690   if (DirectInit) {
11691     if (auto *IL = dyn_cast<InitListExpr>(Init))
11692       DeduceInits = IL->inits();
11693   }
11694 
11695   // Deduction only works if we have exactly one source expression.
11696   if (DeduceInits.empty()) {
11697     // It isn't possible to write this directly, but it is possible to
11698     // end up in this situation with "auto x(some_pack...);"
11699     Diag(Init->getBeginLoc(), IsInitCapture
11700                                   ? diag::err_init_capture_no_expression
11701                                   : diag::err_auto_var_init_no_expression)
11702         << VN << Type << Range;
11703     return QualType();
11704   }
11705 
11706   if (DeduceInits.size() > 1) {
11707     Diag(DeduceInits[1]->getBeginLoc(),
11708          IsInitCapture ? diag::err_init_capture_multiple_expressions
11709                        : diag::err_auto_var_init_multiple_expressions)
11710         << VN << Type << Range;
11711     return QualType();
11712   }
11713 
11714   Expr *DeduceInit = DeduceInits[0];
11715   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11716     Diag(Init->getBeginLoc(), IsInitCapture
11717                                   ? diag::err_init_capture_paren_braces
11718                                   : diag::err_auto_var_init_paren_braces)
11719         << isa<InitListExpr>(Init) << VN << Type << Range;
11720     return QualType();
11721   }
11722 
11723   // Expressions default to 'id' when we're in a debugger.
11724   bool DefaultedAnyToId = false;
11725   if (getLangOpts().DebuggerCastResultToId &&
11726       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11727     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11728     if (Result.isInvalid()) {
11729       return QualType();
11730     }
11731     Init = Result.get();
11732     DefaultedAnyToId = true;
11733   }
11734 
11735   // C++ [dcl.decomp]p1:
11736   //   If the assignment-expression [...] has array type A and no ref-qualifier
11737   //   is present, e has type cv A
11738   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11739       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11740       DeduceInit->getType()->isConstantArrayType())
11741     return Context.getQualifiedType(DeduceInit->getType(),
11742                                     Type.getQualifiers());
11743 
11744   QualType DeducedType;
11745   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11746     if (!IsInitCapture)
11747       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11748     else if (isa<InitListExpr>(Init))
11749       Diag(Range.getBegin(),
11750            diag::err_init_capture_deduction_failure_from_init_list)
11751           << VN
11752           << (DeduceInit->getType().isNull() ? TSI->getType()
11753                                              : DeduceInit->getType())
11754           << DeduceInit->getSourceRange();
11755     else
11756       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11757           << VN << TSI->getType()
11758           << (DeduceInit->getType().isNull() ? TSI->getType()
11759                                              : DeduceInit->getType())
11760           << DeduceInit->getSourceRange();
11761   }
11762 
11763   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11764   // 'id' instead of a specific object type prevents most of our usual
11765   // checks.
11766   // We only want to warn outside of template instantiations, though:
11767   // inside a template, the 'id' could have come from a parameter.
11768   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11769       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11770     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11771     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11772   }
11773 
11774   return DeducedType;
11775 }
11776 
11777 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11778                                          Expr *Init) {
11779   assert(!Init || !Init->containsErrors());
11780   QualType DeducedType = deduceVarTypeFromInitializer(
11781       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11782       VDecl->getSourceRange(), DirectInit, Init);
11783   if (DeducedType.isNull()) {
11784     VDecl->setInvalidDecl();
11785     return true;
11786   }
11787 
11788   VDecl->setType(DeducedType);
11789   assert(VDecl->isLinkageValid());
11790 
11791   // In ARC, infer lifetime.
11792   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11793     VDecl->setInvalidDecl();
11794 
11795   if (getLangOpts().OpenCL)
11796     deduceOpenCLAddressSpace(VDecl);
11797 
11798   // If this is a redeclaration, check that the type we just deduced matches
11799   // the previously declared type.
11800   if (VarDecl *Old = VDecl->getPreviousDecl()) {
11801     // We never need to merge the type, because we cannot form an incomplete
11802     // array of auto, nor deduce such a type.
11803     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11804   }
11805 
11806   // Check the deduced type is valid for a variable declaration.
11807   CheckVariableDeclarationType(VDecl);
11808   return VDecl->isInvalidDecl();
11809 }
11810 
11811 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11812                                               SourceLocation Loc) {
11813   if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
11814     Init = EWC->getSubExpr();
11815 
11816   if (auto *CE = dyn_cast<ConstantExpr>(Init))
11817     Init = CE->getSubExpr();
11818 
11819   QualType InitType = Init->getType();
11820   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11821           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
11822          "shouldn't be called if type doesn't have a non-trivial C struct");
11823   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11824     for (auto I : ILE->inits()) {
11825       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11826           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11827         continue;
11828       SourceLocation SL = I->getExprLoc();
11829       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11830     }
11831     return;
11832   }
11833 
11834   if (isa<ImplicitValueInitExpr>(Init)) {
11835     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11836       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11837                             NTCUK_Init);
11838   } else {
11839     // Assume all other explicit initializers involving copying some existing
11840     // object.
11841     // TODO: ignore any explicit initializers where we can guarantee
11842     // copy-elision.
11843     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11844       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11845   }
11846 }
11847 
11848 namespace {
11849 
11850 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11851   // Ignore unavailable fields. A field can be marked as unavailable explicitly
11852   // in the source code or implicitly by the compiler if it is in a union
11853   // defined in a system header and has non-trivial ObjC ownership
11854   // qualifications. We don't want those fields to participate in determining
11855   // whether the containing union is non-trivial.
11856   return FD->hasAttr<UnavailableAttr>();
11857 }
11858 
11859 struct DiagNonTrivalCUnionDefaultInitializeVisitor
11860     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11861                                     void> {
11862   using Super =
11863       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11864                                     void>;
11865 
11866   DiagNonTrivalCUnionDefaultInitializeVisitor(
11867       QualType OrigTy, SourceLocation OrigLoc,
11868       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11869       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11870 
11871   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11872                      const FieldDecl *FD, bool InNonTrivialUnion) {
11873     if (const auto *AT = S.Context.getAsArrayType(QT))
11874       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11875                                      InNonTrivialUnion);
11876     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11877   }
11878 
11879   void visitARCStrong(QualType QT, const FieldDecl *FD,
11880                       bool InNonTrivialUnion) {
11881     if (InNonTrivialUnion)
11882       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11883           << 1 << 0 << QT << FD->getName();
11884   }
11885 
11886   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11887     if (InNonTrivialUnion)
11888       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11889           << 1 << 0 << QT << FD->getName();
11890   }
11891 
11892   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11893     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11894     if (RD->isUnion()) {
11895       if (OrigLoc.isValid()) {
11896         bool IsUnion = false;
11897         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11898           IsUnion = OrigRD->isUnion();
11899         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11900             << 0 << OrigTy << IsUnion << UseContext;
11901         // Reset OrigLoc so that this diagnostic is emitted only once.
11902         OrigLoc = SourceLocation();
11903       }
11904       InNonTrivialUnion = true;
11905     }
11906 
11907     if (InNonTrivialUnion)
11908       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11909           << 0 << 0 << QT.getUnqualifiedType() << "";
11910 
11911     for (const FieldDecl *FD : RD->fields())
11912       if (!shouldIgnoreForRecordTriviality(FD))
11913         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11914   }
11915 
11916   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11917 
11918   // The non-trivial C union type or the struct/union type that contains a
11919   // non-trivial C union.
11920   QualType OrigTy;
11921   SourceLocation OrigLoc;
11922   Sema::NonTrivialCUnionContext UseContext;
11923   Sema &S;
11924 };
11925 
11926 struct DiagNonTrivalCUnionDestructedTypeVisitor
11927     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
11928   using Super =
11929       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
11930 
11931   DiagNonTrivalCUnionDestructedTypeVisitor(
11932       QualType OrigTy, SourceLocation OrigLoc,
11933       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11934       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11935 
11936   void visitWithKind(QualType::DestructionKind DK, QualType QT,
11937                      const FieldDecl *FD, bool InNonTrivialUnion) {
11938     if (const auto *AT = S.Context.getAsArrayType(QT))
11939       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11940                                      InNonTrivialUnion);
11941     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
11942   }
11943 
11944   void visitARCStrong(QualType QT, const FieldDecl *FD,
11945                       bool InNonTrivialUnion) {
11946     if (InNonTrivialUnion)
11947       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11948           << 1 << 1 << QT << FD->getName();
11949   }
11950 
11951   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11952     if (InNonTrivialUnion)
11953       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11954           << 1 << 1 << QT << FD->getName();
11955   }
11956 
11957   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11958     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11959     if (RD->isUnion()) {
11960       if (OrigLoc.isValid()) {
11961         bool IsUnion = false;
11962         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11963           IsUnion = OrigRD->isUnion();
11964         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11965             << 1 << OrigTy << IsUnion << UseContext;
11966         // Reset OrigLoc so that this diagnostic is emitted only once.
11967         OrigLoc = SourceLocation();
11968       }
11969       InNonTrivialUnion = true;
11970     }
11971 
11972     if (InNonTrivialUnion)
11973       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11974           << 0 << 1 << QT.getUnqualifiedType() << "";
11975 
11976     for (const FieldDecl *FD : RD->fields())
11977       if (!shouldIgnoreForRecordTriviality(FD))
11978         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11979   }
11980 
11981   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11982   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
11983                           bool InNonTrivialUnion) {}
11984 
11985   // The non-trivial C union type or the struct/union type that contains a
11986   // non-trivial C union.
11987   QualType OrigTy;
11988   SourceLocation OrigLoc;
11989   Sema::NonTrivialCUnionContext UseContext;
11990   Sema &S;
11991 };
11992 
11993 struct DiagNonTrivalCUnionCopyVisitor
11994     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
11995   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
11996 
11997   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
11998                                  Sema::NonTrivialCUnionContext UseContext,
11999                                  Sema &S)
12000       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12001 
12002   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
12003                      const FieldDecl *FD, bool InNonTrivialUnion) {
12004     if (const auto *AT = S.Context.getAsArrayType(QT))
12005       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12006                                      InNonTrivialUnion);
12007     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
12008   }
12009 
12010   void visitARCStrong(QualType QT, const FieldDecl *FD,
12011                       bool InNonTrivialUnion) {
12012     if (InNonTrivialUnion)
12013       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12014           << 1 << 2 << QT << FD->getName();
12015   }
12016 
12017   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12018     if (InNonTrivialUnion)
12019       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12020           << 1 << 2 << QT << FD->getName();
12021   }
12022 
12023   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12024     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12025     if (RD->isUnion()) {
12026       if (OrigLoc.isValid()) {
12027         bool IsUnion = false;
12028         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12029           IsUnion = OrigRD->isUnion();
12030         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12031             << 2 << OrigTy << IsUnion << UseContext;
12032         // Reset OrigLoc so that this diagnostic is emitted only once.
12033         OrigLoc = SourceLocation();
12034       }
12035       InNonTrivialUnion = true;
12036     }
12037 
12038     if (InNonTrivialUnion)
12039       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12040           << 0 << 2 << QT.getUnqualifiedType() << "";
12041 
12042     for (const FieldDecl *FD : RD->fields())
12043       if (!shouldIgnoreForRecordTriviality(FD))
12044         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12045   }
12046 
12047   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
12048                 const FieldDecl *FD, bool InNonTrivialUnion) {}
12049   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12050   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
12051                             bool InNonTrivialUnion) {}
12052 
12053   // The non-trivial C union type or the struct/union type that contains a
12054   // non-trivial C union.
12055   QualType OrigTy;
12056   SourceLocation OrigLoc;
12057   Sema::NonTrivialCUnionContext UseContext;
12058   Sema &S;
12059 };
12060 
12061 } // namespace
12062 
12063 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
12064                                  NonTrivialCUnionContext UseContext,
12065                                  unsigned NonTrivialKind) {
12066   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12067           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
12068           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
12069          "shouldn't be called if type doesn't have a non-trivial C union");
12070 
12071   if ((NonTrivialKind & NTCUK_Init) &&
12072       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12073     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
12074         .visit(QT, nullptr, false);
12075   if ((NonTrivialKind & NTCUK_Destruct) &&
12076       QT.hasNonTrivialToPrimitiveDestructCUnion())
12077     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
12078         .visit(QT, nullptr, false);
12079   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
12080     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
12081         .visit(QT, nullptr, false);
12082 }
12083 
12084 /// AddInitializerToDecl - Adds the initializer Init to the
12085 /// declaration dcl. If DirectInit is true, this is C++ direct
12086 /// initialization rather than copy initialization.
12087 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
12088   // If there is no declaration, there was an error parsing it.  Just ignore
12089   // the initializer.
12090   if (!RealDecl || RealDecl->isInvalidDecl()) {
12091     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
12092     return;
12093   }
12094 
12095   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
12096     // Pure-specifiers are handled in ActOnPureSpecifier.
12097     Diag(Method->getLocation(), diag::err_member_function_initialization)
12098       << Method->getDeclName() << Init->getSourceRange();
12099     Method->setInvalidDecl();
12100     return;
12101   }
12102 
12103   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
12104   if (!VDecl) {
12105     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
12106     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
12107     RealDecl->setInvalidDecl();
12108     return;
12109   }
12110 
12111   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
12112   if (VDecl->getType()->isUndeducedType()) {
12113     // Attempt typo correction early so that the type of the init expression can
12114     // be deduced based on the chosen correction if the original init contains a
12115     // TypoExpr.
12116     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
12117     if (!Res.isUsable()) {
12118       // There are unresolved typos in Init, just drop them.
12119       // FIXME: improve the recovery strategy to preserve the Init.
12120       RealDecl->setInvalidDecl();
12121       return;
12122     }
12123     if (Res.get()->containsErrors()) {
12124       // Invalidate the decl as we don't know the type for recovery-expr yet.
12125       RealDecl->setInvalidDecl();
12126       VDecl->setInit(Res.get());
12127       return;
12128     }
12129     Init = Res.get();
12130 
12131     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
12132       return;
12133   }
12134 
12135   // dllimport cannot be used on variable definitions.
12136   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
12137     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
12138     VDecl->setInvalidDecl();
12139     return;
12140   }
12141 
12142   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
12143     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
12144     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
12145     VDecl->setInvalidDecl();
12146     return;
12147   }
12148 
12149   if (!VDecl->getType()->isDependentType()) {
12150     // A definition must end up with a complete type, which means it must be
12151     // complete with the restriction that an array type might be completed by
12152     // the initializer; note that later code assumes this restriction.
12153     QualType BaseDeclType = VDecl->getType();
12154     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
12155       BaseDeclType = Array->getElementType();
12156     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
12157                             diag::err_typecheck_decl_incomplete_type)) {
12158       RealDecl->setInvalidDecl();
12159       return;
12160     }
12161 
12162     // The variable can not have an abstract class type.
12163     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
12164                                diag::err_abstract_type_in_decl,
12165                                AbstractVariableType))
12166       VDecl->setInvalidDecl();
12167   }
12168 
12169   // If adding the initializer will turn this declaration into a definition,
12170   // and we already have a definition for this variable, diagnose or otherwise
12171   // handle the situation.
12172   VarDecl *Def;
12173   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
12174       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12175       !VDecl->isThisDeclarationADemotedDefinition() &&
12176       checkVarDeclRedefinition(Def, VDecl))
12177     return;
12178 
12179   if (getLangOpts().CPlusPlus) {
12180     // C++ [class.static.data]p4
12181     //   If a static data member is of const integral or const
12182     //   enumeration type, its declaration in the class definition can
12183     //   specify a constant-initializer which shall be an integral
12184     //   constant expression (5.19). In that case, the member can appear
12185     //   in integral constant expressions. The member shall still be
12186     //   defined in a namespace scope if it is used in the program and the
12187     //   namespace scope definition shall not contain an initializer.
12188     //
12189     // We already performed a redefinition check above, but for static
12190     // data members we also need to check whether there was an in-class
12191     // declaration with an initializer.
12192     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12193       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12194           << VDecl->getDeclName();
12195       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12196            diag::note_previous_initializer)
12197           << 0;
12198       return;
12199     }
12200 
12201     if (VDecl->hasLocalStorage())
12202       setFunctionHasBranchProtectedScope();
12203 
12204     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12205       VDecl->setInvalidDecl();
12206       return;
12207     }
12208   }
12209 
12210   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12211   // a kernel function cannot be initialized."
12212   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12213     Diag(VDecl->getLocation(), diag::err_local_cant_init);
12214     VDecl->setInvalidDecl();
12215     return;
12216   }
12217 
12218   // The LoaderUninitialized attribute acts as a definition (of undef).
12219   if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12220     Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12221     VDecl->setInvalidDecl();
12222     return;
12223   }
12224 
12225   // Get the decls type and save a reference for later, since
12226   // CheckInitializerTypes may change it.
12227   QualType DclT = VDecl->getType(), SavT = DclT;
12228 
12229   // Expressions default to 'id' when we're in a debugger
12230   // and we are assigning it to a variable of Objective-C pointer type.
12231   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12232       Init->getType() == Context.UnknownAnyTy) {
12233     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12234     if (Result.isInvalid()) {
12235       VDecl->setInvalidDecl();
12236       return;
12237     }
12238     Init = Result.get();
12239   }
12240 
12241   // Perform the initialization.
12242   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12243   if (!VDecl->isInvalidDecl()) {
12244     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12245     InitializationKind Kind = InitializationKind::CreateForInit(
12246         VDecl->getLocation(), DirectInit, Init);
12247 
12248     MultiExprArg Args = Init;
12249     if (CXXDirectInit)
12250       Args = MultiExprArg(CXXDirectInit->getExprs(),
12251                           CXXDirectInit->getNumExprs());
12252 
12253     // Try to correct any TypoExprs in the initialization arguments.
12254     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12255       ExprResult Res = CorrectDelayedTyposInExpr(
12256           Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12257           [this, Entity, Kind](Expr *E) {
12258             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12259             return Init.Failed() ? ExprError() : E;
12260           });
12261       if (Res.isInvalid()) {
12262         VDecl->setInvalidDecl();
12263       } else if (Res.get() != Args[Idx]) {
12264         Args[Idx] = Res.get();
12265       }
12266     }
12267     if (VDecl->isInvalidDecl())
12268       return;
12269 
12270     InitializationSequence InitSeq(*this, Entity, Kind, Args,
12271                                    /*TopLevelOfInitList=*/false,
12272                                    /*TreatUnavailableAsInvalid=*/false);
12273     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12274     if (Result.isInvalid()) {
12275       // If the provied initializer fails to initialize the var decl,
12276       // we attach a recovery expr for better recovery.
12277       auto RecoveryExpr =
12278           CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12279       if (RecoveryExpr.get())
12280         VDecl->setInit(RecoveryExpr.get());
12281       return;
12282     }
12283 
12284     Init = Result.getAs<Expr>();
12285   }
12286 
12287   // Check for self-references within variable initializers.
12288   // Variables declared within a function/method body (except for references)
12289   // are handled by a dataflow analysis.
12290   // This is undefined behavior in C++, but valid in C.
12291   if (getLangOpts().CPlusPlus) {
12292     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12293         VDecl->getType()->isReferenceType()) {
12294       CheckSelfReference(*this, RealDecl, Init, DirectInit);
12295     }
12296   }
12297 
12298   // If the type changed, it means we had an incomplete type that was
12299   // completed by the initializer. For example:
12300   //   int ary[] = { 1, 3, 5 };
12301   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12302   if (!VDecl->isInvalidDecl() && (DclT != SavT))
12303     VDecl->setType(DclT);
12304 
12305   if (!VDecl->isInvalidDecl()) {
12306     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12307 
12308     if (VDecl->hasAttr<BlocksAttr>())
12309       checkRetainCycles(VDecl, Init);
12310 
12311     // It is safe to assign a weak reference into a strong variable.
12312     // Although this code can still have problems:
12313     //   id x = self.weakProp;
12314     //   id y = self.weakProp;
12315     // we do not warn to warn spuriously when 'x' and 'y' are on separate
12316     // paths through the function. This should be revisited if
12317     // -Wrepeated-use-of-weak is made flow-sensitive.
12318     if (FunctionScopeInfo *FSI = getCurFunction())
12319       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12320            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12321           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12322                            Init->getBeginLoc()))
12323         FSI->markSafeWeakUse(Init);
12324   }
12325 
12326   // The initialization is usually a full-expression.
12327   //
12328   // FIXME: If this is a braced initialization of an aggregate, it is not
12329   // an expression, and each individual field initializer is a separate
12330   // full-expression. For instance, in:
12331   //
12332   //   struct Temp { ~Temp(); };
12333   //   struct S { S(Temp); };
12334   //   struct T { S a, b; } t = { Temp(), Temp() }
12335   //
12336   // we should destroy the first Temp before constructing the second.
12337   ExprResult Result =
12338       ActOnFinishFullExpr(Init, VDecl->getLocation(),
12339                           /*DiscardedValue*/ false, VDecl->isConstexpr());
12340   if (Result.isInvalid()) {
12341     VDecl->setInvalidDecl();
12342     return;
12343   }
12344   Init = Result.get();
12345 
12346   // Attach the initializer to the decl.
12347   VDecl->setInit(Init);
12348 
12349   if (VDecl->isLocalVarDecl()) {
12350     // Don't check the initializer if the declaration is malformed.
12351     if (VDecl->isInvalidDecl()) {
12352       // do nothing
12353 
12354     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12355     // This is true even in C++ for OpenCL.
12356     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12357       CheckForConstantInitializer(Init, DclT);
12358 
12359     // Otherwise, C++ does not restrict the initializer.
12360     } else if (getLangOpts().CPlusPlus) {
12361       // do nothing
12362 
12363     // C99 6.7.8p4: All the expressions in an initializer for an object that has
12364     // static storage duration shall be constant expressions or string literals.
12365     } else if (VDecl->getStorageClass() == SC_Static) {
12366       CheckForConstantInitializer(Init, DclT);
12367 
12368     // C89 is stricter than C99 for aggregate initializers.
12369     // C89 6.5.7p3: All the expressions [...] in an initializer list
12370     // for an object that has aggregate or union type shall be
12371     // constant expressions.
12372     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12373                isa<InitListExpr>(Init)) {
12374       const Expr *Culprit;
12375       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12376         Diag(Culprit->getExprLoc(),
12377              diag::ext_aggregate_init_not_constant)
12378           << Culprit->getSourceRange();
12379       }
12380     }
12381 
12382     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12383       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12384         if (VDecl->hasLocalStorage())
12385           BE->getBlockDecl()->setCanAvoidCopyToHeap();
12386   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12387              VDecl->getLexicalDeclContext()->isRecord()) {
12388     // This is an in-class initialization for a static data member, e.g.,
12389     //
12390     // struct S {
12391     //   static const int value = 17;
12392     // };
12393 
12394     // C++ [class.mem]p4:
12395     //   A member-declarator can contain a constant-initializer only
12396     //   if it declares a static member (9.4) of const integral or
12397     //   const enumeration type, see 9.4.2.
12398     //
12399     // C++11 [class.static.data]p3:
12400     //   If a non-volatile non-inline const static data member is of integral
12401     //   or enumeration type, its declaration in the class definition can
12402     //   specify a brace-or-equal-initializer in which every initializer-clause
12403     //   that is an assignment-expression is a constant expression. A static
12404     //   data member of literal type can be declared in the class definition
12405     //   with the constexpr specifier; if so, its declaration shall specify a
12406     //   brace-or-equal-initializer in which every initializer-clause that is
12407     //   an assignment-expression is a constant expression.
12408 
12409     // Do nothing on dependent types.
12410     if (DclT->isDependentType()) {
12411 
12412     // Allow any 'static constexpr' members, whether or not they are of literal
12413     // type. We separately check that every constexpr variable is of literal
12414     // type.
12415     } else if (VDecl->isConstexpr()) {
12416 
12417     // Require constness.
12418     } else if (!DclT.isConstQualified()) {
12419       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12420         << Init->getSourceRange();
12421       VDecl->setInvalidDecl();
12422 
12423     // We allow integer constant expressions in all cases.
12424     } else if (DclT->isIntegralOrEnumerationType()) {
12425       // Check whether the expression is a constant expression.
12426       SourceLocation Loc;
12427       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12428         // In C++11, a non-constexpr const static data member with an
12429         // in-class initializer cannot be volatile.
12430         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12431       else if (Init->isValueDependent())
12432         ; // Nothing to check.
12433       else if (Init->isIntegerConstantExpr(Context, &Loc))
12434         ; // Ok, it's an ICE!
12435       else if (Init->getType()->isScopedEnumeralType() &&
12436                Init->isCXX11ConstantExpr(Context))
12437         ; // Ok, it is a scoped-enum constant expression.
12438       else if (Init->isEvaluatable(Context)) {
12439         // If we can constant fold the initializer through heroics, accept it,
12440         // but report this as a use of an extension for -pedantic.
12441         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12442           << Init->getSourceRange();
12443       } else {
12444         // Otherwise, this is some crazy unknown case.  Report the issue at the
12445         // location provided by the isIntegerConstantExpr failed check.
12446         Diag(Loc, diag::err_in_class_initializer_non_constant)
12447           << Init->getSourceRange();
12448         VDecl->setInvalidDecl();
12449       }
12450 
12451     // We allow foldable floating-point constants as an extension.
12452     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12453       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12454       // it anyway and provide a fixit to add the 'constexpr'.
12455       if (getLangOpts().CPlusPlus11) {
12456         Diag(VDecl->getLocation(),
12457              diag::ext_in_class_initializer_float_type_cxx11)
12458             << DclT << Init->getSourceRange();
12459         Diag(VDecl->getBeginLoc(),
12460              diag::note_in_class_initializer_float_type_cxx11)
12461             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12462       } else {
12463         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12464           << DclT << Init->getSourceRange();
12465 
12466         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12467           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12468             << Init->getSourceRange();
12469           VDecl->setInvalidDecl();
12470         }
12471       }
12472 
12473     // Suggest adding 'constexpr' in C++11 for literal types.
12474     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12475       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12476           << DclT << Init->getSourceRange()
12477           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12478       VDecl->setConstexpr(true);
12479 
12480     } else {
12481       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12482         << DclT << Init->getSourceRange();
12483       VDecl->setInvalidDecl();
12484     }
12485   } else if (VDecl->isFileVarDecl()) {
12486     // In C, extern is typically used to avoid tentative definitions when
12487     // declaring variables in headers, but adding an intializer makes it a
12488     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12489     // In C++, extern is often used to give implictly static const variables
12490     // external linkage, so don't warn in that case. If selectany is present,
12491     // this might be header code intended for C and C++ inclusion, so apply the
12492     // C++ rules.
12493     if (VDecl->getStorageClass() == SC_Extern &&
12494         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12495          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12496         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12497         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12498       Diag(VDecl->getLocation(), diag::warn_extern_init);
12499 
12500     // In Microsoft C++ mode, a const variable defined in namespace scope has
12501     // external linkage by default if the variable is declared with
12502     // __declspec(dllexport).
12503     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12504         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12505         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12506       VDecl->setStorageClass(SC_Extern);
12507 
12508     // C99 6.7.8p4. All file scoped initializers need to be constant.
12509     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12510       CheckForConstantInitializer(Init, DclT);
12511   }
12512 
12513   QualType InitType = Init->getType();
12514   if (!InitType.isNull() &&
12515       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12516        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12517     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12518 
12519   // We will represent direct-initialization similarly to copy-initialization:
12520   //    int x(1);  -as-> int x = 1;
12521   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12522   //
12523   // Clients that want to distinguish between the two forms, can check for
12524   // direct initializer using VarDecl::getInitStyle().
12525   // A major benefit is that clients that don't particularly care about which
12526   // exactly form was it (like the CodeGen) can handle both cases without
12527   // special case code.
12528 
12529   // C++ 8.5p11:
12530   // The form of initialization (using parentheses or '=') is generally
12531   // insignificant, but does matter when the entity being initialized has a
12532   // class type.
12533   if (CXXDirectInit) {
12534     assert(DirectInit && "Call-style initializer must be direct init.");
12535     VDecl->setInitStyle(VarDecl::CallInit);
12536   } else if (DirectInit) {
12537     // This must be list-initialization. No other way is direct-initialization.
12538     VDecl->setInitStyle(VarDecl::ListInit);
12539   }
12540 
12541   if (LangOpts.OpenMP && VDecl->isFileVarDecl())
12542     DeclsToCheckForDeferredDiags.push_back(VDecl);
12543   CheckCompleteVariableDeclaration(VDecl);
12544 }
12545 
12546 /// ActOnInitializerError - Given that there was an error parsing an
12547 /// initializer for the given declaration, try to return to some form
12548 /// of sanity.
12549 void Sema::ActOnInitializerError(Decl *D) {
12550   // Our main concern here is re-establishing invariants like "a
12551   // variable's type is either dependent or complete".
12552   if (!D || D->isInvalidDecl()) return;
12553 
12554   VarDecl *VD = dyn_cast<VarDecl>(D);
12555   if (!VD) return;
12556 
12557   // Bindings are not usable if we can't make sense of the initializer.
12558   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12559     for (auto *BD : DD->bindings())
12560       BD->setInvalidDecl();
12561 
12562   // Auto types are meaningless if we can't make sense of the initializer.
12563   if (VD->getType()->isUndeducedType()) {
12564     D->setInvalidDecl();
12565     return;
12566   }
12567 
12568   QualType Ty = VD->getType();
12569   if (Ty->isDependentType()) return;
12570 
12571   // Require a complete type.
12572   if (RequireCompleteType(VD->getLocation(),
12573                           Context.getBaseElementType(Ty),
12574                           diag::err_typecheck_decl_incomplete_type)) {
12575     VD->setInvalidDecl();
12576     return;
12577   }
12578 
12579   // Require a non-abstract type.
12580   if (RequireNonAbstractType(VD->getLocation(), Ty,
12581                              diag::err_abstract_type_in_decl,
12582                              AbstractVariableType)) {
12583     VD->setInvalidDecl();
12584     return;
12585   }
12586 
12587   // Don't bother complaining about constructors or destructors,
12588   // though.
12589 }
12590 
12591 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12592   // If there is no declaration, there was an error parsing it. Just ignore it.
12593   if (!RealDecl)
12594     return;
12595 
12596   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12597     QualType Type = Var->getType();
12598 
12599     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12600     if (isa<DecompositionDecl>(RealDecl)) {
12601       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12602       Var->setInvalidDecl();
12603       return;
12604     }
12605 
12606     if (Type->isUndeducedType() &&
12607         DeduceVariableDeclarationType(Var, false, nullptr))
12608       return;
12609 
12610     // C++11 [class.static.data]p3: A static data member can be declared with
12611     // the constexpr specifier; if so, its declaration shall specify
12612     // a brace-or-equal-initializer.
12613     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12614     // the definition of a variable [...] or the declaration of a static data
12615     // member.
12616     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12617         !Var->isThisDeclarationADemotedDefinition()) {
12618       if (Var->isStaticDataMember()) {
12619         // C++1z removes the relevant rule; the in-class declaration is always
12620         // a definition there.
12621         if (!getLangOpts().CPlusPlus17 &&
12622             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12623           Diag(Var->getLocation(),
12624                diag::err_constexpr_static_mem_var_requires_init)
12625               << Var;
12626           Var->setInvalidDecl();
12627           return;
12628         }
12629       } else {
12630         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12631         Var->setInvalidDecl();
12632         return;
12633       }
12634     }
12635 
12636     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12637     // be initialized.
12638     if (!Var->isInvalidDecl() &&
12639         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12640         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12641       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12642       Var->setInvalidDecl();
12643       return;
12644     }
12645 
12646     if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
12647       if (Var->getStorageClass() == SC_Extern) {
12648         Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
12649             << Var;
12650         Var->setInvalidDecl();
12651         return;
12652       }
12653       if (RequireCompleteType(Var->getLocation(), Var->getType(),
12654                               diag::err_typecheck_decl_incomplete_type)) {
12655         Var->setInvalidDecl();
12656         return;
12657       }
12658       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12659         if (!RD->hasTrivialDefaultConstructor()) {
12660           Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
12661           Var->setInvalidDecl();
12662           return;
12663         }
12664       }
12665       // The declaration is unitialized, no need for further checks.
12666       return;
12667     }
12668 
12669     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12670     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12671         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12672       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12673                             NTCUC_DefaultInitializedObject, NTCUK_Init);
12674 
12675 
12676     switch (DefKind) {
12677     case VarDecl::Definition:
12678       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12679         break;
12680 
12681       // We have an out-of-line definition of a static data member
12682       // that has an in-class initializer, so we type-check this like
12683       // a declaration.
12684       //
12685       LLVM_FALLTHROUGH;
12686 
12687     case VarDecl::DeclarationOnly:
12688       // It's only a declaration.
12689 
12690       // Block scope. C99 6.7p7: If an identifier for an object is
12691       // declared with no linkage (C99 6.2.2p6), the type for the
12692       // object shall be complete.
12693       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12694           !Var->hasLinkage() && !Var->isInvalidDecl() &&
12695           RequireCompleteType(Var->getLocation(), Type,
12696                               diag::err_typecheck_decl_incomplete_type))
12697         Var->setInvalidDecl();
12698 
12699       // Make sure that the type is not abstract.
12700       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12701           RequireNonAbstractType(Var->getLocation(), Type,
12702                                  diag::err_abstract_type_in_decl,
12703                                  AbstractVariableType))
12704         Var->setInvalidDecl();
12705       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12706           Var->getStorageClass() == SC_PrivateExtern) {
12707         Diag(Var->getLocation(), diag::warn_private_extern);
12708         Diag(Var->getLocation(), diag::note_private_extern);
12709       }
12710 
12711       if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
12712           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12713         ExternalDeclarations.push_back(Var);
12714 
12715       return;
12716 
12717     case VarDecl::TentativeDefinition:
12718       // File scope. C99 6.9.2p2: A declaration of an identifier for an
12719       // object that has file scope without an initializer, and without a
12720       // storage-class specifier or with the storage-class specifier "static",
12721       // constitutes a tentative definition. Note: A tentative definition with
12722       // external linkage is valid (C99 6.2.2p5).
12723       if (!Var->isInvalidDecl()) {
12724         if (const IncompleteArrayType *ArrayT
12725                                     = Context.getAsIncompleteArrayType(Type)) {
12726           if (RequireCompleteSizedType(
12727                   Var->getLocation(), ArrayT->getElementType(),
12728                   diag::err_array_incomplete_or_sizeless_type))
12729             Var->setInvalidDecl();
12730         } else if (Var->getStorageClass() == SC_Static) {
12731           // C99 6.9.2p3: If the declaration of an identifier for an object is
12732           // a tentative definition and has internal linkage (C99 6.2.2p3), the
12733           // declared type shall not be an incomplete type.
12734           // NOTE: code such as the following
12735           //     static struct s;
12736           //     struct s { int a; };
12737           // is accepted by gcc. Hence here we issue a warning instead of
12738           // an error and we do not invalidate the static declaration.
12739           // NOTE: to avoid multiple warnings, only check the first declaration.
12740           if (Var->isFirstDecl())
12741             RequireCompleteType(Var->getLocation(), Type,
12742                                 diag::ext_typecheck_decl_incomplete_type);
12743         }
12744       }
12745 
12746       // Record the tentative definition; we're done.
12747       if (!Var->isInvalidDecl())
12748         TentativeDefinitions.push_back(Var);
12749       return;
12750     }
12751 
12752     // Provide a specific diagnostic for uninitialized variable
12753     // definitions with incomplete array type.
12754     if (Type->isIncompleteArrayType()) {
12755       Diag(Var->getLocation(),
12756            diag::err_typecheck_incomplete_array_needs_initializer);
12757       Var->setInvalidDecl();
12758       return;
12759     }
12760 
12761     // Provide a specific diagnostic for uninitialized variable
12762     // definitions with reference type.
12763     if (Type->isReferenceType()) {
12764       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12765           << Var << SourceRange(Var->getLocation(), Var->getLocation());
12766       Var->setInvalidDecl();
12767       return;
12768     }
12769 
12770     // Do not attempt to type-check the default initializer for a
12771     // variable with dependent type.
12772     if (Type->isDependentType())
12773       return;
12774 
12775     if (Var->isInvalidDecl())
12776       return;
12777 
12778     if (!Var->hasAttr<AliasAttr>()) {
12779       if (RequireCompleteType(Var->getLocation(),
12780                               Context.getBaseElementType(Type),
12781                               diag::err_typecheck_decl_incomplete_type)) {
12782         Var->setInvalidDecl();
12783         return;
12784       }
12785     } else {
12786       return;
12787     }
12788 
12789     // The variable can not have an abstract class type.
12790     if (RequireNonAbstractType(Var->getLocation(), Type,
12791                                diag::err_abstract_type_in_decl,
12792                                AbstractVariableType)) {
12793       Var->setInvalidDecl();
12794       return;
12795     }
12796 
12797     // Check for jumps past the implicit initializer.  C++0x
12798     // clarifies that this applies to a "variable with automatic
12799     // storage duration", not a "local variable".
12800     // C++11 [stmt.dcl]p3
12801     //   A program that jumps from a point where a variable with automatic
12802     //   storage duration is not in scope to a point where it is in scope is
12803     //   ill-formed unless the variable has scalar type, class type with a
12804     //   trivial default constructor and a trivial destructor, a cv-qualified
12805     //   version of one of these types, or an array of one of the preceding
12806     //   types and is declared without an initializer.
12807     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12808       if (const RecordType *Record
12809             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12810         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12811         // Mark the function (if we're in one) for further checking even if the
12812         // looser rules of C++11 do not require such checks, so that we can
12813         // diagnose incompatibilities with C++98.
12814         if (!CXXRecord->isPOD())
12815           setFunctionHasBranchProtectedScope();
12816       }
12817     }
12818     // In OpenCL, we can't initialize objects in the __local address space,
12819     // even implicitly, so don't synthesize an implicit initializer.
12820     if (getLangOpts().OpenCL &&
12821         Var->getType().getAddressSpace() == LangAS::opencl_local)
12822       return;
12823     // C++03 [dcl.init]p9:
12824     //   If no initializer is specified for an object, and the
12825     //   object is of (possibly cv-qualified) non-POD class type (or
12826     //   array thereof), the object shall be default-initialized; if
12827     //   the object is of const-qualified type, the underlying class
12828     //   type shall have a user-declared default
12829     //   constructor. Otherwise, if no initializer is specified for
12830     //   a non- static object, the object and its subobjects, if
12831     //   any, have an indeterminate initial value); if the object
12832     //   or any of its subobjects are of const-qualified type, the
12833     //   program is ill-formed.
12834     // C++0x [dcl.init]p11:
12835     //   If no initializer is specified for an object, the object is
12836     //   default-initialized; [...].
12837     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12838     InitializationKind Kind
12839       = InitializationKind::CreateDefault(Var->getLocation());
12840 
12841     InitializationSequence InitSeq(*this, Entity, Kind, None);
12842     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12843 
12844     if (Init.get()) {
12845       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12846       // This is important for template substitution.
12847       Var->setInitStyle(VarDecl::CallInit);
12848     } else if (Init.isInvalid()) {
12849       // If default-init fails, attach a recovery-expr initializer to track
12850       // that initialization was attempted and failed.
12851       auto RecoveryExpr =
12852           CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
12853       if (RecoveryExpr.get())
12854         Var->setInit(RecoveryExpr.get());
12855     }
12856 
12857     CheckCompleteVariableDeclaration(Var);
12858   }
12859 }
12860 
12861 void Sema::ActOnCXXForRangeDecl(Decl *D) {
12862   // If there is no declaration, there was an error parsing it. Ignore it.
12863   if (!D)
12864     return;
12865 
12866   VarDecl *VD = dyn_cast<VarDecl>(D);
12867   if (!VD) {
12868     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12869     D->setInvalidDecl();
12870     return;
12871   }
12872 
12873   VD->setCXXForRangeDecl(true);
12874 
12875   // for-range-declaration cannot be given a storage class specifier.
12876   int Error = -1;
12877   switch (VD->getStorageClass()) {
12878   case SC_None:
12879     break;
12880   case SC_Extern:
12881     Error = 0;
12882     break;
12883   case SC_Static:
12884     Error = 1;
12885     break;
12886   case SC_PrivateExtern:
12887     Error = 2;
12888     break;
12889   case SC_Auto:
12890     Error = 3;
12891     break;
12892   case SC_Register:
12893     Error = 4;
12894     break;
12895   }
12896 
12897   // for-range-declaration cannot be given a storage class specifier con't.
12898   switch (VD->getTSCSpec()) {
12899   case TSCS_thread_local:
12900     Error = 6;
12901     break;
12902   case TSCS___thread:
12903   case TSCS__Thread_local:
12904   case TSCS_unspecified:
12905     break;
12906   }
12907 
12908   if (Error != -1) {
12909     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12910         << VD << Error;
12911     D->setInvalidDecl();
12912   }
12913 }
12914 
12915 StmtResult
12916 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
12917                                  IdentifierInfo *Ident,
12918                                  ParsedAttributes &Attrs,
12919                                  SourceLocation AttrEnd) {
12920   // C++1y [stmt.iter]p1:
12921   //   A range-based for statement of the form
12922   //      for ( for-range-identifier : for-range-initializer ) statement
12923   //   is equivalent to
12924   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
12925   DeclSpec DS(Attrs.getPool().getFactory());
12926 
12927   const char *PrevSpec;
12928   unsigned DiagID;
12929   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
12930                      getPrintingPolicy());
12931 
12932   Declarator D(DS, DeclaratorContext::ForInit);
12933   D.SetIdentifier(Ident, IdentLoc);
12934   D.takeAttributes(Attrs, AttrEnd);
12935 
12936   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
12937                 IdentLoc);
12938   Decl *Var = ActOnDeclarator(S, D);
12939   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
12940   FinalizeDeclaration(Var);
12941   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
12942                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
12943 }
12944 
12945 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
12946   if (var->isInvalidDecl()) return;
12947 
12948   if (getLangOpts().OpenCL) {
12949     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
12950     // initialiser
12951     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
12952         !var->hasInit()) {
12953       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
12954           << 1 /*Init*/;
12955       var->setInvalidDecl();
12956       return;
12957     }
12958   }
12959 
12960   // In Objective-C, don't allow jumps past the implicit initialization of a
12961   // local retaining variable.
12962   if (getLangOpts().ObjC &&
12963       var->hasLocalStorage()) {
12964     switch (var->getType().getObjCLifetime()) {
12965     case Qualifiers::OCL_None:
12966     case Qualifiers::OCL_ExplicitNone:
12967     case Qualifiers::OCL_Autoreleasing:
12968       break;
12969 
12970     case Qualifiers::OCL_Weak:
12971     case Qualifiers::OCL_Strong:
12972       setFunctionHasBranchProtectedScope();
12973       break;
12974     }
12975   }
12976 
12977   if (var->hasLocalStorage() &&
12978       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
12979     setFunctionHasBranchProtectedScope();
12980 
12981   // Warn about externally-visible variables being defined without a
12982   // prior declaration.  We only want to do this for global
12983   // declarations, but we also specifically need to avoid doing it for
12984   // class members because the linkage of an anonymous class can
12985   // change if it's later given a typedef name.
12986   if (var->isThisDeclarationADefinition() &&
12987       var->getDeclContext()->getRedeclContext()->isFileContext() &&
12988       var->isExternallyVisible() && var->hasLinkage() &&
12989       !var->isInline() && !var->getDescribedVarTemplate() &&
12990       !isa<VarTemplatePartialSpecializationDecl>(var) &&
12991       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
12992       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
12993                                   var->getLocation())) {
12994     // Find a previous declaration that's not a definition.
12995     VarDecl *prev = var->getPreviousDecl();
12996     while (prev && prev->isThisDeclarationADefinition())
12997       prev = prev->getPreviousDecl();
12998 
12999     if (!prev) {
13000       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
13001       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13002           << /* variable */ 0;
13003     }
13004   }
13005 
13006   // Cache the result of checking for constant initialization.
13007   Optional<bool> CacheHasConstInit;
13008   const Expr *CacheCulprit = nullptr;
13009   auto checkConstInit = [&]() mutable {
13010     if (!CacheHasConstInit)
13011       CacheHasConstInit = var->getInit()->isConstantInitializer(
13012             Context, var->getType()->isReferenceType(), &CacheCulprit);
13013     return *CacheHasConstInit;
13014   };
13015 
13016   if (var->getTLSKind() == VarDecl::TLS_Static) {
13017     if (var->getType().isDestructedType()) {
13018       // GNU C++98 edits for __thread, [basic.start.term]p3:
13019       //   The type of an object with thread storage duration shall not
13020       //   have a non-trivial destructor.
13021       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
13022       if (getLangOpts().CPlusPlus11)
13023         Diag(var->getLocation(), diag::note_use_thread_local);
13024     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
13025       if (!checkConstInit()) {
13026         // GNU C++98 edits for __thread, [basic.start.init]p4:
13027         //   An object of thread storage duration shall not require dynamic
13028         //   initialization.
13029         // FIXME: Need strict checking here.
13030         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
13031           << CacheCulprit->getSourceRange();
13032         if (getLangOpts().CPlusPlus11)
13033           Diag(var->getLocation(), diag::note_use_thread_local);
13034       }
13035     }
13036   }
13037 
13038   // Apply section attributes and pragmas to global variables.
13039   bool GlobalStorage = var->hasGlobalStorage();
13040   if (GlobalStorage && var->isThisDeclarationADefinition() &&
13041       !inTemplateInstantiation()) {
13042     PragmaStack<StringLiteral *> *Stack = nullptr;
13043     int SectionFlags = ASTContext::PSF_Read;
13044     if (var->getType().isConstQualified())
13045       Stack = &ConstSegStack;
13046     else if (!var->getInit()) {
13047       Stack = &BSSSegStack;
13048       SectionFlags |= ASTContext::PSF_Write;
13049     } else {
13050       Stack = &DataSegStack;
13051       SectionFlags |= ASTContext::PSF_Write;
13052     }
13053     if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
13054       if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
13055         SectionFlags |= ASTContext::PSF_Implicit;
13056       UnifySection(SA->getName(), SectionFlags, var);
13057     } else if (Stack->CurrentValue) {
13058       SectionFlags |= ASTContext::PSF_Implicit;
13059       auto SectionName = Stack->CurrentValue->getString();
13060       var->addAttr(SectionAttr::CreateImplicit(
13061           Context, SectionName, Stack->CurrentPragmaLocation,
13062           AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
13063       if (UnifySection(SectionName, SectionFlags, var))
13064         var->dropAttr<SectionAttr>();
13065     }
13066 
13067     // Apply the init_seg attribute if this has an initializer.  If the
13068     // initializer turns out to not be dynamic, we'll end up ignoring this
13069     // attribute.
13070     if (CurInitSeg && var->getInit())
13071       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
13072                                                CurInitSegLoc,
13073                                                AttributeCommonInfo::AS_Pragma));
13074   }
13075 
13076   if (!var->getType()->isStructureType() && var->hasInit() &&
13077       isa<InitListExpr>(var->getInit())) {
13078     const auto *ILE = cast<InitListExpr>(var->getInit());
13079     unsigned NumInits = ILE->getNumInits();
13080     if (NumInits > 2)
13081       for (unsigned I = 0; I < NumInits; ++I) {
13082         const auto *Init = ILE->getInit(I);
13083         if (!Init)
13084           break;
13085         const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13086         if (!SL)
13087           break;
13088 
13089         unsigned NumConcat = SL->getNumConcatenated();
13090         // Diagnose missing comma in string array initialization.
13091         // Do not warn when all the elements in the initializer are concatenated
13092         // together. Do not warn for macros too.
13093         if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
13094           bool OnlyOneMissingComma = true;
13095           for (unsigned J = I + 1; J < NumInits; ++J) {
13096             const auto *Init = ILE->getInit(J);
13097             if (!Init)
13098               break;
13099             const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13100             if (!SLJ || SLJ->getNumConcatenated() > 1) {
13101               OnlyOneMissingComma = false;
13102               break;
13103             }
13104           }
13105 
13106           if (OnlyOneMissingComma) {
13107             SmallVector<FixItHint, 1> Hints;
13108             for (unsigned i = 0; i < NumConcat - 1; ++i)
13109               Hints.push_back(FixItHint::CreateInsertion(
13110                   PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
13111 
13112             Diag(SL->getStrTokenLoc(1),
13113                  diag::warn_concatenated_literal_array_init)
13114                 << Hints;
13115             Diag(SL->getBeginLoc(),
13116                  diag::note_concatenated_string_literal_silence);
13117           }
13118           // In any case, stop now.
13119           break;
13120         }
13121       }
13122   }
13123 
13124   // All the following checks are C++ only.
13125   if (!getLangOpts().CPlusPlus) {
13126     // If this variable must be emitted, add it as an initializer for the
13127     // current module.
13128     if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13129       Context.addModuleInitializer(ModuleScopes.back().Module, var);
13130     return;
13131   }
13132 
13133   QualType type = var->getType();
13134 
13135   if (var->hasAttr<BlocksAttr>())
13136     getCurFunction()->addByrefBlockVar(var);
13137 
13138   Expr *Init = var->getInit();
13139   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
13140   QualType baseType = Context.getBaseElementType(type);
13141 
13142   // Check whether the initializer is sufficiently constant.
13143   if (!type->isDependentType() && Init && !Init->isValueDependent() &&
13144       (GlobalStorage || var->isConstexpr() ||
13145        var->mightBeUsableInConstantExpressions(Context))) {
13146     // If this variable might have a constant initializer or might be usable in
13147     // constant expressions, check whether or not it actually is now.  We can't
13148     // do this lazily, because the result might depend on things that change
13149     // later, such as which constexpr functions happen to be defined.
13150     SmallVector<PartialDiagnosticAt, 8> Notes;
13151     bool HasConstInit;
13152     if (!getLangOpts().CPlusPlus11) {
13153       // Prior to C++11, in contexts where a constant initializer is required,
13154       // the set of valid constant initializers is described by syntactic rules
13155       // in [expr.const]p2-6.
13156       // FIXME: Stricter checking for these rules would be useful for constinit /
13157       // -Wglobal-constructors.
13158       HasConstInit = checkConstInit();
13159 
13160       // Compute and cache the constant value, and remember that we have a
13161       // constant initializer.
13162       if (HasConstInit) {
13163         (void)var->checkForConstantInitialization(Notes);
13164         Notes.clear();
13165       } else if (CacheCulprit) {
13166         Notes.emplace_back(CacheCulprit->getExprLoc(),
13167                            PDiag(diag::note_invalid_subexpr_in_const_expr));
13168         Notes.back().second << CacheCulprit->getSourceRange();
13169       }
13170     } else {
13171       // Evaluate the initializer to see if it's a constant initializer.
13172       HasConstInit = var->checkForConstantInitialization(Notes);
13173     }
13174 
13175     if (HasConstInit) {
13176       // FIXME: Consider replacing the initializer with a ConstantExpr.
13177     } else if (var->isConstexpr()) {
13178       SourceLocation DiagLoc = var->getLocation();
13179       // If the note doesn't add any useful information other than a source
13180       // location, fold it into the primary diagnostic.
13181       if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13182                                    diag::note_invalid_subexpr_in_const_expr) {
13183         DiagLoc = Notes[0].first;
13184         Notes.clear();
13185       }
13186       Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
13187           << var << Init->getSourceRange();
13188       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
13189         Diag(Notes[I].first, Notes[I].second);
13190     } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
13191       auto *Attr = var->getAttr<ConstInitAttr>();
13192       Diag(var->getLocation(), diag::err_require_constant_init_failed)
13193           << Init->getSourceRange();
13194       Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
13195           << Attr->getRange() << Attr->isConstinit();
13196       for (auto &it : Notes)
13197         Diag(it.first, it.second);
13198     } else if (IsGlobal &&
13199                !getDiagnostics().isIgnored(diag::warn_global_constructor,
13200                                            var->getLocation())) {
13201       // Warn about globals which don't have a constant initializer.  Don't
13202       // warn about globals with a non-trivial destructor because we already
13203       // warned about them.
13204       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13205       if (!(RD && !RD->hasTrivialDestructor())) {
13206         // checkConstInit() here permits trivial default initialization even in
13207         // C++11 onwards, where such an initializer is not a constant initializer
13208         // but nonetheless doesn't require a global constructor.
13209         if (!checkConstInit())
13210           Diag(var->getLocation(), diag::warn_global_constructor)
13211               << Init->getSourceRange();
13212       }
13213     }
13214   }
13215 
13216   // Require the destructor.
13217   if (!type->isDependentType())
13218     if (const RecordType *recordType = baseType->getAs<RecordType>())
13219       FinalizeVarWithDestructor(var, recordType);
13220 
13221   // If this variable must be emitted, add it as an initializer for the current
13222   // module.
13223   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13224     Context.addModuleInitializer(ModuleScopes.back().Module, var);
13225 
13226   // Build the bindings if this is a structured binding declaration.
13227   if (auto *DD = dyn_cast<DecompositionDecl>(var))
13228     CheckCompleteDecompositionDeclaration(DD);
13229 }
13230 
13231 /// Determines if a variable's alignment is dependent.
13232 static bool hasDependentAlignment(VarDecl *VD) {
13233   if (VD->getType()->isDependentType())
13234     return true;
13235   for (auto *I : VD->specific_attrs<AlignedAttr>())
13236     if (I->isAlignmentDependent())
13237       return true;
13238   return false;
13239 }
13240 
13241 /// Check if VD needs to be dllexport/dllimport due to being in a
13242 /// dllexport/import function.
13243 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
13244   assert(VD->isStaticLocal());
13245 
13246   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13247 
13248   // Find outermost function when VD is in lambda function.
13249   while (FD && !getDLLAttr(FD) &&
13250          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13251          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13252     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13253   }
13254 
13255   if (!FD)
13256     return;
13257 
13258   // Static locals inherit dll attributes from their function.
13259   if (Attr *A = getDLLAttr(FD)) {
13260     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13261     NewAttr->setInherited(true);
13262     VD->addAttr(NewAttr);
13263   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13264     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13265     NewAttr->setInherited(true);
13266     VD->addAttr(NewAttr);
13267 
13268     // Export this function to enforce exporting this static variable even
13269     // if it is not used in this compilation unit.
13270     if (!FD->hasAttr<DLLExportAttr>())
13271       FD->addAttr(NewAttr);
13272 
13273   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13274     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13275     NewAttr->setInherited(true);
13276     VD->addAttr(NewAttr);
13277   }
13278 }
13279 
13280 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13281 /// any semantic actions necessary after any initializer has been attached.
13282 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13283   // Note that we are no longer parsing the initializer for this declaration.
13284   ParsingInitForAutoVars.erase(ThisDecl);
13285 
13286   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13287   if (!VD)
13288     return;
13289 
13290   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13291   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13292       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13293     if (PragmaClangBSSSection.Valid)
13294       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13295           Context, PragmaClangBSSSection.SectionName,
13296           PragmaClangBSSSection.PragmaLocation,
13297           AttributeCommonInfo::AS_Pragma));
13298     if (PragmaClangDataSection.Valid)
13299       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13300           Context, PragmaClangDataSection.SectionName,
13301           PragmaClangDataSection.PragmaLocation,
13302           AttributeCommonInfo::AS_Pragma));
13303     if (PragmaClangRodataSection.Valid)
13304       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13305           Context, PragmaClangRodataSection.SectionName,
13306           PragmaClangRodataSection.PragmaLocation,
13307           AttributeCommonInfo::AS_Pragma));
13308     if (PragmaClangRelroSection.Valid)
13309       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13310           Context, PragmaClangRelroSection.SectionName,
13311           PragmaClangRelroSection.PragmaLocation,
13312           AttributeCommonInfo::AS_Pragma));
13313   }
13314 
13315   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13316     for (auto *BD : DD->bindings()) {
13317       FinalizeDeclaration(BD);
13318     }
13319   }
13320 
13321   checkAttributesAfterMerging(*this, *VD);
13322 
13323   // Perform TLS alignment check here after attributes attached to the variable
13324   // which may affect the alignment have been processed. Only perform the check
13325   // if the target has a maximum TLS alignment (zero means no constraints).
13326   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13327     // Protect the check so that it's not performed on dependent types and
13328     // dependent alignments (we can't determine the alignment in that case).
13329     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
13330         !VD->isInvalidDecl()) {
13331       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13332       if (Context.getDeclAlign(VD) > MaxAlignChars) {
13333         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13334           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13335           << (unsigned)MaxAlignChars.getQuantity();
13336       }
13337     }
13338   }
13339 
13340   if (VD->isStaticLocal())
13341     CheckStaticLocalForDllExport(VD);
13342 
13343   // Perform check for initializers of device-side global variables.
13344   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13345   // 7.5). We must also apply the same checks to all __shared__
13346   // variables whether they are local or not. CUDA also allows
13347   // constant initializers for __constant__ and __device__ variables.
13348   if (getLangOpts().CUDA)
13349     checkAllowedCUDAInitializer(VD);
13350 
13351   // Grab the dllimport or dllexport attribute off of the VarDecl.
13352   const InheritableAttr *DLLAttr = getDLLAttr(VD);
13353 
13354   // Imported static data members cannot be defined out-of-line.
13355   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13356     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13357         VD->isThisDeclarationADefinition()) {
13358       // We allow definitions of dllimport class template static data members
13359       // with a warning.
13360       CXXRecordDecl *Context =
13361         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13362       bool IsClassTemplateMember =
13363           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13364           Context->getDescribedClassTemplate();
13365 
13366       Diag(VD->getLocation(),
13367            IsClassTemplateMember
13368                ? diag::warn_attribute_dllimport_static_field_definition
13369                : diag::err_attribute_dllimport_static_field_definition);
13370       Diag(IA->getLocation(), diag::note_attribute);
13371       if (!IsClassTemplateMember)
13372         VD->setInvalidDecl();
13373     }
13374   }
13375 
13376   // dllimport/dllexport variables cannot be thread local, their TLS index
13377   // isn't exported with the variable.
13378   if (DLLAttr && VD->getTLSKind()) {
13379     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13380     if (F && getDLLAttr(F)) {
13381       assert(VD->isStaticLocal());
13382       // But if this is a static local in a dlimport/dllexport function, the
13383       // function will never be inlined, which means the var would never be
13384       // imported, so having it marked import/export is safe.
13385     } else {
13386       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13387                                                                     << DLLAttr;
13388       VD->setInvalidDecl();
13389     }
13390   }
13391 
13392   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13393     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13394       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13395           << Attr;
13396       VD->dropAttr<UsedAttr>();
13397     }
13398   }
13399   if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
13400     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13401       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13402           << Attr;
13403       VD->dropAttr<RetainAttr>();
13404     }
13405   }
13406 
13407   const DeclContext *DC = VD->getDeclContext();
13408   // If there's a #pragma GCC visibility in scope, and this isn't a class
13409   // member, set the visibility of this variable.
13410   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13411     AddPushedVisibilityAttribute(VD);
13412 
13413   // FIXME: Warn on unused var template partial specializations.
13414   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13415     MarkUnusedFileScopedDecl(VD);
13416 
13417   // Now we have parsed the initializer and can update the table of magic
13418   // tag values.
13419   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13420       !VD->getType()->isIntegralOrEnumerationType())
13421     return;
13422 
13423   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13424     const Expr *MagicValueExpr = VD->getInit();
13425     if (!MagicValueExpr) {
13426       continue;
13427     }
13428     Optional<llvm::APSInt> MagicValueInt;
13429     if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13430       Diag(I->getRange().getBegin(),
13431            diag::err_type_tag_for_datatype_not_ice)
13432         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13433       continue;
13434     }
13435     if (MagicValueInt->getActiveBits() > 64) {
13436       Diag(I->getRange().getBegin(),
13437            diag::err_type_tag_for_datatype_too_large)
13438         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13439       continue;
13440     }
13441     uint64_t MagicValue = MagicValueInt->getZExtValue();
13442     RegisterTypeTagForDatatype(I->getArgumentKind(),
13443                                MagicValue,
13444                                I->getMatchingCType(),
13445                                I->getLayoutCompatible(),
13446                                I->getMustBeNull());
13447   }
13448 }
13449 
13450 static bool hasDeducedAuto(DeclaratorDecl *DD) {
13451   auto *VD = dyn_cast<VarDecl>(DD);
13452   return VD && !VD->getType()->hasAutoForTrailingReturnType();
13453 }
13454 
13455 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13456                                                    ArrayRef<Decl *> Group) {
13457   SmallVector<Decl*, 8> Decls;
13458 
13459   if (DS.isTypeSpecOwned())
13460     Decls.push_back(DS.getRepAsDecl());
13461 
13462   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13463   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13464   bool DiagnosedMultipleDecomps = false;
13465   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13466   bool DiagnosedNonDeducedAuto = false;
13467 
13468   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13469     if (Decl *D = Group[i]) {
13470       // For declarators, there are some additional syntactic-ish checks we need
13471       // to perform.
13472       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13473         if (!FirstDeclaratorInGroup)
13474           FirstDeclaratorInGroup = DD;
13475         if (!FirstDecompDeclaratorInGroup)
13476           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13477         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13478             !hasDeducedAuto(DD))
13479           FirstNonDeducedAutoInGroup = DD;
13480 
13481         if (FirstDeclaratorInGroup != DD) {
13482           // A decomposition declaration cannot be combined with any other
13483           // declaration in the same group.
13484           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13485             Diag(FirstDecompDeclaratorInGroup->getLocation(),
13486                  diag::err_decomp_decl_not_alone)
13487                 << FirstDeclaratorInGroup->getSourceRange()
13488                 << DD->getSourceRange();
13489             DiagnosedMultipleDecomps = true;
13490           }
13491 
13492           // A declarator that uses 'auto' in any way other than to declare a
13493           // variable with a deduced type cannot be combined with any other
13494           // declarator in the same group.
13495           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13496             Diag(FirstNonDeducedAutoInGroup->getLocation(),
13497                  diag::err_auto_non_deduced_not_alone)
13498                 << FirstNonDeducedAutoInGroup->getType()
13499                        ->hasAutoForTrailingReturnType()
13500                 << FirstDeclaratorInGroup->getSourceRange()
13501                 << DD->getSourceRange();
13502             DiagnosedNonDeducedAuto = true;
13503           }
13504         }
13505       }
13506 
13507       Decls.push_back(D);
13508     }
13509   }
13510 
13511   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13512     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13513       handleTagNumbering(Tag, S);
13514       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13515           getLangOpts().CPlusPlus)
13516         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13517     }
13518   }
13519 
13520   return BuildDeclaratorGroup(Decls);
13521 }
13522 
13523 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
13524 /// group, performing any necessary semantic checking.
13525 Sema::DeclGroupPtrTy
13526 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13527   // C++14 [dcl.spec.auto]p7: (DR1347)
13528   //   If the type that replaces the placeholder type is not the same in each
13529   //   deduction, the program is ill-formed.
13530   if (Group.size() > 1) {
13531     QualType Deduced;
13532     VarDecl *DeducedDecl = nullptr;
13533     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13534       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13535       if (!D || D->isInvalidDecl())
13536         break;
13537       DeducedType *DT = D->getType()->getContainedDeducedType();
13538       if (!DT || DT->getDeducedType().isNull())
13539         continue;
13540       if (Deduced.isNull()) {
13541         Deduced = DT->getDeducedType();
13542         DeducedDecl = D;
13543       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13544         auto *AT = dyn_cast<AutoType>(DT);
13545         auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13546                         diag::err_auto_different_deductions)
13547                    << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
13548                    << DeducedDecl->getDeclName() << DT->getDeducedType()
13549                    << D->getDeclName();
13550         if (DeducedDecl->hasInit())
13551           Dia << DeducedDecl->getInit()->getSourceRange();
13552         if (D->getInit())
13553           Dia << D->getInit()->getSourceRange();
13554         D->setInvalidDecl();
13555         break;
13556       }
13557     }
13558   }
13559 
13560   ActOnDocumentableDecls(Group);
13561 
13562   return DeclGroupPtrTy::make(
13563       DeclGroupRef::Create(Context, Group.data(), Group.size()));
13564 }
13565 
13566 void Sema::ActOnDocumentableDecl(Decl *D) {
13567   ActOnDocumentableDecls(D);
13568 }
13569 
13570 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13571   // Don't parse the comment if Doxygen diagnostics are ignored.
13572   if (Group.empty() || !Group[0])
13573     return;
13574 
13575   if (Diags.isIgnored(diag::warn_doc_param_not_found,
13576                       Group[0]->getLocation()) &&
13577       Diags.isIgnored(diag::warn_unknown_comment_command_name,
13578                       Group[0]->getLocation()))
13579     return;
13580 
13581   if (Group.size() >= 2) {
13582     // This is a decl group.  Normally it will contain only declarations
13583     // produced from declarator list.  But in case we have any definitions or
13584     // additional declaration references:
13585     //   'typedef struct S {} S;'
13586     //   'typedef struct S *S;'
13587     //   'struct S *pS;'
13588     // FinalizeDeclaratorGroup adds these as separate declarations.
13589     Decl *MaybeTagDecl = Group[0];
13590     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13591       Group = Group.slice(1);
13592     }
13593   }
13594 
13595   // FIMXE: We assume every Decl in the group is in the same file.
13596   // This is false when preprocessor constructs the group from decls in
13597   // different files (e. g. macros or #include).
13598   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13599 }
13600 
13601 /// Common checks for a parameter-declaration that should apply to both function
13602 /// parameters and non-type template parameters.
13603 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13604   // Check that there are no default arguments inside the type of this
13605   // parameter.
13606   if (getLangOpts().CPlusPlus)
13607     CheckExtraCXXDefaultArguments(D);
13608 
13609   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13610   if (D.getCXXScopeSpec().isSet()) {
13611     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13612       << D.getCXXScopeSpec().getRange();
13613   }
13614 
13615   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13616   // simple identifier except [...irrelevant cases...].
13617   switch (D.getName().getKind()) {
13618   case UnqualifiedIdKind::IK_Identifier:
13619     break;
13620 
13621   case UnqualifiedIdKind::IK_OperatorFunctionId:
13622   case UnqualifiedIdKind::IK_ConversionFunctionId:
13623   case UnqualifiedIdKind::IK_LiteralOperatorId:
13624   case UnqualifiedIdKind::IK_ConstructorName:
13625   case UnqualifiedIdKind::IK_DestructorName:
13626   case UnqualifiedIdKind::IK_ImplicitSelfParam:
13627   case UnqualifiedIdKind::IK_DeductionGuideName:
13628     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13629       << GetNameForDeclarator(D).getName();
13630     break;
13631 
13632   case UnqualifiedIdKind::IK_TemplateId:
13633   case UnqualifiedIdKind::IK_ConstructorTemplateId:
13634     // GetNameForDeclarator would not produce a useful name in this case.
13635     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13636     break;
13637   }
13638 }
13639 
13640 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13641 /// to introduce parameters into function prototype scope.
13642 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13643   const DeclSpec &DS = D.getDeclSpec();
13644 
13645   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13646 
13647   // C++03 [dcl.stc]p2 also permits 'auto'.
13648   StorageClass SC = SC_None;
13649   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13650     SC = SC_Register;
13651     // In C++11, the 'register' storage class specifier is deprecated.
13652     // In C++17, it is not allowed, but we tolerate it as an extension.
13653     if (getLangOpts().CPlusPlus11) {
13654       Diag(DS.getStorageClassSpecLoc(),
13655            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13656                                      : diag::warn_deprecated_register)
13657         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13658     }
13659   } else if (getLangOpts().CPlusPlus &&
13660              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13661     SC = SC_Auto;
13662   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13663     Diag(DS.getStorageClassSpecLoc(),
13664          diag::err_invalid_storage_class_in_func_decl);
13665     D.getMutableDeclSpec().ClearStorageClassSpecs();
13666   }
13667 
13668   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13669     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13670       << DeclSpec::getSpecifierName(TSCS);
13671   if (DS.isInlineSpecified())
13672     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13673         << getLangOpts().CPlusPlus17;
13674   if (DS.hasConstexprSpecifier())
13675     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13676         << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
13677 
13678   DiagnoseFunctionSpecifiers(DS);
13679 
13680   CheckFunctionOrTemplateParamDeclarator(S, D);
13681 
13682   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13683   QualType parmDeclType = TInfo->getType();
13684 
13685   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13686   IdentifierInfo *II = D.getIdentifier();
13687   if (II) {
13688     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13689                    ForVisibleRedeclaration);
13690     LookupName(R, S);
13691     if (R.isSingleResult()) {
13692       NamedDecl *PrevDecl = R.getFoundDecl();
13693       if (PrevDecl->isTemplateParameter()) {
13694         // Maybe we will complain about the shadowed template parameter.
13695         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13696         // Just pretend that we didn't see the previous declaration.
13697         PrevDecl = nullptr;
13698       } else if (S->isDeclScope(PrevDecl)) {
13699         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13700         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13701 
13702         // Recover by removing the name
13703         II = nullptr;
13704         D.SetIdentifier(nullptr, D.getIdentifierLoc());
13705         D.setInvalidType(true);
13706       }
13707     }
13708   }
13709 
13710   // Temporarily put parameter variables in the translation unit, not
13711   // the enclosing context.  This prevents them from accidentally
13712   // looking like class members in C++.
13713   ParmVarDecl *New =
13714       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13715                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13716 
13717   if (D.isInvalidType())
13718     New->setInvalidDecl();
13719 
13720   assert(S->isFunctionPrototypeScope());
13721   assert(S->getFunctionPrototypeDepth() >= 1);
13722   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13723                     S->getNextFunctionPrototypeIndex());
13724 
13725   // Add the parameter declaration into this scope.
13726   S->AddDecl(New);
13727   if (II)
13728     IdResolver.AddDecl(New);
13729 
13730   ProcessDeclAttributes(S, New, D);
13731 
13732   if (D.getDeclSpec().isModulePrivateSpecified())
13733     Diag(New->getLocation(), diag::err_module_private_local)
13734         << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13735         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13736 
13737   if (New->hasAttr<BlocksAttr>()) {
13738     Diag(New->getLocation(), diag::err_block_on_nonlocal);
13739   }
13740 
13741   if (getLangOpts().OpenCL)
13742     deduceOpenCLAddressSpace(New);
13743 
13744   return New;
13745 }
13746 
13747 /// Synthesizes a variable for a parameter arising from a
13748 /// typedef.
13749 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13750                                               SourceLocation Loc,
13751                                               QualType T) {
13752   /* FIXME: setting StartLoc == Loc.
13753      Would it be worth to modify callers so as to provide proper source
13754      location for the unnamed parameters, embedding the parameter's type? */
13755   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13756                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
13757                                            SC_None, nullptr);
13758   Param->setImplicit();
13759   return Param;
13760 }
13761 
13762 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13763   // Don't diagnose unused-parameter errors in template instantiations; we
13764   // will already have done so in the template itself.
13765   if (inTemplateInstantiation())
13766     return;
13767 
13768   for (const ParmVarDecl *Parameter : Parameters) {
13769     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13770         !Parameter->hasAttr<UnusedAttr>()) {
13771       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13772         << Parameter->getDeclName();
13773     }
13774   }
13775 }
13776 
13777 void Sema::DiagnoseSizeOfParametersAndReturnValue(
13778     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13779   if (LangOpts.NumLargeByValueCopy == 0) // No check.
13780     return;
13781 
13782   // Warn if the return value is pass-by-value and larger than the specified
13783   // threshold.
13784   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13785     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13786     if (Size > LangOpts.NumLargeByValueCopy)
13787       Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
13788   }
13789 
13790   // Warn if any parameter is pass-by-value and larger than the specified
13791   // threshold.
13792   for (const ParmVarDecl *Parameter : Parameters) {
13793     QualType T = Parameter->getType();
13794     if (T->isDependentType() || !T.isPODType(Context))
13795       continue;
13796     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13797     if (Size > LangOpts.NumLargeByValueCopy)
13798       Diag(Parameter->getLocation(), diag::warn_parameter_size)
13799           << Parameter << Size;
13800   }
13801 }
13802 
13803 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13804                                   SourceLocation NameLoc, IdentifierInfo *Name,
13805                                   QualType T, TypeSourceInfo *TSInfo,
13806                                   StorageClass SC) {
13807   // In ARC, infer a lifetime qualifier for appropriate parameter types.
13808   if (getLangOpts().ObjCAutoRefCount &&
13809       T.getObjCLifetime() == Qualifiers::OCL_None &&
13810       T->isObjCLifetimeType()) {
13811 
13812     Qualifiers::ObjCLifetime lifetime;
13813 
13814     // Special cases for arrays:
13815     //   - if it's const, use __unsafe_unretained
13816     //   - otherwise, it's an error
13817     if (T->isArrayType()) {
13818       if (!T.isConstQualified()) {
13819         if (DelayedDiagnostics.shouldDelayDiagnostics())
13820           DelayedDiagnostics.add(
13821               sema::DelayedDiagnostic::makeForbiddenType(
13822               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13823         else
13824           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13825               << TSInfo->getTypeLoc().getSourceRange();
13826       }
13827       lifetime = Qualifiers::OCL_ExplicitNone;
13828     } else {
13829       lifetime = T->getObjCARCImplicitLifetime();
13830     }
13831     T = Context.getLifetimeQualifiedType(T, lifetime);
13832   }
13833 
13834   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13835                                          Context.getAdjustedParameterType(T),
13836                                          TSInfo, SC, nullptr);
13837 
13838   // Make a note if we created a new pack in the scope of a lambda, so that
13839   // we know that references to that pack must also be expanded within the
13840   // lambda scope.
13841   if (New->isParameterPack())
13842     if (auto *LSI = getEnclosingLambda())
13843       LSI->LocalPacks.push_back(New);
13844 
13845   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13846       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13847     checkNonTrivialCUnion(New->getType(), New->getLocation(),
13848                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13849 
13850   // Parameters can not be abstract class types.
13851   // For record types, this is done by the AbstractClassUsageDiagnoser once
13852   // the class has been completely parsed.
13853   if (!CurContext->isRecord() &&
13854       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13855                              AbstractParamType))
13856     New->setInvalidDecl();
13857 
13858   // Parameter declarators cannot be interface types. All ObjC objects are
13859   // passed by reference.
13860   if (T->isObjCObjectType()) {
13861     SourceLocation TypeEndLoc =
13862         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13863     Diag(NameLoc,
13864          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13865       << FixItHint::CreateInsertion(TypeEndLoc, "*");
13866     T = Context.getObjCObjectPointerType(T);
13867     New->setType(T);
13868   }
13869 
13870   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13871   // duration shall not be qualified by an address-space qualifier."
13872   // Since all parameters have automatic store duration, they can not have
13873   // an address space.
13874   if (T.getAddressSpace() != LangAS::Default &&
13875       // OpenCL allows function arguments declared to be an array of a type
13876       // to be qualified with an address space.
13877       !(getLangOpts().OpenCL &&
13878         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13879     Diag(NameLoc, diag::err_arg_with_address_space);
13880     New->setInvalidDecl();
13881   }
13882 
13883   // PPC MMA non-pointer types are not allowed as function argument types.
13884   if (Context.getTargetInfo().getTriple().isPPC64() &&
13885       CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
13886     New->setInvalidDecl();
13887   }
13888 
13889   return New;
13890 }
13891 
13892 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
13893                                            SourceLocation LocAfterDecls) {
13894   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
13895 
13896   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
13897   // for a K&R function.
13898   if (!FTI.hasPrototype) {
13899     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
13900       --i;
13901       if (FTI.Params[i].Param == nullptr) {
13902         SmallString<256> Code;
13903         llvm::raw_svector_ostream(Code)
13904             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
13905         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
13906             << FTI.Params[i].Ident
13907             << FixItHint::CreateInsertion(LocAfterDecls, Code);
13908 
13909         // Implicitly declare the argument as type 'int' for lack of a better
13910         // type.
13911         AttributeFactory attrs;
13912         DeclSpec DS(attrs);
13913         const char* PrevSpec; // unused
13914         unsigned DiagID; // unused
13915         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
13916                            DiagID, Context.getPrintingPolicy());
13917         // Use the identifier location for the type source range.
13918         DS.SetRangeStart(FTI.Params[i].IdentLoc);
13919         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
13920         Declarator ParamD(DS, DeclaratorContext::KNRTypeList);
13921         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
13922         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
13923       }
13924     }
13925   }
13926 }
13927 
13928 Decl *
13929 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
13930                               MultiTemplateParamsArg TemplateParameterLists,
13931                               SkipBodyInfo *SkipBody) {
13932   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
13933   assert(D.isFunctionDeclarator() && "Not a function declarator!");
13934   Scope *ParentScope = FnBodyScope->getParent();
13935 
13936   // Check if we are in an `omp begin/end declare variant` scope. If we are, and
13937   // we define a non-templated function definition, we will create a declaration
13938   // instead (=BaseFD), and emit the definition with a mangled name afterwards.
13939   // The base function declaration will have the equivalent of an `omp declare
13940   // variant` annotation which specifies the mangled definition as a
13941   // specialization function under the OpenMP context defined as part of the
13942   // `omp begin declare variant`.
13943   SmallVector<FunctionDecl *, 4> Bases;
13944   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
13945     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
13946         ParentScope, D, TemplateParameterLists, Bases);
13947 
13948   D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
13949   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
13950   Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
13951 
13952   if (!Bases.empty())
13953     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
13954 
13955   return Dcl;
13956 }
13957 
13958 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
13959   Consumer.HandleInlineFunctionDefinition(D);
13960 }
13961 
13962 static bool
13963 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
13964                                 const FunctionDecl *&PossiblePrototype) {
13965   // Don't warn about invalid declarations.
13966   if (FD->isInvalidDecl())
13967     return false;
13968 
13969   // Or declarations that aren't global.
13970   if (!FD->isGlobal())
13971     return false;
13972 
13973   // Don't warn about C++ member functions.
13974   if (isa<CXXMethodDecl>(FD))
13975     return false;
13976 
13977   // Don't warn about 'main'.
13978   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
13979     if (IdentifierInfo *II = FD->getIdentifier())
13980       if (II->isStr("main") || II->isStr("efi_main"))
13981         return false;
13982 
13983   // Don't warn about inline functions.
13984   if (FD->isInlined())
13985     return false;
13986 
13987   // Don't warn about function templates.
13988   if (FD->getDescribedFunctionTemplate())
13989     return false;
13990 
13991   // Don't warn about function template specializations.
13992   if (FD->isFunctionTemplateSpecialization())
13993     return false;
13994 
13995   // Don't warn for OpenCL kernels.
13996   if (FD->hasAttr<OpenCLKernelAttr>())
13997     return false;
13998 
13999   // Don't warn on explicitly deleted functions.
14000   if (FD->isDeleted())
14001     return false;
14002 
14003   for (const FunctionDecl *Prev = FD->getPreviousDecl();
14004        Prev; Prev = Prev->getPreviousDecl()) {
14005     // Ignore any declarations that occur in function or method
14006     // scope, because they aren't visible from the header.
14007     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
14008       continue;
14009 
14010     PossiblePrototype = Prev;
14011     return Prev->getType()->isFunctionNoProtoType();
14012   }
14013 
14014   return true;
14015 }
14016 
14017 void
14018 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
14019                                    const FunctionDecl *EffectiveDefinition,
14020                                    SkipBodyInfo *SkipBody) {
14021   const FunctionDecl *Definition = EffectiveDefinition;
14022   if (!Definition &&
14023       !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
14024     return;
14025 
14026   if (Definition->getFriendObjectKind() != Decl::FOK_None) {
14027     if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
14028       if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
14029         // A merged copy of the same function, instantiated as a member of
14030         // the same class, is OK.
14031         if (declaresSameEntity(OrigFD, OrigDef) &&
14032             declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
14033                                cast<Decl>(FD->getLexicalDeclContext())))
14034           return;
14035       }
14036     }
14037   }
14038 
14039   if (canRedefineFunction(Definition, getLangOpts()))
14040     return;
14041 
14042   // Don't emit an error when this is redefinition of a typo-corrected
14043   // definition.
14044   if (TypoCorrectedFunctionDefinitions.count(Definition))
14045     return;
14046 
14047   // If we don't have a visible definition of the function, and it's inline or
14048   // a template, skip the new definition.
14049   if (SkipBody && !hasVisibleDefinition(Definition) &&
14050       (Definition->getFormalLinkage() == InternalLinkage ||
14051        Definition->isInlined() ||
14052        Definition->getDescribedFunctionTemplate() ||
14053        Definition->getNumTemplateParameterLists())) {
14054     SkipBody->ShouldSkip = true;
14055     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
14056     if (auto *TD = Definition->getDescribedFunctionTemplate())
14057       makeMergedDefinitionVisible(TD);
14058     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
14059     return;
14060   }
14061 
14062   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
14063       Definition->getStorageClass() == SC_Extern)
14064     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
14065         << FD << getLangOpts().CPlusPlus;
14066   else
14067     Diag(FD->getLocation(), diag::err_redefinition) << FD;
14068 
14069   Diag(Definition->getLocation(), diag::note_previous_definition);
14070   FD->setInvalidDecl();
14071 }
14072 
14073 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
14074                                    Sema &S) {
14075   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
14076 
14077   LambdaScopeInfo *LSI = S.PushLambdaScope();
14078   LSI->CallOperator = CallOperator;
14079   LSI->Lambda = LambdaClass;
14080   LSI->ReturnType = CallOperator->getReturnType();
14081   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
14082 
14083   if (LCD == LCD_None)
14084     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
14085   else if (LCD == LCD_ByCopy)
14086     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
14087   else if (LCD == LCD_ByRef)
14088     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
14089   DeclarationNameInfo DNI = CallOperator->getNameInfo();
14090 
14091   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
14092   LSI->Mutable = !CallOperator->isConst();
14093 
14094   // Add the captures to the LSI so they can be noted as already
14095   // captured within tryCaptureVar.
14096   auto I = LambdaClass->field_begin();
14097   for (const auto &C : LambdaClass->captures()) {
14098     if (C.capturesVariable()) {
14099       VarDecl *VD = C.getCapturedVar();
14100       if (VD->isInitCapture())
14101         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
14102       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
14103       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
14104           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
14105           /*EllipsisLoc*/C.isPackExpansion()
14106                          ? C.getEllipsisLoc() : SourceLocation(),
14107           I->getType(), /*Invalid*/false);
14108 
14109     } else if (C.capturesThis()) {
14110       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
14111                           C.getCaptureKind() == LCK_StarThis);
14112     } else {
14113       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
14114                              I->getType());
14115     }
14116     ++I;
14117   }
14118 }
14119 
14120 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
14121                                     SkipBodyInfo *SkipBody) {
14122   if (!D) {
14123     // Parsing the function declaration failed in some way. Push on a fake scope
14124     // anyway so we can try to parse the function body.
14125     PushFunctionScope();
14126     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14127     return D;
14128   }
14129 
14130   FunctionDecl *FD = nullptr;
14131 
14132   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
14133     FD = FunTmpl->getTemplatedDecl();
14134   else
14135     FD = cast<FunctionDecl>(D);
14136 
14137   // Do not push if it is a lambda because one is already pushed when building
14138   // the lambda in ActOnStartOfLambdaDefinition().
14139   if (!isLambdaCallOperator(FD))
14140     PushExpressionEvaluationContext(
14141         FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
14142                           : ExprEvalContexts.back().Context);
14143 
14144   // Check for defining attributes before the check for redefinition.
14145   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
14146     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
14147     FD->dropAttr<AliasAttr>();
14148     FD->setInvalidDecl();
14149   }
14150   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
14151     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
14152     FD->dropAttr<IFuncAttr>();
14153     FD->setInvalidDecl();
14154   }
14155 
14156   if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
14157     if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
14158         Ctor->isDefaultConstructor() &&
14159         Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14160       // If this is an MS ABI dllexport default constructor, instantiate any
14161       // default arguments.
14162       InstantiateDefaultCtorDefaultArgs(Ctor);
14163     }
14164   }
14165 
14166   // See if this is a redefinition. If 'will have body' (or similar) is already
14167   // set, then these checks were already performed when it was set.
14168   if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
14169       !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
14170     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14171 
14172     // If we're skipping the body, we're done. Don't enter the scope.
14173     if (SkipBody && SkipBody->ShouldSkip)
14174       return D;
14175   }
14176 
14177   // Mark this function as "will have a body eventually".  This lets users to
14178   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14179   // this function.
14180   FD->setWillHaveBody();
14181 
14182   // If we are instantiating a generic lambda call operator, push
14183   // a LambdaScopeInfo onto the function stack.  But use the information
14184   // that's already been calculated (ActOnLambdaExpr) to prime the current
14185   // LambdaScopeInfo.
14186   // When the template operator is being specialized, the LambdaScopeInfo,
14187   // has to be properly restored so that tryCaptureVariable doesn't try
14188   // and capture any new variables. In addition when calculating potential
14189   // captures during transformation of nested lambdas, it is necessary to
14190   // have the LSI properly restored.
14191   if (isGenericLambdaCallOperatorSpecialization(FD)) {
14192     assert(inTemplateInstantiation() &&
14193            "There should be an active template instantiation on the stack "
14194            "when instantiating a generic lambda!");
14195     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14196   } else {
14197     // Enter a new function scope
14198     PushFunctionScope();
14199   }
14200 
14201   // Builtin functions cannot be defined.
14202   if (unsigned BuiltinID = FD->getBuiltinID()) {
14203     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14204         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14205       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14206       FD->setInvalidDecl();
14207     }
14208   }
14209 
14210   // The return type of a function definition must be complete
14211   // (C99 6.9.1p3, C++ [dcl.fct]p6).
14212   QualType ResultType = FD->getReturnType();
14213   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14214       !FD->isInvalidDecl() &&
14215       RequireCompleteType(FD->getLocation(), ResultType,
14216                           diag::err_func_def_incomplete_result))
14217     FD->setInvalidDecl();
14218 
14219   if (FnBodyScope)
14220     PushDeclContext(FnBodyScope, FD);
14221 
14222   // Check the validity of our function parameters
14223   CheckParmsForFunctionDef(FD->parameters(),
14224                            /*CheckParameterNames=*/true);
14225 
14226   // Add non-parameter declarations already in the function to the current
14227   // scope.
14228   if (FnBodyScope) {
14229     for (Decl *NPD : FD->decls()) {
14230       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14231       if (!NonParmDecl)
14232         continue;
14233       assert(!isa<ParmVarDecl>(NonParmDecl) &&
14234              "parameters should not be in newly created FD yet");
14235 
14236       // If the decl has a name, make it accessible in the current scope.
14237       if (NonParmDecl->getDeclName())
14238         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14239 
14240       // Similarly, dive into enums and fish their constants out, making them
14241       // accessible in this scope.
14242       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14243         for (auto *EI : ED->enumerators())
14244           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14245       }
14246     }
14247   }
14248 
14249   // Introduce our parameters into the function scope
14250   for (auto Param : FD->parameters()) {
14251     Param->setOwningFunction(FD);
14252 
14253     // If this has an identifier, add it to the scope stack.
14254     if (Param->getIdentifier() && FnBodyScope) {
14255       CheckShadow(FnBodyScope, Param);
14256 
14257       PushOnScopeChains(Param, FnBodyScope);
14258     }
14259   }
14260 
14261   // Ensure that the function's exception specification is instantiated.
14262   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14263     ResolveExceptionSpec(D->getLocation(), FPT);
14264 
14265   // dllimport cannot be applied to non-inline function definitions.
14266   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14267       !FD->isTemplateInstantiation()) {
14268     assert(!FD->hasAttr<DLLExportAttr>());
14269     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14270     FD->setInvalidDecl();
14271     return D;
14272   }
14273   // We want to attach documentation to original Decl (which might be
14274   // a function template).
14275   ActOnDocumentableDecl(D);
14276   if (getCurLexicalContext()->isObjCContainer() &&
14277       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14278       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14279     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14280 
14281   return D;
14282 }
14283 
14284 /// Given the set of return statements within a function body,
14285 /// compute the variables that are subject to the named return value
14286 /// optimization.
14287 ///
14288 /// Each of the variables that is subject to the named return value
14289 /// optimization will be marked as NRVO variables in the AST, and any
14290 /// return statement that has a marked NRVO variable as its NRVO candidate can
14291 /// use the named return value optimization.
14292 ///
14293 /// This function applies a very simplistic algorithm for NRVO: if every return
14294 /// statement in the scope of a variable has the same NRVO candidate, that
14295 /// candidate is an NRVO variable.
14296 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14297   ReturnStmt **Returns = Scope->Returns.data();
14298 
14299   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14300     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14301       if (!NRVOCandidate->isNRVOVariable())
14302         Returns[I]->setNRVOCandidate(nullptr);
14303     }
14304   }
14305 }
14306 
14307 bool Sema::canDelayFunctionBody(const Declarator &D) {
14308   // We can't delay parsing the body of a constexpr function template (yet).
14309   if (D.getDeclSpec().hasConstexprSpecifier())
14310     return false;
14311 
14312   // We can't delay parsing the body of a function template with a deduced
14313   // return type (yet).
14314   if (D.getDeclSpec().hasAutoTypeSpec()) {
14315     // If the placeholder introduces a non-deduced trailing return type,
14316     // we can still delay parsing it.
14317     if (D.getNumTypeObjects()) {
14318       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14319       if (Outer.Kind == DeclaratorChunk::Function &&
14320           Outer.Fun.hasTrailingReturnType()) {
14321         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14322         return Ty.isNull() || !Ty->isUndeducedType();
14323       }
14324     }
14325     return false;
14326   }
14327 
14328   return true;
14329 }
14330 
14331 bool Sema::canSkipFunctionBody(Decl *D) {
14332   // We cannot skip the body of a function (or function template) which is
14333   // constexpr, since we may need to evaluate its body in order to parse the
14334   // rest of the file.
14335   // We cannot skip the body of a function with an undeduced return type,
14336   // because any callers of that function need to know the type.
14337   if (const FunctionDecl *FD = D->getAsFunction()) {
14338     if (FD->isConstexpr())
14339       return false;
14340     // We can't simply call Type::isUndeducedType here, because inside template
14341     // auto can be deduced to a dependent type, which is not considered
14342     // "undeduced".
14343     if (FD->getReturnType()->getContainedDeducedType())
14344       return false;
14345   }
14346   return Consumer.shouldSkipFunctionBody(D);
14347 }
14348 
14349 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14350   if (!Decl)
14351     return nullptr;
14352   if (FunctionDecl *FD = Decl->getAsFunction())
14353     FD->setHasSkippedBody();
14354   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14355     MD->setHasSkippedBody();
14356   return Decl;
14357 }
14358 
14359 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14360   return ActOnFinishFunctionBody(D, BodyArg, false);
14361 }
14362 
14363 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
14364 /// body.
14365 class ExitFunctionBodyRAII {
14366 public:
14367   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14368   ~ExitFunctionBodyRAII() {
14369     if (!IsLambda)
14370       S.PopExpressionEvaluationContext();
14371   }
14372 
14373 private:
14374   Sema &S;
14375   bool IsLambda = false;
14376 };
14377 
14378 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14379   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14380 
14381   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14382     if (EscapeInfo.count(BD))
14383       return EscapeInfo[BD];
14384 
14385     bool R = false;
14386     const BlockDecl *CurBD = BD;
14387 
14388     do {
14389       R = !CurBD->doesNotEscape();
14390       if (R)
14391         break;
14392       CurBD = CurBD->getParent()->getInnermostBlockDecl();
14393     } while (CurBD);
14394 
14395     return EscapeInfo[BD] = R;
14396   };
14397 
14398   // If the location where 'self' is implicitly retained is inside a escaping
14399   // block, emit a diagnostic.
14400   for (const std::pair<SourceLocation, const BlockDecl *> &P :
14401        S.ImplicitlyRetainedSelfLocs)
14402     if (IsOrNestedInEscapingBlock(P.second))
14403       S.Diag(P.first, diag::warn_implicitly_retains_self)
14404           << FixItHint::CreateInsertion(P.first, "self->");
14405 }
14406 
14407 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14408                                     bool IsInstantiation) {
14409   FunctionScopeInfo *FSI = getCurFunction();
14410   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14411 
14412   if (FSI->UsesFPIntrin && !FD->hasAttr<StrictFPAttr>())
14413     FD->addAttr(StrictFPAttr::CreateImplicit(Context));
14414 
14415   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14416   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14417 
14418   if (getLangOpts().Coroutines && FSI->isCoroutine())
14419     CheckCompletedCoroutineBody(FD, Body);
14420 
14421   // Do not call PopExpressionEvaluationContext() if it is a lambda because one
14422   // is already popped when finishing the lambda in BuildLambdaExpr(). This is
14423   // meant to pop the context added in ActOnStartOfFunctionDef().
14424   ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14425 
14426   if (FD) {
14427     FD->setBody(Body);
14428     FD->setWillHaveBody(false);
14429 
14430     if (getLangOpts().CPlusPlus14) {
14431       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14432           FD->getReturnType()->isUndeducedType()) {
14433         // If the function has a deduced result type but contains no 'return'
14434         // statements, the result type as written must be exactly 'auto', and
14435         // the deduced result type is 'void'.
14436         if (!FD->getReturnType()->getAs<AutoType>()) {
14437           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14438               << FD->getReturnType();
14439           FD->setInvalidDecl();
14440         } else {
14441           // Substitute 'void' for the 'auto' in the type.
14442           TypeLoc ResultType = getReturnTypeLoc(FD);
14443           Context.adjustDeducedFunctionResultType(
14444               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
14445         }
14446       }
14447     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14448       // In C++11, we don't use 'auto' deduction rules for lambda call
14449       // operators because we don't support return type deduction.
14450       auto *LSI = getCurLambda();
14451       if (LSI->HasImplicitReturnType) {
14452         deduceClosureReturnType(*LSI);
14453 
14454         // C++11 [expr.prim.lambda]p4:
14455         //   [...] if there are no return statements in the compound-statement
14456         //   [the deduced type is] the type void
14457         QualType RetType =
14458             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14459 
14460         // Update the return type to the deduced type.
14461         const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14462         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14463                                             Proto->getExtProtoInfo()));
14464       }
14465     }
14466 
14467     // If the function implicitly returns zero (like 'main') or is naked,
14468     // don't complain about missing return statements.
14469     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14470       WP.disableCheckFallThrough();
14471 
14472     // MSVC permits the use of pure specifier (=0) on function definition,
14473     // defined at class scope, warn about this non-standard construct.
14474     if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14475       Diag(FD->getLocation(), diag::ext_pure_function_definition);
14476 
14477     if (!FD->isInvalidDecl()) {
14478       // Don't diagnose unused parameters of defaulted or deleted functions.
14479       if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
14480         DiagnoseUnusedParameters(FD->parameters());
14481       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14482                                              FD->getReturnType(), FD);
14483 
14484       // If this is a structor, we need a vtable.
14485       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14486         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14487       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
14488         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14489 
14490       // Try to apply the named return value optimization. We have to check
14491       // if we can do this here because lambdas keep return statements around
14492       // to deduce an implicit return type.
14493       if (FD->getReturnType()->isRecordType() &&
14494           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14495         computeNRVO(Body, FSI);
14496     }
14497 
14498     // GNU warning -Wmissing-prototypes:
14499     //   Warn if a global function is defined without a previous
14500     //   prototype declaration. This warning is issued even if the
14501     //   definition itself provides a prototype. The aim is to detect
14502     //   global functions that fail to be declared in header files.
14503     const FunctionDecl *PossiblePrototype = nullptr;
14504     if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14505       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14506 
14507       if (PossiblePrototype) {
14508         // We found a declaration that is not a prototype,
14509         // but that could be a zero-parameter prototype
14510         if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14511           TypeLoc TL = TI->getTypeLoc();
14512           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14513             Diag(PossiblePrototype->getLocation(),
14514                  diag::note_declaration_not_a_prototype)
14515                 << (FD->getNumParams() != 0)
14516                 << (FD->getNumParams() == 0
14517                         ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
14518                         : FixItHint{});
14519         }
14520       } else {
14521         // Returns true if the token beginning at this Loc is `const`.
14522         auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
14523                                 const LangOptions &LangOpts) {
14524           std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
14525           if (LocInfo.first.isInvalid())
14526             return false;
14527 
14528           bool Invalid = false;
14529           StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
14530           if (Invalid)
14531             return false;
14532 
14533           if (LocInfo.second > Buffer.size())
14534             return false;
14535 
14536           const char *LexStart = Buffer.data() + LocInfo.second;
14537           StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
14538 
14539           return StartTok.consume_front("const") &&
14540                  (StartTok.empty() || isWhitespace(StartTok[0]) ||
14541                   StartTok.startswith("/*") || StartTok.startswith("//"));
14542         };
14543 
14544         auto findBeginLoc = [&]() {
14545           // If the return type has `const` qualifier, we want to insert
14546           // `static` before `const` (and not before the typename).
14547           if ((FD->getReturnType()->isAnyPointerType() &&
14548                FD->getReturnType()->getPointeeType().isConstQualified()) ||
14549               FD->getReturnType().isConstQualified()) {
14550             // But only do this if we can determine where the `const` is.
14551 
14552             if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
14553                              getLangOpts()))
14554 
14555               return FD->getBeginLoc();
14556           }
14557           return FD->getTypeSpecStartLoc();
14558         };
14559         Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14560             << /* function */ 1
14561             << (FD->getStorageClass() == SC_None
14562                     ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
14563                     : FixItHint{});
14564       }
14565 
14566       // GNU warning -Wstrict-prototypes
14567       //   Warn if K&R function is defined without a previous declaration.
14568       //   This warning is issued only if the definition itself does not provide
14569       //   a prototype. Only K&R definitions do not provide a prototype.
14570       if (!FD->hasWrittenPrototype()) {
14571         TypeSourceInfo *TI = FD->getTypeSourceInfo();
14572         TypeLoc TL = TI->getTypeLoc();
14573         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
14574         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14575       }
14576     }
14577 
14578     // Warn on CPUDispatch with an actual body.
14579     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14580       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14581         if (!CmpndBody->body_empty())
14582           Diag(CmpndBody->body_front()->getBeginLoc(),
14583                diag::warn_dispatch_body_ignored);
14584 
14585     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14586       const CXXMethodDecl *KeyFunction;
14587       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14588           MD->isVirtual() &&
14589           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14590           MD == KeyFunction->getCanonicalDecl()) {
14591         // Update the key-function state if necessary for this ABI.
14592         if (FD->isInlined() &&
14593             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14594           Context.setNonKeyFunction(MD);
14595 
14596           // If the newly-chosen key function is already defined, then we
14597           // need to mark the vtable as used retroactively.
14598           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14599           const FunctionDecl *Definition;
14600           if (KeyFunction && KeyFunction->isDefined(Definition))
14601             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14602         } else {
14603           // We just defined they key function; mark the vtable as used.
14604           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14605         }
14606       }
14607     }
14608 
14609     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
14610            "Function parsing confused");
14611   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14612     assert(MD == getCurMethodDecl() && "Method parsing confused");
14613     MD->setBody(Body);
14614     if (!MD->isInvalidDecl()) {
14615       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14616                                              MD->getReturnType(), MD);
14617 
14618       if (Body)
14619         computeNRVO(Body, FSI);
14620     }
14621     if (FSI->ObjCShouldCallSuper) {
14622       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14623           << MD->getSelector().getAsString();
14624       FSI->ObjCShouldCallSuper = false;
14625     }
14626     if (FSI->ObjCWarnForNoDesignatedInitChain) {
14627       const ObjCMethodDecl *InitMethod = nullptr;
14628       bool isDesignated =
14629           MD->isDesignatedInitializerForTheInterface(&InitMethod);
14630       assert(isDesignated && InitMethod);
14631       (void)isDesignated;
14632 
14633       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14634         auto IFace = MD->getClassInterface();
14635         if (!IFace)
14636           return false;
14637         auto SuperD = IFace->getSuperClass();
14638         if (!SuperD)
14639           return false;
14640         return SuperD->getIdentifier() ==
14641             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14642       };
14643       // Don't issue this warning for unavailable inits or direct subclasses
14644       // of NSObject.
14645       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14646         Diag(MD->getLocation(),
14647              diag::warn_objc_designated_init_missing_super_call);
14648         Diag(InitMethod->getLocation(),
14649              diag::note_objc_designated_init_marked_here);
14650       }
14651       FSI->ObjCWarnForNoDesignatedInitChain = false;
14652     }
14653     if (FSI->ObjCWarnForNoInitDelegation) {
14654       // Don't issue this warning for unavaialable inits.
14655       if (!MD->isUnavailable())
14656         Diag(MD->getLocation(),
14657              diag::warn_objc_secondary_init_missing_init_call);
14658       FSI->ObjCWarnForNoInitDelegation = false;
14659     }
14660 
14661     diagnoseImplicitlyRetainedSelf(*this);
14662   } else {
14663     // Parsing the function declaration failed in some way. Pop the fake scope
14664     // we pushed on.
14665     PopFunctionScopeInfo(ActivePolicy, dcl);
14666     return nullptr;
14667   }
14668 
14669   if (Body && FSI->HasPotentialAvailabilityViolations)
14670     DiagnoseUnguardedAvailabilityViolations(dcl);
14671 
14672   assert(!FSI->ObjCShouldCallSuper &&
14673          "This should only be set for ObjC methods, which should have been "
14674          "handled in the block above.");
14675 
14676   // Verify and clean out per-function state.
14677   if (Body && (!FD || !FD->isDefaulted())) {
14678     // C++ constructors that have function-try-blocks can't have return
14679     // statements in the handlers of that block. (C++ [except.handle]p14)
14680     // Verify this.
14681     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14682       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14683 
14684     // Verify that gotos and switch cases don't jump into scopes illegally.
14685     if (FSI->NeedsScopeChecking() &&
14686         !PP.isCodeCompletionEnabled())
14687       DiagnoseInvalidJumps(Body);
14688 
14689     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14690       if (!Destructor->getParent()->isDependentType())
14691         CheckDestructor(Destructor);
14692 
14693       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14694                                              Destructor->getParent());
14695     }
14696 
14697     // If any errors have occurred, clear out any temporaries that may have
14698     // been leftover. This ensures that these temporaries won't be picked up for
14699     // deletion in some later function.
14700     if (hasUncompilableErrorOccurred() ||
14701         getDiagnostics().getSuppressAllDiagnostics()) {
14702       DiscardCleanupsInEvaluationContext();
14703     }
14704     if (!hasUncompilableErrorOccurred() &&
14705         !isa<FunctionTemplateDecl>(dcl)) {
14706       // Since the body is valid, issue any analysis-based warnings that are
14707       // enabled.
14708       ActivePolicy = &WP;
14709     }
14710 
14711     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14712         !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14713       FD->setInvalidDecl();
14714 
14715     if (FD && FD->hasAttr<NakedAttr>()) {
14716       for (const Stmt *S : Body->children()) {
14717         // Allow local register variables without initializer as they don't
14718         // require prologue.
14719         bool RegisterVariables = false;
14720         if (auto *DS = dyn_cast<DeclStmt>(S)) {
14721           for (const auto *Decl : DS->decls()) {
14722             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14723               RegisterVariables =
14724                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14725               if (!RegisterVariables)
14726                 break;
14727             }
14728           }
14729         }
14730         if (RegisterVariables)
14731           continue;
14732         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14733           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14734           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14735           FD->setInvalidDecl();
14736           break;
14737         }
14738       }
14739     }
14740 
14741     assert(ExprCleanupObjects.size() ==
14742                ExprEvalContexts.back().NumCleanupObjects &&
14743            "Leftover temporaries in function");
14744     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
14745     assert(MaybeODRUseExprs.empty() &&
14746            "Leftover expressions for odr-use checking");
14747   }
14748 
14749   if (!IsInstantiation)
14750     PopDeclContext();
14751 
14752   PopFunctionScopeInfo(ActivePolicy, dcl);
14753   // If any errors have occurred, clear out any temporaries that may have
14754   // been leftover. This ensures that these temporaries won't be picked up for
14755   // deletion in some later function.
14756   if (hasUncompilableErrorOccurred()) {
14757     DiscardCleanupsInEvaluationContext();
14758   }
14759 
14760   if (FD && (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
14761     auto ES = getEmissionStatus(FD);
14762     if (ES == Sema::FunctionEmissionStatus::Emitted ||
14763         ES == Sema::FunctionEmissionStatus::Unknown)
14764       DeclsToCheckForDeferredDiags.push_back(FD);
14765   }
14766 
14767   return dcl;
14768 }
14769 
14770 /// When we finish delayed parsing of an attribute, we must attach it to the
14771 /// relevant Decl.
14772 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14773                                        ParsedAttributes &Attrs) {
14774   // Always attach attributes to the underlying decl.
14775   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14776     D = TD->getTemplatedDecl();
14777   ProcessDeclAttributeList(S, D, Attrs);
14778 
14779   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14780     if (Method->isStatic())
14781       checkThisInStaticMemberFunctionAttributes(Method);
14782 }
14783 
14784 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14785 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
14786 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14787                                           IdentifierInfo &II, Scope *S) {
14788   // Find the scope in which the identifier is injected and the corresponding
14789   // DeclContext.
14790   // FIXME: C89 does not say what happens if there is no enclosing block scope.
14791   // In that case, we inject the declaration into the translation unit scope
14792   // instead.
14793   Scope *BlockScope = S;
14794   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14795     BlockScope = BlockScope->getParent();
14796 
14797   Scope *ContextScope = BlockScope;
14798   while (!ContextScope->getEntity())
14799     ContextScope = ContextScope->getParent();
14800   ContextRAII SavedContext(*this, ContextScope->getEntity());
14801 
14802   // Before we produce a declaration for an implicitly defined
14803   // function, see whether there was a locally-scoped declaration of
14804   // this name as a function or variable. If so, use that
14805   // (non-visible) declaration, and complain about it.
14806   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14807   if (ExternCPrev) {
14808     // We still need to inject the function into the enclosing block scope so
14809     // that later (non-call) uses can see it.
14810     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14811 
14812     // C89 footnote 38:
14813     //   If in fact it is not defined as having type "function returning int",
14814     //   the behavior is undefined.
14815     if (!isa<FunctionDecl>(ExternCPrev) ||
14816         !Context.typesAreCompatible(
14817             cast<FunctionDecl>(ExternCPrev)->getType(),
14818             Context.getFunctionNoProtoType(Context.IntTy))) {
14819       Diag(Loc, diag::ext_use_out_of_scope_declaration)
14820           << ExternCPrev << !getLangOpts().C99;
14821       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14822       return ExternCPrev;
14823     }
14824   }
14825 
14826   // Extension in C99.  Legal in C90, but warn about it.
14827   unsigned diag_id;
14828   if (II.getName().startswith("__builtin_"))
14829     diag_id = diag::warn_builtin_unknown;
14830   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14831   else if (getLangOpts().OpenCL)
14832     diag_id = diag::err_opencl_implicit_function_decl;
14833   else if (getLangOpts().C99)
14834     diag_id = diag::ext_implicit_function_decl;
14835   else
14836     diag_id = diag::warn_implicit_function_decl;
14837   Diag(Loc, diag_id) << &II;
14838 
14839   // If we found a prior declaration of this function, don't bother building
14840   // another one. We've already pushed that one into scope, so there's nothing
14841   // more to do.
14842   if (ExternCPrev)
14843     return ExternCPrev;
14844 
14845   // Because typo correction is expensive, only do it if the implicit
14846   // function declaration is going to be treated as an error.
14847   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
14848     TypoCorrection Corrected;
14849     DeclFilterCCC<FunctionDecl> CCC{};
14850     if (S && (Corrected =
14851                   CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
14852                               S, nullptr, CCC, CTK_NonError)))
14853       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
14854                    /*ErrorRecovery*/false);
14855   }
14856 
14857   // Set a Declarator for the implicit definition: int foo();
14858   const char *Dummy;
14859   AttributeFactory attrFactory;
14860   DeclSpec DS(attrFactory);
14861   unsigned DiagID;
14862   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
14863                                   Context.getPrintingPolicy());
14864   (void)Error; // Silence warning.
14865   assert(!Error && "Error setting up implicit decl!");
14866   SourceLocation NoLoc;
14867   Declarator D(DS, DeclaratorContext::Block);
14868   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
14869                                              /*IsAmbiguous=*/false,
14870                                              /*LParenLoc=*/NoLoc,
14871                                              /*Params=*/nullptr,
14872                                              /*NumParams=*/0,
14873                                              /*EllipsisLoc=*/NoLoc,
14874                                              /*RParenLoc=*/NoLoc,
14875                                              /*RefQualifierIsLvalueRef=*/true,
14876                                              /*RefQualifierLoc=*/NoLoc,
14877                                              /*MutableLoc=*/NoLoc, EST_None,
14878                                              /*ESpecRange=*/SourceRange(),
14879                                              /*Exceptions=*/nullptr,
14880                                              /*ExceptionRanges=*/nullptr,
14881                                              /*NumExceptions=*/0,
14882                                              /*NoexceptExpr=*/nullptr,
14883                                              /*ExceptionSpecTokens=*/nullptr,
14884                                              /*DeclsInPrototype=*/None, Loc,
14885                                              Loc, D),
14886                 std::move(DS.getAttributes()), SourceLocation());
14887   D.SetIdentifier(&II, Loc);
14888 
14889   // Insert this function into the enclosing block scope.
14890   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
14891   FD->setImplicit();
14892 
14893   AddKnownFunctionAttributes(FD);
14894 
14895   return FD;
14896 }
14897 
14898 /// If this function is a C++ replaceable global allocation function
14899 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
14900 /// adds any function attributes that we know a priori based on the standard.
14901 ///
14902 /// We need to check for duplicate attributes both here and where user-written
14903 /// attributes are applied to declarations.
14904 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
14905     FunctionDecl *FD) {
14906   if (FD->isInvalidDecl())
14907     return;
14908 
14909   if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
14910       FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
14911     return;
14912 
14913   Optional<unsigned> AlignmentParam;
14914   bool IsNothrow = false;
14915   if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
14916     return;
14917 
14918   // C++2a [basic.stc.dynamic.allocation]p4:
14919   //   An allocation function that has a non-throwing exception specification
14920   //   indicates failure by returning a null pointer value. Any other allocation
14921   //   function never returns a null pointer value and indicates failure only by
14922   //   throwing an exception [...]
14923   if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
14924     FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
14925 
14926   // C++2a [basic.stc.dynamic.allocation]p2:
14927   //   An allocation function attempts to allocate the requested amount of
14928   //   storage. [...] If the request succeeds, the value returned by a
14929   //   replaceable allocation function is a [...] pointer value p0 different
14930   //   from any previously returned value p1 [...]
14931   //
14932   // However, this particular information is being added in codegen,
14933   // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
14934 
14935   // C++2a [basic.stc.dynamic.allocation]p2:
14936   //   An allocation function attempts to allocate the requested amount of
14937   //   storage. If it is successful, it returns the address of the start of a
14938   //   block of storage whose length in bytes is at least as large as the
14939   //   requested size.
14940   if (!FD->hasAttr<AllocSizeAttr>()) {
14941     FD->addAttr(AllocSizeAttr::CreateImplicit(
14942         Context, /*ElemSizeParam=*/ParamIdx(1, FD),
14943         /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
14944   }
14945 
14946   // C++2a [basic.stc.dynamic.allocation]p3:
14947   //   For an allocation function [...], the pointer returned on a successful
14948   //   call shall represent the address of storage that is aligned as follows:
14949   //   (3.1) If the allocation function takes an argument of type
14950   //         std​::​align_­val_­t, the storage will have the alignment
14951   //         specified by the value of this argument.
14952   if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
14953     FD->addAttr(AllocAlignAttr::CreateImplicit(
14954         Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
14955   }
14956 
14957   // FIXME:
14958   // C++2a [basic.stc.dynamic.allocation]p3:
14959   //   For an allocation function [...], the pointer returned on a successful
14960   //   call shall represent the address of storage that is aligned as follows:
14961   //   (3.2) Otherwise, if the allocation function is named operator new[],
14962   //         the storage is aligned for any object that does not have
14963   //         new-extended alignment ([basic.align]) and is no larger than the
14964   //         requested size.
14965   //   (3.3) Otherwise, the storage is aligned for any object that does not
14966   //         have new-extended alignment and is of the requested size.
14967 }
14968 
14969 /// Adds any function attributes that we know a priori based on
14970 /// the declaration of this function.
14971 ///
14972 /// These attributes can apply both to implicitly-declared builtins
14973 /// (like __builtin___printf_chk) or to library-declared functions
14974 /// like NSLog or printf.
14975 ///
14976 /// We need to check for duplicate attributes both here and where user-written
14977 /// attributes are applied to declarations.
14978 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
14979   if (FD->isInvalidDecl())
14980     return;
14981 
14982   // If this is a built-in function, map its builtin attributes to
14983   // actual attributes.
14984   if (unsigned BuiltinID = FD->getBuiltinID()) {
14985     // Handle printf-formatting attributes.
14986     unsigned FormatIdx;
14987     bool HasVAListArg;
14988     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
14989       if (!FD->hasAttr<FormatAttr>()) {
14990         const char *fmt = "printf";
14991         unsigned int NumParams = FD->getNumParams();
14992         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
14993             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
14994           fmt = "NSString";
14995         FD->addAttr(FormatAttr::CreateImplicit(Context,
14996                                                &Context.Idents.get(fmt),
14997                                                FormatIdx+1,
14998                                                HasVAListArg ? 0 : FormatIdx+2,
14999                                                FD->getLocation()));
15000       }
15001     }
15002     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
15003                                              HasVAListArg)) {
15004      if (!FD->hasAttr<FormatAttr>())
15005        FD->addAttr(FormatAttr::CreateImplicit(Context,
15006                                               &Context.Idents.get("scanf"),
15007                                               FormatIdx+1,
15008                                               HasVAListArg ? 0 : FormatIdx+2,
15009                                               FD->getLocation()));
15010     }
15011 
15012     // Handle automatically recognized callbacks.
15013     SmallVector<int, 4> Encoding;
15014     if (!FD->hasAttr<CallbackAttr>() &&
15015         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
15016       FD->addAttr(CallbackAttr::CreateImplicit(
15017           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
15018 
15019     // Mark const if we don't care about errno and that is the only thing
15020     // preventing the function from being const. This allows IRgen to use LLVM
15021     // intrinsics for such functions.
15022     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
15023         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
15024       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15025 
15026     // We make "fma" on some platforms const because we know it does not set
15027     // errno in those environments even though it could set errno based on the
15028     // C standard.
15029     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
15030     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
15031         !FD->hasAttr<ConstAttr>()) {
15032       switch (BuiltinID) {
15033       case Builtin::BI__builtin_fma:
15034       case Builtin::BI__builtin_fmaf:
15035       case Builtin::BI__builtin_fmal:
15036       case Builtin::BIfma:
15037       case Builtin::BIfmaf:
15038       case Builtin::BIfmal:
15039         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15040         break;
15041       default:
15042         break;
15043       }
15044     }
15045 
15046     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
15047         !FD->hasAttr<ReturnsTwiceAttr>())
15048       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
15049                                          FD->getLocation()));
15050     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
15051       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15052     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
15053       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
15054     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
15055       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15056     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
15057         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
15058       // Add the appropriate attribute, depending on the CUDA compilation mode
15059       // and which target the builtin belongs to. For example, during host
15060       // compilation, aux builtins are __device__, while the rest are __host__.
15061       if (getLangOpts().CUDAIsDevice !=
15062           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
15063         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
15064       else
15065         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
15066     }
15067   }
15068 
15069   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
15070 
15071   // If C++ exceptions are enabled but we are told extern "C" functions cannot
15072   // throw, add an implicit nothrow attribute to any extern "C" function we come
15073   // across.
15074   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
15075       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
15076     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
15077     if (!FPT || FPT->getExceptionSpecType() == EST_None)
15078       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15079   }
15080 
15081   IdentifierInfo *Name = FD->getIdentifier();
15082   if (!Name)
15083     return;
15084   if ((!getLangOpts().CPlusPlus &&
15085        FD->getDeclContext()->isTranslationUnit()) ||
15086       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
15087        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
15088        LinkageSpecDecl::lang_c)) {
15089     // Okay: this could be a libc/libm/Objective-C function we know
15090     // about.
15091   } else
15092     return;
15093 
15094   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
15095     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
15096     // target-specific builtins, perhaps?
15097     if (!FD->hasAttr<FormatAttr>())
15098       FD->addAttr(FormatAttr::CreateImplicit(Context,
15099                                              &Context.Idents.get("printf"), 2,
15100                                              Name->isStr("vasprintf") ? 0 : 3,
15101                                              FD->getLocation()));
15102   }
15103 
15104   if (Name->isStr("__CFStringMakeConstantString")) {
15105     // We already have a __builtin___CFStringMakeConstantString,
15106     // but builds that use -fno-constant-cfstrings don't go through that.
15107     if (!FD->hasAttr<FormatArgAttr>())
15108       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
15109                                                 FD->getLocation()));
15110   }
15111 }
15112 
15113 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
15114                                     TypeSourceInfo *TInfo) {
15115   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
15116   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
15117 
15118   if (!TInfo) {
15119     assert(D.isInvalidType() && "no declarator info for valid type");
15120     TInfo = Context.getTrivialTypeSourceInfo(T);
15121   }
15122 
15123   // Scope manipulation handled by caller.
15124   TypedefDecl *NewTD =
15125       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
15126                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
15127 
15128   // Bail out immediately if we have an invalid declaration.
15129   if (D.isInvalidType()) {
15130     NewTD->setInvalidDecl();
15131     return NewTD;
15132   }
15133 
15134   if (D.getDeclSpec().isModulePrivateSpecified()) {
15135     if (CurContext->isFunctionOrMethod())
15136       Diag(NewTD->getLocation(), diag::err_module_private_local)
15137           << 2 << NewTD
15138           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15139           << FixItHint::CreateRemoval(
15140                  D.getDeclSpec().getModulePrivateSpecLoc());
15141     else
15142       NewTD->setModulePrivate();
15143   }
15144 
15145   // C++ [dcl.typedef]p8:
15146   //   If the typedef declaration defines an unnamed class (or
15147   //   enum), the first typedef-name declared by the declaration
15148   //   to be that class type (or enum type) is used to denote the
15149   //   class type (or enum type) for linkage purposes only.
15150   // We need to check whether the type was declared in the declaration.
15151   switch (D.getDeclSpec().getTypeSpecType()) {
15152   case TST_enum:
15153   case TST_struct:
15154   case TST_interface:
15155   case TST_union:
15156   case TST_class: {
15157     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
15158     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15159     break;
15160   }
15161 
15162   default:
15163     break;
15164   }
15165 
15166   return NewTD;
15167 }
15168 
15169 /// Check that this is a valid underlying type for an enum declaration.
15170 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
15171   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15172   QualType T = TI->getType();
15173 
15174   if (T->isDependentType())
15175     return false;
15176 
15177   // This doesn't use 'isIntegralType' despite the error message mentioning
15178   // integral type because isIntegralType would also allow enum types in C.
15179   if (const BuiltinType *BT = T->getAs<BuiltinType>())
15180     if (BT->isInteger())
15181       return false;
15182 
15183   if (T->isExtIntType())
15184     return false;
15185 
15186   return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15187 }
15188 
15189 /// Check whether this is a valid redeclaration of a previous enumeration.
15190 /// \return true if the redeclaration was invalid.
15191 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15192                                   QualType EnumUnderlyingTy, bool IsFixed,
15193                                   const EnumDecl *Prev) {
15194   if (IsScoped != Prev->isScoped()) {
15195     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15196       << Prev->isScoped();
15197     Diag(Prev->getLocation(), diag::note_previous_declaration);
15198     return true;
15199   }
15200 
15201   if (IsFixed && Prev->isFixed()) {
15202     if (!EnumUnderlyingTy->isDependentType() &&
15203         !Prev->getIntegerType()->isDependentType() &&
15204         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15205                                         Prev->getIntegerType())) {
15206       // TODO: Highlight the underlying type of the redeclaration.
15207       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15208         << EnumUnderlyingTy << Prev->getIntegerType();
15209       Diag(Prev->getLocation(), diag::note_previous_declaration)
15210           << Prev->getIntegerTypeRange();
15211       return true;
15212     }
15213   } else if (IsFixed != Prev->isFixed()) {
15214     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15215       << Prev->isFixed();
15216     Diag(Prev->getLocation(), diag::note_previous_declaration);
15217     return true;
15218   }
15219 
15220   return false;
15221 }
15222 
15223 /// Get diagnostic %select index for tag kind for
15224 /// redeclaration diagnostic message.
15225 /// WARNING: Indexes apply to particular diagnostics only!
15226 ///
15227 /// \returns diagnostic %select index.
15228 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15229   switch (Tag) {
15230   case TTK_Struct: return 0;
15231   case TTK_Interface: return 1;
15232   case TTK_Class:  return 2;
15233   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
15234   }
15235 }
15236 
15237 /// Determine if tag kind is a class-key compatible with
15238 /// class for redeclaration (class, struct, or __interface).
15239 ///
15240 /// \returns true iff the tag kind is compatible.
15241 static bool isClassCompatTagKind(TagTypeKind Tag)
15242 {
15243   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15244 }
15245 
15246 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15247                                              TagTypeKind TTK) {
15248   if (isa<TypedefDecl>(PrevDecl))
15249     return NTK_Typedef;
15250   else if (isa<TypeAliasDecl>(PrevDecl))
15251     return NTK_TypeAlias;
15252   else if (isa<ClassTemplateDecl>(PrevDecl))
15253     return NTK_Template;
15254   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15255     return NTK_TypeAliasTemplate;
15256   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15257     return NTK_TemplateTemplateArgument;
15258   switch (TTK) {
15259   case TTK_Struct:
15260   case TTK_Interface:
15261   case TTK_Class:
15262     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15263   case TTK_Union:
15264     return NTK_NonUnion;
15265   case TTK_Enum:
15266     return NTK_NonEnum;
15267   }
15268   llvm_unreachable("invalid TTK");
15269 }
15270 
15271 /// Determine whether a tag with a given kind is acceptable
15272 /// as a redeclaration of the given tag declaration.
15273 ///
15274 /// \returns true if the new tag kind is acceptable, false otherwise.
15275 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15276                                         TagTypeKind NewTag, bool isDefinition,
15277                                         SourceLocation NewTagLoc,
15278                                         const IdentifierInfo *Name) {
15279   // C++ [dcl.type.elab]p3:
15280   //   The class-key or enum keyword present in the
15281   //   elaborated-type-specifier shall agree in kind with the
15282   //   declaration to which the name in the elaborated-type-specifier
15283   //   refers. This rule also applies to the form of
15284   //   elaborated-type-specifier that declares a class-name or
15285   //   friend class since it can be construed as referring to the
15286   //   definition of the class. Thus, in any
15287   //   elaborated-type-specifier, the enum keyword shall be used to
15288   //   refer to an enumeration (7.2), the union class-key shall be
15289   //   used to refer to a union (clause 9), and either the class or
15290   //   struct class-key shall be used to refer to a class (clause 9)
15291   //   declared using the class or struct class-key.
15292   TagTypeKind OldTag = Previous->getTagKind();
15293   if (OldTag != NewTag &&
15294       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15295     return false;
15296 
15297   // Tags are compatible, but we might still want to warn on mismatched tags.
15298   // Non-class tags can't be mismatched at this point.
15299   if (!isClassCompatTagKind(NewTag))
15300     return true;
15301 
15302   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15303   // by our warning analysis. We don't want to warn about mismatches with (eg)
15304   // declarations in system headers that are designed to be specialized, but if
15305   // a user asks us to warn, we should warn if their code contains mismatched
15306   // declarations.
15307   auto IsIgnoredLoc = [&](SourceLocation Loc) {
15308     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15309                                       Loc);
15310   };
15311   if (IsIgnoredLoc(NewTagLoc))
15312     return true;
15313 
15314   auto IsIgnored = [&](const TagDecl *Tag) {
15315     return IsIgnoredLoc(Tag->getLocation());
15316   };
15317   while (IsIgnored(Previous)) {
15318     Previous = Previous->getPreviousDecl();
15319     if (!Previous)
15320       return true;
15321     OldTag = Previous->getTagKind();
15322   }
15323 
15324   bool isTemplate = false;
15325   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15326     isTemplate = Record->getDescribedClassTemplate();
15327 
15328   if (inTemplateInstantiation()) {
15329     if (OldTag != NewTag) {
15330       // In a template instantiation, do not offer fix-its for tag mismatches
15331       // since they usually mess up the template instead of fixing the problem.
15332       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15333         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15334         << getRedeclDiagFromTagKind(OldTag);
15335       // FIXME: Note previous location?
15336     }
15337     return true;
15338   }
15339 
15340   if (isDefinition) {
15341     // On definitions, check all previous tags and issue a fix-it for each
15342     // one that doesn't match the current tag.
15343     if (Previous->getDefinition()) {
15344       // Don't suggest fix-its for redefinitions.
15345       return true;
15346     }
15347 
15348     bool previousMismatch = false;
15349     for (const TagDecl *I : Previous->redecls()) {
15350       if (I->getTagKind() != NewTag) {
15351         // Ignore previous declarations for which the warning was disabled.
15352         if (IsIgnored(I))
15353           continue;
15354 
15355         if (!previousMismatch) {
15356           previousMismatch = true;
15357           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15358             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15359             << getRedeclDiagFromTagKind(I->getTagKind());
15360         }
15361         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15362           << getRedeclDiagFromTagKind(NewTag)
15363           << FixItHint::CreateReplacement(I->getInnerLocStart(),
15364                TypeWithKeyword::getTagTypeKindName(NewTag));
15365       }
15366     }
15367     return true;
15368   }
15369 
15370   // Identify the prevailing tag kind: this is the kind of the definition (if
15371   // there is a non-ignored definition), or otherwise the kind of the prior
15372   // (non-ignored) declaration.
15373   const TagDecl *PrevDef = Previous->getDefinition();
15374   if (PrevDef && IsIgnored(PrevDef))
15375     PrevDef = nullptr;
15376   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15377   if (Redecl->getTagKind() != NewTag) {
15378     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15379       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15380       << getRedeclDiagFromTagKind(OldTag);
15381     Diag(Redecl->getLocation(), diag::note_previous_use);
15382 
15383     // If there is a previous definition, suggest a fix-it.
15384     if (PrevDef) {
15385       Diag(NewTagLoc, diag::note_struct_class_suggestion)
15386         << getRedeclDiagFromTagKind(Redecl->getTagKind())
15387         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15388              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15389     }
15390   }
15391 
15392   return true;
15393 }
15394 
15395 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15396 /// from an outer enclosing namespace or file scope inside a friend declaration.
15397 /// This should provide the commented out code in the following snippet:
15398 ///   namespace N {
15399 ///     struct X;
15400 ///     namespace M {
15401 ///       struct Y { friend struct /*N::*/ X; };
15402 ///     }
15403 ///   }
15404 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
15405                                          SourceLocation NameLoc) {
15406   // While the decl is in a namespace, do repeated lookup of that name and see
15407   // if we get the same namespace back.  If we do not, continue until
15408   // translation unit scope, at which point we have a fully qualified NNS.
15409   SmallVector<IdentifierInfo *, 4> Namespaces;
15410   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15411   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15412     // This tag should be declared in a namespace, which can only be enclosed by
15413     // other namespaces.  Bail if there's an anonymous namespace in the chain.
15414     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15415     if (!Namespace || Namespace->isAnonymousNamespace())
15416       return FixItHint();
15417     IdentifierInfo *II = Namespace->getIdentifier();
15418     Namespaces.push_back(II);
15419     NamedDecl *Lookup = SemaRef.LookupSingleName(
15420         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15421     if (Lookup == Namespace)
15422       break;
15423   }
15424 
15425   // Once we have all the namespaces, reverse them to go outermost first, and
15426   // build an NNS.
15427   SmallString<64> Insertion;
15428   llvm::raw_svector_ostream OS(Insertion);
15429   if (DC->isTranslationUnit())
15430     OS << "::";
15431   std::reverse(Namespaces.begin(), Namespaces.end());
15432   for (auto *II : Namespaces)
15433     OS << II->getName() << "::";
15434   return FixItHint::CreateInsertion(NameLoc, Insertion);
15435 }
15436 
15437 /// Determine whether a tag originally declared in context \p OldDC can
15438 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15439 /// found a declaration in \p OldDC as a previous decl, perhaps through a
15440 /// using-declaration).
15441 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15442                                          DeclContext *NewDC) {
15443   OldDC = OldDC->getRedeclContext();
15444   NewDC = NewDC->getRedeclContext();
15445 
15446   if (OldDC->Equals(NewDC))
15447     return true;
15448 
15449   // In MSVC mode, we allow a redeclaration if the contexts are related (either
15450   // encloses the other).
15451   if (S.getLangOpts().MSVCCompat &&
15452       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
15453     return true;
15454 
15455   return false;
15456 }
15457 
15458 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
15459 /// former case, Name will be non-null.  In the later case, Name will be null.
15460 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
15461 /// reference/declaration/definition of a tag.
15462 ///
15463 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
15464 /// trailing-type-specifier) other than one in an alias-declaration.
15465 ///
15466 /// \param SkipBody If non-null, will be set to indicate if the caller should
15467 /// skip the definition of this tag and treat it as if it were a declaration.
15468 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
15469                      SourceLocation KWLoc, CXXScopeSpec &SS,
15470                      IdentifierInfo *Name, SourceLocation NameLoc,
15471                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
15472                      SourceLocation ModulePrivateLoc,
15473                      MultiTemplateParamsArg TemplateParameterLists,
15474                      bool &OwnedDecl, bool &IsDependent,
15475                      SourceLocation ScopedEnumKWLoc,
15476                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
15477                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
15478                      SkipBodyInfo *SkipBody) {
15479   // If this is not a definition, it must have a name.
15480   IdentifierInfo *OrigName = Name;
15481   assert((Name != nullptr || TUK == TUK_Definition) &&
15482          "Nameless record must be a definition!");
15483   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
15484 
15485   OwnedDecl = false;
15486   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
15487   bool ScopedEnum = ScopedEnumKWLoc.isValid();
15488 
15489   // FIXME: Check member specializations more carefully.
15490   bool isMemberSpecialization = false;
15491   bool Invalid = false;
15492 
15493   // We only need to do this matching if we have template parameters
15494   // or a scope specifier, which also conveniently avoids this work
15495   // for non-C++ cases.
15496   if (TemplateParameterLists.size() > 0 ||
15497       (SS.isNotEmpty() && TUK != TUK_Reference)) {
15498     if (TemplateParameterList *TemplateParams =
15499             MatchTemplateParametersToScopeSpecifier(
15500                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
15501                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
15502       if (Kind == TTK_Enum) {
15503         Diag(KWLoc, diag::err_enum_template);
15504         return nullptr;
15505       }
15506 
15507       if (TemplateParams->size() > 0) {
15508         // This is a declaration or definition of a class template (which may
15509         // be a member of another template).
15510 
15511         if (Invalid)
15512           return nullptr;
15513 
15514         OwnedDecl = false;
15515         DeclResult Result = CheckClassTemplate(
15516             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
15517             AS, ModulePrivateLoc,
15518             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
15519             TemplateParameterLists.data(), SkipBody);
15520         return Result.get();
15521       } else {
15522         // The "template<>" header is extraneous.
15523         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
15524           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
15525         isMemberSpecialization = true;
15526       }
15527     }
15528 
15529     if (!TemplateParameterLists.empty() && isMemberSpecialization &&
15530         CheckTemplateDeclScope(S, TemplateParameterLists.back()))
15531       return nullptr;
15532   }
15533 
15534   // Figure out the underlying type if this a enum declaration. We need to do
15535   // this early, because it's needed to detect if this is an incompatible
15536   // redeclaration.
15537   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
15538   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
15539 
15540   if (Kind == TTK_Enum) {
15541     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
15542       // No underlying type explicitly specified, or we failed to parse the
15543       // type, default to int.
15544       EnumUnderlying = Context.IntTy.getTypePtr();
15545     } else if (UnderlyingType.get()) {
15546       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
15547       // integral type; any cv-qualification is ignored.
15548       TypeSourceInfo *TI = nullptr;
15549       GetTypeFromParser(UnderlyingType.get(), &TI);
15550       EnumUnderlying = TI;
15551 
15552       if (CheckEnumUnderlyingType(TI))
15553         // Recover by falling back to int.
15554         EnumUnderlying = Context.IntTy.getTypePtr();
15555 
15556       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
15557                                           UPPC_FixedUnderlyingType))
15558         EnumUnderlying = Context.IntTy.getTypePtr();
15559 
15560     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
15561       // For MSVC ABI compatibility, unfixed enums must use an underlying type
15562       // of 'int'. However, if this is an unfixed forward declaration, don't set
15563       // the underlying type unless the user enables -fms-compatibility. This
15564       // makes unfixed forward declared enums incomplete and is more conforming.
15565       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
15566         EnumUnderlying = Context.IntTy.getTypePtr();
15567     }
15568   }
15569 
15570   DeclContext *SearchDC = CurContext;
15571   DeclContext *DC = CurContext;
15572   bool isStdBadAlloc = false;
15573   bool isStdAlignValT = false;
15574 
15575   RedeclarationKind Redecl = forRedeclarationInCurContext();
15576   if (TUK == TUK_Friend || TUK == TUK_Reference)
15577     Redecl = NotForRedeclaration;
15578 
15579   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
15580   /// implemented asks for structural equivalence checking, the returned decl
15581   /// here is passed back to the parser, allowing the tag body to be parsed.
15582   auto createTagFromNewDecl = [&]() -> TagDecl * {
15583     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
15584     // If there is an identifier, use the location of the identifier as the
15585     // location of the decl, otherwise use the location of the struct/union
15586     // keyword.
15587     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15588     TagDecl *New = nullptr;
15589 
15590     if (Kind == TTK_Enum) {
15591       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
15592                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
15593       // If this is an undefined enum, bail.
15594       if (TUK != TUK_Definition && !Invalid)
15595         return nullptr;
15596       if (EnumUnderlying) {
15597         EnumDecl *ED = cast<EnumDecl>(New);
15598         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
15599           ED->setIntegerTypeSourceInfo(TI);
15600         else
15601           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
15602         ED->setPromotionType(ED->getIntegerType());
15603       }
15604     } else { // struct/union
15605       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15606                                nullptr);
15607     }
15608 
15609     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15610       // Add alignment attributes if necessary; these attributes are checked
15611       // when the ASTContext lays out the structure.
15612       //
15613       // It is important for implementing the correct semantics that this
15614       // happen here (in ActOnTag). The #pragma pack stack is
15615       // maintained as a result of parser callbacks which can occur at
15616       // many points during the parsing of a struct declaration (because
15617       // the #pragma tokens are effectively skipped over during the
15618       // parsing of the struct).
15619       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15620         AddAlignmentAttributesForRecord(RD);
15621         AddMsStructLayoutForRecord(RD);
15622       }
15623     }
15624     New->setLexicalDeclContext(CurContext);
15625     return New;
15626   };
15627 
15628   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
15629   if (Name && SS.isNotEmpty()) {
15630     // We have a nested-name tag ('struct foo::bar').
15631 
15632     // Check for invalid 'foo::'.
15633     if (SS.isInvalid()) {
15634       Name = nullptr;
15635       goto CreateNewDecl;
15636     }
15637 
15638     // If this is a friend or a reference to a class in a dependent
15639     // context, don't try to make a decl for it.
15640     if (TUK == TUK_Friend || TUK == TUK_Reference) {
15641       DC = computeDeclContext(SS, false);
15642       if (!DC) {
15643         IsDependent = true;
15644         return nullptr;
15645       }
15646     } else {
15647       DC = computeDeclContext(SS, true);
15648       if (!DC) {
15649         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
15650           << SS.getRange();
15651         return nullptr;
15652       }
15653     }
15654 
15655     if (RequireCompleteDeclContext(SS, DC))
15656       return nullptr;
15657 
15658     SearchDC = DC;
15659     // Look-up name inside 'foo::'.
15660     LookupQualifiedName(Previous, DC);
15661 
15662     if (Previous.isAmbiguous())
15663       return nullptr;
15664 
15665     if (Previous.empty()) {
15666       // Name lookup did not find anything. However, if the
15667       // nested-name-specifier refers to the current instantiation,
15668       // and that current instantiation has any dependent base
15669       // classes, we might find something at instantiation time: treat
15670       // this as a dependent elaborated-type-specifier.
15671       // But this only makes any sense for reference-like lookups.
15672       if (Previous.wasNotFoundInCurrentInstantiation() &&
15673           (TUK == TUK_Reference || TUK == TUK_Friend)) {
15674         IsDependent = true;
15675         return nullptr;
15676       }
15677 
15678       // A tag 'foo::bar' must already exist.
15679       Diag(NameLoc, diag::err_not_tag_in_scope)
15680         << Kind << Name << DC << SS.getRange();
15681       Name = nullptr;
15682       Invalid = true;
15683       goto CreateNewDecl;
15684     }
15685   } else if (Name) {
15686     // C++14 [class.mem]p14:
15687     //   If T is the name of a class, then each of the following shall have a
15688     //   name different from T:
15689     //    -- every member of class T that is itself a type
15690     if (TUK != TUK_Reference && TUK != TUK_Friend &&
15691         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15692       return nullptr;
15693 
15694     // If this is a named struct, check to see if there was a previous forward
15695     // declaration or definition.
15696     // FIXME: We're looking into outer scopes here, even when we
15697     // shouldn't be. Doing so can result in ambiguities that we
15698     // shouldn't be diagnosing.
15699     LookupName(Previous, S);
15700 
15701     // When declaring or defining a tag, ignore ambiguities introduced
15702     // by types using'ed into this scope.
15703     if (Previous.isAmbiguous() &&
15704         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
15705       LookupResult::Filter F = Previous.makeFilter();
15706       while (F.hasNext()) {
15707         NamedDecl *ND = F.next();
15708         if (!ND->getDeclContext()->getRedeclContext()->Equals(
15709                 SearchDC->getRedeclContext()))
15710           F.erase();
15711       }
15712       F.done();
15713     }
15714 
15715     // C++11 [namespace.memdef]p3:
15716     //   If the name in a friend declaration is neither qualified nor
15717     //   a template-id and the declaration is a function or an
15718     //   elaborated-type-specifier, the lookup to determine whether
15719     //   the entity has been previously declared shall not consider
15720     //   any scopes outside the innermost enclosing namespace.
15721     //
15722     // MSVC doesn't implement the above rule for types, so a friend tag
15723     // declaration may be a redeclaration of a type declared in an enclosing
15724     // scope.  They do implement this rule for friend functions.
15725     //
15726     // Does it matter that this should be by scope instead of by
15727     // semantic context?
15728     if (!Previous.empty() && TUK == TUK_Friend) {
15729       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
15730       LookupResult::Filter F = Previous.makeFilter();
15731       bool FriendSawTagOutsideEnclosingNamespace = false;
15732       while (F.hasNext()) {
15733         NamedDecl *ND = F.next();
15734         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15735         if (DC->isFileContext() &&
15736             !EnclosingNS->Encloses(ND->getDeclContext())) {
15737           if (getLangOpts().MSVCCompat)
15738             FriendSawTagOutsideEnclosingNamespace = true;
15739           else
15740             F.erase();
15741         }
15742       }
15743       F.done();
15744 
15745       // Diagnose this MSVC extension in the easy case where lookup would have
15746       // unambiguously found something outside the enclosing namespace.
15747       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
15748         NamedDecl *ND = Previous.getFoundDecl();
15749         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
15750             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
15751       }
15752     }
15753 
15754     // Note:  there used to be some attempt at recovery here.
15755     if (Previous.isAmbiguous())
15756       return nullptr;
15757 
15758     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
15759       // FIXME: This makes sure that we ignore the contexts associated
15760       // with C structs, unions, and enums when looking for a matching
15761       // tag declaration or definition. See the similar lookup tweak
15762       // in Sema::LookupName; is there a better way to deal with this?
15763       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
15764         SearchDC = SearchDC->getParent();
15765     }
15766   }
15767 
15768   if (Previous.isSingleResult() &&
15769       Previous.getFoundDecl()->isTemplateParameter()) {
15770     // Maybe we will complain about the shadowed template parameter.
15771     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
15772     // Just pretend that we didn't see the previous declaration.
15773     Previous.clear();
15774   }
15775 
15776   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
15777       DC->Equals(getStdNamespace())) {
15778     if (Name->isStr("bad_alloc")) {
15779       // This is a declaration of or a reference to "std::bad_alloc".
15780       isStdBadAlloc = true;
15781 
15782       // If std::bad_alloc has been implicitly declared (but made invisible to
15783       // name lookup), fill in this implicit declaration as the previous
15784       // declaration, so that the declarations get chained appropriately.
15785       if (Previous.empty() && StdBadAlloc)
15786         Previous.addDecl(getStdBadAlloc());
15787     } else if (Name->isStr("align_val_t")) {
15788       isStdAlignValT = true;
15789       if (Previous.empty() && StdAlignValT)
15790         Previous.addDecl(getStdAlignValT());
15791     }
15792   }
15793 
15794   // If we didn't find a previous declaration, and this is a reference
15795   // (or friend reference), move to the correct scope.  In C++, we
15796   // also need to do a redeclaration lookup there, just in case
15797   // there's a shadow friend decl.
15798   if (Name && Previous.empty() &&
15799       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
15800     if (Invalid) goto CreateNewDecl;
15801     assert(SS.isEmpty());
15802 
15803     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
15804       // C++ [basic.scope.pdecl]p5:
15805       //   -- for an elaborated-type-specifier of the form
15806       //
15807       //          class-key identifier
15808       //
15809       //      if the elaborated-type-specifier is used in the
15810       //      decl-specifier-seq or parameter-declaration-clause of a
15811       //      function defined in namespace scope, the identifier is
15812       //      declared as a class-name in the namespace that contains
15813       //      the declaration; otherwise, except as a friend
15814       //      declaration, the identifier is declared in the smallest
15815       //      non-class, non-function-prototype scope that contains the
15816       //      declaration.
15817       //
15818       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
15819       // C structs and unions.
15820       //
15821       // It is an error in C++ to declare (rather than define) an enum
15822       // type, including via an elaborated type specifier.  We'll
15823       // diagnose that later; for now, declare the enum in the same
15824       // scope as we would have picked for any other tag type.
15825       //
15826       // GNU C also supports this behavior as part of its incomplete
15827       // enum types extension, while GNU C++ does not.
15828       //
15829       // Find the context where we'll be declaring the tag.
15830       // FIXME: We would like to maintain the current DeclContext as the
15831       // lexical context,
15832       SearchDC = getTagInjectionContext(SearchDC);
15833 
15834       // Find the scope where we'll be declaring the tag.
15835       S = getTagInjectionScope(S, getLangOpts());
15836     } else {
15837       assert(TUK == TUK_Friend);
15838       // C++ [namespace.memdef]p3:
15839       //   If a friend declaration in a non-local class first declares a
15840       //   class or function, the friend class or function is a member of
15841       //   the innermost enclosing namespace.
15842       SearchDC = SearchDC->getEnclosingNamespaceContext();
15843     }
15844 
15845     // In C++, we need to do a redeclaration lookup to properly
15846     // diagnose some problems.
15847     // FIXME: redeclaration lookup is also used (with and without C++) to find a
15848     // hidden declaration so that we don't get ambiguity errors when using a
15849     // type declared by an elaborated-type-specifier.  In C that is not correct
15850     // and we should instead merge compatible types found by lookup.
15851     if (getLangOpts().CPlusPlus) {
15852       // FIXME: This can perform qualified lookups into function contexts,
15853       // which are meaningless.
15854       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15855       LookupQualifiedName(Previous, SearchDC);
15856     } else {
15857       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15858       LookupName(Previous, S);
15859     }
15860   }
15861 
15862   // If we have a known previous declaration to use, then use it.
15863   if (Previous.empty() && SkipBody && SkipBody->Previous)
15864     Previous.addDecl(SkipBody->Previous);
15865 
15866   if (!Previous.empty()) {
15867     NamedDecl *PrevDecl = Previous.getFoundDecl();
15868     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
15869 
15870     // It's okay to have a tag decl in the same scope as a typedef
15871     // which hides a tag decl in the same scope.  Finding this
15872     // insanity with a redeclaration lookup can only actually happen
15873     // in C++.
15874     //
15875     // This is also okay for elaborated-type-specifiers, which is
15876     // technically forbidden by the current standard but which is
15877     // okay according to the likely resolution of an open issue;
15878     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
15879     if (getLangOpts().CPlusPlus) {
15880       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15881         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
15882           TagDecl *Tag = TT->getDecl();
15883           if (Tag->getDeclName() == Name &&
15884               Tag->getDeclContext()->getRedeclContext()
15885                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
15886             PrevDecl = Tag;
15887             Previous.clear();
15888             Previous.addDecl(Tag);
15889             Previous.resolveKind();
15890           }
15891         }
15892       }
15893     }
15894 
15895     // If this is a redeclaration of a using shadow declaration, it must
15896     // declare a tag in the same context. In MSVC mode, we allow a
15897     // redefinition if either context is within the other.
15898     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
15899       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
15900       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
15901           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
15902           !(OldTag && isAcceptableTagRedeclContext(
15903                           *this, OldTag->getDeclContext(), SearchDC))) {
15904         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
15905         Diag(Shadow->getTargetDecl()->getLocation(),
15906              diag::note_using_decl_target);
15907         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
15908             << 0;
15909         // Recover by ignoring the old declaration.
15910         Previous.clear();
15911         goto CreateNewDecl;
15912       }
15913     }
15914 
15915     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
15916       // If this is a use of a previous tag, or if the tag is already declared
15917       // in the same scope (so that the definition/declaration completes or
15918       // rementions the tag), reuse the decl.
15919       if (TUK == TUK_Reference || TUK == TUK_Friend ||
15920           isDeclInScope(DirectPrevDecl, SearchDC, S,
15921                         SS.isNotEmpty() || isMemberSpecialization)) {
15922         // Make sure that this wasn't declared as an enum and now used as a
15923         // struct or something similar.
15924         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
15925                                           TUK == TUK_Definition, KWLoc,
15926                                           Name)) {
15927           bool SafeToContinue
15928             = (PrevTagDecl->getTagKind() != TTK_Enum &&
15929                Kind != TTK_Enum);
15930           if (SafeToContinue)
15931             Diag(KWLoc, diag::err_use_with_wrong_tag)
15932               << Name
15933               << FixItHint::CreateReplacement(SourceRange(KWLoc),
15934                                               PrevTagDecl->getKindName());
15935           else
15936             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
15937           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
15938 
15939           if (SafeToContinue)
15940             Kind = PrevTagDecl->getTagKind();
15941           else {
15942             // Recover by making this an anonymous redefinition.
15943             Name = nullptr;
15944             Previous.clear();
15945             Invalid = true;
15946           }
15947         }
15948 
15949         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
15950           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
15951           if (TUK == TUK_Reference || TUK == TUK_Friend)
15952             return PrevTagDecl;
15953 
15954           QualType EnumUnderlyingTy;
15955           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15956             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
15957           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
15958             EnumUnderlyingTy = QualType(T, 0);
15959 
15960           // All conflicts with previous declarations are recovered by
15961           // returning the previous declaration, unless this is a definition,
15962           // in which case we want the caller to bail out.
15963           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
15964                                      ScopedEnum, EnumUnderlyingTy,
15965                                      IsFixed, PrevEnum))
15966             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
15967         }
15968 
15969         // C++11 [class.mem]p1:
15970         //   A member shall not be declared twice in the member-specification,
15971         //   except that a nested class or member class template can be declared
15972         //   and then later defined.
15973         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
15974             S->isDeclScope(PrevDecl)) {
15975           Diag(NameLoc, diag::ext_member_redeclared);
15976           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
15977         }
15978 
15979         if (!Invalid) {
15980           // If this is a use, just return the declaration we found, unless
15981           // we have attributes.
15982           if (TUK == TUK_Reference || TUK == TUK_Friend) {
15983             if (!Attrs.empty()) {
15984               // FIXME: Diagnose these attributes. For now, we create a new
15985               // declaration to hold them.
15986             } else if (TUK == TUK_Reference &&
15987                        (PrevTagDecl->getFriendObjectKind() ==
15988                             Decl::FOK_Undeclared ||
15989                         PrevDecl->getOwningModule() != getCurrentModule()) &&
15990                        SS.isEmpty()) {
15991               // This declaration is a reference to an existing entity, but
15992               // has different visibility from that entity: it either makes
15993               // a friend visible or it makes a type visible in a new module.
15994               // In either case, create a new declaration. We only do this if
15995               // the declaration would have meant the same thing if no prior
15996               // declaration were found, that is, if it was found in the same
15997               // scope where we would have injected a declaration.
15998               if (!getTagInjectionContext(CurContext)->getRedeclContext()
15999                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
16000                 return PrevTagDecl;
16001               // This is in the injected scope, create a new declaration in
16002               // that scope.
16003               S = getTagInjectionScope(S, getLangOpts());
16004             } else {
16005               return PrevTagDecl;
16006             }
16007           }
16008 
16009           // Diagnose attempts to redefine a tag.
16010           if (TUK == TUK_Definition) {
16011             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
16012               // If we're defining a specialization and the previous definition
16013               // is from an implicit instantiation, don't emit an error
16014               // here; we'll catch this in the general case below.
16015               bool IsExplicitSpecializationAfterInstantiation = false;
16016               if (isMemberSpecialization) {
16017                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
16018                   IsExplicitSpecializationAfterInstantiation =
16019                     RD->getTemplateSpecializationKind() !=
16020                     TSK_ExplicitSpecialization;
16021                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
16022                   IsExplicitSpecializationAfterInstantiation =
16023                     ED->getTemplateSpecializationKind() !=
16024                     TSK_ExplicitSpecialization;
16025               }
16026 
16027               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
16028               // not keep more that one definition around (merge them). However,
16029               // ensure the decl passes the structural compatibility check in
16030               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
16031               NamedDecl *Hidden = nullptr;
16032               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
16033                 // There is a definition of this tag, but it is not visible. We
16034                 // explicitly make use of C++'s one definition rule here, and
16035                 // assume that this definition is identical to the hidden one
16036                 // we already have. Make the existing definition visible and
16037                 // use it in place of this one.
16038                 if (!getLangOpts().CPlusPlus) {
16039                   // Postpone making the old definition visible until after we
16040                   // complete parsing the new one and do the structural
16041                   // comparison.
16042                   SkipBody->CheckSameAsPrevious = true;
16043                   SkipBody->New = createTagFromNewDecl();
16044                   SkipBody->Previous = Def;
16045                   return Def;
16046                 } else {
16047                   SkipBody->ShouldSkip = true;
16048                   SkipBody->Previous = Def;
16049                   makeMergedDefinitionVisible(Hidden);
16050                   // Carry on and handle it like a normal definition. We'll
16051                   // skip starting the definitiion later.
16052                 }
16053               } else if (!IsExplicitSpecializationAfterInstantiation) {
16054                 // A redeclaration in function prototype scope in C isn't
16055                 // visible elsewhere, so merely issue a warning.
16056                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
16057                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
16058                 else
16059                   Diag(NameLoc, diag::err_redefinition) << Name;
16060                 notePreviousDefinition(Def,
16061                                        NameLoc.isValid() ? NameLoc : KWLoc);
16062                 // If this is a redefinition, recover by making this
16063                 // struct be anonymous, which will make any later
16064                 // references get the previous definition.
16065                 Name = nullptr;
16066                 Previous.clear();
16067                 Invalid = true;
16068               }
16069             } else {
16070               // If the type is currently being defined, complain
16071               // about a nested redefinition.
16072               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
16073               if (TD->isBeingDefined()) {
16074                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
16075                 Diag(PrevTagDecl->getLocation(),
16076                      diag::note_previous_definition);
16077                 Name = nullptr;
16078                 Previous.clear();
16079                 Invalid = true;
16080               }
16081             }
16082 
16083             // Okay, this is definition of a previously declared or referenced
16084             // tag. We're going to create a new Decl for it.
16085           }
16086 
16087           // Okay, we're going to make a redeclaration.  If this is some kind
16088           // of reference, make sure we build the redeclaration in the same DC
16089           // as the original, and ignore the current access specifier.
16090           if (TUK == TUK_Friend || TUK == TUK_Reference) {
16091             SearchDC = PrevTagDecl->getDeclContext();
16092             AS = AS_none;
16093           }
16094         }
16095         // If we get here we have (another) forward declaration or we
16096         // have a definition.  Just create a new decl.
16097 
16098       } else {
16099         // If we get here, this is a definition of a new tag type in a nested
16100         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
16101         // new decl/type.  We set PrevDecl to NULL so that the entities
16102         // have distinct types.
16103         Previous.clear();
16104       }
16105       // If we get here, we're going to create a new Decl. If PrevDecl
16106       // is non-NULL, it's a definition of the tag declared by
16107       // PrevDecl. If it's NULL, we have a new definition.
16108 
16109     // Otherwise, PrevDecl is not a tag, but was found with tag
16110     // lookup.  This is only actually possible in C++, where a few
16111     // things like templates still live in the tag namespace.
16112     } else {
16113       // Use a better diagnostic if an elaborated-type-specifier
16114       // found the wrong kind of type on the first
16115       // (non-redeclaration) lookup.
16116       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
16117           !Previous.isForRedeclaration()) {
16118         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16119         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
16120                                                        << Kind;
16121         Diag(PrevDecl->getLocation(), diag::note_declared_at);
16122         Invalid = true;
16123 
16124       // Otherwise, only diagnose if the declaration is in scope.
16125       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
16126                                 SS.isNotEmpty() || isMemberSpecialization)) {
16127         // do nothing
16128 
16129       // Diagnose implicit declarations introduced by elaborated types.
16130       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
16131         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16132         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
16133         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16134         Invalid = true;
16135 
16136       // Otherwise it's a declaration.  Call out a particularly common
16137       // case here.
16138       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16139         unsigned Kind = 0;
16140         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
16141         Diag(NameLoc, diag::err_tag_definition_of_typedef)
16142           << Name << Kind << TND->getUnderlyingType();
16143         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16144         Invalid = true;
16145 
16146       // Otherwise, diagnose.
16147       } else {
16148         // The tag name clashes with something else in the target scope,
16149         // issue an error and recover by making this tag be anonymous.
16150         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
16151         notePreviousDefinition(PrevDecl, NameLoc);
16152         Name = nullptr;
16153         Invalid = true;
16154       }
16155 
16156       // The existing declaration isn't relevant to us; we're in a
16157       // new scope, so clear out the previous declaration.
16158       Previous.clear();
16159     }
16160   }
16161 
16162 CreateNewDecl:
16163 
16164   TagDecl *PrevDecl = nullptr;
16165   if (Previous.isSingleResult())
16166     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16167 
16168   // If there is an identifier, use the location of the identifier as the
16169   // location of the decl, otherwise use the location of the struct/union
16170   // keyword.
16171   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16172 
16173   // Otherwise, create a new declaration. If there is a previous
16174   // declaration of the same entity, the two will be linked via
16175   // PrevDecl.
16176   TagDecl *New;
16177 
16178   if (Kind == TTK_Enum) {
16179     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16180     // enum X { A, B, C } D;    D should chain to X.
16181     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16182                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16183                            ScopedEnumUsesClassTag, IsFixed);
16184 
16185     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16186       StdAlignValT = cast<EnumDecl>(New);
16187 
16188     // If this is an undefined enum, warn.
16189     if (TUK != TUK_Definition && !Invalid) {
16190       TagDecl *Def;
16191       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16192         // C++0x: 7.2p2: opaque-enum-declaration.
16193         // Conflicts are diagnosed above. Do nothing.
16194       }
16195       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16196         Diag(Loc, diag::ext_forward_ref_enum_def)
16197           << New;
16198         Diag(Def->getLocation(), diag::note_previous_definition);
16199       } else {
16200         unsigned DiagID = diag::ext_forward_ref_enum;
16201         if (getLangOpts().MSVCCompat)
16202           DiagID = diag::ext_ms_forward_ref_enum;
16203         else if (getLangOpts().CPlusPlus)
16204           DiagID = diag::err_forward_ref_enum;
16205         Diag(Loc, DiagID);
16206       }
16207     }
16208 
16209     if (EnumUnderlying) {
16210       EnumDecl *ED = cast<EnumDecl>(New);
16211       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16212         ED->setIntegerTypeSourceInfo(TI);
16213       else
16214         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
16215       ED->setPromotionType(ED->getIntegerType());
16216       assert(ED->isComplete() && "enum with type should be complete");
16217     }
16218   } else {
16219     // struct/union/class
16220 
16221     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16222     // struct X { int A; } D;    D should chain to X.
16223     if (getLangOpts().CPlusPlus) {
16224       // FIXME: Look for a way to use RecordDecl for simple structs.
16225       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16226                                   cast_or_null<CXXRecordDecl>(PrevDecl));
16227 
16228       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16229         StdBadAlloc = cast<CXXRecordDecl>(New);
16230     } else
16231       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16232                                cast_or_null<RecordDecl>(PrevDecl));
16233   }
16234 
16235   // C++11 [dcl.type]p3:
16236   //   A type-specifier-seq shall not define a class or enumeration [...].
16237   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16238       TUK == TUK_Definition) {
16239     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16240       << Context.getTagDeclType(New);
16241     Invalid = true;
16242   }
16243 
16244   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16245       DC->getDeclKind() == Decl::Enum) {
16246     Diag(New->getLocation(), diag::err_type_defined_in_enum)
16247       << Context.getTagDeclType(New);
16248     Invalid = true;
16249   }
16250 
16251   // Maybe add qualifier info.
16252   if (SS.isNotEmpty()) {
16253     if (SS.isSet()) {
16254       // If this is either a declaration or a definition, check the
16255       // nested-name-specifier against the current context.
16256       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16257           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16258                                        isMemberSpecialization))
16259         Invalid = true;
16260 
16261       New->setQualifierInfo(SS.getWithLocInContext(Context));
16262       if (TemplateParameterLists.size() > 0) {
16263         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16264       }
16265     }
16266     else
16267       Invalid = true;
16268   }
16269 
16270   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16271     // Add alignment attributes if necessary; these attributes are checked when
16272     // the ASTContext lays out the structure.
16273     //
16274     // It is important for implementing the correct semantics that this
16275     // happen here (in ActOnTag). The #pragma pack stack is
16276     // maintained as a result of parser callbacks which can occur at
16277     // many points during the parsing of a struct declaration (because
16278     // the #pragma tokens are effectively skipped over during the
16279     // parsing of the struct).
16280     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16281       AddAlignmentAttributesForRecord(RD);
16282       AddMsStructLayoutForRecord(RD);
16283     }
16284   }
16285 
16286   if (ModulePrivateLoc.isValid()) {
16287     if (isMemberSpecialization)
16288       Diag(New->getLocation(), diag::err_module_private_specialization)
16289         << 2
16290         << FixItHint::CreateRemoval(ModulePrivateLoc);
16291     // __module_private__ does not apply to local classes. However, we only
16292     // diagnose this as an error when the declaration specifiers are
16293     // freestanding. Here, we just ignore the __module_private__.
16294     else if (!SearchDC->isFunctionOrMethod())
16295       New->setModulePrivate();
16296   }
16297 
16298   // If this is a specialization of a member class (of a class template),
16299   // check the specialization.
16300   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16301     Invalid = true;
16302 
16303   // If we're declaring or defining a tag in function prototype scope in C,
16304   // note that this type can only be used within the function and add it to
16305   // the list of decls to inject into the function definition scope.
16306   if ((Name || Kind == TTK_Enum) &&
16307       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16308     if (getLangOpts().CPlusPlus) {
16309       // C++ [dcl.fct]p6:
16310       //   Types shall not be defined in return or parameter types.
16311       if (TUK == TUK_Definition && !IsTypeSpecifier) {
16312         Diag(Loc, diag::err_type_defined_in_param_type)
16313             << Name;
16314         Invalid = true;
16315       }
16316     } else if (!PrevDecl) {
16317       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16318     }
16319   }
16320 
16321   if (Invalid)
16322     New->setInvalidDecl();
16323 
16324   // Set the lexical context. If the tag has a C++ scope specifier, the
16325   // lexical context will be different from the semantic context.
16326   New->setLexicalDeclContext(CurContext);
16327 
16328   // Mark this as a friend decl if applicable.
16329   // In Microsoft mode, a friend declaration also acts as a forward
16330   // declaration so we always pass true to setObjectOfFriendDecl to make
16331   // the tag name visible.
16332   if (TUK == TUK_Friend)
16333     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16334 
16335   // Set the access specifier.
16336   if (!Invalid && SearchDC->isRecord())
16337     SetMemberAccessSpecifier(New, PrevDecl, AS);
16338 
16339   if (PrevDecl)
16340     CheckRedeclarationModuleOwnership(New, PrevDecl);
16341 
16342   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16343     New->startDefinition();
16344 
16345   ProcessDeclAttributeList(S, New, Attrs);
16346   AddPragmaAttributes(S, New);
16347 
16348   // If this has an identifier, add it to the scope stack.
16349   if (TUK == TUK_Friend) {
16350     // We might be replacing an existing declaration in the lookup tables;
16351     // if so, borrow its access specifier.
16352     if (PrevDecl)
16353       New->setAccess(PrevDecl->getAccess());
16354 
16355     DeclContext *DC = New->getDeclContext()->getRedeclContext();
16356     DC->makeDeclVisibleInContext(New);
16357     if (Name) // can be null along some error paths
16358       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16359         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16360   } else if (Name) {
16361     S = getNonFieldDeclScope(S);
16362     PushOnScopeChains(New, S, true);
16363   } else {
16364     CurContext->addDecl(New);
16365   }
16366 
16367   // If this is the C FILE type, notify the AST context.
16368   if (IdentifierInfo *II = New->getIdentifier())
16369     if (!New->isInvalidDecl() &&
16370         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16371         II->isStr("FILE"))
16372       Context.setFILEDecl(New);
16373 
16374   if (PrevDecl)
16375     mergeDeclAttributes(New, PrevDecl);
16376 
16377   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16378     inferGslOwnerPointerAttribute(CXXRD);
16379 
16380   // If there's a #pragma GCC visibility in scope, set the visibility of this
16381   // record.
16382   AddPushedVisibilityAttribute(New);
16383 
16384   if (isMemberSpecialization && !New->isInvalidDecl())
16385     CompleteMemberSpecialization(New, Previous);
16386 
16387   OwnedDecl = true;
16388   // In C++, don't return an invalid declaration. We can't recover well from
16389   // the cases where we make the type anonymous.
16390   if (Invalid && getLangOpts().CPlusPlus) {
16391     if (New->isBeingDefined())
16392       if (auto RD = dyn_cast<RecordDecl>(New))
16393         RD->completeDefinition();
16394     return nullptr;
16395   } else if (SkipBody && SkipBody->ShouldSkip) {
16396     return SkipBody->Previous;
16397   } else {
16398     return New;
16399   }
16400 }
16401 
16402 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
16403   AdjustDeclIfTemplate(TagD);
16404   TagDecl *Tag = cast<TagDecl>(TagD);
16405 
16406   // Enter the tag context.
16407   PushDeclContext(S, Tag);
16408 
16409   ActOnDocumentableDecl(TagD);
16410 
16411   // If there's a #pragma GCC visibility in scope, set the visibility of this
16412   // record.
16413   AddPushedVisibilityAttribute(Tag);
16414 }
16415 
16416 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
16417                                     SkipBodyInfo &SkipBody) {
16418   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16419     return false;
16420 
16421   // Make the previous decl visible.
16422   makeMergedDefinitionVisible(SkipBody.Previous);
16423   return true;
16424 }
16425 
16426 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
16427   assert(isa<ObjCContainerDecl>(IDecl) &&
16428          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
16429   DeclContext *OCD = cast<DeclContext>(IDecl);
16430   assert(OCD->getLexicalParent() == CurContext &&
16431       "The next DeclContext should be lexically contained in the current one.");
16432   CurContext = OCD;
16433   return IDecl;
16434 }
16435 
16436 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16437                                            SourceLocation FinalLoc,
16438                                            bool IsFinalSpelledSealed,
16439                                            SourceLocation LBraceLoc) {
16440   AdjustDeclIfTemplate(TagD);
16441   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
16442 
16443   FieldCollector->StartClass();
16444 
16445   if (!Record->getIdentifier())
16446     return;
16447 
16448   if (FinalLoc.isValid())
16449     Record->addAttr(FinalAttr::Create(
16450         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
16451         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
16452 
16453   // C++ [class]p2:
16454   //   [...] The class-name is also inserted into the scope of the
16455   //   class itself; this is known as the injected-class-name. For
16456   //   purposes of access checking, the injected-class-name is treated
16457   //   as if it were a public member name.
16458   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
16459       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
16460       Record->getLocation(), Record->getIdentifier(),
16461       /*PrevDecl=*/nullptr,
16462       /*DelayTypeCreation=*/true);
16463   Context.getTypeDeclType(InjectedClassName, Record);
16464   InjectedClassName->setImplicit();
16465   InjectedClassName->setAccess(AS_public);
16466   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
16467       InjectedClassName->setDescribedClassTemplate(Template);
16468   PushOnScopeChains(InjectedClassName, S);
16469   assert(InjectedClassName->isInjectedClassName() &&
16470          "Broken injected-class-name");
16471 }
16472 
16473 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
16474                                     SourceRange BraceRange) {
16475   AdjustDeclIfTemplate(TagD);
16476   TagDecl *Tag = cast<TagDecl>(TagD);
16477   Tag->setBraceRange(BraceRange);
16478 
16479   // Make sure we "complete" the definition even it is invalid.
16480   if (Tag->isBeingDefined()) {
16481     assert(Tag->isInvalidDecl() && "We should already have completed it");
16482     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16483       RD->completeDefinition();
16484   }
16485 
16486   if (isa<CXXRecordDecl>(Tag)) {
16487     FieldCollector->FinishClass();
16488   }
16489 
16490   // Exit this scope of this tag's definition.
16491   PopDeclContext();
16492 
16493   if (getCurLexicalContext()->isObjCContainer() &&
16494       Tag->getDeclContext()->isFileContext())
16495     Tag->setTopLevelDeclInObjCContainer();
16496 
16497   // Notify the consumer that we've defined a tag.
16498   if (!Tag->isInvalidDecl())
16499     Consumer.HandleTagDeclDefinition(Tag);
16500 }
16501 
16502 void Sema::ActOnObjCContainerFinishDefinition() {
16503   // Exit this scope of this interface definition.
16504   PopDeclContext();
16505 }
16506 
16507 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
16508   assert(DC == CurContext && "Mismatch of container contexts");
16509   OriginalLexicalContext = DC;
16510   ActOnObjCContainerFinishDefinition();
16511 }
16512 
16513 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
16514   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
16515   OriginalLexicalContext = nullptr;
16516 }
16517 
16518 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
16519   AdjustDeclIfTemplate(TagD);
16520   TagDecl *Tag = cast<TagDecl>(TagD);
16521   Tag->setInvalidDecl();
16522 
16523   // Make sure we "complete" the definition even it is invalid.
16524   if (Tag->isBeingDefined()) {
16525     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16526       RD->completeDefinition();
16527   }
16528 
16529   // We're undoing ActOnTagStartDefinition here, not
16530   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
16531   // the FieldCollector.
16532 
16533   PopDeclContext();
16534 }
16535 
16536 // Note that FieldName may be null for anonymous bitfields.
16537 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
16538                                 IdentifierInfo *FieldName,
16539                                 QualType FieldTy, bool IsMsStruct,
16540                                 Expr *BitWidth, bool *ZeroWidth) {
16541   assert(BitWidth);
16542   if (BitWidth->containsErrors())
16543     return ExprError();
16544 
16545   // Default to true; that shouldn't confuse checks for emptiness
16546   if (ZeroWidth)
16547     *ZeroWidth = true;
16548 
16549   // C99 6.7.2.1p4 - verify the field type.
16550   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
16551   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
16552     // Handle incomplete and sizeless types with a specific error.
16553     if (RequireCompleteSizedType(FieldLoc, FieldTy,
16554                                  diag::err_field_incomplete_or_sizeless))
16555       return ExprError();
16556     if (FieldName)
16557       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
16558         << FieldName << FieldTy << BitWidth->getSourceRange();
16559     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
16560       << FieldTy << BitWidth->getSourceRange();
16561   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
16562                                              UPPC_BitFieldWidth))
16563     return ExprError();
16564 
16565   // If the bit-width is type- or value-dependent, don't try to check
16566   // it now.
16567   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
16568     return BitWidth;
16569 
16570   llvm::APSInt Value;
16571   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
16572   if (ICE.isInvalid())
16573     return ICE;
16574   BitWidth = ICE.get();
16575 
16576   if (Value != 0 && ZeroWidth)
16577     *ZeroWidth = false;
16578 
16579   // Zero-width bitfield is ok for anonymous field.
16580   if (Value == 0 && FieldName)
16581     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
16582 
16583   if (Value.isSigned() && Value.isNegative()) {
16584     if (FieldName)
16585       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
16586                << FieldName << Value.toString(10);
16587     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
16588       << Value.toString(10);
16589   }
16590 
16591   // The size of the bit-field must not exceed our maximum permitted object
16592   // size.
16593   if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
16594     return Diag(FieldLoc, diag::err_bitfield_too_wide)
16595            << !FieldName << FieldName << Value.toString(10);
16596   }
16597 
16598   if (!FieldTy->isDependentType()) {
16599     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
16600     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
16601     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
16602 
16603     // Over-wide bitfields are an error in C or when using the MSVC bitfield
16604     // ABI.
16605     bool CStdConstraintViolation =
16606         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
16607     bool MSBitfieldViolation =
16608         Value.ugt(TypeStorageSize) &&
16609         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
16610     if (CStdConstraintViolation || MSBitfieldViolation) {
16611       unsigned DiagWidth =
16612           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
16613       if (FieldName)
16614         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
16615                << FieldName << Value.toString(10)
16616                << !CStdConstraintViolation << DiagWidth;
16617 
16618       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
16619              << Value.toString(10) << !CStdConstraintViolation
16620              << DiagWidth;
16621     }
16622 
16623     // Warn on types where the user might conceivably expect to get all
16624     // specified bits as value bits: that's all integral types other than
16625     // 'bool'.
16626     if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
16627       Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
16628           << FieldName << Value.toString(10)
16629           << (unsigned)TypeWidth;
16630     }
16631   }
16632 
16633   return BitWidth;
16634 }
16635 
16636 /// ActOnField - Each field of a C struct/union is passed into this in order
16637 /// to create a FieldDecl object for it.
16638 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
16639                        Declarator &D, Expr *BitfieldWidth) {
16640   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
16641                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
16642                                /*InitStyle=*/ICIS_NoInit, AS_public);
16643   return Res;
16644 }
16645 
16646 /// HandleField - Analyze a field of a C struct or a C++ data member.
16647 ///
16648 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
16649                              SourceLocation DeclStart,
16650                              Declarator &D, Expr *BitWidth,
16651                              InClassInitStyle InitStyle,
16652                              AccessSpecifier AS) {
16653   if (D.isDecompositionDeclarator()) {
16654     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
16655     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
16656       << Decomp.getSourceRange();
16657     return nullptr;
16658   }
16659 
16660   IdentifierInfo *II = D.getIdentifier();
16661   SourceLocation Loc = DeclStart;
16662   if (II) Loc = D.getIdentifierLoc();
16663 
16664   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16665   QualType T = TInfo->getType();
16666   if (getLangOpts().CPlusPlus) {
16667     CheckExtraCXXDefaultArguments(D);
16668 
16669     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16670                                         UPPC_DataMemberType)) {
16671       D.setInvalidType();
16672       T = Context.IntTy;
16673       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
16674     }
16675   }
16676 
16677   DiagnoseFunctionSpecifiers(D.getDeclSpec());
16678 
16679   if (D.getDeclSpec().isInlineSpecified())
16680     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
16681         << getLangOpts().CPlusPlus17;
16682   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
16683     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
16684          diag::err_invalid_thread)
16685       << DeclSpec::getSpecifierName(TSCS);
16686 
16687   // Check to see if this name was declared as a member previously
16688   NamedDecl *PrevDecl = nullptr;
16689   LookupResult Previous(*this, II, Loc, LookupMemberName,
16690                         ForVisibleRedeclaration);
16691   LookupName(Previous, S);
16692   switch (Previous.getResultKind()) {
16693     case LookupResult::Found:
16694     case LookupResult::FoundUnresolvedValue:
16695       PrevDecl = Previous.getAsSingle<NamedDecl>();
16696       break;
16697 
16698     case LookupResult::FoundOverloaded:
16699       PrevDecl = Previous.getRepresentativeDecl();
16700       break;
16701 
16702     case LookupResult::NotFound:
16703     case LookupResult::NotFoundInCurrentInstantiation:
16704     case LookupResult::Ambiguous:
16705       break;
16706   }
16707   Previous.suppressDiagnostics();
16708 
16709   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16710     // Maybe we will complain about the shadowed template parameter.
16711     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16712     // Just pretend that we didn't see the previous declaration.
16713     PrevDecl = nullptr;
16714   }
16715 
16716   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
16717     PrevDecl = nullptr;
16718 
16719   bool Mutable
16720     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
16721   SourceLocation TSSL = D.getBeginLoc();
16722   FieldDecl *NewFD
16723     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
16724                      TSSL, AS, PrevDecl, &D);
16725 
16726   if (NewFD->isInvalidDecl())
16727     Record->setInvalidDecl();
16728 
16729   if (D.getDeclSpec().isModulePrivateSpecified())
16730     NewFD->setModulePrivate();
16731 
16732   if (NewFD->isInvalidDecl() && PrevDecl) {
16733     // Don't introduce NewFD into scope; there's already something
16734     // with the same name in the same scope.
16735   } else if (II) {
16736     PushOnScopeChains(NewFD, S);
16737   } else
16738     Record->addDecl(NewFD);
16739 
16740   return NewFD;
16741 }
16742 
16743 /// Build a new FieldDecl and check its well-formedness.
16744 ///
16745 /// This routine builds a new FieldDecl given the fields name, type,
16746 /// record, etc. \p PrevDecl should refer to any previous declaration
16747 /// with the same name and in the same scope as the field to be
16748 /// created.
16749 ///
16750 /// \returns a new FieldDecl.
16751 ///
16752 /// \todo The Declarator argument is a hack. It will be removed once
16753 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
16754                                 TypeSourceInfo *TInfo,
16755                                 RecordDecl *Record, SourceLocation Loc,
16756                                 bool Mutable, Expr *BitWidth,
16757                                 InClassInitStyle InitStyle,
16758                                 SourceLocation TSSL,
16759                                 AccessSpecifier AS, NamedDecl *PrevDecl,
16760                                 Declarator *D) {
16761   IdentifierInfo *II = Name.getAsIdentifierInfo();
16762   bool InvalidDecl = false;
16763   if (D) InvalidDecl = D->isInvalidType();
16764 
16765   // If we receive a broken type, recover by assuming 'int' and
16766   // marking this declaration as invalid.
16767   if (T.isNull() || T->containsErrors()) {
16768     InvalidDecl = true;
16769     T = Context.IntTy;
16770   }
16771 
16772   QualType EltTy = Context.getBaseElementType(T);
16773   if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
16774     if (RequireCompleteSizedType(Loc, EltTy,
16775                                  diag::err_field_incomplete_or_sizeless)) {
16776       // Fields of incomplete type force their record to be invalid.
16777       Record->setInvalidDecl();
16778       InvalidDecl = true;
16779     } else {
16780       NamedDecl *Def;
16781       EltTy->isIncompleteType(&Def);
16782       if (Def && Def->isInvalidDecl()) {
16783         Record->setInvalidDecl();
16784         InvalidDecl = true;
16785       }
16786     }
16787   }
16788 
16789   // TR 18037 does not allow fields to be declared with address space
16790   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
16791       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
16792     Diag(Loc, diag::err_field_with_address_space);
16793     Record->setInvalidDecl();
16794     InvalidDecl = true;
16795   }
16796 
16797   if (LangOpts.OpenCL) {
16798     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
16799     // used as structure or union field: image, sampler, event or block types.
16800     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
16801         T->isBlockPointerType()) {
16802       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
16803       Record->setInvalidDecl();
16804       InvalidDecl = true;
16805     }
16806     // OpenCL v1.2 s6.9.c: bitfields are not supported.
16807     if (BitWidth) {
16808       Diag(Loc, diag::err_opencl_bitfields);
16809       InvalidDecl = true;
16810     }
16811   }
16812 
16813   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
16814   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
16815       T.hasQualifiers()) {
16816     InvalidDecl = true;
16817     Diag(Loc, diag::err_anon_bitfield_qualifiers);
16818   }
16819 
16820   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16821   // than a variably modified type.
16822   if (!InvalidDecl && T->isVariablyModifiedType()) {
16823     if (!tryToFixVariablyModifiedVarType(
16824             TInfo, T, Loc, diag::err_typecheck_field_variable_size))
16825       InvalidDecl = true;
16826   }
16827 
16828   // Fields can not have abstract class types
16829   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
16830                                              diag::err_abstract_type_in_decl,
16831                                              AbstractFieldType))
16832     InvalidDecl = true;
16833 
16834   bool ZeroWidth = false;
16835   if (InvalidDecl)
16836     BitWidth = nullptr;
16837   // If this is declared as a bit-field, check the bit-field.
16838   if (BitWidth) {
16839     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
16840                               &ZeroWidth).get();
16841     if (!BitWidth) {
16842       InvalidDecl = true;
16843       BitWidth = nullptr;
16844       ZeroWidth = false;
16845     }
16846   }
16847 
16848   // Check that 'mutable' is consistent with the type of the declaration.
16849   if (!InvalidDecl && Mutable) {
16850     unsigned DiagID = 0;
16851     if (T->isReferenceType())
16852       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
16853                                         : diag::err_mutable_reference;
16854     else if (T.isConstQualified())
16855       DiagID = diag::err_mutable_const;
16856 
16857     if (DiagID) {
16858       SourceLocation ErrLoc = Loc;
16859       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
16860         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
16861       Diag(ErrLoc, DiagID);
16862       if (DiagID != diag::ext_mutable_reference) {
16863         Mutable = false;
16864         InvalidDecl = true;
16865       }
16866     }
16867   }
16868 
16869   // C++11 [class.union]p8 (DR1460):
16870   //   At most one variant member of a union may have a
16871   //   brace-or-equal-initializer.
16872   if (InitStyle != ICIS_NoInit)
16873     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
16874 
16875   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
16876                                        BitWidth, Mutable, InitStyle);
16877   if (InvalidDecl)
16878     NewFD->setInvalidDecl();
16879 
16880   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
16881     Diag(Loc, diag::err_duplicate_member) << II;
16882     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16883     NewFD->setInvalidDecl();
16884   }
16885 
16886   if (!InvalidDecl && getLangOpts().CPlusPlus) {
16887     if (Record->isUnion()) {
16888       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16889         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
16890         if (RDecl->getDefinition()) {
16891           // C++ [class.union]p1: An object of a class with a non-trivial
16892           // constructor, a non-trivial copy constructor, a non-trivial
16893           // destructor, or a non-trivial copy assignment operator
16894           // cannot be a member of a union, nor can an array of such
16895           // objects.
16896           if (CheckNontrivialField(NewFD))
16897             NewFD->setInvalidDecl();
16898         }
16899       }
16900 
16901       // C++ [class.union]p1: If a union contains a member of reference type,
16902       // the program is ill-formed, except when compiling with MSVC extensions
16903       // enabled.
16904       if (EltTy->isReferenceType()) {
16905         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
16906                                     diag::ext_union_member_of_reference_type :
16907                                     diag::err_union_member_of_reference_type)
16908           << NewFD->getDeclName() << EltTy;
16909         if (!getLangOpts().MicrosoftExt)
16910           NewFD->setInvalidDecl();
16911       }
16912     }
16913   }
16914 
16915   // FIXME: We need to pass in the attributes given an AST
16916   // representation, not a parser representation.
16917   if (D) {
16918     // FIXME: The current scope is almost... but not entirely... correct here.
16919     ProcessDeclAttributes(getCurScope(), NewFD, *D);
16920 
16921     if (NewFD->hasAttrs())
16922       CheckAlignasUnderalignment(NewFD);
16923   }
16924 
16925   // In auto-retain/release, infer strong retension for fields of
16926   // retainable type.
16927   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
16928     NewFD->setInvalidDecl();
16929 
16930   if (T.isObjCGCWeak())
16931     Diag(Loc, diag::warn_attribute_weak_on_field);
16932 
16933   // PPC MMA non-pointer types are not allowed as field types.
16934   if (Context.getTargetInfo().getTriple().isPPC64() &&
16935       CheckPPCMMAType(T, NewFD->getLocation()))
16936     NewFD->setInvalidDecl();
16937 
16938   NewFD->setAccess(AS);
16939   return NewFD;
16940 }
16941 
16942 bool Sema::CheckNontrivialField(FieldDecl *FD) {
16943   assert(FD);
16944   assert(getLangOpts().CPlusPlus && "valid check only for C++");
16945 
16946   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
16947     return false;
16948 
16949   QualType EltTy = Context.getBaseElementType(FD->getType());
16950   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16951     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
16952     if (RDecl->getDefinition()) {
16953       // We check for copy constructors before constructors
16954       // because otherwise we'll never get complaints about
16955       // copy constructors.
16956 
16957       CXXSpecialMember member = CXXInvalid;
16958       // We're required to check for any non-trivial constructors. Since the
16959       // implicit default constructor is suppressed if there are any
16960       // user-declared constructors, we just need to check that there is a
16961       // trivial default constructor and a trivial copy constructor. (We don't
16962       // worry about move constructors here, since this is a C++98 check.)
16963       if (RDecl->hasNonTrivialCopyConstructor())
16964         member = CXXCopyConstructor;
16965       else if (!RDecl->hasTrivialDefaultConstructor())
16966         member = CXXDefaultConstructor;
16967       else if (RDecl->hasNonTrivialCopyAssignment())
16968         member = CXXCopyAssignment;
16969       else if (RDecl->hasNonTrivialDestructor())
16970         member = CXXDestructor;
16971 
16972       if (member != CXXInvalid) {
16973         if (!getLangOpts().CPlusPlus11 &&
16974             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
16975           // Objective-C++ ARC: it is an error to have a non-trivial field of
16976           // a union. However, system headers in Objective-C programs
16977           // occasionally have Objective-C lifetime objects within unions,
16978           // and rather than cause the program to fail, we make those
16979           // members unavailable.
16980           SourceLocation Loc = FD->getLocation();
16981           if (getSourceManager().isInSystemHeader(Loc)) {
16982             if (!FD->hasAttr<UnavailableAttr>())
16983               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
16984                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
16985             return false;
16986           }
16987         }
16988 
16989         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
16990                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
16991                diag::err_illegal_union_or_anon_struct_member)
16992           << FD->getParent()->isUnion() << FD->getDeclName() << member;
16993         DiagnoseNontrivial(RDecl, member);
16994         return !getLangOpts().CPlusPlus11;
16995       }
16996     }
16997   }
16998 
16999   return false;
17000 }
17001 
17002 /// TranslateIvarVisibility - Translate visibility from a token ID to an
17003 ///  AST enum value.
17004 static ObjCIvarDecl::AccessControl
17005 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
17006   switch (ivarVisibility) {
17007   default: llvm_unreachable("Unknown visitibility kind");
17008   case tok::objc_private: return ObjCIvarDecl::Private;
17009   case tok::objc_public: return ObjCIvarDecl::Public;
17010   case tok::objc_protected: return ObjCIvarDecl::Protected;
17011   case tok::objc_package: return ObjCIvarDecl::Package;
17012   }
17013 }
17014 
17015 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
17016 /// in order to create an IvarDecl object for it.
17017 Decl *Sema::ActOnIvar(Scope *S,
17018                                 SourceLocation DeclStart,
17019                                 Declarator &D, Expr *BitfieldWidth,
17020                                 tok::ObjCKeywordKind Visibility) {
17021 
17022   IdentifierInfo *II = D.getIdentifier();
17023   Expr *BitWidth = (Expr*)BitfieldWidth;
17024   SourceLocation Loc = DeclStart;
17025   if (II) Loc = D.getIdentifierLoc();
17026 
17027   // FIXME: Unnamed fields can be handled in various different ways, for
17028   // example, unnamed unions inject all members into the struct namespace!
17029 
17030   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17031   QualType T = TInfo->getType();
17032 
17033   if (BitWidth) {
17034     // 6.7.2.1p3, 6.7.2.1p4
17035     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
17036     if (!BitWidth)
17037       D.setInvalidType();
17038   } else {
17039     // Not a bitfield.
17040 
17041     // validate II.
17042 
17043   }
17044   if (T->isReferenceType()) {
17045     Diag(Loc, diag::err_ivar_reference_type);
17046     D.setInvalidType();
17047   }
17048   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17049   // than a variably modified type.
17050   else if (T->isVariablyModifiedType()) {
17051     if (!tryToFixVariablyModifiedVarType(
17052             TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
17053       D.setInvalidType();
17054   }
17055 
17056   // Get the visibility (access control) for this ivar.
17057   ObjCIvarDecl::AccessControl ac =
17058     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
17059                                         : ObjCIvarDecl::None;
17060   // Must set ivar's DeclContext to its enclosing interface.
17061   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
17062   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
17063     return nullptr;
17064   ObjCContainerDecl *EnclosingContext;
17065   if (ObjCImplementationDecl *IMPDecl =
17066       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17067     if (LangOpts.ObjCRuntime.isFragile()) {
17068     // Case of ivar declared in an implementation. Context is that of its class.
17069       EnclosingContext = IMPDecl->getClassInterface();
17070       assert(EnclosingContext && "Implementation has no class interface!");
17071     }
17072     else
17073       EnclosingContext = EnclosingDecl;
17074   } else {
17075     if (ObjCCategoryDecl *CDecl =
17076         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17077       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
17078         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
17079         return nullptr;
17080       }
17081     }
17082     EnclosingContext = EnclosingDecl;
17083   }
17084 
17085   // Construct the decl.
17086   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
17087                                              DeclStart, Loc, II, T,
17088                                              TInfo, ac, (Expr *)BitfieldWidth);
17089 
17090   if (II) {
17091     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
17092                                            ForVisibleRedeclaration);
17093     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
17094         && !isa<TagDecl>(PrevDecl)) {
17095       Diag(Loc, diag::err_duplicate_member) << II;
17096       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17097       NewID->setInvalidDecl();
17098     }
17099   }
17100 
17101   // Process attributes attached to the ivar.
17102   ProcessDeclAttributes(S, NewID, D);
17103 
17104   if (D.isInvalidType())
17105     NewID->setInvalidDecl();
17106 
17107   // In ARC, infer 'retaining' for ivars of retainable type.
17108   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
17109     NewID->setInvalidDecl();
17110 
17111   if (D.getDeclSpec().isModulePrivateSpecified())
17112     NewID->setModulePrivate();
17113 
17114   if (II) {
17115     // FIXME: When interfaces are DeclContexts, we'll need to add
17116     // these to the interface.
17117     S->AddDecl(NewID);
17118     IdResolver.AddDecl(NewID);
17119   }
17120 
17121   if (LangOpts.ObjCRuntime.isNonFragile() &&
17122       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
17123     Diag(Loc, diag::warn_ivars_in_interface);
17124 
17125   return NewID;
17126 }
17127 
17128 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
17129 /// class and class extensions. For every class \@interface and class
17130 /// extension \@interface, if the last ivar is a bitfield of any type,
17131 /// then add an implicit `char :0` ivar to the end of that interface.
17132 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
17133                              SmallVectorImpl<Decl *> &AllIvarDecls) {
17134   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
17135     return;
17136 
17137   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
17138   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
17139 
17140   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
17141     return;
17142   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
17143   if (!ID) {
17144     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
17145       if (!CD->IsClassExtension())
17146         return;
17147     }
17148     // No need to add this to end of @implementation.
17149     else
17150       return;
17151   }
17152   // All conditions are met. Add a new bitfield to the tail end of ivars.
17153   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
17154   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
17155 
17156   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17157                               DeclLoc, DeclLoc, nullptr,
17158                               Context.CharTy,
17159                               Context.getTrivialTypeSourceInfo(Context.CharTy,
17160                                                                DeclLoc),
17161                               ObjCIvarDecl::Private, BW,
17162                               true);
17163   AllIvarDecls.push_back(Ivar);
17164 }
17165 
17166 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17167                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
17168                        SourceLocation RBrac,
17169                        const ParsedAttributesView &Attrs) {
17170   assert(EnclosingDecl && "missing record or interface decl");
17171 
17172   // If this is an Objective-C @implementation or category and we have
17173   // new fields here we should reset the layout of the interface since
17174   // it will now change.
17175   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17176     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17177     switch (DC->getKind()) {
17178     default: break;
17179     case Decl::ObjCCategory:
17180       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17181       break;
17182     case Decl::ObjCImplementation:
17183       Context.
17184         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17185       break;
17186     }
17187   }
17188 
17189   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17190   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17191 
17192   // Start counting up the number of named members; make sure to include
17193   // members of anonymous structs and unions in the total.
17194   unsigned NumNamedMembers = 0;
17195   if (Record) {
17196     for (const auto *I : Record->decls()) {
17197       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17198         if (IFD->getDeclName())
17199           ++NumNamedMembers;
17200     }
17201   }
17202 
17203   // Verify that all the fields are okay.
17204   SmallVector<FieldDecl*, 32> RecFields;
17205 
17206   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17207        i != end; ++i) {
17208     FieldDecl *FD = cast<FieldDecl>(*i);
17209 
17210     // Get the type for the field.
17211     const Type *FDTy = FD->getType().getTypePtr();
17212 
17213     if (!FD->isAnonymousStructOrUnion()) {
17214       // Remember all fields written by the user.
17215       RecFields.push_back(FD);
17216     }
17217 
17218     // If the field is already invalid for some reason, don't emit more
17219     // diagnostics about it.
17220     if (FD->isInvalidDecl()) {
17221       EnclosingDecl->setInvalidDecl();
17222       continue;
17223     }
17224 
17225     // C99 6.7.2.1p2:
17226     //   A structure or union shall not contain a member with
17227     //   incomplete or function type (hence, a structure shall not
17228     //   contain an instance of itself, but may contain a pointer to
17229     //   an instance of itself), except that the last member of a
17230     //   structure with more than one named member may have incomplete
17231     //   array type; such a structure (and any union containing,
17232     //   possibly recursively, a member that is such a structure)
17233     //   shall not be a member of a structure or an element of an
17234     //   array.
17235     bool IsLastField = (i + 1 == Fields.end());
17236     if (FDTy->isFunctionType()) {
17237       // Field declared as a function.
17238       Diag(FD->getLocation(), diag::err_field_declared_as_function)
17239         << FD->getDeclName();
17240       FD->setInvalidDecl();
17241       EnclosingDecl->setInvalidDecl();
17242       continue;
17243     } else if (FDTy->isIncompleteArrayType() &&
17244                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17245       if (Record) {
17246         // Flexible array member.
17247         // Microsoft and g++ is more permissive regarding flexible array.
17248         // It will accept flexible array in union and also
17249         // as the sole element of a struct/class.
17250         unsigned DiagID = 0;
17251         if (!Record->isUnion() && !IsLastField) {
17252           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17253             << FD->getDeclName() << FD->getType() << Record->getTagKind();
17254           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17255           FD->setInvalidDecl();
17256           EnclosingDecl->setInvalidDecl();
17257           continue;
17258         } else if (Record->isUnion())
17259           DiagID = getLangOpts().MicrosoftExt
17260                        ? diag::ext_flexible_array_union_ms
17261                        : getLangOpts().CPlusPlus
17262                              ? diag::ext_flexible_array_union_gnu
17263                              : diag::err_flexible_array_union;
17264         else if (NumNamedMembers < 1)
17265           DiagID = getLangOpts().MicrosoftExt
17266                        ? diag::ext_flexible_array_empty_aggregate_ms
17267                        : getLangOpts().CPlusPlus
17268                              ? diag::ext_flexible_array_empty_aggregate_gnu
17269                              : diag::err_flexible_array_empty_aggregate;
17270 
17271         if (DiagID)
17272           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17273                                           << Record->getTagKind();
17274         // While the layout of types that contain virtual bases is not specified
17275         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17276         // virtual bases after the derived members.  This would make a flexible
17277         // array member declared at the end of an object not adjacent to the end
17278         // of the type.
17279         if (CXXRecord && CXXRecord->getNumVBases() != 0)
17280           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17281               << FD->getDeclName() << Record->getTagKind();
17282         if (!getLangOpts().C99)
17283           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17284             << FD->getDeclName() << Record->getTagKind();
17285 
17286         // If the element type has a non-trivial destructor, we would not
17287         // implicitly destroy the elements, so disallow it for now.
17288         //
17289         // FIXME: GCC allows this. We should probably either implicitly delete
17290         // the destructor of the containing class, or just allow this.
17291         QualType BaseElem = Context.getBaseElementType(FD->getType());
17292         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17293           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17294             << FD->getDeclName() << FD->getType();
17295           FD->setInvalidDecl();
17296           EnclosingDecl->setInvalidDecl();
17297           continue;
17298         }
17299         // Okay, we have a legal flexible array member at the end of the struct.
17300         Record->setHasFlexibleArrayMember(true);
17301       } else {
17302         // In ObjCContainerDecl ivars with incomplete array type are accepted,
17303         // unless they are followed by another ivar. That check is done
17304         // elsewhere, after synthesized ivars are known.
17305       }
17306     } else if (!FDTy->isDependentType() &&
17307                RequireCompleteSizedType(
17308                    FD->getLocation(), FD->getType(),
17309                    diag::err_field_incomplete_or_sizeless)) {
17310       // Incomplete type
17311       FD->setInvalidDecl();
17312       EnclosingDecl->setInvalidDecl();
17313       continue;
17314     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
17315       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
17316         // A type which contains a flexible array member is considered to be a
17317         // flexible array member.
17318         Record->setHasFlexibleArrayMember(true);
17319         if (!Record->isUnion()) {
17320           // If this is a struct/class and this is not the last element, reject
17321           // it.  Note that GCC supports variable sized arrays in the middle of
17322           // structures.
17323           if (!IsLastField)
17324             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
17325               << FD->getDeclName() << FD->getType();
17326           else {
17327             // We support flexible arrays at the end of structs in
17328             // other structs as an extension.
17329             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
17330               << FD->getDeclName();
17331           }
17332         }
17333       }
17334       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17335           RequireNonAbstractType(FD->getLocation(), FD->getType(),
17336                                  diag::err_abstract_type_in_decl,
17337                                  AbstractIvarType)) {
17338         // Ivars can not have abstract class types
17339         FD->setInvalidDecl();
17340       }
17341       if (Record && FDTTy->getDecl()->hasObjectMember())
17342         Record->setHasObjectMember(true);
17343       if (Record && FDTTy->getDecl()->hasVolatileMember())
17344         Record->setHasVolatileMember(true);
17345     } else if (FDTy->isObjCObjectType()) {
17346       /// A field cannot be an Objective-c object
17347       Diag(FD->getLocation(), diag::err_statically_allocated_object)
17348         << FixItHint::CreateInsertion(FD->getLocation(), "*");
17349       QualType T = Context.getObjCObjectPointerType(FD->getType());
17350       FD->setType(T);
17351     } else if (Record && Record->isUnion() &&
17352                FD->getType().hasNonTrivialObjCLifetime() &&
17353                getSourceManager().isInSystemHeader(FD->getLocation()) &&
17354                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
17355                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
17356                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
17357       // For backward compatibility, fields of C unions declared in system
17358       // headers that have non-trivial ObjC ownership qualifications are marked
17359       // as unavailable unless the qualifier is explicit and __strong. This can
17360       // break ABI compatibility between programs compiled with ARC and MRR, but
17361       // is a better option than rejecting programs using those unions under
17362       // ARC.
17363       FD->addAttr(UnavailableAttr::CreateImplicit(
17364           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
17365           FD->getLocation()));
17366     } else if (getLangOpts().ObjC &&
17367                getLangOpts().getGC() != LangOptions::NonGC && Record &&
17368                !Record->hasObjectMember()) {
17369       if (FD->getType()->isObjCObjectPointerType() ||
17370           FD->getType().isObjCGCStrong())
17371         Record->setHasObjectMember(true);
17372       else if (Context.getAsArrayType(FD->getType())) {
17373         QualType BaseType = Context.getBaseElementType(FD->getType());
17374         if (BaseType->isRecordType() &&
17375             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
17376           Record->setHasObjectMember(true);
17377         else if (BaseType->isObjCObjectPointerType() ||
17378                  BaseType.isObjCGCStrong())
17379                Record->setHasObjectMember(true);
17380       }
17381     }
17382 
17383     if (Record && !getLangOpts().CPlusPlus &&
17384         !shouldIgnoreForRecordTriviality(FD)) {
17385       QualType FT = FD->getType();
17386       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
17387         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
17388         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
17389             Record->isUnion())
17390           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
17391       }
17392       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
17393       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
17394         Record->setNonTrivialToPrimitiveCopy(true);
17395         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
17396           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
17397       }
17398       if (FT.isDestructedType()) {
17399         Record->setNonTrivialToPrimitiveDestroy(true);
17400         Record->setParamDestroyedInCallee(true);
17401         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
17402           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
17403       }
17404 
17405       if (const auto *RT = FT->getAs<RecordType>()) {
17406         if (RT->getDecl()->getArgPassingRestrictions() ==
17407             RecordDecl::APK_CanNeverPassInRegs)
17408           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17409       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
17410         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17411     }
17412 
17413     if (Record && FD->getType().isVolatileQualified())
17414       Record->setHasVolatileMember(true);
17415     // Keep track of the number of named members.
17416     if (FD->getIdentifier())
17417       ++NumNamedMembers;
17418   }
17419 
17420   // Okay, we successfully defined 'Record'.
17421   if (Record) {
17422     bool Completed = false;
17423     if (CXXRecord) {
17424       if (!CXXRecord->isInvalidDecl()) {
17425         // Set access bits correctly on the directly-declared conversions.
17426         for (CXXRecordDecl::conversion_iterator
17427                I = CXXRecord->conversion_begin(),
17428                E = CXXRecord->conversion_end(); I != E; ++I)
17429           I.setAccess((*I)->getAccess());
17430       }
17431 
17432       // Add any implicitly-declared members to this class.
17433       AddImplicitlyDeclaredMembersToClass(CXXRecord);
17434 
17435       if (!CXXRecord->isDependentType()) {
17436         if (!CXXRecord->isInvalidDecl()) {
17437           // If we have virtual base classes, we may end up finding multiple
17438           // final overriders for a given virtual function. Check for this
17439           // problem now.
17440           if (CXXRecord->getNumVBases()) {
17441             CXXFinalOverriderMap FinalOverriders;
17442             CXXRecord->getFinalOverriders(FinalOverriders);
17443 
17444             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
17445                                              MEnd = FinalOverriders.end();
17446                  M != MEnd; ++M) {
17447               for (OverridingMethods::iterator SO = M->second.begin(),
17448                                             SOEnd = M->second.end();
17449                    SO != SOEnd; ++SO) {
17450                 assert(SO->second.size() > 0 &&
17451                        "Virtual function without overriding functions?");
17452                 if (SO->second.size() == 1)
17453                   continue;
17454 
17455                 // C++ [class.virtual]p2:
17456                 //   In a derived class, if a virtual member function of a base
17457                 //   class subobject has more than one final overrider the
17458                 //   program is ill-formed.
17459                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
17460                   << (const NamedDecl *)M->first << Record;
17461                 Diag(M->first->getLocation(),
17462                      diag::note_overridden_virtual_function);
17463                 for (OverridingMethods::overriding_iterator
17464                           OM = SO->second.begin(),
17465                        OMEnd = SO->second.end();
17466                      OM != OMEnd; ++OM)
17467                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
17468                     << (const NamedDecl *)M->first << OM->Method->getParent();
17469 
17470                 Record->setInvalidDecl();
17471               }
17472             }
17473             CXXRecord->completeDefinition(&FinalOverriders);
17474             Completed = true;
17475           }
17476         }
17477       }
17478     }
17479 
17480     if (!Completed)
17481       Record->completeDefinition();
17482 
17483     // Handle attributes before checking the layout.
17484     ProcessDeclAttributeList(S, Record, Attrs);
17485 
17486     // We may have deferred checking for a deleted destructor. Check now.
17487     if (CXXRecord) {
17488       auto *Dtor = CXXRecord->getDestructor();
17489       if (Dtor && Dtor->isImplicit() &&
17490           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
17491         CXXRecord->setImplicitDestructorIsDeleted();
17492         SetDeclDeleted(Dtor, CXXRecord->getLocation());
17493       }
17494     }
17495 
17496     if (Record->hasAttrs()) {
17497       CheckAlignasUnderalignment(Record);
17498 
17499       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
17500         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
17501                                            IA->getRange(), IA->getBestCase(),
17502                                            IA->getInheritanceModel());
17503     }
17504 
17505     // Check if the structure/union declaration is a type that can have zero
17506     // size in C. For C this is a language extension, for C++ it may cause
17507     // compatibility problems.
17508     bool CheckForZeroSize;
17509     if (!getLangOpts().CPlusPlus) {
17510       CheckForZeroSize = true;
17511     } else {
17512       // For C++ filter out types that cannot be referenced in C code.
17513       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
17514       CheckForZeroSize =
17515           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
17516           !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
17517           CXXRecord->isCLike();
17518     }
17519     if (CheckForZeroSize) {
17520       bool ZeroSize = true;
17521       bool IsEmpty = true;
17522       unsigned NonBitFields = 0;
17523       for (RecordDecl::field_iterator I = Record->field_begin(),
17524                                       E = Record->field_end();
17525            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
17526         IsEmpty = false;
17527         if (I->isUnnamedBitfield()) {
17528           if (!I->isZeroLengthBitField(Context))
17529             ZeroSize = false;
17530         } else {
17531           ++NonBitFields;
17532           QualType FieldType = I->getType();
17533           if (FieldType->isIncompleteType() ||
17534               !Context.getTypeSizeInChars(FieldType).isZero())
17535             ZeroSize = false;
17536         }
17537       }
17538 
17539       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
17540       // allowed in C++, but warn if its declaration is inside
17541       // extern "C" block.
17542       if (ZeroSize) {
17543         Diag(RecLoc, getLangOpts().CPlusPlus ?
17544                          diag::warn_zero_size_struct_union_in_extern_c :
17545                          diag::warn_zero_size_struct_union_compat)
17546           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
17547       }
17548 
17549       // Structs without named members are extension in C (C99 6.7.2.1p7),
17550       // but are accepted by GCC.
17551       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
17552         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
17553                                diag::ext_no_named_members_in_struct_union)
17554           << Record->isUnion();
17555       }
17556     }
17557   } else {
17558     ObjCIvarDecl **ClsFields =
17559       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
17560     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
17561       ID->setEndOfDefinitionLoc(RBrac);
17562       // Add ivar's to class's DeclContext.
17563       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17564         ClsFields[i]->setLexicalDeclContext(ID);
17565         ID->addDecl(ClsFields[i]);
17566       }
17567       // Must enforce the rule that ivars in the base classes may not be
17568       // duplicates.
17569       if (ID->getSuperClass())
17570         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
17571     } else if (ObjCImplementationDecl *IMPDecl =
17572                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17573       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
17574       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
17575         // Ivar declared in @implementation never belongs to the implementation.
17576         // Only it is in implementation's lexical context.
17577         ClsFields[I]->setLexicalDeclContext(IMPDecl);
17578       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
17579       IMPDecl->setIvarLBraceLoc(LBrac);
17580       IMPDecl->setIvarRBraceLoc(RBrac);
17581     } else if (ObjCCategoryDecl *CDecl =
17582                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17583       // case of ivars in class extension; all other cases have been
17584       // reported as errors elsewhere.
17585       // FIXME. Class extension does not have a LocEnd field.
17586       // CDecl->setLocEnd(RBrac);
17587       // Add ivar's to class extension's DeclContext.
17588       // Diagnose redeclaration of private ivars.
17589       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
17590       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17591         if (IDecl) {
17592           if (const ObjCIvarDecl *ClsIvar =
17593               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
17594             Diag(ClsFields[i]->getLocation(),
17595                  diag::err_duplicate_ivar_declaration);
17596             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
17597             continue;
17598           }
17599           for (const auto *Ext : IDecl->known_extensions()) {
17600             if (const ObjCIvarDecl *ClsExtIvar
17601                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
17602               Diag(ClsFields[i]->getLocation(),
17603                    diag::err_duplicate_ivar_declaration);
17604               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
17605               continue;
17606             }
17607           }
17608         }
17609         ClsFields[i]->setLexicalDeclContext(CDecl);
17610         CDecl->addDecl(ClsFields[i]);
17611       }
17612       CDecl->setIvarLBraceLoc(LBrac);
17613       CDecl->setIvarRBraceLoc(RBrac);
17614     }
17615   }
17616 }
17617 
17618 /// Determine whether the given integral value is representable within
17619 /// the given type T.
17620 static bool isRepresentableIntegerValue(ASTContext &Context,
17621                                         llvm::APSInt &Value,
17622                                         QualType T) {
17623   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
17624          "Integral type required!");
17625   unsigned BitWidth = Context.getIntWidth(T);
17626 
17627   if (Value.isUnsigned() || Value.isNonNegative()) {
17628     if (T->isSignedIntegerOrEnumerationType())
17629       --BitWidth;
17630     return Value.getActiveBits() <= BitWidth;
17631   }
17632   return Value.getMinSignedBits() <= BitWidth;
17633 }
17634 
17635 // Given an integral type, return the next larger integral type
17636 // (or a NULL type of no such type exists).
17637 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
17638   // FIXME: Int128/UInt128 support, which also needs to be introduced into
17639   // enum checking below.
17640   assert((T->isIntegralType(Context) ||
17641          T->isEnumeralType()) && "Integral type required!");
17642   const unsigned NumTypes = 4;
17643   QualType SignedIntegralTypes[NumTypes] = {
17644     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
17645   };
17646   QualType UnsignedIntegralTypes[NumTypes] = {
17647     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
17648     Context.UnsignedLongLongTy
17649   };
17650 
17651   unsigned BitWidth = Context.getTypeSize(T);
17652   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
17653                                                         : UnsignedIntegralTypes;
17654   for (unsigned I = 0; I != NumTypes; ++I)
17655     if (Context.getTypeSize(Types[I]) > BitWidth)
17656       return Types[I];
17657 
17658   return QualType();
17659 }
17660 
17661 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
17662                                           EnumConstantDecl *LastEnumConst,
17663                                           SourceLocation IdLoc,
17664                                           IdentifierInfo *Id,
17665                                           Expr *Val) {
17666   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17667   llvm::APSInt EnumVal(IntWidth);
17668   QualType EltTy;
17669 
17670   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
17671     Val = nullptr;
17672 
17673   if (Val)
17674     Val = DefaultLvalueConversion(Val).get();
17675 
17676   if (Val) {
17677     if (Enum->isDependentType() || Val->isTypeDependent())
17678       EltTy = Context.DependentTy;
17679     else {
17680       // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
17681       // underlying type, but do allow it in all other contexts.
17682       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
17683         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
17684         // constant-expression in the enumerator-definition shall be a converted
17685         // constant expression of the underlying type.
17686         EltTy = Enum->getIntegerType();
17687         ExprResult Converted =
17688           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
17689                                            CCEK_Enumerator);
17690         if (Converted.isInvalid())
17691           Val = nullptr;
17692         else
17693           Val = Converted.get();
17694       } else if (!Val->isValueDependent() &&
17695                  !(Val =
17696                        VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
17697                            .get())) {
17698         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
17699       } else {
17700         if (Enum->isComplete()) {
17701           EltTy = Enum->getIntegerType();
17702 
17703           // In Obj-C and Microsoft mode, require the enumeration value to be
17704           // representable in the underlying type of the enumeration. In C++11,
17705           // we perform a non-narrowing conversion as part of converted constant
17706           // expression checking.
17707           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17708             if (Context.getTargetInfo()
17709                     .getTriple()
17710                     .isWindowsMSVCEnvironment()) {
17711               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
17712             } else {
17713               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
17714             }
17715           }
17716 
17717           // Cast to the underlying type.
17718           Val = ImpCastExprToType(Val, EltTy,
17719                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
17720                                                          : CK_IntegralCast)
17721                     .get();
17722         } else if (getLangOpts().CPlusPlus) {
17723           // C++11 [dcl.enum]p5:
17724           //   If the underlying type is not fixed, the type of each enumerator
17725           //   is the type of its initializing value:
17726           //     - If an initializer is specified for an enumerator, the
17727           //       initializing value has the same type as the expression.
17728           EltTy = Val->getType();
17729         } else {
17730           // C99 6.7.2.2p2:
17731           //   The expression that defines the value of an enumeration constant
17732           //   shall be an integer constant expression that has a value
17733           //   representable as an int.
17734 
17735           // Complain if the value is not representable in an int.
17736           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
17737             Diag(IdLoc, diag::ext_enum_value_not_int)
17738               << EnumVal.toString(10) << Val->getSourceRange()
17739               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
17740           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
17741             // Force the type of the expression to 'int'.
17742             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
17743           }
17744           EltTy = Val->getType();
17745         }
17746       }
17747     }
17748   }
17749 
17750   if (!Val) {
17751     if (Enum->isDependentType())
17752       EltTy = Context.DependentTy;
17753     else if (!LastEnumConst) {
17754       // C++0x [dcl.enum]p5:
17755       //   If the underlying type is not fixed, the type of each enumerator
17756       //   is the type of its initializing value:
17757       //     - If no initializer is specified for the first enumerator, the
17758       //       initializing value has an unspecified integral type.
17759       //
17760       // GCC uses 'int' for its unspecified integral type, as does
17761       // C99 6.7.2.2p3.
17762       if (Enum->isFixed()) {
17763         EltTy = Enum->getIntegerType();
17764       }
17765       else {
17766         EltTy = Context.IntTy;
17767       }
17768     } else {
17769       // Assign the last value + 1.
17770       EnumVal = LastEnumConst->getInitVal();
17771       ++EnumVal;
17772       EltTy = LastEnumConst->getType();
17773 
17774       // Check for overflow on increment.
17775       if (EnumVal < LastEnumConst->getInitVal()) {
17776         // C++0x [dcl.enum]p5:
17777         //   If the underlying type is not fixed, the type of each enumerator
17778         //   is the type of its initializing value:
17779         //
17780         //     - Otherwise the type of the initializing value is the same as
17781         //       the type of the initializing value of the preceding enumerator
17782         //       unless the incremented value is not representable in that type,
17783         //       in which case the type is an unspecified integral type
17784         //       sufficient to contain the incremented value. If no such type
17785         //       exists, the program is ill-formed.
17786         QualType T = getNextLargerIntegralType(Context, EltTy);
17787         if (T.isNull() || Enum->isFixed()) {
17788           // There is no integral type larger enough to represent this
17789           // value. Complain, then allow the value to wrap around.
17790           EnumVal = LastEnumConst->getInitVal();
17791           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
17792           ++EnumVal;
17793           if (Enum->isFixed())
17794             // When the underlying type is fixed, this is ill-formed.
17795             Diag(IdLoc, diag::err_enumerator_wrapped)
17796               << EnumVal.toString(10)
17797               << EltTy;
17798           else
17799             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
17800               << EnumVal.toString(10);
17801         } else {
17802           EltTy = T;
17803         }
17804 
17805         // Retrieve the last enumerator's value, extent that type to the
17806         // type that is supposed to be large enough to represent the incremented
17807         // value, then increment.
17808         EnumVal = LastEnumConst->getInitVal();
17809         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17810         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
17811         ++EnumVal;
17812 
17813         // If we're not in C++, diagnose the overflow of enumerator values,
17814         // which in C99 means that the enumerator value is not representable in
17815         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
17816         // permits enumerator values that are representable in some larger
17817         // integral type.
17818         if (!getLangOpts().CPlusPlus && !T.isNull())
17819           Diag(IdLoc, diag::warn_enum_value_overflow);
17820       } else if (!getLangOpts().CPlusPlus &&
17821                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17822         // Enforce C99 6.7.2.2p2 even when we compute the next value.
17823         Diag(IdLoc, diag::ext_enum_value_not_int)
17824           << EnumVal.toString(10) << 1;
17825       }
17826     }
17827   }
17828 
17829   if (!EltTy->isDependentType()) {
17830     // Make the enumerator value match the signedness and size of the
17831     // enumerator's type.
17832     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
17833     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17834   }
17835 
17836   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
17837                                   Val, EnumVal);
17838 }
17839 
17840 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
17841                                                 SourceLocation IILoc) {
17842   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
17843       !getLangOpts().CPlusPlus)
17844     return SkipBodyInfo();
17845 
17846   // We have an anonymous enum definition. Look up the first enumerator to
17847   // determine if we should merge the definition with an existing one and
17848   // skip the body.
17849   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
17850                                          forRedeclarationInCurContext());
17851   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
17852   if (!PrevECD)
17853     return SkipBodyInfo();
17854 
17855   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
17856   NamedDecl *Hidden;
17857   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
17858     SkipBodyInfo Skip;
17859     Skip.Previous = Hidden;
17860     return Skip;
17861   }
17862 
17863   return SkipBodyInfo();
17864 }
17865 
17866 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
17867                               SourceLocation IdLoc, IdentifierInfo *Id,
17868                               const ParsedAttributesView &Attrs,
17869                               SourceLocation EqualLoc, Expr *Val) {
17870   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
17871   EnumConstantDecl *LastEnumConst =
17872     cast_or_null<EnumConstantDecl>(lastEnumConst);
17873 
17874   // The scope passed in may not be a decl scope.  Zip up the scope tree until
17875   // we find one that is.
17876   S = getNonFieldDeclScope(S);
17877 
17878   // Verify that there isn't already something declared with this name in this
17879   // scope.
17880   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
17881   LookupName(R, S);
17882   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
17883 
17884   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17885     // Maybe we will complain about the shadowed template parameter.
17886     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
17887     // Just pretend that we didn't see the previous declaration.
17888     PrevDecl = nullptr;
17889   }
17890 
17891   // C++ [class.mem]p15:
17892   // If T is the name of a class, then each of the following shall have a name
17893   // different from T:
17894   // - every enumerator of every member of class T that is an unscoped
17895   // enumerated type
17896   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
17897     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
17898                             DeclarationNameInfo(Id, IdLoc));
17899 
17900   EnumConstantDecl *New =
17901     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
17902   if (!New)
17903     return nullptr;
17904 
17905   if (PrevDecl) {
17906     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
17907       // Check for other kinds of shadowing not already handled.
17908       CheckShadow(New, PrevDecl, R);
17909     }
17910 
17911     // When in C++, we may get a TagDecl with the same name; in this case the
17912     // enum constant will 'hide' the tag.
17913     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
17914            "Received TagDecl when not in C++!");
17915     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
17916       if (isa<EnumConstantDecl>(PrevDecl))
17917         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
17918       else
17919         Diag(IdLoc, diag::err_redefinition) << Id;
17920       notePreviousDefinition(PrevDecl, IdLoc);
17921       return nullptr;
17922     }
17923   }
17924 
17925   // Process attributes.
17926   ProcessDeclAttributeList(S, New, Attrs);
17927   AddPragmaAttributes(S, New);
17928 
17929   // Register this decl in the current scope stack.
17930   New->setAccess(TheEnumDecl->getAccess());
17931   PushOnScopeChains(New, S);
17932 
17933   ActOnDocumentableDecl(New);
17934 
17935   return New;
17936 }
17937 
17938 // Returns true when the enum initial expression does not trigger the
17939 // duplicate enum warning.  A few common cases are exempted as follows:
17940 // Element2 = Element1
17941 // Element2 = Element1 + 1
17942 // Element2 = Element1 - 1
17943 // Where Element2 and Element1 are from the same enum.
17944 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
17945   Expr *InitExpr = ECD->getInitExpr();
17946   if (!InitExpr)
17947     return true;
17948   InitExpr = InitExpr->IgnoreImpCasts();
17949 
17950   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
17951     if (!BO->isAdditiveOp())
17952       return true;
17953     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
17954     if (!IL)
17955       return true;
17956     if (IL->getValue() != 1)
17957       return true;
17958 
17959     InitExpr = BO->getLHS();
17960   }
17961 
17962   // This checks if the elements are from the same enum.
17963   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
17964   if (!DRE)
17965     return true;
17966 
17967   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
17968   if (!EnumConstant)
17969     return true;
17970 
17971   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
17972       Enum)
17973     return true;
17974 
17975   return false;
17976 }
17977 
17978 // Emits a warning when an element is implicitly set a value that
17979 // a previous element has already been set to.
17980 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
17981                                         EnumDecl *Enum, QualType EnumType) {
17982   // Avoid anonymous enums
17983   if (!Enum->getIdentifier())
17984     return;
17985 
17986   // Only check for small enums.
17987   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
17988     return;
17989 
17990   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
17991     return;
17992 
17993   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
17994   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
17995 
17996   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
17997 
17998   // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
17999   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
18000 
18001   // Use int64_t as a key to avoid needing special handling for map keys.
18002   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
18003     llvm::APSInt Val = D->getInitVal();
18004     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
18005   };
18006 
18007   DuplicatesVector DupVector;
18008   ValueToVectorMap EnumMap;
18009 
18010   // Populate the EnumMap with all values represented by enum constants without
18011   // an initializer.
18012   for (auto *Element : Elements) {
18013     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
18014 
18015     // Null EnumConstantDecl means a previous diagnostic has been emitted for
18016     // this constant.  Skip this enum since it may be ill-formed.
18017     if (!ECD) {
18018       return;
18019     }
18020 
18021     // Constants with initalizers are handled in the next loop.
18022     if (ECD->getInitExpr())
18023       continue;
18024 
18025     // Duplicate values are handled in the next loop.
18026     EnumMap.insert({EnumConstantToKey(ECD), ECD});
18027   }
18028 
18029   if (EnumMap.size() == 0)
18030     return;
18031 
18032   // Create vectors for any values that has duplicates.
18033   for (auto *Element : Elements) {
18034     // The last loop returned if any constant was null.
18035     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
18036     if (!ValidDuplicateEnum(ECD, Enum))
18037       continue;
18038 
18039     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
18040     if (Iter == EnumMap.end())
18041       continue;
18042 
18043     DeclOrVector& Entry = Iter->second;
18044     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
18045       // Ensure constants are different.
18046       if (D == ECD)
18047         continue;
18048 
18049       // Create new vector and push values onto it.
18050       auto Vec = std::make_unique<ECDVector>();
18051       Vec->push_back(D);
18052       Vec->push_back(ECD);
18053 
18054       // Update entry to point to the duplicates vector.
18055       Entry = Vec.get();
18056 
18057       // Store the vector somewhere we can consult later for quick emission of
18058       // diagnostics.
18059       DupVector.emplace_back(std::move(Vec));
18060       continue;
18061     }
18062 
18063     ECDVector *Vec = Entry.get<ECDVector*>();
18064     // Make sure constants are not added more than once.
18065     if (*Vec->begin() == ECD)
18066       continue;
18067 
18068     Vec->push_back(ECD);
18069   }
18070 
18071   // Emit diagnostics.
18072   for (const auto &Vec : DupVector) {
18073     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
18074 
18075     // Emit warning for one enum constant.
18076     auto *FirstECD = Vec->front();
18077     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
18078       << FirstECD << FirstECD->getInitVal().toString(10)
18079       << FirstECD->getSourceRange();
18080 
18081     // Emit one note for each of the remaining enum constants with
18082     // the same value.
18083     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
18084       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
18085         << ECD << ECD->getInitVal().toString(10)
18086         << ECD->getSourceRange();
18087   }
18088 }
18089 
18090 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
18091                              bool AllowMask) const {
18092   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
18093   assert(ED->isCompleteDefinition() && "expected enum definition");
18094 
18095   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
18096   llvm::APInt &FlagBits = R.first->second;
18097 
18098   if (R.second) {
18099     for (auto *E : ED->enumerators()) {
18100       const auto &EVal = E->getInitVal();
18101       // Only single-bit enumerators introduce new flag values.
18102       if (EVal.isPowerOf2())
18103         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
18104     }
18105   }
18106 
18107   // A value is in a flag enum if either its bits are a subset of the enum's
18108   // flag bits (the first condition) or we are allowing masks and the same is
18109   // true of its complement (the second condition). When masks are allowed, we
18110   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
18111   //
18112   // While it's true that any value could be used as a mask, the assumption is
18113   // that a mask will have all of the insignificant bits set. Anything else is
18114   // likely a logic error.
18115   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
18116   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
18117 }
18118 
18119 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
18120                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
18121                          const ParsedAttributesView &Attrs) {
18122   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
18123   QualType EnumType = Context.getTypeDeclType(Enum);
18124 
18125   ProcessDeclAttributeList(S, Enum, Attrs);
18126 
18127   if (Enum->isDependentType()) {
18128     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18129       EnumConstantDecl *ECD =
18130         cast_or_null<EnumConstantDecl>(Elements[i]);
18131       if (!ECD) continue;
18132 
18133       ECD->setType(EnumType);
18134     }
18135 
18136     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
18137     return;
18138   }
18139 
18140   // TODO: If the result value doesn't fit in an int, it must be a long or long
18141   // long value.  ISO C does not support this, but GCC does as an extension,
18142   // emit a warning.
18143   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18144   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
18145   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
18146 
18147   // Verify that all the values are okay, compute the size of the values, and
18148   // reverse the list.
18149   unsigned NumNegativeBits = 0;
18150   unsigned NumPositiveBits = 0;
18151 
18152   // Keep track of whether all elements have type int.
18153   bool AllElementsInt = true;
18154 
18155   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18156     EnumConstantDecl *ECD =
18157       cast_or_null<EnumConstantDecl>(Elements[i]);
18158     if (!ECD) continue;  // Already issued a diagnostic.
18159 
18160     const llvm::APSInt &InitVal = ECD->getInitVal();
18161 
18162     // Keep track of the size of positive and negative values.
18163     if (InitVal.isUnsigned() || InitVal.isNonNegative())
18164       NumPositiveBits = std::max(NumPositiveBits,
18165                                  (unsigned)InitVal.getActiveBits());
18166     else
18167       NumNegativeBits = std::max(NumNegativeBits,
18168                                  (unsigned)InitVal.getMinSignedBits());
18169 
18170     // Keep track of whether every enum element has type int (very common).
18171     if (AllElementsInt)
18172       AllElementsInt = ECD->getType() == Context.IntTy;
18173   }
18174 
18175   // Figure out the type that should be used for this enum.
18176   QualType BestType;
18177   unsigned BestWidth;
18178 
18179   // C++0x N3000 [conv.prom]p3:
18180   //   An rvalue of an unscoped enumeration type whose underlying
18181   //   type is not fixed can be converted to an rvalue of the first
18182   //   of the following types that can represent all the values of
18183   //   the enumeration: int, unsigned int, long int, unsigned long
18184   //   int, long long int, or unsigned long long int.
18185   // C99 6.4.4.3p2:
18186   //   An identifier declared as an enumeration constant has type int.
18187   // The C99 rule is modified by a gcc extension
18188   QualType BestPromotionType;
18189 
18190   bool Packed = Enum->hasAttr<PackedAttr>();
18191   // -fshort-enums is the equivalent to specifying the packed attribute on all
18192   // enum definitions.
18193   if (LangOpts.ShortEnums)
18194     Packed = true;
18195 
18196   // If the enum already has a type because it is fixed or dictated by the
18197   // target, promote that type instead of analyzing the enumerators.
18198   if (Enum->isComplete()) {
18199     BestType = Enum->getIntegerType();
18200     if (BestType->isPromotableIntegerType())
18201       BestPromotionType = Context.getPromotedIntegerType(BestType);
18202     else
18203       BestPromotionType = BestType;
18204 
18205     BestWidth = Context.getIntWidth(BestType);
18206   }
18207   else if (NumNegativeBits) {
18208     // If there is a negative value, figure out the smallest integer type (of
18209     // int/long/longlong) that fits.
18210     // If it's packed, check also if it fits a char or a short.
18211     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18212       BestType = Context.SignedCharTy;
18213       BestWidth = CharWidth;
18214     } else if (Packed && NumNegativeBits <= ShortWidth &&
18215                NumPositiveBits < ShortWidth) {
18216       BestType = Context.ShortTy;
18217       BestWidth = ShortWidth;
18218     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18219       BestType = Context.IntTy;
18220       BestWidth = IntWidth;
18221     } else {
18222       BestWidth = Context.getTargetInfo().getLongWidth();
18223 
18224       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18225         BestType = Context.LongTy;
18226       } else {
18227         BestWidth = Context.getTargetInfo().getLongLongWidth();
18228 
18229         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18230           Diag(Enum->getLocation(), diag::ext_enum_too_large);
18231         BestType = Context.LongLongTy;
18232       }
18233     }
18234     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18235   } else {
18236     // If there is no negative value, figure out the smallest type that fits
18237     // all of the enumerator values.
18238     // If it's packed, check also if it fits a char or a short.
18239     if (Packed && NumPositiveBits <= CharWidth) {
18240       BestType = Context.UnsignedCharTy;
18241       BestPromotionType = Context.IntTy;
18242       BestWidth = CharWidth;
18243     } else if (Packed && NumPositiveBits <= ShortWidth) {
18244       BestType = Context.UnsignedShortTy;
18245       BestPromotionType = Context.IntTy;
18246       BestWidth = ShortWidth;
18247     } else if (NumPositiveBits <= IntWidth) {
18248       BestType = Context.UnsignedIntTy;
18249       BestWidth = IntWidth;
18250       BestPromotionType
18251         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18252                            ? Context.UnsignedIntTy : Context.IntTy;
18253     } else if (NumPositiveBits <=
18254                (BestWidth = Context.getTargetInfo().getLongWidth())) {
18255       BestType = Context.UnsignedLongTy;
18256       BestPromotionType
18257         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18258                            ? Context.UnsignedLongTy : Context.LongTy;
18259     } else {
18260       BestWidth = Context.getTargetInfo().getLongLongWidth();
18261       assert(NumPositiveBits <= BestWidth &&
18262              "How could an initializer get larger than ULL?");
18263       BestType = Context.UnsignedLongLongTy;
18264       BestPromotionType
18265         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18266                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
18267     }
18268   }
18269 
18270   // Loop over all of the enumerator constants, changing their types to match
18271   // the type of the enum if needed.
18272   for (auto *D : Elements) {
18273     auto *ECD = cast_or_null<EnumConstantDecl>(D);
18274     if (!ECD) continue;  // Already issued a diagnostic.
18275 
18276     // Standard C says the enumerators have int type, but we allow, as an
18277     // extension, the enumerators to be larger than int size.  If each
18278     // enumerator value fits in an int, type it as an int, otherwise type it the
18279     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
18280     // that X has type 'int', not 'unsigned'.
18281 
18282     // Determine whether the value fits into an int.
18283     llvm::APSInt InitVal = ECD->getInitVal();
18284 
18285     // If it fits into an integer type, force it.  Otherwise force it to match
18286     // the enum decl type.
18287     QualType NewTy;
18288     unsigned NewWidth;
18289     bool NewSign;
18290     if (!getLangOpts().CPlusPlus &&
18291         !Enum->isFixed() &&
18292         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
18293       NewTy = Context.IntTy;
18294       NewWidth = IntWidth;
18295       NewSign = true;
18296     } else if (ECD->getType() == BestType) {
18297       // Already the right type!
18298       if (getLangOpts().CPlusPlus)
18299         // C++ [dcl.enum]p4: Following the closing brace of an
18300         // enum-specifier, each enumerator has the type of its
18301         // enumeration.
18302         ECD->setType(EnumType);
18303       continue;
18304     } else {
18305       NewTy = BestType;
18306       NewWidth = BestWidth;
18307       NewSign = BestType->isSignedIntegerOrEnumerationType();
18308     }
18309 
18310     // Adjust the APSInt value.
18311     InitVal = InitVal.extOrTrunc(NewWidth);
18312     InitVal.setIsSigned(NewSign);
18313     ECD->setInitVal(InitVal);
18314 
18315     // Adjust the Expr initializer and type.
18316     if (ECD->getInitExpr() &&
18317         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
18318       ECD->setInitExpr(ImplicitCastExpr::Create(
18319           Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
18320           /*base paths*/ nullptr, VK_RValue, FPOptionsOverride()));
18321     if (getLangOpts().CPlusPlus)
18322       // C++ [dcl.enum]p4: Following the closing brace of an
18323       // enum-specifier, each enumerator has the type of its
18324       // enumeration.
18325       ECD->setType(EnumType);
18326     else
18327       ECD->setType(NewTy);
18328   }
18329 
18330   Enum->completeDefinition(BestType, BestPromotionType,
18331                            NumPositiveBits, NumNegativeBits);
18332 
18333   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
18334 
18335   if (Enum->isClosedFlag()) {
18336     for (Decl *D : Elements) {
18337       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
18338       if (!ECD) continue;  // Already issued a diagnostic.
18339 
18340       llvm::APSInt InitVal = ECD->getInitVal();
18341       if (InitVal != 0 && !InitVal.isPowerOf2() &&
18342           !IsValueInFlagEnum(Enum, InitVal, true))
18343         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
18344           << ECD << Enum;
18345     }
18346   }
18347 
18348   // Now that the enum type is defined, ensure it's not been underaligned.
18349   if (Enum->hasAttrs())
18350     CheckAlignasUnderalignment(Enum);
18351 }
18352 
18353 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
18354                                   SourceLocation StartLoc,
18355                                   SourceLocation EndLoc) {
18356   StringLiteral *AsmString = cast<StringLiteral>(expr);
18357 
18358   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
18359                                                    AsmString, StartLoc,
18360                                                    EndLoc);
18361   CurContext->addDecl(New);
18362   return New;
18363 }
18364 
18365 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
18366                                       IdentifierInfo* AliasName,
18367                                       SourceLocation PragmaLoc,
18368                                       SourceLocation NameLoc,
18369                                       SourceLocation AliasNameLoc) {
18370   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
18371                                          LookupOrdinaryName);
18372   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
18373                            AttributeCommonInfo::AS_Pragma);
18374   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
18375       Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
18376 
18377   // If a declaration that:
18378   // 1) declares a function or a variable
18379   // 2) has external linkage
18380   // already exists, add a label attribute to it.
18381   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18382     if (isDeclExternC(PrevDecl))
18383       PrevDecl->addAttr(Attr);
18384     else
18385       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
18386           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
18387   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
18388   } else
18389     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
18390 }
18391 
18392 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
18393                              SourceLocation PragmaLoc,
18394                              SourceLocation NameLoc) {
18395   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
18396 
18397   if (PrevDecl) {
18398     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
18399   } else {
18400     (void)WeakUndeclaredIdentifiers.insert(
18401       std::pair<IdentifierInfo*,WeakInfo>
18402         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
18403   }
18404 }
18405 
18406 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
18407                                 IdentifierInfo* AliasName,
18408                                 SourceLocation PragmaLoc,
18409                                 SourceLocation NameLoc,
18410                                 SourceLocation AliasNameLoc) {
18411   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
18412                                     LookupOrdinaryName);
18413   WeakInfo W = WeakInfo(Name, NameLoc);
18414 
18415   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18416     if (!PrevDecl->hasAttr<AliasAttr>())
18417       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
18418         DeclApplyPragmaWeak(TUScope, ND, W);
18419   } else {
18420     (void)WeakUndeclaredIdentifiers.insert(
18421       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
18422   }
18423 }
18424 
18425 Decl *Sema::getObjCDeclContext() const {
18426   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
18427 }
18428 
18429 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
18430                                                      bool Final) {
18431   assert(FD && "Expected non-null FunctionDecl");
18432 
18433   // SYCL functions can be template, so we check if they have appropriate
18434   // attribute prior to checking if it is a template.
18435   if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
18436     return FunctionEmissionStatus::Emitted;
18437 
18438   // Templates are emitted when they're instantiated.
18439   if (FD->isDependentContext())
18440     return FunctionEmissionStatus::TemplateDiscarded;
18441 
18442   // Check whether this function is an externally visible definition.
18443   auto IsEmittedForExternalSymbol = [this, FD]() {
18444     // We have to check the GVA linkage of the function's *definition* -- if we
18445     // only have a declaration, we don't know whether or not the function will
18446     // be emitted, because (say) the definition could include "inline".
18447     FunctionDecl *Def = FD->getDefinition();
18448 
18449     return Def && !isDiscardableGVALinkage(
18450                       getASTContext().GetGVALinkageForFunction(Def));
18451   };
18452 
18453   if (LangOpts.OpenMPIsDevice) {
18454     // In OpenMP device mode we will not emit host only functions, or functions
18455     // we don't need due to their linkage.
18456     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18457         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18458     // DevTy may be changed later by
18459     //  #pragma omp declare target to(*) device_type(*).
18460     // Therefore DevTy having no value does not imply host. The emission status
18461     // will be checked again at the end of compilation unit with Final = true.
18462     if (DevTy.hasValue())
18463       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
18464         return FunctionEmissionStatus::OMPDiscarded;
18465     // If we have an explicit value for the device type, or we are in a target
18466     // declare context, we need to emit all extern and used symbols.
18467     if (isInOpenMPDeclareTargetContext() || DevTy.hasValue())
18468       if (IsEmittedForExternalSymbol())
18469         return FunctionEmissionStatus::Emitted;
18470     // Device mode only emits what it must, if it wasn't tagged yet and needed,
18471     // we'll omit it.
18472     if (Final)
18473       return FunctionEmissionStatus::OMPDiscarded;
18474   } else if (LangOpts.OpenMP > 45) {
18475     // In OpenMP host compilation prior to 5.0 everything was an emitted host
18476     // function. In 5.0, no_host was introduced which might cause a function to
18477     // be ommitted.
18478     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18479         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18480     if (DevTy.hasValue())
18481       if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
18482         return FunctionEmissionStatus::OMPDiscarded;
18483   }
18484 
18485   if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
18486     return FunctionEmissionStatus::Emitted;
18487 
18488   if (LangOpts.CUDA) {
18489     // When compiling for device, host functions are never emitted.  Similarly,
18490     // when compiling for host, device and global functions are never emitted.
18491     // (Technically, we do emit a host-side stub for global functions, but this
18492     // doesn't count for our purposes here.)
18493     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
18494     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
18495       return FunctionEmissionStatus::CUDADiscarded;
18496     if (!LangOpts.CUDAIsDevice &&
18497         (T == Sema::CFT_Device || T == Sema::CFT_Global))
18498       return FunctionEmissionStatus::CUDADiscarded;
18499 
18500     if (IsEmittedForExternalSymbol())
18501       return FunctionEmissionStatus::Emitted;
18502   }
18503 
18504   // Otherwise, the function is known-emitted if it's in our set of
18505   // known-emitted functions.
18506   return FunctionEmissionStatus::Unknown;
18507 }
18508 
18509 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
18510   // Host-side references to a __global__ function refer to the stub, so the
18511   // function itself is never emitted and therefore should not be marked.
18512   // If we have host fn calls kernel fn calls host+device, the HD function
18513   // does not get instantiated on the host. We model this by omitting at the
18514   // call to the kernel from the callgraph. This ensures that, when compiling
18515   // for host, only HD functions actually called from the host get marked as
18516   // known-emitted.
18517   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
18518          IdentifyCUDATarget(Callee) == CFT_Global;
18519 }
18520