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 }
1520 
1521 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1522                          bool AllowInlineNamespace) {
1523   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1524 }
1525 
1526 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1527   DeclContext *TargetDC = DC->getPrimaryContext();
1528   do {
1529     if (DeclContext *ScopeDC = S->getEntity())
1530       if (ScopeDC->getPrimaryContext() == TargetDC)
1531         return S;
1532   } while ((S = S->getParent()));
1533 
1534   return nullptr;
1535 }
1536 
1537 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1538                                             DeclContext*,
1539                                             ASTContext&);
1540 
1541 /// Filters out lookup results that don't fall within the given scope
1542 /// as determined by isDeclInScope.
1543 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1544                                 bool ConsiderLinkage,
1545                                 bool AllowInlineNamespace) {
1546   LookupResult::Filter F = R.makeFilter();
1547   while (F.hasNext()) {
1548     NamedDecl *D = F.next();
1549 
1550     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1551       continue;
1552 
1553     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1554       continue;
1555 
1556     F.erase();
1557   }
1558 
1559   F.done();
1560 }
1561 
1562 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1563 /// have compatible owning modules.
1564 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1565   // FIXME: The Modules TS is not clear about how friend declarations are
1566   // to be treated. It's not meaningful to have different owning modules for
1567   // linkage in redeclarations of the same entity, so for now allow the
1568   // redeclaration and change the owning modules to match.
1569   if (New->getFriendObjectKind() &&
1570       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1571     New->setLocalOwningModule(Old->getOwningModule());
1572     makeMergedDefinitionVisible(New);
1573     return false;
1574   }
1575 
1576   Module *NewM = New->getOwningModule();
1577   Module *OldM = Old->getOwningModule();
1578 
1579   if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1580     NewM = NewM->Parent;
1581   if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1582     OldM = OldM->Parent;
1583 
1584   if (NewM == OldM)
1585     return false;
1586 
1587   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1588   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1589   if (NewIsModuleInterface || OldIsModuleInterface) {
1590     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1591     //   if a declaration of D [...] appears in the purview of a module, all
1592     //   other such declarations shall appear in the purview of the same module
1593     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1594       << New
1595       << NewIsModuleInterface
1596       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1597       << OldIsModuleInterface
1598       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1599     Diag(Old->getLocation(), diag::note_previous_declaration);
1600     New->setInvalidDecl();
1601     return true;
1602   }
1603 
1604   return false;
1605 }
1606 
1607 static bool isUsingDecl(NamedDecl *D) {
1608   return isa<UsingShadowDecl>(D) ||
1609          isa<UnresolvedUsingTypenameDecl>(D) ||
1610          isa<UnresolvedUsingValueDecl>(D);
1611 }
1612 
1613 /// Removes using shadow declarations from the lookup results.
1614 static void RemoveUsingDecls(LookupResult &R) {
1615   LookupResult::Filter F = R.makeFilter();
1616   while (F.hasNext())
1617     if (isUsingDecl(F.next()))
1618       F.erase();
1619 
1620   F.done();
1621 }
1622 
1623 /// Check for this common pattern:
1624 /// @code
1625 /// class S {
1626 ///   S(const S&); // DO NOT IMPLEMENT
1627 ///   void operator=(const S&); // DO NOT IMPLEMENT
1628 /// };
1629 /// @endcode
1630 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1631   // FIXME: Should check for private access too but access is set after we get
1632   // the decl here.
1633   if (D->doesThisDeclarationHaveABody())
1634     return false;
1635 
1636   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1637     return CD->isCopyConstructor();
1638   return D->isCopyAssignmentOperator();
1639 }
1640 
1641 // We need this to handle
1642 //
1643 // typedef struct {
1644 //   void *foo() { return 0; }
1645 // } A;
1646 //
1647 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1648 // for example. If 'A', foo will have external linkage. If we have '*A',
1649 // foo will have no linkage. Since we can't know until we get to the end
1650 // of the typedef, this function finds out if D might have non-external linkage.
1651 // Callers should verify at the end of the TU if it D has external linkage or
1652 // not.
1653 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1654   const DeclContext *DC = D->getDeclContext();
1655   while (!DC->isTranslationUnit()) {
1656     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1657       if (!RD->hasNameForLinkage())
1658         return true;
1659     }
1660     DC = DC->getParent();
1661   }
1662 
1663   return !D->isExternallyVisible();
1664 }
1665 
1666 // FIXME: This needs to be refactored; some other isInMainFile users want
1667 // these semantics.
1668 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1669   if (S.TUKind != TU_Complete)
1670     return false;
1671   return S.SourceMgr.isInMainFile(Loc);
1672 }
1673 
1674 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1675   assert(D);
1676 
1677   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1678     return false;
1679 
1680   // Ignore all entities declared within templates, and out-of-line definitions
1681   // of members of class templates.
1682   if (D->getDeclContext()->isDependentContext() ||
1683       D->getLexicalDeclContext()->isDependentContext())
1684     return false;
1685 
1686   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1687     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1688       return false;
1689     // A non-out-of-line declaration of a member specialization was implicitly
1690     // instantiated; it's the out-of-line declaration that we're interested in.
1691     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1692         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1693       return false;
1694 
1695     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1696       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1697         return false;
1698     } else {
1699       // 'static inline' functions are defined in headers; don't warn.
1700       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1701         return false;
1702     }
1703 
1704     if (FD->doesThisDeclarationHaveABody() &&
1705         Context.DeclMustBeEmitted(FD))
1706       return false;
1707   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1708     // Constants and utility variables are defined in headers with internal
1709     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1710     // like "inline".)
1711     if (!isMainFileLoc(*this, VD->getLocation()))
1712       return false;
1713 
1714     if (Context.DeclMustBeEmitted(VD))
1715       return false;
1716 
1717     if (VD->isStaticDataMember() &&
1718         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1719       return false;
1720     if (VD->isStaticDataMember() &&
1721         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1722         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1723       return false;
1724 
1725     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1726       return false;
1727   } else {
1728     return false;
1729   }
1730 
1731   // Only warn for unused decls internal to the translation unit.
1732   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1733   // for inline functions defined in the main source file, for instance.
1734   return mightHaveNonExternalLinkage(D);
1735 }
1736 
1737 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1738   if (!D)
1739     return;
1740 
1741   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1742     const FunctionDecl *First = FD->getFirstDecl();
1743     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1744       return; // First should already be in the vector.
1745   }
1746 
1747   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1748     const VarDecl *First = VD->getFirstDecl();
1749     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1750       return; // First should already be in the vector.
1751   }
1752 
1753   if (ShouldWarnIfUnusedFileScopedDecl(D))
1754     UnusedFileScopedDecls.push_back(D);
1755 }
1756 
1757 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1758   if (D->isInvalidDecl())
1759     return false;
1760 
1761   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1762     // For a decomposition declaration, warn if none of the bindings are
1763     // referenced, instead of if the variable itself is referenced (which
1764     // it is, by the bindings' expressions).
1765     for (auto *BD : DD->bindings())
1766       if (BD->isReferenced())
1767         return false;
1768   } else if (!D->getDeclName()) {
1769     return false;
1770   } else if (D->isReferenced() || D->isUsed()) {
1771     return false;
1772   }
1773 
1774   if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
1775     return false;
1776 
1777   if (isa<LabelDecl>(D))
1778     return true;
1779 
1780   // Except for labels, we only care about unused decls that are local to
1781   // functions.
1782   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1783   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1784     // For dependent types, the diagnostic is deferred.
1785     WithinFunction =
1786         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1787   if (!WithinFunction)
1788     return false;
1789 
1790   if (isa<TypedefNameDecl>(D))
1791     return true;
1792 
1793   // White-list anything that isn't a local variable.
1794   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1795     return false;
1796 
1797   // Types of valid local variables should be complete, so this should succeed.
1798   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1799 
1800     // White-list anything with an __attribute__((unused)) type.
1801     const auto *Ty = VD->getType().getTypePtr();
1802 
1803     // Only look at the outermost level of typedef.
1804     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1805       if (TT->getDecl()->hasAttr<UnusedAttr>())
1806         return false;
1807     }
1808 
1809     // If we failed to complete the type for some reason, or if the type is
1810     // dependent, don't diagnose the variable.
1811     if (Ty->isIncompleteType() || Ty->isDependentType())
1812       return false;
1813 
1814     // Look at the element type to ensure that the warning behaviour is
1815     // consistent for both scalars and arrays.
1816     Ty = Ty->getBaseElementTypeUnsafe();
1817 
1818     if (const TagType *TT = Ty->getAs<TagType>()) {
1819       const TagDecl *Tag = TT->getDecl();
1820       if (Tag->hasAttr<UnusedAttr>())
1821         return false;
1822 
1823       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1824         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1825           return false;
1826 
1827         if (const Expr *Init = VD->getInit()) {
1828           if (const ExprWithCleanups *Cleanups =
1829                   dyn_cast<ExprWithCleanups>(Init))
1830             Init = Cleanups->getSubExpr();
1831           const CXXConstructExpr *Construct =
1832             dyn_cast<CXXConstructExpr>(Init);
1833           if (Construct && !Construct->isElidable()) {
1834             CXXConstructorDecl *CD = Construct->getConstructor();
1835             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1836                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1837               return false;
1838           }
1839 
1840           // Suppress the warning if we don't know how this is constructed, and
1841           // it could possibly be non-trivial constructor.
1842           if (Init->isTypeDependent())
1843             for (const CXXConstructorDecl *Ctor : RD->ctors())
1844               if (!Ctor->isTrivial())
1845                 return false;
1846         }
1847       }
1848     }
1849 
1850     // TODO: __attribute__((unused)) templates?
1851   }
1852 
1853   return true;
1854 }
1855 
1856 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1857                                      FixItHint &Hint) {
1858   if (isa<LabelDecl>(D)) {
1859     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1860         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1861         true);
1862     if (AfterColon.isInvalid())
1863       return;
1864     Hint = FixItHint::CreateRemoval(
1865         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1866   }
1867 }
1868 
1869 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1870   if (D->getTypeForDecl()->isDependentType())
1871     return;
1872 
1873   for (auto *TmpD : D->decls()) {
1874     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1875       DiagnoseUnusedDecl(T);
1876     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1877       DiagnoseUnusedNestedTypedefs(R);
1878   }
1879 }
1880 
1881 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1882 /// unless they are marked attr(unused).
1883 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1884   if (!ShouldDiagnoseUnusedDecl(D))
1885     return;
1886 
1887   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1888     // typedefs can be referenced later on, so the diagnostics are emitted
1889     // at end-of-translation-unit.
1890     UnusedLocalTypedefNameCandidates.insert(TD);
1891     return;
1892   }
1893 
1894   FixItHint Hint;
1895   GenerateFixForUnusedDecl(D, Context, Hint);
1896 
1897   unsigned DiagID;
1898   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1899     DiagID = diag::warn_unused_exception_param;
1900   else if (isa<LabelDecl>(D))
1901     DiagID = diag::warn_unused_label;
1902   else
1903     DiagID = diag::warn_unused_variable;
1904 
1905   Diag(D->getLocation(), DiagID) << D << Hint;
1906 }
1907 
1908 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1909   // Verify that we have no forward references left.  If so, there was a goto
1910   // or address of a label taken, but no definition of it.  Label fwd
1911   // definitions are indicated with a null substmt which is also not a resolved
1912   // MS inline assembly label name.
1913   bool Diagnose = false;
1914   if (L->isMSAsmLabel())
1915     Diagnose = !L->isResolvedMSAsmLabel();
1916   else
1917     Diagnose = L->getStmt() == nullptr;
1918   if (Diagnose)
1919     S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
1920 }
1921 
1922 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1923   S->mergeNRVOIntoParent();
1924 
1925   if (S->decl_empty()) return;
1926   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1927          "Scope shouldn't contain decls!");
1928 
1929   for (auto *TmpD : S->decls()) {
1930     assert(TmpD && "This decl didn't get pushed??");
1931 
1932     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1933     NamedDecl *D = cast<NamedDecl>(TmpD);
1934 
1935     // Diagnose unused variables in this scope.
1936     if (!S->hasUnrecoverableErrorOccurred()) {
1937       DiagnoseUnusedDecl(D);
1938       if (const auto *RD = dyn_cast<RecordDecl>(D))
1939         DiagnoseUnusedNestedTypedefs(RD);
1940     }
1941 
1942     if (!D->getDeclName()) continue;
1943 
1944     // If this was a forward reference to a label, verify it was defined.
1945     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1946       CheckPoppedLabel(LD, *this);
1947 
1948     // Remove this name from our lexical scope, and warn on it if we haven't
1949     // already.
1950     IdResolver.RemoveDecl(D);
1951     auto ShadowI = ShadowingDecls.find(D);
1952     if (ShadowI != ShadowingDecls.end()) {
1953       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1954         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1955             << D << FD << FD->getParent();
1956         Diag(FD->getLocation(), diag::note_previous_declaration);
1957       }
1958       ShadowingDecls.erase(ShadowI);
1959     }
1960   }
1961 }
1962 
1963 /// Look for an Objective-C class in the translation unit.
1964 ///
1965 /// \param Id The name of the Objective-C class we're looking for. If
1966 /// typo-correction fixes this name, the Id will be updated
1967 /// to the fixed name.
1968 ///
1969 /// \param IdLoc The location of the name in the translation unit.
1970 ///
1971 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1972 /// if there is no class with the given name.
1973 ///
1974 /// \returns The declaration of the named Objective-C class, or NULL if the
1975 /// class could not be found.
1976 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1977                                               SourceLocation IdLoc,
1978                                               bool DoTypoCorrection) {
1979   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1980   // creation from this context.
1981   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1982 
1983   if (!IDecl && DoTypoCorrection) {
1984     // Perform typo correction at the given location, but only if we
1985     // find an Objective-C class name.
1986     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
1987     if (TypoCorrection C =
1988             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
1989                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
1990       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1991       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1992       Id = IDecl->getIdentifier();
1993     }
1994   }
1995   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1996   // This routine must always return a class definition, if any.
1997   if (Def && Def->getDefinition())
1998       Def = Def->getDefinition();
1999   return Def;
2000 }
2001 
2002 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
2003 /// from S, where a non-field would be declared. This routine copes
2004 /// with the difference between C and C++ scoping rules in structs and
2005 /// unions. For example, the following code is well-formed in C but
2006 /// ill-formed in C++:
2007 /// @code
2008 /// struct S6 {
2009 ///   enum { BAR } e;
2010 /// };
2011 ///
2012 /// void test_S6() {
2013 ///   struct S6 a;
2014 ///   a.e = BAR;
2015 /// }
2016 /// @endcode
2017 /// For the declaration of BAR, this routine will return a different
2018 /// scope. The scope S will be the scope of the unnamed enumeration
2019 /// within S6. In C++, this routine will return the scope associated
2020 /// with S6, because the enumeration's scope is a transparent
2021 /// context but structures can contain non-field names. In C, this
2022 /// routine will return the translation unit scope, since the
2023 /// enumeration's scope is a transparent context and structures cannot
2024 /// contain non-field names.
2025 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2026   while (((S->getFlags() & Scope::DeclScope) == 0) ||
2027          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2028          (S->isClassScope() && !getLangOpts().CPlusPlus))
2029     S = S->getParent();
2030   return S;
2031 }
2032 
2033 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2034                                ASTContext::GetBuiltinTypeError Error) {
2035   switch (Error) {
2036   case ASTContext::GE_None:
2037     return "";
2038   case ASTContext::GE_Missing_type:
2039     return BuiltinInfo.getHeaderName(ID);
2040   case ASTContext::GE_Missing_stdio:
2041     return "stdio.h";
2042   case ASTContext::GE_Missing_setjmp:
2043     return "setjmp.h";
2044   case ASTContext::GE_Missing_ucontext:
2045     return "ucontext.h";
2046   }
2047   llvm_unreachable("unhandled error kind");
2048 }
2049 
2050 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2051                                   unsigned ID, SourceLocation Loc) {
2052   DeclContext *Parent = Context.getTranslationUnitDecl();
2053 
2054   if (getLangOpts().CPlusPlus) {
2055     LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2056         Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2057     CLinkageDecl->setImplicit();
2058     Parent->addDecl(CLinkageDecl);
2059     Parent = CLinkageDecl;
2060   }
2061 
2062   FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2063                                            /*TInfo=*/nullptr, SC_Extern, false,
2064                                            Type->isFunctionProtoType());
2065   New->setImplicit();
2066   New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2067 
2068   // Create Decl objects for each parameter, adding them to the
2069   // FunctionDecl.
2070   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2071     SmallVector<ParmVarDecl *, 16> Params;
2072     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2073       ParmVarDecl *parm = ParmVarDecl::Create(
2074           Context, New, SourceLocation(), SourceLocation(), nullptr,
2075           FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2076       parm->setScopeInfo(0, i);
2077       Params.push_back(parm);
2078     }
2079     New->setParams(Params);
2080   }
2081 
2082   AddKnownFunctionAttributes(New);
2083   return New;
2084 }
2085 
2086 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2087 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2088 /// if we're creating this built-in in anticipation of redeclaring the
2089 /// built-in.
2090 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2091                                      Scope *S, bool ForRedeclaration,
2092                                      SourceLocation Loc) {
2093   LookupNecessaryTypesForBuiltin(S, ID);
2094 
2095   ASTContext::GetBuiltinTypeError Error;
2096   QualType R = Context.GetBuiltinType(ID, Error);
2097   if (Error) {
2098     if (!ForRedeclaration)
2099       return nullptr;
2100 
2101     // If we have a builtin without an associated type we should not emit a
2102     // warning when we were not able to find a type for it.
2103     if (Error == ASTContext::GE_Missing_type ||
2104         Context.BuiltinInfo.allowTypeMismatch(ID))
2105       return nullptr;
2106 
2107     // If we could not find a type for setjmp it is because the jmp_buf type was
2108     // not defined prior to the setjmp declaration.
2109     if (Error == ASTContext::GE_Missing_setjmp) {
2110       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2111           << Context.BuiltinInfo.getName(ID);
2112       return nullptr;
2113     }
2114 
2115     // Generally, we emit a warning that the declaration requires the
2116     // appropriate header.
2117     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2118         << getHeaderName(Context.BuiltinInfo, ID, Error)
2119         << Context.BuiltinInfo.getName(ID);
2120     return nullptr;
2121   }
2122 
2123   if (!ForRedeclaration &&
2124       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2125        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2126     Diag(Loc, diag::ext_implicit_lib_function_decl)
2127         << Context.BuiltinInfo.getName(ID) << R;
2128     if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2129       Diag(Loc, diag::note_include_header_or_declare)
2130           << Header << Context.BuiltinInfo.getName(ID);
2131   }
2132 
2133   if (R.isNull())
2134     return nullptr;
2135 
2136   FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2137   RegisterLocallyScopedExternCDecl(New, S);
2138 
2139   // TUScope is the translation-unit scope to insert this function into.
2140   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2141   // relate Scopes to DeclContexts, and probably eliminate CurContext
2142   // entirely, but we're not there yet.
2143   DeclContext *SavedContext = CurContext;
2144   CurContext = New->getDeclContext();
2145   PushOnScopeChains(New, TUScope);
2146   CurContext = SavedContext;
2147   return New;
2148 }
2149 
2150 /// Typedef declarations don't have linkage, but they still denote the same
2151 /// entity if their types are the same.
2152 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2153 /// isSameEntity.
2154 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2155                                                      TypedefNameDecl *Decl,
2156                                                      LookupResult &Previous) {
2157   // This is only interesting when modules are enabled.
2158   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2159     return;
2160 
2161   // Empty sets are uninteresting.
2162   if (Previous.empty())
2163     return;
2164 
2165   LookupResult::Filter Filter = Previous.makeFilter();
2166   while (Filter.hasNext()) {
2167     NamedDecl *Old = Filter.next();
2168 
2169     // Non-hidden declarations are never ignored.
2170     if (S.isVisible(Old))
2171       continue;
2172 
2173     // Declarations of the same entity are not ignored, even if they have
2174     // different linkages.
2175     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2176       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2177                                 Decl->getUnderlyingType()))
2178         continue;
2179 
2180       // If both declarations give a tag declaration a typedef name for linkage
2181       // purposes, then they declare the same entity.
2182       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2183           Decl->getAnonDeclWithTypedefName())
2184         continue;
2185     }
2186 
2187     Filter.erase();
2188   }
2189 
2190   Filter.done();
2191 }
2192 
2193 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2194   QualType OldType;
2195   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2196     OldType = OldTypedef->getUnderlyingType();
2197   else
2198     OldType = Context.getTypeDeclType(Old);
2199   QualType NewType = New->getUnderlyingType();
2200 
2201   if (NewType->isVariablyModifiedType()) {
2202     // Must not redefine a typedef with a variably-modified type.
2203     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2204     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2205       << Kind << NewType;
2206     if (Old->getLocation().isValid())
2207       notePreviousDefinition(Old, New->getLocation());
2208     New->setInvalidDecl();
2209     return true;
2210   }
2211 
2212   if (OldType != NewType &&
2213       !OldType->isDependentType() &&
2214       !NewType->isDependentType() &&
2215       !Context.hasSameType(OldType, NewType)) {
2216     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2217     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2218       << Kind << NewType << OldType;
2219     if (Old->getLocation().isValid())
2220       notePreviousDefinition(Old, New->getLocation());
2221     New->setInvalidDecl();
2222     return true;
2223   }
2224   return false;
2225 }
2226 
2227 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2228 /// same name and scope as a previous declaration 'Old'.  Figure out
2229 /// how to resolve this situation, merging decls or emitting
2230 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2231 ///
2232 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2233                                 LookupResult &OldDecls) {
2234   // If the new decl is known invalid already, don't bother doing any
2235   // merging checks.
2236   if (New->isInvalidDecl()) return;
2237 
2238   // Allow multiple definitions for ObjC built-in typedefs.
2239   // FIXME: Verify the underlying types are equivalent!
2240   if (getLangOpts().ObjC) {
2241     const IdentifierInfo *TypeID = New->getIdentifier();
2242     switch (TypeID->getLength()) {
2243     default: break;
2244     case 2:
2245       {
2246         if (!TypeID->isStr("id"))
2247           break;
2248         QualType T = New->getUnderlyingType();
2249         if (!T->isPointerType())
2250           break;
2251         if (!T->isVoidPointerType()) {
2252           QualType PT = T->castAs<PointerType>()->getPointeeType();
2253           if (!PT->isStructureType())
2254             break;
2255         }
2256         Context.setObjCIdRedefinitionType(T);
2257         // Install the built-in type for 'id', ignoring the current definition.
2258         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2259         return;
2260       }
2261     case 5:
2262       if (!TypeID->isStr("Class"))
2263         break;
2264       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2265       // Install the built-in type for 'Class', ignoring the current definition.
2266       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2267       return;
2268     case 3:
2269       if (!TypeID->isStr("SEL"))
2270         break;
2271       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2272       // Install the built-in type for 'SEL', ignoring the current definition.
2273       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2274       return;
2275     }
2276     // Fall through - the typedef name was not a builtin type.
2277   }
2278 
2279   // Verify the old decl was also a type.
2280   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2281   if (!Old) {
2282     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2283       << New->getDeclName();
2284 
2285     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2286     if (OldD->getLocation().isValid())
2287       notePreviousDefinition(OldD, New->getLocation());
2288 
2289     return New->setInvalidDecl();
2290   }
2291 
2292   // If the old declaration is invalid, just give up here.
2293   if (Old->isInvalidDecl())
2294     return New->setInvalidDecl();
2295 
2296   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2297     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2298     auto *NewTag = New->getAnonDeclWithTypedefName();
2299     NamedDecl *Hidden = nullptr;
2300     if (OldTag && NewTag &&
2301         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2302         !hasVisibleDefinition(OldTag, &Hidden)) {
2303       // There is a definition of this tag, but it is not visible. Use it
2304       // instead of our tag.
2305       New->setTypeForDecl(OldTD->getTypeForDecl());
2306       if (OldTD->isModed())
2307         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2308                                     OldTD->getUnderlyingType());
2309       else
2310         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2311 
2312       // Make the old tag definition visible.
2313       makeMergedDefinitionVisible(Hidden);
2314 
2315       // If this was an unscoped enumeration, yank all of its enumerators
2316       // out of the scope.
2317       if (isa<EnumDecl>(NewTag)) {
2318         Scope *EnumScope = getNonFieldDeclScope(S);
2319         for (auto *D : NewTag->decls()) {
2320           auto *ED = cast<EnumConstantDecl>(D);
2321           assert(EnumScope->isDeclScope(ED));
2322           EnumScope->RemoveDecl(ED);
2323           IdResolver.RemoveDecl(ED);
2324           ED->getLexicalDeclContext()->removeDecl(ED);
2325         }
2326       }
2327     }
2328   }
2329 
2330   // If the typedef types are not identical, reject them in all languages and
2331   // with any extensions enabled.
2332   if (isIncompatibleTypedef(Old, New))
2333     return;
2334 
2335   // The types match.  Link up the redeclaration chain and merge attributes if
2336   // the old declaration was a typedef.
2337   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2338     New->setPreviousDecl(Typedef);
2339     mergeDeclAttributes(New, Old);
2340   }
2341 
2342   if (getLangOpts().MicrosoftExt)
2343     return;
2344 
2345   if (getLangOpts().CPlusPlus) {
2346     // C++ [dcl.typedef]p2:
2347     //   In a given non-class scope, a typedef specifier can be used to
2348     //   redefine the name of any type declared in that scope to refer
2349     //   to the type to which it already refers.
2350     if (!isa<CXXRecordDecl>(CurContext))
2351       return;
2352 
2353     // C++0x [dcl.typedef]p4:
2354     //   In a given class scope, a typedef specifier can be used to redefine
2355     //   any class-name declared in that scope that is not also a typedef-name
2356     //   to refer to the type to which it already refers.
2357     //
2358     // This wording came in via DR424, which was a correction to the
2359     // wording in DR56, which accidentally banned code like:
2360     //
2361     //   struct S {
2362     //     typedef struct A { } A;
2363     //   };
2364     //
2365     // in the C++03 standard. We implement the C++0x semantics, which
2366     // allow the above but disallow
2367     //
2368     //   struct S {
2369     //     typedef int I;
2370     //     typedef int I;
2371     //   };
2372     //
2373     // since that was the intent of DR56.
2374     if (!isa<TypedefNameDecl>(Old))
2375       return;
2376 
2377     Diag(New->getLocation(), diag::err_redefinition)
2378       << New->getDeclName();
2379     notePreviousDefinition(Old, New->getLocation());
2380     return New->setInvalidDecl();
2381   }
2382 
2383   // Modules always permit redefinition of typedefs, as does C11.
2384   if (getLangOpts().Modules || getLangOpts().C11)
2385     return;
2386 
2387   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2388   // is normally mapped to an error, but can be controlled with
2389   // -Wtypedef-redefinition.  If either the original or the redefinition is
2390   // in a system header, don't emit this for compatibility with GCC.
2391   if (getDiagnostics().getSuppressSystemWarnings() &&
2392       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2393       (Old->isImplicit() ||
2394        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2395        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2396     return;
2397 
2398   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2399     << New->getDeclName();
2400   notePreviousDefinition(Old, New->getLocation());
2401 }
2402 
2403 /// DeclhasAttr - returns true if decl Declaration already has the target
2404 /// attribute.
2405 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2406   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2407   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2408   for (const auto *i : D->attrs())
2409     if (i->getKind() == A->getKind()) {
2410       if (Ann) {
2411         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2412           return true;
2413         continue;
2414       }
2415       // FIXME: Don't hardcode this check
2416       if (OA && isa<OwnershipAttr>(i))
2417         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2418       return true;
2419     }
2420 
2421   return false;
2422 }
2423 
2424 static bool isAttributeTargetADefinition(Decl *D) {
2425   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2426     return VD->isThisDeclarationADefinition();
2427   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2428     return TD->isCompleteDefinition() || TD->isBeingDefined();
2429   return true;
2430 }
2431 
2432 /// Merge alignment attributes from \p Old to \p New, taking into account the
2433 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2434 ///
2435 /// \return \c true if any attributes were added to \p New.
2436 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2437   // Look for alignas attributes on Old, and pick out whichever attribute
2438   // specifies the strictest alignment requirement.
2439   AlignedAttr *OldAlignasAttr = nullptr;
2440   AlignedAttr *OldStrictestAlignAttr = nullptr;
2441   unsigned OldAlign = 0;
2442   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2443     // FIXME: We have no way of representing inherited dependent alignments
2444     // in a case like:
2445     //   template<int A, int B> struct alignas(A) X;
2446     //   template<int A, int B> struct alignas(B) X {};
2447     // For now, we just ignore any alignas attributes which are not on the
2448     // definition in such a case.
2449     if (I->isAlignmentDependent())
2450       return false;
2451 
2452     if (I->isAlignas())
2453       OldAlignasAttr = I;
2454 
2455     unsigned Align = I->getAlignment(S.Context);
2456     if (Align > OldAlign) {
2457       OldAlign = Align;
2458       OldStrictestAlignAttr = I;
2459     }
2460   }
2461 
2462   // Look for alignas attributes on New.
2463   AlignedAttr *NewAlignasAttr = nullptr;
2464   unsigned NewAlign = 0;
2465   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2466     if (I->isAlignmentDependent())
2467       return false;
2468 
2469     if (I->isAlignas())
2470       NewAlignasAttr = I;
2471 
2472     unsigned Align = I->getAlignment(S.Context);
2473     if (Align > NewAlign)
2474       NewAlign = Align;
2475   }
2476 
2477   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2478     // Both declarations have 'alignas' attributes. We require them to match.
2479     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2480     // fall short. (If two declarations both have alignas, they must both match
2481     // every definition, and so must match each other if there is a definition.)
2482 
2483     // If either declaration only contains 'alignas(0)' specifiers, then it
2484     // specifies the natural alignment for the type.
2485     if (OldAlign == 0 || NewAlign == 0) {
2486       QualType Ty;
2487       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2488         Ty = VD->getType();
2489       else
2490         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2491 
2492       if (OldAlign == 0)
2493         OldAlign = S.Context.getTypeAlign(Ty);
2494       if (NewAlign == 0)
2495         NewAlign = S.Context.getTypeAlign(Ty);
2496     }
2497 
2498     if (OldAlign != NewAlign) {
2499       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2500         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2501         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2502       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2503     }
2504   }
2505 
2506   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2507     // C++11 [dcl.align]p6:
2508     //   if any declaration of an entity has an alignment-specifier,
2509     //   every defining declaration of that entity shall specify an
2510     //   equivalent alignment.
2511     // C11 6.7.5/7:
2512     //   If the definition of an object does not have an alignment
2513     //   specifier, any other declaration of that object shall also
2514     //   have no alignment specifier.
2515     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2516       << OldAlignasAttr;
2517     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2518       << OldAlignasAttr;
2519   }
2520 
2521   bool AnyAdded = false;
2522 
2523   // Ensure we have an attribute representing the strictest alignment.
2524   if (OldAlign > NewAlign) {
2525     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2526     Clone->setInherited(true);
2527     New->addAttr(Clone);
2528     AnyAdded = true;
2529   }
2530 
2531   // Ensure we have an alignas attribute if the old declaration had one.
2532   if (OldAlignasAttr && !NewAlignasAttr &&
2533       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2534     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2535     Clone->setInherited(true);
2536     New->addAttr(Clone);
2537     AnyAdded = true;
2538   }
2539 
2540   return AnyAdded;
2541 }
2542 
2543 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2544                                const InheritableAttr *Attr,
2545                                Sema::AvailabilityMergeKind AMK) {
2546   // This function copies an attribute Attr from a previous declaration to the
2547   // new declaration D if the new declaration doesn't itself have that attribute
2548   // yet or if that attribute allows duplicates.
2549   // If you're adding a new attribute that requires logic different from
2550   // "use explicit attribute on decl if present, else use attribute from
2551   // previous decl", for example if the attribute needs to be consistent
2552   // between redeclarations, you need to call a custom merge function here.
2553   InheritableAttr *NewAttr = nullptr;
2554   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2555     NewAttr = S.mergeAvailabilityAttr(
2556         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2557         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2558         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2559         AA->getPriority());
2560   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2561     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2562   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2563     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2564   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2565     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2566   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2567     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2568   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2569     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2570                                 FA->getFirstArg());
2571   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2572     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2573   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2574     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2575   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2576     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2577                                        IA->getInheritanceModel());
2578   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2579     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2580                                       &S.Context.Idents.get(AA->getSpelling()));
2581   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2582            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2583             isa<CUDAGlobalAttr>(Attr))) {
2584     // CUDA target attributes are part of function signature for
2585     // overloading purposes and must not be merged.
2586     return false;
2587   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2588     NewAttr = S.mergeMinSizeAttr(D, *MA);
2589   else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2590     NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2591   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2592     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2593   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2594     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2595   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2596     NewAttr = S.mergeCommonAttr(D, *CommonA);
2597   else if (isa<AlignedAttr>(Attr))
2598     // AlignedAttrs are handled separately, because we need to handle all
2599     // such attributes on a declaration at the same time.
2600     NewAttr = nullptr;
2601   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2602            (AMK == Sema::AMK_Override ||
2603             AMK == Sema::AMK_ProtocolImplementation))
2604     NewAttr = nullptr;
2605   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2606     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2607   else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
2608     NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
2609   else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
2610     NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
2611   else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2612     NewAttr = S.mergeImportModuleAttr(D, *IMA);
2613   else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2614     NewAttr = S.mergeImportNameAttr(D, *INA);
2615   else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2616     NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2617   else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2618     NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2619   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2620     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2621 
2622   if (NewAttr) {
2623     NewAttr->setInherited(true);
2624     D->addAttr(NewAttr);
2625     if (isa<MSInheritanceAttr>(NewAttr))
2626       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2627     return true;
2628   }
2629 
2630   return false;
2631 }
2632 
2633 static const NamedDecl *getDefinition(const Decl *D) {
2634   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2635     return TD->getDefinition();
2636   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2637     const VarDecl *Def = VD->getDefinition();
2638     if (Def)
2639       return Def;
2640     return VD->getActingDefinition();
2641   }
2642   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2643     const FunctionDecl *Def = nullptr;
2644     if (FD->isDefined(Def, true))
2645       return Def;
2646   }
2647   return nullptr;
2648 }
2649 
2650 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2651   for (const auto *Attribute : D->attrs())
2652     if (Attribute->getKind() == Kind)
2653       return true;
2654   return false;
2655 }
2656 
2657 /// checkNewAttributesAfterDef - If we already have a definition, check that
2658 /// there are no new attributes in this declaration.
2659 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2660   if (!New->hasAttrs())
2661     return;
2662 
2663   const NamedDecl *Def = getDefinition(Old);
2664   if (!Def || Def == New)
2665     return;
2666 
2667   AttrVec &NewAttributes = New->getAttrs();
2668   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2669     const Attr *NewAttribute = NewAttributes[I];
2670 
2671     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2672       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2673         Sema::SkipBodyInfo SkipBody;
2674         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2675 
2676         // If we're skipping this definition, drop the "alias" attribute.
2677         if (SkipBody.ShouldSkip) {
2678           NewAttributes.erase(NewAttributes.begin() + I);
2679           --E;
2680           continue;
2681         }
2682       } else {
2683         VarDecl *VD = cast<VarDecl>(New);
2684         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2685                                 VarDecl::TentativeDefinition
2686                             ? diag::err_alias_after_tentative
2687                             : diag::err_redefinition;
2688         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2689         if (Diag == diag::err_redefinition)
2690           S.notePreviousDefinition(Def, VD->getLocation());
2691         else
2692           S.Diag(Def->getLocation(), diag::note_previous_definition);
2693         VD->setInvalidDecl();
2694       }
2695       ++I;
2696       continue;
2697     }
2698 
2699     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2700       // Tentative definitions are only interesting for the alias check above.
2701       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2702         ++I;
2703         continue;
2704       }
2705     }
2706 
2707     if (hasAttribute(Def, NewAttribute->getKind())) {
2708       ++I;
2709       continue; // regular attr merging will take care of validating this.
2710     }
2711 
2712     if (isa<C11NoReturnAttr>(NewAttribute)) {
2713       // C's _Noreturn is allowed to be added to a function after it is defined.
2714       ++I;
2715       continue;
2716     } else if (isa<UuidAttr>(NewAttribute)) {
2717       // msvc will allow a subsequent definition to add an uuid to a class
2718       ++I;
2719       continue;
2720     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2721       if (AA->isAlignas()) {
2722         // C++11 [dcl.align]p6:
2723         //   if any declaration of an entity has an alignment-specifier,
2724         //   every defining declaration of that entity shall specify an
2725         //   equivalent alignment.
2726         // C11 6.7.5/7:
2727         //   If the definition of an object does not have an alignment
2728         //   specifier, any other declaration of that object shall also
2729         //   have no alignment specifier.
2730         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2731           << AA;
2732         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2733           << AA;
2734         NewAttributes.erase(NewAttributes.begin() + I);
2735         --E;
2736         continue;
2737       }
2738     } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2739       // If there is a C definition followed by a redeclaration with this
2740       // attribute then there are two different definitions. In C++, prefer the
2741       // standard diagnostics.
2742       if (!S.getLangOpts().CPlusPlus) {
2743         S.Diag(NewAttribute->getLocation(),
2744                diag::err_loader_uninitialized_redeclaration);
2745         S.Diag(Def->getLocation(), diag::note_previous_definition);
2746         NewAttributes.erase(NewAttributes.begin() + I);
2747         --E;
2748         continue;
2749       }
2750     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2751                cast<VarDecl>(New)->isInline() &&
2752                !cast<VarDecl>(New)->isInlineSpecified()) {
2753       // Don't warn about applying selectany to implicitly inline variables.
2754       // Older compilers and language modes would require the use of selectany
2755       // to make such variables inline, and it would have no effect if we
2756       // honored it.
2757       ++I;
2758       continue;
2759     } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2760       // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2761       // declarations after defintions.
2762       ++I;
2763       continue;
2764     }
2765 
2766     S.Diag(NewAttribute->getLocation(),
2767            diag::warn_attribute_precede_definition);
2768     S.Diag(Def->getLocation(), diag::note_previous_definition);
2769     NewAttributes.erase(NewAttributes.begin() + I);
2770     --E;
2771   }
2772 }
2773 
2774 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2775                                      const ConstInitAttr *CIAttr,
2776                                      bool AttrBeforeInit) {
2777   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2778 
2779   // Figure out a good way to write this specifier on the old declaration.
2780   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2781   // enough of the attribute list spelling information to extract that without
2782   // heroics.
2783   std::string SuitableSpelling;
2784   if (S.getLangOpts().CPlusPlus20)
2785     SuitableSpelling = std::string(
2786         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2787   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2788     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2789         InsertLoc, {tok::l_square, tok::l_square,
2790                     S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2791                     S.PP.getIdentifierInfo("require_constant_initialization"),
2792                     tok::r_square, tok::r_square}));
2793   if (SuitableSpelling.empty())
2794     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2795         InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2796                     S.PP.getIdentifierInfo("require_constant_initialization"),
2797                     tok::r_paren, tok::r_paren}));
2798   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2799     SuitableSpelling = "constinit";
2800   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2801     SuitableSpelling = "[[clang::require_constant_initialization]]";
2802   if (SuitableSpelling.empty())
2803     SuitableSpelling = "__attribute__((require_constant_initialization))";
2804   SuitableSpelling += " ";
2805 
2806   if (AttrBeforeInit) {
2807     // extern constinit int a;
2808     // int a = 0; // error (missing 'constinit'), accepted as extension
2809     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
2810     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2811         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2812     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2813   } else {
2814     // int a = 0;
2815     // constinit extern int a; // error (missing 'constinit')
2816     S.Diag(CIAttr->getLocation(),
2817            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2818                                  : diag::warn_require_const_init_added_too_late)
2819         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2820     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2821         << CIAttr->isConstinit()
2822         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2823   }
2824 }
2825 
2826 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2827 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2828                                AvailabilityMergeKind AMK) {
2829   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2830     UsedAttr *NewAttr = OldAttr->clone(Context);
2831     NewAttr->setInherited(true);
2832     New->addAttr(NewAttr);
2833   }
2834 
2835   if (!Old->hasAttrs() && !New->hasAttrs())
2836     return;
2837 
2838   // [dcl.constinit]p1:
2839   //   If the [constinit] specifier is applied to any declaration of a
2840   //   variable, it shall be applied to the initializing declaration.
2841   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2842   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2843   if (bool(OldConstInit) != bool(NewConstInit)) {
2844     const auto *OldVD = cast<VarDecl>(Old);
2845     auto *NewVD = cast<VarDecl>(New);
2846 
2847     // Find the initializing declaration. Note that we might not have linked
2848     // the new declaration into the redeclaration chain yet.
2849     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2850     if (!InitDecl &&
2851         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2852       InitDecl = NewVD;
2853 
2854     if (InitDecl == NewVD) {
2855       // This is the initializing declaration. If it would inherit 'constinit',
2856       // that's ill-formed. (Note that we do not apply this to the attribute
2857       // form).
2858       if (OldConstInit && OldConstInit->isConstinit())
2859         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2860                                  /*AttrBeforeInit=*/true);
2861     } else if (NewConstInit) {
2862       // This is the first time we've been told that this declaration should
2863       // have a constant initializer. If we already saw the initializing
2864       // declaration, this is too late.
2865       if (InitDecl && InitDecl != NewVD) {
2866         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2867                                  /*AttrBeforeInit=*/false);
2868         NewVD->dropAttr<ConstInitAttr>();
2869       }
2870     }
2871   }
2872 
2873   // Attributes declared post-definition are currently ignored.
2874   checkNewAttributesAfterDef(*this, New, Old);
2875 
2876   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2877     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2878       if (!OldA->isEquivalent(NewA)) {
2879         // This redeclaration changes __asm__ label.
2880         Diag(New->getLocation(), diag::err_different_asm_label);
2881         Diag(OldA->getLocation(), diag::note_previous_declaration);
2882       }
2883     } else if (Old->isUsed()) {
2884       // This redeclaration adds an __asm__ label to a declaration that has
2885       // already been ODR-used.
2886       Diag(New->getLocation(), diag::err_late_asm_label_name)
2887         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2888     }
2889   }
2890 
2891   // Re-declaration cannot add abi_tag's.
2892   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2893     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2894       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2895         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2896                       NewTag) == OldAbiTagAttr->tags_end()) {
2897           Diag(NewAbiTagAttr->getLocation(),
2898                diag::err_new_abi_tag_on_redeclaration)
2899               << NewTag;
2900           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2901         }
2902       }
2903     } else {
2904       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2905       Diag(Old->getLocation(), diag::note_previous_declaration);
2906     }
2907   }
2908 
2909   // This redeclaration adds a section attribute.
2910   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2911     if (auto *VD = dyn_cast<VarDecl>(New)) {
2912       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2913         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2914         Diag(Old->getLocation(), diag::note_previous_declaration);
2915       }
2916     }
2917   }
2918 
2919   // Redeclaration adds code-seg attribute.
2920   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2921   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2922       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2923     Diag(New->getLocation(), diag::warn_mismatched_section)
2924          << 0 /*codeseg*/;
2925     Diag(Old->getLocation(), diag::note_previous_declaration);
2926   }
2927 
2928   if (!Old->hasAttrs())
2929     return;
2930 
2931   bool foundAny = New->hasAttrs();
2932 
2933   // Ensure that any moving of objects within the allocated map is done before
2934   // we process them.
2935   if (!foundAny) New->setAttrs(AttrVec());
2936 
2937   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2938     // Ignore deprecated/unavailable/availability attributes if requested.
2939     AvailabilityMergeKind LocalAMK = AMK_None;
2940     if (isa<DeprecatedAttr>(I) ||
2941         isa<UnavailableAttr>(I) ||
2942         isa<AvailabilityAttr>(I)) {
2943       switch (AMK) {
2944       case AMK_None:
2945         continue;
2946 
2947       case AMK_Redeclaration:
2948       case AMK_Override:
2949       case AMK_ProtocolImplementation:
2950         LocalAMK = AMK;
2951         break;
2952       }
2953     }
2954 
2955     // Already handled.
2956     if (isa<UsedAttr>(I))
2957       continue;
2958 
2959     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2960       foundAny = true;
2961   }
2962 
2963   if (mergeAlignedAttrs(*this, New, Old))
2964     foundAny = true;
2965 
2966   if (!foundAny) New->dropAttrs();
2967 }
2968 
2969 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2970 /// to the new one.
2971 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2972                                      const ParmVarDecl *oldDecl,
2973                                      Sema &S) {
2974   // C++11 [dcl.attr.depend]p2:
2975   //   The first declaration of a function shall specify the
2976   //   carries_dependency attribute for its declarator-id if any declaration
2977   //   of the function specifies the carries_dependency attribute.
2978   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2979   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2980     S.Diag(CDA->getLocation(),
2981            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2982     // Find the first declaration of the parameter.
2983     // FIXME: Should we build redeclaration chains for function parameters?
2984     const FunctionDecl *FirstFD =
2985       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2986     const ParmVarDecl *FirstVD =
2987       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2988     S.Diag(FirstVD->getLocation(),
2989            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2990   }
2991 
2992   if (!oldDecl->hasAttrs())
2993     return;
2994 
2995   bool foundAny = newDecl->hasAttrs();
2996 
2997   // Ensure that any moving of objects within the allocated map is
2998   // done before we process them.
2999   if (!foundAny) newDecl->setAttrs(AttrVec());
3000 
3001   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3002     if (!DeclHasAttr(newDecl, I)) {
3003       InheritableAttr *newAttr =
3004         cast<InheritableParamAttr>(I->clone(S.Context));
3005       newAttr->setInherited(true);
3006       newDecl->addAttr(newAttr);
3007       foundAny = true;
3008     }
3009   }
3010 
3011   if (!foundAny) newDecl->dropAttrs();
3012 }
3013 
3014 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3015                                 const ParmVarDecl *OldParam,
3016                                 Sema &S) {
3017   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3018     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3019       if (*Oldnullability != *Newnullability) {
3020         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3021           << DiagNullabilityKind(
3022                *Newnullability,
3023                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3024                 != 0))
3025           << DiagNullabilityKind(
3026                *Oldnullability,
3027                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3028                 != 0));
3029         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3030       }
3031     } else {
3032       QualType NewT = NewParam->getType();
3033       NewT = S.Context.getAttributedType(
3034                          AttributedType::getNullabilityAttrKind(*Oldnullability),
3035                          NewT, NewT);
3036       NewParam->setType(NewT);
3037     }
3038   }
3039 }
3040 
3041 namespace {
3042 
3043 /// Used in MergeFunctionDecl to keep track of function parameters in
3044 /// C.
3045 struct GNUCompatibleParamWarning {
3046   ParmVarDecl *OldParm;
3047   ParmVarDecl *NewParm;
3048   QualType PromotedType;
3049 };
3050 
3051 } // end anonymous namespace
3052 
3053 // Determine whether the previous declaration was a definition, implicit
3054 // declaration, or a declaration.
3055 template <typename T>
3056 static std::pair<diag::kind, SourceLocation>
3057 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3058   diag::kind PrevDiag;
3059   SourceLocation OldLocation = Old->getLocation();
3060   if (Old->isThisDeclarationADefinition())
3061     PrevDiag = diag::note_previous_definition;
3062   else if (Old->isImplicit()) {
3063     PrevDiag = diag::note_previous_implicit_declaration;
3064     if (OldLocation.isInvalid())
3065       OldLocation = New->getLocation();
3066   } else
3067     PrevDiag = diag::note_previous_declaration;
3068   return std::make_pair(PrevDiag, OldLocation);
3069 }
3070 
3071 /// canRedefineFunction - checks if a function can be redefined. Currently,
3072 /// only extern inline functions can be redefined, and even then only in
3073 /// GNU89 mode.
3074 static bool canRedefineFunction(const FunctionDecl *FD,
3075                                 const LangOptions& LangOpts) {
3076   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3077           !LangOpts.CPlusPlus &&
3078           FD->isInlineSpecified() &&
3079           FD->getStorageClass() == SC_Extern);
3080 }
3081 
3082 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3083   const AttributedType *AT = T->getAs<AttributedType>();
3084   while (AT && !AT->isCallingConv())
3085     AT = AT->getModifiedType()->getAs<AttributedType>();
3086   return AT;
3087 }
3088 
3089 template <typename T>
3090 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3091   const DeclContext *DC = Old->getDeclContext();
3092   if (DC->isRecord())
3093     return false;
3094 
3095   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3096   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3097     return true;
3098   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3099     return true;
3100   return false;
3101 }
3102 
3103 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3104 static bool isExternC(VarTemplateDecl *) { return false; }
3105 
3106 /// Check whether a redeclaration of an entity introduced by a
3107 /// using-declaration is valid, given that we know it's not an overload
3108 /// (nor a hidden tag declaration).
3109 template<typename ExpectedDecl>
3110 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3111                                    ExpectedDecl *New) {
3112   // C++11 [basic.scope.declarative]p4:
3113   //   Given a set of declarations in a single declarative region, each of
3114   //   which specifies the same unqualified name,
3115   //   -- they shall all refer to the same entity, or all refer to functions
3116   //      and function templates; or
3117   //   -- exactly one declaration shall declare a class name or enumeration
3118   //      name that is not a typedef name and the other declarations shall all
3119   //      refer to the same variable or enumerator, or all refer to functions
3120   //      and function templates; in this case the class name or enumeration
3121   //      name is hidden (3.3.10).
3122 
3123   // C++11 [namespace.udecl]p14:
3124   //   If a function declaration in namespace scope or block scope has the
3125   //   same name and the same parameter-type-list as a function introduced
3126   //   by a using-declaration, and the declarations do not declare the same
3127   //   function, the program is ill-formed.
3128 
3129   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3130   if (Old &&
3131       !Old->getDeclContext()->getRedeclContext()->Equals(
3132           New->getDeclContext()->getRedeclContext()) &&
3133       !(isExternC(Old) && isExternC(New)))
3134     Old = nullptr;
3135 
3136   if (!Old) {
3137     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3138     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3139     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
3140     return true;
3141   }
3142   return false;
3143 }
3144 
3145 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3146                                             const FunctionDecl *B) {
3147   assert(A->getNumParams() == B->getNumParams());
3148 
3149   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3150     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3151     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3152     if (AttrA == AttrB)
3153       return true;
3154     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3155            AttrA->isDynamic() == AttrB->isDynamic();
3156   };
3157 
3158   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3159 }
3160 
3161 /// If necessary, adjust the semantic declaration context for a qualified
3162 /// declaration to name the correct inline namespace within the qualifier.
3163 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3164                                                DeclaratorDecl *OldD) {
3165   // The only case where we need to update the DeclContext is when
3166   // redeclaration lookup for a qualified name finds a declaration
3167   // in an inline namespace within the context named by the qualifier:
3168   //
3169   //   inline namespace N { int f(); }
3170   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3171   //
3172   // For unqualified declarations, the semantic context *can* change
3173   // along the redeclaration chain (for local extern declarations,
3174   // extern "C" declarations, and friend declarations in particular).
3175   if (!NewD->getQualifier())
3176     return;
3177 
3178   // NewD is probably already in the right context.
3179   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3180   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3181   if (NamedDC->Equals(SemaDC))
3182     return;
3183 
3184   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3185           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3186          "unexpected context for redeclaration");
3187 
3188   auto *LexDC = NewD->getLexicalDeclContext();
3189   auto FixSemaDC = [=](NamedDecl *D) {
3190     if (!D)
3191       return;
3192     D->setDeclContext(SemaDC);
3193     D->setLexicalDeclContext(LexDC);
3194   };
3195 
3196   FixSemaDC(NewD);
3197   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3198     FixSemaDC(FD->getDescribedFunctionTemplate());
3199   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3200     FixSemaDC(VD->getDescribedVarTemplate());
3201 }
3202 
3203 /// MergeFunctionDecl - We just parsed a function 'New' from
3204 /// declarator D which has the same name and scope as a previous
3205 /// declaration 'Old'.  Figure out how to resolve this situation,
3206 /// merging decls or emitting diagnostics as appropriate.
3207 ///
3208 /// In C++, New and Old must be declarations that are not
3209 /// overloaded. Use IsOverload to determine whether New and Old are
3210 /// overloaded, and to select the Old declaration that New should be
3211 /// merged with.
3212 ///
3213 /// Returns true if there was an error, false otherwise.
3214 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3215                              Scope *S, bool MergeTypeWithOld) {
3216   // Verify the old decl was also a function.
3217   FunctionDecl *Old = OldD->getAsFunction();
3218   if (!Old) {
3219     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3220       if (New->getFriendObjectKind()) {
3221         Diag(New->getLocation(), diag::err_using_decl_friend);
3222         Diag(Shadow->getTargetDecl()->getLocation(),
3223              diag::note_using_decl_target);
3224         Diag(Shadow->getUsingDecl()->getLocation(),
3225              diag::note_using_decl) << 0;
3226         return true;
3227       }
3228 
3229       // Check whether the two declarations might declare the same function.
3230       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3231         return true;
3232       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3233     } else {
3234       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3235         << New->getDeclName();
3236       notePreviousDefinition(OldD, New->getLocation());
3237       return true;
3238     }
3239   }
3240 
3241   // If the old declaration was found in an inline namespace and the new
3242   // declaration was qualified, update the DeclContext to match.
3243   adjustDeclContextForDeclaratorDecl(New, Old);
3244 
3245   // If the old declaration is invalid, just give up here.
3246   if (Old->isInvalidDecl())
3247     return true;
3248 
3249   // Disallow redeclaration of some builtins.
3250   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3251     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3252     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3253         << Old << Old->getType();
3254     return true;
3255   }
3256 
3257   diag::kind PrevDiag;
3258   SourceLocation OldLocation;
3259   std::tie(PrevDiag, OldLocation) =
3260       getNoteDiagForInvalidRedeclaration(Old, New);
3261 
3262   // Don't complain about this if we're in GNU89 mode and the old function
3263   // is an extern inline function.
3264   // Don't complain about specializations. They are not supposed to have
3265   // storage classes.
3266   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3267       New->getStorageClass() == SC_Static &&
3268       Old->hasExternalFormalLinkage() &&
3269       !New->getTemplateSpecializationInfo() &&
3270       !canRedefineFunction(Old, getLangOpts())) {
3271     if (getLangOpts().MicrosoftExt) {
3272       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3273       Diag(OldLocation, PrevDiag);
3274     } else {
3275       Diag(New->getLocation(), diag::err_static_non_static) << New;
3276       Diag(OldLocation, PrevDiag);
3277       return true;
3278     }
3279   }
3280 
3281   if (New->hasAttr<InternalLinkageAttr>() &&
3282       !Old->hasAttr<InternalLinkageAttr>()) {
3283     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3284         << New->getDeclName();
3285     notePreviousDefinition(Old, New->getLocation());
3286     New->dropAttr<InternalLinkageAttr>();
3287   }
3288 
3289   if (CheckRedeclarationModuleOwnership(New, Old))
3290     return true;
3291 
3292   if (!getLangOpts().CPlusPlus) {
3293     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3294     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3295       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3296         << New << OldOvl;
3297 
3298       // Try our best to find a decl that actually has the overloadable
3299       // attribute for the note. In most cases (e.g. programs with only one
3300       // broken declaration/definition), this won't matter.
3301       //
3302       // FIXME: We could do this if we juggled some extra state in
3303       // OverloadableAttr, rather than just removing it.
3304       const Decl *DiagOld = Old;
3305       if (OldOvl) {
3306         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3307           const auto *A = D->getAttr<OverloadableAttr>();
3308           return A && !A->isImplicit();
3309         });
3310         // If we've implicitly added *all* of the overloadable attrs to this
3311         // chain, emitting a "previous redecl" note is pointless.
3312         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3313       }
3314 
3315       if (DiagOld)
3316         Diag(DiagOld->getLocation(),
3317              diag::note_attribute_overloadable_prev_overload)
3318           << OldOvl;
3319 
3320       if (OldOvl)
3321         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3322       else
3323         New->dropAttr<OverloadableAttr>();
3324     }
3325   }
3326 
3327   // If a function is first declared with a calling convention, but is later
3328   // declared or defined without one, all following decls assume the calling
3329   // convention of the first.
3330   //
3331   // It's OK if a function is first declared without a calling convention,
3332   // but is later declared or defined with the default calling convention.
3333   //
3334   // To test if either decl has an explicit calling convention, we look for
3335   // AttributedType sugar nodes on the type as written.  If they are missing or
3336   // were canonicalized away, we assume the calling convention was implicit.
3337   //
3338   // Note also that we DO NOT return at this point, because we still have
3339   // other tests to run.
3340   QualType OldQType = Context.getCanonicalType(Old->getType());
3341   QualType NewQType = Context.getCanonicalType(New->getType());
3342   const FunctionType *OldType = cast<FunctionType>(OldQType);
3343   const FunctionType *NewType = cast<FunctionType>(NewQType);
3344   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3345   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3346   bool RequiresAdjustment = false;
3347 
3348   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3349     FunctionDecl *First = Old->getFirstDecl();
3350     const FunctionType *FT =
3351         First->getType().getCanonicalType()->castAs<FunctionType>();
3352     FunctionType::ExtInfo FI = FT->getExtInfo();
3353     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3354     if (!NewCCExplicit) {
3355       // Inherit the CC from the previous declaration if it was specified
3356       // there but not here.
3357       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3358       RequiresAdjustment = true;
3359     } else if (Old->getBuiltinID()) {
3360       // Builtin attribute isn't propagated to the new one yet at this point,
3361       // so we check if the old one is a builtin.
3362 
3363       // Calling Conventions on a Builtin aren't really useful and setting a
3364       // default calling convention and cdecl'ing some builtin redeclarations is
3365       // common, so warn and ignore the calling convention on the redeclaration.
3366       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3367           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3368           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3369       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3370       RequiresAdjustment = true;
3371     } else {
3372       // Calling conventions aren't compatible, so complain.
3373       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3374       Diag(New->getLocation(), diag::err_cconv_change)
3375         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3376         << !FirstCCExplicit
3377         << (!FirstCCExplicit ? "" :
3378             FunctionType::getNameForCallConv(FI.getCC()));
3379 
3380       // Put the note on the first decl, since it is the one that matters.
3381       Diag(First->getLocation(), diag::note_previous_declaration);
3382       return true;
3383     }
3384   }
3385 
3386   // FIXME: diagnose the other way around?
3387   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3388     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3389     RequiresAdjustment = true;
3390   }
3391 
3392   // Merge regparm attribute.
3393   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3394       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3395     if (NewTypeInfo.getHasRegParm()) {
3396       Diag(New->getLocation(), diag::err_regparm_mismatch)
3397         << NewType->getRegParmType()
3398         << OldType->getRegParmType();
3399       Diag(OldLocation, diag::note_previous_declaration);
3400       return true;
3401     }
3402 
3403     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3404     RequiresAdjustment = true;
3405   }
3406 
3407   // Merge ns_returns_retained attribute.
3408   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3409     if (NewTypeInfo.getProducesResult()) {
3410       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3411           << "'ns_returns_retained'";
3412       Diag(OldLocation, diag::note_previous_declaration);
3413       return true;
3414     }
3415 
3416     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3417     RequiresAdjustment = true;
3418   }
3419 
3420   if (OldTypeInfo.getNoCallerSavedRegs() !=
3421       NewTypeInfo.getNoCallerSavedRegs()) {
3422     if (NewTypeInfo.getNoCallerSavedRegs()) {
3423       AnyX86NoCallerSavedRegistersAttr *Attr =
3424         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3425       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3426       Diag(OldLocation, diag::note_previous_declaration);
3427       return true;
3428     }
3429 
3430     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3431     RequiresAdjustment = true;
3432   }
3433 
3434   if (RequiresAdjustment) {
3435     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3436     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3437     New->setType(QualType(AdjustedType, 0));
3438     NewQType = Context.getCanonicalType(New->getType());
3439   }
3440 
3441   // If this redeclaration makes the function inline, we may need to add it to
3442   // UndefinedButUsed.
3443   if (!Old->isInlined() && New->isInlined() &&
3444       !New->hasAttr<GNUInlineAttr>() &&
3445       !getLangOpts().GNUInline &&
3446       Old->isUsed(false) &&
3447       !Old->isDefined() && !New->isThisDeclarationADefinition())
3448     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3449                                            SourceLocation()));
3450 
3451   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3452   // about it.
3453   if (New->hasAttr<GNUInlineAttr>() &&
3454       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3455     UndefinedButUsed.erase(Old->getCanonicalDecl());
3456   }
3457 
3458   // If pass_object_size params don't match up perfectly, this isn't a valid
3459   // redeclaration.
3460   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3461       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3462     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3463         << New->getDeclName();
3464     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3465     return true;
3466   }
3467 
3468   if (getLangOpts().CPlusPlus) {
3469     // C++1z [over.load]p2
3470     //   Certain function declarations cannot be overloaded:
3471     //     -- Function declarations that differ only in the return type,
3472     //        the exception specification, or both cannot be overloaded.
3473 
3474     // Check the exception specifications match. This may recompute the type of
3475     // both Old and New if it resolved exception specifications, so grab the
3476     // types again after this. Because this updates the type, we do this before
3477     // any of the other checks below, which may update the "de facto" NewQType
3478     // but do not necessarily update the type of New.
3479     if (CheckEquivalentExceptionSpec(Old, New))
3480       return true;
3481     OldQType = Context.getCanonicalType(Old->getType());
3482     NewQType = Context.getCanonicalType(New->getType());
3483 
3484     // Go back to the type source info to compare the declared return types,
3485     // per C++1y [dcl.type.auto]p13:
3486     //   Redeclarations or specializations of a function or function template
3487     //   with a declared return type that uses a placeholder type shall also
3488     //   use that placeholder, not a deduced type.
3489     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3490     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3491     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3492         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3493                                        OldDeclaredReturnType)) {
3494       QualType ResQT;
3495       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3496           OldDeclaredReturnType->isObjCObjectPointerType())
3497         // FIXME: This does the wrong thing for a deduced return type.
3498         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3499       if (ResQT.isNull()) {
3500         if (New->isCXXClassMember() && New->isOutOfLine())
3501           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3502               << New << New->getReturnTypeSourceRange();
3503         else
3504           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3505               << New->getReturnTypeSourceRange();
3506         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3507                                     << Old->getReturnTypeSourceRange();
3508         return true;
3509       }
3510       else
3511         NewQType = ResQT;
3512     }
3513 
3514     QualType OldReturnType = OldType->getReturnType();
3515     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3516     if (OldReturnType != NewReturnType) {
3517       // If this function has a deduced return type and has already been
3518       // defined, copy the deduced value from the old declaration.
3519       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3520       if (OldAT && OldAT->isDeduced()) {
3521         New->setType(
3522             SubstAutoType(New->getType(),
3523                           OldAT->isDependentType() ? Context.DependentTy
3524                                                    : OldAT->getDeducedType()));
3525         NewQType = Context.getCanonicalType(
3526             SubstAutoType(NewQType,
3527                           OldAT->isDependentType() ? Context.DependentTy
3528                                                    : OldAT->getDeducedType()));
3529       }
3530     }
3531 
3532     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3533     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3534     if (OldMethod && NewMethod) {
3535       // Preserve triviality.
3536       NewMethod->setTrivial(OldMethod->isTrivial());
3537 
3538       // MSVC allows explicit template specialization at class scope:
3539       // 2 CXXMethodDecls referring to the same function will be injected.
3540       // We don't want a redeclaration error.
3541       bool IsClassScopeExplicitSpecialization =
3542                               OldMethod->isFunctionTemplateSpecialization() &&
3543                               NewMethod->isFunctionTemplateSpecialization();
3544       bool isFriend = NewMethod->getFriendObjectKind();
3545 
3546       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3547           !IsClassScopeExplicitSpecialization) {
3548         //    -- Member function declarations with the same name and the
3549         //       same parameter types cannot be overloaded if any of them
3550         //       is a static member function declaration.
3551         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3552           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3553           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3554           return true;
3555         }
3556 
3557         // C++ [class.mem]p1:
3558         //   [...] A member shall not be declared twice in the
3559         //   member-specification, except that a nested class or member
3560         //   class template can be declared and then later defined.
3561         if (!inTemplateInstantiation()) {
3562           unsigned NewDiag;
3563           if (isa<CXXConstructorDecl>(OldMethod))
3564             NewDiag = diag::err_constructor_redeclared;
3565           else if (isa<CXXDestructorDecl>(NewMethod))
3566             NewDiag = diag::err_destructor_redeclared;
3567           else if (isa<CXXConversionDecl>(NewMethod))
3568             NewDiag = diag::err_conv_function_redeclared;
3569           else
3570             NewDiag = diag::err_member_redeclared;
3571 
3572           Diag(New->getLocation(), NewDiag);
3573         } else {
3574           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3575             << New << New->getType();
3576         }
3577         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3578         return true;
3579 
3580       // Complain if this is an explicit declaration of a special
3581       // member that was initially declared implicitly.
3582       //
3583       // As an exception, it's okay to befriend such methods in order
3584       // to permit the implicit constructor/destructor/operator calls.
3585       } else if (OldMethod->isImplicit()) {
3586         if (isFriend) {
3587           NewMethod->setImplicit();
3588         } else {
3589           Diag(NewMethod->getLocation(),
3590                diag::err_definition_of_implicitly_declared_member)
3591             << New << getSpecialMember(OldMethod);
3592           return true;
3593         }
3594       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3595         Diag(NewMethod->getLocation(),
3596              diag::err_definition_of_explicitly_defaulted_member)
3597           << getSpecialMember(OldMethod);
3598         return true;
3599       }
3600     }
3601 
3602     // C++11 [dcl.attr.noreturn]p1:
3603     //   The first declaration of a function shall specify the noreturn
3604     //   attribute if any declaration of that function specifies the noreturn
3605     //   attribute.
3606     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3607     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3608       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3609       Diag(Old->getFirstDecl()->getLocation(),
3610            diag::note_noreturn_missing_first_decl);
3611     }
3612 
3613     // C++11 [dcl.attr.depend]p2:
3614     //   The first declaration of a function shall specify the
3615     //   carries_dependency attribute for its declarator-id if any declaration
3616     //   of the function specifies the carries_dependency attribute.
3617     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3618     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3619       Diag(CDA->getLocation(),
3620            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3621       Diag(Old->getFirstDecl()->getLocation(),
3622            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3623     }
3624 
3625     // (C++98 8.3.5p3):
3626     //   All declarations for a function shall agree exactly in both the
3627     //   return type and the parameter-type-list.
3628     // We also want to respect all the extended bits except noreturn.
3629 
3630     // noreturn should now match unless the old type info didn't have it.
3631     QualType OldQTypeForComparison = OldQType;
3632     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3633       auto *OldType = OldQType->castAs<FunctionProtoType>();
3634       const FunctionType *OldTypeForComparison
3635         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3636       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3637       assert(OldQTypeForComparison.isCanonical());
3638     }
3639 
3640     if (haveIncompatibleLanguageLinkages(Old, New)) {
3641       // As a special case, retain the language linkage from previous
3642       // declarations of a friend function as an extension.
3643       //
3644       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3645       // and is useful because there's otherwise no way to specify language
3646       // linkage within class scope.
3647       //
3648       // Check cautiously as the friend object kind isn't yet complete.
3649       if (New->getFriendObjectKind() != Decl::FOK_None) {
3650         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3651         Diag(OldLocation, PrevDiag);
3652       } else {
3653         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3654         Diag(OldLocation, PrevDiag);
3655         return true;
3656       }
3657     }
3658 
3659     // If the function types are compatible, merge the declarations. Ignore the
3660     // exception specifier because it was already checked above in
3661     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3662     // about incompatible types under -fms-compatibility.
3663     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3664                                                          NewQType))
3665       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3666 
3667     // If the types are imprecise (due to dependent constructs in friends or
3668     // local extern declarations), it's OK if they differ. We'll check again
3669     // during instantiation.
3670     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3671       return false;
3672 
3673     // Fall through for conflicting redeclarations and redefinitions.
3674   }
3675 
3676   // C: Function types need to be compatible, not identical. This handles
3677   // duplicate function decls like "void f(int); void f(enum X);" properly.
3678   if (!getLangOpts().CPlusPlus &&
3679       Context.typesAreCompatible(OldQType, NewQType)) {
3680     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3681     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3682     const FunctionProtoType *OldProto = nullptr;
3683     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3684         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3685       // The old declaration provided a function prototype, but the
3686       // new declaration does not. Merge in the prototype.
3687       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3688       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3689       NewQType =
3690           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3691                                   OldProto->getExtProtoInfo());
3692       New->setType(NewQType);
3693       New->setHasInheritedPrototype();
3694 
3695       // Synthesize parameters with the same types.
3696       SmallVector<ParmVarDecl*, 16> Params;
3697       for (const auto &ParamType : OldProto->param_types()) {
3698         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3699                                                  SourceLocation(), nullptr,
3700                                                  ParamType, /*TInfo=*/nullptr,
3701                                                  SC_None, nullptr);
3702         Param->setScopeInfo(0, Params.size());
3703         Param->setImplicit();
3704         Params.push_back(Param);
3705       }
3706 
3707       New->setParams(Params);
3708     }
3709 
3710     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3711   }
3712 
3713   // Check if the function types are compatible when pointer size address
3714   // spaces are ignored.
3715   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3716     return false;
3717 
3718   // GNU C permits a K&R definition to follow a prototype declaration
3719   // if the declared types of the parameters in the K&R definition
3720   // match the types in the prototype declaration, even when the
3721   // promoted types of the parameters from the K&R definition differ
3722   // from the types in the prototype. GCC then keeps the types from
3723   // the prototype.
3724   //
3725   // If a variadic prototype is followed by a non-variadic K&R definition,
3726   // the K&R definition becomes variadic.  This is sort of an edge case, but
3727   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3728   // C99 6.9.1p8.
3729   if (!getLangOpts().CPlusPlus &&
3730       Old->hasPrototype() && !New->hasPrototype() &&
3731       New->getType()->getAs<FunctionProtoType>() &&
3732       Old->getNumParams() == New->getNumParams()) {
3733     SmallVector<QualType, 16> ArgTypes;
3734     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3735     const FunctionProtoType *OldProto
3736       = Old->getType()->getAs<FunctionProtoType>();
3737     const FunctionProtoType *NewProto
3738       = New->getType()->getAs<FunctionProtoType>();
3739 
3740     // Determine whether this is the GNU C extension.
3741     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3742                                                NewProto->getReturnType());
3743     bool LooseCompatible = !MergedReturn.isNull();
3744     for (unsigned Idx = 0, End = Old->getNumParams();
3745          LooseCompatible && Idx != End; ++Idx) {
3746       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3747       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3748       if (Context.typesAreCompatible(OldParm->getType(),
3749                                      NewProto->getParamType(Idx))) {
3750         ArgTypes.push_back(NewParm->getType());
3751       } else if (Context.typesAreCompatible(OldParm->getType(),
3752                                             NewParm->getType(),
3753                                             /*CompareUnqualified=*/true)) {
3754         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3755                                            NewProto->getParamType(Idx) };
3756         Warnings.push_back(Warn);
3757         ArgTypes.push_back(NewParm->getType());
3758       } else
3759         LooseCompatible = false;
3760     }
3761 
3762     if (LooseCompatible) {
3763       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3764         Diag(Warnings[Warn].NewParm->getLocation(),
3765              diag::ext_param_promoted_not_compatible_with_prototype)
3766           << Warnings[Warn].PromotedType
3767           << Warnings[Warn].OldParm->getType();
3768         if (Warnings[Warn].OldParm->getLocation().isValid())
3769           Diag(Warnings[Warn].OldParm->getLocation(),
3770                diag::note_previous_declaration);
3771       }
3772 
3773       if (MergeTypeWithOld)
3774         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3775                                              OldProto->getExtProtoInfo()));
3776       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3777     }
3778 
3779     // Fall through to diagnose conflicting types.
3780   }
3781 
3782   // A function that has already been declared has been redeclared or
3783   // defined with a different type; show an appropriate diagnostic.
3784 
3785   // If the previous declaration was an implicitly-generated builtin
3786   // declaration, then at the very least we should use a specialized note.
3787   unsigned BuiltinID;
3788   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3789     // If it's actually a library-defined builtin function like 'malloc'
3790     // or 'printf', just warn about the incompatible redeclaration.
3791     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3792       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3793       Diag(OldLocation, diag::note_previous_builtin_declaration)
3794         << Old << Old->getType();
3795       return false;
3796     }
3797 
3798     PrevDiag = diag::note_previous_builtin_declaration;
3799   }
3800 
3801   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3802   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3803   return true;
3804 }
3805 
3806 /// Completes the merge of two function declarations that are
3807 /// known to be compatible.
3808 ///
3809 /// This routine handles the merging of attributes and other
3810 /// properties of function declarations from the old declaration to
3811 /// the new declaration, once we know that New is in fact a
3812 /// redeclaration of Old.
3813 ///
3814 /// \returns false
3815 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3816                                         Scope *S, bool MergeTypeWithOld) {
3817   // Merge the attributes
3818   mergeDeclAttributes(New, Old);
3819 
3820   // Merge "pure" flag.
3821   if (Old->isPure())
3822     New->setPure();
3823 
3824   // Merge "used" flag.
3825   if (Old->getMostRecentDecl()->isUsed(false))
3826     New->setIsUsed();
3827 
3828   // Merge attributes from the parameters.  These can mismatch with K&R
3829   // declarations.
3830   if (New->getNumParams() == Old->getNumParams())
3831       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3832         ParmVarDecl *NewParam = New->getParamDecl(i);
3833         ParmVarDecl *OldParam = Old->getParamDecl(i);
3834         mergeParamDeclAttributes(NewParam, OldParam, *this);
3835         mergeParamDeclTypes(NewParam, OldParam, *this);
3836       }
3837 
3838   if (getLangOpts().CPlusPlus)
3839     return MergeCXXFunctionDecl(New, Old, S);
3840 
3841   // Merge the function types so the we get the composite types for the return
3842   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3843   // was visible.
3844   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3845   if (!Merged.isNull() && MergeTypeWithOld)
3846     New->setType(Merged);
3847 
3848   return false;
3849 }
3850 
3851 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3852                                 ObjCMethodDecl *oldMethod) {
3853   // Merge the attributes, including deprecated/unavailable
3854   AvailabilityMergeKind MergeKind =
3855     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3856       ? AMK_ProtocolImplementation
3857       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3858                                                        : AMK_Override;
3859 
3860   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3861 
3862   // Merge attributes from the parameters.
3863   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3864                                        oe = oldMethod->param_end();
3865   for (ObjCMethodDecl::param_iterator
3866          ni = newMethod->param_begin(), ne = newMethod->param_end();
3867        ni != ne && oi != oe; ++ni, ++oi)
3868     mergeParamDeclAttributes(*ni, *oi, *this);
3869 
3870   CheckObjCMethodOverride(newMethod, oldMethod);
3871 }
3872 
3873 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3874   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3875 
3876   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3877          ? diag::err_redefinition_different_type
3878          : diag::err_redeclaration_different_type)
3879     << New->getDeclName() << New->getType() << Old->getType();
3880 
3881   diag::kind PrevDiag;
3882   SourceLocation OldLocation;
3883   std::tie(PrevDiag, OldLocation)
3884     = getNoteDiagForInvalidRedeclaration(Old, New);
3885   S.Diag(OldLocation, PrevDiag);
3886   New->setInvalidDecl();
3887 }
3888 
3889 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3890 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3891 /// emitting diagnostics as appropriate.
3892 ///
3893 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3894 /// to here in AddInitializerToDecl. We can't check them before the initializer
3895 /// is attached.
3896 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3897                              bool MergeTypeWithOld) {
3898   if (New->isInvalidDecl() || Old->isInvalidDecl())
3899     return;
3900 
3901   QualType MergedT;
3902   if (getLangOpts().CPlusPlus) {
3903     if (New->getType()->isUndeducedType()) {
3904       // We don't know what the new type is until the initializer is attached.
3905       return;
3906     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3907       // These could still be something that needs exception specs checked.
3908       return MergeVarDeclExceptionSpecs(New, Old);
3909     }
3910     // C++ [basic.link]p10:
3911     //   [...] the types specified by all declarations referring to a given
3912     //   object or function shall be identical, except that declarations for an
3913     //   array object can specify array types that differ by the presence or
3914     //   absence of a major array bound (8.3.4).
3915     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3916       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3917       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3918 
3919       // We are merging a variable declaration New into Old. If it has an array
3920       // bound, and that bound differs from Old's bound, we should diagnose the
3921       // mismatch.
3922       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3923         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3924              PrevVD = PrevVD->getPreviousDecl()) {
3925           QualType PrevVDTy = PrevVD->getType();
3926           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3927             continue;
3928 
3929           if (!Context.hasSameType(New->getType(), PrevVDTy))
3930             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3931         }
3932       }
3933 
3934       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3935         if (Context.hasSameType(OldArray->getElementType(),
3936                                 NewArray->getElementType()))
3937           MergedT = New->getType();
3938       }
3939       // FIXME: Check visibility. New is hidden but has a complete type. If New
3940       // has no array bound, it should not inherit one from Old, if Old is not
3941       // visible.
3942       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3943         if (Context.hasSameType(OldArray->getElementType(),
3944                                 NewArray->getElementType()))
3945           MergedT = Old->getType();
3946       }
3947     }
3948     else if (New->getType()->isObjCObjectPointerType() &&
3949                Old->getType()->isObjCObjectPointerType()) {
3950       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3951                                               Old->getType());
3952     }
3953   } else {
3954     // C 6.2.7p2:
3955     //   All declarations that refer to the same object or function shall have
3956     //   compatible type.
3957     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3958   }
3959   if (MergedT.isNull()) {
3960     // It's OK if we couldn't merge types if either type is dependent, for a
3961     // block-scope variable. In other cases (static data members of class
3962     // templates, variable templates, ...), we require the types to be
3963     // equivalent.
3964     // FIXME: The C++ standard doesn't say anything about this.
3965     if ((New->getType()->isDependentType() ||
3966          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3967       // If the old type was dependent, we can't merge with it, so the new type
3968       // becomes dependent for now. We'll reproduce the original type when we
3969       // instantiate the TypeSourceInfo for the variable.
3970       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3971         New->setType(Context.DependentTy);
3972       return;
3973     }
3974     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3975   }
3976 
3977   // Don't actually update the type on the new declaration if the old
3978   // declaration was an extern declaration in a different scope.
3979   if (MergeTypeWithOld)
3980     New->setType(MergedT);
3981 }
3982 
3983 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3984                                   LookupResult &Previous) {
3985   // C11 6.2.7p4:
3986   //   For an identifier with internal or external linkage declared
3987   //   in a scope in which a prior declaration of that identifier is
3988   //   visible, if the prior declaration specifies internal or
3989   //   external linkage, the type of the identifier at the later
3990   //   declaration becomes the composite type.
3991   //
3992   // If the variable isn't visible, we do not merge with its type.
3993   if (Previous.isShadowed())
3994     return false;
3995 
3996   if (S.getLangOpts().CPlusPlus) {
3997     // C++11 [dcl.array]p3:
3998     //   If there is a preceding declaration of the entity in the same
3999     //   scope in which the bound was specified, an omitted array bound
4000     //   is taken to be the same as in that earlier declaration.
4001     return NewVD->isPreviousDeclInSameBlockScope() ||
4002            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4003             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4004   } else {
4005     // If the old declaration was function-local, don't merge with its
4006     // type unless we're in the same function.
4007     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4008            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4009   }
4010 }
4011 
4012 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4013 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4014 /// situation, merging decls or emitting diagnostics as appropriate.
4015 ///
4016 /// Tentative definition rules (C99 6.9.2p2) are checked by
4017 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4018 /// definitions here, since the initializer hasn't been attached.
4019 ///
4020 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4021   // If the new decl is already invalid, don't do any other checking.
4022   if (New->isInvalidDecl())
4023     return;
4024 
4025   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4026     return;
4027 
4028   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4029 
4030   // Verify the old decl was also a variable or variable template.
4031   VarDecl *Old = nullptr;
4032   VarTemplateDecl *OldTemplate = nullptr;
4033   if (Previous.isSingleResult()) {
4034     if (NewTemplate) {
4035       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4036       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4037 
4038       if (auto *Shadow =
4039               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4040         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4041           return New->setInvalidDecl();
4042     } else {
4043       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4044 
4045       if (auto *Shadow =
4046               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4047         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4048           return New->setInvalidDecl();
4049     }
4050   }
4051   if (!Old) {
4052     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4053         << New->getDeclName();
4054     notePreviousDefinition(Previous.getRepresentativeDecl(),
4055                            New->getLocation());
4056     return New->setInvalidDecl();
4057   }
4058 
4059   // If the old declaration was found in an inline namespace and the new
4060   // declaration was qualified, update the DeclContext to match.
4061   adjustDeclContextForDeclaratorDecl(New, Old);
4062 
4063   // Ensure the template parameters are compatible.
4064   if (NewTemplate &&
4065       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4066                                       OldTemplate->getTemplateParameters(),
4067                                       /*Complain=*/true, TPL_TemplateMatch))
4068     return New->setInvalidDecl();
4069 
4070   // C++ [class.mem]p1:
4071   //   A member shall not be declared twice in the member-specification [...]
4072   //
4073   // Here, we need only consider static data members.
4074   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4075     Diag(New->getLocation(), diag::err_duplicate_member)
4076       << New->getIdentifier();
4077     Diag(Old->getLocation(), diag::note_previous_declaration);
4078     New->setInvalidDecl();
4079   }
4080 
4081   mergeDeclAttributes(New, Old);
4082   // Warn if an already-declared variable is made a weak_import in a subsequent
4083   // declaration
4084   if (New->hasAttr<WeakImportAttr>() &&
4085       Old->getStorageClass() == SC_None &&
4086       !Old->hasAttr<WeakImportAttr>()) {
4087     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4088     notePreviousDefinition(Old, New->getLocation());
4089     // Remove weak_import attribute on new declaration.
4090     New->dropAttr<WeakImportAttr>();
4091   }
4092 
4093   if (New->hasAttr<InternalLinkageAttr>() &&
4094       !Old->hasAttr<InternalLinkageAttr>()) {
4095     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
4096         << New->getDeclName();
4097     notePreviousDefinition(Old, New->getLocation());
4098     New->dropAttr<InternalLinkageAttr>();
4099   }
4100 
4101   // Merge the types.
4102   VarDecl *MostRecent = Old->getMostRecentDecl();
4103   if (MostRecent != Old) {
4104     MergeVarDeclTypes(New, MostRecent,
4105                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4106     if (New->isInvalidDecl())
4107       return;
4108   }
4109 
4110   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4111   if (New->isInvalidDecl())
4112     return;
4113 
4114   diag::kind PrevDiag;
4115   SourceLocation OldLocation;
4116   std::tie(PrevDiag, OldLocation) =
4117       getNoteDiagForInvalidRedeclaration(Old, New);
4118 
4119   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4120   if (New->getStorageClass() == SC_Static &&
4121       !New->isStaticDataMember() &&
4122       Old->hasExternalFormalLinkage()) {
4123     if (getLangOpts().MicrosoftExt) {
4124       Diag(New->getLocation(), diag::ext_static_non_static)
4125           << New->getDeclName();
4126       Diag(OldLocation, PrevDiag);
4127     } else {
4128       Diag(New->getLocation(), diag::err_static_non_static)
4129           << New->getDeclName();
4130       Diag(OldLocation, PrevDiag);
4131       return New->setInvalidDecl();
4132     }
4133   }
4134   // C99 6.2.2p4:
4135   //   For an identifier declared with the storage-class specifier
4136   //   extern in a scope in which a prior declaration of that
4137   //   identifier is visible,23) if the prior declaration specifies
4138   //   internal or external linkage, the linkage of the identifier at
4139   //   the later declaration is the same as the linkage specified at
4140   //   the prior declaration. If no prior declaration is visible, or
4141   //   if the prior declaration specifies no linkage, then the
4142   //   identifier has external linkage.
4143   if (New->hasExternalStorage() && Old->hasLinkage())
4144     /* Okay */;
4145   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4146            !New->isStaticDataMember() &&
4147            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4148     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4149     Diag(OldLocation, PrevDiag);
4150     return New->setInvalidDecl();
4151   }
4152 
4153   // Check if extern is followed by non-extern and vice-versa.
4154   if (New->hasExternalStorage() &&
4155       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4156     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4157     Diag(OldLocation, PrevDiag);
4158     return New->setInvalidDecl();
4159   }
4160   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4161       !New->hasExternalStorage()) {
4162     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4163     Diag(OldLocation, PrevDiag);
4164     return New->setInvalidDecl();
4165   }
4166 
4167   if (CheckRedeclarationModuleOwnership(New, Old))
4168     return;
4169 
4170   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4171 
4172   // FIXME: The test for external storage here seems wrong? We still
4173   // need to check for mismatches.
4174   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4175       // Don't complain about out-of-line definitions of static members.
4176       !(Old->getLexicalDeclContext()->isRecord() &&
4177         !New->getLexicalDeclContext()->isRecord())) {
4178     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4179     Diag(OldLocation, PrevDiag);
4180     return New->setInvalidDecl();
4181   }
4182 
4183   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4184     if (VarDecl *Def = Old->getDefinition()) {
4185       // C++1z [dcl.fcn.spec]p4:
4186       //   If the definition of a variable appears in a translation unit before
4187       //   its first declaration as inline, the program is ill-formed.
4188       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4189       Diag(Def->getLocation(), diag::note_previous_definition);
4190     }
4191   }
4192 
4193   // If this redeclaration makes the variable inline, we may need to add it to
4194   // UndefinedButUsed.
4195   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4196       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4197     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4198                                            SourceLocation()));
4199 
4200   if (New->getTLSKind() != Old->getTLSKind()) {
4201     if (!Old->getTLSKind()) {
4202       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4203       Diag(OldLocation, PrevDiag);
4204     } else if (!New->getTLSKind()) {
4205       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4206       Diag(OldLocation, PrevDiag);
4207     } else {
4208       // Do not allow redeclaration to change the variable between requiring
4209       // static and dynamic initialization.
4210       // FIXME: GCC allows this, but uses the TLS keyword on the first
4211       // declaration to determine the kind. Do we need to be compatible here?
4212       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4213         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4214       Diag(OldLocation, PrevDiag);
4215     }
4216   }
4217 
4218   // C++ doesn't have tentative definitions, so go right ahead and check here.
4219   if (getLangOpts().CPlusPlus &&
4220       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4221     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4222         Old->getCanonicalDecl()->isConstexpr()) {
4223       // This definition won't be a definition any more once it's been merged.
4224       Diag(New->getLocation(),
4225            diag::warn_deprecated_redundant_constexpr_static_def);
4226     } else if (VarDecl *Def = Old->getDefinition()) {
4227       if (checkVarDeclRedefinition(Def, New))
4228         return;
4229     }
4230   }
4231 
4232   if (haveIncompatibleLanguageLinkages(Old, New)) {
4233     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4234     Diag(OldLocation, PrevDiag);
4235     New->setInvalidDecl();
4236     return;
4237   }
4238 
4239   // Merge "used" flag.
4240   if (Old->getMostRecentDecl()->isUsed(false))
4241     New->setIsUsed();
4242 
4243   // Keep a chain of previous declarations.
4244   New->setPreviousDecl(Old);
4245   if (NewTemplate)
4246     NewTemplate->setPreviousDecl(OldTemplate);
4247 
4248   // Inherit access appropriately.
4249   New->setAccess(Old->getAccess());
4250   if (NewTemplate)
4251     NewTemplate->setAccess(New->getAccess());
4252 
4253   if (Old->isInline())
4254     New->setImplicitlyInline();
4255 }
4256 
4257 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4258   SourceManager &SrcMgr = getSourceManager();
4259   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4260   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4261   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4262   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4263   auto &HSI = PP.getHeaderSearchInfo();
4264   StringRef HdrFilename =
4265       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4266 
4267   auto noteFromModuleOrInclude = [&](Module *Mod,
4268                                      SourceLocation IncLoc) -> bool {
4269     // Redefinition errors with modules are common with non modular mapped
4270     // headers, example: a non-modular header H in module A that also gets
4271     // included directly in a TU. Pointing twice to the same header/definition
4272     // is confusing, try to get better diagnostics when modules is on.
4273     if (IncLoc.isValid()) {
4274       if (Mod) {
4275         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4276             << HdrFilename.str() << Mod->getFullModuleName();
4277         if (!Mod->DefinitionLoc.isInvalid())
4278           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4279               << Mod->getFullModuleName();
4280       } else {
4281         Diag(IncLoc, diag::note_redefinition_include_same_file)
4282             << HdrFilename.str();
4283       }
4284       return true;
4285     }
4286 
4287     return false;
4288   };
4289 
4290   // Is it the same file and same offset? Provide more information on why
4291   // this leads to a redefinition error.
4292   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4293     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4294     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4295     bool EmittedDiag =
4296         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4297     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4298 
4299     // If the header has no guards, emit a note suggesting one.
4300     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4301       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4302 
4303     if (EmittedDiag)
4304       return;
4305   }
4306 
4307   // Redefinition coming from different files or couldn't do better above.
4308   if (Old->getLocation().isValid())
4309     Diag(Old->getLocation(), diag::note_previous_definition);
4310 }
4311 
4312 /// We've just determined that \p Old and \p New both appear to be definitions
4313 /// of the same variable. Either diagnose or fix the problem.
4314 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4315   if (!hasVisibleDefinition(Old) &&
4316       (New->getFormalLinkage() == InternalLinkage ||
4317        New->isInline() ||
4318        New->getDescribedVarTemplate() ||
4319        New->getNumTemplateParameterLists() ||
4320        New->getDeclContext()->isDependentContext())) {
4321     // The previous definition is hidden, and multiple definitions are
4322     // permitted (in separate TUs). Demote this to a declaration.
4323     New->demoteThisDefinitionToDeclaration();
4324 
4325     // Make the canonical definition visible.
4326     if (auto *OldTD = Old->getDescribedVarTemplate())
4327       makeMergedDefinitionVisible(OldTD);
4328     makeMergedDefinitionVisible(Old);
4329     return false;
4330   } else {
4331     Diag(New->getLocation(), diag::err_redefinition) << New;
4332     notePreviousDefinition(Old, New->getLocation());
4333     New->setInvalidDecl();
4334     return true;
4335   }
4336 }
4337 
4338 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4339 /// no declarator (e.g. "struct foo;") is parsed.
4340 Decl *
4341 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4342                                  RecordDecl *&AnonRecord) {
4343   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4344                                     AnonRecord);
4345 }
4346 
4347 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4348 // disambiguate entities defined in different scopes.
4349 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4350 // compatibility.
4351 // We will pick our mangling number depending on which version of MSVC is being
4352 // targeted.
4353 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4354   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4355              ? S->getMSCurManglingNumber()
4356              : S->getMSLastManglingNumber();
4357 }
4358 
4359 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4360   if (!Context.getLangOpts().CPlusPlus)
4361     return;
4362 
4363   if (isa<CXXRecordDecl>(Tag->getParent())) {
4364     // If this tag is the direct child of a class, number it if
4365     // it is anonymous.
4366     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4367       return;
4368     MangleNumberingContext &MCtx =
4369         Context.getManglingNumberContext(Tag->getParent());
4370     Context.setManglingNumber(
4371         Tag, MCtx.getManglingNumber(
4372                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4373     return;
4374   }
4375 
4376   // If this tag isn't a direct child of a class, number it if it is local.
4377   MangleNumberingContext *MCtx;
4378   Decl *ManglingContextDecl;
4379   std::tie(MCtx, ManglingContextDecl) =
4380       getCurrentMangleNumberContext(Tag->getDeclContext());
4381   if (MCtx) {
4382     Context.setManglingNumber(
4383         Tag, MCtx->getManglingNumber(
4384                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4385   }
4386 }
4387 
4388 namespace {
4389 struct NonCLikeKind {
4390   enum {
4391     None,
4392     BaseClass,
4393     DefaultMemberInit,
4394     Lambda,
4395     Friend,
4396     OtherMember,
4397     Invalid,
4398   } Kind = None;
4399   SourceRange Range;
4400 
4401   explicit operator bool() { return Kind != None; }
4402 };
4403 }
4404 
4405 /// Determine whether a class is C-like, according to the rules of C++
4406 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4407 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4408   if (RD->isInvalidDecl())
4409     return {NonCLikeKind::Invalid, {}};
4410 
4411   // C++ [dcl.typedef]p9: [P1766R1]
4412   //   An unnamed class with a typedef name for linkage purposes shall not
4413   //
4414   //    -- have any base classes
4415   if (RD->getNumBases())
4416     return {NonCLikeKind::BaseClass,
4417             SourceRange(RD->bases_begin()->getBeginLoc(),
4418                         RD->bases_end()[-1].getEndLoc())};
4419   bool Invalid = false;
4420   for (Decl *D : RD->decls()) {
4421     // Don't complain about things we already diagnosed.
4422     if (D->isInvalidDecl()) {
4423       Invalid = true;
4424       continue;
4425     }
4426 
4427     //  -- have any [...] default member initializers
4428     if (auto *FD = dyn_cast<FieldDecl>(D)) {
4429       if (FD->hasInClassInitializer()) {
4430         auto *Init = FD->getInClassInitializer();
4431         return {NonCLikeKind::DefaultMemberInit,
4432                 Init ? Init->getSourceRange() : D->getSourceRange()};
4433       }
4434       continue;
4435     }
4436 
4437     // FIXME: We don't allow friend declarations. This violates the wording of
4438     // P1766, but not the intent.
4439     if (isa<FriendDecl>(D))
4440       return {NonCLikeKind::Friend, D->getSourceRange()};
4441 
4442     //  -- declare any members other than non-static data members, member
4443     //     enumerations, or member classes,
4444     if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4445         isa<EnumDecl>(D))
4446       continue;
4447     auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4448     if (!MemberRD) {
4449       if (D->isImplicit())
4450         continue;
4451       return {NonCLikeKind::OtherMember, D->getSourceRange()};
4452     }
4453 
4454     //  -- contain a lambda-expression,
4455     if (MemberRD->isLambda())
4456       return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4457 
4458     //  and all member classes shall also satisfy these requirements
4459     //  (recursively).
4460     if (MemberRD->isThisDeclarationADefinition()) {
4461       if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4462         return Kind;
4463     }
4464   }
4465 
4466   return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4467 }
4468 
4469 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4470                                         TypedefNameDecl *NewTD) {
4471   if (TagFromDeclSpec->isInvalidDecl())
4472     return;
4473 
4474   // Do nothing if the tag already has a name for linkage purposes.
4475   if (TagFromDeclSpec->hasNameForLinkage())
4476     return;
4477 
4478   // A well-formed anonymous tag must always be a TUK_Definition.
4479   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4480 
4481   // The type must match the tag exactly;  no qualifiers allowed.
4482   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4483                            Context.getTagDeclType(TagFromDeclSpec))) {
4484     if (getLangOpts().CPlusPlus)
4485       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4486     return;
4487   }
4488 
4489   // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4490   //   An unnamed class with a typedef name for linkage purposes shall [be
4491   //   C-like].
4492   //
4493   // FIXME: Also diagnose if we've already computed the linkage. That ideally
4494   // shouldn't happen, but there are constructs that the language rule doesn't
4495   // disallow for which we can't reasonably avoid computing linkage early.
4496   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4497   NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4498                              : NonCLikeKind();
4499   bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4500   if (NonCLike || ChangesLinkage) {
4501     if (NonCLike.Kind == NonCLikeKind::Invalid)
4502       return;
4503 
4504     unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4505     if (ChangesLinkage) {
4506       // If the linkage changes, we can't accept this as an extension.
4507       if (NonCLike.Kind == NonCLikeKind::None)
4508         DiagID = diag::err_typedef_changes_linkage;
4509       else
4510         DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4511     }
4512 
4513     SourceLocation FixitLoc =
4514         getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4515     llvm::SmallString<40> TextToInsert;
4516     TextToInsert += ' ';
4517     TextToInsert += NewTD->getIdentifier()->getName();
4518 
4519     Diag(FixitLoc, DiagID)
4520       << isa<TypeAliasDecl>(NewTD)
4521       << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4522     if (NonCLike.Kind != NonCLikeKind::None) {
4523       Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4524         << NonCLike.Kind - 1 << NonCLike.Range;
4525     }
4526     Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4527       << NewTD << isa<TypeAliasDecl>(NewTD);
4528 
4529     if (ChangesLinkage)
4530       return;
4531   }
4532 
4533   // Otherwise, set this as the anon-decl typedef for the tag.
4534   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4535 }
4536 
4537 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4538   switch (T) {
4539   case DeclSpec::TST_class:
4540     return 0;
4541   case DeclSpec::TST_struct:
4542     return 1;
4543   case DeclSpec::TST_interface:
4544     return 2;
4545   case DeclSpec::TST_union:
4546     return 3;
4547   case DeclSpec::TST_enum:
4548     return 4;
4549   default:
4550     llvm_unreachable("unexpected type specifier");
4551   }
4552 }
4553 
4554 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4555 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4556 /// parameters to cope with template friend declarations.
4557 Decl *
4558 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4559                                  MultiTemplateParamsArg TemplateParams,
4560                                  bool IsExplicitInstantiation,
4561                                  RecordDecl *&AnonRecord) {
4562   Decl *TagD = nullptr;
4563   TagDecl *Tag = nullptr;
4564   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4565       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4566       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4567       DS.getTypeSpecType() == DeclSpec::TST_union ||
4568       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4569     TagD = DS.getRepAsDecl();
4570 
4571     if (!TagD) // We probably had an error
4572       return nullptr;
4573 
4574     // Note that the above type specs guarantee that the
4575     // type rep is a Decl, whereas in many of the others
4576     // it's a Type.
4577     if (isa<TagDecl>(TagD))
4578       Tag = cast<TagDecl>(TagD);
4579     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4580       Tag = CTD->getTemplatedDecl();
4581   }
4582 
4583   if (Tag) {
4584     handleTagNumbering(Tag, S);
4585     Tag->setFreeStanding();
4586     if (Tag->isInvalidDecl())
4587       return Tag;
4588   }
4589 
4590   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4591     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4592     // or incomplete types shall not be restrict-qualified."
4593     if (TypeQuals & DeclSpec::TQ_restrict)
4594       Diag(DS.getRestrictSpecLoc(),
4595            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4596            << DS.getSourceRange();
4597   }
4598 
4599   if (DS.isInlineSpecified())
4600     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4601         << getLangOpts().CPlusPlus17;
4602 
4603   if (DS.hasConstexprSpecifier()) {
4604     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4605     // and definitions of functions and variables.
4606     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4607     // the declaration of a function or function template
4608     if (Tag)
4609       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4610           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4611           << static_cast<int>(DS.getConstexprSpecifier());
4612     else
4613       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4614           << static_cast<int>(DS.getConstexprSpecifier());
4615     // Don't emit warnings after this error.
4616     return TagD;
4617   }
4618 
4619   DiagnoseFunctionSpecifiers(DS);
4620 
4621   if (DS.isFriendSpecified()) {
4622     // If we're dealing with a decl but not a TagDecl, assume that
4623     // whatever routines created it handled the friendship aspect.
4624     if (TagD && !Tag)
4625       return nullptr;
4626     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4627   }
4628 
4629   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4630   bool IsExplicitSpecialization =
4631     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4632   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4633       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4634       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4635     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4636     // nested-name-specifier unless it is an explicit instantiation
4637     // or an explicit specialization.
4638     //
4639     // FIXME: We allow class template partial specializations here too, per the
4640     // obvious intent of DR1819.
4641     //
4642     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4643     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4644         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4645     return nullptr;
4646   }
4647 
4648   // Track whether this decl-specifier declares anything.
4649   bool DeclaresAnything = true;
4650 
4651   // Handle anonymous struct definitions.
4652   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4653     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4654         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4655       if (getLangOpts().CPlusPlus ||
4656           Record->getDeclContext()->isRecord()) {
4657         // If CurContext is a DeclContext that can contain statements,
4658         // RecursiveASTVisitor won't visit the decls that
4659         // BuildAnonymousStructOrUnion() will put into CurContext.
4660         // Also store them here so that they can be part of the
4661         // DeclStmt that gets created in this case.
4662         // FIXME: Also return the IndirectFieldDecls created by
4663         // BuildAnonymousStructOr union, for the same reason?
4664         if (CurContext->isFunctionOrMethod())
4665           AnonRecord = Record;
4666         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4667                                            Context.getPrintingPolicy());
4668       }
4669 
4670       DeclaresAnything = false;
4671     }
4672   }
4673 
4674   // C11 6.7.2.1p2:
4675   //   A struct-declaration that does not declare an anonymous structure or
4676   //   anonymous union shall contain a struct-declarator-list.
4677   //
4678   // This rule also existed in C89 and C99; the grammar for struct-declaration
4679   // did not permit a struct-declaration without a struct-declarator-list.
4680   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4681       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4682     // Check for Microsoft C extension: anonymous struct/union member.
4683     // Handle 2 kinds of anonymous struct/union:
4684     //   struct STRUCT;
4685     //   union UNION;
4686     // and
4687     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4688     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4689     if ((Tag && Tag->getDeclName()) ||
4690         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4691       RecordDecl *Record = nullptr;
4692       if (Tag)
4693         Record = dyn_cast<RecordDecl>(Tag);
4694       else if (const RecordType *RT =
4695                    DS.getRepAsType().get()->getAsStructureType())
4696         Record = RT->getDecl();
4697       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4698         Record = UT->getDecl();
4699 
4700       if (Record && getLangOpts().MicrosoftExt) {
4701         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4702             << Record->isUnion() << DS.getSourceRange();
4703         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4704       }
4705 
4706       DeclaresAnything = false;
4707     }
4708   }
4709 
4710   // Skip all the checks below if we have a type error.
4711   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4712       (TagD && TagD->isInvalidDecl()))
4713     return TagD;
4714 
4715   if (getLangOpts().CPlusPlus &&
4716       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4717     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4718       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4719           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4720         DeclaresAnything = false;
4721 
4722   if (!DS.isMissingDeclaratorOk()) {
4723     // Customize diagnostic for a typedef missing a name.
4724     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4725       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4726           << DS.getSourceRange();
4727     else
4728       DeclaresAnything = false;
4729   }
4730 
4731   if (DS.isModulePrivateSpecified() &&
4732       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4733     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4734       << Tag->getTagKind()
4735       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4736 
4737   ActOnDocumentableDecl(TagD);
4738 
4739   // C 6.7/2:
4740   //   A declaration [...] shall declare at least a declarator [...], a tag,
4741   //   or the members of an enumeration.
4742   // C++ [dcl.dcl]p3:
4743   //   [If there are no declarators], and except for the declaration of an
4744   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4745   //   names into the program, or shall redeclare a name introduced by a
4746   //   previous declaration.
4747   if (!DeclaresAnything) {
4748     // In C, we allow this as a (popular) extension / bug. Don't bother
4749     // producing further diagnostics for redundant qualifiers after this.
4750     Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
4751                                ? diag::err_no_declarators
4752                                : diag::ext_no_declarators)
4753         << DS.getSourceRange();
4754     return TagD;
4755   }
4756 
4757   // C++ [dcl.stc]p1:
4758   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4759   //   init-declarator-list of the declaration shall not be empty.
4760   // C++ [dcl.fct.spec]p1:
4761   //   If a cv-qualifier appears in a decl-specifier-seq, the
4762   //   init-declarator-list of the declaration shall not be empty.
4763   //
4764   // Spurious qualifiers here appear to be valid in C.
4765   unsigned DiagID = diag::warn_standalone_specifier;
4766   if (getLangOpts().CPlusPlus)
4767     DiagID = diag::ext_standalone_specifier;
4768 
4769   // Note that a linkage-specification sets a storage class, but
4770   // 'extern "C" struct foo;' is actually valid and not theoretically
4771   // useless.
4772   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4773     if (SCS == DeclSpec::SCS_mutable)
4774       // Since mutable is not a viable storage class specifier in C, there is
4775       // no reason to treat it as an extension. Instead, diagnose as an error.
4776       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4777     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4778       Diag(DS.getStorageClassSpecLoc(), DiagID)
4779         << DeclSpec::getSpecifierName(SCS);
4780   }
4781 
4782   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4783     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4784       << DeclSpec::getSpecifierName(TSCS);
4785   if (DS.getTypeQualifiers()) {
4786     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4787       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4788     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4789       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4790     // Restrict is covered above.
4791     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4792       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4793     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4794       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4795   }
4796 
4797   // Warn about ignored type attributes, for example:
4798   // __attribute__((aligned)) struct A;
4799   // Attributes should be placed after tag to apply to type declaration.
4800   if (!DS.getAttributes().empty()) {
4801     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4802     if (TypeSpecType == DeclSpec::TST_class ||
4803         TypeSpecType == DeclSpec::TST_struct ||
4804         TypeSpecType == DeclSpec::TST_interface ||
4805         TypeSpecType == DeclSpec::TST_union ||
4806         TypeSpecType == DeclSpec::TST_enum) {
4807       for (const ParsedAttr &AL : DS.getAttributes())
4808         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4809             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4810     }
4811   }
4812 
4813   return TagD;
4814 }
4815 
4816 /// We are trying to inject an anonymous member into the given scope;
4817 /// check if there's an existing declaration that can't be overloaded.
4818 ///
4819 /// \return true if this is a forbidden redeclaration
4820 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4821                                          Scope *S,
4822                                          DeclContext *Owner,
4823                                          DeclarationName Name,
4824                                          SourceLocation NameLoc,
4825                                          bool IsUnion) {
4826   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4827                  Sema::ForVisibleRedeclaration);
4828   if (!SemaRef.LookupName(R, S)) return false;
4829 
4830   // Pick a representative declaration.
4831   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4832   assert(PrevDecl && "Expected a non-null Decl");
4833 
4834   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4835     return false;
4836 
4837   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4838     << IsUnion << Name;
4839   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4840 
4841   return true;
4842 }
4843 
4844 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4845 /// anonymous struct or union AnonRecord into the owning context Owner
4846 /// and scope S. This routine will be invoked just after we realize
4847 /// that an unnamed union or struct is actually an anonymous union or
4848 /// struct, e.g.,
4849 ///
4850 /// @code
4851 /// union {
4852 ///   int i;
4853 ///   float f;
4854 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4855 ///    // f into the surrounding scope.x
4856 /// @endcode
4857 ///
4858 /// This routine is recursive, injecting the names of nested anonymous
4859 /// structs/unions into the owning context and scope as well.
4860 static bool
4861 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4862                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4863                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4864   bool Invalid = false;
4865 
4866   // Look every FieldDecl and IndirectFieldDecl with a name.
4867   for (auto *D : AnonRecord->decls()) {
4868     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4869         cast<NamedDecl>(D)->getDeclName()) {
4870       ValueDecl *VD = cast<ValueDecl>(D);
4871       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4872                                        VD->getLocation(),
4873                                        AnonRecord->isUnion())) {
4874         // C++ [class.union]p2:
4875         //   The names of the members of an anonymous union shall be
4876         //   distinct from the names of any other entity in the
4877         //   scope in which the anonymous union is declared.
4878         Invalid = true;
4879       } else {
4880         // C++ [class.union]p2:
4881         //   For the purpose of name lookup, after the anonymous union
4882         //   definition, the members of the anonymous union are
4883         //   considered to have been defined in the scope in which the
4884         //   anonymous union is declared.
4885         unsigned OldChainingSize = Chaining.size();
4886         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4887           Chaining.append(IF->chain_begin(), IF->chain_end());
4888         else
4889           Chaining.push_back(VD);
4890 
4891         assert(Chaining.size() >= 2);
4892         NamedDecl **NamedChain =
4893           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4894         for (unsigned i = 0; i < Chaining.size(); i++)
4895           NamedChain[i] = Chaining[i];
4896 
4897         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4898             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4899             VD->getType(), {NamedChain, Chaining.size()});
4900 
4901         for (const auto *Attr : VD->attrs())
4902           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4903 
4904         IndirectField->setAccess(AS);
4905         IndirectField->setImplicit();
4906         SemaRef.PushOnScopeChains(IndirectField, S);
4907 
4908         // That includes picking up the appropriate access specifier.
4909         if (AS != AS_none) IndirectField->setAccess(AS);
4910 
4911         Chaining.resize(OldChainingSize);
4912       }
4913     }
4914   }
4915 
4916   return Invalid;
4917 }
4918 
4919 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4920 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4921 /// illegal input values are mapped to SC_None.
4922 static StorageClass
4923 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4924   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4925   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4926          "Parser allowed 'typedef' as storage class VarDecl.");
4927   switch (StorageClassSpec) {
4928   case DeclSpec::SCS_unspecified:    return SC_None;
4929   case DeclSpec::SCS_extern:
4930     if (DS.isExternInLinkageSpec())
4931       return SC_None;
4932     return SC_Extern;
4933   case DeclSpec::SCS_static:         return SC_Static;
4934   case DeclSpec::SCS_auto:           return SC_Auto;
4935   case DeclSpec::SCS_register:       return SC_Register;
4936   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4937     // Illegal SCSs map to None: error reporting is up to the caller.
4938   case DeclSpec::SCS_mutable:        // Fall through.
4939   case DeclSpec::SCS_typedef:        return SC_None;
4940   }
4941   llvm_unreachable("unknown storage class specifier");
4942 }
4943 
4944 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4945   assert(Record->hasInClassInitializer());
4946 
4947   for (const auto *I : Record->decls()) {
4948     const auto *FD = dyn_cast<FieldDecl>(I);
4949     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4950       FD = IFD->getAnonField();
4951     if (FD && FD->hasInClassInitializer())
4952       return FD->getLocation();
4953   }
4954 
4955   llvm_unreachable("couldn't find in-class initializer");
4956 }
4957 
4958 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4959                                       SourceLocation DefaultInitLoc) {
4960   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4961     return;
4962 
4963   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4964   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4965 }
4966 
4967 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4968                                       CXXRecordDecl *AnonUnion) {
4969   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4970     return;
4971 
4972   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4973 }
4974 
4975 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4976 /// anonymous structure or union. Anonymous unions are a C++ feature
4977 /// (C++ [class.union]) and a C11 feature; anonymous structures
4978 /// are a C11 feature and GNU C++ extension.
4979 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4980                                         AccessSpecifier AS,
4981                                         RecordDecl *Record,
4982                                         const PrintingPolicy &Policy) {
4983   DeclContext *Owner = Record->getDeclContext();
4984 
4985   // Diagnose whether this anonymous struct/union is an extension.
4986   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4987     Diag(Record->getLocation(), diag::ext_anonymous_union);
4988   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4989     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4990   else if (!Record->isUnion() && !getLangOpts().C11)
4991     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4992 
4993   // C and C++ require different kinds of checks for anonymous
4994   // structs/unions.
4995   bool Invalid = false;
4996   if (getLangOpts().CPlusPlus) {
4997     const char *PrevSpec = nullptr;
4998     if (Record->isUnion()) {
4999       // C++ [class.union]p6:
5000       // C++17 [class.union.anon]p2:
5001       //   Anonymous unions declared in a named namespace or in the
5002       //   global namespace shall be declared static.
5003       unsigned DiagID;
5004       DeclContext *OwnerScope = Owner->getRedeclContext();
5005       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5006           (OwnerScope->isTranslationUnit() ||
5007            (OwnerScope->isNamespace() &&
5008             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5009         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5010           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5011 
5012         // Recover by adding 'static'.
5013         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5014                                PrevSpec, DiagID, Policy);
5015       }
5016       // C++ [class.union]p6:
5017       //   A storage class is not allowed in a declaration of an
5018       //   anonymous union in a class scope.
5019       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5020                isa<RecordDecl>(Owner)) {
5021         Diag(DS.getStorageClassSpecLoc(),
5022              diag::err_anonymous_union_with_storage_spec)
5023           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5024 
5025         // Recover by removing the storage specifier.
5026         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5027                                SourceLocation(),
5028                                PrevSpec, DiagID, Context.getPrintingPolicy());
5029       }
5030     }
5031 
5032     // Ignore const/volatile/restrict qualifiers.
5033     if (DS.getTypeQualifiers()) {
5034       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5035         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5036           << Record->isUnion() << "const"
5037           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5038       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5039         Diag(DS.getVolatileSpecLoc(),
5040              diag::ext_anonymous_struct_union_qualified)
5041           << Record->isUnion() << "volatile"
5042           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5043       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5044         Diag(DS.getRestrictSpecLoc(),
5045              diag::ext_anonymous_struct_union_qualified)
5046           << Record->isUnion() << "restrict"
5047           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5048       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5049         Diag(DS.getAtomicSpecLoc(),
5050              diag::ext_anonymous_struct_union_qualified)
5051           << Record->isUnion() << "_Atomic"
5052           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5053       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5054         Diag(DS.getUnalignedSpecLoc(),
5055              diag::ext_anonymous_struct_union_qualified)
5056           << Record->isUnion() << "__unaligned"
5057           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5058 
5059       DS.ClearTypeQualifiers();
5060     }
5061 
5062     // C++ [class.union]p2:
5063     //   The member-specification of an anonymous union shall only
5064     //   define non-static data members. [Note: nested types and
5065     //   functions cannot be declared within an anonymous union. ]
5066     for (auto *Mem : Record->decls()) {
5067       // Ignore invalid declarations; we already diagnosed them.
5068       if (Mem->isInvalidDecl())
5069         continue;
5070 
5071       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5072         // C++ [class.union]p3:
5073         //   An anonymous union shall not have private or protected
5074         //   members (clause 11).
5075         assert(FD->getAccess() != AS_none);
5076         if (FD->getAccess() != AS_public) {
5077           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5078             << Record->isUnion() << (FD->getAccess() == AS_protected);
5079           Invalid = true;
5080         }
5081 
5082         // C++ [class.union]p1
5083         //   An object of a class with a non-trivial constructor, a non-trivial
5084         //   copy constructor, a non-trivial destructor, or a non-trivial copy
5085         //   assignment operator cannot be a member of a union, nor can an
5086         //   array of such objects.
5087         if (CheckNontrivialField(FD))
5088           Invalid = true;
5089       } else if (Mem->isImplicit()) {
5090         // Any implicit members are fine.
5091       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5092         // This is a type that showed up in an
5093         // elaborated-type-specifier inside the anonymous struct or
5094         // union, but which actually declares a type outside of the
5095         // anonymous struct or union. It's okay.
5096       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5097         if (!MemRecord->isAnonymousStructOrUnion() &&
5098             MemRecord->getDeclName()) {
5099           // Visual C++ allows type definition in anonymous struct or union.
5100           if (getLangOpts().MicrosoftExt)
5101             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5102               << Record->isUnion();
5103           else {
5104             // This is a nested type declaration.
5105             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5106               << Record->isUnion();
5107             Invalid = true;
5108           }
5109         } else {
5110           // This is an anonymous type definition within another anonymous type.
5111           // This is a popular extension, provided by Plan9, MSVC and GCC, but
5112           // not part of standard C++.
5113           Diag(MemRecord->getLocation(),
5114                diag::ext_anonymous_record_with_anonymous_type)
5115             << Record->isUnion();
5116         }
5117       } else if (isa<AccessSpecDecl>(Mem)) {
5118         // Any access specifier is fine.
5119       } else if (isa<StaticAssertDecl>(Mem)) {
5120         // In C++1z, static_assert declarations are also fine.
5121       } else {
5122         // We have something that isn't a non-static data
5123         // member. Complain about it.
5124         unsigned DK = diag::err_anonymous_record_bad_member;
5125         if (isa<TypeDecl>(Mem))
5126           DK = diag::err_anonymous_record_with_type;
5127         else if (isa<FunctionDecl>(Mem))
5128           DK = diag::err_anonymous_record_with_function;
5129         else if (isa<VarDecl>(Mem))
5130           DK = diag::err_anonymous_record_with_static;
5131 
5132         // Visual C++ allows type definition in anonymous struct or union.
5133         if (getLangOpts().MicrosoftExt &&
5134             DK == diag::err_anonymous_record_with_type)
5135           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5136             << Record->isUnion();
5137         else {
5138           Diag(Mem->getLocation(), DK) << Record->isUnion();
5139           Invalid = true;
5140         }
5141       }
5142     }
5143 
5144     // C++11 [class.union]p8 (DR1460):
5145     //   At most one variant member of a union may have a
5146     //   brace-or-equal-initializer.
5147     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5148         Owner->isRecord())
5149       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5150                                 cast<CXXRecordDecl>(Record));
5151   }
5152 
5153   if (!Record->isUnion() && !Owner->isRecord()) {
5154     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5155       << getLangOpts().CPlusPlus;
5156     Invalid = true;
5157   }
5158 
5159   // C++ [dcl.dcl]p3:
5160   //   [If there are no declarators], and except for the declaration of an
5161   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5162   //   names into the program
5163   // C++ [class.mem]p2:
5164   //   each such member-declaration shall either declare at least one member
5165   //   name of the class or declare at least one unnamed bit-field
5166   //
5167   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5168   if (getLangOpts().CPlusPlus && Record->field_empty())
5169     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5170 
5171   // Mock up a declarator.
5172   Declarator Dc(DS, DeclaratorContext::Member);
5173   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5174   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5175 
5176   // Create a declaration for this anonymous struct/union.
5177   NamedDecl *Anon = nullptr;
5178   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5179     Anon = FieldDecl::Create(
5180         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5181         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5182         /*BitWidth=*/nullptr, /*Mutable=*/false,
5183         /*InitStyle=*/ICIS_NoInit);
5184     Anon->setAccess(AS);
5185     ProcessDeclAttributes(S, Anon, Dc);
5186 
5187     if (getLangOpts().CPlusPlus)
5188       FieldCollector->Add(cast<FieldDecl>(Anon));
5189   } else {
5190     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5191     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5192     if (SCSpec == DeclSpec::SCS_mutable) {
5193       // mutable can only appear on non-static class members, so it's always
5194       // an error here
5195       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5196       Invalid = true;
5197       SC = SC_None;
5198     }
5199 
5200     assert(DS.getAttributes().empty() && "No attribute expected");
5201     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5202                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5203                            Context.getTypeDeclType(Record), TInfo, SC);
5204 
5205     // Default-initialize the implicit variable. This initialization will be
5206     // trivial in almost all cases, except if a union member has an in-class
5207     // initializer:
5208     //   union { int n = 0; };
5209     ActOnUninitializedDecl(Anon);
5210   }
5211   Anon->setImplicit();
5212 
5213   // Mark this as an anonymous struct/union type.
5214   Record->setAnonymousStructOrUnion(true);
5215 
5216   // Add the anonymous struct/union object to the current
5217   // context. We'll be referencing this object when we refer to one of
5218   // its members.
5219   Owner->addDecl(Anon);
5220 
5221   // Inject the members of the anonymous struct/union into the owning
5222   // context and into the identifier resolver chain for name lookup
5223   // purposes.
5224   SmallVector<NamedDecl*, 2> Chain;
5225   Chain.push_back(Anon);
5226 
5227   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5228     Invalid = true;
5229 
5230   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5231     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5232       MangleNumberingContext *MCtx;
5233       Decl *ManglingContextDecl;
5234       std::tie(MCtx, ManglingContextDecl) =
5235           getCurrentMangleNumberContext(NewVD->getDeclContext());
5236       if (MCtx) {
5237         Context.setManglingNumber(
5238             NewVD, MCtx->getManglingNumber(
5239                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5240         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5241       }
5242     }
5243   }
5244 
5245   if (Invalid)
5246     Anon->setInvalidDecl();
5247 
5248   return Anon;
5249 }
5250 
5251 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5252 /// Microsoft C anonymous structure.
5253 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5254 /// Example:
5255 ///
5256 /// struct A { int a; };
5257 /// struct B { struct A; int b; };
5258 ///
5259 /// void foo() {
5260 ///   B var;
5261 ///   var.a = 3;
5262 /// }
5263 ///
5264 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5265                                            RecordDecl *Record) {
5266   assert(Record && "expected a record!");
5267 
5268   // Mock up a declarator.
5269   Declarator Dc(DS, DeclaratorContext::TypeName);
5270   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5271   assert(TInfo && "couldn't build declarator info for anonymous struct");
5272 
5273   auto *ParentDecl = cast<RecordDecl>(CurContext);
5274   QualType RecTy = Context.getTypeDeclType(Record);
5275 
5276   // Create a declaration for this anonymous struct.
5277   NamedDecl *Anon =
5278       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5279                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5280                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5281                         /*InitStyle=*/ICIS_NoInit);
5282   Anon->setImplicit();
5283 
5284   // Add the anonymous struct object to the current context.
5285   CurContext->addDecl(Anon);
5286 
5287   // Inject the members of the anonymous struct into the current
5288   // context and into the identifier resolver chain for name lookup
5289   // purposes.
5290   SmallVector<NamedDecl*, 2> Chain;
5291   Chain.push_back(Anon);
5292 
5293   RecordDecl *RecordDef = Record->getDefinition();
5294   if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5295                                diag::err_field_incomplete_or_sizeless) ||
5296       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5297                                           AS_none, Chain)) {
5298     Anon->setInvalidDecl();
5299     ParentDecl->setInvalidDecl();
5300   }
5301 
5302   return Anon;
5303 }
5304 
5305 /// GetNameForDeclarator - Determine the full declaration name for the
5306 /// given Declarator.
5307 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5308   return GetNameFromUnqualifiedId(D.getName());
5309 }
5310 
5311 /// Retrieves the declaration name from a parsed unqualified-id.
5312 DeclarationNameInfo
5313 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5314   DeclarationNameInfo NameInfo;
5315   NameInfo.setLoc(Name.StartLocation);
5316 
5317   switch (Name.getKind()) {
5318 
5319   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5320   case UnqualifiedIdKind::IK_Identifier:
5321     NameInfo.setName(Name.Identifier);
5322     return NameInfo;
5323 
5324   case UnqualifiedIdKind::IK_DeductionGuideName: {
5325     // C++ [temp.deduct.guide]p3:
5326     //   The simple-template-id shall name a class template specialization.
5327     //   The template-name shall be the same identifier as the template-name
5328     //   of the simple-template-id.
5329     // These together intend to imply that the template-name shall name a
5330     // class template.
5331     // FIXME: template<typename T> struct X {};
5332     //        template<typename T> using Y = X<T>;
5333     //        Y(int) -> Y<int>;
5334     //   satisfies these rules but does not name a class template.
5335     TemplateName TN = Name.TemplateName.get().get();
5336     auto *Template = TN.getAsTemplateDecl();
5337     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5338       Diag(Name.StartLocation,
5339            diag::err_deduction_guide_name_not_class_template)
5340         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5341       if (Template)
5342         Diag(Template->getLocation(), diag::note_template_decl_here);
5343       return DeclarationNameInfo();
5344     }
5345 
5346     NameInfo.setName(
5347         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5348     return NameInfo;
5349   }
5350 
5351   case UnqualifiedIdKind::IK_OperatorFunctionId:
5352     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5353                                            Name.OperatorFunctionId.Operator));
5354     NameInfo.setCXXOperatorNameRange(SourceRange(
5355         Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5356     return NameInfo;
5357 
5358   case UnqualifiedIdKind::IK_LiteralOperatorId:
5359     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5360                                                            Name.Identifier));
5361     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5362     return NameInfo;
5363 
5364   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5365     TypeSourceInfo *TInfo;
5366     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5367     if (Ty.isNull())
5368       return DeclarationNameInfo();
5369     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5370                                                Context.getCanonicalType(Ty)));
5371     NameInfo.setNamedTypeInfo(TInfo);
5372     return NameInfo;
5373   }
5374 
5375   case UnqualifiedIdKind::IK_ConstructorName: {
5376     TypeSourceInfo *TInfo;
5377     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5378     if (Ty.isNull())
5379       return DeclarationNameInfo();
5380     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5381                                               Context.getCanonicalType(Ty)));
5382     NameInfo.setNamedTypeInfo(TInfo);
5383     return NameInfo;
5384   }
5385 
5386   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5387     // In well-formed code, we can only have a constructor
5388     // template-id that refers to the current context, so go there
5389     // to find the actual type being constructed.
5390     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5391     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5392       return DeclarationNameInfo();
5393 
5394     // Determine the type of the class being constructed.
5395     QualType CurClassType = Context.getTypeDeclType(CurClass);
5396 
5397     // FIXME: Check two things: that the template-id names the same type as
5398     // CurClassType, and that the template-id does not occur when the name
5399     // was qualified.
5400 
5401     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5402                                     Context.getCanonicalType(CurClassType)));
5403     // FIXME: should we retrieve TypeSourceInfo?
5404     NameInfo.setNamedTypeInfo(nullptr);
5405     return NameInfo;
5406   }
5407 
5408   case UnqualifiedIdKind::IK_DestructorName: {
5409     TypeSourceInfo *TInfo;
5410     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5411     if (Ty.isNull())
5412       return DeclarationNameInfo();
5413     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5414                                               Context.getCanonicalType(Ty)));
5415     NameInfo.setNamedTypeInfo(TInfo);
5416     return NameInfo;
5417   }
5418 
5419   case UnqualifiedIdKind::IK_TemplateId: {
5420     TemplateName TName = Name.TemplateId->Template.get();
5421     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5422     return Context.getNameForTemplate(TName, TNameLoc);
5423   }
5424 
5425   } // switch (Name.getKind())
5426 
5427   llvm_unreachable("Unknown name kind");
5428 }
5429 
5430 static QualType getCoreType(QualType Ty) {
5431   do {
5432     if (Ty->isPointerType() || Ty->isReferenceType())
5433       Ty = Ty->getPointeeType();
5434     else if (Ty->isArrayType())
5435       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5436     else
5437       return Ty.withoutLocalFastQualifiers();
5438   } while (true);
5439 }
5440 
5441 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5442 /// and Definition have "nearly" matching parameters. This heuristic is
5443 /// used to improve diagnostics in the case where an out-of-line function
5444 /// definition doesn't match any declaration within the class or namespace.
5445 /// Also sets Params to the list of indices to the parameters that differ
5446 /// between the declaration and the definition. If hasSimilarParameters
5447 /// returns true and Params is empty, then all of the parameters match.
5448 static bool hasSimilarParameters(ASTContext &Context,
5449                                      FunctionDecl *Declaration,
5450                                      FunctionDecl *Definition,
5451                                      SmallVectorImpl<unsigned> &Params) {
5452   Params.clear();
5453   if (Declaration->param_size() != Definition->param_size())
5454     return false;
5455   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5456     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5457     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5458 
5459     // The parameter types are identical
5460     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5461       continue;
5462 
5463     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5464     QualType DefParamBaseTy = getCoreType(DefParamTy);
5465     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5466     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5467 
5468     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5469         (DeclTyName && DeclTyName == DefTyName))
5470       Params.push_back(Idx);
5471     else  // The two parameters aren't even close
5472       return false;
5473   }
5474 
5475   return true;
5476 }
5477 
5478 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5479 /// declarator needs to be rebuilt in the current instantiation.
5480 /// Any bits of declarator which appear before the name are valid for
5481 /// consideration here.  That's specifically the type in the decl spec
5482 /// and the base type in any member-pointer chunks.
5483 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5484                                                     DeclarationName Name) {
5485   // The types we specifically need to rebuild are:
5486   //   - typenames, typeofs, and decltypes
5487   //   - types which will become injected class names
5488   // Of course, we also need to rebuild any type referencing such a
5489   // type.  It's safest to just say "dependent", but we call out a
5490   // few cases here.
5491 
5492   DeclSpec &DS = D.getMutableDeclSpec();
5493   switch (DS.getTypeSpecType()) {
5494   case DeclSpec::TST_typename:
5495   case DeclSpec::TST_typeofType:
5496   case DeclSpec::TST_underlyingType:
5497   case DeclSpec::TST_atomic: {
5498     // Grab the type from the parser.
5499     TypeSourceInfo *TSI = nullptr;
5500     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5501     if (T.isNull() || !T->isInstantiationDependentType()) break;
5502 
5503     // Make sure there's a type source info.  This isn't really much
5504     // of a waste; most dependent types should have type source info
5505     // attached already.
5506     if (!TSI)
5507       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5508 
5509     // Rebuild the type in the current instantiation.
5510     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5511     if (!TSI) return true;
5512 
5513     // Store the new type back in the decl spec.
5514     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5515     DS.UpdateTypeRep(LocType);
5516     break;
5517   }
5518 
5519   case DeclSpec::TST_decltype:
5520   case DeclSpec::TST_typeofExpr: {
5521     Expr *E = DS.getRepAsExpr();
5522     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5523     if (Result.isInvalid()) return true;
5524     DS.UpdateExprRep(Result.get());
5525     break;
5526   }
5527 
5528   default:
5529     // Nothing to do for these decl specs.
5530     break;
5531   }
5532 
5533   // It doesn't matter what order we do this in.
5534   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5535     DeclaratorChunk &Chunk = D.getTypeObject(I);
5536 
5537     // The only type information in the declarator which can come
5538     // before the declaration name is the base type of a member
5539     // pointer.
5540     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5541       continue;
5542 
5543     // Rebuild the scope specifier in-place.
5544     CXXScopeSpec &SS = Chunk.Mem.Scope();
5545     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5546       return true;
5547   }
5548 
5549   return false;
5550 }
5551 
5552 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5553   D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
5554   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5555 
5556   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5557       Dcl && Dcl->getDeclContext()->isFileContext())
5558     Dcl->setTopLevelDeclInObjCContainer();
5559 
5560   if (getLangOpts().OpenCL)
5561     setCurrentOpenCLExtensionForDecl(Dcl);
5562 
5563   return Dcl;
5564 }
5565 
5566 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5567 ///   If T is the name of a class, then each of the following shall have a
5568 ///   name different from T:
5569 ///     - every static data member of class T;
5570 ///     - every member function of class T
5571 ///     - every member of class T that is itself a type;
5572 /// \returns true if the declaration name violates these rules.
5573 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5574                                    DeclarationNameInfo NameInfo) {
5575   DeclarationName Name = NameInfo.getName();
5576 
5577   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5578   while (Record && Record->isAnonymousStructOrUnion())
5579     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5580   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5581     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5582     return true;
5583   }
5584 
5585   return false;
5586 }
5587 
5588 /// Diagnose a declaration whose declarator-id has the given
5589 /// nested-name-specifier.
5590 ///
5591 /// \param SS The nested-name-specifier of the declarator-id.
5592 ///
5593 /// \param DC The declaration context to which the nested-name-specifier
5594 /// resolves.
5595 ///
5596 /// \param Name The name of the entity being declared.
5597 ///
5598 /// \param Loc The location of the name of the entity being declared.
5599 ///
5600 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5601 /// we're declaring an explicit / partial specialization / instantiation.
5602 ///
5603 /// \returns true if we cannot safely recover from this error, false otherwise.
5604 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5605                                         DeclarationName Name,
5606                                         SourceLocation Loc, bool IsTemplateId) {
5607   DeclContext *Cur = CurContext;
5608   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5609     Cur = Cur->getParent();
5610 
5611   // If the user provided a superfluous scope specifier that refers back to the
5612   // class in which the entity is already declared, diagnose and ignore it.
5613   //
5614   // class X {
5615   //   void X::f();
5616   // };
5617   //
5618   // Note, it was once ill-formed to give redundant qualification in all
5619   // contexts, but that rule was removed by DR482.
5620   if (Cur->Equals(DC)) {
5621     if (Cur->isRecord()) {
5622       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5623                                       : diag::err_member_extra_qualification)
5624         << Name << FixItHint::CreateRemoval(SS.getRange());
5625       SS.clear();
5626     } else {
5627       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5628     }
5629     return false;
5630   }
5631 
5632   // Check whether the qualifying scope encloses the scope of the original
5633   // declaration. For a template-id, we perform the checks in
5634   // CheckTemplateSpecializationScope.
5635   if (!Cur->Encloses(DC) && !IsTemplateId) {
5636     if (Cur->isRecord())
5637       Diag(Loc, diag::err_member_qualification)
5638         << Name << SS.getRange();
5639     else if (isa<TranslationUnitDecl>(DC))
5640       Diag(Loc, diag::err_invalid_declarator_global_scope)
5641         << Name << SS.getRange();
5642     else if (isa<FunctionDecl>(Cur))
5643       Diag(Loc, diag::err_invalid_declarator_in_function)
5644         << Name << SS.getRange();
5645     else if (isa<BlockDecl>(Cur))
5646       Diag(Loc, diag::err_invalid_declarator_in_block)
5647         << Name << SS.getRange();
5648     else
5649       Diag(Loc, diag::err_invalid_declarator_scope)
5650       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5651 
5652     return true;
5653   }
5654 
5655   if (Cur->isRecord()) {
5656     // Cannot qualify members within a class.
5657     Diag(Loc, diag::err_member_qualification)
5658       << Name << SS.getRange();
5659     SS.clear();
5660 
5661     // C++ constructors and destructors with incorrect scopes can break
5662     // our AST invariants by having the wrong underlying types. If
5663     // that's the case, then drop this declaration entirely.
5664     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5665          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5666         !Context.hasSameType(Name.getCXXNameType(),
5667                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5668       return true;
5669 
5670     return false;
5671   }
5672 
5673   // C++11 [dcl.meaning]p1:
5674   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5675   //   not begin with a decltype-specifer"
5676   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5677   while (SpecLoc.getPrefix())
5678     SpecLoc = SpecLoc.getPrefix();
5679   if (dyn_cast_or_null<DecltypeType>(
5680         SpecLoc.getNestedNameSpecifier()->getAsType()))
5681     Diag(Loc, diag::err_decltype_in_declarator)
5682       << SpecLoc.getTypeLoc().getSourceRange();
5683 
5684   return false;
5685 }
5686 
5687 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5688                                   MultiTemplateParamsArg TemplateParamLists) {
5689   // TODO: consider using NameInfo for diagnostic.
5690   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5691   DeclarationName Name = NameInfo.getName();
5692 
5693   // All of these full declarators require an identifier.  If it doesn't have
5694   // one, the ParsedFreeStandingDeclSpec action should be used.
5695   if (D.isDecompositionDeclarator()) {
5696     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5697   } else if (!Name) {
5698     if (!D.isInvalidType())  // Reject this if we think it is valid.
5699       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5700           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5701     return nullptr;
5702   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5703     return nullptr;
5704 
5705   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5706   // we find one that is.
5707   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5708          (S->getFlags() & Scope::TemplateParamScope) != 0)
5709     S = S->getParent();
5710 
5711   DeclContext *DC = CurContext;
5712   if (D.getCXXScopeSpec().isInvalid())
5713     D.setInvalidType();
5714   else if (D.getCXXScopeSpec().isSet()) {
5715     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5716                                         UPPC_DeclarationQualifier))
5717       return nullptr;
5718 
5719     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5720     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5721     if (!DC || isa<EnumDecl>(DC)) {
5722       // If we could not compute the declaration context, it's because the
5723       // declaration context is dependent but does not refer to a class,
5724       // class template, or class template partial specialization. Complain
5725       // and return early, to avoid the coming semantic disaster.
5726       Diag(D.getIdentifierLoc(),
5727            diag::err_template_qualified_declarator_no_match)
5728         << D.getCXXScopeSpec().getScopeRep()
5729         << D.getCXXScopeSpec().getRange();
5730       return nullptr;
5731     }
5732     bool IsDependentContext = DC->isDependentContext();
5733 
5734     if (!IsDependentContext &&
5735         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5736       return nullptr;
5737 
5738     // If a class is incomplete, do not parse entities inside it.
5739     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5740       Diag(D.getIdentifierLoc(),
5741            diag::err_member_def_undefined_record)
5742         << Name << DC << D.getCXXScopeSpec().getRange();
5743       return nullptr;
5744     }
5745     if (!D.getDeclSpec().isFriendSpecified()) {
5746       if (diagnoseQualifiedDeclaration(
5747               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5748               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5749         if (DC->isRecord())
5750           return nullptr;
5751 
5752         D.setInvalidType();
5753       }
5754     }
5755 
5756     // Check whether we need to rebuild the type of the given
5757     // declaration in the current instantiation.
5758     if (EnteringContext && IsDependentContext &&
5759         TemplateParamLists.size() != 0) {
5760       ContextRAII SavedContext(*this, DC);
5761       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5762         D.setInvalidType();
5763     }
5764   }
5765 
5766   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5767   QualType R = TInfo->getType();
5768 
5769   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5770                                       UPPC_DeclarationType))
5771     D.setInvalidType();
5772 
5773   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5774                         forRedeclarationInCurContext());
5775 
5776   // See if this is a redefinition of a variable in the same scope.
5777   if (!D.getCXXScopeSpec().isSet()) {
5778     bool IsLinkageLookup = false;
5779     bool CreateBuiltins = false;
5780 
5781     // If the declaration we're planning to build will be a function
5782     // or object with linkage, then look for another declaration with
5783     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5784     //
5785     // If the declaration we're planning to build will be declared with
5786     // external linkage in the translation unit, create any builtin with
5787     // the same name.
5788     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5789       /* Do nothing*/;
5790     else if (CurContext->isFunctionOrMethod() &&
5791              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5792               R->isFunctionType())) {
5793       IsLinkageLookup = true;
5794       CreateBuiltins =
5795           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5796     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5797                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5798       CreateBuiltins = true;
5799 
5800     if (IsLinkageLookup) {
5801       Previous.clear(LookupRedeclarationWithLinkage);
5802       Previous.setRedeclarationKind(ForExternalRedeclaration);
5803     }
5804 
5805     LookupName(Previous, S, CreateBuiltins);
5806   } else { // Something like "int foo::x;"
5807     LookupQualifiedName(Previous, DC);
5808 
5809     // C++ [dcl.meaning]p1:
5810     //   When the declarator-id is qualified, the declaration shall refer to a
5811     //  previously declared member of the class or namespace to which the
5812     //  qualifier refers (or, in the case of a namespace, of an element of the
5813     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5814     //  thereof; [...]
5815     //
5816     // Note that we already checked the context above, and that we do not have
5817     // enough information to make sure that Previous contains the declaration
5818     // we want to match. For example, given:
5819     //
5820     //   class X {
5821     //     void f();
5822     //     void f(float);
5823     //   };
5824     //
5825     //   void X::f(int) { } // ill-formed
5826     //
5827     // In this case, Previous will point to the overload set
5828     // containing the two f's declared in X, but neither of them
5829     // matches.
5830 
5831     // C++ [dcl.meaning]p1:
5832     //   [...] the member shall not merely have been introduced by a
5833     //   using-declaration in the scope of the class or namespace nominated by
5834     //   the nested-name-specifier of the declarator-id.
5835     RemoveUsingDecls(Previous);
5836   }
5837 
5838   if (Previous.isSingleResult() &&
5839       Previous.getFoundDecl()->isTemplateParameter()) {
5840     // Maybe we will complain about the shadowed template parameter.
5841     if (!D.isInvalidType())
5842       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5843                                       Previous.getFoundDecl());
5844 
5845     // Just pretend that we didn't see the previous declaration.
5846     Previous.clear();
5847   }
5848 
5849   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5850     // Forget that the previous declaration is the injected-class-name.
5851     Previous.clear();
5852 
5853   // In C++, the previous declaration we find might be a tag type
5854   // (class or enum). In this case, the new declaration will hide the
5855   // tag type. Note that this applies to functions, function templates, and
5856   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5857   if (Previous.isSingleTagDecl() &&
5858       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5859       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5860     Previous.clear();
5861 
5862   // Check that there are no default arguments other than in the parameters
5863   // of a function declaration (C++ only).
5864   if (getLangOpts().CPlusPlus)
5865     CheckExtraCXXDefaultArguments(D);
5866 
5867   NamedDecl *New;
5868 
5869   bool AddToScope = true;
5870   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5871     if (TemplateParamLists.size()) {
5872       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5873       return nullptr;
5874     }
5875 
5876     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5877   } else if (R->isFunctionType()) {
5878     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5879                                   TemplateParamLists,
5880                                   AddToScope);
5881   } else {
5882     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5883                                   AddToScope);
5884   }
5885 
5886   if (!New)
5887     return nullptr;
5888 
5889   // If this has an identifier and is not a function template specialization,
5890   // add it to the scope stack.
5891   if (New->getDeclName() && AddToScope)
5892     PushOnScopeChains(New, S);
5893 
5894   if (isInOpenMPDeclareTargetContext())
5895     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5896 
5897   return New;
5898 }
5899 
5900 /// Helper method to turn variable array types into constant array
5901 /// types in certain situations which would otherwise be errors (for
5902 /// GCC compatibility).
5903 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5904                                                     ASTContext &Context,
5905                                                     bool &SizeIsNegative,
5906                                                     llvm::APSInt &Oversized) {
5907   // This method tries to turn a variable array into a constant
5908   // array even when the size isn't an ICE.  This is necessary
5909   // for compatibility with code that depends on gcc's buggy
5910   // constant expression folding, like struct {char x[(int)(char*)2];}
5911   SizeIsNegative = false;
5912   Oversized = 0;
5913 
5914   if (T->isDependentType())
5915     return QualType();
5916 
5917   QualifierCollector Qs;
5918   const Type *Ty = Qs.strip(T);
5919 
5920   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5921     QualType Pointee = PTy->getPointeeType();
5922     QualType FixedType =
5923         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5924                                             Oversized);
5925     if (FixedType.isNull()) return FixedType;
5926     FixedType = Context.getPointerType(FixedType);
5927     return Qs.apply(Context, FixedType);
5928   }
5929   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5930     QualType Inner = PTy->getInnerType();
5931     QualType FixedType =
5932         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5933                                             Oversized);
5934     if (FixedType.isNull()) return FixedType;
5935     FixedType = Context.getParenType(FixedType);
5936     return Qs.apply(Context, FixedType);
5937   }
5938 
5939   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5940   if (!VLATy)
5941     return QualType();
5942 
5943   QualType ElemTy = VLATy->getElementType();
5944   if (ElemTy->isVariablyModifiedType()) {
5945     ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
5946                                                  SizeIsNegative, Oversized);
5947     if (ElemTy.isNull())
5948       return QualType();
5949   }
5950 
5951   Expr::EvalResult Result;
5952   if (!VLATy->getSizeExpr() ||
5953       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5954     return QualType();
5955 
5956   llvm::APSInt Res = Result.Val.getInt();
5957 
5958   // Check whether the array size is negative.
5959   if (Res.isSigned() && Res.isNegative()) {
5960     SizeIsNegative = true;
5961     return QualType();
5962   }
5963 
5964   // Check whether the array is too large to be addressed.
5965   unsigned ActiveSizeBits =
5966       (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
5967        !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
5968           ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
5969           : Res.getActiveBits();
5970   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5971     Oversized = Res;
5972     return QualType();
5973   }
5974 
5975   QualType FoldedArrayType = Context.getConstantArrayType(
5976       ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
5977   return Qs.apply(Context, FoldedArrayType);
5978 }
5979 
5980 static void
5981 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5982   SrcTL = SrcTL.getUnqualifiedLoc();
5983   DstTL = DstTL.getUnqualifiedLoc();
5984   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5985     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5986     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5987                                       DstPTL.getPointeeLoc());
5988     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5989     return;
5990   }
5991   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5992     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5993     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5994                                       DstPTL.getInnerLoc());
5995     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5996     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5997     return;
5998   }
5999   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6000   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6001   TypeLoc SrcElemTL = SrcATL.getElementLoc();
6002   TypeLoc DstElemTL = DstATL.getElementLoc();
6003   if (VariableArrayTypeLoc SrcElemATL =
6004           SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6005     ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6006     FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6007   } else {
6008     DstElemTL.initializeFullCopy(SrcElemTL);
6009   }
6010   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6011   DstATL.setSizeExpr(SrcATL.getSizeExpr());
6012   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6013 }
6014 
6015 /// Helper method to turn variable array types into constant array
6016 /// types in certain situations which would otherwise be errors (for
6017 /// GCC compatibility).
6018 static TypeSourceInfo*
6019 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6020                                               ASTContext &Context,
6021                                               bool &SizeIsNegative,
6022                                               llvm::APSInt &Oversized) {
6023   QualType FixedTy
6024     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6025                                           SizeIsNegative, Oversized);
6026   if (FixedTy.isNull())
6027     return nullptr;
6028   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6029   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6030                                     FixedTInfo->getTypeLoc());
6031   return FixedTInfo;
6032 }
6033 
6034 /// Attempt to fold a variable-sized type to a constant-sized type, returning
6035 /// true if we were successful.
6036 static bool tryToFixVariablyModifiedVarType(Sema &S, TypeSourceInfo *&TInfo,
6037                                             QualType &T, SourceLocation Loc,
6038                                             unsigned FailedFoldDiagID) {
6039   bool SizeIsNegative;
6040   llvm::APSInt Oversized;
6041   TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6042       TInfo, S.Context, SizeIsNegative, Oversized);
6043   if (FixedTInfo) {
6044     S.Diag(Loc, diag::ext_vla_folded_to_constant);
6045     TInfo = FixedTInfo;
6046     T = FixedTInfo->getType();
6047     return true;
6048   }
6049 
6050   if (SizeIsNegative)
6051     S.Diag(Loc, diag::err_typecheck_negative_array_size);
6052   else if (Oversized.getBoolValue())
6053     S.Diag(Loc, diag::err_array_too_large) << Oversized.toString(10);
6054   else if (FailedFoldDiagID)
6055     S.Diag(Loc, FailedFoldDiagID);
6056   return false;
6057 }
6058 
6059 /// Register the given locally-scoped extern "C" declaration so
6060 /// that it can be found later for redeclarations. We include any extern "C"
6061 /// declaration that is not visible in the translation unit here, not just
6062 /// function-scope declarations.
6063 void
6064 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6065   if (!getLangOpts().CPlusPlus &&
6066       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6067     // Don't need to track declarations in the TU in C.
6068     return;
6069 
6070   // Note that we have a locally-scoped external with this name.
6071   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6072 }
6073 
6074 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6075   // FIXME: We can have multiple results via __attribute__((overloadable)).
6076   auto Result = Context.getExternCContextDecl()->lookup(Name);
6077   return Result.empty() ? nullptr : *Result.begin();
6078 }
6079 
6080 /// Diagnose function specifiers on a declaration of an identifier that
6081 /// does not identify a function.
6082 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6083   // FIXME: We should probably indicate the identifier in question to avoid
6084   // confusion for constructs like "virtual int a(), b;"
6085   if (DS.isVirtualSpecified())
6086     Diag(DS.getVirtualSpecLoc(),
6087          diag::err_virtual_non_function);
6088 
6089   if (DS.hasExplicitSpecifier())
6090     Diag(DS.getExplicitSpecLoc(),
6091          diag::err_explicit_non_function);
6092 
6093   if (DS.isNoreturnSpecified())
6094     Diag(DS.getNoreturnSpecLoc(),
6095          diag::err_noreturn_non_function);
6096 }
6097 
6098 NamedDecl*
6099 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6100                              TypeSourceInfo *TInfo, LookupResult &Previous) {
6101   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6102   if (D.getCXXScopeSpec().isSet()) {
6103     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6104       << D.getCXXScopeSpec().getRange();
6105     D.setInvalidType();
6106     // Pretend we didn't see the scope specifier.
6107     DC = CurContext;
6108     Previous.clear();
6109   }
6110 
6111   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6112 
6113   if (D.getDeclSpec().isInlineSpecified())
6114     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6115         << getLangOpts().CPlusPlus17;
6116   if (D.getDeclSpec().hasConstexprSpecifier())
6117     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6118         << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6119 
6120   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6121     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6122       Diag(D.getName().StartLocation,
6123            diag::err_deduction_guide_invalid_specifier)
6124           << "typedef";
6125     else
6126       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6127           << D.getName().getSourceRange();
6128     return nullptr;
6129   }
6130 
6131   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6132   if (!NewTD) return nullptr;
6133 
6134   // Handle attributes prior to checking for duplicates in MergeVarDecl
6135   ProcessDeclAttributes(S, NewTD, D);
6136 
6137   CheckTypedefForVariablyModifiedType(S, NewTD);
6138 
6139   bool Redeclaration = D.isRedeclaration();
6140   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6141   D.setRedeclaration(Redeclaration);
6142   return ND;
6143 }
6144 
6145 void
6146 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6147   // C99 6.7.7p2: If a typedef name specifies a variably modified type
6148   // then it shall have block scope.
6149   // Note that variably modified types must be fixed before merging the decl so
6150   // that redeclarations will match.
6151   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6152   QualType T = TInfo->getType();
6153   if (T->isVariablyModifiedType()) {
6154     setFunctionHasBranchProtectedScope();
6155 
6156     if (S->getFnParent() == nullptr) {
6157       bool SizeIsNegative;
6158       llvm::APSInt Oversized;
6159       TypeSourceInfo *FixedTInfo =
6160         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6161                                                       SizeIsNegative,
6162                                                       Oversized);
6163       if (FixedTInfo) {
6164         Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6165         NewTD->setTypeSourceInfo(FixedTInfo);
6166       } else {
6167         if (SizeIsNegative)
6168           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6169         else if (T->isVariableArrayType())
6170           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6171         else if (Oversized.getBoolValue())
6172           Diag(NewTD->getLocation(), diag::err_array_too_large)
6173             << Oversized.toString(10);
6174         else
6175           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6176         NewTD->setInvalidDecl();
6177       }
6178     }
6179   }
6180 }
6181 
6182 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6183 /// declares a typedef-name, either using the 'typedef' type specifier or via
6184 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6185 NamedDecl*
6186 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6187                            LookupResult &Previous, bool &Redeclaration) {
6188 
6189   // Find the shadowed declaration before filtering for scope.
6190   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6191 
6192   // Merge the decl with the existing one if appropriate. If the decl is
6193   // in an outer scope, it isn't the same thing.
6194   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6195                        /*AllowInlineNamespace*/false);
6196   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6197   if (!Previous.empty()) {
6198     Redeclaration = true;
6199     MergeTypedefNameDecl(S, NewTD, Previous);
6200   } else {
6201     inferGslPointerAttribute(NewTD);
6202   }
6203 
6204   if (ShadowedDecl && !Redeclaration)
6205     CheckShadow(NewTD, ShadowedDecl, Previous);
6206 
6207   // If this is the C FILE type, notify the AST context.
6208   if (IdentifierInfo *II = NewTD->getIdentifier())
6209     if (!NewTD->isInvalidDecl() &&
6210         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6211       if (II->isStr("FILE"))
6212         Context.setFILEDecl(NewTD);
6213       else if (II->isStr("jmp_buf"))
6214         Context.setjmp_bufDecl(NewTD);
6215       else if (II->isStr("sigjmp_buf"))
6216         Context.setsigjmp_bufDecl(NewTD);
6217       else if (II->isStr("ucontext_t"))
6218         Context.setucontext_tDecl(NewTD);
6219     }
6220 
6221   return NewTD;
6222 }
6223 
6224 /// Determines whether the given declaration is an out-of-scope
6225 /// previous declaration.
6226 ///
6227 /// This routine should be invoked when name lookup has found a
6228 /// previous declaration (PrevDecl) that is not in the scope where a
6229 /// new declaration by the same name is being introduced. If the new
6230 /// declaration occurs in a local scope, previous declarations with
6231 /// linkage may still be considered previous declarations (C99
6232 /// 6.2.2p4-5, C++ [basic.link]p6).
6233 ///
6234 /// \param PrevDecl the previous declaration found by name
6235 /// lookup
6236 ///
6237 /// \param DC the context in which the new declaration is being
6238 /// declared.
6239 ///
6240 /// \returns true if PrevDecl is an out-of-scope previous declaration
6241 /// for a new delcaration with the same name.
6242 static bool
6243 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6244                                 ASTContext &Context) {
6245   if (!PrevDecl)
6246     return false;
6247 
6248   if (!PrevDecl->hasLinkage())
6249     return false;
6250 
6251   if (Context.getLangOpts().CPlusPlus) {
6252     // C++ [basic.link]p6:
6253     //   If there is a visible declaration of an entity with linkage
6254     //   having the same name and type, ignoring entities declared
6255     //   outside the innermost enclosing namespace scope, the block
6256     //   scope declaration declares that same entity and receives the
6257     //   linkage of the previous declaration.
6258     DeclContext *OuterContext = DC->getRedeclContext();
6259     if (!OuterContext->isFunctionOrMethod())
6260       // This rule only applies to block-scope declarations.
6261       return false;
6262 
6263     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6264     if (PrevOuterContext->isRecord())
6265       // We found a member function: ignore it.
6266       return false;
6267 
6268     // Find the innermost enclosing namespace for the new and
6269     // previous declarations.
6270     OuterContext = OuterContext->getEnclosingNamespaceContext();
6271     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6272 
6273     // The previous declaration is in a different namespace, so it
6274     // isn't the same function.
6275     if (!OuterContext->Equals(PrevOuterContext))
6276       return false;
6277   }
6278 
6279   return true;
6280 }
6281 
6282 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6283   CXXScopeSpec &SS = D.getCXXScopeSpec();
6284   if (!SS.isSet()) return;
6285   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6286 }
6287 
6288 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6289   QualType type = decl->getType();
6290   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6291   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6292     // Various kinds of declaration aren't allowed to be __autoreleasing.
6293     unsigned kind = -1U;
6294     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6295       if (var->hasAttr<BlocksAttr>())
6296         kind = 0; // __block
6297       else if (!var->hasLocalStorage())
6298         kind = 1; // global
6299     } else if (isa<ObjCIvarDecl>(decl)) {
6300       kind = 3; // ivar
6301     } else if (isa<FieldDecl>(decl)) {
6302       kind = 2; // field
6303     }
6304 
6305     if (kind != -1U) {
6306       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6307         << kind;
6308     }
6309   } else if (lifetime == Qualifiers::OCL_None) {
6310     // Try to infer lifetime.
6311     if (!type->isObjCLifetimeType())
6312       return false;
6313 
6314     lifetime = type->getObjCARCImplicitLifetime();
6315     type = Context.getLifetimeQualifiedType(type, lifetime);
6316     decl->setType(type);
6317   }
6318 
6319   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6320     // Thread-local variables cannot have lifetime.
6321     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6322         var->getTLSKind()) {
6323       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6324         << var->getType();
6325       return true;
6326     }
6327   }
6328 
6329   return false;
6330 }
6331 
6332 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6333   if (Decl->getType().hasAddressSpace())
6334     return;
6335   if (Decl->getType()->isDependentType())
6336     return;
6337   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6338     QualType Type = Var->getType();
6339     if (Type->isSamplerT() || Type->isVoidType())
6340       return;
6341     LangAS ImplAS = LangAS::opencl_private;
6342     if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) &&
6343         Var->hasGlobalStorage())
6344       ImplAS = LangAS::opencl_global;
6345     // If the original type from a decayed type is an array type and that array
6346     // type has no address space yet, deduce it now.
6347     if (auto DT = dyn_cast<DecayedType>(Type)) {
6348       auto OrigTy = DT->getOriginalType();
6349       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6350         // Add the address space to the original array type and then propagate
6351         // that to the element type through `getAsArrayType`.
6352         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6353         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6354         // Re-generate the decayed type.
6355         Type = Context.getDecayedType(OrigTy);
6356       }
6357     }
6358     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6359     // Apply any qualifiers (including address space) from the array type to
6360     // the element type. This implements C99 6.7.3p8: "If the specification of
6361     // an array type includes any type qualifiers, the element type is so
6362     // qualified, not the array type."
6363     if (Type->isArrayType())
6364       Type = QualType(Context.getAsArrayType(Type), 0);
6365     Decl->setType(Type);
6366   }
6367 }
6368 
6369 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6370   // Ensure that an auto decl is deduced otherwise the checks below might cache
6371   // the wrong linkage.
6372   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6373 
6374   // 'weak' only applies to declarations with external linkage.
6375   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6376     if (!ND.isExternallyVisible()) {
6377       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6378       ND.dropAttr<WeakAttr>();
6379     }
6380   }
6381   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6382     if (ND.isExternallyVisible()) {
6383       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6384       ND.dropAttr<WeakRefAttr>();
6385       ND.dropAttr<AliasAttr>();
6386     }
6387   }
6388 
6389   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6390     if (VD->hasInit()) {
6391       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6392         assert(VD->isThisDeclarationADefinition() &&
6393                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6394         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6395         VD->dropAttr<AliasAttr>();
6396       }
6397     }
6398   }
6399 
6400   // 'selectany' only applies to externally visible variable declarations.
6401   // It does not apply to functions.
6402   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6403     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6404       S.Diag(Attr->getLocation(),
6405              diag::err_attribute_selectany_non_extern_data);
6406       ND.dropAttr<SelectAnyAttr>();
6407     }
6408   }
6409 
6410   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6411     auto *VD = dyn_cast<VarDecl>(&ND);
6412     bool IsAnonymousNS = false;
6413     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6414     if (VD) {
6415       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6416       while (NS && !IsAnonymousNS) {
6417         IsAnonymousNS = NS->isAnonymousNamespace();
6418         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6419       }
6420     }
6421     // dll attributes require external linkage. Static locals may have external
6422     // linkage but still cannot be explicitly imported or exported.
6423     // In Microsoft mode, a variable defined in anonymous namespace must have
6424     // external linkage in order to be exported.
6425     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6426     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6427         (!AnonNSInMicrosoftMode &&
6428          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6429       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6430         << &ND << Attr;
6431       ND.setInvalidDecl();
6432     }
6433   }
6434 
6435   // Virtual functions cannot be marked as 'notail'.
6436   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
6437     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
6438       if (MD->isVirtual()) {
6439         S.Diag(ND.getLocation(),
6440                diag::err_invalid_attribute_on_virtual_function)
6441             << Attr;
6442         ND.dropAttr<NotTailCalledAttr>();
6443       }
6444 
6445   // Check the attributes on the function type, if any.
6446   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6447     // Don't declare this variable in the second operand of the for-statement;
6448     // GCC miscompiles that by ending its lifetime before evaluating the
6449     // third operand. See gcc.gnu.org/PR86769.
6450     AttributedTypeLoc ATL;
6451     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6452          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6453          TL = ATL.getModifiedLoc()) {
6454       // The [[lifetimebound]] attribute can be applied to the implicit object
6455       // parameter of a non-static member function (other than a ctor or dtor)
6456       // by applying it to the function type.
6457       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6458         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6459         if (!MD || MD->isStatic()) {
6460           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6461               << !MD << A->getRange();
6462         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6463           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6464               << isa<CXXDestructorDecl>(MD) << A->getRange();
6465         }
6466       }
6467     }
6468   }
6469 }
6470 
6471 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6472                                            NamedDecl *NewDecl,
6473                                            bool IsSpecialization,
6474                                            bool IsDefinition) {
6475   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6476     return;
6477 
6478   bool IsTemplate = false;
6479   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6480     OldDecl = OldTD->getTemplatedDecl();
6481     IsTemplate = true;
6482     if (!IsSpecialization)
6483       IsDefinition = false;
6484   }
6485   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6486     NewDecl = NewTD->getTemplatedDecl();
6487     IsTemplate = true;
6488   }
6489 
6490   if (!OldDecl || !NewDecl)
6491     return;
6492 
6493   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6494   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6495   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6496   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6497 
6498   // dllimport and dllexport are inheritable attributes so we have to exclude
6499   // inherited attribute instances.
6500   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6501                     (NewExportAttr && !NewExportAttr->isInherited());
6502 
6503   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6504   // the only exception being explicit specializations.
6505   // Implicitly generated declarations are also excluded for now because there
6506   // is no other way to switch these to use dllimport or dllexport.
6507   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6508 
6509   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6510     // Allow with a warning for free functions and global variables.
6511     bool JustWarn = false;
6512     if (!OldDecl->isCXXClassMember()) {
6513       auto *VD = dyn_cast<VarDecl>(OldDecl);
6514       if (VD && !VD->getDescribedVarTemplate())
6515         JustWarn = true;
6516       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6517       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6518         JustWarn = true;
6519     }
6520 
6521     // We cannot change a declaration that's been used because IR has already
6522     // been emitted. Dllimported functions will still work though (modulo
6523     // address equality) as they can use the thunk.
6524     if (OldDecl->isUsed())
6525       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6526         JustWarn = false;
6527 
6528     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6529                                : diag::err_attribute_dll_redeclaration;
6530     S.Diag(NewDecl->getLocation(), DiagID)
6531         << NewDecl
6532         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6533     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6534     if (!JustWarn) {
6535       NewDecl->setInvalidDecl();
6536       return;
6537     }
6538   }
6539 
6540   // A redeclaration is not allowed to drop a dllimport attribute, the only
6541   // exceptions being inline function definitions (except for function
6542   // templates), local extern declarations, qualified friend declarations or
6543   // special MSVC extension: in the last case, the declaration is treated as if
6544   // it were marked dllexport.
6545   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6546   bool IsMicrosoftABI  = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
6547   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6548     // Ignore static data because out-of-line definitions are diagnosed
6549     // separately.
6550     IsStaticDataMember = VD->isStaticDataMember();
6551     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6552                    VarDecl::DeclarationOnly;
6553   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6554     IsInline = FD->isInlined();
6555     IsQualifiedFriend = FD->getQualifier() &&
6556                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6557   }
6558 
6559   if (OldImportAttr && !HasNewAttr &&
6560       (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
6561       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6562     if (IsMicrosoftABI && IsDefinition) {
6563       S.Diag(NewDecl->getLocation(),
6564              diag::warn_redeclaration_without_import_attribute)
6565           << NewDecl;
6566       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6567       NewDecl->dropAttr<DLLImportAttr>();
6568       NewDecl->addAttr(
6569           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6570     } else {
6571       S.Diag(NewDecl->getLocation(),
6572              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6573           << NewDecl << OldImportAttr;
6574       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6575       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6576       OldDecl->dropAttr<DLLImportAttr>();
6577       NewDecl->dropAttr<DLLImportAttr>();
6578     }
6579   } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
6580     // In MinGW, seeing a function declared inline drops the dllimport
6581     // attribute.
6582     OldDecl->dropAttr<DLLImportAttr>();
6583     NewDecl->dropAttr<DLLImportAttr>();
6584     S.Diag(NewDecl->getLocation(),
6585            diag::warn_dllimport_dropped_from_inline_function)
6586         << NewDecl << OldImportAttr;
6587   }
6588 
6589   // A specialization of a class template member function is processed here
6590   // since it's a redeclaration. If the parent class is dllexport, the
6591   // specialization inherits that attribute. This doesn't happen automatically
6592   // since the parent class isn't instantiated until later.
6593   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6594     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6595         !NewImportAttr && !NewExportAttr) {
6596       if (const DLLExportAttr *ParentExportAttr =
6597               MD->getParent()->getAttr<DLLExportAttr>()) {
6598         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6599         NewAttr->setInherited(true);
6600         NewDecl->addAttr(NewAttr);
6601       }
6602     }
6603   }
6604 }
6605 
6606 /// Given that we are within the definition of the given function,
6607 /// will that definition behave like C99's 'inline', where the
6608 /// definition is discarded except for optimization purposes?
6609 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6610   // Try to avoid calling GetGVALinkageForFunction.
6611 
6612   // All cases of this require the 'inline' keyword.
6613   if (!FD->isInlined()) return false;
6614 
6615   // This is only possible in C++ with the gnu_inline attribute.
6616   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6617     return false;
6618 
6619   // Okay, go ahead and call the relatively-more-expensive function.
6620   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6621 }
6622 
6623 /// Determine whether a variable is extern "C" prior to attaching
6624 /// an initializer. We can't just call isExternC() here, because that
6625 /// will also compute and cache whether the declaration is externally
6626 /// visible, which might change when we attach the initializer.
6627 ///
6628 /// This can only be used if the declaration is known to not be a
6629 /// redeclaration of an internal linkage declaration.
6630 ///
6631 /// For instance:
6632 ///
6633 ///   auto x = []{};
6634 ///
6635 /// Attaching the initializer here makes this declaration not externally
6636 /// visible, because its type has internal linkage.
6637 ///
6638 /// FIXME: This is a hack.
6639 template<typename T>
6640 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6641   if (S.getLangOpts().CPlusPlus) {
6642     // In C++, the overloadable attribute negates the effects of extern "C".
6643     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6644       return false;
6645 
6646     // So do CUDA's host/device attributes.
6647     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6648                                  D->template hasAttr<CUDAHostAttr>()))
6649       return false;
6650   }
6651   return D->isExternC();
6652 }
6653 
6654 static bool shouldConsiderLinkage(const VarDecl *VD) {
6655   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6656   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6657       isa<OMPDeclareMapperDecl>(DC))
6658     return VD->hasExternalStorage();
6659   if (DC->isFileContext())
6660     return true;
6661   if (DC->isRecord())
6662     return false;
6663   if (isa<RequiresExprBodyDecl>(DC))
6664     return false;
6665   llvm_unreachable("Unexpected context");
6666 }
6667 
6668 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6669   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6670   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6671       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6672     return true;
6673   if (DC->isRecord())
6674     return false;
6675   llvm_unreachable("Unexpected context");
6676 }
6677 
6678 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6679                           ParsedAttr::Kind Kind) {
6680   // Check decl attributes on the DeclSpec.
6681   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6682     return true;
6683 
6684   // Walk the declarator structure, checking decl attributes that were in a type
6685   // position to the decl itself.
6686   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6687     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6688       return true;
6689   }
6690 
6691   // Finally, check attributes on the decl itself.
6692   return PD.getAttributes().hasAttribute(Kind);
6693 }
6694 
6695 /// Adjust the \c DeclContext for a function or variable that might be a
6696 /// function-local external declaration.
6697 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6698   if (!DC->isFunctionOrMethod())
6699     return false;
6700 
6701   // If this is a local extern function or variable declared within a function
6702   // template, don't add it into the enclosing namespace scope until it is
6703   // instantiated; it might have a dependent type right now.
6704   if (DC->isDependentContext())
6705     return true;
6706 
6707   // C++11 [basic.link]p7:
6708   //   When a block scope declaration of an entity with linkage is not found to
6709   //   refer to some other declaration, then that entity is a member of the
6710   //   innermost enclosing namespace.
6711   //
6712   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6713   // semantically-enclosing namespace, not a lexically-enclosing one.
6714   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6715     DC = DC->getParent();
6716   return true;
6717 }
6718 
6719 /// Returns true if given declaration has external C language linkage.
6720 static bool isDeclExternC(const Decl *D) {
6721   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6722     return FD->isExternC();
6723   if (const auto *VD = dyn_cast<VarDecl>(D))
6724     return VD->isExternC();
6725 
6726   llvm_unreachable("Unknown type of decl!");
6727 }
6728 /// Returns true if there hasn't been any invalid type diagnosed.
6729 static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D,
6730                                 DeclContext *DC, QualType R) {
6731   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6732   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6733   // argument.
6734   if (R->isImageType() || R->isPipeType()) {
6735     Se.Diag(D.getIdentifierLoc(),
6736             diag::err_opencl_type_can_only_be_used_as_function_parameter)
6737         << R;
6738     D.setInvalidType();
6739     return false;
6740   }
6741 
6742   // OpenCL v1.2 s6.9.r:
6743   // The event type cannot be used to declare a program scope variable.
6744   // OpenCL v2.0 s6.9.q:
6745   // The clk_event_t and reserve_id_t types cannot be declared in program
6746   // scope.
6747   if (NULL == S->getParent()) {
6748     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6749       Se.Diag(D.getIdentifierLoc(),
6750               diag::err_invalid_type_for_program_scope_var)
6751           << R;
6752       D.setInvalidType();
6753       return false;
6754     }
6755   }
6756 
6757   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6758   if (!Se.getOpenCLOptions().isEnabled("__cl_clang_function_pointers")) {
6759     QualType NR = R.getCanonicalType();
6760     while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
6761            NR->isReferenceType()) {
6762       if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
6763           NR->isFunctionReferenceType()) {
6764         Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer)
6765             << NR->isReferenceType();
6766         D.setInvalidType();
6767         return false;
6768       }
6769       NR = NR->getPointeeType();
6770     }
6771   }
6772 
6773   if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6774     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6775     // half array type (unless the cl_khr_fp16 extension is enabled).
6776     if (Se.Context.getBaseElementType(R)->isHalfType()) {
6777       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6778       D.setInvalidType();
6779       return false;
6780     }
6781   }
6782 
6783   // OpenCL v1.2 s6.9.r:
6784   // The event type cannot be used with the __local, __constant and __global
6785   // address space qualifiers.
6786   if (R->isEventT()) {
6787     if (R.getAddressSpace() != LangAS::opencl_private) {
6788       Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6789       D.setInvalidType();
6790       return false;
6791     }
6792   }
6793 
6794   // C++ for OpenCL does not allow the thread_local storage qualifier.
6795   // OpenCL C does not support thread_local either, and
6796   // also reject all other thread storage class specifiers.
6797   DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6798   if (TSC != TSCS_unspecified) {
6799     bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus;
6800     Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6801             diag::err_opencl_unknown_type_specifier)
6802         << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString()
6803         << DeclSpec::getSpecifierName(TSC) << 1;
6804     D.setInvalidType();
6805     return false;
6806   }
6807 
6808   if (R->isSamplerT()) {
6809     // OpenCL v1.2 s6.9.b p4:
6810     // The sampler type cannot be used with the __local and __global address
6811     // space qualifiers.
6812     if (R.getAddressSpace() == LangAS::opencl_local ||
6813         R.getAddressSpace() == LangAS::opencl_global) {
6814       Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6815       D.setInvalidType();
6816     }
6817 
6818     // OpenCL v1.2 s6.12.14.1:
6819     // A global sampler must be declared with either the constant address
6820     // space qualifier or with the const qualifier.
6821     if (DC->isTranslationUnit() &&
6822         !(R.getAddressSpace() == LangAS::opencl_constant ||
6823           R.isConstQualified())) {
6824       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6825       D.setInvalidType();
6826     }
6827     if (D.isInvalidType())
6828       return false;
6829   }
6830   return true;
6831 }
6832 
6833 NamedDecl *Sema::ActOnVariableDeclarator(
6834     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6835     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6836     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6837   QualType R = TInfo->getType();
6838   DeclarationName Name = GetNameForDeclarator(D).getName();
6839 
6840   IdentifierInfo *II = Name.getAsIdentifierInfo();
6841 
6842   if (D.isDecompositionDeclarator()) {
6843     // Take the name of the first declarator as our name for diagnostic
6844     // purposes.
6845     auto &Decomp = D.getDecompositionDeclarator();
6846     if (!Decomp.bindings().empty()) {
6847       II = Decomp.bindings()[0].Name;
6848       Name = II;
6849     }
6850   } else if (!II) {
6851     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6852     return nullptr;
6853   }
6854 
6855 
6856   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6857   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6858 
6859   // dllimport globals without explicit storage class are treated as extern. We
6860   // have to change the storage class this early to get the right DeclContext.
6861   if (SC == SC_None && !DC->isRecord() &&
6862       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6863       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6864     SC = SC_Extern;
6865 
6866   DeclContext *OriginalDC = DC;
6867   bool IsLocalExternDecl = SC == SC_Extern &&
6868                            adjustContextForLocalExternDecl(DC);
6869 
6870   if (SCSpec == DeclSpec::SCS_mutable) {
6871     // mutable can only appear on non-static class members, so it's always
6872     // an error here
6873     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6874     D.setInvalidType();
6875     SC = SC_None;
6876   }
6877 
6878   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6879       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6880                               D.getDeclSpec().getStorageClassSpecLoc())) {
6881     // In C++11, the 'register' storage class specifier is deprecated.
6882     // Suppress the warning in system macros, it's used in macros in some
6883     // popular C system headers, such as in glibc's htonl() macro.
6884     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6885          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6886                                    : diag::warn_deprecated_register)
6887       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6888   }
6889 
6890   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6891 
6892   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6893     // C99 6.9p2: The storage-class specifiers auto and register shall not
6894     // appear in the declaration specifiers in an external declaration.
6895     // Global Register+Asm is a GNU extension we support.
6896     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6897       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6898       D.setInvalidType();
6899     }
6900   }
6901 
6902   // If this variable has a variable-modified type and an initializer, try to
6903   // fold to a constant-sized type. This is otherwise invalid.
6904   if (D.hasInitializer() && R->isVariablyModifiedType())
6905     tryToFixVariablyModifiedVarType(*this, TInfo, R, D.getIdentifierLoc(),
6906                                     /*DiagID=*/0);
6907 
6908   bool IsMemberSpecialization = false;
6909   bool IsVariableTemplateSpecialization = false;
6910   bool IsPartialSpecialization = false;
6911   bool IsVariableTemplate = false;
6912   VarDecl *NewVD = nullptr;
6913   VarTemplateDecl *NewTemplate = nullptr;
6914   TemplateParameterList *TemplateParams = nullptr;
6915   if (!getLangOpts().CPlusPlus) {
6916     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6917                             II, R, TInfo, SC);
6918 
6919     if (R->getContainedDeducedType())
6920       ParsingInitForAutoVars.insert(NewVD);
6921 
6922     if (D.isInvalidType())
6923       NewVD->setInvalidDecl();
6924 
6925     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
6926         NewVD->hasLocalStorage())
6927       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
6928                             NTCUC_AutoVar, NTCUK_Destruct);
6929   } else {
6930     bool Invalid = false;
6931 
6932     if (DC->isRecord() && !CurContext->isRecord()) {
6933       // This is an out-of-line definition of a static data member.
6934       switch (SC) {
6935       case SC_None:
6936         break;
6937       case SC_Static:
6938         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6939              diag::err_static_out_of_line)
6940           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6941         break;
6942       case SC_Auto:
6943       case SC_Register:
6944       case SC_Extern:
6945         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6946         // to names of variables declared in a block or to function parameters.
6947         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6948         // of class members
6949 
6950         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6951              diag::err_storage_class_for_static_member)
6952           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6953         break;
6954       case SC_PrivateExtern:
6955         llvm_unreachable("C storage class in c++!");
6956       }
6957     }
6958 
6959     if (SC == SC_Static && CurContext->isRecord()) {
6960       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6961         // Walk up the enclosing DeclContexts to check for any that are
6962         // incompatible with static data members.
6963         const DeclContext *FunctionOrMethod = nullptr;
6964         const CXXRecordDecl *AnonStruct = nullptr;
6965         for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
6966           if (Ctxt->isFunctionOrMethod()) {
6967             FunctionOrMethod = Ctxt;
6968             break;
6969           }
6970           const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
6971           if (ParentDecl && !ParentDecl->getDeclName()) {
6972             AnonStruct = ParentDecl;
6973             break;
6974           }
6975         }
6976         if (FunctionOrMethod) {
6977           // C++ [class.static.data]p5: A local class shall not have static data
6978           // members.
6979           Diag(D.getIdentifierLoc(),
6980                diag::err_static_data_member_not_allowed_in_local_class)
6981             << Name << RD->getDeclName() << RD->getTagKind();
6982         } else if (AnonStruct) {
6983           // C++ [class.static.data]p4: Unnamed classes and classes contained
6984           // directly or indirectly within unnamed classes shall not contain
6985           // static data members.
6986           Diag(D.getIdentifierLoc(),
6987                diag::err_static_data_member_not_allowed_in_anon_struct)
6988             << Name << AnonStruct->getTagKind();
6989           Invalid = true;
6990         } else if (RD->isUnion()) {
6991           // C++98 [class.union]p1: If a union contains a static data member,
6992           // the program is ill-formed. C++11 drops this restriction.
6993           Diag(D.getIdentifierLoc(),
6994                getLangOpts().CPlusPlus11
6995                  ? diag::warn_cxx98_compat_static_data_member_in_union
6996                  : diag::ext_static_data_member_in_union) << Name;
6997         }
6998       }
6999     }
7000 
7001     // Match up the template parameter lists with the scope specifier, then
7002     // determine whether we have a template or a template specialization.
7003     bool InvalidScope = false;
7004     TemplateParams = MatchTemplateParametersToScopeSpecifier(
7005         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7006         D.getCXXScopeSpec(),
7007         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7008             ? D.getName().TemplateId
7009             : nullptr,
7010         TemplateParamLists,
7011         /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7012     Invalid |= InvalidScope;
7013 
7014     if (TemplateParams) {
7015       if (!TemplateParams->size() &&
7016           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7017         // There is an extraneous 'template<>' for this variable. Complain
7018         // about it, but allow the declaration of the variable.
7019         Diag(TemplateParams->getTemplateLoc(),
7020              diag::err_template_variable_noparams)
7021           << II
7022           << SourceRange(TemplateParams->getTemplateLoc(),
7023                          TemplateParams->getRAngleLoc());
7024         TemplateParams = nullptr;
7025       } else {
7026         // Check that we can declare a template here.
7027         if (CheckTemplateDeclScope(S, TemplateParams))
7028           return nullptr;
7029 
7030         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7031           // This is an explicit specialization or a partial specialization.
7032           IsVariableTemplateSpecialization = true;
7033           IsPartialSpecialization = TemplateParams->size() > 0;
7034         } else { // if (TemplateParams->size() > 0)
7035           // This is a template declaration.
7036           IsVariableTemplate = true;
7037 
7038           // Only C++1y supports variable templates (N3651).
7039           Diag(D.getIdentifierLoc(),
7040                getLangOpts().CPlusPlus14
7041                    ? diag::warn_cxx11_compat_variable_template
7042                    : diag::ext_variable_template);
7043         }
7044       }
7045     } else {
7046       // Check that we can declare a member specialization here.
7047       if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7048           CheckTemplateDeclScope(S, TemplateParamLists.back()))
7049         return nullptr;
7050       assert((Invalid ||
7051               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7052              "should have a 'template<>' for this decl");
7053     }
7054 
7055     if (IsVariableTemplateSpecialization) {
7056       SourceLocation TemplateKWLoc =
7057           TemplateParamLists.size() > 0
7058               ? TemplateParamLists[0]->getTemplateLoc()
7059               : SourceLocation();
7060       DeclResult Res = ActOnVarTemplateSpecialization(
7061           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7062           IsPartialSpecialization);
7063       if (Res.isInvalid())
7064         return nullptr;
7065       NewVD = cast<VarDecl>(Res.get());
7066       AddToScope = false;
7067     } else if (D.isDecompositionDeclarator()) {
7068       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7069                                         D.getIdentifierLoc(), R, TInfo, SC,
7070                                         Bindings);
7071     } else
7072       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7073                               D.getIdentifierLoc(), II, R, TInfo, SC);
7074 
7075     // If this is supposed to be a variable template, create it as such.
7076     if (IsVariableTemplate) {
7077       NewTemplate =
7078           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7079                                   TemplateParams, NewVD);
7080       NewVD->setDescribedVarTemplate(NewTemplate);
7081     }
7082 
7083     // If this decl has an auto type in need of deduction, make a note of the
7084     // Decl so we can diagnose uses of it in its own initializer.
7085     if (R->getContainedDeducedType())
7086       ParsingInitForAutoVars.insert(NewVD);
7087 
7088     if (D.isInvalidType() || Invalid) {
7089       NewVD->setInvalidDecl();
7090       if (NewTemplate)
7091         NewTemplate->setInvalidDecl();
7092     }
7093 
7094     SetNestedNameSpecifier(*this, NewVD, D);
7095 
7096     // If we have any template parameter lists that don't directly belong to
7097     // the variable (matching the scope specifier), store them.
7098     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7099     if (TemplateParamLists.size() > VDTemplateParamLists)
7100       NewVD->setTemplateParameterListsInfo(
7101           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7102   }
7103 
7104   if (D.getDeclSpec().isInlineSpecified()) {
7105     if (!getLangOpts().CPlusPlus) {
7106       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7107           << 0;
7108     } else if (CurContext->isFunctionOrMethod()) {
7109       // 'inline' is not allowed on block scope variable declaration.
7110       Diag(D.getDeclSpec().getInlineSpecLoc(),
7111            diag::err_inline_declaration_block_scope) << Name
7112         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7113     } else {
7114       Diag(D.getDeclSpec().getInlineSpecLoc(),
7115            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7116                                      : diag::ext_inline_variable);
7117       NewVD->setInlineSpecified();
7118     }
7119   }
7120 
7121   // Set the lexical context. If the declarator has a C++ scope specifier, the
7122   // lexical context will be different from the semantic context.
7123   NewVD->setLexicalDeclContext(CurContext);
7124   if (NewTemplate)
7125     NewTemplate->setLexicalDeclContext(CurContext);
7126 
7127   if (IsLocalExternDecl) {
7128     if (D.isDecompositionDeclarator())
7129       for (auto *B : Bindings)
7130         B->setLocalExternDecl();
7131     else
7132       NewVD->setLocalExternDecl();
7133   }
7134 
7135   bool EmitTLSUnsupportedError = false;
7136   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7137     // C++11 [dcl.stc]p4:
7138     //   When thread_local is applied to a variable of block scope the
7139     //   storage-class-specifier static is implied if it does not appear
7140     //   explicitly.
7141     // Core issue: 'static' is not implied if the variable is declared
7142     //   'extern'.
7143     if (NewVD->hasLocalStorage() &&
7144         (SCSpec != DeclSpec::SCS_unspecified ||
7145          TSCS != DeclSpec::TSCS_thread_local ||
7146          !DC->isFunctionOrMethod()))
7147       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7148            diag::err_thread_non_global)
7149         << DeclSpec::getSpecifierName(TSCS);
7150     else if (!Context.getTargetInfo().isTLSSupported()) {
7151       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7152           getLangOpts().SYCLIsDevice) {
7153         // Postpone error emission until we've collected attributes required to
7154         // figure out whether it's a host or device variable and whether the
7155         // error should be ignored.
7156         EmitTLSUnsupportedError = true;
7157         // We still need to mark the variable as TLS so it shows up in AST with
7158         // proper storage class for other tools to use even if we're not going
7159         // to emit any code for it.
7160         NewVD->setTSCSpec(TSCS);
7161       } else
7162         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7163              diag::err_thread_unsupported);
7164     } else
7165       NewVD->setTSCSpec(TSCS);
7166   }
7167 
7168   switch (D.getDeclSpec().getConstexprSpecifier()) {
7169   case ConstexprSpecKind::Unspecified:
7170     break;
7171 
7172   case ConstexprSpecKind::Consteval:
7173     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7174          diag::err_constexpr_wrong_decl_kind)
7175         << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7176     LLVM_FALLTHROUGH;
7177 
7178   case ConstexprSpecKind::Constexpr:
7179     NewVD->setConstexpr(true);
7180     MaybeAddCUDAConstantAttr(NewVD);
7181     // C++1z [dcl.spec.constexpr]p1:
7182     //   A static data member declared with the constexpr specifier is
7183     //   implicitly an inline variable.
7184     if (NewVD->isStaticDataMember() &&
7185         (getLangOpts().CPlusPlus17 ||
7186          Context.getTargetInfo().getCXXABI().isMicrosoft()))
7187       NewVD->setImplicitlyInline();
7188     break;
7189 
7190   case ConstexprSpecKind::Constinit:
7191     if (!NewVD->hasGlobalStorage())
7192       Diag(D.getDeclSpec().getConstexprSpecLoc(),
7193            diag::err_constinit_local_variable);
7194     else
7195       NewVD->addAttr(ConstInitAttr::Create(
7196           Context, D.getDeclSpec().getConstexprSpecLoc(),
7197           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7198     break;
7199   }
7200 
7201   // C99 6.7.4p3
7202   //   An inline definition of a function with external linkage shall
7203   //   not contain a definition of a modifiable object with static or
7204   //   thread storage duration...
7205   // We only apply this when the function is required to be defined
7206   // elsewhere, i.e. when the function is not 'extern inline'.  Note
7207   // that a local variable with thread storage duration still has to
7208   // be marked 'static'.  Also note that it's possible to get these
7209   // semantics in C++ using __attribute__((gnu_inline)).
7210   if (SC == SC_Static && S->getFnParent() != nullptr &&
7211       !NewVD->getType().isConstQualified()) {
7212     FunctionDecl *CurFD = getCurFunctionDecl();
7213     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7214       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7215            diag::warn_static_local_in_extern_inline);
7216       MaybeSuggestAddingStaticToDecl(CurFD);
7217     }
7218   }
7219 
7220   if (D.getDeclSpec().isModulePrivateSpecified()) {
7221     if (IsVariableTemplateSpecialization)
7222       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7223           << (IsPartialSpecialization ? 1 : 0)
7224           << FixItHint::CreateRemoval(
7225                  D.getDeclSpec().getModulePrivateSpecLoc());
7226     else if (IsMemberSpecialization)
7227       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7228         << 2
7229         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7230     else if (NewVD->hasLocalStorage())
7231       Diag(NewVD->getLocation(), diag::err_module_private_local)
7232           << 0 << NewVD
7233           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7234           << FixItHint::CreateRemoval(
7235                  D.getDeclSpec().getModulePrivateSpecLoc());
7236     else {
7237       NewVD->setModulePrivate();
7238       if (NewTemplate)
7239         NewTemplate->setModulePrivate();
7240       for (auto *B : Bindings)
7241         B->setModulePrivate();
7242     }
7243   }
7244 
7245   if (getLangOpts().OpenCL) {
7246 
7247     deduceOpenCLAddressSpace(NewVD);
7248 
7249     diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType());
7250   }
7251 
7252   // Handle attributes prior to checking for duplicates in MergeVarDecl
7253   ProcessDeclAttributes(S, NewVD, D);
7254 
7255   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7256       getLangOpts().SYCLIsDevice) {
7257     if (EmitTLSUnsupportedError &&
7258         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7259          (getLangOpts().OpenMPIsDevice &&
7260           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7261       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7262            diag::err_thread_unsupported);
7263 
7264     if (EmitTLSUnsupportedError &&
7265         (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7266       targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7267     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7268     // storage [duration]."
7269     if (SC == SC_None && S->getFnParent() != nullptr &&
7270         (NewVD->hasAttr<CUDASharedAttr>() ||
7271          NewVD->hasAttr<CUDAConstantAttr>())) {
7272       NewVD->setStorageClass(SC_Static);
7273     }
7274   }
7275 
7276   // Ensure that dllimport globals without explicit storage class are treated as
7277   // extern. The storage class is set above using parsed attributes. Now we can
7278   // check the VarDecl itself.
7279   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7280          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7281          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7282 
7283   // In auto-retain/release, infer strong retension for variables of
7284   // retainable type.
7285   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7286     NewVD->setInvalidDecl();
7287 
7288   // Handle GNU asm-label extension (encoded as an attribute).
7289   if (Expr *E = (Expr*)D.getAsmLabel()) {
7290     // The parser guarantees this is a string.
7291     StringLiteral *SE = cast<StringLiteral>(E);
7292     StringRef Label = SE->getString();
7293     if (S->getFnParent() != nullptr) {
7294       switch (SC) {
7295       case SC_None:
7296       case SC_Auto:
7297         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7298         break;
7299       case SC_Register:
7300         // Local Named register
7301         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7302             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7303           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7304         break;
7305       case SC_Static:
7306       case SC_Extern:
7307       case SC_PrivateExtern:
7308         break;
7309       }
7310     } else if (SC == SC_Register) {
7311       // Global Named register
7312       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7313         const auto &TI = Context.getTargetInfo();
7314         bool HasSizeMismatch;
7315 
7316         if (!TI.isValidGCCRegisterName(Label))
7317           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7318         else if (!TI.validateGlobalRegisterVariable(Label,
7319                                                     Context.getTypeSize(R),
7320                                                     HasSizeMismatch))
7321           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7322         else if (HasSizeMismatch)
7323           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7324       }
7325 
7326       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7327         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7328         NewVD->setInvalidDecl(true);
7329       }
7330     }
7331 
7332     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7333                                         /*IsLiteralLabel=*/true,
7334                                         SE->getStrTokenLoc(0)));
7335   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7336     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7337       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7338     if (I != ExtnameUndeclaredIdentifiers.end()) {
7339       if (isDeclExternC(NewVD)) {
7340         NewVD->addAttr(I->second);
7341         ExtnameUndeclaredIdentifiers.erase(I);
7342       } else
7343         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7344             << /*Variable*/1 << NewVD;
7345     }
7346   }
7347 
7348   // Find the shadowed declaration before filtering for scope.
7349   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7350                                 ? getShadowedDeclaration(NewVD, Previous)
7351                                 : nullptr;
7352 
7353   // Don't consider existing declarations that are in a different
7354   // scope and are out-of-semantic-context declarations (if the new
7355   // declaration has linkage).
7356   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7357                        D.getCXXScopeSpec().isNotEmpty() ||
7358                        IsMemberSpecialization ||
7359                        IsVariableTemplateSpecialization);
7360 
7361   // Check whether the previous declaration is in the same block scope. This
7362   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7363   if (getLangOpts().CPlusPlus &&
7364       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7365     NewVD->setPreviousDeclInSameBlockScope(
7366         Previous.isSingleResult() && !Previous.isShadowed() &&
7367         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7368 
7369   if (!getLangOpts().CPlusPlus) {
7370     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7371   } else {
7372     // If this is an explicit specialization of a static data member, check it.
7373     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7374         CheckMemberSpecialization(NewVD, Previous))
7375       NewVD->setInvalidDecl();
7376 
7377     // Merge the decl with the existing one if appropriate.
7378     if (!Previous.empty()) {
7379       if (Previous.isSingleResult() &&
7380           isa<FieldDecl>(Previous.getFoundDecl()) &&
7381           D.getCXXScopeSpec().isSet()) {
7382         // The user tried to define a non-static data member
7383         // out-of-line (C++ [dcl.meaning]p1).
7384         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7385           << D.getCXXScopeSpec().getRange();
7386         Previous.clear();
7387         NewVD->setInvalidDecl();
7388       }
7389     } else if (D.getCXXScopeSpec().isSet()) {
7390       // No previous declaration in the qualifying scope.
7391       Diag(D.getIdentifierLoc(), diag::err_no_member)
7392         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7393         << D.getCXXScopeSpec().getRange();
7394       NewVD->setInvalidDecl();
7395     }
7396 
7397     if (!IsVariableTemplateSpecialization)
7398       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7399 
7400     if (NewTemplate) {
7401       VarTemplateDecl *PrevVarTemplate =
7402           NewVD->getPreviousDecl()
7403               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7404               : nullptr;
7405 
7406       // Check the template parameter list of this declaration, possibly
7407       // merging in the template parameter list from the previous variable
7408       // template declaration.
7409       if (CheckTemplateParameterList(
7410               TemplateParams,
7411               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7412                               : nullptr,
7413               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7414                DC->isDependentContext())
7415                   ? TPC_ClassTemplateMember
7416                   : TPC_VarTemplate))
7417         NewVD->setInvalidDecl();
7418 
7419       // If we are providing an explicit specialization of a static variable
7420       // template, make a note of that.
7421       if (PrevVarTemplate &&
7422           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7423         PrevVarTemplate->setMemberSpecialization();
7424     }
7425   }
7426 
7427   // Diagnose shadowed variables iff this isn't a redeclaration.
7428   if (ShadowedDecl && !D.isRedeclaration())
7429     CheckShadow(NewVD, ShadowedDecl, Previous);
7430 
7431   ProcessPragmaWeak(S, NewVD);
7432 
7433   // If this is the first declaration of an extern C variable, update
7434   // the map of such variables.
7435   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7436       isIncompleteDeclExternC(*this, NewVD))
7437     RegisterLocallyScopedExternCDecl(NewVD, S);
7438 
7439   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7440     MangleNumberingContext *MCtx;
7441     Decl *ManglingContextDecl;
7442     std::tie(MCtx, ManglingContextDecl) =
7443         getCurrentMangleNumberContext(NewVD->getDeclContext());
7444     if (MCtx) {
7445       Context.setManglingNumber(
7446           NewVD, MCtx->getManglingNumber(
7447                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7448       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7449     }
7450   }
7451 
7452   // Special handling of variable named 'main'.
7453   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7454       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7455       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7456 
7457     // C++ [basic.start.main]p3
7458     // A program that declares a variable main at global scope is ill-formed.
7459     if (getLangOpts().CPlusPlus)
7460       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7461 
7462     // In C, and external-linkage variable named main results in undefined
7463     // behavior.
7464     else if (NewVD->hasExternalFormalLinkage())
7465       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7466   }
7467 
7468   if (D.isRedeclaration() && !Previous.empty()) {
7469     NamedDecl *Prev = Previous.getRepresentativeDecl();
7470     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7471                                    D.isFunctionDefinition());
7472   }
7473 
7474   if (NewTemplate) {
7475     if (NewVD->isInvalidDecl())
7476       NewTemplate->setInvalidDecl();
7477     ActOnDocumentableDecl(NewTemplate);
7478     return NewTemplate;
7479   }
7480 
7481   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7482     CompleteMemberSpecialization(NewVD, Previous);
7483 
7484   return NewVD;
7485 }
7486 
7487 /// Enum describing the %select options in diag::warn_decl_shadow.
7488 enum ShadowedDeclKind {
7489   SDK_Local,
7490   SDK_Global,
7491   SDK_StaticMember,
7492   SDK_Field,
7493   SDK_Typedef,
7494   SDK_Using
7495 };
7496 
7497 /// Determine what kind of declaration we're shadowing.
7498 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7499                                                 const DeclContext *OldDC) {
7500   if (isa<TypeAliasDecl>(ShadowedDecl))
7501     return SDK_Using;
7502   else if (isa<TypedefDecl>(ShadowedDecl))
7503     return SDK_Typedef;
7504   else if (isa<RecordDecl>(OldDC))
7505     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7506 
7507   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7508 }
7509 
7510 /// Return the location of the capture if the given lambda captures the given
7511 /// variable \p VD, or an invalid source location otherwise.
7512 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7513                                          const VarDecl *VD) {
7514   for (const Capture &Capture : LSI->Captures) {
7515     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7516       return Capture.getLocation();
7517   }
7518   return SourceLocation();
7519 }
7520 
7521 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7522                                      const LookupResult &R) {
7523   // Only diagnose if we're shadowing an unambiguous field or variable.
7524   if (R.getResultKind() != LookupResult::Found)
7525     return false;
7526 
7527   // Return false if warning is ignored.
7528   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7529 }
7530 
7531 /// Return the declaration shadowed by the given variable \p D, or null
7532 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7533 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7534                                         const LookupResult &R) {
7535   if (!shouldWarnIfShadowedDecl(Diags, R))
7536     return nullptr;
7537 
7538   // Don't diagnose declarations at file scope.
7539   if (D->hasGlobalStorage())
7540     return nullptr;
7541 
7542   NamedDecl *ShadowedDecl = R.getFoundDecl();
7543   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
7544              ? ShadowedDecl
7545              : nullptr;
7546 }
7547 
7548 /// Return the declaration shadowed by the given typedef \p D, or null
7549 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7550 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7551                                         const LookupResult &R) {
7552   // Don't warn if typedef declaration is part of a class
7553   if (D->getDeclContext()->isRecord())
7554     return nullptr;
7555 
7556   if (!shouldWarnIfShadowedDecl(Diags, R))
7557     return nullptr;
7558 
7559   NamedDecl *ShadowedDecl = R.getFoundDecl();
7560   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7561 }
7562 
7563 /// Diagnose variable or built-in function shadowing.  Implements
7564 /// -Wshadow.
7565 ///
7566 /// This method is called whenever a VarDecl is added to a "useful"
7567 /// scope.
7568 ///
7569 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7570 /// \param R the lookup of the name
7571 ///
7572 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7573                        const LookupResult &R) {
7574   DeclContext *NewDC = D->getDeclContext();
7575 
7576   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7577     // Fields are not shadowed by variables in C++ static methods.
7578     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7579       if (MD->isStatic())
7580         return;
7581 
7582     // Fields shadowed by constructor parameters are a special case. Usually
7583     // the constructor initializes the field with the parameter.
7584     if (isa<CXXConstructorDecl>(NewDC))
7585       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7586         // Remember that this was shadowed so we can either warn about its
7587         // modification or its existence depending on warning settings.
7588         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7589         return;
7590       }
7591   }
7592 
7593   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7594     if (shadowedVar->isExternC()) {
7595       // For shadowing external vars, make sure that we point to the global
7596       // declaration, not a locally scoped extern declaration.
7597       for (auto I : shadowedVar->redecls())
7598         if (I->isFileVarDecl()) {
7599           ShadowedDecl = I;
7600           break;
7601         }
7602     }
7603 
7604   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7605 
7606   unsigned WarningDiag = diag::warn_decl_shadow;
7607   SourceLocation CaptureLoc;
7608   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7609       isa<CXXMethodDecl>(NewDC)) {
7610     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7611       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7612         if (RD->getLambdaCaptureDefault() == LCD_None) {
7613           // Try to avoid warnings for lambdas with an explicit capture list.
7614           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7615           // Warn only when the lambda captures the shadowed decl explicitly.
7616           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7617           if (CaptureLoc.isInvalid())
7618             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7619         } else {
7620           // Remember that this was shadowed so we can avoid the warning if the
7621           // shadowed decl isn't captured and the warning settings allow it.
7622           cast<LambdaScopeInfo>(getCurFunction())
7623               ->ShadowingDecls.push_back(
7624                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7625           return;
7626         }
7627       }
7628 
7629       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7630         // A variable can't shadow a local variable in an enclosing scope, if
7631         // they are separated by a non-capturing declaration context.
7632         for (DeclContext *ParentDC = NewDC;
7633              ParentDC && !ParentDC->Equals(OldDC);
7634              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7635           // Only block literals, captured statements, and lambda expressions
7636           // can capture; other scopes don't.
7637           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7638               !isLambdaCallOperator(ParentDC)) {
7639             return;
7640           }
7641         }
7642       }
7643     }
7644   }
7645 
7646   // Only warn about certain kinds of shadowing for class members.
7647   if (NewDC && NewDC->isRecord()) {
7648     // In particular, don't warn about shadowing non-class members.
7649     if (!OldDC->isRecord())
7650       return;
7651 
7652     // TODO: should we warn about static data members shadowing
7653     // static data members from base classes?
7654 
7655     // TODO: don't diagnose for inaccessible shadowed members.
7656     // This is hard to do perfectly because we might friend the
7657     // shadowing context, but that's just a false negative.
7658   }
7659 
7660 
7661   DeclarationName Name = R.getLookupName();
7662 
7663   // Emit warning and note.
7664   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7665     return;
7666   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7667   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7668   if (!CaptureLoc.isInvalid())
7669     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7670         << Name << /*explicitly*/ 1;
7671   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7672 }
7673 
7674 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7675 /// when these variables are captured by the lambda.
7676 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7677   for (const auto &Shadow : LSI->ShadowingDecls) {
7678     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7679     // Try to avoid the warning when the shadowed decl isn't captured.
7680     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7681     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7682     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7683                                        ? diag::warn_decl_shadow_uncaptured_local
7684                                        : diag::warn_decl_shadow)
7685         << Shadow.VD->getDeclName()
7686         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7687     if (!CaptureLoc.isInvalid())
7688       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7689           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7690     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7691   }
7692 }
7693 
7694 /// Check -Wshadow without the advantage of a previous lookup.
7695 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7696   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7697     return;
7698 
7699   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7700                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7701   LookupName(R, S);
7702   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7703     CheckShadow(D, ShadowedDecl, R);
7704 }
7705 
7706 /// Check if 'E', which is an expression that is about to be modified, refers
7707 /// to a constructor parameter that shadows a field.
7708 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7709   // Quickly ignore expressions that can't be shadowing ctor parameters.
7710   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7711     return;
7712   E = E->IgnoreParenImpCasts();
7713   auto *DRE = dyn_cast<DeclRefExpr>(E);
7714   if (!DRE)
7715     return;
7716   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7717   auto I = ShadowingDecls.find(D);
7718   if (I == ShadowingDecls.end())
7719     return;
7720   const NamedDecl *ShadowedDecl = I->second;
7721   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7722   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7723   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7724   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7725 
7726   // Avoid issuing multiple warnings about the same decl.
7727   ShadowingDecls.erase(I);
7728 }
7729 
7730 /// Check for conflict between this global or extern "C" declaration and
7731 /// previous global or extern "C" declarations. This is only used in C++.
7732 template<typename T>
7733 static bool checkGlobalOrExternCConflict(
7734     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7735   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7736   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7737 
7738   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7739     // The common case: this global doesn't conflict with any extern "C"
7740     // declaration.
7741     return false;
7742   }
7743 
7744   if (Prev) {
7745     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7746       // Both the old and new declarations have C language linkage. This is a
7747       // redeclaration.
7748       Previous.clear();
7749       Previous.addDecl(Prev);
7750       return true;
7751     }
7752 
7753     // This is a global, non-extern "C" declaration, and there is a previous
7754     // non-global extern "C" declaration. Diagnose if this is a variable
7755     // declaration.
7756     if (!isa<VarDecl>(ND))
7757       return false;
7758   } else {
7759     // The declaration is extern "C". Check for any declaration in the
7760     // translation unit which might conflict.
7761     if (IsGlobal) {
7762       // We have already performed the lookup into the translation unit.
7763       IsGlobal = false;
7764       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7765            I != E; ++I) {
7766         if (isa<VarDecl>(*I)) {
7767           Prev = *I;
7768           break;
7769         }
7770       }
7771     } else {
7772       DeclContext::lookup_result R =
7773           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7774       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7775            I != E; ++I) {
7776         if (isa<VarDecl>(*I)) {
7777           Prev = *I;
7778           break;
7779         }
7780         // FIXME: If we have any other entity with this name in global scope,
7781         // the declaration is ill-formed, but that is a defect: it breaks the
7782         // 'stat' hack, for instance. Only variables can have mangled name
7783         // clashes with extern "C" declarations, so only they deserve a
7784         // diagnostic.
7785       }
7786     }
7787 
7788     if (!Prev)
7789       return false;
7790   }
7791 
7792   // Use the first declaration's location to ensure we point at something which
7793   // is lexically inside an extern "C" linkage-spec.
7794   assert(Prev && "should have found a previous declaration to diagnose");
7795   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7796     Prev = FD->getFirstDecl();
7797   else
7798     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7799 
7800   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7801     << IsGlobal << ND;
7802   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7803     << IsGlobal;
7804   return false;
7805 }
7806 
7807 /// Apply special rules for handling extern "C" declarations. Returns \c true
7808 /// if we have found that this is a redeclaration of some prior entity.
7809 ///
7810 /// Per C++ [dcl.link]p6:
7811 ///   Two declarations [for a function or variable] with C language linkage
7812 ///   with the same name that appear in different scopes refer to the same
7813 ///   [entity]. An entity with C language linkage shall not be declared with
7814 ///   the same name as an entity in global scope.
7815 template<typename T>
7816 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7817                                                   LookupResult &Previous) {
7818   if (!S.getLangOpts().CPlusPlus) {
7819     // In C, when declaring a global variable, look for a corresponding 'extern'
7820     // variable declared in function scope. We don't need this in C++, because
7821     // we find local extern decls in the surrounding file-scope DeclContext.
7822     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7823       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7824         Previous.clear();
7825         Previous.addDecl(Prev);
7826         return true;
7827       }
7828     }
7829     return false;
7830   }
7831 
7832   // A declaration in the translation unit can conflict with an extern "C"
7833   // declaration.
7834   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7835     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7836 
7837   // An extern "C" declaration can conflict with a declaration in the
7838   // translation unit or can be a redeclaration of an extern "C" declaration
7839   // in another scope.
7840   if (isIncompleteDeclExternC(S,ND))
7841     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7842 
7843   // Neither global nor extern "C": nothing to do.
7844   return false;
7845 }
7846 
7847 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7848   // If the decl is already known invalid, don't check it.
7849   if (NewVD->isInvalidDecl())
7850     return;
7851 
7852   QualType T = NewVD->getType();
7853 
7854   // Defer checking an 'auto' type until its initializer is attached.
7855   if (T->isUndeducedType())
7856     return;
7857 
7858   if (NewVD->hasAttrs())
7859     CheckAlignasUnderalignment(NewVD);
7860 
7861   if (T->isObjCObjectType()) {
7862     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7863       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7864     T = Context.getObjCObjectPointerType(T);
7865     NewVD->setType(T);
7866   }
7867 
7868   // Emit an error if an address space was applied to decl with local storage.
7869   // This includes arrays of objects with address space qualifiers, but not
7870   // automatic variables that point to other address spaces.
7871   // ISO/IEC TR 18037 S5.1.2
7872   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7873       T.getAddressSpace() != LangAS::Default) {
7874     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7875     NewVD->setInvalidDecl();
7876     return;
7877   }
7878 
7879   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7880   // scope.
7881   if (getLangOpts().OpenCLVersion == 120 &&
7882       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7883       NewVD->isStaticLocal()) {
7884     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7885     NewVD->setInvalidDecl();
7886     return;
7887   }
7888 
7889   if (getLangOpts().OpenCL) {
7890     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7891     if (NewVD->hasAttr<BlocksAttr>()) {
7892       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7893       return;
7894     }
7895 
7896     if (T->isBlockPointerType()) {
7897       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7898       // can't use 'extern' storage class.
7899       if (!T.isConstQualified()) {
7900         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7901             << 0 /*const*/;
7902         NewVD->setInvalidDecl();
7903         return;
7904       }
7905       if (NewVD->hasExternalStorage()) {
7906         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7907         NewVD->setInvalidDecl();
7908         return;
7909       }
7910     }
7911     // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7912     // __constant address space.
7913     // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7914     // variables inside a function can also be declared in the global
7915     // address space.
7916     // C++ for OpenCL inherits rule from OpenCL C v2.0.
7917     // FIXME: Adding local AS in C++ for OpenCL might make sense.
7918     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7919         NewVD->hasExternalStorage()) {
7920       if (!T->isSamplerT() &&
7921           !T->isDependentType() &&
7922           !(T.getAddressSpace() == LangAS::opencl_constant ||
7923             (T.getAddressSpace() == LangAS::opencl_global &&
7924              (getLangOpts().OpenCLVersion == 200 ||
7925               getLangOpts().OpenCLCPlusPlus)))) {
7926         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7927         if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7928           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7929               << Scope << "global or constant";
7930         else
7931           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7932               << Scope << "constant";
7933         NewVD->setInvalidDecl();
7934         return;
7935       }
7936     } else {
7937       if (T.getAddressSpace() == LangAS::opencl_global) {
7938         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7939             << 1 /*is any function*/ << "global";
7940         NewVD->setInvalidDecl();
7941         return;
7942       }
7943       if (T.getAddressSpace() == LangAS::opencl_constant ||
7944           T.getAddressSpace() == LangAS::opencl_local) {
7945         FunctionDecl *FD = getCurFunctionDecl();
7946         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7947         // in functions.
7948         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7949           if (T.getAddressSpace() == LangAS::opencl_constant)
7950             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7951                 << 0 /*non-kernel only*/ << "constant";
7952           else
7953             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7954                 << 0 /*non-kernel only*/ << "local";
7955           NewVD->setInvalidDecl();
7956           return;
7957         }
7958         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7959         // in the outermost scope of a kernel function.
7960         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7961           if (!getCurScope()->isFunctionScope()) {
7962             if (T.getAddressSpace() == LangAS::opencl_constant)
7963               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7964                   << "constant";
7965             else
7966               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7967                   << "local";
7968             NewVD->setInvalidDecl();
7969             return;
7970           }
7971         }
7972       } else if (T.getAddressSpace() != LangAS::opencl_private &&
7973                  // If we are parsing a template we didn't deduce an addr
7974                  // space yet.
7975                  T.getAddressSpace() != LangAS::Default) {
7976         // Do not allow other address spaces on automatic variable.
7977         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7978         NewVD->setInvalidDecl();
7979         return;
7980       }
7981     }
7982   }
7983 
7984   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7985       && !NewVD->hasAttr<BlocksAttr>()) {
7986     if (getLangOpts().getGC() != LangOptions::NonGC)
7987       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7988     else {
7989       assert(!getLangOpts().ObjCAutoRefCount);
7990       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7991     }
7992   }
7993 
7994   bool isVM = T->isVariablyModifiedType();
7995   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7996       NewVD->hasAttr<BlocksAttr>())
7997     setFunctionHasBranchProtectedScope();
7998 
7999   if ((isVM && NewVD->hasLinkage()) ||
8000       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8001     bool SizeIsNegative;
8002     llvm::APSInt Oversized;
8003     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8004         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8005     QualType FixedT;
8006     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
8007       FixedT = FixedTInfo->getType();
8008     else if (FixedTInfo) {
8009       // Type and type-as-written are canonically different. We need to fix up
8010       // both types separately.
8011       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8012                                                    Oversized);
8013     }
8014     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8015       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8016       // FIXME: This won't give the correct result for
8017       // int a[10][n];
8018       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8019 
8020       if (NewVD->isFileVarDecl())
8021         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8022         << SizeRange;
8023       else if (NewVD->isStaticLocal())
8024         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8025         << SizeRange;
8026       else
8027         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8028         << SizeRange;
8029       NewVD->setInvalidDecl();
8030       return;
8031     }
8032 
8033     if (!FixedTInfo) {
8034       if (NewVD->isFileVarDecl())
8035         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8036       else
8037         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8038       NewVD->setInvalidDecl();
8039       return;
8040     }
8041 
8042     Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8043     NewVD->setType(FixedT);
8044     NewVD->setTypeSourceInfo(FixedTInfo);
8045   }
8046 
8047   if (T->isVoidType()) {
8048     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8049     //                    of objects and functions.
8050     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8051       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8052         << T;
8053       NewVD->setInvalidDecl();
8054       return;
8055     }
8056   }
8057 
8058   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8059     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8060     NewVD->setInvalidDecl();
8061     return;
8062   }
8063 
8064   if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8065     Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8066     NewVD->setInvalidDecl();
8067     return;
8068   }
8069 
8070   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8071     Diag(NewVD->getLocation(), diag::err_block_on_vm);
8072     NewVD->setInvalidDecl();
8073     return;
8074   }
8075 
8076   if (NewVD->isConstexpr() && !T->isDependentType() &&
8077       RequireLiteralType(NewVD->getLocation(), T,
8078                          diag::err_constexpr_var_non_literal)) {
8079     NewVD->setInvalidDecl();
8080     return;
8081   }
8082 
8083   // PPC MMA non-pointer types are not allowed as non-local variable types.
8084   if (Context.getTargetInfo().getTriple().isPPC64() &&
8085       !NewVD->isLocalVarDecl() &&
8086       CheckPPCMMAType(T, NewVD->getLocation())) {
8087     NewVD->setInvalidDecl();
8088     return;
8089   }
8090 }
8091 
8092 /// Perform semantic checking on a newly-created variable
8093 /// declaration.
8094 ///
8095 /// This routine performs all of the type-checking required for a
8096 /// variable declaration once it has been built. It is used both to
8097 /// check variables after they have been parsed and their declarators
8098 /// have been translated into a declaration, and to check variables
8099 /// that have been instantiated from a template.
8100 ///
8101 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8102 ///
8103 /// Returns true if the variable declaration is a redeclaration.
8104 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8105   CheckVariableDeclarationType(NewVD);
8106 
8107   // If the decl is already known invalid, don't check it.
8108   if (NewVD->isInvalidDecl())
8109     return false;
8110 
8111   // If we did not find anything by this name, look for a non-visible
8112   // extern "C" declaration with the same name.
8113   if (Previous.empty() &&
8114       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8115     Previous.setShadowed();
8116 
8117   if (!Previous.empty()) {
8118     MergeVarDecl(NewVD, Previous);
8119     return true;
8120   }
8121   return false;
8122 }
8123 
8124 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8125 /// and if so, check that it's a valid override and remember it.
8126 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8127   llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8128 
8129   // Look for methods in base classes that this method might override.
8130   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8131                      /*DetectVirtual=*/false);
8132   auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8133     CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8134     DeclarationName Name = MD->getDeclName();
8135 
8136     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8137       // We really want to find the base class destructor here.
8138       QualType T = Context.getTypeDeclType(BaseRecord);
8139       CanQualType CT = Context.getCanonicalType(T);
8140       Name = Context.DeclarationNames.getCXXDestructorName(CT);
8141     }
8142 
8143     for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8144       CXXMethodDecl *BaseMD =
8145           dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8146       if (!BaseMD || !BaseMD->isVirtual() ||
8147           IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8148                      /*ConsiderCudaAttrs=*/true,
8149                      // C++2a [class.virtual]p2 does not consider requires
8150                      // clauses when overriding.
8151                      /*ConsiderRequiresClauses=*/false))
8152         continue;
8153 
8154       if (Overridden.insert(BaseMD).second) {
8155         MD->addOverriddenMethod(BaseMD);
8156         CheckOverridingFunctionReturnType(MD, BaseMD);
8157         CheckOverridingFunctionAttributes(MD, BaseMD);
8158         CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8159         CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8160       }
8161 
8162       // A method can only override one function from each base class. We
8163       // don't track indirectly overridden methods from bases of bases.
8164       return true;
8165     }
8166 
8167     return false;
8168   };
8169 
8170   DC->lookupInBases(VisitBase, Paths);
8171   return !Overridden.empty();
8172 }
8173 
8174 namespace {
8175   // Struct for holding all of the extra arguments needed by
8176   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8177   struct ActOnFDArgs {
8178     Scope *S;
8179     Declarator &D;
8180     MultiTemplateParamsArg TemplateParamLists;
8181     bool AddToScope;
8182   };
8183 } // end anonymous namespace
8184 
8185 namespace {
8186 
8187 // Callback to only accept typo corrections that have a non-zero edit distance.
8188 // Also only accept corrections that have the same parent decl.
8189 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8190  public:
8191   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8192                             CXXRecordDecl *Parent)
8193       : Context(Context), OriginalFD(TypoFD),
8194         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8195 
8196   bool ValidateCandidate(const TypoCorrection &candidate) override {
8197     if (candidate.getEditDistance() == 0)
8198       return false;
8199 
8200     SmallVector<unsigned, 1> MismatchedParams;
8201     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8202                                           CDeclEnd = candidate.end();
8203          CDecl != CDeclEnd; ++CDecl) {
8204       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8205 
8206       if (FD && !FD->hasBody() &&
8207           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8208         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8209           CXXRecordDecl *Parent = MD->getParent();
8210           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8211             return true;
8212         } else if (!ExpectedParent) {
8213           return true;
8214         }
8215       }
8216     }
8217 
8218     return false;
8219   }
8220 
8221   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8222     return std::make_unique<DifferentNameValidatorCCC>(*this);
8223   }
8224 
8225  private:
8226   ASTContext &Context;
8227   FunctionDecl *OriginalFD;
8228   CXXRecordDecl *ExpectedParent;
8229 };
8230 
8231 } // end anonymous namespace
8232 
8233 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8234   TypoCorrectedFunctionDefinitions.insert(F);
8235 }
8236 
8237 /// Generate diagnostics for an invalid function redeclaration.
8238 ///
8239 /// This routine handles generating the diagnostic messages for an invalid
8240 /// function redeclaration, including finding possible similar declarations
8241 /// or performing typo correction if there are no previous declarations with
8242 /// the same name.
8243 ///
8244 /// Returns a NamedDecl iff typo correction was performed and substituting in
8245 /// the new declaration name does not cause new errors.
8246 static NamedDecl *DiagnoseInvalidRedeclaration(
8247     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8248     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8249   DeclarationName Name = NewFD->getDeclName();
8250   DeclContext *NewDC = NewFD->getDeclContext();
8251   SmallVector<unsigned, 1> MismatchedParams;
8252   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8253   TypoCorrection Correction;
8254   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8255   unsigned DiagMsg =
8256     IsLocalFriend ? diag::err_no_matching_local_friend :
8257     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8258     diag::err_member_decl_does_not_match;
8259   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8260                     IsLocalFriend ? Sema::LookupLocalFriendName
8261                                   : Sema::LookupOrdinaryName,
8262                     Sema::ForVisibleRedeclaration);
8263 
8264   NewFD->setInvalidDecl();
8265   if (IsLocalFriend)
8266     SemaRef.LookupName(Prev, S);
8267   else
8268     SemaRef.LookupQualifiedName(Prev, NewDC);
8269   assert(!Prev.isAmbiguous() &&
8270          "Cannot have an ambiguity in previous-declaration lookup");
8271   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8272   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8273                                 MD ? MD->getParent() : nullptr);
8274   if (!Prev.empty()) {
8275     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8276          Func != FuncEnd; ++Func) {
8277       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8278       if (FD &&
8279           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8280         // Add 1 to the index so that 0 can mean the mismatch didn't
8281         // involve a parameter
8282         unsigned ParamNum =
8283             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8284         NearMatches.push_back(std::make_pair(FD, ParamNum));
8285       }
8286     }
8287   // If the qualified name lookup yielded nothing, try typo correction
8288   } else if ((Correction = SemaRef.CorrectTypo(
8289                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8290                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8291                   IsLocalFriend ? nullptr : NewDC))) {
8292     // Set up everything for the call to ActOnFunctionDeclarator
8293     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8294                               ExtraArgs.D.getIdentifierLoc());
8295     Previous.clear();
8296     Previous.setLookupName(Correction.getCorrection());
8297     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8298                                     CDeclEnd = Correction.end();
8299          CDecl != CDeclEnd; ++CDecl) {
8300       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8301       if (FD && !FD->hasBody() &&
8302           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8303         Previous.addDecl(FD);
8304       }
8305     }
8306     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8307 
8308     NamedDecl *Result;
8309     // Retry building the function declaration with the new previous
8310     // declarations, and with errors suppressed.
8311     {
8312       // Trap errors.
8313       Sema::SFINAETrap Trap(SemaRef);
8314 
8315       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8316       // pieces need to verify the typo-corrected C++ declaration and hopefully
8317       // eliminate the need for the parameter pack ExtraArgs.
8318       Result = SemaRef.ActOnFunctionDeclarator(
8319           ExtraArgs.S, ExtraArgs.D,
8320           Correction.getCorrectionDecl()->getDeclContext(),
8321           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8322           ExtraArgs.AddToScope);
8323 
8324       if (Trap.hasErrorOccurred())
8325         Result = nullptr;
8326     }
8327 
8328     if (Result) {
8329       // Determine which correction we picked.
8330       Decl *Canonical = Result->getCanonicalDecl();
8331       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8332            I != E; ++I)
8333         if ((*I)->getCanonicalDecl() == Canonical)
8334           Correction.setCorrectionDecl(*I);
8335 
8336       // Let Sema know about the correction.
8337       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8338       SemaRef.diagnoseTypo(
8339           Correction,
8340           SemaRef.PDiag(IsLocalFriend
8341                           ? diag::err_no_matching_local_friend_suggest
8342                           : diag::err_member_decl_does_not_match_suggest)
8343             << Name << NewDC << IsDefinition);
8344       return Result;
8345     }
8346 
8347     // Pretend the typo correction never occurred
8348     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8349                               ExtraArgs.D.getIdentifierLoc());
8350     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8351     Previous.clear();
8352     Previous.setLookupName(Name);
8353   }
8354 
8355   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8356       << Name << NewDC << IsDefinition << NewFD->getLocation();
8357 
8358   bool NewFDisConst = false;
8359   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8360     NewFDisConst = NewMD->isConst();
8361 
8362   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8363        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8364        NearMatch != NearMatchEnd; ++NearMatch) {
8365     FunctionDecl *FD = NearMatch->first;
8366     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8367     bool FDisConst = MD && MD->isConst();
8368     bool IsMember = MD || !IsLocalFriend;
8369 
8370     // FIXME: These notes are poorly worded for the local friend case.
8371     if (unsigned Idx = NearMatch->second) {
8372       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8373       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8374       if (Loc.isInvalid()) Loc = FD->getLocation();
8375       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8376                                  : diag::note_local_decl_close_param_match)
8377         << Idx << FDParam->getType()
8378         << NewFD->getParamDecl(Idx - 1)->getType();
8379     } else if (FDisConst != NewFDisConst) {
8380       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8381           << NewFDisConst << FD->getSourceRange().getEnd();
8382     } else
8383       SemaRef.Diag(FD->getLocation(),
8384                    IsMember ? diag::note_member_def_close_match
8385                             : diag::note_local_decl_close_match);
8386   }
8387   return nullptr;
8388 }
8389 
8390 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8391   switch (D.getDeclSpec().getStorageClassSpec()) {
8392   default: llvm_unreachable("Unknown storage class!");
8393   case DeclSpec::SCS_auto:
8394   case DeclSpec::SCS_register:
8395   case DeclSpec::SCS_mutable:
8396     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8397                  diag::err_typecheck_sclass_func);
8398     D.getMutableDeclSpec().ClearStorageClassSpecs();
8399     D.setInvalidType();
8400     break;
8401   case DeclSpec::SCS_unspecified: break;
8402   case DeclSpec::SCS_extern:
8403     if (D.getDeclSpec().isExternInLinkageSpec())
8404       return SC_None;
8405     return SC_Extern;
8406   case DeclSpec::SCS_static: {
8407     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8408       // C99 6.7.1p5:
8409       //   The declaration of an identifier for a function that has
8410       //   block scope shall have no explicit storage-class specifier
8411       //   other than extern
8412       // See also (C++ [dcl.stc]p4).
8413       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8414                    diag::err_static_block_func);
8415       break;
8416     } else
8417       return SC_Static;
8418   }
8419   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8420   }
8421 
8422   // No explicit storage class has already been returned
8423   return SC_None;
8424 }
8425 
8426 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8427                                            DeclContext *DC, QualType &R,
8428                                            TypeSourceInfo *TInfo,
8429                                            StorageClass SC,
8430                                            bool &IsVirtualOkay) {
8431   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8432   DeclarationName Name = NameInfo.getName();
8433 
8434   FunctionDecl *NewFD = nullptr;
8435   bool isInline = D.getDeclSpec().isInlineSpecified();
8436 
8437   if (!SemaRef.getLangOpts().CPlusPlus) {
8438     // Determine whether the function was written with a
8439     // prototype. This true when:
8440     //   - there is a prototype in the declarator, or
8441     //   - the type R of the function is some kind of typedef or other non-
8442     //     attributed reference to a type name (which eventually refers to a
8443     //     function type).
8444     bool HasPrototype =
8445       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8446       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8447 
8448     NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8449                                  R, TInfo, SC, isInline, HasPrototype,
8450                                  ConstexprSpecKind::Unspecified,
8451                                  /*TrailingRequiresClause=*/nullptr);
8452     if (D.isInvalidType())
8453       NewFD->setInvalidDecl();
8454 
8455     return NewFD;
8456   }
8457 
8458   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8459 
8460   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8461   if (ConstexprKind == ConstexprSpecKind::Constinit) {
8462     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8463                  diag::err_constexpr_wrong_decl_kind)
8464         << static_cast<int>(ConstexprKind);
8465     ConstexprKind = ConstexprSpecKind::Unspecified;
8466     D.getMutableDeclSpec().ClearConstexprSpec();
8467   }
8468   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8469 
8470   // Check that the return type is not an abstract class type.
8471   // For record types, this is done by the AbstractClassUsageDiagnoser once
8472   // the class has been completely parsed.
8473   if (!DC->isRecord() &&
8474       SemaRef.RequireNonAbstractType(
8475           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8476           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8477     D.setInvalidType();
8478 
8479   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8480     // This is a C++ constructor declaration.
8481     assert(DC->isRecord() &&
8482            "Constructors can only be declared in a member context");
8483 
8484     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8485     return CXXConstructorDecl::Create(
8486         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8487         TInfo, ExplicitSpecifier, isInline,
8488         /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(),
8489         TrailingRequiresClause);
8490 
8491   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8492     // This is a C++ destructor declaration.
8493     if (DC->isRecord()) {
8494       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8495       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8496       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8497           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8498           isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8499           TrailingRequiresClause);
8500 
8501       // If the destructor needs an implicit exception specification, set it
8502       // now. FIXME: It'd be nice to be able to create the right type to start
8503       // with, but the type needs to reference the destructor declaration.
8504       if (SemaRef.getLangOpts().CPlusPlus11)
8505         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8506 
8507       IsVirtualOkay = true;
8508       return NewDD;
8509 
8510     } else {
8511       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8512       D.setInvalidType();
8513 
8514       // Create a FunctionDecl to satisfy the function definition parsing
8515       // code path.
8516       return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8517                                   D.getIdentifierLoc(), Name, R, TInfo, SC,
8518                                   isInline,
8519                                   /*hasPrototype=*/true, ConstexprKind,
8520                                   TrailingRequiresClause);
8521     }
8522 
8523   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8524     if (!DC->isRecord()) {
8525       SemaRef.Diag(D.getIdentifierLoc(),
8526            diag::err_conv_function_not_member);
8527       return nullptr;
8528     }
8529 
8530     SemaRef.CheckConversionDeclarator(D, R, SC);
8531     if (D.isInvalidType())
8532       return nullptr;
8533 
8534     IsVirtualOkay = true;
8535     return CXXConversionDecl::Create(
8536         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8537         TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(),
8538         TrailingRequiresClause);
8539 
8540   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8541     if (TrailingRequiresClause)
8542       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8543                    diag::err_trailing_requires_clause_on_deduction_guide)
8544           << TrailingRequiresClause->getSourceRange();
8545     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8546 
8547     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8548                                          ExplicitSpecifier, NameInfo, R, TInfo,
8549                                          D.getEndLoc());
8550   } else if (DC->isRecord()) {
8551     // If the name of the function is the same as the name of the record,
8552     // then this must be an invalid constructor that has a return type.
8553     // (The parser checks for a return type and makes the declarator a
8554     // constructor if it has no return type).
8555     if (Name.getAsIdentifierInfo() &&
8556         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8557       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8558         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8559         << SourceRange(D.getIdentifierLoc());
8560       return nullptr;
8561     }
8562 
8563     // This is a C++ method declaration.
8564     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8565         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8566         TInfo, SC, isInline, ConstexprKind, SourceLocation(),
8567         TrailingRequiresClause);
8568     IsVirtualOkay = !Ret->isStatic();
8569     return Ret;
8570   } else {
8571     bool isFriend =
8572         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8573     if (!isFriend && SemaRef.CurContext->isRecord())
8574       return nullptr;
8575 
8576     // Determine whether the function was written with a
8577     // prototype. This true when:
8578     //   - we're in C++ (where every function has a prototype),
8579     return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8580                                 R, TInfo, SC, isInline, true /*HasPrototype*/,
8581                                 ConstexprKind, TrailingRequiresClause);
8582   }
8583 }
8584 
8585 enum OpenCLParamType {
8586   ValidKernelParam,
8587   PtrPtrKernelParam,
8588   PtrKernelParam,
8589   InvalidAddrSpacePtrKernelParam,
8590   InvalidKernelParam,
8591   RecordKernelParam
8592 };
8593 
8594 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8595   // Size dependent types are just typedefs to normal integer types
8596   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8597   // integers other than by their names.
8598   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8599 
8600   // Remove typedefs one by one until we reach a typedef
8601   // for a size dependent type.
8602   QualType DesugaredTy = Ty;
8603   do {
8604     ArrayRef<StringRef> Names(SizeTypeNames);
8605     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8606     if (Names.end() != Match)
8607       return true;
8608 
8609     Ty = DesugaredTy;
8610     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8611   } while (DesugaredTy != Ty);
8612 
8613   return false;
8614 }
8615 
8616 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8617   if (PT->isPointerType()) {
8618     QualType PointeeType = PT->getPointeeType();
8619     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8620         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8621         PointeeType.getAddressSpace() == LangAS::Default)
8622       return InvalidAddrSpacePtrKernelParam;
8623 
8624     if (PointeeType->isPointerType()) {
8625       // This is a pointer to pointer parameter.
8626       // Recursively check inner type.
8627       OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
8628       if (ParamKind == InvalidAddrSpacePtrKernelParam ||
8629           ParamKind == InvalidKernelParam)
8630         return ParamKind;
8631 
8632       return PtrPtrKernelParam;
8633     }
8634     return PtrKernelParam;
8635   }
8636 
8637   // OpenCL v1.2 s6.9.k:
8638   // Arguments to kernel functions in a program cannot be declared with the
8639   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8640   // uintptr_t or a struct and/or union that contain fields declared to be one
8641   // of these built-in scalar types.
8642   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8643     return InvalidKernelParam;
8644 
8645   if (PT->isImageType())
8646     return PtrKernelParam;
8647 
8648   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8649     return InvalidKernelParam;
8650 
8651   // OpenCL extension spec v1.2 s9.5:
8652   // This extension adds support for half scalar and vector types as built-in
8653   // types that can be used for arithmetic operations, conversions etc.
8654   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8655     return InvalidKernelParam;
8656 
8657   if (PT->isRecordType())
8658     return RecordKernelParam;
8659 
8660   // Look into an array argument to check if it has a forbidden type.
8661   if (PT->isArrayType()) {
8662     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8663     // Call ourself to check an underlying type of an array. Since the
8664     // getPointeeOrArrayElementType returns an innermost type which is not an
8665     // array, this recursive call only happens once.
8666     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8667   }
8668 
8669   return ValidKernelParam;
8670 }
8671 
8672 static void checkIsValidOpenCLKernelParameter(
8673   Sema &S,
8674   Declarator &D,
8675   ParmVarDecl *Param,
8676   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8677   QualType PT = Param->getType();
8678 
8679   // Cache the valid types we encounter to avoid rechecking structs that are
8680   // used again
8681   if (ValidTypes.count(PT.getTypePtr()))
8682     return;
8683 
8684   switch (getOpenCLKernelParameterType(S, PT)) {
8685   case PtrPtrKernelParam:
8686     // OpenCL v3.0 s6.11.a:
8687     // A kernel function argument cannot be declared as a pointer to a pointer
8688     // type. [...] This restriction only applies to OpenCL C 1.2 or below.
8689     if (S.getLangOpts().OpenCLVersion < 120 &&
8690         !S.getLangOpts().OpenCLCPlusPlus) {
8691       S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8692       D.setInvalidType();
8693       return;
8694     }
8695 
8696     ValidTypes.insert(PT.getTypePtr());
8697     return;
8698 
8699   case InvalidAddrSpacePtrKernelParam:
8700     // OpenCL v1.0 s6.5:
8701     // __kernel function arguments declared to be a pointer of a type can point
8702     // to one of the following address spaces only : __global, __local or
8703     // __constant.
8704     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8705     D.setInvalidType();
8706     return;
8707 
8708     // OpenCL v1.2 s6.9.k:
8709     // Arguments to kernel functions in a program cannot be declared with the
8710     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8711     // uintptr_t or a struct and/or union that contain fields declared to be
8712     // one of these built-in scalar types.
8713 
8714   case InvalidKernelParam:
8715     // OpenCL v1.2 s6.8 n:
8716     // A kernel function argument cannot be declared
8717     // of event_t type.
8718     // Do not diagnose half type since it is diagnosed as invalid argument
8719     // type for any function elsewhere.
8720     if (!PT->isHalfType()) {
8721       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8722 
8723       // Explain what typedefs are involved.
8724       const TypedefType *Typedef = nullptr;
8725       while ((Typedef = PT->getAs<TypedefType>())) {
8726         SourceLocation Loc = Typedef->getDecl()->getLocation();
8727         // SourceLocation may be invalid for a built-in type.
8728         if (Loc.isValid())
8729           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8730         PT = Typedef->desugar();
8731       }
8732     }
8733 
8734     D.setInvalidType();
8735     return;
8736 
8737   case PtrKernelParam:
8738   case ValidKernelParam:
8739     ValidTypes.insert(PT.getTypePtr());
8740     return;
8741 
8742   case RecordKernelParam:
8743     break;
8744   }
8745 
8746   // Track nested structs we will inspect
8747   SmallVector<const Decl *, 4> VisitStack;
8748 
8749   // Track where we are in the nested structs. Items will migrate from
8750   // VisitStack to HistoryStack as we do the DFS for bad field.
8751   SmallVector<const FieldDecl *, 4> HistoryStack;
8752   HistoryStack.push_back(nullptr);
8753 
8754   // At this point we already handled everything except of a RecordType or
8755   // an ArrayType of a RecordType.
8756   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8757   const RecordType *RecTy =
8758       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8759   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8760 
8761   VisitStack.push_back(RecTy->getDecl());
8762   assert(VisitStack.back() && "First decl null?");
8763 
8764   do {
8765     const Decl *Next = VisitStack.pop_back_val();
8766     if (!Next) {
8767       assert(!HistoryStack.empty());
8768       // Found a marker, we have gone up a level
8769       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8770         ValidTypes.insert(Hist->getType().getTypePtr());
8771 
8772       continue;
8773     }
8774 
8775     // Adds everything except the original parameter declaration (which is not a
8776     // field itself) to the history stack.
8777     const RecordDecl *RD;
8778     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8779       HistoryStack.push_back(Field);
8780 
8781       QualType FieldTy = Field->getType();
8782       // Other field types (known to be valid or invalid) are handled while we
8783       // walk around RecordDecl::fields().
8784       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8785              "Unexpected type.");
8786       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8787 
8788       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8789     } else {
8790       RD = cast<RecordDecl>(Next);
8791     }
8792 
8793     // Add a null marker so we know when we've gone back up a level
8794     VisitStack.push_back(nullptr);
8795 
8796     for (const auto *FD : RD->fields()) {
8797       QualType QT = FD->getType();
8798 
8799       if (ValidTypes.count(QT.getTypePtr()))
8800         continue;
8801 
8802       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8803       if (ParamType == ValidKernelParam)
8804         continue;
8805 
8806       if (ParamType == RecordKernelParam) {
8807         VisitStack.push_back(FD);
8808         continue;
8809       }
8810 
8811       // OpenCL v1.2 s6.9.p:
8812       // Arguments to kernel functions that are declared to be a struct or union
8813       // do not allow OpenCL objects to be passed as elements of the struct or
8814       // union.
8815       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8816           ParamType == InvalidAddrSpacePtrKernelParam) {
8817         S.Diag(Param->getLocation(),
8818                diag::err_record_with_pointers_kernel_param)
8819           << PT->isUnionType()
8820           << PT;
8821       } else {
8822         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8823       }
8824 
8825       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8826           << OrigRecDecl->getDeclName();
8827 
8828       // We have an error, now let's go back up through history and show where
8829       // the offending field came from
8830       for (ArrayRef<const FieldDecl *>::const_iterator
8831                I = HistoryStack.begin() + 1,
8832                E = HistoryStack.end();
8833            I != E; ++I) {
8834         const FieldDecl *OuterField = *I;
8835         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8836           << OuterField->getType();
8837       }
8838 
8839       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8840         << QT->isPointerType()
8841         << QT;
8842       D.setInvalidType();
8843       return;
8844     }
8845   } while (!VisitStack.empty());
8846 }
8847 
8848 /// Find the DeclContext in which a tag is implicitly declared if we see an
8849 /// elaborated type specifier in the specified context, and lookup finds
8850 /// nothing.
8851 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8852   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8853     DC = DC->getParent();
8854   return DC;
8855 }
8856 
8857 /// Find the Scope in which a tag is implicitly declared if we see an
8858 /// elaborated type specifier in the specified context, and lookup finds
8859 /// nothing.
8860 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8861   while (S->isClassScope() ||
8862          (LangOpts.CPlusPlus &&
8863           S->isFunctionPrototypeScope()) ||
8864          ((S->getFlags() & Scope::DeclScope) == 0) ||
8865          (S->getEntity() && S->getEntity()->isTransparentContext()))
8866     S = S->getParent();
8867   return S;
8868 }
8869 
8870 NamedDecl*
8871 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8872                               TypeSourceInfo *TInfo, LookupResult &Previous,
8873                               MultiTemplateParamsArg TemplateParamListsRef,
8874                               bool &AddToScope) {
8875   QualType R = TInfo->getType();
8876 
8877   assert(R->isFunctionType());
8878   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
8879     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
8880 
8881   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
8882   for (TemplateParameterList *TPL : TemplateParamListsRef)
8883     TemplateParamLists.push_back(TPL);
8884   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
8885     if (!TemplateParamLists.empty() &&
8886         Invented->getDepth() == TemplateParamLists.back()->getDepth())
8887       TemplateParamLists.back() = Invented;
8888     else
8889       TemplateParamLists.push_back(Invented);
8890   }
8891 
8892   // TODO: consider using NameInfo for diagnostic.
8893   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8894   DeclarationName Name = NameInfo.getName();
8895   StorageClass SC = getFunctionStorageClass(*this, D);
8896 
8897   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8898     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8899          diag::err_invalid_thread)
8900       << DeclSpec::getSpecifierName(TSCS);
8901 
8902   if (D.isFirstDeclarationOfMember())
8903     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8904                            D.getIdentifierLoc());
8905 
8906   bool isFriend = false;
8907   FunctionTemplateDecl *FunctionTemplate = nullptr;
8908   bool isMemberSpecialization = false;
8909   bool isFunctionTemplateSpecialization = false;
8910 
8911   bool isDependentClassScopeExplicitSpecialization = false;
8912   bool HasExplicitTemplateArgs = false;
8913   TemplateArgumentListInfo TemplateArgs;
8914 
8915   bool isVirtualOkay = false;
8916 
8917   DeclContext *OriginalDC = DC;
8918   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8919 
8920   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8921                                               isVirtualOkay);
8922   if (!NewFD) return nullptr;
8923 
8924   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8925     NewFD->setTopLevelDeclInObjCContainer();
8926 
8927   // Set the lexical context. If this is a function-scope declaration, or has a
8928   // C++ scope specifier, or is the object of a friend declaration, the lexical
8929   // context will be different from the semantic context.
8930   NewFD->setLexicalDeclContext(CurContext);
8931 
8932   if (IsLocalExternDecl)
8933     NewFD->setLocalExternDecl();
8934 
8935   if (getLangOpts().CPlusPlus) {
8936     bool isInline = D.getDeclSpec().isInlineSpecified();
8937     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8938     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
8939     isFriend = D.getDeclSpec().isFriendSpecified();
8940     if (isFriend && !isInline && D.isFunctionDefinition()) {
8941       // C++ [class.friend]p5
8942       //   A function can be defined in a friend declaration of a
8943       //   class . . . . Such a function is implicitly inline.
8944       NewFD->setImplicitlyInline();
8945     }
8946 
8947     // If this is a method defined in an __interface, and is not a constructor
8948     // or an overloaded operator, then set the pure flag (isVirtual will already
8949     // return true).
8950     if (const CXXRecordDecl *Parent =
8951           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8952       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8953         NewFD->setPure(true);
8954 
8955       // C++ [class.union]p2
8956       //   A union can have member functions, but not virtual functions.
8957       if (isVirtual && Parent->isUnion())
8958         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8959     }
8960 
8961     SetNestedNameSpecifier(*this, NewFD, D);
8962     isMemberSpecialization = false;
8963     isFunctionTemplateSpecialization = false;
8964     if (D.isInvalidType())
8965       NewFD->setInvalidDecl();
8966 
8967     // Match up the template parameter lists with the scope specifier, then
8968     // determine whether we have a template or a template specialization.
8969     bool Invalid = false;
8970     TemplateParameterList *TemplateParams =
8971         MatchTemplateParametersToScopeSpecifier(
8972             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8973             D.getCXXScopeSpec(),
8974             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8975                 ? D.getName().TemplateId
8976                 : nullptr,
8977             TemplateParamLists, isFriend, isMemberSpecialization,
8978             Invalid);
8979     if (TemplateParams) {
8980       // Check that we can declare a template here.
8981       if (CheckTemplateDeclScope(S, TemplateParams))
8982         NewFD->setInvalidDecl();
8983 
8984       if (TemplateParams->size() > 0) {
8985         // This is a function template
8986 
8987         // A destructor cannot be a template.
8988         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8989           Diag(NewFD->getLocation(), diag::err_destructor_template);
8990           NewFD->setInvalidDecl();
8991         }
8992 
8993         // If we're adding a template to a dependent context, we may need to
8994         // rebuilding some of the types used within the template parameter list,
8995         // now that we know what the current instantiation is.
8996         if (DC->isDependentContext()) {
8997           ContextRAII SavedContext(*this, DC);
8998           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8999             Invalid = true;
9000         }
9001 
9002         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9003                                                         NewFD->getLocation(),
9004                                                         Name, TemplateParams,
9005                                                         NewFD);
9006         FunctionTemplate->setLexicalDeclContext(CurContext);
9007         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9008 
9009         // For source fidelity, store the other template param lists.
9010         if (TemplateParamLists.size() > 1) {
9011           NewFD->setTemplateParameterListsInfo(Context,
9012               ArrayRef<TemplateParameterList *>(TemplateParamLists)
9013                   .drop_back(1));
9014         }
9015       } else {
9016         // This is a function template specialization.
9017         isFunctionTemplateSpecialization = true;
9018         // For source fidelity, store all the template param lists.
9019         if (TemplateParamLists.size() > 0)
9020           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9021 
9022         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9023         if (isFriend) {
9024           // We want to remove the "template<>", found here.
9025           SourceRange RemoveRange = TemplateParams->getSourceRange();
9026 
9027           // If we remove the template<> and the name is not a
9028           // template-id, we're actually silently creating a problem:
9029           // the friend declaration will refer to an untemplated decl,
9030           // and clearly the user wants a template specialization.  So
9031           // we need to insert '<>' after the name.
9032           SourceLocation InsertLoc;
9033           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9034             InsertLoc = D.getName().getSourceRange().getEnd();
9035             InsertLoc = getLocForEndOfToken(InsertLoc);
9036           }
9037 
9038           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9039             << Name << RemoveRange
9040             << FixItHint::CreateRemoval(RemoveRange)
9041             << FixItHint::CreateInsertion(InsertLoc, "<>");
9042         }
9043       }
9044     } else {
9045       // Check that we can declare a template here.
9046       if (!TemplateParamLists.empty() && isMemberSpecialization &&
9047           CheckTemplateDeclScope(S, TemplateParamLists.back()))
9048         NewFD->setInvalidDecl();
9049 
9050       // All template param lists were matched against the scope specifier:
9051       // this is NOT (an explicit specialization of) a template.
9052       if (TemplateParamLists.size() > 0)
9053         // For source fidelity, store all the template param lists.
9054         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9055     }
9056 
9057     if (Invalid) {
9058       NewFD->setInvalidDecl();
9059       if (FunctionTemplate)
9060         FunctionTemplate->setInvalidDecl();
9061     }
9062 
9063     // C++ [dcl.fct.spec]p5:
9064     //   The virtual specifier shall only be used in declarations of
9065     //   nonstatic class member functions that appear within a
9066     //   member-specification of a class declaration; see 10.3.
9067     //
9068     if (isVirtual && !NewFD->isInvalidDecl()) {
9069       if (!isVirtualOkay) {
9070         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9071              diag::err_virtual_non_function);
9072       } else if (!CurContext->isRecord()) {
9073         // 'virtual' was specified outside of the class.
9074         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9075              diag::err_virtual_out_of_class)
9076           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9077       } else if (NewFD->getDescribedFunctionTemplate()) {
9078         // C++ [temp.mem]p3:
9079         //  A member function template shall not be virtual.
9080         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9081              diag::err_virtual_member_function_template)
9082           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9083       } else {
9084         // Okay: Add virtual to the method.
9085         NewFD->setVirtualAsWritten(true);
9086       }
9087 
9088       if (getLangOpts().CPlusPlus14 &&
9089           NewFD->getReturnType()->isUndeducedType())
9090         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9091     }
9092 
9093     if (getLangOpts().CPlusPlus14 &&
9094         (NewFD->isDependentContext() ||
9095          (isFriend && CurContext->isDependentContext())) &&
9096         NewFD->getReturnType()->isUndeducedType()) {
9097       // If the function template is referenced directly (for instance, as a
9098       // member of the current instantiation), pretend it has a dependent type.
9099       // This is not really justified by the standard, but is the only sane
9100       // thing to do.
9101       // FIXME: For a friend function, we have not marked the function as being
9102       // a friend yet, so 'isDependentContext' on the FD doesn't work.
9103       const FunctionProtoType *FPT =
9104           NewFD->getType()->castAs<FunctionProtoType>();
9105       QualType Result =
9106           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
9107       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9108                                              FPT->getExtProtoInfo()));
9109     }
9110 
9111     // C++ [dcl.fct.spec]p3:
9112     //  The inline specifier shall not appear on a block scope function
9113     //  declaration.
9114     if (isInline && !NewFD->isInvalidDecl()) {
9115       if (CurContext->isFunctionOrMethod()) {
9116         // 'inline' is not allowed on block scope function declaration.
9117         Diag(D.getDeclSpec().getInlineSpecLoc(),
9118              diag::err_inline_declaration_block_scope) << Name
9119           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9120       }
9121     }
9122 
9123     // C++ [dcl.fct.spec]p6:
9124     //  The explicit specifier shall be used only in the declaration of a
9125     //  constructor or conversion function within its class definition;
9126     //  see 12.3.1 and 12.3.2.
9127     if (hasExplicit && !NewFD->isInvalidDecl() &&
9128         !isa<CXXDeductionGuideDecl>(NewFD)) {
9129       if (!CurContext->isRecord()) {
9130         // 'explicit' was specified outside of the class.
9131         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9132              diag::err_explicit_out_of_class)
9133             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9134       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9135                  !isa<CXXConversionDecl>(NewFD)) {
9136         // 'explicit' was specified on a function that wasn't a constructor
9137         // or conversion function.
9138         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9139              diag::err_explicit_non_ctor_or_conv_function)
9140             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9141       }
9142     }
9143 
9144     ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9145     if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9146       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9147       // are implicitly inline.
9148       NewFD->setImplicitlyInline();
9149 
9150       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9151       // be either constructors or to return a literal type. Therefore,
9152       // destructors cannot be declared constexpr.
9153       if (isa<CXXDestructorDecl>(NewFD) &&
9154           (!getLangOpts().CPlusPlus20 ||
9155            ConstexprKind == ConstexprSpecKind::Consteval)) {
9156         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9157             << static_cast<int>(ConstexprKind);
9158         NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9159                                     ? ConstexprSpecKind::Unspecified
9160                                     : ConstexprSpecKind::Constexpr);
9161       }
9162       // C++20 [dcl.constexpr]p2: An allocation function, or a
9163       // deallocation function shall not be declared with the consteval
9164       // specifier.
9165       if (ConstexprKind == ConstexprSpecKind::Consteval &&
9166           (NewFD->getOverloadedOperator() == OO_New ||
9167            NewFD->getOverloadedOperator() == OO_Array_New ||
9168            NewFD->getOverloadedOperator() == OO_Delete ||
9169            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9170         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9171              diag::err_invalid_consteval_decl_kind)
9172             << NewFD;
9173         NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
9174       }
9175     }
9176 
9177     // If __module_private__ was specified, mark the function accordingly.
9178     if (D.getDeclSpec().isModulePrivateSpecified()) {
9179       if (isFunctionTemplateSpecialization) {
9180         SourceLocation ModulePrivateLoc
9181           = D.getDeclSpec().getModulePrivateSpecLoc();
9182         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9183           << 0
9184           << FixItHint::CreateRemoval(ModulePrivateLoc);
9185       } else {
9186         NewFD->setModulePrivate();
9187         if (FunctionTemplate)
9188           FunctionTemplate->setModulePrivate();
9189       }
9190     }
9191 
9192     if (isFriend) {
9193       if (FunctionTemplate) {
9194         FunctionTemplate->setObjectOfFriendDecl();
9195         FunctionTemplate->setAccess(AS_public);
9196       }
9197       NewFD->setObjectOfFriendDecl();
9198       NewFD->setAccess(AS_public);
9199     }
9200 
9201     // If a function is defined as defaulted or deleted, mark it as such now.
9202     // We'll do the relevant checks on defaulted / deleted functions later.
9203     switch (D.getFunctionDefinitionKind()) {
9204     case FunctionDefinitionKind::Declaration:
9205     case FunctionDefinitionKind::Definition:
9206       break;
9207 
9208     case FunctionDefinitionKind::Defaulted:
9209       NewFD->setDefaulted();
9210       break;
9211 
9212     case FunctionDefinitionKind::Deleted:
9213       NewFD->setDeletedAsWritten();
9214       break;
9215     }
9216 
9217     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9218         D.isFunctionDefinition()) {
9219       // C++ [class.mfct]p2:
9220       //   A member function may be defined (8.4) in its class definition, in
9221       //   which case it is an inline member function (7.1.2)
9222       NewFD->setImplicitlyInline();
9223     }
9224 
9225     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9226         !CurContext->isRecord()) {
9227       // C++ [class.static]p1:
9228       //   A data or function member of a class may be declared static
9229       //   in a class definition, in which case it is a static member of
9230       //   the class.
9231 
9232       // Complain about the 'static' specifier if it's on an out-of-line
9233       // member function definition.
9234 
9235       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9236       // member function template declaration and class member template
9237       // declaration (MSVC versions before 2015), warn about this.
9238       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9239            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9240              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9241            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9242            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9243         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9244     }
9245 
9246     // C++11 [except.spec]p15:
9247     //   A deallocation function with no exception-specification is treated
9248     //   as if it were specified with noexcept(true).
9249     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9250     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9251          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9252         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9253       NewFD->setType(Context.getFunctionType(
9254           FPT->getReturnType(), FPT->getParamTypes(),
9255           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9256   }
9257 
9258   // Filter out previous declarations that don't match the scope.
9259   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9260                        D.getCXXScopeSpec().isNotEmpty() ||
9261                        isMemberSpecialization ||
9262                        isFunctionTemplateSpecialization);
9263 
9264   // Handle GNU asm-label extension (encoded as an attribute).
9265   if (Expr *E = (Expr*) D.getAsmLabel()) {
9266     // The parser guarantees this is a string.
9267     StringLiteral *SE = cast<StringLiteral>(E);
9268     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9269                                         /*IsLiteralLabel=*/true,
9270                                         SE->getStrTokenLoc(0)));
9271   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9272     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9273       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9274     if (I != ExtnameUndeclaredIdentifiers.end()) {
9275       if (isDeclExternC(NewFD)) {
9276         NewFD->addAttr(I->second);
9277         ExtnameUndeclaredIdentifiers.erase(I);
9278       } else
9279         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9280             << /*Variable*/0 << NewFD;
9281     }
9282   }
9283 
9284   // Copy the parameter declarations from the declarator D to the function
9285   // declaration NewFD, if they are available.  First scavenge them into Params.
9286   SmallVector<ParmVarDecl*, 16> Params;
9287   unsigned FTIIdx;
9288   if (D.isFunctionDeclarator(FTIIdx)) {
9289     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9290 
9291     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9292     // function that takes no arguments, not a function that takes a
9293     // single void argument.
9294     // We let through "const void" here because Sema::GetTypeForDeclarator
9295     // already checks for that case.
9296     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9297       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9298         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9299         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9300         Param->setDeclContext(NewFD);
9301         Params.push_back(Param);
9302 
9303         if (Param->isInvalidDecl())
9304           NewFD->setInvalidDecl();
9305       }
9306     }
9307 
9308     if (!getLangOpts().CPlusPlus) {
9309       // In C, find all the tag declarations from the prototype and move them
9310       // into the function DeclContext. Remove them from the surrounding tag
9311       // injection context of the function, which is typically but not always
9312       // the TU.
9313       DeclContext *PrototypeTagContext =
9314           getTagInjectionContext(NewFD->getLexicalDeclContext());
9315       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9316         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9317 
9318         // We don't want to reparent enumerators. Look at their parent enum
9319         // instead.
9320         if (!TD) {
9321           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9322             TD = cast<EnumDecl>(ECD->getDeclContext());
9323         }
9324         if (!TD)
9325           continue;
9326         DeclContext *TagDC = TD->getLexicalDeclContext();
9327         if (!TagDC->containsDecl(TD))
9328           continue;
9329         TagDC->removeDecl(TD);
9330         TD->setDeclContext(NewFD);
9331         NewFD->addDecl(TD);
9332 
9333         // Preserve the lexical DeclContext if it is not the surrounding tag
9334         // injection context of the FD. In this example, the semantic context of
9335         // E will be f and the lexical context will be S, while both the
9336         // semantic and lexical contexts of S will be f:
9337         //   void f(struct S { enum E { a } f; } s);
9338         if (TagDC != PrototypeTagContext)
9339           TD->setLexicalDeclContext(TagDC);
9340       }
9341     }
9342   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9343     // When we're declaring a function with a typedef, typeof, etc as in the
9344     // following example, we'll need to synthesize (unnamed)
9345     // parameters for use in the declaration.
9346     //
9347     // @code
9348     // typedef void fn(int);
9349     // fn f;
9350     // @endcode
9351 
9352     // Synthesize a parameter for each argument type.
9353     for (const auto &AI : FT->param_types()) {
9354       ParmVarDecl *Param =
9355           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9356       Param->setScopeInfo(0, Params.size());
9357       Params.push_back(Param);
9358     }
9359   } else {
9360     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9361            "Should not need args for typedef of non-prototype fn");
9362   }
9363 
9364   // Finally, we know we have the right number of parameters, install them.
9365   NewFD->setParams(Params);
9366 
9367   if (D.getDeclSpec().isNoreturnSpecified())
9368     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9369                                            D.getDeclSpec().getNoreturnSpecLoc(),
9370                                            AttributeCommonInfo::AS_Keyword));
9371 
9372   // Functions returning a variably modified type violate C99 6.7.5.2p2
9373   // because all functions have linkage.
9374   if (!NewFD->isInvalidDecl() &&
9375       NewFD->getReturnType()->isVariablyModifiedType()) {
9376     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9377     NewFD->setInvalidDecl();
9378   }
9379 
9380   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9381   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9382       !NewFD->hasAttr<SectionAttr>())
9383     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9384         Context, PragmaClangTextSection.SectionName,
9385         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9386 
9387   // Apply an implicit SectionAttr if #pragma code_seg is active.
9388   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9389       !NewFD->hasAttr<SectionAttr>()) {
9390     NewFD->addAttr(SectionAttr::CreateImplicit(
9391         Context, CodeSegStack.CurrentValue->getString(),
9392         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9393         SectionAttr::Declspec_allocate));
9394     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9395                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9396                          ASTContext::PSF_Read,
9397                      NewFD))
9398       NewFD->dropAttr<SectionAttr>();
9399   }
9400 
9401   // Apply an implicit CodeSegAttr from class declspec or
9402   // apply an implicit SectionAttr from #pragma code_seg if active.
9403   if (!NewFD->hasAttr<CodeSegAttr>()) {
9404     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9405                                                                  D.isFunctionDefinition())) {
9406       NewFD->addAttr(SAttr);
9407     }
9408   }
9409 
9410   // Handle attributes.
9411   ProcessDeclAttributes(S, NewFD, D);
9412 
9413   if (getLangOpts().OpenCL) {
9414     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9415     // type declaration will generate a compilation error.
9416     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9417     if (AddressSpace != LangAS::Default) {
9418       Diag(NewFD->getLocation(),
9419            diag::err_opencl_return_value_with_address_space);
9420       NewFD->setInvalidDecl();
9421     }
9422   }
9423 
9424   if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))
9425     checkDeviceDecl(NewFD, D.getBeginLoc());
9426 
9427   if (!getLangOpts().CPlusPlus) {
9428     // Perform semantic checking on the function declaration.
9429     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9430       CheckMain(NewFD, D.getDeclSpec());
9431 
9432     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9433       CheckMSVCRTEntryPoint(NewFD);
9434 
9435     if (!NewFD->isInvalidDecl())
9436       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9437                                                   isMemberSpecialization));
9438     else if (!Previous.empty())
9439       // Recover gracefully from an invalid redeclaration.
9440       D.setRedeclaration(true);
9441     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9442             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9443            "previous declaration set still overloaded");
9444 
9445     // Diagnose no-prototype function declarations with calling conventions that
9446     // don't support variadic calls. Only do this in C and do it after merging
9447     // possibly prototyped redeclarations.
9448     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9449     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9450       CallingConv CC = FT->getExtInfo().getCC();
9451       if (!supportsVariadicCall(CC)) {
9452         // Windows system headers sometimes accidentally use stdcall without
9453         // (void) parameters, so we relax this to a warning.
9454         int DiagID =
9455             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9456         Diag(NewFD->getLocation(), DiagID)
9457             << FunctionType::getNameForCallConv(CC);
9458       }
9459     }
9460 
9461    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9462        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9463      checkNonTrivialCUnion(NewFD->getReturnType(),
9464                            NewFD->getReturnTypeSourceRange().getBegin(),
9465                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9466   } else {
9467     // C++11 [replacement.functions]p3:
9468     //  The program's definitions shall not be specified as inline.
9469     //
9470     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9471     //
9472     // Suppress the diagnostic if the function is __attribute__((used)), since
9473     // that forces an external definition to be emitted.
9474     if (D.getDeclSpec().isInlineSpecified() &&
9475         NewFD->isReplaceableGlobalAllocationFunction() &&
9476         !NewFD->hasAttr<UsedAttr>())
9477       Diag(D.getDeclSpec().getInlineSpecLoc(),
9478            diag::ext_operator_new_delete_declared_inline)
9479         << NewFD->getDeclName();
9480 
9481     // If the declarator is a template-id, translate the parser's template
9482     // argument list into our AST format.
9483     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9484       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9485       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9486       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9487       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9488                                          TemplateId->NumArgs);
9489       translateTemplateArguments(TemplateArgsPtr,
9490                                  TemplateArgs);
9491 
9492       HasExplicitTemplateArgs = true;
9493 
9494       if (NewFD->isInvalidDecl()) {
9495         HasExplicitTemplateArgs = false;
9496       } else if (FunctionTemplate) {
9497         // Function template with explicit template arguments.
9498         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9499           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9500 
9501         HasExplicitTemplateArgs = false;
9502       } else {
9503         assert((isFunctionTemplateSpecialization ||
9504                 D.getDeclSpec().isFriendSpecified()) &&
9505                "should have a 'template<>' for this decl");
9506         // "friend void foo<>(int);" is an implicit specialization decl.
9507         isFunctionTemplateSpecialization = true;
9508       }
9509     } else if (isFriend && isFunctionTemplateSpecialization) {
9510       // This combination is only possible in a recovery case;  the user
9511       // wrote something like:
9512       //   template <> friend void foo(int);
9513       // which we're recovering from as if the user had written:
9514       //   friend void foo<>(int);
9515       // Go ahead and fake up a template id.
9516       HasExplicitTemplateArgs = true;
9517       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9518       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9519     }
9520 
9521     // We do not add HD attributes to specializations here because
9522     // they may have different constexpr-ness compared to their
9523     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9524     // may end up with different effective targets. Instead, a
9525     // specialization inherits its target attributes from its template
9526     // in the CheckFunctionTemplateSpecialization() call below.
9527     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9528       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9529 
9530     // If it's a friend (and only if it's a friend), it's possible
9531     // that either the specialized function type or the specialized
9532     // template is dependent, and therefore matching will fail.  In
9533     // this case, don't check the specialization yet.
9534     if (isFunctionTemplateSpecialization && isFriend &&
9535         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9536          TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
9537              TemplateArgs.arguments()))) {
9538       assert(HasExplicitTemplateArgs &&
9539              "friend function specialization without template args");
9540       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9541                                                        Previous))
9542         NewFD->setInvalidDecl();
9543     } else if (isFunctionTemplateSpecialization) {
9544       if (CurContext->isDependentContext() && CurContext->isRecord()
9545           && !isFriend) {
9546         isDependentClassScopeExplicitSpecialization = true;
9547       } else if (!NewFD->isInvalidDecl() &&
9548                  CheckFunctionTemplateSpecialization(
9549                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9550                      Previous))
9551         NewFD->setInvalidDecl();
9552 
9553       // C++ [dcl.stc]p1:
9554       //   A storage-class-specifier shall not be specified in an explicit
9555       //   specialization (14.7.3)
9556       FunctionTemplateSpecializationInfo *Info =
9557           NewFD->getTemplateSpecializationInfo();
9558       if (Info && SC != SC_None) {
9559         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9560           Diag(NewFD->getLocation(),
9561                diag::err_explicit_specialization_inconsistent_storage_class)
9562             << SC
9563             << FixItHint::CreateRemoval(
9564                                       D.getDeclSpec().getStorageClassSpecLoc());
9565 
9566         else
9567           Diag(NewFD->getLocation(),
9568                diag::ext_explicit_specialization_storage_class)
9569             << FixItHint::CreateRemoval(
9570                                       D.getDeclSpec().getStorageClassSpecLoc());
9571       }
9572     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9573       if (CheckMemberSpecialization(NewFD, Previous))
9574           NewFD->setInvalidDecl();
9575     }
9576 
9577     // Perform semantic checking on the function declaration.
9578     if (!isDependentClassScopeExplicitSpecialization) {
9579       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9580         CheckMain(NewFD, D.getDeclSpec());
9581 
9582       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9583         CheckMSVCRTEntryPoint(NewFD);
9584 
9585       if (!NewFD->isInvalidDecl())
9586         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9587                                                     isMemberSpecialization));
9588       else if (!Previous.empty())
9589         // Recover gracefully from an invalid redeclaration.
9590         D.setRedeclaration(true);
9591     }
9592 
9593     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9594             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9595            "previous declaration set still overloaded");
9596 
9597     NamedDecl *PrincipalDecl = (FunctionTemplate
9598                                 ? cast<NamedDecl>(FunctionTemplate)
9599                                 : NewFD);
9600 
9601     if (isFriend && NewFD->getPreviousDecl()) {
9602       AccessSpecifier Access = AS_public;
9603       if (!NewFD->isInvalidDecl())
9604         Access = NewFD->getPreviousDecl()->getAccess();
9605 
9606       NewFD->setAccess(Access);
9607       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9608     }
9609 
9610     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9611         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9612       PrincipalDecl->setNonMemberOperator();
9613 
9614     // If we have a function template, check the template parameter
9615     // list. This will check and merge default template arguments.
9616     if (FunctionTemplate) {
9617       FunctionTemplateDecl *PrevTemplate =
9618                                      FunctionTemplate->getPreviousDecl();
9619       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9620                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9621                                     : nullptr,
9622                             D.getDeclSpec().isFriendSpecified()
9623                               ? (D.isFunctionDefinition()
9624                                    ? TPC_FriendFunctionTemplateDefinition
9625                                    : TPC_FriendFunctionTemplate)
9626                               : (D.getCXXScopeSpec().isSet() &&
9627                                  DC && DC->isRecord() &&
9628                                  DC->isDependentContext())
9629                                   ? TPC_ClassTemplateMember
9630                                   : TPC_FunctionTemplate);
9631     }
9632 
9633     if (NewFD->isInvalidDecl()) {
9634       // Ignore all the rest of this.
9635     } else if (!D.isRedeclaration()) {
9636       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9637                                        AddToScope };
9638       // Fake up an access specifier if it's supposed to be a class member.
9639       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9640         NewFD->setAccess(AS_public);
9641 
9642       // Qualified decls generally require a previous declaration.
9643       if (D.getCXXScopeSpec().isSet()) {
9644         // ...with the major exception of templated-scope or
9645         // dependent-scope friend declarations.
9646 
9647         // TODO: we currently also suppress this check in dependent
9648         // contexts because (1) the parameter depth will be off when
9649         // matching friend templates and (2) we might actually be
9650         // selecting a friend based on a dependent factor.  But there
9651         // are situations where these conditions don't apply and we
9652         // can actually do this check immediately.
9653         //
9654         // Unless the scope is dependent, it's always an error if qualified
9655         // redeclaration lookup found nothing at all. Diagnose that now;
9656         // nothing will diagnose that error later.
9657         if (isFriend &&
9658             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9659              (!Previous.empty() && CurContext->isDependentContext()))) {
9660           // ignore these
9661         } else {
9662           // The user tried to provide an out-of-line definition for a
9663           // function that is a member of a class or namespace, but there
9664           // was no such member function declared (C++ [class.mfct]p2,
9665           // C++ [namespace.memdef]p2). For example:
9666           //
9667           // class X {
9668           //   void f() const;
9669           // };
9670           //
9671           // void X::f() { } // ill-formed
9672           //
9673           // Complain about this problem, and attempt to suggest close
9674           // matches (e.g., those that differ only in cv-qualifiers and
9675           // whether the parameter types are references).
9676 
9677           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9678                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9679             AddToScope = ExtraArgs.AddToScope;
9680             return Result;
9681           }
9682         }
9683 
9684         // Unqualified local friend declarations are required to resolve
9685         // to something.
9686       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9687         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9688                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9689           AddToScope = ExtraArgs.AddToScope;
9690           return Result;
9691         }
9692       }
9693     } else if (!D.isFunctionDefinition() &&
9694                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9695                !isFriend && !isFunctionTemplateSpecialization &&
9696                !isMemberSpecialization) {
9697       // An out-of-line member function declaration must also be a
9698       // definition (C++ [class.mfct]p2).
9699       // Note that this is not the case for explicit specializations of
9700       // function templates or member functions of class templates, per
9701       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9702       // extension for compatibility with old SWIG code which likes to
9703       // generate them.
9704       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9705         << D.getCXXScopeSpec().getRange();
9706     }
9707   }
9708 
9709   // If this is the first declaration of a library builtin function, add
9710   // attributes as appropriate.
9711   if (!D.isRedeclaration() &&
9712       NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
9713     if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
9714       if (unsigned BuiltinID = II->getBuiltinID()) {
9715         if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
9716           // Validate the type matches unless this builtin is specified as
9717           // matching regardless of its declared type.
9718           if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
9719             NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9720           } else {
9721             ASTContext::GetBuiltinTypeError Error;
9722             LookupNecessaryTypesForBuiltin(S, BuiltinID);
9723             QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
9724 
9725             if (!Error && !BuiltinType.isNull() &&
9726                 Context.hasSameFunctionTypeIgnoringExceptionSpec(
9727                     NewFD->getType(), BuiltinType))
9728               NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9729           }
9730         } else if (BuiltinID == Builtin::BI__GetExceptionInfo &&
9731                    Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9732           // FIXME: We should consider this a builtin only in the std namespace.
9733           NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9734         }
9735       }
9736     }
9737   }
9738 
9739   ProcessPragmaWeak(S, NewFD);
9740   checkAttributesAfterMerging(*this, *NewFD);
9741 
9742   AddKnownFunctionAttributes(NewFD);
9743 
9744   if (NewFD->hasAttr<OverloadableAttr>() &&
9745       !NewFD->getType()->getAs<FunctionProtoType>()) {
9746     Diag(NewFD->getLocation(),
9747          diag::err_attribute_overloadable_no_prototype)
9748       << NewFD;
9749 
9750     // Turn this into a variadic function with no parameters.
9751     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9752     FunctionProtoType::ExtProtoInfo EPI(
9753         Context.getDefaultCallingConvention(true, false));
9754     EPI.Variadic = true;
9755     EPI.ExtInfo = FT->getExtInfo();
9756 
9757     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9758     NewFD->setType(R);
9759   }
9760 
9761   // If there's a #pragma GCC visibility in scope, and this isn't a class
9762   // member, set the visibility of this function.
9763   if (!DC->isRecord() && NewFD->isExternallyVisible())
9764     AddPushedVisibilityAttribute(NewFD);
9765 
9766   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9767   // marking the function.
9768   AddCFAuditedAttribute(NewFD);
9769 
9770   // If this is a function definition, check if we have to apply optnone due to
9771   // a pragma.
9772   if(D.isFunctionDefinition())
9773     AddRangeBasedOptnone(NewFD);
9774 
9775   // If this is the first declaration of an extern C variable, update
9776   // the map of such variables.
9777   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9778       isIncompleteDeclExternC(*this, NewFD))
9779     RegisterLocallyScopedExternCDecl(NewFD, S);
9780 
9781   // Set this FunctionDecl's range up to the right paren.
9782   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9783 
9784   if (D.isRedeclaration() && !Previous.empty()) {
9785     NamedDecl *Prev = Previous.getRepresentativeDecl();
9786     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9787                                    isMemberSpecialization ||
9788                                        isFunctionTemplateSpecialization,
9789                                    D.isFunctionDefinition());
9790   }
9791 
9792   if (getLangOpts().CUDA) {
9793     IdentifierInfo *II = NewFD->getIdentifier();
9794     if (II && II->isStr(getCudaConfigureFuncName()) &&
9795         !NewFD->isInvalidDecl() &&
9796         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9797       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9798         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9799             << getCudaConfigureFuncName();
9800       Context.setcudaConfigureCallDecl(NewFD);
9801     }
9802 
9803     // Variadic functions, other than a *declaration* of printf, are not allowed
9804     // in device-side CUDA code, unless someone passed
9805     // -fcuda-allow-variadic-functions.
9806     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9807         (NewFD->hasAttr<CUDADeviceAttr>() ||
9808          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9809         !(II && II->isStr("printf") && NewFD->isExternC() &&
9810           !D.isFunctionDefinition())) {
9811       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9812     }
9813   }
9814 
9815   MarkUnusedFileScopedDecl(NewFD);
9816 
9817 
9818 
9819   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9820     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9821     if ((getLangOpts().OpenCLVersion >= 120)
9822         && (SC == SC_Static)) {
9823       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9824       D.setInvalidType();
9825     }
9826 
9827     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9828     if (!NewFD->getReturnType()->isVoidType()) {
9829       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9830       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9831           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9832                                 : FixItHint());
9833       D.setInvalidType();
9834     }
9835 
9836     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9837     for (auto Param : NewFD->parameters())
9838       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9839 
9840     if (getLangOpts().OpenCLCPlusPlus) {
9841       if (DC->isRecord()) {
9842         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9843         D.setInvalidType();
9844       }
9845       if (FunctionTemplate) {
9846         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9847         D.setInvalidType();
9848       }
9849     }
9850   }
9851 
9852   if (getLangOpts().CPlusPlus) {
9853     if (FunctionTemplate) {
9854       if (NewFD->isInvalidDecl())
9855         FunctionTemplate->setInvalidDecl();
9856       return FunctionTemplate;
9857     }
9858 
9859     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9860       CompleteMemberSpecialization(NewFD, Previous);
9861   }
9862 
9863   for (const ParmVarDecl *Param : NewFD->parameters()) {
9864     QualType PT = Param->getType();
9865 
9866     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9867     // types.
9868     if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
9869       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9870         QualType ElemTy = PipeTy->getElementType();
9871           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9872             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9873             D.setInvalidType();
9874           }
9875       }
9876     }
9877   }
9878 
9879   // Here we have an function template explicit specialization at class scope.
9880   // The actual specialization will be postponed to template instatiation
9881   // time via the ClassScopeFunctionSpecializationDecl node.
9882   if (isDependentClassScopeExplicitSpecialization) {
9883     ClassScopeFunctionSpecializationDecl *NewSpec =
9884                          ClassScopeFunctionSpecializationDecl::Create(
9885                                 Context, CurContext, NewFD->getLocation(),
9886                                 cast<CXXMethodDecl>(NewFD),
9887                                 HasExplicitTemplateArgs, TemplateArgs);
9888     CurContext->addDecl(NewSpec);
9889     AddToScope = false;
9890   }
9891 
9892   // Diagnose availability attributes. Availability cannot be used on functions
9893   // that are run during load/unload.
9894   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9895     if (NewFD->hasAttr<ConstructorAttr>()) {
9896       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9897           << 1;
9898       NewFD->dropAttr<AvailabilityAttr>();
9899     }
9900     if (NewFD->hasAttr<DestructorAttr>()) {
9901       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9902           << 2;
9903       NewFD->dropAttr<AvailabilityAttr>();
9904     }
9905   }
9906 
9907   // Diagnose no_builtin attribute on function declaration that are not a
9908   // definition.
9909   // FIXME: We should really be doing this in
9910   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
9911   // the FunctionDecl and at this point of the code
9912   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
9913   // because Sema::ActOnStartOfFunctionDef has not been called yet.
9914   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
9915     switch (D.getFunctionDefinitionKind()) {
9916     case FunctionDefinitionKind::Defaulted:
9917     case FunctionDefinitionKind::Deleted:
9918       Diag(NBA->getLocation(),
9919            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
9920           << NBA->getSpelling();
9921       break;
9922     case FunctionDefinitionKind::Declaration:
9923       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
9924           << NBA->getSpelling();
9925       break;
9926     case FunctionDefinitionKind::Definition:
9927       break;
9928     }
9929 
9930   return NewFD;
9931 }
9932 
9933 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
9934 /// when __declspec(code_seg) "is applied to a class, all member functions of
9935 /// the class and nested classes -- this includes compiler-generated special
9936 /// member functions -- are put in the specified segment."
9937 /// The actual behavior is a little more complicated. The Microsoft compiler
9938 /// won't check outer classes if there is an active value from #pragma code_seg.
9939 /// The CodeSeg is always applied from the direct parent but only from outer
9940 /// classes when the #pragma code_seg stack is empty. See:
9941 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9942 /// available since MS has removed the page.
9943 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9944   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9945   if (!Method)
9946     return nullptr;
9947   const CXXRecordDecl *Parent = Method->getParent();
9948   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9949     Attr *NewAttr = SAttr->clone(S.getASTContext());
9950     NewAttr->setImplicit(true);
9951     return NewAttr;
9952   }
9953 
9954   // The Microsoft compiler won't check outer classes for the CodeSeg
9955   // when the #pragma code_seg stack is active.
9956   if (S.CodeSegStack.CurrentValue)
9957    return nullptr;
9958 
9959   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9960     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9961       Attr *NewAttr = SAttr->clone(S.getASTContext());
9962       NewAttr->setImplicit(true);
9963       return NewAttr;
9964     }
9965   }
9966   return nullptr;
9967 }
9968 
9969 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9970 /// containing class. Otherwise it will return implicit SectionAttr if the
9971 /// function is a definition and there is an active value on CodeSegStack
9972 /// (from the current #pragma code-seg value).
9973 ///
9974 /// \param FD Function being declared.
9975 /// \param IsDefinition Whether it is a definition or just a declarartion.
9976 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
9977 ///          nullptr if no attribute should be added.
9978 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9979                                                        bool IsDefinition) {
9980   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9981     return A;
9982   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9983       CodeSegStack.CurrentValue)
9984     return SectionAttr::CreateImplicit(
9985         getASTContext(), CodeSegStack.CurrentValue->getString(),
9986         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9987         SectionAttr::Declspec_allocate);
9988   return nullptr;
9989 }
9990 
9991 /// Determines if we can perform a correct type check for \p D as a
9992 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
9993 /// best-effort check.
9994 ///
9995 /// \param NewD The new declaration.
9996 /// \param OldD The old declaration.
9997 /// \param NewT The portion of the type of the new declaration to check.
9998 /// \param OldT The portion of the type of the old declaration to check.
9999 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10000                                           QualType NewT, QualType OldT) {
10001   if (!NewD->getLexicalDeclContext()->isDependentContext())
10002     return true;
10003 
10004   // For dependently-typed local extern declarations and friends, we can't
10005   // perform a correct type check in general until instantiation:
10006   //
10007   //   int f();
10008   //   template<typename T> void g() { T f(); }
10009   //
10010   // (valid if g() is only instantiated with T = int).
10011   if (NewT->isDependentType() &&
10012       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10013     return false;
10014 
10015   // Similarly, if the previous declaration was a dependent local extern
10016   // declaration, we don't really know its type yet.
10017   if (OldT->isDependentType() && OldD->isLocalExternDecl())
10018     return false;
10019 
10020   return true;
10021 }
10022 
10023 /// Checks if the new declaration declared in dependent context must be
10024 /// put in the same redeclaration chain as the specified declaration.
10025 ///
10026 /// \param D Declaration that is checked.
10027 /// \param PrevDecl Previous declaration found with proper lookup method for the
10028 ///                 same declaration name.
10029 /// \returns True if D must be added to the redeclaration chain which PrevDecl
10030 ///          belongs to.
10031 ///
10032 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10033   if (!D->getLexicalDeclContext()->isDependentContext())
10034     return true;
10035 
10036   // Don't chain dependent friend function definitions until instantiation, to
10037   // permit cases like
10038   //
10039   //   void func();
10040   //   template<typename T> class C1 { friend void func() {} };
10041   //   template<typename T> class C2 { friend void func() {} };
10042   //
10043   // ... which is valid if only one of C1 and C2 is ever instantiated.
10044   //
10045   // FIXME: This need only apply to function definitions. For now, we proxy
10046   // this by checking for a file-scope function. We do not want this to apply
10047   // to friend declarations nominating member functions, because that gets in
10048   // the way of access checks.
10049   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10050     return false;
10051 
10052   auto *VD = dyn_cast<ValueDecl>(D);
10053   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10054   return !VD || !PrevVD ||
10055          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10056                                         PrevVD->getType());
10057 }
10058 
10059 /// Check the target attribute of the function for MultiVersion
10060 /// validity.
10061 ///
10062 /// Returns true if there was an error, false otherwise.
10063 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10064   const auto *TA = FD->getAttr<TargetAttr>();
10065   assert(TA && "MultiVersion Candidate requires a target attribute");
10066   ParsedTargetAttr ParseInfo = TA->parse();
10067   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10068   enum ErrType { Feature = 0, Architecture = 1 };
10069 
10070   if (!ParseInfo.Architecture.empty() &&
10071       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10072     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10073         << Architecture << ParseInfo.Architecture;
10074     return true;
10075   }
10076 
10077   for (const auto &Feat : ParseInfo.Features) {
10078     auto BareFeat = StringRef{Feat}.substr(1);
10079     if (Feat[0] == '-') {
10080       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10081           << Feature << ("no-" + BareFeat).str();
10082       return true;
10083     }
10084 
10085     if (!TargetInfo.validateCpuSupports(BareFeat) ||
10086         !TargetInfo.isValidFeatureName(BareFeat)) {
10087       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10088           << Feature << BareFeat;
10089       return true;
10090     }
10091   }
10092   return false;
10093 }
10094 
10095 // Provide a white-list of attributes that are allowed to be combined with
10096 // multiversion functions.
10097 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10098                                            MultiVersionKind MVType) {
10099   // Note: this list/diagnosis must match the list in
10100   // checkMultiversionAttributesAllSame.
10101   switch (Kind) {
10102   default:
10103     return false;
10104   case attr::Used:
10105     return MVType == MultiVersionKind::Target;
10106   case attr::NonNull:
10107   case attr::NoThrow:
10108     return true;
10109   }
10110 }
10111 
10112 static bool checkNonMultiVersionCompatAttributes(Sema &S,
10113                                                  const FunctionDecl *FD,
10114                                                  const FunctionDecl *CausedFD,
10115                                                  MultiVersionKind MVType) {
10116   bool IsCPUSpecificCPUDispatchMVType =
10117       MVType == MultiVersionKind::CPUDispatch ||
10118       MVType == MultiVersionKind::CPUSpecific;
10119   const auto Diagnose = [FD, CausedFD, IsCPUSpecificCPUDispatchMVType](
10120                             Sema &S, const Attr *A) {
10121     S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10122         << IsCPUSpecificCPUDispatchMVType << A;
10123     if (CausedFD)
10124       S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10125     return true;
10126   };
10127 
10128   for (const Attr *A : FD->attrs()) {
10129     switch (A->getKind()) {
10130     case attr::CPUDispatch:
10131     case attr::CPUSpecific:
10132       if (MVType != MultiVersionKind::CPUDispatch &&
10133           MVType != MultiVersionKind::CPUSpecific)
10134         return Diagnose(S, A);
10135       break;
10136     case attr::Target:
10137       if (MVType != MultiVersionKind::Target)
10138         return Diagnose(S, A);
10139       break;
10140     default:
10141       if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType))
10142         return Diagnose(S, A);
10143       break;
10144     }
10145   }
10146   return false;
10147 }
10148 
10149 bool Sema::areMultiversionVariantFunctionsCompatible(
10150     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10151     const PartialDiagnostic &NoProtoDiagID,
10152     const PartialDiagnosticAt &NoteCausedDiagIDAt,
10153     const PartialDiagnosticAt &NoSupportDiagIDAt,
10154     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10155     bool ConstexprSupported, bool CLinkageMayDiffer) {
10156   enum DoesntSupport {
10157     FuncTemplates = 0,
10158     VirtFuncs = 1,
10159     DeducedReturn = 2,
10160     Constructors = 3,
10161     Destructors = 4,
10162     DeletedFuncs = 5,
10163     DefaultedFuncs = 6,
10164     ConstexprFuncs = 7,
10165     ConstevalFuncs = 8,
10166   };
10167   enum Different {
10168     CallingConv = 0,
10169     ReturnType = 1,
10170     ConstexprSpec = 2,
10171     InlineSpec = 3,
10172     StorageClass = 4,
10173     Linkage = 5,
10174   };
10175 
10176   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10177       !OldFD->getType()->getAs<FunctionProtoType>()) {
10178     Diag(OldFD->getLocation(), NoProtoDiagID);
10179     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10180     return true;
10181   }
10182 
10183   if (NoProtoDiagID.getDiagID() != 0 &&
10184       !NewFD->getType()->getAs<FunctionProtoType>())
10185     return Diag(NewFD->getLocation(), NoProtoDiagID);
10186 
10187   if (!TemplatesSupported &&
10188       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10189     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10190            << FuncTemplates;
10191 
10192   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10193     if (NewCXXFD->isVirtual())
10194       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10195              << VirtFuncs;
10196 
10197     if (isa<CXXConstructorDecl>(NewCXXFD))
10198       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10199              << Constructors;
10200 
10201     if (isa<CXXDestructorDecl>(NewCXXFD))
10202       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10203              << Destructors;
10204   }
10205 
10206   if (NewFD->isDeleted())
10207     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10208            << DeletedFuncs;
10209 
10210   if (NewFD->isDefaulted())
10211     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10212            << DefaultedFuncs;
10213 
10214   if (!ConstexprSupported && NewFD->isConstexpr())
10215     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10216            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10217 
10218   QualType NewQType = Context.getCanonicalType(NewFD->getType());
10219   const auto *NewType = cast<FunctionType>(NewQType);
10220   QualType NewReturnType = NewType->getReturnType();
10221 
10222   if (NewReturnType->isUndeducedType())
10223     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10224            << DeducedReturn;
10225 
10226   // Ensure the return type is identical.
10227   if (OldFD) {
10228     QualType OldQType = Context.getCanonicalType(OldFD->getType());
10229     const auto *OldType = cast<FunctionType>(OldQType);
10230     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10231     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10232 
10233     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10234       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10235 
10236     QualType OldReturnType = OldType->getReturnType();
10237 
10238     if (OldReturnType != NewReturnType)
10239       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10240 
10241     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10242       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10243 
10244     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10245       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10246 
10247     if (OldFD->getStorageClass() != NewFD->getStorageClass())
10248       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass;
10249 
10250     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10251       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10252 
10253     if (CheckEquivalentExceptionSpec(
10254             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10255             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10256       return true;
10257   }
10258   return false;
10259 }
10260 
10261 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10262                                              const FunctionDecl *NewFD,
10263                                              bool CausesMV,
10264                                              MultiVersionKind MVType) {
10265   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10266     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10267     if (OldFD)
10268       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10269     return true;
10270   }
10271 
10272   bool IsCPUSpecificCPUDispatchMVType =
10273       MVType == MultiVersionKind::CPUDispatch ||
10274       MVType == MultiVersionKind::CPUSpecific;
10275 
10276   if (CausesMV && OldFD &&
10277       checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType))
10278     return true;
10279 
10280   if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType))
10281     return true;
10282 
10283   // Only allow transition to MultiVersion if it hasn't been used.
10284   if (OldFD && CausesMV && OldFD->isUsed(false))
10285     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10286 
10287   return S.areMultiversionVariantFunctionsCompatible(
10288       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10289       PartialDiagnosticAt(NewFD->getLocation(),
10290                           S.PDiag(diag::note_multiversioning_caused_here)),
10291       PartialDiagnosticAt(NewFD->getLocation(),
10292                           S.PDiag(diag::err_multiversion_doesnt_support)
10293                               << IsCPUSpecificCPUDispatchMVType),
10294       PartialDiagnosticAt(NewFD->getLocation(),
10295                           S.PDiag(diag::err_multiversion_diff)),
10296       /*TemplatesSupported=*/false,
10297       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
10298       /*CLinkageMayDiffer=*/false);
10299 }
10300 
10301 /// Check the validity of a multiversion function declaration that is the
10302 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10303 ///
10304 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10305 ///
10306 /// Returns true if there was an error, false otherwise.
10307 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10308                                            MultiVersionKind MVType,
10309                                            const TargetAttr *TA) {
10310   assert(MVType != MultiVersionKind::None &&
10311          "Function lacks multiversion attribute");
10312 
10313   // Target only causes MV if it is default, otherwise this is a normal
10314   // function.
10315   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
10316     return false;
10317 
10318   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10319     FD->setInvalidDecl();
10320     return true;
10321   }
10322 
10323   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
10324     FD->setInvalidDecl();
10325     return true;
10326   }
10327 
10328   FD->setIsMultiVersion();
10329   return false;
10330 }
10331 
10332 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10333   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10334     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10335       return true;
10336   }
10337 
10338   return false;
10339 }
10340 
10341 static bool CheckTargetCausesMultiVersioning(
10342     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10343     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10344     LookupResult &Previous) {
10345   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10346   ParsedTargetAttr NewParsed = NewTA->parse();
10347   // Sort order doesn't matter, it just needs to be consistent.
10348   llvm::sort(NewParsed.Features);
10349 
10350   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10351   // to change, this is a simple redeclaration.
10352   if (!NewTA->isDefaultVersion() &&
10353       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10354     return false;
10355 
10356   // Otherwise, this decl causes MultiVersioning.
10357   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10358     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10359     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10360     NewFD->setInvalidDecl();
10361     return true;
10362   }
10363 
10364   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10365                                        MultiVersionKind::Target)) {
10366     NewFD->setInvalidDecl();
10367     return true;
10368   }
10369 
10370   if (CheckMultiVersionValue(S, NewFD)) {
10371     NewFD->setInvalidDecl();
10372     return true;
10373   }
10374 
10375   // If this is 'default', permit the forward declaration.
10376   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10377     Redeclaration = true;
10378     OldDecl = OldFD;
10379     OldFD->setIsMultiVersion();
10380     NewFD->setIsMultiVersion();
10381     return false;
10382   }
10383 
10384   if (CheckMultiVersionValue(S, OldFD)) {
10385     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10386     NewFD->setInvalidDecl();
10387     return true;
10388   }
10389 
10390   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10391 
10392   if (OldParsed == NewParsed) {
10393     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10394     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10395     NewFD->setInvalidDecl();
10396     return true;
10397   }
10398 
10399   for (const auto *FD : OldFD->redecls()) {
10400     const auto *CurTA = FD->getAttr<TargetAttr>();
10401     // We allow forward declarations before ANY multiversioning attributes, but
10402     // nothing after the fact.
10403     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10404         (!CurTA || CurTA->isInherited())) {
10405       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10406           << 0;
10407       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10408       NewFD->setInvalidDecl();
10409       return true;
10410     }
10411   }
10412 
10413   OldFD->setIsMultiVersion();
10414   NewFD->setIsMultiVersion();
10415   Redeclaration = false;
10416   MergeTypeWithPrevious = false;
10417   OldDecl = nullptr;
10418   Previous.clear();
10419   return false;
10420 }
10421 
10422 /// Check the validity of a new function declaration being added to an existing
10423 /// multiversioned declaration collection.
10424 static bool CheckMultiVersionAdditionalDecl(
10425     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10426     MultiVersionKind NewMVType, const TargetAttr *NewTA,
10427     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10428     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10429     LookupResult &Previous) {
10430 
10431   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10432   // Disallow mixing of multiversioning types.
10433   if ((OldMVType == MultiVersionKind::Target &&
10434        NewMVType != MultiVersionKind::Target) ||
10435       (NewMVType == MultiVersionKind::Target &&
10436        OldMVType != MultiVersionKind::Target)) {
10437     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10438     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10439     NewFD->setInvalidDecl();
10440     return true;
10441   }
10442 
10443   ParsedTargetAttr NewParsed;
10444   if (NewTA) {
10445     NewParsed = NewTA->parse();
10446     llvm::sort(NewParsed.Features);
10447   }
10448 
10449   bool UseMemberUsingDeclRules =
10450       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10451 
10452   // Next, check ALL non-overloads to see if this is a redeclaration of a
10453   // previous member of the MultiVersion set.
10454   for (NamedDecl *ND : Previous) {
10455     FunctionDecl *CurFD = ND->getAsFunction();
10456     if (!CurFD)
10457       continue;
10458     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10459       continue;
10460 
10461     if (NewMVType == MultiVersionKind::Target) {
10462       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10463       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10464         NewFD->setIsMultiVersion();
10465         Redeclaration = true;
10466         OldDecl = ND;
10467         return false;
10468       }
10469 
10470       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10471       if (CurParsed == NewParsed) {
10472         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10473         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10474         NewFD->setInvalidDecl();
10475         return true;
10476       }
10477     } else {
10478       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10479       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10480       // Handle CPUDispatch/CPUSpecific versions.
10481       // Only 1 CPUDispatch function is allowed, this will make it go through
10482       // the redeclaration errors.
10483       if (NewMVType == MultiVersionKind::CPUDispatch &&
10484           CurFD->hasAttr<CPUDispatchAttr>()) {
10485         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10486             std::equal(
10487                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10488                 NewCPUDisp->cpus_begin(),
10489                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10490                   return Cur->getName() == New->getName();
10491                 })) {
10492           NewFD->setIsMultiVersion();
10493           Redeclaration = true;
10494           OldDecl = ND;
10495           return false;
10496         }
10497 
10498         // If the declarations don't match, this is an error condition.
10499         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10500         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10501         NewFD->setInvalidDecl();
10502         return true;
10503       }
10504       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10505 
10506         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10507             std::equal(
10508                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10509                 NewCPUSpec->cpus_begin(),
10510                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10511                   return Cur->getName() == New->getName();
10512                 })) {
10513           NewFD->setIsMultiVersion();
10514           Redeclaration = true;
10515           OldDecl = ND;
10516           return false;
10517         }
10518 
10519         // Only 1 version of CPUSpecific is allowed for each CPU.
10520         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10521           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10522             if (CurII == NewII) {
10523               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10524                   << NewII;
10525               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10526               NewFD->setInvalidDecl();
10527               return true;
10528             }
10529           }
10530         }
10531       }
10532       // If the two decls aren't the same MVType, there is no possible error
10533       // condition.
10534     }
10535   }
10536 
10537   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10538   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10539   // handled in the attribute adding step.
10540   if (NewMVType == MultiVersionKind::Target &&
10541       CheckMultiVersionValue(S, NewFD)) {
10542     NewFD->setInvalidDecl();
10543     return true;
10544   }
10545 
10546   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10547                                        !OldFD->isMultiVersion(), NewMVType)) {
10548     NewFD->setInvalidDecl();
10549     return true;
10550   }
10551 
10552   // Permit forward declarations in the case where these two are compatible.
10553   if (!OldFD->isMultiVersion()) {
10554     OldFD->setIsMultiVersion();
10555     NewFD->setIsMultiVersion();
10556     Redeclaration = true;
10557     OldDecl = OldFD;
10558     return false;
10559   }
10560 
10561   NewFD->setIsMultiVersion();
10562   Redeclaration = false;
10563   MergeTypeWithPrevious = false;
10564   OldDecl = nullptr;
10565   Previous.clear();
10566   return false;
10567 }
10568 
10569 
10570 /// Check the validity of a mulitversion function declaration.
10571 /// Also sets the multiversion'ness' of the function itself.
10572 ///
10573 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10574 ///
10575 /// Returns true if there was an error, false otherwise.
10576 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10577                                       bool &Redeclaration, NamedDecl *&OldDecl,
10578                                       bool &MergeTypeWithPrevious,
10579                                       LookupResult &Previous) {
10580   const auto *NewTA = NewFD->getAttr<TargetAttr>();
10581   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10582   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10583 
10584   // Mixing Multiversioning types is prohibited.
10585   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
10586       (NewCPUDisp && NewCPUSpec)) {
10587     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10588     NewFD->setInvalidDecl();
10589     return true;
10590   }
10591 
10592   MultiVersionKind  MVType = NewFD->getMultiVersionKind();
10593 
10594   // Main isn't allowed to become a multiversion function, however it IS
10595   // permitted to have 'main' be marked with the 'target' optimization hint.
10596   if (NewFD->isMain()) {
10597     if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10598         MVType == MultiVersionKind::CPUDispatch ||
10599         MVType == MultiVersionKind::CPUSpecific) {
10600       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10601       NewFD->setInvalidDecl();
10602       return true;
10603     }
10604     return false;
10605   }
10606 
10607   if (!OldDecl || !OldDecl->getAsFunction() ||
10608       OldDecl->getDeclContext()->getRedeclContext() !=
10609           NewFD->getDeclContext()->getRedeclContext()) {
10610     // If there's no previous declaration, AND this isn't attempting to cause
10611     // multiversioning, this isn't an error condition.
10612     if (MVType == MultiVersionKind::None)
10613       return false;
10614     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10615   }
10616 
10617   FunctionDecl *OldFD = OldDecl->getAsFunction();
10618 
10619   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10620     return false;
10621 
10622   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10623     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10624         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10625     NewFD->setInvalidDecl();
10626     return true;
10627   }
10628 
10629   // Handle the target potentially causes multiversioning case.
10630   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10631     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10632                                             Redeclaration, OldDecl,
10633                                             MergeTypeWithPrevious, Previous);
10634 
10635   // At this point, we have a multiversion function decl (in OldFD) AND an
10636   // appropriate attribute in the current function decl.  Resolve that these are
10637   // still compatible with previous declarations.
10638   return CheckMultiVersionAdditionalDecl(
10639       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10640       OldDecl, MergeTypeWithPrevious, Previous);
10641 }
10642 
10643 /// Perform semantic checking of a new function declaration.
10644 ///
10645 /// Performs semantic analysis of the new function declaration
10646 /// NewFD. This routine performs all semantic checking that does not
10647 /// require the actual declarator involved in the declaration, and is
10648 /// used both for the declaration of functions as they are parsed
10649 /// (called via ActOnDeclarator) and for the declaration of functions
10650 /// that have been instantiated via C++ template instantiation (called
10651 /// via InstantiateDecl).
10652 ///
10653 /// \param IsMemberSpecialization whether this new function declaration is
10654 /// a member specialization (that replaces any definition provided by the
10655 /// previous declaration).
10656 ///
10657 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10658 ///
10659 /// \returns true if the function declaration is a redeclaration.
10660 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10661                                     LookupResult &Previous,
10662                                     bool IsMemberSpecialization) {
10663   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10664          "Variably modified return types are not handled here");
10665 
10666   // Determine whether the type of this function should be merged with
10667   // a previous visible declaration. This never happens for functions in C++,
10668   // and always happens in C if the previous declaration was visible.
10669   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10670                                !Previous.isShadowed();
10671 
10672   bool Redeclaration = false;
10673   NamedDecl *OldDecl = nullptr;
10674   bool MayNeedOverloadableChecks = false;
10675 
10676   // Merge or overload the declaration with an existing declaration of
10677   // the same name, if appropriate.
10678   if (!Previous.empty()) {
10679     // Determine whether NewFD is an overload of PrevDecl or
10680     // a declaration that requires merging. If it's an overload,
10681     // there's no more work to do here; we'll just add the new
10682     // function to the scope.
10683     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10684       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10685       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10686         Redeclaration = true;
10687         OldDecl = Candidate;
10688       }
10689     } else {
10690       MayNeedOverloadableChecks = true;
10691       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10692                             /*NewIsUsingDecl*/ false)) {
10693       case Ovl_Match:
10694         Redeclaration = true;
10695         break;
10696 
10697       case Ovl_NonFunction:
10698         Redeclaration = true;
10699         break;
10700 
10701       case Ovl_Overload:
10702         Redeclaration = false;
10703         break;
10704       }
10705     }
10706   }
10707 
10708   // Check for a previous extern "C" declaration with this name.
10709   if (!Redeclaration &&
10710       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10711     if (!Previous.empty()) {
10712       // This is an extern "C" declaration with the same name as a previous
10713       // declaration, and thus redeclares that entity...
10714       Redeclaration = true;
10715       OldDecl = Previous.getFoundDecl();
10716       MergeTypeWithPrevious = false;
10717 
10718       // ... except in the presence of __attribute__((overloadable)).
10719       if (OldDecl->hasAttr<OverloadableAttr>() ||
10720           NewFD->hasAttr<OverloadableAttr>()) {
10721         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10722           MayNeedOverloadableChecks = true;
10723           Redeclaration = false;
10724           OldDecl = nullptr;
10725         }
10726       }
10727     }
10728   }
10729 
10730   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10731                                 MergeTypeWithPrevious, Previous))
10732     return Redeclaration;
10733 
10734   // PPC MMA non-pointer types are not allowed as function return types.
10735   if (Context.getTargetInfo().getTriple().isPPC64() &&
10736       CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
10737     NewFD->setInvalidDecl();
10738   }
10739 
10740   // C++11 [dcl.constexpr]p8:
10741   //   A constexpr specifier for a non-static member function that is not
10742   //   a constructor declares that member function to be const.
10743   //
10744   // This needs to be delayed until we know whether this is an out-of-line
10745   // definition of a static member function.
10746   //
10747   // This rule is not present in C++1y, so we produce a backwards
10748   // compatibility warning whenever it happens in C++11.
10749   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10750   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10751       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10752       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10753     CXXMethodDecl *OldMD = nullptr;
10754     if (OldDecl)
10755       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10756     if (!OldMD || !OldMD->isStatic()) {
10757       const FunctionProtoType *FPT =
10758         MD->getType()->castAs<FunctionProtoType>();
10759       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10760       EPI.TypeQuals.addConst();
10761       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10762                                           FPT->getParamTypes(), EPI));
10763 
10764       // Warn that we did this, if we're not performing template instantiation.
10765       // In that case, we'll have warned already when the template was defined.
10766       if (!inTemplateInstantiation()) {
10767         SourceLocation AddConstLoc;
10768         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10769                 .IgnoreParens().getAs<FunctionTypeLoc>())
10770           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10771 
10772         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10773           << FixItHint::CreateInsertion(AddConstLoc, " const");
10774       }
10775     }
10776   }
10777 
10778   if (Redeclaration) {
10779     // NewFD and OldDecl represent declarations that need to be
10780     // merged.
10781     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10782       NewFD->setInvalidDecl();
10783       return Redeclaration;
10784     }
10785 
10786     Previous.clear();
10787     Previous.addDecl(OldDecl);
10788 
10789     if (FunctionTemplateDecl *OldTemplateDecl =
10790             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10791       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10792       FunctionTemplateDecl *NewTemplateDecl
10793         = NewFD->getDescribedFunctionTemplate();
10794       assert(NewTemplateDecl && "Template/non-template mismatch");
10795 
10796       // The call to MergeFunctionDecl above may have created some state in
10797       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10798       // can add it as a redeclaration.
10799       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10800 
10801       NewFD->setPreviousDeclaration(OldFD);
10802       if (NewFD->isCXXClassMember()) {
10803         NewFD->setAccess(OldTemplateDecl->getAccess());
10804         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10805       }
10806 
10807       // If this is an explicit specialization of a member that is a function
10808       // template, mark it as a member specialization.
10809       if (IsMemberSpecialization &&
10810           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10811         NewTemplateDecl->setMemberSpecialization();
10812         assert(OldTemplateDecl->isMemberSpecialization());
10813         // Explicit specializations of a member template do not inherit deleted
10814         // status from the parent member template that they are specializing.
10815         if (OldFD->isDeleted()) {
10816           // FIXME: This assert will not hold in the presence of modules.
10817           assert(OldFD->getCanonicalDecl() == OldFD);
10818           // FIXME: We need an update record for this AST mutation.
10819           OldFD->setDeletedAsWritten(false);
10820         }
10821       }
10822 
10823     } else {
10824       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10825         auto *OldFD = cast<FunctionDecl>(OldDecl);
10826         // This needs to happen first so that 'inline' propagates.
10827         NewFD->setPreviousDeclaration(OldFD);
10828         if (NewFD->isCXXClassMember())
10829           NewFD->setAccess(OldFD->getAccess());
10830       }
10831     }
10832   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10833              !NewFD->getAttr<OverloadableAttr>()) {
10834     assert((Previous.empty() ||
10835             llvm::any_of(Previous,
10836                          [](const NamedDecl *ND) {
10837                            return ND->hasAttr<OverloadableAttr>();
10838                          })) &&
10839            "Non-redecls shouldn't happen without overloadable present");
10840 
10841     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10842       const auto *FD = dyn_cast<FunctionDecl>(ND);
10843       return FD && !FD->hasAttr<OverloadableAttr>();
10844     });
10845 
10846     if (OtherUnmarkedIter != Previous.end()) {
10847       Diag(NewFD->getLocation(),
10848            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10849       Diag((*OtherUnmarkedIter)->getLocation(),
10850            diag::note_attribute_overloadable_prev_overload)
10851           << false;
10852 
10853       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10854     }
10855   }
10856 
10857   if (LangOpts.OpenMP)
10858     ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
10859 
10860   // Semantic checking for this function declaration (in isolation).
10861 
10862   if (getLangOpts().CPlusPlus) {
10863     // C++-specific checks.
10864     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10865       CheckConstructor(Constructor);
10866     } else if (CXXDestructorDecl *Destructor =
10867                 dyn_cast<CXXDestructorDecl>(NewFD)) {
10868       CXXRecordDecl *Record = Destructor->getParent();
10869       QualType ClassType = Context.getTypeDeclType(Record);
10870 
10871       // FIXME: Shouldn't we be able to perform this check even when the class
10872       // type is dependent? Both gcc and edg can handle that.
10873       if (!ClassType->isDependentType()) {
10874         DeclarationName Name
10875           = Context.DeclarationNames.getCXXDestructorName(
10876                                         Context.getCanonicalType(ClassType));
10877         if (NewFD->getDeclName() != Name) {
10878           Diag(NewFD->getLocation(), diag::err_destructor_name);
10879           NewFD->setInvalidDecl();
10880           return Redeclaration;
10881         }
10882       }
10883     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10884       if (auto *TD = Guide->getDescribedFunctionTemplate())
10885         CheckDeductionGuideTemplate(TD);
10886 
10887       // A deduction guide is not on the list of entities that can be
10888       // explicitly specialized.
10889       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10890         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10891             << /*explicit specialization*/ 1;
10892     }
10893 
10894     // Find any virtual functions that this function overrides.
10895     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10896       if (!Method->isFunctionTemplateSpecialization() &&
10897           !Method->getDescribedFunctionTemplate() &&
10898           Method->isCanonicalDecl()) {
10899         AddOverriddenMethods(Method->getParent(), Method);
10900       }
10901       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
10902         // C++2a [class.virtual]p6
10903         // A virtual method shall not have a requires-clause.
10904         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
10905              diag::err_constrained_virtual_method);
10906 
10907       if (Method->isStatic())
10908         checkThisInStaticMemberFunctionType(Method);
10909     }
10910 
10911     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
10912       ActOnConversionDeclarator(Conversion);
10913 
10914     // Extra checking for C++ overloaded operators (C++ [over.oper]).
10915     if (NewFD->isOverloadedOperator() &&
10916         CheckOverloadedOperatorDeclaration(NewFD)) {
10917       NewFD->setInvalidDecl();
10918       return Redeclaration;
10919     }
10920 
10921     // Extra checking for C++0x literal operators (C++0x [over.literal]).
10922     if (NewFD->getLiteralIdentifier() &&
10923         CheckLiteralOperatorDeclaration(NewFD)) {
10924       NewFD->setInvalidDecl();
10925       return Redeclaration;
10926     }
10927 
10928     // In C++, check default arguments now that we have merged decls. Unless
10929     // the lexical context is the class, because in this case this is done
10930     // during delayed parsing anyway.
10931     if (!CurContext->isRecord())
10932       CheckCXXDefaultArguments(NewFD);
10933 
10934     // If this function declares a builtin function, check the type of this
10935     // declaration against the expected type for the builtin.
10936     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10937       ASTContext::GetBuiltinTypeError Error;
10938       LookupNecessaryTypesForBuiltin(S, BuiltinID);
10939       QualType T = Context.GetBuiltinType(BuiltinID, Error);
10940       // If the type of the builtin differs only in its exception
10941       // specification, that's OK.
10942       // FIXME: If the types do differ in this way, it would be better to
10943       // retain the 'noexcept' form of the type.
10944       if (!T.isNull() &&
10945           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10946                                                             NewFD->getType()))
10947         // The type of this function differs from the type of the builtin,
10948         // so forget about the builtin entirely.
10949         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10950     }
10951 
10952     // If this function is declared as being extern "C", then check to see if
10953     // the function returns a UDT (class, struct, or union type) that is not C
10954     // compatible, and if it does, warn the user.
10955     // But, issue any diagnostic on the first declaration only.
10956     if (Previous.empty() && NewFD->isExternC()) {
10957       QualType R = NewFD->getReturnType();
10958       if (R->isIncompleteType() && !R->isVoidType())
10959         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10960             << NewFD << R;
10961       else if (!R.isPODType(Context) && !R->isVoidType() &&
10962                !R->isObjCObjectPointerType())
10963         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10964     }
10965 
10966     // C++1z [dcl.fct]p6:
10967     //   [...] whether the function has a non-throwing exception-specification
10968     //   [is] part of the function type
10969     //
10970     // This results in an ABI break between C++14 and C++17 for functions whose
10971     // declared type includes an exception-specification in a parameter or
10972     // return type. (Exception specifications on the function itself are OK in
10973     // most cases, and exception specifications are not permitted in most other
10974     // contexts where they could make it into a mangling.)
10975     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10976       auto HasNoexcept = [&](QualType T) -> bool {
10977         // Strip off declarator chunks that could be between us and a function
10978         // type. We don't need to look far, exception specifications are very
10979         // restricted prior to C++17.
10980         if (auto *RT = T->getAs<ReferenceType>())
10981           T = RT->getPointeeType();
10982         else if (T->isAnyPointerType())
10983           T = T->getPointeeType();
10984         else if (auto *MPT = T->getAs<MemberPointerType>())
10985           T = MPT->getPointeeType();
10986         if (auto *FPT = T->getAs<FunctionProtoType>())
10987           if (FPT->isNothrow())
10988             return true;
10989         return false;
10990       };
10991 
10992       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10993       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10994       for (QualType T : FPT->param_types())
10995         AnyNoexcept |= HasNoexcept(T);
10996       if (AnyNoexcept)
10997         Diag(NewFD->getLocation(),
10998              diag::warn_cxx17_compat_exception_spec_in_signature)
10999             << NewFD;
11000     }
11001 
11002     if (!Redeclaration && LangOpts.CUDA)
11003       checkCUDATargetOverload(NewFD, Previous);
11004   }
11005   return Redeclaration;
11006 }
11007 
11008 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
11009   // C++11 [basic.start.main]p3:
11010   //   A program that [...] declares main to be inline, static or
11011   //   constexpr is ill-formed.
11012   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
11013   //   appear in a declaration of main.
11014   // static main is not an error under C99, but we should warn about it.
11015   // We accept _Noreturn main as an extension.
11016   if (FD->getStorageClass() == SC_Static)
11017     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
11018          ? diag::err_static_main : diag::warn_static_main)
11019       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
11020   if (FD->isInlineSpecified())
11021     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
11022       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
11023   if (DS.isNoreturnSpecified()) {
11024     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
11025     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
11026     Diag(NoreturnLoc, diag::ext_noreturn_main);
11027     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
11028       << FixItHint::CreateRemoval(NoreturnRange);
11029   }
11030   if (FD->isConstexpr()) {
11031     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
11032         << FD->isConsteval()
11033         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
11034     FD->setConstexprKind(ConstexprSpecKind::Unspecified);
11035   }
11036 
11037   if (getLangOpts().OpenCL) {
11038     Diag(FD->getLocation(), diag::err_opencl_no_main)
11039         << FD->hasAttr<OpenCLKernelAttr>();
11040     FD->setInvalidDecl();
11041     return;
11042   }
11043 
11044   QualType T = FD->getType();
11045   assert(T->isFunctionType() && "function decl is not of function type");
11046   const FunctionType* FT = T->castAs<FunctionType>();
11047 
11048   // Set default calling convention for main()
11049   if (FT->getCallConv() != CC_C) {
11050     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
11051     FD->setType(QualType(FT, 0));
11052     T = Context.getCanonicalType(FD->getType());
11053   }
11054 
11055   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
11056     // In C with GNU extensions we allow main() to have non-integer return
11057     // type, but we should warn about the extension, and we disable the
11058     // implicit-return-zero rule.
11059 
11060     // GCC in C mode accepts qualified 'int'.
11061     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
11062       FD->setHasImplicitReturnZero(true);
11063     else {
11064       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
11065       SourceRange RTRange = FD->getReturnTypeSourceRange();
11066       if (RTRange.isValid())
11067         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
11068             << FixItHint::CreateReplacement(RTRange, "int");
11069     }
11070   } else {
11071     // In C and C++, main magically returns 0 if you fall off the end;
11072     // set the flag which tells us that.
11073     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11074 
11075     // All the standards say that main() should return 'int'.
11076     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
11077       FD->setHasImplicitReturnZero(true);
11078     else {
11079       // Otherwise, this is just a flat-out error.
11080       SourceRange RTRange = FD->getReturnTypeSourceRange();
11081       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11082           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11083                                 : FixItHint());
11084       FD->setInvalidDecl(true);
11085     }
11086   }
11087 
11088   // Treat protoless main() as nullary.
11089   if (isa<FunctionNoProtoType>(FT)) return;
11090 
11091   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11092   unsigned nparams = FTP->getNumParams();
11093   assert(FD->getNumParams() == nparams);
11094 
11095   bool HasExtraParameters = (nparams > 3);
11096 
11097   if (FTP->isVariadic()) {
11098     Diag(FD->getLocation(), diag::ext_variadic_main);
11099     // FIXME: if we had information about the location of the ellipsis, we
11100     // could add a FixIt hint to remove it as a parameter.
11101   }
11102 
11103   // Darwin passes an undocumented fourth argument of type char**.  If
11104   // other platforms start sprouting these, the logic below will start
11105   // getting shifty.
11106   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11107     HasExtraParameters = false;
11108 
11109   if (HasExtraParameters) {
11110     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11111     FD->setInvalidDecl(true);
11112     nparams = 3;
11113   }
11114 
11115   // FIXME: a lot of the following diagnostics would be improved
11116   // if we had some location information about types.
11117 
11118   QualType CharPP =
11119     Context.getPointerType(Context.getPointerType(Context.CharTy));
11120   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11121 
11122   for (unsigned i = 0; i < nparams; ++i) {
11123     QualType AT = FTP->getParamType(i);
11124 
11125     bool mismatch = true;
11126 
11127     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11128       mismatch = false;
11129     else if (Expected[i] == CharPP) {
11130       // As an extension, the following forms are okay:
11131       //   char const **
11132       //   char const * const *
11133       //   char * const *
11134 
11135       QualifierCollector qs;
11136       const PointerType* PT;
11137       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11138           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11139           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11140                               Context.CharTy)) {
11141         qs.removeConst();
11142         mismatch = !qs.empty();
11143       }
11144     }
11145 
11146     if (mismatch) {
11147       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11148       // TODO: suggest replacing given type with expected type
11149       FD->setInvalidDecl(true);
11150     }
11151   }
11152 
11153   if (nparams == 1 && !FD->isInvalidDecl()) {
11154     Diag(FD->getLocation(), diag::warn_main_one_arg);
11155   }
11156 
11157   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11158     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11159     FD->setInvalidDecl();
11160   }
11161 }
11162 
11163 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11164   QualType T = FD->getType();
11165   assert(T->isFunctionType() && "function decl is not of function type");
11166   const FunctionType *FT = T->castAs<FunctionType>();
11167 
11168   // Set an implicit return of 'zero' if the function can return some integral,
11169   // enumeration, pointer or nullptr type.
11170   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11171       FT->getReturnType()->isAnyPointerType() ||
11172       FT->getReturnType()->isNullPtrType())
11173     // DllMain is exempt because a return value of zero means it failed.
11174     if (FD->getName() != "DllMain")
11175       FD->setHasImplicitReturnZero(true);
11176 
11177   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11178     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11179     FD->setInvalidDecl();
11180   }
11181 }
11182 
11183 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11184   // FIXME: Need strict checking.  In C89, we need to check for
11185   // any assignment, increment, decrement, function-calls, or
11186   // commas outside of a sizeof.  In C99, it's the same list,
11187   // except that the aforementioned are allowed in unevaluated
11188   // expressions.  Everything else falls under the
11189   // "may accept other forms of constant expressions" exception.
11190   //
11191   // Regular C++ code will not end up here (exceptions: language extensions,
11192   // OpenCL C++ etc), so the constant expression rules there don't matter.
11193   if (Init->isValueDependent()) {
11194     assert(Init->containsErrors() &&
11195            "Dependent code should only occur in error-recovery path.");
11196     return true;
11197   }
11198   const Expr *Culprit;
11199   if (Init->isConstantInitializer(Context, false, &Culprit))
11200     return false;
11201   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11202     << Culprit->getSourceRange();
11203   return true;
11204 }
11205 
11206 namespace {
11207   // Visits an initialization expression to see if OrigDecl is evaluated in
11208   // its own initialization and throws a warning if it does.
11209   class SelfReferenceChecker
11210       : public EvaluatedExprVisitor<SelfReferenceChecker> {
11211     Sema &S;
11212     Decl *OrigDecl;
11213     bool isRecordType;
11214     bool isPODType;
11215     bool isReferenceType;
11216 
11217     bool isInitList;
11218     llvm::SmallVector<unsigned, 4> InitFieldIndex;
11219 
11220   public:
11221     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11222 
11223     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11224                                                     S(S), OrigDecl(OrigDecl) {
11225       isPODType = false;
11226       isRecordType = false;
11227       isReferenceType = false;
11228       isInitList = false;
11229       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11230         isPODType = VD->getType().isPODType(S.Context);
11231         isRecordType = VD->getType()->isRecordType();
11232         isReferenceType = VD->getType()->isReferenceType();
11233       }
11234     }
11235 
11236     // For most expressions, just call the visitor.  For initializer lists,
11237     // track the index of the field being initialized since fields are
11238     // initialized in order allowing use of previously initialized fields.
11239     void CheckExpr(Expr *E) {
11240       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11241       if (!InitList) {
11242         Visit(E);
11243         return;
11244       }
11245 
11246       // Track and increment the index here.
11247       isInitList = true;
11248       InitFieldIndex.push_back(0);
11249       for (auto Child : InitList->children()) {
11250         CheckExpr(cast<Expr>(Child));
11251         ++InitFieldIndex.back();
11252       }
11253       InitFieldIndex.pop_back();
11254     }
11255 
11256     // Returns true if MemberExpr is checked and no further checking is needed.
11257     // Returns false if additional checking is required.
11258     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11259       llvm::SmallVector<FieldDecl*, 4> Fields;
11260       Expr *Base = E;
11261       bool ReferenceField = false;
11262 
11263       // Get the field members used.
11264       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11265         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11266         if (!FD)
11267           return false;
11268         Fields.push_back(FD);
11269         if (FD->getType()->isReferenceType())
11270           ReferenceField = true;
11271         Base = ME->getBase()->IgnoreParenImpCasts();
11272       }
11273 
11274       // Keep checking only if the base Decl is the same.
11275       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11276       if (!DRE || DRE->getDecl() != OrigDecl)
11277         return false;
11278 
11279       // A reference field can be bound to an unininitialized field.
11280       if (CheckReference && !ReferenceField)
11281         return true;
11282 
11283       // Convert FieldDecls to their index number.
11284       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11285       for (const FieldDecl *I : llvm::reverse(Fields))
11286         UsedFieldIndex.push_back(I->getFieldIndex());
11287 
11288       // See if a warning is needed by checking the first difference in index
11289       // numbers.  If field being used has index less than the field being
11290       // initialized, then the use is safe.
11291       for (auto UsedIter = UsedFieldIndex.begin(),
11292                 UsedEnd = UsedFieldIndex.end(),
11293                 OrigIter = InitFieldIndex.begin(),
11294                 OrigEnd = InitFieldIndex.end();
11295            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11296         if (*UsedIter < *OrigIter)
11297           return true;
11298         if (*UsedIter > *OrigIter)
11299           break;
11300       }
11301 
11302       // TODO: Add a different warning which will print the field names.
11303       HandleDeclRefExpr(DRE);
11304       return true;
11305     }
11306 
11307     // For most expressions, the cast is directly above the DeclRefExpr.
11308     // For conditional operators, the cast can be outside the conditional
11309     // operator if both expressions are DeclRefExpr's.
11310     void HandleValue(Expr *E) {
11311       E = E->IgnoreParens();
11312       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11313         HandleDeclRefExpr(DRE);
11314         return;
11315       }
11316 
11317       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11318         Visit(CO->getCond());
11319         HandleValue(CO->getTrueExpr());
11320         HandleValue(CO->getFalseExpr());
11321         return;
11322       }
11323 
11324       if (BinaryConditionalOperator *BCO =
11325               dyn_cast<BinaryConditionalOperator>(E)) {
11326         Visit(BCO->getCond());
11327         HandleValue(BCO->getFalseExpr());
11328         return;
11329       }
11330 
11331       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11332         HandleValue(OVE->getSourceExpr());
11333         return;
11334       }
11335 
11336       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11337         if (BO->getOpcode() == BO_Comma) {
11338           Visit(BO->getLHS());
11339           HandleValue(BO->getRHS());
11340           return;
11341         }
11342       }
11343 
11344       if (isa<MemberExpr>(E)) {
11345         if (isInitList) {
11346           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11347                                       false /*CheckReference*/))
11348             return;
11349         }
11350 
11351         Expr *Base = E->IgnoreParenImpCasts();
11352         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11353           // Check for static member variables and don't warn on them.
11354           if (!isa<FieldDecl>(ME->getMemberDecl()))
11355             return;
11356           Base = ME->getBase()->IgnoreParenImpCasts();
11357         }
11358         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11359           HandleDeclRefExpr(DRE);
11360         return;
11361       }
11362 
11363       Visit(E);
11364     }
11365 
11366     // Reference types not handled in HandleValue are handled here since all
11367     // uses of references are bad, not just r-value uses.
11368     void VisitDeclRefExpr(DeclRefExpr *E) {
11369       if (isReferenceType)
11370         HandleDeclRefExpr(E);
11371     }
11372 
11373     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11374       if (E->getCastKind() == CK_LValueToRValue) {
11375         HandleValue(E->getSubExpr());
11376         return;
11377       }
11378 
11379       Inherited::VisitImplicitCastExpr(E);
11380     }
11381 
11382     void VisitMemberExpr(MemberExpr *E) {
11383       if (isInitList) {
11384         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11385           return;
11386       }
11387 
11388       // Don't warn on arrays since they can be treated as pointers.
11389       if (E->getType()->canDecayToPointerType()) return;
11390 
11391       // Warn when a non-static method call is followed by non-static member
11392       // field accesses, which is followed by a DeclRefExpr.
11393       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11394       bool Warn = (MD && !MD->isStatic());
11395       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11396       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11397         if (!isa<FieldDecl>(ME->getMemberDecl()))
11398           Warn = false;
11399         Base = ME->getBase()->IgnoreParenImpCasts();
11400       }
11401 
11402       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11403         if (Warn)
11404           HandleDeclRefExpr(DRE);
11405         return;
11406       }
11407 
11408       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11409       // Visit that expression.
11410       Visit(Base);
11411     }
11412 
11413     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11414       Expr *Callee = E->getCallee();
11415 
11416       if (isa<UnresolvedLookupExpr>(Callee))
11417         return Inherited::VisitCXXOperatorCallExpr(E);
11418 
11419       Visit(Callee);
11420       for (auto Arg: E->arguments())
11421         HandleValue(Arg->IgnoreParenImpCasts());
11422     }
11423 
11424     void VisitUnaryOperator(UnaryOperator *E) {
11425       // For POD record types, addresses of its own members are well-defined.
11426       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11427           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11428         if (!isPODType)
11429           HandleValue(E->getSubExpr());
11430         return;
11431       }
11432 
11433       if (E->isIncrementDecrementOp()) {
11434         HandleValue(E->getSubExpr());
11435         return;
11436       }
11437 
11438       Inherited::VisitUnaryOperator(E);
11439     }
11440 
11441     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11442 
11443     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11444       if (E->getConstructor()->isCopyConstructor()) {
11445         Expr *ArgExpr = E->getArg(0);
11446         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11447           if (ILE->getNumInits() == 1)
11448             ArgExpr = ILE->getInit(0);
11449         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11450           if (ICE->getCastKind() == CK_NoOp)
11451             ArgExpr = ICE->getSubExpr();
11452         HandleValue(ArgExpr);
11453         return;
11454       }
11455       Inherited::VisitCXXConstructExpr(E);
11456     }
11457 
11458     void VisitCallExpr(CallExpr *E) {
11459       // Treat std::move as a use.
11460       if (E->isCallToStdMove()) {
11461         HandleValue(E->getArg(0));
11462         return;
11463       }
11464 
11465       Inherited::VisitCallExpr(E);
11466     }
11467 
11468     void VisitBinaryOperator(BinaryOperator *E) {
11469       if (E->isCompoundAssignmentOp()) {
11470         HandleValue(E->getLHS());
11471         Visit(E->getRHS());
11472         return;
11473       }
11474 
11475       Inherited::VisitBinaryOperator(E);
11476     }
11477 
11478     // A custom visitor for BinaryConditionalOperator is needed because the
11479     // regular visitor would check the condition and true expression separately
11480     // but both point to the same place giving duplicate diagnostics.
11481     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11482       Visit(E->getCond());
11483       Visit(E->getFalseExpr());
11484     }
11485 
11486     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11487       Decl* ReferenceDecl = DRE->getDecl();
11488       if (OrigDecl != ReferenceDecl) return;
11489       unsigned diag;
11490       if (isReferenceType) {
11491         diag = diag::warn_uninit_self_reference_in_reference_init;
11492       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11493         diag = diag::warn_static_self_reference_in_init;
11494       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11495                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11496                  DRE->getDecl()->getType()->isRecordType()) {
11497         diag = diag::warn_uninit_self_reference_in_init;
11498       } else {
11499         // Local variables will be handled by the CFG analysis.
11500         return;
11501       }
11502 
11503       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11504                             S.PDiag(diag)
11505                                 << DRE->getDecl() << OrigDecl->getLocation()
11506                                 << DRE->getSourceRange());
11507     }
11508   };
11509 
11510   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11511   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11512                                  bool DirectInit) {
11513     // Parameters arguments are occassionially constructed with itself,
11514     // for instance, in recursive functions.  Skip them.
11515     if (isa<ParmVarDecl>(OrigDecl))
11516       return;
11517 
11518     E = E->IgnoreParens();
11519 
11520     // Skip checking T a = a where T is not a record or reference type.
11521     // Doing so is a way to silence uninitialized warnings.
11522     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11523       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11524         if (ICE->getCastKind() == CK_LValueToRValue)
11525           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11526             if (DRE->getDecl() == OrigDecl)
11527               return;
11528 
11529     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11530   }
11531 } // end anonymous namespace
11532 
11533 namespace {
11534   // Simple wrapper to add the name of a variable or (if no variable is
11535   // available) a DeclarationName into a diagnostic.
11536   struct VarDeclOrName {
11537     VarDecl *VDecl;
11538     DeclarationName Name;
11539 
11540     friend const Sema::SemaDiagnosticBuilder &
11541     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11542       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11543     }
11544   };
11545 } // end anonymous namespace
11546 
11547 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11548                                             DeclarationName Name, QualType Type,
11549                                             TypeSourceInfo *TSI,
11550                                             SourceRange Range, bool DirectInit,
11551                                             Expr *Init) {
11552   bool IsInitCapture = !VDecl;
11553   assert((!VDecl || !VDecl->isInitCapture()) &&
11554          "init captures are expected to be deduced prior to initialization");
11555 
11556   VarDeclOrName VN{VDecl, Name};
11557 
11558   DeducedType *Deduced = Type->getContainedDeducedType();
11559   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11560 
11561   // C++11 [dcl.spec.auto]p3
11562   if (!Init) {
11563     assert(VDecl && "no init for init capture deduction?");
11564 
11565     // Except for class argument deduction, and then for an initializing
11566     // declaration only, i.e. no static at class scope or extern.
11567     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11568         VDecl->hasExternalStorage() ||
11569         VDecl->isStaticDataMember()) {
11570       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11571         << VDecl->getDeclName() << Type;
11572       return QualType();
11573     }
11574   }
11575 
11576   ArrayRef<Expr*> DeduceInits;
11577   if (Init)
11578     DeduceInits = Init;
11579 
11580   if (DirectInit) {
11581     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11582       DeduceInits = PL->exprs();
11583   }
11584 
11585   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11586     assert(VDecl && "non-auto type for init capture deduction?");
11587     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11588     InitializationKind Kind = InitializationKind::CreateForInit(
11589         VDecl->getLocation(), DirectInit, Init);
11590     // FIXME: Initialization should not be taking a mutable list of inits.
11591     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11592     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11593                                                        InitsCopy);
11594   }
11595 
11596   if (DirectInit) {
11597     if (auto *IL = dyn_cast<InitListExpr>(Init))
11598       DeduceInits = IL->inits();
11599   }
11600 
11601   // Deduction only works if we have exactly one source expression.
11602   if (DeduceInits.empty()) {
11603     // It isn't possible to write this directly, but it is possible to
11604     // end up in this situation with "auto x(some_pack...);"
11605     Diag(Init->getBeginLoc(), IsInitCapture
11606                                   ? diag::err_init_capture_no_expression
11607                                   : diag::err_auto_var_init_no_expression)
11608         << VN << Type << Range;
11609     return QualType();
11610   }
11611 
11612   if (DeduceInits.size() > 1) {
11613     Diag(DeduceInits[1]->getBeginLoc(),
11614          IsInitCapture ? diag::err_init_capture_multiple_expressions
11615                        : diag::err_auto_var_init_multiple_expressions)
11616         << VN << Type << Range;
11617     return QualType();
11618   }
11619 
11620   Expr *DeduceInit = DeduceInits[0];
11621   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11622     Diag(Init->getBeginLoc(), IsInitCapture
11623                                   ? diag::err_init_capture_paren_braces
11624                                   : diag::err_auto_var_init_paren_braces)
11625         << isa<InitListExpr>(Init) << VN << Type << Range;
11626     return QualType();
11627   }
11628 
11629   // Expressions default to 'id' when we're in a debugger.
11630   bool DefaultedAnyToId = false;
11631   if (getLangOpts().DebuggerCastResultToId &&
11632       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11633     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11634     if (Result.isInvalid()) {
11635       return QualType();
11636     }
11637     Init = Result.get();
11638     DefaultedAnyToId = true;
11639   }
11640 
11641   // C++ [dcl.decomp]p1:
11642   //   If the assignment-expression [...] has array type A and no ref-qualifier
11643   //   is present, e has type cv A
11644   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11645       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11646       DeduceInit->getType()->isConstantArrayType())
11647     return Context.getQualifiedType(DeduceInit->getType(),
11648                                     Type.getQualifiers());
11649 
11650   QualType DeducedType;
11651   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11652     if (!IsInitCapture)
11653       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11654     else if (isa<InitListExpr>(Init))
11655       Diag(Range.getBegin(),
11656            diag::err_init_capture_deduction_failure_from_init_list)
11657           << VN
11658           << (DeduceInit->getType().isNull() ? TSI->getType()
11659                                              : DeduceInit->getType())
11660           << DeduceInit->getSourceRange();
11661     else
11662       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11663           << VN << TSI->getType()
11664           << (DeduceInit->getType().isNull() ? TSI->getType()
11665                                              : DeduceInit->getType())
11666           << DeduceInit->getSourceRange();
11667   }
11668 
11669   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11670   // 'id' instead of a specific object type prevents most of our usual
11671   // checks.
11672   // We only want to warn outside of template instantiations, though:
11673   // inside a template, the 'id' could have come from a parameter.
11674   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11675       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11676     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11677     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11678   }
11679 
11680   return DeducedType;
11681 }
11682 
11683 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11684                                          Expr *Init) {
11685   assert(!Init || !Init->containsErrors());
11686   QualType DeducedType = deduceVarTypeFromInitializer(
11687       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11688       VDecl->getSourceRange(), DirectInit, Init);
11689   if (DeducedType.isNull()) {
11690     VDecl->setInvalidDecl();
11691     return true;
11692   }
11693 
11694   VDecl->setType(DeducedType);
11695   assert(VDecl->isLinkageValid());
11696 
11697   // In ARC, infer lifetime.
11698   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11699     VDecl->setInvalidDecl();
11700 
11701   if (getLangOpts().OpenCL)
11702     deduceOpenCLAddressSpace(VDecl);
11703 
11704   // If this is a redeclaration, check that the type we just deduced matches
11705   // the previously declared type.
11706   if (VarDecl *Old = VDecl->getPreviousDecl()) {
11707     // We never need to merge the type, because we cannot form an incomplete
11708     // array of auto, nor deduce such a type.
11709     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11710   }
11711 
11712   // Check the deduced type is valid for a variable declaration.
11713   CheckVariableDeclarationType(VDecl);
11714   return VDecl->isInvalidDecl();
11715 }
11716 
11717 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11718                                               SourceLocation Loc) {
11719   if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
11720     Init = EWC->getSubExpr();
11721 
11722   if (auto *CE = dyn_cast<ConstantExpr>(Init))
11723     Init = CE->getSubExpr();
11724 
11725   QualType InitType = Init->getType();
11726   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11727           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
11728          "shouldn't be called if type doesn't have a non-trivial C struct");
11729   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11730     for (auto I : ILE->inits()) {
11731       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11732           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11733         continue;
11734       SourceLocation SL = I->getExprLoc();
11735       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11736     }
11737     return;
11738   }
11739 
11740   if (isa<ImplicitValueInitExpr>(Init)) {
11741     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11742       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11743                             NTCUK_Init);
11744   } else {
11745     // Assume all other explicit initializers involving copying some existing
11746     // object.
11747     // TODO: ignore any explicit initializers where we can guarantee
11748     // copy-elision.
11749     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11750       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11751   }
11752 }
11753 
11754 namespace {
11755 
11756 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11757   // Ignore unavailable fields. A field can be marked as unavailable explicitly
11758   // in the source code or implicitly by the compiler if it is in a union
11759   // defined in a system header and has non-trivial ObjC ownership
11760   // qualifications. We don't want those fields to participate in determining
11761   // whether the containing union is non-trivial.
11762   return FD->hasAttr<UnavailableAttr>();
11763 }
11764 
11765 struct DiagNonTrivalCUnionDefaultInitializeVisitor
11766     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11767                                     void> {
11768   using Super =
11769       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11770                                     void>;
11771 
11772   DiagNonTrivalCUnionDefaultInitializeVisitor(
11773       QualType OrigTy, SourceLocation OrigLoc,
11774       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11775       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11776 
11777   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11778                      const FieldDecl *FD, bool InNonTrivialUnion) {
11779     if (const auto *AT = S.Context.getAsArrayType(QT))
11780       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11781                                      InNonTrivialUnion);
11782     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11783   }
11784 
11785   void visitARCStrong(QualType QT, const FieldDecl *FD,
11786                       bool InNonTrivialUnion) {
11787     if (InNonTrivialUnion)
11788       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11789           << 1 << 0 << QT << FD->getName();
11790   }
11791 
11792   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11793     if (InNonTrivialUnion)
11794       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11795           << 1 << 0 << QT << FD->getName();
11796   }
11797 
11798   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11799     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11800     if (RD->isUnion()) {
11801       if (OrigLoc.isValid()) {
11802         bool IsUnion = false;
11803         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11804           IsUnion = OrigRD->isUnion();
11805         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11806             << 0 << OrigTy << IsUnion << UseContext;
11807         // Reset OrigLoc so that this diagnostic is emitted only once.
11808         OrigLoc = SourceLocation();
11809       }
11810       InNonTrivialUnion = true;
11811     }
11812 
11813     if (InNonTrivialUnion)
11814       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11815           << 0 << 0 << QT.getUnqualifiedType() << "";
11816 
11817     for (const FieldDecl *FD : RD->fields())
11818       if (!shouldIgnoreForRecordTriviality(FD))
11819         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11820   }
11821 
11822   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11823 
11824   // The non-trivial C union type or the struct/union type that contains a
11825   // non-trivial C union.
11826   QualType OrigTy;
11827   SourceLocation OrigLoc;
11828   Sema::NonTrivialCUnionContext UseContext;
11829   Sema &S;
11830 };
11831 
11832 struct DiagNonTrivalCUnionDestructedTypeVisitor
11833     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
11834   using Super =
11835       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
11836 
11837   DiagNonTrivalCUnionDestructedTypeVisitor(
11838       QualType OrigTy, SourceLocation OrigLoc,
11839       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11840       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11841 
11842   void visitWithKind(QualType::DestructionKind DK, QualType QT,
11843                      const FieldDecl *FD, bool InNonTrivialUnion) {
11844     if (const auto *AT = S.Context.getAsArrayType(QT))
11845       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11846                                      InNonTrivialUnion);
11847     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
11848   }
11849 
11850   void visitARCStrong(QualType QT, const FieldDecl *FD,
11851                       bool InNonTrivialUnion) {
11852     if (InNonTrivialUnion)
11853       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11854           << 1 << 1 << QT << FD->getName();
11855   }
11856 
11857   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11858     if (InNonTrivialUnion)
11859       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11860           << 1 << 1 << QT << FD->getName();
11861   }
11862 
11863   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11864     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11865     if (RD->isUnion()) {
11866       if (OrigLoc.isValid()) {
11867         bool IsUnion = false;
11868         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11869           IsUnion = OrigRD->isUnion();
11870         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11871             << 1 << OrigTy << IsUnion << UseContext;
11872         // Reset OrigLoc so that this diagnostic is emitted only once.
11873         OrigLoc = SourceLocation();
11874       }
11875       InNonTrivialUnion = true;
11876     }
11877 
11878     if (InNonTrivialUnion)
11879       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11880           << 0 << 1 << QT.getUnqualifiedType() << "";
11881 
11882     for (const FieldDecl *FD : RD->fields())
11883       if (!shouldIgnoreForRecordTriviality(FD))
11884         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11885   }
11886 
11887   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11888   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
11889                           bool InNonTrivialUnion) {}
11890 
11891   // The non-trivial C union type or the struct/union type that contains a
11892   // non-trivial C union.
11893   QualType OrigTy;
11894   SourceLocation OrigLoc;
11895   Sema::NonTrivialCUnionContext UseContext;
11896   Sema &S;
11897 };
11898 
11899 struct DiagNonTrivalCUnionCopyVisitor
11900     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
11901   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
11902 
11903   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
11904                                  Sema::NonTrivialCUnionContext UseContext,
11905                                  Sema &S)
11906       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11907 
11908   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
11909                      const FieldDecl *FD, bool InNonTrivialUnion) {
11910     if (const auto *AT = S.Context.getAsArrayType(QT))
11911       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11912                                      InNonTrivialUnion);
11913     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
11914   }
11915 
11916   void visitARCStrong(QualType QT, const FieldDecl *FD,
11917                       bool InNonTrivialUnion) {
11918     if (InNonTrivialUnion)
11919       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11920           << 1 << 2 << QT << FD->getName();
11921   }
11922 
11923   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11924     if (InNonTrivialUnion)
11925       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11926           << 1 << 2 << QT << FD->getName();
11927   }
11928 
11929   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11930     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11931     if (RD->isUnion()) {
11932       if (OrigLoc.isValid()) {
11933         bool IsUnion = false;
11934         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11935           IsUnion = OrigRD->isUnion();
11936         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11937             << 2 << OrigTy << IsUnion << UseContext;
11938         // Reset OrigLoc so that this diagnostic is emitted only once.
11939         OrigLoc = SourceLocation();
11940       }
11941       InNonTrivialUnion = true;
11942     }
11943 
11944     if (InNonTrivialUnion)
11945       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11946           << 0 << 2 << QT.getUnqualifiedType() << "";
11947 
11948     for (const FieldDecl *FD : RD->fields())
11949       if (!shouldIgnoreForRecordTriviality(FD))
11950         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11951   }
11952 
11953   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
11954                 const FieldDecl *FD, bool InNonTrivialUnion) {}
11955   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11956   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
11957                             bool InNonTrivialUnion) {}
11958 
11959   // The non-trivial C union type or the struct/union type that contains a
11960   // non-trivial C union.
11961   QualType OrigTy;
11962   SourceLocation OrigLoc;
11963   Sema::NonTrivialCUnionContext UseContext;
11964   Sema &S;
11965 };
11966 
11967 } // namespace
11968 
11969 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
11970                                  NonTrivialCUnionContext UseContext,
11971                                  unsigned NonTrivialKind) {
11972   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11973           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
11974           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
11975          "shouldn't be called if type doesn't have a non-trivial C union");
11976 
11977   if ((NonTrivialKind & NTCUK_Init) &&
11978       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11979     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
11980         .visit(QT, nullptr, false);
11981   if ((NonTrivialKind & NTCUK_Destruct) &&
11982       QT.hasNonTrivialToPrimitiveDestructCUnion())
11983     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
11984         .visit(QT, nullptr, false);
11985   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
11986     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
11987         .visit(QT, nullptr, false);
11988 }
11989 
11990 /// AddInitializerToDecl - Adds the initializer Init to the
11991 /// declaration dcl. If DirectInit is true, this is C++ direct
11992 /// initialization rather than copy initialization.
11993 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
11994   // If there is no declaration, there was an error parsing it.  Just ignore
11995   // the initializer.
11996   if (!RealDecl || RealDecl->isInvalidDecl()) {
11997     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
11998     return;
11999   }
12000 
12001   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
12002     // Pure-specifiers are handled in ActOnPureSpecifier.
12003     Diag(Method->getLocation(), diag::err_member_function_initialization)
12004       << Method->getDeclName() << Init->getSourceRange();
12005     Method->setInvalidDecl();
12006     return;
12007   }
12008 
12009   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
12010   if (!VDecl) {
12011     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
12012     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
12013     RealDecl->setInvalidDecl();
12014     return;
12015   }
12016 
12017   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
12018   if (VDecl->getType()->isUndeducedType()) {
12019     // Attempt typo correction early so that the type of the init expression can
12020     // be deduced based on the chosen correction if the original init contains a
12021     // TypoExpr.
12022     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
12023     if (!Res.isUsable()) {
12024       // There are unresolved typos in Init, just drop them.
12025       // FIXME: improve the recovery strategy to preserve the Init.
12026       RealDecl->setInvalidDecl();
12027       return;
12028     }
12029     if (Res.get()->containsErrors()) {
12030       // Invalidate the decl as we don't know the type for recovery-expr yet.
12031       RealDecl->setInvalidDecl();
12032       VDecl->setInit(Res.get());
12033       return;
12034     }
12035     Init = Res.get();
12036 
12037     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
12038       return;
12039   }
12040 
12041   // dllimport cannot be used on variable definitions.
12042   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
12043     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
12044     VDecl->setInvalidDecl();
12045     return;
12046   }
12047 
12048   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
12049     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
12050     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
12051     VDecl->setInvalidDecl();
12052     return;
12053   }
12054 
12055   if (!VDecl->getType()->isDependentType()) {
12056     // A definition must end up with a complete type, which means it must be
12057     // complete with the restriction that an array type might be completed by
12058     // the initializer; note that later code assumes this restriction.
12059     QualType BaseDeclType = VDecl->getType();
12060     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
12061       BaseDeclType = Array->getElementType();
12062     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
12063                             diag::err_typecheck_decl_incomplete_type)) {
12064       RealDecl->setInvalidDecl();
12065       return;
12066     }
12067 
12068     // The variable can not have an abstract class type.
12069     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
12070                                diag::err_abstract_type_in_decl,
12071                                AbstractVariableType))
12072       VDecl->setInvalidDecl();
12073   }
12074 
12075   // If adding the initializer will turn this declaration into a definition,
12076   // and we already have a definition for this variable, diagnose or otherwise
12077   // handle the situation.
12078   VarDecl *Def;
12079   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
12080       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12081       !VDecl->isThisDeclarationADemotedDefinition() &&
12082       checkVarDeclRedefinition(Def, VDecl))
12083     return;
12084 
12085   if (getLangOpts().CPlusPlus) {
12086     // C++ [class.static.data]p4
12087     //   If a static data member is of const integral or const
12088     //   enumeration type, its declaration in the class definition can
12089     //   specify a constant-initializer which shall be an integral
12090     //   constant expression (5.19). In that case, the member can appear
12091     //   in integral constant expressions. The member shall still be
12092     //   defined in a namespace scope if it is used in the program and the
12093     //   namespace scope definition shall not contain an initializer.
12094     //
12095     // We already performed a redefinition check above, but for static
12096     // data members we also need to check whether there was an in-class
12097     // declaration with an initializer.
12098     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12099       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12100           << VDecl->getDeclName();
12101       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12102            diag::note_previous_initializer)
12103           << 0;
12104       return;
12105     }
12106 
12107     if (VDecl->hasLocalStorage())
12108       setFunctionHasBranchProtectedScope();
12109 
12110     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12111       VDecl->setInvalidDecl();
12112       return;
12113     }
12114   }
12115 
12116   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12117   // a kernel function cannot be initialized."
12118   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12119     Diag(VDecl->getLocation(), diag::err_local_cant_init);
12120     VDecl->setInvalidDecl();
12121     return;
12122   }
12123 
12124   // The LoaderUninitialized attribute acts as a definition (of undef).
12125   if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12126     Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12127     VDecl->setInvalidDecl();
12128     return;
12129   }
12130 
12131   // Get the decls type and save a reference for later, since
12132   // CheckInitializerTypes may change it.
12133   QualType DclT = VDecl->getType(), SavT = DclT;
12134 
12135   // Expressions default to 'id' when we're in a debugger
12136   // and we are assigning it to a variable of Objective-C pointer type.
12137   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12138       Init->getType() == Context.UnknownAnyTy) {
12139     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12140     if (Result.isInvalid()) {
12141       VDecl->setInvalidDecl();
12142       return;
12143     }
12144     Init = Result.get();
12145   }
12146 
12147   // Perform the initialization.
12148   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12149   if (!VDecl->isInvalidDecl()) {
12150     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12151     InitializationKind Kind = InitializationKind::CreateForInit(
12152         VDecl->getLocation(), DirectInit, Init);
12153 
12154     MultiExprArg Args = Init;
12155     if (CXXDirectInit)
12156       Args = MultiExprArg(CXXDirectInit->getExprs(),
12157                           CXXDirectInit->getNumExprs());
12158 
12159     // Try to correct any TypoExprs in the initialization arguments.
12160     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12161       ExprResult Res = CorrectDelayedTyposInExpr(
12162           Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12163           [this, Entity, Kind](Expr *E) {
12164             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12165             return Init.Failed() ? ExprError() : E;
12166           });
12167       if (Res.isInvalid()) {
12168         VDecl->setInvalidDecl();
12169       } else if (Res.get() != Args[Idx]) {
12170         Args[Idx] = Res.get();
12171       }
12172     }
12173     if (VDecl->isInvalidDecl())
12174       return;
12175 
12176     InitializationSequence InitSeq(*this, Entity, Kind, Args,
12177                                    /*TopLevelOfInitList=*/false,
12178                                    /*TreatUnavailableAsInvalid=*/false);
12179     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12180     if (Result.isInvalid()) {
12181       // If the provied initializer fails to initialize the var decl,
12182       // we attach a recovery expr for better recovery.
12183       auto RecoveryExpr =
12184           CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12185       if (RecoveryExpr.get())
12186         VDecl->setInit(RecoveryExpr.get());
12187       return;
12188     }
12189 
12190     Init = Result.getAs<Expr>();
12191   }
12192 
12193   // Check for self-references within variable initializers.
12194   // Variables declared within a function/method body (except for references)
12195   // are handled by a dataflow analysis.
12196   // This is undefined behavior in C++, but valid in C.
12197   if (getLangOpts().CPlusPlus) {
12198     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12199         VDecl->getType()->isReferenceType()) {
12200       CheckSelfReference(*this, RealDecl, Init, DirectInit);
12201     }
12202   }
12203 
12204   // If the type changed, it means we had an incomplete type that was
12205   // completed by the initializer. For example:
12206   //   int ary[] = { 1, 3, 5 };
12207   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12208   if (!VDecl->isInvalidDecl() && (DclT != SavT))
12209     VDecl->setType(DclT);
12210 
12211   if (!VDecl->isInvalidDecl()) {
12212     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12213 
12214     if (VDecl->hasAttr<BlocksAttr>())
12215       checkRetainCycles(VDecl, Init);
12216 
12217     // It is safe to assign a weak reference into a strong variable.
12218     // Although this code can still have problems:
12219     //   id x = self.weakProp;
12220     //   id y = self.weakProp;
12221     // we do not warn to warn spuriously when 'x' and 'y' are on separate
12222     // paths through the function. This should be revisited if
12223     // -Wrepeated-use-of-weak is made flow-sensitive.
12224     if (FunctionScopeInfo *FSI = getCurFunction())
12225       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12226            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12227           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12228                            Init->getBeginLoc()))
12229         FSI->markSafeWeakUse(Init);
12230   }
12231 
12232   // The initialization is usually a full-expression.
12233   //
12234   // FIXME: If this is a braced initialization of an aggregate, it is not
12235   // an expression, and each individual field initializer is a separate
12236   // full-expression. For instance, in:
12237   //
12238   //   struct Temp { ~Temp(); };
12239   //   struct S { S(Temp); };
12240   //   struct T { S a, b; } t = { Temp(), Temp() }
12241   //
12242   // we should destroy the first Temp before constructing the second.
12243   ExprResult Result =
12244       ActOnFinishFullExpr(Init, VDecl->getLocation(),
12245                           /*DiscardedValue*/ false, VDecl->isConstexpr());
12246   if (Result.isInvalid()) {
12247     VDecl->setInvalidDecl();
12248     return;
12249   }
12250   Init = Result.get();
12251 
12252   // Attach the initializer to the decl.
12253   VDecl->setInit(Init);
12254 
12255   if (VDecl->isLocalVarDecl()) {
12256     // Don't check the initializer if the declaration is malformed.
12257     if (VDecl->isInvalidDecl()) {
12258       // do nothing
12259 
12260     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12261     // This is true even in C++ for OpenCL.
12262     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12263       CheckForConstantInitializer(Init, DclT);
12264 
12265     // Otherwise, C++ does not restrict the initializer.
12266     } else if (getLangOpts().CPlusPlus) {
12267       // do nothing
12268 
12269     // C99 6.7.8p4: All the expressions in an initializer for an object that has
12270     // static storage duration shall be constant expressions or string literals.
12271     } else if (VDecl->getStorageClass() == SC_Static) {
12272       CheckForConstantInitializer(Init, DclT);
12273 
12274     // C89 is stricter than C99 for aggregate initializers.
12275     // C89 6.5.7p3: All the expressions [...] in an initializer list
12276     // for an object that has aggregate or union type shall be
12277     // constant expressions.
12278     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12279                isa<InitListExpr>(Init)) {
12280       const Expr *Culprit;
12281       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12282         Diag(Culprit->getExprLoc(),
12283              diag::ext_aggregate_init_not_constant)
12284           << Culprit->getSourceRange();
12285       }
12286     }
12287 
12288     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12289       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12290         if (VDecl->hasLocalStorage())
12291           BE->getBlockDecl()->setCanAvoidCopyToHeap();
12292   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12293              VDecl->getLexicalDeclContext()->isRecord()) {
12294     // This is an in-class initialization for a static data member, e.g.,
12295     //
12296     // struct S {
12297     //   static const int value = 17;
12298     // };
12299 
12300     // C++ [class.mem]p4:
12301     //   A member-declarator can contain a constant-initializer only
12302     //   if it declares a static member (9.4) of const integral or
12303     //   const enumeration type, see 9.4.2.
12304     //
12305     // C++11 [class.static.data]p3:
12306     //   If a non-volatile non-inline const static data member is of integral
12307     //   or enumeration type, its declaration in the class definition can
12308     //   specify a brace-or-equal-initializer in which every initializer-clause
12309     //   that is an assignment-expression is a constant expression. A static
12310     //   data member of literal type can be declared in the class definition
12311     //   with the constexpr specifier; if so, its declaration shall specify a
12312     //   brace-or-equal-initializer in which every initializer-clause that is
12313     //   an assignment-expression is a constant expression.
12314 
12315     // Do nothing on dependent types.
12316     if (DclT->isDependentType()) {
12317 
12318     // Allow any 'static constexpr' members, whether or not they are of literal
12319     // type. We separately check that every constexpr variable is of literal
12320     // type.
12321     } else if (VDecl->isConstexpr()) {
12322 
12323     // Require constness.
12324     } else if (!DclT.isConstQualified()) {
12325       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12326         << Init->getSourceRange();
12327       VDecl->setInvalidDecl();
12328 
12329     // We allow integer constant expressions in all cases.
12330     } else if (DclT->isIntegralOrEnumerationType()) {
12331       // Check whether the expression is a constant expression.
12332       SourceLocation Loc;
12333       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12334         // In C++11, a non-constexpr const static data member with an
12335         // in-class initializer cannot be volatile.
12336         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12337       else if (Init->isValueDependent())
12338         ; // Nothing to check.
12339       else if (Init->isIntegerConstantExpr(Context, &Loc))
12340         ; // Ok, it's an ICE!
12341       else if (Init->getType()->isScopedEnumeralType() &&
12342                Init->isCXX11ConstantExpr(Context))
12343         ; // Ok, it is a scoped-enum constant expression.
12344       else if (Init->isEvaluatable(Context)) {
12345         // If we can constant fold the initializer through heroics, accept it,
12346         // but report this as a use of an extension for -pedantic.
12347         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12348           << Init->getSourceRange();
12349       } else {
12350         // Otherwise, this is some crazy unknown case.  Report the issue at the
12351         // location provided by the isIntegerConstantExpr failed check.
12352         Diag(Loc, diag::err_in_class_initializer_non_constant)
12353           << Init->getSourceRange();
12354         VDecl->setInvalidDecl();
12355       }
12356 
12357     // We allow foldable floating-point constants as an extension.
12358     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12359       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12360       // it anyway and provide a fixit to add the 'constexpr'.
12361       if (getLangOpts().CPlusPlus11) {
12362         Diag(VDecl->getLocation(),
12363              diag::ext_in_class_initializer_float_type_cxx11)
12364             << DclT << Init->getSourceRange();
12365         Diag(VDecl->getBeginLoc(),
12366              diag::note_in_class_initializer_float_type_cxx11)
12367             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12368       } else {
12369         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12370           << DclT << Init->getSourceRange();
12371 
12372         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12373           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12374             << Init->getSourceRange();
12375           VDecl->setInvalidDecl();
12376         }
12377       }
12378 
12379     // Suggest adding 'constexpr' in C++11 for literal types.
12380     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12381       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12382           << DclT << Init->getSourceRange()
12383           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12384       VDecl->setConstexpr(true);
12385 
12386     } else {
12387       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12388         << DclT << Init->getSourceRange();
12389       VDecl->setInvalidDecl();
12390     }
12391   } else if (VDecl->isFileVarDecl()) {
12392     // In C, extern is typically used to avoid tentative definitions when
12393     // declaring variables in headers, but adding an intializer makes it a
12394     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12395     // In C++, extern is often used to give implictly static const variables
12396     // external linkage, so don't warn in that case. If selectany is present,
12397     // this might be header code intended for C and C++ inclusion, so apply the
12398     // C++ rules.
12399     if (VDecl->getStorageClass() == SC_Extern &&
12400         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12401          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12402         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12403         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12404       Diag(VDecl->getLocation(), diag::warn_extern_init);
12405 
12406     // In Microsoft C++ mode, a const variable defined in namespace scope has
12407     // external linkage by default if the variable is declared with
12408     // __declspec(dllexport).
12409     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12410         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12411         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12412       VDecl->setStorageClass(SC_Extern);
12413 
12414     // C99 6.7.8p4. All file scoped initializers need to be constant.
12415     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12416       CheckForConstantInitializer(Init, DclT);
12417   }
12418 
12419   QualType InitType = Init->getType();
12420   if (!InitType.isNull() &&
12421       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12422        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12423     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12424 
12425   // We will represent direct-initialization similarly to copy-initialization:
12426   //    int x(1);  -as-> int x = 1;
12427   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12428   //
12429   // Clients that want to distinguish between the two forms, can check for
12430   // direct initializer using VarDecl::getInitStyle().
12431   // A major benefit is that clients that don't particularly care about which
12432   // exactly form was it (like the CodeGen) can handle both cases without
12433   // special case code.
12434 
12435   // C++ 8.5p11:
12436   // The form of initialization (using parentheses or '=') is generally
12437   // insignificant, but does matter when the entity being initialized has a
12438   // class type.
12439   if (CXXDirectInit) {
12440     assert(DirectInit && "Call-style initializer must be direct init.");
12441     VDecl->setInitStyle(VarDecl::CallInit);
12442   } else if (DirectInit) {
12443     // This must be list-initialization. No other way is direct-initialization.
12444     VDecl->setInitStyle(VarDecl::ListInit);
12445   }
12446 
12447   if (LangOpts.OpenMP && VDecl->isFileVarDecl())
12448     DeclsToCheckForDeferredDiags.push_back(VDecl);
12449   CheckCompleteVariableDeclaration(VDecl);
12450 }
12451 
12452 /// ActOnInitializerError - Given that there was an error parsing an
12453 /// initializer for the given declaration, try to return to some form
12454 /// of sanity.
12455 void Sema::ActOnInitializerError(Decl *D) {
12456   // Our main concern here is re-establishing invariants like "a
12457   // variable's type is either dependent or complete".
12458   if (!D || D->isInvalidDecl()) return;
12459 
12460   VarDecl *VD = dyn_cast<VarDecl>(D);
12461   if (!VD) return;
12462 
12463   // Bindings are not usable if we can't make sense of the initializer.
12464   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12465     for (auto *BD : DD->bindings())
12466       BD->setInvalidDecl();
12467 
12468   // Auto types are meaningless if we can't make sense of the initializer.
12469   if (VD->getType()->isUndeducedType()) {
12470     D->setInvalidDecl();
12471     return;
12472   }
12473 
12474   QualType Ty = VD->getType();
12475   if (Ty->isDependentType()) return;
12476 
12477   // Require a complete type.
12478   if (RequireCompleteType(VD->getLocation(),
12479                           Context.getBaseElementType(Ty),
12480                           diag::err_typecheck_decl_incomplete_type)) {
12481     VD->setInvalidDecl();
12482     return;
12483   }
12484 
12485   // Require a non-abstract type.
12486   if (RequireNonAbstractType(VD->getLocation(), Ty,
12487                              diag::err_abstract_type_in_decl,
12488                              AbstractVariableType)) {
12489     VD->setInvalidDecl();
12490     return;
12491   }
12492 
12493   // Don't bother complaining about constructors or destructors,
12494   // though.
12495 }
12496 
12497 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12498   // If there is no declaration, there was an error parsing it. Just ignore it.
12499   if (!RealDecl)
12500     return;
12501 
12502   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12503     QualType Type = Var->getType();
12504 
12505     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12506     if (isa<DecompositionDecl>(RealDecl)) {
12507       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12508       Var->setInvalidDecl();
12509       return;
12510     }
12511 
12512     if (Type->isUndeducedType() &&
12513         DeduceVariableDeclarationType(Var, false, nullptr))
12514       return;
12515 
12516     // C++11 [class.static.data]p3: A static data member can be declared with
12517     // the constexpr specifier; if so, its declaration shall specify
12518     // a brace-or-equal-initializer.
12519     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12520     // the definition of a variable [...] or the declaration of a static data
12521     // member.
12522     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12523         !Var->isThisDeclarationADemotedDefinition()) {
12524       if (Var->isStaticDataMember()) {
12525         // C++1z removes the relevant rule; the in-class declaration is always
12526         // a definition there.
12527         if (!getLangOpts().CPlusPlus17 &&
12528             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12529           Diag(Var->getLocation(),
12530                diag::err_constexpr_static_mem_var_requires_init)
12531               << Var;
12532           Var->setInvalidDecl();
12533           return;
12534         }
12535       } else {
12536         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12537         Var->setInvalidDecl();
12538         return;
12539       }
12540     }
12541 
12542     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12543     // be initialized.
12544     if (!Var->isInvalidDecl() &&
12545         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12546         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12547       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12548       Var->setInvalidDecl();
12549       return;
12550     }
12551 
12552     if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
12553       if (Var->getStorageClass() == SC_Extern) {
12554         Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
12555             << Var;
12556         Var->setInvalidDecl();
12557         return;
12558       }
12559       if (RequireCompleteType(Var->getLocation(), Var->getType(),
12560                               diag::err_typecheck_decl_incomplete_type)) {
12561         Var->setInvalidDecl();
12562         return;
12563       }
12564       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12565         if (!RD->hasTrivialDefaultConstructor()) {
12566           Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
12567           Var->setInvalidDecl();
12568           return;
12569         }
12570       }
12571     }
12572 
12573     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12574     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12575         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12576       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12577                             NTCUC_DefaultInitializedObject, NTCUK_Init);
12578 
12579 
12580     switch (DefKind) {
12581     case VarDecl::Definition:
12582       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12583         break;
12584 
12585       // We have an out-of-line definition of a static data member
12586       // that has an in-class initializer, so we type-check this like
12587       // a declaration.
12588       //
12589       LLVM_FALLTHROUGH;
12590 
12591     case VarDecl::DeclarationOnly:
12592       // It's only a declaration.
12593 
12594       // Block scope. C99 6.7p7: If an identifier for an object is
12595       // declared with no linkage (C99 6.2.2p6), the type for the
12596       // object shall be complete.
12597       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12598           !Var->hasLinkage() && !Var->isInvalidDecl() &&
12599           RequireCompleteType(Var->getLocation(), Type,
12600                               diag::err_typecheck_decl_incomplete_type))
12601         Var->setInvalidDecl();
12602 
12603       // Make sure that the type is not abstract.
12604       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12605           RequireNonAbstractType(Var->getLocation(), Type,
12606                                  diag::err_abstract_type_in_decl,
12607                                  AbstractVariableType))
12608         Var->setInvalidDecl();
12609       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12610           Var->getStorageClass() == SC_PrivateExtern) {
12611         Diag(Var->getLocation(), diag::warn_private_extern);
12612         Diag(Var->getLocation(), diag::note_private_extern);
12613       }
12614 
12615       if (Context.getTargetInfo().allowDebugInfoForExternalVar() &&
12616           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12617         ExternalDeclarations.push_back(Var);
12618 
12619       return;
12620 
12621     case VarDecl::TentativeDefinition:
12622       // File scope. C99 6.9.2p2: A declaration of an identifier for an
12623       // object that has file scope without an initializer, and without a
12624       // storage-class specifier or with the storage-class specifier "static",
12625       // constitutes a tentative definition. Note: A tentative definition with
12626       // external linkage is valid (C99 6.2.2p5).
12627       if (!Var->isInvalidDecl()) {
12628         if (const IncompleteArrayType *ArrayT
12629                                     = Context.getAsIncompleteArrayType(Type)) {
12630           if (RequireCompleteSizedType(
12631                   Var->getLocation(), ArrayT->getElementType(),
12632                   diag::err_array_incomplete_or_sizeless_type))
12633             Var->setInvalidDecl();
12634         } else if (Var->getStorageClass() == SC_Static) {
12635           // C99 6.9.2p3: If the declaration of an identifier for an object is
12636           // a tentative definition and has internal linkage (C99 6.2.2p3), the
12637           // declared type shall not be an incomplete type.
12638           // NOTE: code such as the following
12639           //     static struct s;
12640           //     struct s { int a; };
12641           // is accepted by gcc. Hence here we issue a warning instead of
12642           // an error and we do not invalidate the static declaration.
12643           // NOTE: to avoid multiple warnings, only check the first declaration.
12644           if (Var->isFirstDecl())
12645             RequireCompleteType(Var->getLocation(), Type,
12646                                 diag::ext_typecheck_decl_incomplete_type);
12647         }
12648       }
12649 
12650       // Record the tentative definition; we're done.
12651       if (!Var->isInvalidDecl())
12652         TentativeDefinitions.push_back(Var);
12653       return;
12654     }
12655 
12656     // Provide a specific diagnostic for uninitialized variable
12657     // definitions with incomplete array type.
12658     if (Type->isIncompleteArrayType()) {
12659       Diag(Var->getLocation(),
12660            diag::err_typecheck_incomplete_array_needs_initializer);
12661       Var->setInvalidDecl();
12662       return;
12663     }
12664 
12665     // Provide a specific diagnostic for uninitialized variable
12666     // definitions with reference type.
12667     if (Type->isReferenceType()) {
12668       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12669           << Var << SourceRange(Var->getLocation(), Var->getLocation());
12670       Var->setInvalidDecl();
12671       return;
12672     }
12673 
12674     // Do not attempt to type-check the default initializer for a
12675     // variable with dependent type.
12676     if (Type->isDependentType())
12677       return;
12678 
12679     if (Var->isInvalidDecl())
12680       return;
12681 
12682     if (!Var->hasAttr<AliasAttr>()) {
12683       if (RequireCompleteType(Var->getLocation(),
12684                               Context.getBaseElementType(Type),
12685                               diag::err_typecheck_decl_incomplete_type)) {
12686         Var->setInvalidDecl();
12687         return;
12688       }
12689     } else {
12690       return;
12691     }
12692 
12693     // The variable can not have an abstract class type.
12694     if (RequireNonAbstractType(Var->getLocation(), Type,
12695                                diag::err_abstract_type_in_decl,
12696                                AbstractVariableType)) {
12697       Var->setInvalidDecl();
12698       return;
12699     }
12700 
12701     // Check for jumps past the implicit initializer.  C++0x
12702     // clarifies that this applies to a "variable with automatic
12703     // storage duration", not a "local variable".
12704     // C++11 [stmt.dcl]p3
12705     //   A program that jumps from a point where a variable with automatic
12706     //   storage duration is not in scope to a point where it is in scope is
12707     //   ill-formed unless the variable has scalar type, class type with a
12708     //   trivial default constructor and a trivial destructor, a cv-qualified
12709     //   version of one of these types, or an array of one of the preceding
12710     //   types and is declared without an initializer.
12711     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12712       if (const RecordType *Record
12713             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12714         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12715         // Mark the function (if we're in one) for further checking even if the
12716         // looser rules of C++11 do not require such checks, so that we can
12717         // diagnose incompatibilities with C++98.
12718         if (!CXXRecord->isPOD())
12719           setFunctionHasBranchProtectedScope();
12720       }
12721     }
12722     // In OpenCL, we can't initialize objects in the __local address space,
12723     // even implicitly, so don't synthesize an implicit initializer.
12724     if (getLangOpts().OpenCL &&
12725         Var->getType().getAddressSpace() == LangAS::opencl_local)
12726       return;
12727     // C++03 [dcl.init]p9:
12728     //   If no initializer is specified for an object, and the
12729     //   object is of (possibly cv-qualified) non-POD class type (or
12730     //   array thereof), the object shall be default-initialized; if
12731     //   the object is of const-qualified type, the underlying class
12732     //   type shall have a user-declared default
12733     //   constructor. Otherwise, if no initializer is specified for
12734     //   a non- static object, the object and its subobjects, if
12735     //   any, have an indeterminate initial value); if the object
12736     //   or any of its subobjects are of const-qualified type, the
12737     //   program is ill-formed.
12738     // C++0x [dcl.init]p11:
12739     //   If no initializer is specified for an object, the object is
12740     //   default-initialized; [...].
12741     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12742     InitializationKind Kind
12743       = InitializationKind::CreateDefault(Var->getLocation());
12744 
12745     InitializationSequence InitSeq(*this, Entity, Kind, None);
12746     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12747 
12748     if (Init.get()) {
12749       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12750       // This is important for template substitution.
12751       Var->setInitStyle(VarDecl::CallInit);
12752     } else if (Init.isInvalid()) {
12753       // If default-init fails, attach a recovery-expr initializer to track
12754       // that initialization was attempted and failed.
12755       auto RecoveryExpr =
12756           CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
12757       if (RecoveryExpr.get())
12758         Var->setInit(RecoveryExpr.get());
12759     }
12760 
12761     CheckCompleteVariableDeclaration(Var);
12762   }
12763 }
12764 
12765 void Sema::ActOnCXXForRangeDecl(Decl *D) {
12766   // If there is no declaration, there was an error parsing it. Ignore it.
12767   if (!D)
12768     return;
12769 
12770   VarDecl *VD = dyn_cast<VarDecl>(D);
12771   if (!VD) {
12772     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12773     D->setInvalidDecl();
12774     return;
12775   }
12776 
12777   VD->setCXXForRangeDecl(true);
12778 
12779   // for-range-declaration cannot be given a storage class specifier.
12780   int Error = -1;
12781   switch (VD->getStorageClass()) {
12782   case SC_None:
12783     break;
12784   case SC_Extern:
12785     Error = 0;
12786     break;
12787   case SC_Static:
12788     Error = 1;
12789     break;
12790   case SC_PrivateExtern:
12791     Error = 2;
12792     break;
12793   case SC_Auto:
12794     Error = 3;
12795     break;
12796   case SC_Register:
12797     Error = 4;
12798     break;
12799   }
12800 
12801   // for-range-declaration cannot be given a storage class specifier con't.
12802   switch (VD->getTSCSpec()) {
12803   case TSCS_thread_local:
12804     Error = 6;
12805     break;
12806   case TSCS___thread:
12807   case TSCS__Thread_local:
12808   case TSCS_unspecified:
12809     break;
12810   }
12811 
12812   if (Error != -1) {
12813     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12814         << VD << Error;
12815     D->setInvalidDecl();
12816   }
12817 }
12818 
12819 StmtResult
12820 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
12821                                  IdentifierInfo *Ident,
12822                                  ParsedAttributes &Attrs,
12823                                  SourceLocation AttrEnd) {
12824   // C++1y [stmt.iter]p1:
12825   //   A range-based for statement of the form
12826   //      for ( for-range-identifier : for-range-initializer ) statement
12827   //   is equivalent to
12828   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
12829   DeclSpec DS(Attrs.getPool().getFactory());
12830 
12831   const char *PrevSpec;
12832   unsigned DiagID;
12833   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
12834                      getPrintingPolicy());
12835 
12836   Declarator D(DS, DeclaratorContext::ForInit);
12837   D.SetIdentifier(Ident, IdentLoc);
12838   D.takeAttributes(Attrs, AttrEnd);
12839 
12840   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
12841                 IdentLoc);
12842   Decl *Var = ActOnDeclarator(S, D);
12843   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
12844   FinalizeDeclaration(Var);
12845   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
12846                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
12847 }
12848 
12849 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
12850   if (var->isInvalidDecl()) return;
12851 
12852   if (getLangOpts().OpenCL) {
12853     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
12854     // initialiser
12855     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
12856         !var->hasInit()) {
12857       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
12858           << 1 /*Init*/;
12859       var->setInvalidDecl();
12860       return;
12861     }
12862   }
12863 
12864   // In Objective-C, don't allow jumps past the implicit initialization of a
12865   // local retaining variable.
12866   if (getLangOpts().ObjC &&
12867       var->hasLocalStorage()) {
12868     switch (var->getType().getObjCLifetime()) {
12869     case Qualifiers::OCL_None:
12870     case Qualifiers::OCL_ExplicitNone:
12871     case Qualifiers::OCL_Autoreleasing:
12872       break;
12873 
12874     case Qualifiers::OCL_Weak:
12875     case Qualifiers::OCL_Strong:
12876       setFunctionHasBranchProtectedScope();
12877       break;
12878     }
12879   }
12880 
12881   if (var->hasLocalStorage() &&
12882       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
12883     setFunctionHasBranchProtectedScope();
12884 
12885   // Warn about externally-visible variables being defined without a
12886   // prior declaration.  We only want to do this for global
12887   // declarations, but we also specifically need to avoid doing it for
12888   // class members because the linkage of an anonymous class can
12889   // change if it's later given a typedef name.
12890   if (var->isThisDeclarationADefinition() &&
12891       var->getDeclContext()->getRedeclContext()->isFileContext() &&
12892       var->isExternallyVisible() && var->hasLinkage() &&
12893       !var->isInline() && !var->getDescribedVarTemplate() &&
12894       !isa<VarTemplatePartialSpecializationDecl>(var) &&
12895       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
12896       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
12897                                   var->getLocation())) {
12898     // Find a previous declaration that's not a definition.
12899     VarDecl *prev = var->getPreviousDecl();
12900     while (prev && prev->isThisDeclarationADefinition())
12901       prev = prev->getPreviousDecl();
12902 
12903     if (!prev) {
12904       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
12905       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
12906           << /* variable */ 0;
12907     }
12908   }
12909 
12910   // Cache the result of checking for constant initialization.
12911   Optional<bool> CacheHasConstInit;
12912   const Expr *CacheCulprit = nullptr;
12913   auto checkConstInit = [&]() mutable {
12914     if (!CacheHasConstInit)
12915       CacheHasConstInit = var->getInit()->isConstantInitializer(
12916             Context, var->getType()->isReferenceType(), &CacheCulprit);
12917     return *CacheHasConstInit;
12918   };
12919 
12920   if (var->getTLSKind() == VarDecl::TLS_Static) {
12921     if (var->getType().isDestructedType()) {
12922       // GNU C++98 edits for __thread, [basic.start.term]p3:
12923       //   The type of an object with thread storage duration shall not
12924       //   have a non-trivial destructor.
12925       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
12926       if (getLangOpts().CPlusPlus11)
12927         Diag(var->getLocation(), diag::note_use_thread_local);
12928     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
12929       if (!checkConstInit()) {
12930         // GNU C++98 edits for __thread, [basic.start.init]p4:
12931         //   An object of thread storage duration shall not require dynamic
12932         //   initialization.
12933         // FIXME: Need strict checking here.
12934         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
12935           << CacheCulprit->getSourceRange();
12936         if (getLangOpts().CPlusPlus11)
12937           Diag(var->getLocation(), diag::note_use_thread_local);
12938       }
12939     }
12940   }
12941 
12942   // Apply section attributes and pragmas to global variables.
12943   bool GlobalStorage = var->hasGlobalStorage();
12944   if (GlobalStorage && var->isThisDeclarationADefinition() &&
12945       !inTemplateInstantiation()) {
12946     PragmaStack<StringLiteral *> *Stack = nullptr;
12947     int SectionFlags = ASTContext::PSF_Read;
12948     if (var->getType().isConstQualified())
12949       Stack = &ConstSegStack;
12950     else if (!var->getInit()) {
12951       Stack = &BSSSegStack;
12952       SectionFlags |= ASTContext::PSF_Write;
12953     } else {
12954       Stack = &DataSegStack;
12955       SectionFlags |= ASTContext::PSF_Write;
12956     }
12957     if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
12958       if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
12959         SectionFlags |= ASTContext::PSF_Implicit;
12960       UnifySection(SA->getName(), SectionFlags, var);
12961     } else if (Stack->CurrentValue) {
12962       SectionFlags |= ASTContext::PSF_Implicit;
12963       auto SectionName = Stack->CurrentValue->getString();
12964       var->addAttr(SectionAttr::CreateImplicit(
12965           Context, SectionName, Stack->CurrentPragmaLocation,
12966           AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
12967       if (UnifySection(SectionName, SectionFlags, var))
12968         var->dropAttr<SectionAttr>();
12969     }
12970 
12971     // Apply the init_seg attribute if this has an initializer.  If the
12972     // initializer turns out to not be dynamic, we'll end up ignoring this
12973     // attribute.
12974     if (CurInitSeg && var->getInit())
12975       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
12976                                                CurInitSegLoc,
12977                                                AttributeCommonInfo::AS_Pragma));
12978   }
12979 
12980   if (!var->getType()->isStructureType() && var->hasInit() &&
12981       isa<InitListExpr>(var->getInit())) {
12982     const auto *ILE = cast<InitListExpr>(var->getInit());
12983     unsigned NumInits = ILE->getNumInits();
12984     if (NumInits > 2)
12985       for (unsigned I = 0; I < NumInits; ++I) {
12986         const auto *Init = ILE->getInit(I);
12987         if (!Init)
12988           break;
12989         const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
12990         if (!SL)
12991           break;
12992 
12993         unsigned NumConcat = SL->getNumConcatenated();
12994         // Diagnose missing comma in string array initialization.
12995         // Do not warn when all the elements in the initializer are concatenated
12996         // together. Do not warn for macros too.
12997         if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
12998           bool OnlyOneMissingComma = true;
12999           for (unsigned J = I + 1; J < NumInits; ++J) {
13000             const auto *Init = ILE->getInit(J);
13001             if (!Init)
13002               break;
13003             const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13004             if (!SLJ || SLJ->getNumConcatenated() > 1) {
13005               OnlyOneMissingComma = false;
13006               break;
13007             }
13008           }
13009 
13010           if (OnlyOneMissingComma) {
13011             SmallVector<FixItHint, 1> Hints;
13012             for (unsigned i = 0; i < NumConcat - 1; ++i)
13013               Hints.push_back(FixItHint::CreateInsertion(
13014                   PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
13015 
13016             Diag(SL->getStrTokenLoc(1),
13017                  diag::warn_concatenated_literal_array_init)
13018                 << Hints;
13019             Diag(SL->getBeginLoc(),
13020                  diag::note_concatenated_string_literal_silence);
13021           }
13022           // In any case, stop now.
13023           break;
13024         }
13025       }
13026   }
13027 
13028   // All the following checks are C++ only.
13029   if (!getLangOpts().CPlusPlus) {
13030     // If this variable must be emitted, add it as an initializer for the
13031     // current module.
13032     if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13033       Context.addModuleInitializer(ModuleScopes.back().Module, var);
13034     return;
13035   }
13036 
13037   QualType type = var->getType();
13038 
13039   if (var->hasAttr<BlocksAttr>())
13040     getCurFunction()->addByrefBlockVar(var);
13041 
13042   Expr *Init = var->getInit();
13043   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
13044   QualType baseType = Context.getBaseElementType(type);
13045 
13046   // Check whether the initializer is sufficiently constant.
13047   if (!type->isDependentType() && Init && !Init->isValueDependent() &&
13048       (GlobalStorage || var->isConstexpr() ||
13049        var->mightBeUsableInConstantExpressions(Context))) {
13050     // If this variable might have a constant initializer or might be usable in
13051     // constant expressions, check whether or not it actually is now.  We can't
13052     // do this lazily, because the result might depend on things that change
13053     // later, such as which constexpr functions happen to be defined.
13054     SmallVector<PartialDiagnosticAt, 8> Notes;
13055     bool HasConstInit;
13056     if (!getLangOpts().CPlusPlus11) {
13057       // Prior to C++11, in contexts where a constant initializer is required,
13058       // the set of valid constant initializers is described by syntactic rules
13059       // in [expr.const]p2-6.
13060       // FIXME: Stricter checking for these rules would be useful for constinit /
13061       // -Wglobal-constructors.
13062       HasConstInit = checkConstInit();
13063 
13064       // Compute and cache the constant value, and remember that we have a
13065       // constant initializer.
13066       if (HasConstInit) {
13067         (void)var->checkForConstantInitialization(Notes);
13068         Notes.clear();
13069       } else if (CacheCulprit) {
13070         Notes.emplace_back(CacheCulprit->getExprLoc(),
13071                            PDiag(diag::note_invalid_subexpr_in_const_expr));
13072         Notes.back().second << CacheCulprit->getSourceRange();
13073       }
13074     } else {
13075       // Evaluate the initializer to see if it's a constant initializer.
13076       HasConstInit = var->checkForConstantInitialization(Notes);
13077     }
13078 
13079     if (HasConstInit) {
13080       // FIXME: Consider replacing the initializer with a ConstantExpr.
13081     } else if (var->isConstexpr()) {
13082       SourceLocation DiagLoc = var->getLocation();
13083       // If the note doesn't add any useful information other than a source
13084       // location, fold it into the primary diagnostic.
13085       if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13086                                    diag::note_invalid_subexpr_in_const_expr) {
13087         DiagLoc = Notes[0].first;
13088         Notes.clear();
13089       }
13090       Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
13091           << var << Init->getSourceRange();
13092       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
13093         Diag(Notes[I].first, Notes[I].second);
13094     } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
13095       auto *Attr = var->getAttr<ConstInitAttr>();
13096       Diag(var->getLocation(), diag::err_require_constant_init_failed)
13097           << Init->getSourceRange();
13098       Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
13099           << Attr->getRange() << Attr->isConstinit();
13100       for (auto &it : Notes)
13101         Diag(it.first, it.second);
13102     } else if (IsGlobal &&
13103                !getDiagnostics().isIgnored(diag::warn_global_constructor,
13104                                            var->getLocation())) {
13105       // Warn about globals which don't have a constant initializer.  Don't
13106       // warn about globals with a non-trivial destructor because we already
13107       // warned about them.
13108       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13109       if (!(RD && !RD->hasTrivialDestructor())) {
13110         // checkConstInit() here permits trivial default initialization even in
13111         // C++11 onwards, where such an initializer is not a constant initializer
13112         // but nonetheless doesn't require a global constructor.
13113         if (!checkConstInit())
13114           Diag(var->getLocation(), diag::warn_global_constructor)
13115               << Init->getSourceRange();
13116       }
13117     }
13118   }
13119 
13120   // Require the destructor.
13121   if (!type->isDependentType())
13122     if (const RecordType *recordType = baseType->getAs<RecordType>())
13123       FinalizeVarWithDestructor(var, recordType);
13124 
13125   // If this variable must be emitted, add it as an initializer for the current
13126   // module.
13127   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13128     Context.addModuleInitializer(ModuleScopes.back().Module, var);
13129 
13130   // Build the bindings if this is a structured binding declaration.
13131   if (auto *DD = dyn_cast<DecompositionDecl>(var))
13132     CheckCompleteDecompositionDeclaration(DD);
13133 }
13134 
13135 /// Determines if a variable's alignment is dependent.
13136 static bool hasDependentAlignment(VarDecl *VD) {
13137   if (VD->getType()->isDependentType())
13138     return true;
13139   for (auto *I : VD->specific_attrs<AlignedAttr>())
13140     if (I->isAlignmentDependent())
13141       return true;
13142   return false;
13143 }
13144 
13145 /// Check if VD needs to be dllexport/dllimport due to being in a
13146 /// dllexport/import function.
13147 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
13148   assert(VD->isStaticLocal());
13149 
13150   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13151 
13152   // Find outermost function when VD is in lambda function.
13153   while (FD && !getDLLAttr(FD) &&
13154          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13155          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13156     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13157   }
13158 
13159   if (!FD)
13160     return;
13161 
13162   // Static locals inherit dll attributes from their function.
13163   if (Attr *A = getDLLAttr(FD)) {
13164     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13165     NewAttr->setInherited(true);
13166     VD->addAttr(NewAttr);
13167   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13168     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13169     NewAttr->setInherited(true);
13170     VD->addAttr(NewAttr);
13171 
13172     // Export this function to enforce exporting this static variable even
13173     // if it is not used in this compilation unit.
13174     if (!FD->hasAttr<DLLExportAttr>())
13175       FD->addAttr(NewAttr);
13176 
13177   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13178     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13179     NewAttr->setInherited(true);
13180     VD->addAttr(NewAttr);
13181   }
13182 }
13183 
13184 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13185 /// any semantic actions necessary after any initializer has been attached.
13186 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13187   // Note that we are no longer parsing the initializer for this declaration.
13188   ParsingInitForAutoVars.erase(ThisDecl);
13189 
13190   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13191   if (!VD)
13192     return;
13193 
13194   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13195   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13196       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13197     if (PragmaClangBSSSection.Valid)
13198       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13199           Context, PragmaClangBSSSection.SectionName,
13200           PragmaClangBSSSection.PragmaLocation,
13201           AttributeCommonInfo::AS_Pragma));
13202     if (PragmaClangDataSection.Valid)
13203       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13204           Context, PragmaClangDataSection.SectionName,
13205           PragmaClangDataSection.PragmaLocation,
13206           AttributeCommonInfo::AS_Pragma));
13207     if (PragmaClangRodataSection.Valid)
13208       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13209           Context, PragmaClangRodataSection.SectionName,
13210           PragmaClangRodataSection.PragmaLocation,
13211           AttributeCommonInfo::AS_Pragma));
13212     if (PragmaClangRelroSection.Valid)
13213       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13214           Context, PragmaClangRelroSection.SectionName,
13215           PragmaClangRelroSection.PragmaLocation,
13216           AttributeCommonInfo::AS_Pragma));
13217   }
13218 
13219   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13220     for (auto *BD : DD->bindings()) {
13221       FinalizeDeclaration(BD);
13222     }
13223   }
13224 
13225   checkAttributesAfterMerging(*this, *VD);
13226 
13227   // Perform TLS alignment check here after attributes attached to the variable
13228   // which may affect the alignment have been processed. Only perform the check
13229   // if the target has a maximum TLS alignment (zero means no constraints).
13230   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13231     // Protect the check so that it's not performed on dependent types and
13232     // dependent alignments (we can't determine the alignment in that case).
13233     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
13234         !VD->isInvalidDecl()) {
13235       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13236       if (Context.getDeclAlign(VD) > MaxAlignChars) {
13237         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13238           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13239           << (unsigned)MaxAlignChars.getQuantity();
13240       }
13241     }
13242   }
13243 
13244   if (VD->isStaticLocal())
13245     CheckStaticLocalForDllExport(VD);
13246 
13247   // Perform check for initializers of device-side global variables.
13248   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13249   // 7.5). We must also apply the same checks to all __shared__
13250   // variables whether they are local or not. CUDA also allows
13251   // constant initializers for __constant__ and __device__ variables.
13252   if (getLangOpts().CUDA)
13253     checkAllowedCUDAInitializer(VD);
13254 
13255   // Grab the dllimport or dllexport attribute off of the VarDecl.
13256   const InheritableAttr *DLLAttr = getDLLAttr(VD);
13257 
13258   // Imported static data members cannot be defined out-of-line.
13259   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13260     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13261         VD->isThisDeclarationADefinition()) {
13262       // We allow definitions of dllimport class template static data members
13263       // with a warning.
13264       CXXRecordDecl *Context =
13265         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13266       bool IsClassTemplateMember =
13267           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13268           Context->getDescribedClassTemplate();
13269 
13270       Diag(VD->getLocation(),
13271            IsClassTemplateMember
13272                ? diag::warn_attribute_dllimport_static_field_definition
13273                : diag::err_attribute_dllimport_static_field_definition);
13274       Diag(IA->getLocation(), diag::note_attribute);
13275       if (!IsClassTemplateMember)
13276         VD->setInvalidDecl();
13277     }
13278   }
13279 
13280   // dllimport/dllexport variables cannot be thread local, their TLS index
13281   // isn't exported with the variable.
13282   if (DLLAttr && VD->getTLSKind()) {
13283     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13284     if (F && getDLLAttr(F)) {
13285       assert(VD->isStaticLocal());
13286       // But if this is a static local in a dlimport/dllexport function, the
13287       // function will never be inlined, which means the var would never be
13288       // imported, so having it marked import/export is safe.
13289     } else {
13290       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13291                                                                     << DLLAttr;
13292       VD->setInvalidDecl();
13293     }
13294   }
13295 
13296   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13297     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13298       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
13299       VD->dropAttr<UsedAttr>();
13300     }
13301   }
13302 
13303   const DeclContext *DC = VD->getDeclContext();
13304   // If there's a #pragma GCC visibility in scope, and this isn't a class
13305   // member, set the visibility of this variable.
13306   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13307     AddPushedVisibilityAttribute(VD);
13308 
13309   // FIXME: Warn on unused var template partial specializations.
13310   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13311     MarkUnusedFileScopedDecl(VD);
13312 
13313   // Now we have parsed the initializer and can update the table of magic
13314   // tag values.
13315   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13316       !VD->getType()->isIntegralOrEnumerationType())
13317     return;
13318 
13319   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13320     const Expr *MagicValueExpr = VD->getInit();
13321     if (!MagicValueExpr) {
13322       continue;
13323     }
13324     Optional<llvm::APSInt> MagicValueInt;
13325     if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13326       Diag(I->getRange().getBegin(),
13327            diag::err_type_tag_for_datatype_not_ice)
13328         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13329       continue;
13330     }
13331     if (MagicValueInt->getActiveBits() > 64) {
13332       Diag(I->getRange().getBegin(),
13333            diag::err_type_tag_for_datatype_too_large)
13334         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13335       continue;
13336     }
13337     uint64_t MagicValue = MagicValueInt->getZExtValue();
13338     RegisterTypeTagForDatatype(I->getArgumentKind(),
13339                                MagicValue,
13340                                I->getMatchingCType(),
13341                                I->getLayoutCompatible(),
13342                                I->getMustBeNull());
13343   }
13344 }
13345 
13346 static bool hasDeducedAuto(DeclaratorDecl *DD) {
13347   auto *VD = dyn_cast<VarDecl>(DD);
13348   return VD && !VD->getType()->hasAutoForTrailingReturnType();
13349 }
13350 
13351 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13352                                                    ArrayRef<Decl *> Group) {
13353   SmallVector<Decl*, 8> Decls;
13354 
13355   if (DS.isTypeSpecOwned())
13356     Decls.push_back(DS.getRepAsDecl());
13357 
13358   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13359   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13360   bool DiagnosedMultipleDecomps = false;
13361   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13362   bool DiagnosedNonDeducedAuto = false;
13363 
13364   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13365     if (Decl *D = Group[i]) {
13366       // For declarators, there are some additional syntactic-ish checks we need
13367       // to perform.
13368       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13369         if (!FirstDeclaratorInGroup)
13370           FirstDeclaratorInGroup = DD;
13371         if (!FirstDecompDeclaratorInGroup)
13372           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13373         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13374             !hasDeducedAuto(DD))
13375           FirstNonDeducedAutoInGroup = DD;
13376 
13377         if (FirstDeclaratorInGroup != DD) {
13378           // A decomposition declaration cannot be combined with any other
13379           // declaration in the same group.
13380           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13381             Diag(FirstDecompDeclaratorInGroup->getLocation(),
13382                  diag::err_decomp_decl_not_alone)
13383                 << FirstDeclaratorInGroup->getSourceRange()
13384                 << DD->getSourceRange();
13385             DiagnosedMultipleDecomps = true;
13386           }
13387 
13388           // A declarator that uses 'auto' in any way other than to declare a
13389           // variable with a deduced type cannot be combined with any other
13390           // declarator in the same group.
13391           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13392             Diag(FirstNonDeducedAutoInGroup->getLocation(),
13393                  diag::err_auto_non_deduced_not_alone)
13394                 << FirstNonDeducedAutoInGroup->getType()
13395                        ->hasAutoForTrailingReturnType()
13396                 << FirstDeclaratorInGroup->getSourceRange()
13397                 << DD->getSourceRange();
13398             DiagnosedNonDeducedAuto = true;
13399           }
13400         }
13401       }
13402 
13403       Decls.push_back(D);
13404     }
13405   }
13406 
13407   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13408     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13409       handleTagNumbering(Tag, S);
13410       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13411           getLangOpts().CPlusPlus)
13412         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13413     }
13414   }
13415 
13416   return BuildDeclaratorGroup(Decls);
13417 }
13418 
13419 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
13420 /// group, performing any necessary semantic checking.
13421 Sema::DeclGroupPtrTy
13422 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13423   // C++14 [dcl.spec.auto]p7: (DR1347)
13424   //   If the type that replaces the placeholder type is not the same in each
13425   //   deduction, the program is ill-formed.
13426   if (Group.size() > 1) {
13427     QualType Deduced;
13428     VarDecl *DeducedDecl = nullptr;
13429     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13430       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13431       if (!D || D->isInvalidDecl())
13432         break;
13433       DeducedType *DT = D->getType()->getContainedDeducedType();
13434       if (!DT || DT->getDeducedType().isNull())
13435         continue;
13436       if (Deduced.isNull()) {
13437         Deduced = DT->getDeducedType();
13438         DeducedDecl = D;
13439       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13440         auto *AT = dyn_cast<AutoType>(DT);
13441         auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13442                         diag::err_auto_different_deductions)
13443                    << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
13444                    << DeducedDecl->getDeclName() << DT->getDeducedType()
13445                    << D->getDeclName();
13446         if (DeducedDecl->hasInit())
13447           Dia << DeducedDecl->getInit()->getSourceRange();
13448         if (D->getInit())
13449           Dia << D->getInit()->getSourceRange();
13450         D->setInvalidDecl();
13451         break;
13452       }
13453     }
13454   }
13455 
13456   ActOnDocumentableDecls(Group);
13457 
13458   return DeclGroupPtrTy::make(
13459       DeclGroupRef::Create(Context, Group.data(), Group.size()));
13460 }
13461 
13462 void Sema::ActOnDocumentableDecl(Decl *D) {
13463   ActOnDocumentableDecls(D);
13464 }
13465 
13466 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13467   // Don't parse the comment if Doxygen diagnostics are ignored.
13468   if (Group.empty() || !Group[0])
13469     return;
13470 
13471   if (Diags.isIgnored(diag::warn_doc_param_not_found,
13472                       Group[0]->getLocation()) &&
13473       Diags.isIgnored(diag::warn_unknown_comment_command_name,
13474                       Group[0]->getLocation()))
13475     return;
13476 
13477   if (Group.size() >= 2) {
13478     // This is a decl group.  Normally it will contain only declarations
13479     // produced from declarator list.  But in case we have any definitions or
13480     // additional declaration references:
13481     //   'typedef struct S {} S;'
13482     //   'typedef struct S *S;'
13483     //   'struct S *pS;'
13484     // FinalizeDeclaratorGroup adds these as separate declarations.
13485     Decl *MaybeTagDecl = Group[0];
13486     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13487       Group = Group.slice(1);
13488     }
13489   }
13490 
13491   // FIMXE: We assume every Decl in the group is in the same file.
13492   // This is false when preprocessor constructs the group from decls in
13493   // different files (e. g. macros or #include).
13494   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13495 }
13496 
13497 /// Common checks for a parameter-declaration that should apply to both function
13498 /// parameters and non-type template parameters.
13499 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13500   // Check that there are no default arguments inside the type of this
13501   // parameter.
13502   if (getLangOpts().CPlusPlus)
13503     CheckExtraCXXDefaultArguments(D);
13504 
13505   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13506   if (D.getCXXScopeSpec().isSet()) {
13507     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13508       << D.getCXXScopeSpec().getRange();
13509   }
13510 
13511   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13512   // simple identifier except [...irrelevant cases...].
13513   switch (D.getName().getKind()) {
13514   case UnqualifiedIdKind::IK_Identifier:
13515     break;
13516 
13517   case UnqualifiedIdKind::IK_OperatorFunctionId:
13518   case UnqualifiedIdKind::IK_ConversionFunctionId:
13519   case UnqualifiedIdKind::IK_LiteralOperatorId:
13520   case UnqualifiedIdKind::IK_ConstructorName:
13521   case UnqualifiedIdKind::IK_DestructorName:
13522   case UnqualifiedIdKind::IK_ImplicitSelfParam:
13523   case UnqualifiedIdKind::IK_DeductionGuideName:
13524     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13525       << GetNameForDeclarator(D).getName();
13526     break;
13527 
13528   case UnqualifiedIdKind::IK_TemplateId:
13529   case UnqualifiedIdKind::IK_ConstructorTemplateId:
13530     // GetNameForDeclarator would not produce a useful name in this case.
13531     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13532     break;
13533   }
13534 }
13535 
13536 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13537 /// to introduce parameters into function prototype scope.
13538 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13539   const DeclSpec &DS = D.getDeclSpec();
13540 
13541   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13542 
13543   // C++03 [dcl.stc]p2 also permits 'auto'.
13544   StorageClass SC = SC_None;
13545   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13546     SC = SC_Register;
13547     // In C++11, the 'register' storage class specifier is deprecated.
13548     // In C++17, it is not allowed, but we tolerate it as an extension.
13549     if (getLangOpts().CPlusPlus11) {
13550       Diag(DS.getStorageClassSpecLoc(),
13551            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13552                                      : diag::warn_deprecated_register)
13553         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13554     }
13555   } else if (getLangOpts().CPlusPlus &&
13556              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13557     SC = SC_Auto;
13558   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13559     Diag(DS.getStorageClassSpecLoc(),
13560          diag::err_invalid_storage_class_in_func_decl);
13561     D.getMutableDeclSpec().ClearStorageClassSpecs();
13562   }
13563 
13564   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13565     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13566       << DeclSpec::getSpecifierName(TSCS);
13567   if (DS.isInlineSpecified())
13568     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13569         << getLangOpts().CPlusPlus17;
13570   if (DS.hasConstexprSpecifier())
13571     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13572         << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
13573 
13574   DiagnoseFunctionSpecifiers(DS);
13575 
13576   CheckFunctionOrTemplateParamDeclarator(S, D);
13577 
13578   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13579   QualType parmDeclType = TInfo->getType();
13580 
13581   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13582   IdentifierInfo *II = D.getIdentifier();
13583   if (II) {
13584     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13585                    ForVisibleRedeclaration);
13586     LookupName(R, S);
13587     if (R.isSingleResult()) {
13588       NamedDecl *PrevDecl = R.getFoundDecl();
13589       if (PrevDecl->isTemplateParameter()) {
13590         // Maybe we will complain about the shadowed template parameter.
13591         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13592         // Just pretend that we didn't see the previous declaration.
13593         PrevDecl = nullptr;
13594       } else if (S->isDeclScope(PrevDecl)) {
13595         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13596         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13597 
13598         // Recover by removing the name
13599         II = nullptr;
13600         D.SetIdentifier(nullptr, D.getIdentifierLoc());
13601         D.setInvalidType(true);
13602       }
13603     }
13604   }
13605 
13606   // Temporarily put parameter variables in the translation unit, not
13607   // the enclosing context.  This prevents them from accidentally
13608   // looking like class members in C++.
13609   ParmVarDecl *New =
13610       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13611                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13612 
13613   if (D.isInvalidType())
13614     New->setInvalidDecl();
13615 
13616   assert(S->isFunctionPrototypeScope());
13617   assert(S->getFunctionPrototypeDepth() >= 1);
13618   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13619                     S->getNextFunctionPrototypeIndex());
13620 
13621   // Add the parameter declaration into this scope.
13622   S->AddDecl(New);
13623   if (II)
13624     IdResolver.AddDecl(New);
13625 
13626   ProcessDeclAttributes(S, New, D);
13627 
13628   if (D.getDeclSpec().isModulePrivateSpecified())
13629     Diag(New->getLocation(), diag::err_module_private_local)
13630         << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13631         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13632 
13633   if (New->hasAttr<BlocksAttr>()) {
13634     Diag(New->getLocation(), diag::err_block_on_nonlocal);
13635   }
13636 
13637   if (getLangOpts().OpenCL)
13638     deduceOpenCLAddressSpace(New);
13639 
13640   return New;
13641 }
13642 
13643 /// Synthesizes a variable for a parameter arising from a
13644 /// typedef.
13645 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13646                                               SourceLocation Loc,
13647                                               QualType T) {
13648   /* FIXME: setting StartLoc == Loc.
13649      Would it be worth to modify callers so as to provide proper source
13650      location for the unnamed parameters, embedding the parameter's type? */
13651   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13652                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
13653                                            SC_None, nullptr);
13654   Param->setImplicit();
13655   return Param;
13656 }
13657 
13658 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13659   // Don't diagnose unused-parameter errors in template instantiations; we
13660   // will already have done so in the template itself.
13661   if (inTemplateInstantiation())
13662     return;
13663 
13664   for (const ParmVarDecl *Parameter : Parameters) {
13665     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13666         !Parameter->hasAttr<UnusedAttr>()) {
13667       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13668         << Parameter->getDeclName();
13669     }
13670   }
13671 }
13672 
13673 void Sema::DiagnoseSizeOfParametersAndReturnValue(
13674     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13675   if (LangOpts.NumLargeByValueCopy == 0) // No check.
13676     return;
13677 
13678   // Warn if the return value is pass-by-value and larger than the specified
13679   // threshold.
13680   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13681     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13682     if (Size > LangOpts.NumLargeByValueCopy)
13683       Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
13684   }
13685 
13686   // Warn if any parameter is pass-by-value and larger than the specified
13687   // threshold.
13688   for (const ParmVarDecl *Parameter : Parameters) {
13689     QualType T = Parameter->getType();
13690     if (T->isDependentType() || !T.isPODType(Context))
13691       continue;
13692     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13693     if (Size > LangOpts.NumLargeByValueCopy)
13694       Diag(Parameter->getLocation(), diag::warn_parameter_size)
13695           << Parameter << Size;
13696   }
13697 }
13698 
13699 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13700                                   SourceLocation NameLoc, IdentifierInfo *Name,
13701                                   QualType T, TypeSourceInfo *TSInfo,
13702                                   StorageClass SC) {
13703   // In ARC, infer a lifetime qualifier for appropriate parameter types.
13704   if (getLangOpts().ObjCAutoRefCount &&
13705       T.getObjCLifetime() == Qualifiers::OCL_None &&
13706       T->isObjCLifetimeType()) {
13707 
13708     Qualifiers::ObjCLifetime lifetime;
13709 
13710     // Special cases for arrays:
13711     //   - if it's const, use __unsafe_unretained
13712     //   - otherwise, it's an error
13713     if (T->isArrayType()) {
13714       if (!T.isConstQualified()) {
13715         if (DelayedDiagnostics.shouldDelayDiagnostics())
13716           DelayedDiagnostics.add(
13717               sema::DelayedDiagnostic::makeForbiddenType(
13718               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13719         else
13720           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13721               << TSInfo->getTypeLoc().getSourceRange();
13722       }
13723       lifetime = Qualifiers::OCL_ExplicitNone;
13724     } else {
13725       lifetime = T->getObjCARCImplicitLifetime();
13726     }
13727     T = Context.getLifetimeQualifiedType(T, lifetime);
13728   }
13729 
13730   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13731                                          Context.getAdjustedParameterType(T),
13732                                          TSInfo, SC, nullptr);
13733 
13734   // Make a note if we created a new pack in the scope of a lambda, so that
13735   // we know that references to that pack must also be expanded within the
13736   // lambda scope.
13737   if (New->isParameterPack())
13738     if (auto *LSI = getEnclosingLambda())
13739       LSI->LocalPacks.push_back(New);
13740 
13741   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13742       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13743     checkNonTrivialCUnion(New->getType(), New->getLocation(),
13744                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13745 
13746   // Parameters can not be abstract class types.
13747   // For record types, this is done by the AbstractClassUsageDiagnoser once
13748   // the class has been completely parsed.
13749   if (!CurContext->isRecord() &&
13750       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13751                              AbstractParamType))
13752     New->setInvalidDecl();
13753 
13754   // Parameter declarators cannot be interface types. All ObjC objects are
13755   // passed by reference.
13756   if (T->isObjCObjectType()) {
13757     SourceLocation TypeEndLoc =
13758         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13759     Diag(NameLoc,
13760          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13761       << FixItHint::CreateInsertion(TypeEndLoc, "*");
13762     T = Context.getObjCObjectPointerType(T);
13763     New->setType(T);
13764   }
13765 
13766   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13767   // duration shall not be qualified by an address-space qualifier."
13768   // Since all parameters have automatic store duration, they can not have
13769   // an address space.
13770   if (T.getAddressSpace() != LangAS::Default &&
13771       // OpenCL allows function arguments declared to be an array of a type
13772       // to be qualified with an address space.
13773       !(getLangOpts().OpenCL &&
13774         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13775     Diag(NameLoc, diag::err_arg_with_address_space);
13776     New->setInvalidDecl();
13777   }
13778 
13779   // PPC MMA non-pointer types are not allowed as function argument types.
13780   if (Context.getTargetInfo().getTriple().isPPC64() &&
13781       CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
13782     New->setInvalidDecl();
13783   }
13784 
13785   return New;
13786 }
13787 
13788 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
13789                                            SourceLocation LocAfterDecls) {
13790   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
13791 
13792   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
13793   // for a K&R function.
13794   if (!FTI.hasPrototype) {
13795     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
13796       --i;
13797       if (FTI.Params[i].Param == nullptr) {
13798         SmallString<256> Code;
13799         llvm::raw_svector_ostream(Code)
13800             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
13801         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
13802             << FTI.Params[i].Ident
13803             << FixItHint::CreateInsertion(LocAfterDecls, Code);
13804 
13805         // Implicitly declare the argument as type 'int' for lack of a better
13806         // type.
13807         AttributeFactory attrs;
13808         DeclSpec DS(attrs);
13809         const char* PrevSpec; // unused
13810         unsigned DiagID; // unused
13811         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
13812                            DiagID, Context.getPrintingPolicy());
13813         // Use the identifier location for the type source range.
13814         DS.SetRangeStart(FTI.Params[i].IdentLoc);
13815         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
13816         Declarator ParamD(DS, DeclaratorContext::KNRTypeList);
13817         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
13818         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
13819       }
13820     }
13821   }
13822 }
13823 
13824 Decl *
13825 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
13826                               MultiTemplateParamsArg TemplateParameterLists,
13827                               SkipBodyInfo *SkipBody) {
13828   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
13829   assert(D.isFunctionDeclarator() && "Not a function declarator!");
13830   Scope *ParentScope = FnBodyScope->getParent();
13831 
13832   // Check if we are in an `omp begin/end declare variant` scope. If we are, and
13833   // we define a non-templated function definition, we will create a declaration
13834   // instead (=BaseFD), and emit the definition with a mangled name afterwards.
13835   // The base function declaration will have the equivalent of an `omp declare
13836   // variant` annotation which specifies the mangled definition as a
13837   // specialization function under the OpenMP context defined as part of the
13838   // `omp begin declare variant`.
13839   SmallVector<FunctionDecl *, 4> Bases;
13840   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
13841     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
13842         ParentScope, D, TemplateParameterLists, Bases);
13843 
13844   D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
13845   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
13846   Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
13847 
13848   if (!Bases.empty())
13849     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
13850 
13851   return Dcl;
13852 }
13853 
13854 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
13855   Consumer.HandleInlineFunctionDefinition(D);
13856 }
13857 
13858 static bool
13859 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
13860                                 const FunctionDecl *&PossiblePrototype) {
13861   // Don't warn about invalid declarations.
13862   if (FD->isInvalidDecl())
13863     return false;
13864 
13865   // Or declarations that aren't global.
13866   if (!FD->isGlobal())
13867     return false;
13868 
13869   // Don't warn about C++ member functions.
13870   if (isa<CXXMethodDecl>(FD))
13871     return false;
13872 
13873   // Don't warn about 'main'.
13874   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
13875     if (IdentifierInfo *II = FD->getIdentifier())
13876       if (II->isStr("main"))
13877         return false;
13878 
13879   // Don't warn about inline functions.
13880   if (FD->isInlined())
13881     return false;
13882 
13883   // Don't warn about function templates.
13884   if (FD->getDescribedFunctionTemplate())
13885     return false;
13886 
13887   // Don't warn about function template specializations.
13888   if (FD->isFunctionTemplateSpecialization())
13889     return false;
13890 
13891   // Don't warn for OpenCL kernels.
13892   if (FD->hasAttr<OpenCLKernelAttr>())
13893     return false;
13894 
13895   // Don't warn on explicitly deleted functions.
13896   if (FD->isDeleted())
13897     return false;
13898 
13899   for (const FunctionDecl *Prev = FD->getPreviousDecl();
13900        Prev; Prev = Prev->getPreviousDecl()) {
13901     // Ignore any declarations that occur in function or method
13902     // scope, because they aren't visible from the header.
13903     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
13904       continue;
13905 
13906     PossiblePrototype = Prev;
13907     return Prev->getType()->isFunctionNoProtoType();
13908   }
13909 
13910   return true;
13911 }
13912 
13913 void
13914 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
13915                                    const FunctionDecl *EffectiveDefinition,
13916                                    SkipBodyInfo *SkipBody) {
13917   const FunctionDecl *Definition = EffectiveDefinition;
13918   if (!Definition &&
13919       !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
13920     return;
13921 
13922   if (Definition->getFriendObjectKind() != Decl::FOK_None) {
13923     if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
13924       if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
13925         // A merged copy of the same function, instantiated as a member of
13926         // the same class, is OK.
13927         if (declaresSameEntity(OrigFD, OrigDef) &&
13928             declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
13929                                cast<Decl>(FD->getLexicalDeclContext())))
13930           return;
13931       }
13932     }
13933   }
13934 
13935   if (canRedefineFunction(Definition, getLangOpts()))
13936     return;
13937 
13938   // Don't emit an error when this is redefinition of a typo-corrected
13939   // definition.
13940   if (TypoCorrectedFunctionDefinitions.count(Definition))
13941     return;
13942 
13943   // If we don't have a visible definition of the function, and it's inline or
13944   // a template, skip the new definition.
13945   if (SkipBody && !hasVisibleDefinition(Definition) &&
13946       (Definition->getFormalLinkage() == InternalLinkage ||
13947        Definition->isInlined() ||
13948        Definition->getDescribedFunctionTemplate() ||
13949        Definition->getNumTemplateParameterLists())) {
13950     SkipBody->ShouldSkip = true;
13951     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
13952     if (auto *TD = Definition->getDescribedFunctionTemplate())
13953       makeMergedDefinitionVisible(TD);
13954     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
13955     return;
13956   }
13957 
13958   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
13959       Definition->getStorageClass() == SC_Extern)
13960     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
13961         << FD << getLangOpts().CPlusPlus;
13962   else
13963     Diag(FD->getLocation(), diag::err_redefinition) << FD;
13964 
13965   Diag(Definition->getLocation(), diag::note_previous_definition);
13966   FD->setInvalidDecl();
13967 }
13968 
13969 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
13970                                    Sema &S) {
13971   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
13972 
13973   LambdaScopeInfo *LSI = S.PushLambdaScope();
13974   LSI->CallOperator = CallOperator;
13975   LSI->Lambda = LambdaClass;
13976   LSI->ReturnType = CallOperator->getReturnType();
13977   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
13978 
13979   if (LCD == LCD_None)
13980     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
13981   else if (LCD == LCD_ByCopy)
13982     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
13983   else if (LCD == LCD_ByRef)
13984     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
13985   DeclarationNameInfo DNI = CallOperator->getNameInfo();
13986 
13987   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
13988   LSI->Mutable = !CallOperator->isConst();
13989 
13990   // Add the captures to the LSI so they can be noted as already
13991   // captured within tryCaptureVar.
13992   auto I = LambdaClass->field_begin();
13993   for (const auto &C : LambdaClass->captures()) {
13994     if (C.capturesVariable()) {
13995       VarDecl *VD = C.getCapturedVar();
13996       if (VD->isInitCapture())
13997         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
13998       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
13999       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
14000           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
14001           /*EllipsisLoc*/C.isPackExpansion()
14002                          ? C.getEllipsisLoc() : SourceLocation(),
14003           I->getType(), /*Invalid*/false);
14004 
14005     } else if (C.capturesThis()) {
14006       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
14007                           C.getCaptureKind() == LCK_StarThis);
14008     } else {
14009       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
14010                              I->getType());
14011     }
14012     ++I;
14013   }
14014 }
14015 
14016 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
14017                                     SkipBodyInfo *SkipBody) {
14018   if (!D) {
14019     // Parsing the function declaration failed in some way. Push on a fake scope
14020     // anyway so we can try to parse the function body.
14021     PushFunctionScope();
14022     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14023     return D;
14024   }
14025 
14026   FunctionDecl *FD = nullptr;
14027 
14028   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
14029     FD = FunTmpl->getTemplatedDecl();
14030   else
14031     FD = cast<FunctionDecl>(D);
14032 
14033   // Do not push if it is a lambda because one is already pushed when building
14034   // the lambda in ActOnStartOfLambdaDefinition().
14035   if (!isLambdaCallOperator(FD))
14036     PushExpressionEvaluationContext(
14037         FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
14038                           : ExprEvalContexts.back().Context);
14039 
14040   // Check for defining attributes before the check for redefinition.
14041   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
14042     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
14043     FD->dropAttr<AliasAttr>();
14044     FD->setInvalidDecl();
14045   }
14046   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
14047     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
14048     FD->dropAttr<IFuncAttr>();
14049     FD->setInvalidDecl();
14050   }
14051 
14052   if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
14053     if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
14054         Ctor->isDefaultConstructor() &&
14055         Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14056       // If this is an MS ABI dllexport default constructor, instantiate any
14057       // default arguments.
14058       InstantiateDefaultCtorDefaultArgs(Ctor);
14059     }
14060   }
14061 
14062   // See if this is a redefinition. If 'will have body' (or similar) is already
14063   // set, then these checks were already performed when it was set.
14064   if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
14065       !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
14066     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14067 
14068     // If we're skipping the body, we're done. Don't enter the scope.
14069     if (SkipBody && SkipBody->ShouldSkip)
14070       return D;
14071   }
14072 
14073   // Mark this function as "will have a body eventually".  This lets users to
14074   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14075   // this function.
14076   FD->setWillHaveBody();
14077 
14078   // If we are instantiating a generic lambda call operator, push
14079   // a LambdaScopeInfo onto the function stack.  But use the information
14080   // that's already been calculated (ActOnLambdaExpr) to prime the current
14081   // LambdaScopeInfo.
14082   // When the template operator is being specialized, the LambdaScopeInfo,
14083   // has to be properly restored so that tryCaptureVariable doesn't try
14084   // and capture any new variables. In addition when calculating potential
14085   // captures during transformation of nested lambdas, it is necessary to
14086   // have the LSI properly restored.
14087   if (isGenericLambdaCallOperatorSpecialization(FD)) {
14088     assert(inTemplateInstantiation() &&
14089            "There should be an active template instantiation on the stack "
14090            "when instantiating a generic lambda!");
14091     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14092   } else {
14093     // Enter a new function scope
14094     PushFunctionScope();
14095   }
14096 
14097   // Builtin functions cannot be defined.
14098   if (unsigned BuiltinID = FD->getBuiltinID()) {
14099     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14100         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14101       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14102       FD->setInvalidDecl();
14103     }
14104   }
14105 
14106   // The return type of a function definition must be complete
14107   // (C99 6.9.1p3, C++ [dcl.fct]p6).
14108   QualType ResultType = FD->getReturnType();
14109   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14110       !FD->isInvalidDecl() &&
14111       RequireCompleteType(FD->getLocation(), ResultType,
14112                           diag::err_func_def_incomplete_result))
14113     FD->setInvalidDecl();
14114 
14115   if (FnBodyScope)
14116     PushDeclContext(FnBodyScope, FD);
14117 
14118   // Check the validity of our function parameters
14119   CheckParmsForFunctionDef(FD->parameters(),
14120                            /*CheckParameterNames=*/true);
14121 
14122   // Add non-parameter declarations already in the function to the current
14123   // scope.
14124   if (FnBodyScope) {
14125     for (Decl *NPD : FD->decls()) {
14126       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14127       if (!NonParmDecl)
14128         continue;
14129       assert(!isa<ParmVarDecl>(NonParmDecl) &&
14130              "parameters should not be in newly created FD yet");
14131 
14132       // If the decl has a name, make it accessible in the current scope.
14133       if (NonParmDecl->getDeclName())
14134         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14135 
14136       // Similarly, dive into enums and fish their constants out, making them
14137       // accessible in this scope.
14138       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14139         for (auto *EI : ED->enumerators())
14140           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14141       }
14142     }
14143   }
14144 
14145   // Introduce our parameters into the function scope
14146   for (auto Param : FD->parameters()) {
14147     Param->setOwningFunction(FD);
14148 
14149     // If this has an identifier, add it to the scope stack.
14150     if (Param->getIdentifier() && FnBodyScope) {
14151       CheckShadow(FnBodyScope, Param);
14152 
14153       PushOnScopeChains(Param, FnBodyScope);
14154     }
14155   }
14156 
14157   // Ensure that the function's exception specification is instantiated.
14158   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14159     ResolveExceptionSpec(D->getLocation(), FPT);
14160 
14161   // dllimport cannot be applied to non-inline function definitions.
14162   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14163       !FD->isTemplateInstantiation()) {
14164     assert(!FD->hasAttr<DLLExportAttr>());
14165     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14166     FD->setInvalidDecl();
14167     return D;
14168   }
14169   // We want to attach documentation to original Decl (which might be
14170   // a function template).
14171   ActOnDocumentableDecl(D);
14172   if (getCurLexicalContext()->isObjCContainer() &&
14173       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14174       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14175     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14176 
14177   return D;
14178 }
14179 
14180 /// Given the set of return statements within a function body,
14181 /// compute the variables that are subject to the named return value
14182 /// optimization.
14183 ///
14184 /// Each of the variables that is subject to the named return value
14185 /// optimization will be marked as NRVO variables in the AST, and any
14186 /// return statement that has a marked NRVO variable as its NRVO candidate can
14187 /// use the named return value optimization.
14188 ///
14189 /// This function applies a very simplistic algorithm for NRVO: if every return
14190 /// statement in the scope of a variable has the same NRVO candidate, that
14191 /// candidate is an NRVO variable.
14192 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14193   ReturnStmt **Returns = Scope->Returns.data();
14194 
14195   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14196     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14197       if (!NRVOCandidate->isNRVOVariable())
14198         Returns[I]->setNRVOCandidate(nullptr);
14199     }
14200   }
14201 }
14202 
14203 bool Sema::canDelayFunctionBody(const Declarator &D) {
14204   // We can't delay parsing the body of a constexpr function template (yet).
14205   if (D.getDeclSpec().hasConstexprSpecifier())
14206     return false;
14207 
14208   // We can't delay parsing the body of a function template with a deduced
14209   // return type (yet).
14210   if (D.getDeclSpec().hasAutoTypeSpec()) {
14211     // If the placeholder introduces a non-deduced trailing return type,
14212     // we can still delay parsing it.
14213     if (D.getNumTypeObjects()) {
14214       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14215       if (Outer.Kind == DeclaratorChunk::Function &&
14216           Outer.Fun.hasTrailingReturnType()) {
14217         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14218         return Ty.isNull() || !Ty->isUndeducedType();
14219       }
14220     }
14221     return false;
14222   }
14223 
14224   return true;
14225 }
14226 
14227 bool Sema::canSkipFunctionBody(Decl *D) {
14228   // We cannot skip the body of a function (or function template) which is
14229   // constexpr, since we may need to evaluate its body in order to parse the
14230   // rest of the file.
14231   // We cannot skip the body of a function with an undeduced return type,
14232   // because any callers of that function need to know the type.
14233   if (const FunctionDecl *FD = D->getAsFunction()) {
14234     if (FD->isConstexpr())
14235       return false;
14236     // We can't simply call Type::isUndeducedType here, because inside template
14237     // auto can be deduced to a dependent type, which is not considered
14238     // "undeduced".
14239     if (FD->getReturnType()->getContainedDeducedType())
14240       return false;
14241   }
14242   return Consumer.shouldSkipFunctionBody(D);
14243 }
14244 
14245 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14246   if (!Decl)
14247     return nullptr;
14248   if (FunctionDecl *FD = Decl->getAsFunction())
14249     FD->setHasSkippedBody();
14250   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14251     MD->setHasSkippedBody();
14252   return Decl;
14253 }
14254 
14255 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14256   return ActOnFinishFunctionBody(D, BodyArg, false);
14257 }
14258 
14259 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
14260 /// body.
14261 class ExitFunctionBodyRAII {
14262 public:
14263   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14264   ~ExitFunctionBodyRAII() {
14265     if (!IsLambda)
14266       S.PopExpressionEvaluationContext();
14267   }
14268 
14269 private:
14270   Sema &S;
14271   bool IsLambda = false;
14272 };
14273 
14274 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14275   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14276 
14277   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14278     if (EscapeInfo.count(BD))
14279       return EscapeInfo[BD];
14280 
14281     bool R = false;
14282     const BlockDecl *CurBD = BD;
14283 
14284     do {
14285       R = !CurBD->doesNotEscape();
14286       if (R)
14287         break;
14288       CurBD = CurBD->getParent()->getInnermostBlockDecl();
14289     } while (CurBD);
14290 
14291     return EscapeInfo[BD] = R;
14292   };
14293 
14294   // If the location where 'self' is implicitly retained is inside a escaping
14295   // block, emit a diagnostic.
14296   for (const std::pair<SourceLocation, const BlockDecl *> &P :
14297        S.ImplicitlyRetainedSelfLocs)
14298     if (IsOrNestedInEscapingBlock(P.second))
14299       S.Diag(P.first, diag::warn_implicitly_retains_self)
14300           << FixItHint::CreateInsertion(P.first, "self->");
14301 }
14302 
14303 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14304                                     bool IsInstantiation) {
14305   FunctionScopeInfo *FSI = getCurFunction();
14306   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14307 
14308   if (FSI->UsesFPIntrin && !FD->hasAttr<StrictFPAttr>())
14309     FD->addAttr(StrictFPAttr::CreateImplicit(Context));
14310 
14311   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14312   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14313 
14314   if (getLangOpts().Coroutines && FSI->isCoroutine())
14315     CheckCompletedCoroutineBody(FD, Body);
14316 
14317   // Do not call PopExpressionEvaluationContext() if it is a lambda because one
14318   // is already popped when finishing the lambda in BuildLambdaExpr(). This is
14319   // meant to pop the context added in ActOnStartOfFunctionDef().
14320   ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14321 
14322   if (FD) {
14323     FD->setBody(Body);
14324     FD->setWillHaveBody(false);
14325 
14326     if (getLangOpts().CPlusPlus14) {
14327       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14328           FD->getReturnType()->isUndeducedType()) {
14329         // If the function has a deduced result type but contains no 'return'
14330         // statements, the result type as written must be exactly 'auto', and
14331         // the deduced result type is 'void'.
14332         if (!FD->getReturnType()->getAs<AutoType>()) {
14333           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14334               << FD->getReturnType();
14335           FD->setInvalidDecl();
14336         } else {
14337           // Substitute 'void' for the 'auto' in the type.
14338           TypeLoc ResultType = getReturnTypeLoc(FD);
14339           Context.adjustDeducedFunctionResultType(
14340               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
14341         }
14342       }
14343     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14344       // In C++11, we don't use 'auto' deduction rules for lambda call
14345       // operators because we don't support return type deduction.
14346       auto *LSI = getCurLambda();
14347       if (LSI->HasImplicitReturnType) {
14348         deduceClosureReturnType(*LSI);
14349 
14350         // C++11 [expr.prim.lambda]p4:
14351         //   [...] if there are no return statements in the compound-statement
14352         //   [the deduced type is] the type void
14353         QualType RetType =
14354             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14355 
14356         // Update the return type to the deduced type.
14357         const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14358         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14359                                             Proto->getExtProtoInfo()));
14360       }
14361     }
14362 
14363     // If the function implicitly returns zero (like 'main') or is naked,
14364     // don't complain about missing return statements.
14365     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14366       WP.disableCheckFallThrough();
14367 
14368     // MSVC permits the use of pure specifier (=0) on function definition,
14369     // defined at class scope, warn about this non-standard construct.
14370     if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14371       Diag(FD->getLocation(), diag::ext_pure_function_definition);
14372 
14373     if (!FD->isInvalidDecl()) {
14374       // Don't diagnose unused parameters of defaulted or deleted functions.
14375       if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
14376         DiagnoseUnusedParameters(FD->parameters());
14377       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14378                                              FD->getReturnType(), FD);
14379 
14380       // If this is a structor, we need a vtable.
14381       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14382         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14383       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
14384         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14385 
14386       // Try to apply the named return value optimization. We have to check
14387       // if we can do this here because lambdas keep return statements around
14388       // to deduce an implicit return type.
14389       if (FD->getReturnType()->isRecordType() &&
14390           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14391         computeNRVO(Body, FSI);
14392     }
14393 
14394     // GNU warning -Wmissing-prototypes:
14395     //   Warn if a global function is defined without a previous
14396     //   prototype declaration. This warning is issued even if the
14397     //   definition itself provides a prototype. The aim is to detect
14398     //   global functions that fail to be declared in header files.
14399     const FunctionDecl *PossiblePrototype = nullptr;
14400     if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14401       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14402 
14403       if (PossiblePrototype) {
14404         // We found a declaration that is not a prototype,
14405         // but that could be a zero-parameter prototype
14406         if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14407           TypeLoc TL = TI->getTypeLoc();
14408           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14409             Diag(PossiblePrototype->getLocation(),
14410                  diag::note_declaration_not_a_prototype)
14411                 << (FD->getNumParams() != 0)
14412                 << (FD->getNumParams() == 0
14413                         ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
14414                         : FixItHint{});
14415         }
14416       } else {
14417         // Returns true if the token beginning at this Loc is `const`.
14418         auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
14419                                 const LangOptions &LangOpts) {
14420           std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
14421           if (LocInfo.first.isInvalid())
14422             return false;
14423 
14424           bool Invalid = false;
14425           StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
14426           if (Invalid)
14427             return false;
14428 
14429           if (LocInfo.second > Buffer.size())
14430             return false;
14431 
14432           const char *LexStart = Buffer.data() + LocInfo.second;
14433           StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
14434 
14435           return StartTok.consume_front("const") &&
14436                  (StartTok.empty() || isWhitespace(StartTok[0]) ||
14437                   StartTok.startswith("/*") || StartTok.startswith("//"));
14438         };
14439 
14440         auto findBeginLoc = [&]() {
14441           // If the return type has `const` qualifier, we want to insert
14442           // `static` before `const` (and not before the typename).
14443           if ((FD->getReturnType()->isAnyPointerType() &&
14444                FD->getReturnType()->getPointeeType().isConstQualified()) ||
14445               FD->getReturnType().isConstQualified()) {
14446             // But only do this if we can determine where the `const` is.
14447 
14448             if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
14449                              getLangOpts()))
14450 
14451               return FD->getBeginLoc();
14452           }
14453           return FD->getTypeSpecStartLoc();
14454         };
14455         Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14456             << /* function */ 1
14457             << (FD->getStorageClass() == SC_None
14458                     ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
14459                     : FixItHint{});
14460       }
14461 
14462       // GNU warning -Wstrict-prototypes
14463       //   Warn if K&R function is defined without a previous declaration.
14464       //   This warning is issued only if the definition itself does not provide
14465       //   a prototype. Only K&R definitions do not provide a prototype.
14466       if (!FD->hasWrittenPrototype()) {
14467         TypeSourceInfo *TI = FD->getTypeSourceInfo();
14468         TypeLoc TL = TI->getTypeLoc();
14469         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
14470         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14471       }
14472     }
14473 
14474     // Warn on CPUDispatch with an actual body.
14475     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14476       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14477         if (!CmpndBody->body_empty())
14478           Diag(CmpndBody->body_front()->getBeginLoc(),
14479                diag::warn_dispatch_body_ignored);
14480 
14481     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14482       const CXXMethodDecl *KeyFunction;
14483       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14484           MD->isVirtual() &&
14485           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14486           MD == KeyFunction->getCanonicalDecl()) {
14487         // Update the key-function state if necessary for this ABI.
14488         if (FD->isInlined() &&
14489             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14490           Context.setNonKeyFunction(MD);
14491 
14492           // If the newly-chosen key function is already defined, then we
14493           // need to mark the vtable as used retroactively.
14494           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14495           const FunctionDecl *Definition;
14496           if (KeyFunction && KeyFunction->isDefined(Definition))
14497             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14498         } else {
14499           // We just defined they key function; mark the vtable as used.
14500           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14501         }
14502       }
14503     }
14504 
14505     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
14506            "Function parsing confused");
14507   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14508     assert(MD == getCurMethodDecl() && "Method parsing confused");
14509     MD->setBody(Body);
14510     if (!MD->isInvalidDecl()) {
14511       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14512                                              MD->getReturnType(), MD);
14513 
14514       if (Body)
14515         computeNRVO(Body, FSI);
14516     }
14517     if (FSI->ObjCShouldCallSuper) {
14518       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14519           << MD->getSelector().getAsString();
14520       FSI->ObjCShouldCallSuper = false;
14521     }
14522     if (FSI->ObjCWarnForNoDesignatedInitChain) {
14523       const ObjCMethodDecl *InitMethod = nullptr;
14524       bool isDesignated =
14525           MD->isDesignatedInitializerForTheInterface(&InitMethod);
14526       assert(isDesignated && InitMethod);
14527       (void)isDesignated;
14528 
14529       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14530         auto IFace = MD->getClassInterface();
14531         if (!IFace)
14532           return false;
14533         auto SuperD = IFace->getSuperClass();
14534         if (!SuperD)
14535           return false;
14536         return SuperD->getIdentifier() ==
14537             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14538       };
14539       // Don't issue this warning for unavailable inits or direct subclasses
14540       // of NSObject.
14541       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14542         Diag(MD->getLocation(),
14543              diag::warn_objc_designated_init_missing_super_call);
14544         Diag(InitMethod->getLocation(),
14545              diag::note_objc_designated_init_marked_here);
14546       }
14547       FSI->ObjCWarnForNoDesignatedInitChain = false;
14548     }
14549     if (FSI->ObjCWarnForNoInitDelegation) {
14550       // Don't issue this warning for unavaialable inits.
14551       if (!MD->isUnavailable())
14552         Diag(MD->getLocation(),
14553              diag::warn_objc_secondary_init_missing_init_call);
14554       FSI->ObjCWarnForNoInitDelegation = false;
14555     }
14556 
14557     diagnoseImplicitlyRetainedSelf(*this);
14558   } else {
14559     // Parsing the function declaration failed in some way. Pop the fake scope
14560     // we pushed on.
14561     PopFunctionScopeInfo(ActivePolicy, dcl);
14562     return nullptr;
14563   }
14564 
14565   if (Body && FSI->HasPotentialAvailabilityViolations)
14566     DiagnoseUnguardedAvailabilityViolations(dcl);
14567 
14568   assert(!FSI->ObjCShouldCallSuper &&
14569          "This should only be set for ObjC methods, which should have been "
14570          "handled in the block above.");
14571 
14572   // Verify and clean out per-function state.
14573   if (Body && (!FD || !FD->isDefaulted())) {
14574     // C++ constructors that have function-try-blocks can't have return
14575     // statements in the handlers of that block. (C++ [except.handle]p14)
14576     // Verify this.
14577     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14578       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14579 
14580     // Verify that gotos and switch cases don't jump into scopes illegally.
14581     if (FSI->NeedsScopeChecking() &&
14582         !PP.isCodeCompletionEnabled())
14583       DiagnoseInvalidJumps(Body);
14584 
14585     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14586       if (!Destructor->getParent()->isDependentType())
14587         CheckDestructor(Destructor);
14588 
14589       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14590                                              Destructor->getParent());
14591     }
14592 
14593     // If any errors have occurred, clear out any temporaries that may have
14594     // been leftover. This ensures that these temporaries won't be picked up for
14595     // deletion in some later function.
14596     if (hasUncompilableErrorOccurred() ||
14597         getDiagnostics().getSuppressAllDiagnostics()) {
14598       DiscardCleanupsInEvaluationContext();
14599     }
14600     if (!hasUncompilableErrorOccurred() &&
14601         !isa<FunctionTemplateDecl>(dcl)) {
14602       // Since the body is valid, issue any analysis-based warnings that are
14603       // enabled.
14604       ActivePolicy = &WP;
14605     }
14606 
14607     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14608         !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14609       FD->setInvalidDecl();
14610 
14611     if (FD && FD->hasAttr<NakedAttr>()) {
14612       for (const Stmt *S : Body->children()) {
14613         // Allow local register variables without initializer as they don't
14614         // require prologue.
14615         bool RegisterVariables = false;
14616         if (auto *DS = dyn_cast<DeclStmt>(S)) {
14617           for (const auto *Decl : DS->decls()) {
14618             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14619               RegisterVariables =
14620                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14621               if (!RegisterVariables)
14622                 break;
14623             }
14624           }
14625         }
14626         if (RegisterVariables)
14627           continue;
14628         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14629           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14630           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14631           FD->setInvalidDecl();
14632           break;
14633         }
14634       }
14635     }
14636 
14637     assert(ExprCleanupObjects.size() ==
14638                ExprEvalContexts.back().NumCleanupObjects &&
14639            "Leftover temporaries in function");
14640     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
14641     assert(MaybeODRUseExprs.empty() &&
14642            "Leftover expressions for odr-use checking");
14643   }
14644 
14645   if (!IsInstantiation)
14646     PopDeclContext();
14647 
14648   PopFunctionScopeInfo(ActivePolicy, dcl);
14649   // If any errors have occurred, clear out any temporaries that may have
14650   // been leftover. This ensures that these temporaries won't be picked up for
14651   // deletion in some later function.
14652   if (hasUncompilableErrorOccurred()) {
14653     DiscardCleanupsInEvaluationContext();
14654   }
14655 
14656   if (FD && (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
14657     auto ES = getEmissionStatus(FD);
14658     if (ES == Sema::FunctionEmissionStatus::Emitted ||
14659         ES == Sema::FunctionEmissionStatus::Unknown)
14660       DeclsToCheckForDeferredDiags.push_back(FD);
14661   }
14662 
14663   return dcl;
14664 }
14665 
14666 /// When we finish delayed parsing of an attribute, we must attach it to the
14667 /// relevant Decl.
14668 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14669                                        ParsedAttributes &Attrs) {
14670   // Always attach attributes to the underlying decl.
14671   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14672     D = TD->getTemplatedDecl();
14673   ProcessDeclAttributeList(S, D, Attrs);
14674 
14675   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14676     if (Method->isStatic())
14677       checkThisInStaticMemberFunctionAttributes(Method);
14678 }
14679 
14680 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14681 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
14682 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14683                                           IdentifierInfo &II, Scope *S) {
14684   // Find the scope in which the identifier is injected and the corresponding
14685   // DeclContext.
14686   // FIXME: C89 does not say what happens if there is no enclosing block scope.
14687   // In that case, we inject the declaration into the translation unit scope
14688   // instead.
14689   Scope *BlockScope = S;
14690   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14691     BlockScope = BlockScope->getParent();
14692 
14693   Scope *ContextScope = BlockScope;
14694   while (!ContextScope->getEntity())
14695     ContextScope = ContextScope->getParent();
14696   ContextRAII SavedContext(*this, ContextScope->getEntity());
14697 
14698   // Before we produce a declaration for an implicitly defined
14699   // function, see whether there was a locally-scoped declaration of
14700   // this name as a function or variable. If so, use that
14701   // (non-visible) declaration, and complain about it.
14702   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14703   if (ExternCPrev) {
14704     // We still need to inject the function into the enclosing block scope so
14705     // that later (non-call) uses can see it.
14706     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14707 
14708     // C89 footnote 38:
14709     //   If in fact it is not defined as having type "function returning int",
14710     //   the behavior is undefined.
14711     if (!isa<FunctionDecl>(ExternCPrev) ||
14712         !Context.typesAreCompatible(
14713             cast<FunctionDecl>(ExternCPrev)->getType(),
14714             Context.getFunctionNoProtoType(Context.IntTy))) {
14715       Diag(Loc, diag::ext_use_out_of_scope_declaration)
14716           << ExternCPrev << !getLangOpts().C99;
14717       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14718       return ExternCPrev;
14719     }
14720   }
14721 
14722   // Extension in C99.  Legal in C90, but warn about it.
14723   unsigned diag_id;
14724   if (II.getName().startswith("__builtin_"))
14725     diag_id = diag::warn_builtin_unknown;
14726   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14727   else if (getLangOpts().OpenCL)
14728     diag_id = diag::err_opencl_implicit_function_decl;
14729   else if (getLangOpts().C99)
14730     diag_id = diag::ext_implicit_function_decl;
14731   else
14732     diag_id = diag::warn_implicit_function_decl;
14733   Diag(Loc, diag_id) << &II;
14734 
14735   // If we found a prior declaration of this function, don't bother building
14736   // another one. We've already pushed that one into scope, so there's nothing
14737   // more to do.
14738   if (ExternCPrev)
14739     return ExternCPrev;
14740 
14741   // Because typo correction is expensive, only do it if the implicit
14742   // function declaration is going to be treated as an error.
14743   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
14744     TypoCorrection Corrected;
14745     DeclFilterCCC<FunctionDecl> CCC{};
14746     if (S && (Corrected =
14747                   CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
14748                               S, nullptr, CCC, CTK_NonError)))
14749       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
14750                    /*ErrorRecovery*/false);
14751   }
14752 
14753   // Set a Declarator for the implicit definition: int foo();
14754   const char *Dummy;
14755   AttributeFactory attrFactory;
14756   DeclSpec DS(attrFactory);
14757   unsigned DiagID;
14758   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
14759                                   Context.getPrintingPolicy());
14760   (void)Error; // Silence warning.
14761   assert(!Error && "Error setting up implicit decl!");
14762   SourceLocation NoLoc;
14763   Declarator D(DS, DeclaratorContext::Block);
14764   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
14765                                              /*IsAmbiguous=*/false,
14766                                              /*LParenLoc=*/NoLoc,
14767                                              /*Params=*/nullptr,
14768                                              /*NumParams=*/0,
14769                                              /*EllipsisLoc=*/NoLoc,
14770                                              /*RParenLoc=*/NoLoc,
14771                                              /*RefQualifierIsLvalueRef=*/true,
14772                                              /*RefQualifierLoc=*/NoLoc,
14773                                              /*MutableLoc=*/NoLoc, EST_None,
14774                                              /*ESpecRange=*/SourceRange(),
14775                                              /*Exceptions=*/nullptr,
14776                                              /*ExceptionRanges=*/nullptr,
14777                                              /*NumExceptions=*/0,
14778                                              /*NoexceptExpr=*/nullptr,
14779                                              /*ExceptionSpecTokens=*/nullptr,
14780                                              /*DeclsInPrototype=*/None, Loc,
14781                                              Loc, D),
14782                 std::move(DS.getAttributes()), SourceLocation());
14783   D.SetIdentifier(&II, Loc);
14784 
14785   // Insert this function into the enclosing block scope.
14786   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
14787   FD->setImplicit();
14788 
14789   AddKnownFunctionAttributes(FD);
14790 
14791   return FD;
14792 }
14793 
14794 /// If this function is a C++ replaceable global allocation function
14795 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
14796 /// adds any function attributes that we know a priori based on the standard.
14797 ///
14798 /// We need to check for duplicate attributes both here and where user-written
14799 /// attributes are applied to declarations.
14800 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
14801     FunctionDecl *FD) {
14802   if (FD->isInvalidDecl())
14803     return;
14804 
14805   if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
14806       FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
14807     return;
14808 
14809   Optional<unsigned> AlignmentParam;
14810   bool IsNothrow = false;
14811   if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
14812     return;
14813 
14814   // C++2a [basic.stc.dynamic.allocation]p4:
14815   //   An allocation function that has a non-throwing exception specification
14816   //   indicates failure by returning a null pointer value. Any other allocation
14817   //   function never returns a null pointer value and indicates failure only by
14818   //   throwing an exception [...]
14819   if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
14820     FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
14821 
14822   // C++2a [basic.stc.dynamic.allocation]p2:
14823   //   An allocation function attempts to allocate the requested amount of
14824   //   storage. [...] If the request succeeds, the value returned by a
14825   //   replaceable allocation function is a [...] pointer value p0 different
14826   //   from any previously returned value p1 [...]
14827   //
14828   // However, this particular information is being added in codegen,
14829   // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
14830 
14831   // C++2a [basic.stc.dynamic.allocation]p2:
14832   //   An allocation function attempts to allocate the requested amount of
14833   //   storage. If it is successful, it returns the address of the start of a
14834   //   block of storage whose length in bytes is at least as large as the
14835   //   requested size.
14836   if (!FD->hasAttr<AllocSizeAttr>()) {
14837     FD->addAttr(AllocSizeAttr::CreateImplicit(
14838         Context, /*ElemSizeParam=*/ParamIdx(1, FD),
14839         /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
14840   }
14841 
14842   // C++2a [basic.stc.dynamic.allocation]p3:
14843   //   For an allocation function [...], the pointer returned on a successful
14844   //   call shall represent the address of storage that is aligned as follows:
14845   //   (3.1) If the allocation function takes an argument of type
14846   //         std​::​align_­val_­t, the storage will have the alignment
14847   //         specified by the value of this argument.
14848   if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
14849     FD->addAttr(AllocAlignAttr::CreateImplicit(
14850         Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
14851   }
14852 
14853   // FIXME:
14854   // C++2a [basic.stc.dynamic.allocation]p3:
14855   //   For an allocation function [...], the pointer returned on a successful
14856   //   call shall represent the address of storage that is aligned as follows:
14857   //   (3.2) Otherwise, if the allocation function is named operator new[],
14858   //         the storage is aligned for any object that does not have
14859   //         new-extended alignment ([basic.align]) and is no larger than the
14860   //         requested size.
14861   //   (3.3) Otherwise, the storage is aligned for any object that does not
14862   //         have new-extended alignment and is of the requested size.
14863 }
14864 
14865 /// Adds any function attributes that we know a priori based on
14866 /// the declaration of this function.
14867 ///
14868 /// These attributes can apply both to implicitly-declared builtins
14869 /// (like __builtin___printf_chk) or to library-declared functions
14870 /// like NSLog or printf.
14871 ///
14872 /// We need to check for duplicate attributes both here and where user-written
14873 /// attributes are applied to declarations.
14874 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
14875   if (FD->isInvalidDecl())
14876     return;
14877 
14878   // If this is a built-in function, map its builtin attributes to
14879   // actual attributes.
14880   if (unsigned BuiltinID = FD->getBuiltinID()) {
14881     // Handle printf-formatting attributes.
14882     unsigned FormatIdx;
14883     bool HasVAListArg;
14884     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
14885       if (!FD->hasAttr<FormatAttr>()) {
14886         const char *fmt = "printf";
14887         unsigned int NumParams = FD->getNumParams();
14888         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
14889             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
14890           fmt = "NSString";
14891         FD->addAttr(FormatAttr::CreateImplicit(Context,
14892                                                &Context.Idents.get(fmt),
14893                                                FormatIdx+1,
14894                                                HasVAListArg ? 0 : FormatIdx+2,
14895                                                FD->getLocation()));
14896       }
14897     }
14898     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
14899                                              HasVAListArg)) {
14900      if (!FD->hasAttr<FormatAttr>())
14901        FD->addAttr(FormatAttr::CreateImplicit(Context,
14902                                               &Context.Idents.get("scanf"),
14903                                               FormatIdx+1,
14904                                               HasVAListArg ? 0 : FormatIdx+2,
14905                                               FD->getLocation()));
14906     }
14907 
14908     // Handle automatically recognized callbacks.
14909     SmallVector<int, 4> Encoding;
14910     if (!FD->hasAttr<CallbackAttr>() &&
14911         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
14912       FD->addAttr(CallbackAttr::CreateImplicit(
14913           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
14914 
14915     // Mark const if we don't care about errno and that is the only thing
14916     // preventing the function from being const. This allows IRgen to use LLVM
14917     // intrinsics for such functions.
14918     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
14919         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
14920       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14921 
14922     // We make "fma" on some platforms const because we know it does not set
14923     // errno in those environments even though it could set errno based on the
14924     // C standard.
14925     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
14926     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
14927         !FD->hasAttr<ConstAttr>()) {
14928       switch (BuiltinID) {
14929       case Builtin::BI__builtin_fma:
14930       case Builtin::BI__builtin_fmaf:
14931       case Builtin::BI__builtin_fmal:
14932       case Builtin::BIfma:
14933       case Builtin::BIfmaf:
14934       case Builtin::BIfmal:
14935         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14936         break;
14937       default:
14938         break;
14939       }
14940     }
14941 
14942     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
14943         !FD->hasAttr<ReturnsTwiceAttr>())
14944       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
14945                                          FD->getLocation()));
14946     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
14947       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14948     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
14949       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
14950     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
14951       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14952     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
14953         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
14954       // Add the appropriate attribute, depending on the CUDA compilation mode
14955       // and which target the builtin belongs to. For example, during host
14956       // compilation, aux builtins are __device__, while the rest are __host__.
14957       if (getLangOpts().CUDAIsDevice !=
14958           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
14959         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
14960       else
14961         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
14962     }
14963   }
14964 
14965   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
14966 
14967   // If C++ exceptions are enabled but we are told extern "C" functions cannot
14968   // throw, add an implicit nothrow attribute to any extern "C" function we come
14969   // across.
14970   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
14971       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
14972     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
14973     if (!FPT || FPT->getExceptionSpecType() == EST_None)
14974       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14975   }
14976 
14977   IdentifierInfo *Name = FD->getIdentifier();
14978   if (!Name)
14979     return;
14980   if ((!getLangOpts().CPlusPlus &&
14981        FD->getDeclContext()->isTranslationUnit()) ||
14982       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
14983        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
14984        LinkageSpecDecl::lang_c)) {
14985     // Okay: this could be a libc/libm/Objective-C function we know
14986     // about.
14987   } else
14988     return;
14989 
14990   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
14991     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
14992     // target-specific builtins, perhaps?
14993     if (!FD->hasAttr<FormatAttr>())
14994       FD->addAttr(FormatAttr::CreateImplicit(Context,
14995                                              &Context.Idents.get("printf"), 2,
14996                                              Name->isStr("vasprintf") ? 0 : 3,
14997                                              FD->getLocation()));
14998   }
14999 
15000   if (Name->isStr("__CFStringMakeConstantString")) {
15001     // We already have a __builtin___CFStringMakeConstantString,
15002     // but builds that use -fno-constant-cfstrings don't go through that.
15003     if (!FD->hasAttr<FormatArgAttr>())
15004       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
15005                                                 FD->getLocation()));
15006   }
15007 }
15008 
15009 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
15010                                     TypeSourceInfo *TInfo) {
15011   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
15012   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
15013 
15014   if (!TInfo) {
15015     assert(D.isInvalidType() && "no declarator info for valid type");
15016     TInfo = Context.getTrivialTypeSourceInfo(T);
15017   }
15018 
15019   // Scope manipulation handled by caller.
15020   TypedefDecl *NewTD =
15021       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
15022                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
15023 
15024   // Bail out immediately if we have an invalid declaration.
15025   if (D.isInvalidType()) {
15026     NewTD->setInvalidDecl();
15027     return NewTD;
15028   }
15029 
15030   if (D.getDeclSpec().isModulePrivateSpecified()) {
15031     if (CurContext->isFunctionOrMethod())
15032       Diag(NewTD->getLocation(), diag::err_module_private_local)
15033           << 2 << NewTD
15034           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15035           << FixItHint::CreateRemoval(
15036                  D.getDeclSpec().getModulePrivateSpecLoc());
15037     else
15038       NewTD->setModulePrivate();
15039   }
15040 
15041   // C++ [dcl.typedef]p8:
15042   //   If the typedef declaration defines an unnamed class (or
15043   //   enum), the first typedef-name declared by the declaration
15044   //   to be that class type (or enum type) is used to denote the
15045   //   class type (or enum type) for linkage purposes only.
15046   // We need to check whether the type was declared in the declaration.
15047   switch (D.getDeclSpec().getTypeSpecType()) {
15048   case TST_enum:
15049   case TST_struct:
15050   case TST_interface:
15051   case TST_union:
15052   case TST_class: {
15053     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
15054     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15055     break;
15056   }
15057 
15058   default:
15059     break;
15060   }
15061 
15062   return NewTD;
15063 }
15064 
15065 /// Check that this is a valid underlying type for an enum declaration.
15066 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
15067   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15068   QualType T = TI->getType();
15069 
15070   if (T->isDependentType())
15071     return false;
15072 
15073   // This doesn't use 'isIntegralType' despite the error message mentioning
15074   // integral type because isIntegralType would also allow enum types in C.
15075   if (const BuiltinType *BT = T->getAs<BuiltinType>())
15076     if (BT->isInteger())
15077       return false;
15078 
15079   if (T->isExtIntType())
15080     return false;
15081 
15082   return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15083 }
15084 
15085 /// Check whether this is a valid redeclaration of a previous enumeration.
15086 /// \return true if the redeclaration was invalid.
15087 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15088                                   QualType EnumUnderlyingTy, bool IsFixed,
15089                                   const EnumDecl *Prev) {
15090   if (IsScoped != Prev->isScoped()) {
15091     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15092       << Prev->isScoped();
15093     Diag(Prev->getLocation(), diag::note_previous_declaration);
15094     return true;
15095   }
15096 
15097   if (IsFixed && Prev->isFixed()) {
15098     if (!EnumUnderlyingTy->isDependentType() &&
15099         !Prev->getIntegerType()->isDependentType() &&
15100         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15101                                         Prev->getIntegerType())) {
15102       // TODO: Highlight the underlying type of the redeclaration.
15103       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15104         << EnumUnderlyingTy << Prev->getIntegerType();
15105       Diag(Prev->getLocation(), diag::note_previous_declaration)
15106           << Prev->getIntegerTypeRange();
15107       return true;
15108     }
15109   } else if (IsFixed != Prev->isFixed()) {
15110     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15111       << Prev->isFixed();
15112     Diag(Prev->getLocation(), diag::note_previous_declaration);
15113     return true;
15114   }
15115 
15116   return false;
15117 }
15118 
15119 /// Get diagnostic %select index for tag kind for
15120 /// redeclaration diagnostic message.
15121 /// WARNING: Indexes apply to particular diagnostics only!
15122 ///
15123 /// \returns diagnostic %select index.
15124 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15125   switch (Tag) {
15126   case TTK_Struct: return 0;
15127   case TTK_Interface: return 1;
15128   case TTK_Class:  return 2;
15129   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
15130   }
15131 }
15132 
15133 /// Determine if tag kind is a class-key compatible with
15134 /// class for redeclaration (class, struct, or __interface).
15135 ///
15136 /// \returns true iff the tag kind is compatible.
15137 static bool isClassCompatTagKind(TagTypeKind Tag)
15138 {
15139   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15140 }
15141 
15142 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15143                                              TagTypeKind TTK) {
15144   if (isa<TypedefDecl>(PrevDecl))
15145     return NTK_Typedef;
15146   else if (isa<TypeAliasDecl>(PrevDecl))
15147     return NTK_TypeAlias;
15148   else if (isa<ClassTemplateDecl>(PrevDecl))
15149     return NTK_Template;
15150   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15151     return NTK_TypeAliasTemplate;
15152   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15153     return NTK_TemplateTemplateArgument;
15154   switch (TTK) {
15155   case TTK_Struct:
15156   case TTK_Interface:
15157   case TTK_Class:
15158     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15159   case TTK_Union:
15160     return NTK_NonUnion;
15161   case TTK_Enum:
15162     return NTK_NonEnum;
15163   }
15164   llvm_unreachable("invalid TTK");
15165 }
15166 
15167 /// Determine whether a tag with a given kind is acceptable
15168 /// as a redeclaration of the given tag declaration.
15169 ///
15170 /// \returns true if the new tag kind is acceptable, false otherwise.
15171 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15172                                         TagTypeKind NewTag, bool isDefinition,
15173                                         SourceLocation NewTagLoc,
15174                                         const IdentifierInfo *Name) {
15175   // C++ [dcl.type.elab]p3:
15176   //   The class-key or enum keyword present in the
15177   //   elaborated-type-specifier shall agree in kind with the
15178   //   declaration to which the name in the elaborated-type-specifier
15179   //   refers. This rule also applies to the form of
15180   //   elaborated-type-specifier that declares a class-name or
15181   //   friend class since it can be construed as referring to the
15182   //   definition of the class. Thus, in any
15183   //   elaborated-type-specifier, the enum keyword shall be used to
15184   //   refer to an enumeration (7.2), the union class-key shall be
15185   //   used to refer to a union (clause 9), and either the class or
15186   //   struct class-key shall be used to refer to a class (clause 9)
15187   //   declared using the class or struct class-key.
15188   TagTypeKind OldTag = Previous->getTagKind();
15189   if (OldTag != NewTag &&
15190       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15191     return false;
15192 
15193   // Tags are compatible, but we might still want to warn on mismatched tags.
15194   // Non-class tags can't be mismatched at this point.
15195   if (!isClassCompatTagKind(NewTag))
15196     return true;
15197 
15198   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15199   // by our warning analysis. We don't want to warn about mismatches with (eg)
15200   // declarations in system headers that are designed to be specialized, but if
15201   // a user asks us to warn, we should warn if their code contains mismatched
15202   // declarations.
15203   auto IsIgnoredLoc = [&](SourceLocation Loc) {
15204     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15205                                       Loc);
15206   };
15207   if (IsIgnoredLoc(NewTagLoc))
15208     return true;
15209 
15210   auto IsIgnored = [&](const TagDecl *Tag) {
15211     return IsIgnoredLoc(Tag->getLocation());
15212   };
15213   while (IsIgnored(Previous)) {
15214     Previous = Previous->getPreviousDecl();
15215     if (!Previous)
15216       return true;
15217     OldTag = Previous->getTagKind();
15218   }
15219 
15220   bool isTemplate = false;
15221   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15222     isTemplate = Record->getDescribedClassTemplate();
15223 
15224   if (inTemplateInstantiation()) {
15225     if (OldTag != NewTag) {
15226       // In a template instantiation, do not offer fix-its for tag mismatches
15227       // since they usually mess up the template instead of fixing the problem.
15228       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15229         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15230         << getRedeclDiagFromTagKind(OldTag);
15231       // FIXME: Note previous location?
15232     }
15233     return true;
15234   }
15235 
15236   if (isDefinition) {
15237     // On definitions, check all previous tags and issue a fix-it for each
15238     // one that doesn't match the current tag.
15239     if (Previous->getDefinition()) {
15240       // Don't suggest fix-its for redefinitions.
15241       return true;
15242     }
15243 
15244     bool previousMismatch = false;
15245     for (const TagDecl *I : Previous->redecls()) {
15246       if (I->getTagKind() != NewTag) {
15247         // Ignore previous declarations for which the warning was disabled.
15248         if (IsIgnored(I))
15249           continue;
15250 
15251         if (!previousMismatch) {
15252           previousMismatch = true;
15253           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15254             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15255             << getRedeclDiagFromTagKind(I->getTagKind());
15256         }
15257         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15258           << getRedeclDiagFromTagKind(NewTag)
15259           << FixItHint::CreateReplacement(I->getInnerLocStart(),
15260                TypeWithKeyword::getTagTypeKindName(NewTag));
15261       }
15262     }
15263     return true;
15264   }
15265 
15266   // Identify the prevailing tag kind: this is the kind of the definition (if
15267   // there is a non-ignored definition), or otherwise the kind of the prior
15268   // (non-ignored) declaration.
15269   const TagDecl *PrevDef = Previous->getDefinition();
15270   if (PrevDef && IsIgnored(PrevDef))
15271     PrevDef = nullptr;
15272   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15273   if (Redecl->getTagKind() != NewTag) {
15274     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15275       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15276       << getRedeclDiagFromTagKind(OldTag);
15277     Diag(Redecl->getLocation(), diag::note_previous_use);
15278 
15279     // If there is a previous definition, suggest a fix-it.
15280     if (PrevDef) {
15281       Diag(NewTagLoc, diag::note_struct_class_suggestion)
15282         << getRedeclDiagFromTagKind(Redecl->getTagKind())
15283         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15284              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15285     }
15286   }
15287 
15288   return true;
15289 }
15290 
15291 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15292 /// from an outer enclosing namespace or file scope inside a friend declaration.
15293 /// This should provide the commented out code in the following snippet:
15294 ///   namespace N {
15295 ///     struct X;
15296 ///     namespace M {
15297 ///       struct Y { friend struct /*N::*/ X; };
15298 ///     }
15299 ///   }
15300 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
15301                                          SourceLocation NameLoc) {
15302   // While the decl is in a namespace, do repeated lookup of that name and see
15303   // if we get the same namespace back.  If we do not, continue until
15304   // translation unit scope, at which point we have a fully qualified NNS.
15305   SmallVector<IdentifierInfo *, 4> Namespaces;
15306   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15307   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15308     // This tag should be declared in a namespace, which can only be enclosed by
15309     // other namespaces.  Bail if there's an anonymous namespace in the chain.
15310     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15311     if (!Namespace || Namespace->isAnonymousNamespace())
15312       return FixItHint();
15313     IdentifierInfo *II = Namespace->getIdentifier();
15314     Namespaces.push_back(II);
15315     NamedDecl *Lookup = SemaRef.LookupSingleName(
15316         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15317     if (Lookup == Namespace)
15318       break;
15319   }
15320 
15321   // Once we have all the namespaces, reverse them to go outermost first, and
15322   // build an NNS.
15323   SmallString<64> Insertion;
15324   llvm::raw_svector_ostream OS(Insertion);
15325   if (DC->isTranslationUnit())
15326     OS << "::";
15327   std::reverse(Namespaces.begin(), Namespaces.end());
15328   for (auto *II : Namespaces)
15329     OS << II->getName() << "::";
15330   return FixItHint::CreateInsertion(NameLoc, Insertion);
15331 }
15332 
15333 /// Determine whether a tag originally declared in context \p OldDC can
15334 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15335 /// found a declaration in \p OldDC as a previous decl, perhaps through a
15336 /// using-declaration).
15337 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15338                                          DeclContext *NewDC) {
15339   OldDC = OldDC->getRedeclContext();
15340   NewDC = NewDC->getRedeclContext();
15341 
15342   if (OldDC->Equals(NewDC))
15343     return true;
15344 
15345   // In MSVC mode, we allow a redeclaration if the contexts are related (either
15346   // encloses the other).
15347   if (S.getLangOpts().MSVCCompat &&
15348       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
15349     return true;
15350 
15351   return false;
15352 }
15353 
15354 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
15355 /// former case, Name will be non-null.  In the later case, Name will be null.
15356 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
15357 /// reference/declaration/definition of a tag.
15358 ///
15359 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
15360 /// trailing-type-specifier) other than one in an alias-declaration.
15361 ///
15362 /// \param SkipBody If non-null, will be set to indicate if the caller should
15363 /// skip the definition of this tag and treat it as if it were a declaration.
15364 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
15365                      SourceLocation KWLoc, CXXScopeSpec &SS,
15366                      IdentifierInfo *Name, SourceLocation NameLoc,
15367                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
15368                      SourceLocation ModulePrivateLoc,
15369                      MultiTemplateParamsArg TemplateParameterLists,
15370                      bool &OwnedDecl, bool &IsDependent,
15371                      SourceLocation ScopedEnumKWLoc,
15372                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
15373                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
15374                      SkipBodyInfo *SkipBody) {
15375   // If this is not a definition, it must have a name.
15376   IdentifierInfo *OrigName = Name;
15377   assert((Name != nullptr || TUK == TUK_Definition) &&
15378          "Nameless record must be a definition!");
15379   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
15380 
15381   OwnedDecl = false;
15382   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
15383   bool ScopedEnum = ScopedEnumKWLoc.isValid();
15384 
15385   // FIXME: Check member specializations more carefully.
15386   bool isMemberSpecialization = false;
15387   bool Invalid = false;
15388 
15389   // We only need to do this matching if we have template parameters
15390   // or a scope specifier, which also conveniently avoids this work
15391   // for non-C++ cases.
15392   if (TemplateParameterLists.size() > 0 ||
15393       (SS.isNotEmpty() && TUK != TUK_Reference)) {
15394     if (TemplateParameterList *TemplateParams =
15395             MatchTemplateParametersToScopeSpecifier(
15396                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
15397                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
15398       if (Kind == TTK_Enum) {
15399         Diag(KWLoc, diag::err_enum_template);
15400         return nullptr;
15401       }
15402 
15403       if (TemplateParams->size() > 0) {
15404         // This is a declaration or definition of a class template (which may
15405         // be a member of another template).
15406 
15407         if (Invalid)
15408           return nullptr;
15409 
15410         OwnedDecl = false;
15411         DeclResult Result = CheckClassTemplate(
15412             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
15413             AS, ModulePrivateLoc,
15414             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
15415             TemplateParameterLists.data(), SkipBody);
15416         return Result.get();
15417       } else {
15418         // The "template<>" header is extraneous.
15419         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
15420           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
15421         isMemberSpecialization = true;
15422       }
15423     }
15424 
15425     if (!TemplateParameterLists.empty() && isMemberSpecialization &&
15426         CheckTemplateDeclScope(S, TemplateParameterLists.back()))
15427       return nullptr;
15428   }
15429 
15430   // Figure out the underlying type if this a enum declaration. We need to do
15431   // this early, because it's needed to detect if this is an incompatible
15432   // redeclaration.
15433   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
15434   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
15435 
15436   if (Kind == TTK_Enum) {
15437     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
15438       // No underlying type explicitly specified, or we failed to parse the
15439       // type, default to int.
15440       EnumUnderlying = Context.IntTy.getTypePtr();
15441     } else if (UnderlyingType.get()) {
15442       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
15443       // integral type; any cv-qualification is ignored.
15444       TypeSourceInfo *TI = nullptr;
15445       GetTypeFromParser(UnderlyingType.get(), &TI);
15446       EnumUnderlying = TI;
15447 
15448       if (CheckEnumUnderlyingType(TI))
15449         // Recover by falling back to int.
15450         EnumUnderlying = Context.IntTy.getTypePtr();
15451 
15452       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
15453                                           UPPC_FixedUnderlyingType))
15454         EnumUnderlying = Context.IntTy.getTypePtr();
15455 
15456     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
15457       // For MSVC ABI compatibility, unfixed enums must use an underlying type
15458       // of 'int'. However, if this is an unfixed forward declaration, don't set
15459       // the underlying type unless the user enables -fms-compatibility. This
15460       // makes unfixed forward declared enums incomplete and is more conforming.
15461       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
15462         EnumUnderlying = Context.IntTy.getTypePtr();
15463     }
15464   }
15465 
15466   DeclContext *SearchDC = CurContext;
15467   DeclContext *DC = CurContext;
15468   bool isStdBadAlloc = false;
15469   bool isStdAlignValT = false;
15470 
15471   RedeclarationKind Redecl = forRedeclarationInCurContext();
15472   if (TUK == TUK_Friend || TUK == TUK_Reference)
15473     Redecl = NotForRedeclaration;
15474 
15475   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
15476   /// implemented asks for structural equivalence checking, the returned decl
15477   /// here is passed back to the parser, allowing the tag body to be parsed.
15478   auto createTagFromNewDecl = [&]() -> TagDecl * {
15479     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
15480     // If there is an identifier, use the location of the identifier as the
15481     // location of the decl, otherwise use the location of the struct/union
15482     // keyword.
15483     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15484     TagDecl *New = nullptr;
15485 
15486     if (Kind == TTK_Enum) {
15487       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
15488                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
15489       // If this is an undefined enum, bail.
15490       if (TUK != TUK_Definition && !Invalid)
15491         return nullptr;
15492       if (EnumUnderlying) {
15493         EnumDecl *ED = cast<EnumDecl>(New);
15494         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
15495           ED->setIntegerTypeSourceInfo(TI);
15496         else
15497           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
15498         ED->setPromotionType(ED->getIntegerType());
15499       }
15500     } else { // struct/union
15501       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15502                                nullptr);
15503     }
15504 
15505     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15506       // Add alignment attributes if necessary; these attributes are checked
15507       // when the ASTContext lays out the structure.
15508       //
15509       // It is important for implementing the correct semantics that this
15510       // happen here (in ActOnTag). The #pragma pack stack is
15511       // maintained as a result of parser callbacks which can occur at
15512       // many points during the parsing of a struct declaration (because
15513       // the #pragma tokens are effectively skipped over during the
15514       // parsing of the struct).
15515       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15516         AddAlignmentAttributesForRecord(RD);
15517         AddMsStructLayoutForRecord(RD);
15518       }
15519     }
15520     New->setLexicalDeclContext(CurContext);
15521     return New;
15522   };
15523 
15524   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
15525   if (Name && SS.isNotEmpty()) {
15526     // We have a nested-name tag ('struct foo::bar').
15527 
15528     // Check for invalid 'foo::'.
15529     if (SS.isInvalid()) {
15530       Name = nullptr;
15531       goto CreateNewDecl;
15532     }
15533 
15534     // If this is a friend or a reference to a class in a dependent
15535     // context, don't try to make a decl for it.
15536     if (TUK == TUK_Friend || TUK == TUK_Reference) {
15537       DC = computeDeclContext(SS, false);
15538       if (!DC) {
15539         IsDependent = true;
15540         return nullptr;
15541       }
15542     } else {
15543       DC = computeDeclContext(SS, true);
15544       if (!DC) {
15545         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
15546           << SS.getRange();
15547         return nullptr;
15548       }
15549     }
15550 
15551     if (RequireCompleteDeclContext(SS, DC))
15552       return nullptr;
15553 
15554     SearchDC = DC;
15555     // Look-up name inside 'foo::'.
15556     LookupQualifiedName(Previous, DC);
15557 
15558     if (Previous.isAmbiguous())
15559       return nullptr;
15560 
15561     if (Previous.empty()) {
15562       // Name lookup did not find anything. However, if the
15563       // nested-name-specifier refers to the current instantiation,
15564       // and that current instantiation has any dependent base
15565       // classes, we might find something at instantiation time: treat
15566       // this as a dependent elaborated-type-specifier.
15567       // But this only makes any sense for reference-like lookups.
15568       if (Previous.wasNotFoundInCurrentInstantiation() &&
15569           (TUK == TUK_Reference || TUK == TUK_Friend)) {
15570         IsDependent = true;
15571         return nullptr;
15572       }
15573 
15574       // A tag 'foo::bar' must already exist.
15575       Diag(NameLoc, diag::err_not_tag_in_scope)
15576         << Kind << Name << DC << SS.getRange();
15577       Name = nullptr;
15578       Invalid = true;
15579       goto CreateNewDecl;
15580     }
15581   } else if (Name) {
15582     // C++14 [class.mem]p14:
15583     //   If T is the name of a class, then each of the following shall have a
15584     //   name different from T:
15585     //    -- every member of class T that is itself a type
15586     if (TUK != TUK_Reference && TUK != TUK_Friend &&
15587         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15588       return nullptr;
15589 
15590     // If this is a named struct, check to see if there was a previous forward
15591     // declaration or definition.
15592     // FIXME: We're looking into outer scopes here, even when we
15593     // shouldn't be. Doing so can result in ambiguities that we
15594     // shouldn't be diagnosing.
15595     LookupName(Previous, S);
15596 
15597     // When declaring or defining a tag, ignore ambiguities introduced
15598     // by types using'ed into this scope.
15599     if (Previous.isAmbiguous() &&
15600         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
15601       LookupResult::Filter F = Previous.makeFilter();
15602       while (F.hasNext()) {
15603         NamedDecl *ND = F.next();
15604         if (!ND->getDeclContext()->getRedeclContext()->Equals(
15605                 SearchDC->getRedeclContext()))
15606           F.erase();
15607       }
15608       F.done();
15609     }
15610 
15611     // C++11 [namespace.memdef]p3:
15612     //   If the name in a friend declaration is neither qualified nor
15613     //   a template-id and the declaration is a function or an
15614     //   elaborated-type-specifier, the lookup to determine whether
15615     //   the entity has been previously declared shall not consider
15616     //   any scopes outside the innermost enclosing namespace.
15617     //
15618     // MSVC doesn't implement the above rule for types, so a friend tag
15619     // declaration may be a redeclaration of a type declared in an enclosing
15620     // scope.  They do implement this rule for friend functions.
15621     //
15622     // Does it matter that this should be by scope instead of by
15623     // semantic context?
15624     if (!Previous.empty() && TUK == TUK_Friend) {
15625       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
15626       LookupResult::Filter F = Previous.makeFilter();
15627       bool FriendSawTagOutsideEnclosingNamespace = false;
15628       while (F.hasNext()) {
15629         NamedDecl *ND = F.next();
15630         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15631         if (DC->isFileContext() &&
15632             !EnclosingNS->Encloses(ND->getDeclContext())) {
15633           if (getLangOpts().MSVCCompat)
15634             FriendSawTagOutsideEnclosingNamespace = true;
15635           else
15636             F.erase();
15637         }
15638       }
15639       F.done();
15640 
15641       // Diagnose this MSVC extension in the easy case where lookup would have
15642       // unambiguously found something outside the enclosing namespace.
15643       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
15644         NamedDecl *ND = Previous.getFoundDecl();
15645         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
15646             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
15647       }
15648     }
15649 
15650     // Note:  there used to be some attempt at recovery here.
15651     if (Previous.isAmbiguous())
15652       return nullptr;
15653 
15654     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
15655       // FIXME: This makes sure that we ignore the contexts associated
15656       // with C structs, unions, and enums when looking for a matching
15657       // tag declaration or definition. See the similar lookup tweak
15658       // in Sema::LookupName; is there a better way to deal with this?
15659       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
15660         SearchDC = SearchDC->getParent();
15661     }
15662   }
15663 
15664   if (Previous.isSingleResult() &&
15665       Previous.getFoundDecl()->isTemplateParameter()) {
15666     // Maybe we will complain about the shadowed template parameter.
15667     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
15668     // Just pretend that we didn't see the previous declaration.
15669     Previous.clear();
15670   }
15671 
15672   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
15673       DC->Equals(getStdNamespace())) {
15674     if (Name->isStr("bad_alloc")) {
15675       // This is a declaration of or a reference to "std::bad_alloc".
15676       isStdBadAlloc = true;
15677 
15678       // If std::bad_alloc has been implicitly declared (but made invisible to
15679       // name lookup), fill in this implicit declaration as the previous
15680       // declaration, so that the declarations get chained appropriately.
15681       if (Previous.empty() && StdBadAlloc)
15682         Previous.addDecl(getStdBadAlloc());
15683     } else if (Name->isStr("align_val_t")) {
15684       isStdAlignValT = true;
15685       if (Previous.empty() && StdAlignValT)
15686         Previous.addDecl(getStdAlignValT());
15687     }
15688   }
15689 
15690   // If we didn't find a previous declaration, and this is a reference
15691   // (or friend reference), move to the correct scope.  In C++, we
15692   // also need to do a redeclaration lookup there, just in case
15693   // there's a shadow friend decl.
15694   if (Name && Previous.empty() &&
15695       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
15696     if (Invalid) goto CreateNewDecl;
15697     assert(SS.isEmpty());
15698 
15699     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
15700       // C++ [basic.scope.pdecl]p5:
15701       //   -- for an elaborated-type-specifier of the form
15702       //
15703       //          class-key identifier
15704       //
15705       //      if the elaborated-type-specifier is used in the
15706       //      decl-specifier-seq or parameter-declaration-clause of a
15707       //      function defined in namespace scope, the identifier is
15708       //      declared as a class-name in the namespace that contains
15709       //      the declaration; otherwise, except as a friend
15710       //      declaration, the identifier is declared in the smallest
15711       //      non-class, non-function-prototype scope that contains the
15712       //      declaration.
15713       //
15714       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
15715       // C structs and unions.
15716       //
15717       // It is an error in C++ to declare (rather than define) an enum
15718       // type, including via an elaborated type specifier.  We'll
15719       // diagnose that later; for now, declare the enum in the same
15720       // scope as we would have picked for any other tag type.
15721       //
15722       // GNU C also supports this behavior as part of its incomplete
15723       // enum types extension, while GNU C++ does not.
15724       //
15725       // Find the context where we'll be declaring the tag.
15726       // FIXME: We would like to maintain the current DeclContext as the
15727       // lexical context,
15728       SearchDC = getTagInjectionContext(SearchDC);
15729 
15730       // Find the scope where we'll be declaring the tag.
15731       S = getTagInjectionScope(S, getLangOpts());
15732     } else {
15733       assert(TUK == TUK_Friend);
15734       // C++ [namespace.memdef]p3:
15735       //   If a friend declaration in a non-local class first declares a
15736       //   class or function, the friend class or function is a member of
15737       //   the innermost enclosing namespace.
15738       SearchDC = SearchDC->getEnclosingNamespaceContext();
15739     }
15740 
15741     // In C++, we need to do a redeclaration lookup to properly
15742     // diagnose some problems.
15743     // FIXME: redeclaration lookup is also used (with and without C++) to find a
15744     // hidden declaration so that we don't get ambiguity errors when using a
15745     // type declared by an elaborated-type-specifier.  In C that is not correct
15746     // and we should instead merge compatible types found by lookup.
15747     if (getLangOpts().CPlusPlus) {
15748       // FIXME: This can perform qualified lookups into function contexts,
15749       // which are meaningless.
15750       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15751       LookupQualifiedName(Previous, SearchDC);
15752     } else {
15753       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15754       LookupName(Previous, S);
15755     }
15756   }
15757 
15758   // If we have a known previous declaration to use, then use it.
15759   if (Previous.empty() && SkipBody && SkipBody->Previous)
15760     Previous.addDecl(SkipBody->Previous);
15761 
15762   if (!Previous.empty()) {
15763     NamedDecl *PrevDecl = Previous.getFoundDecl();
15764     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
15765 
15766     // It's okay to have a tag decl in the same scope as a typedef
15767     // which hides a tag decl in the same scope.  Finding this
15768     // insanity with a redeclaration lookup can only actually happen
15769     // in C++.
15770     //
15771     // This is also okay for elaborated-type-specifiers, which is
15772     // technically forbidden by the current standard but which is
15773     // okay according to the likely resolution of an open issue;
15774     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
15775     if (getLangOpts().CPlusPlus) {
15776       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15777         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
15778           TagDecl *Tag = TT->getDecl();
15779           if (Tag->getDeclName() == Name &&
15780               Tag->getDeclContext()->getRedeclContext()
15781                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
15782             PrevDecl = Tag;
15783             Previous.clear();
15784             Previous.addDecl(Tag);
15785             Previous.resolveKind();
15786           }
15787         }
15788       }
15789     }
15790 
15791     // If this is a redeclaration of a using shadow declaration, it must
15792     // declare a tag in the same context. In MSVC mode, we allow a
15793     // redefinition if either context is within the other.
15794     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
15795       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
15796       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
15797           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
15798           !(OldTag && isAcceptableTagRedeclContext(
15799                           *this, OldTag->getDeclContext(), SearchDC))) {
15800         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
15801         Diag(Shadow->getTargetDecl()->getLocation(),
15802              diag::note_using_decl_target);
15803         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
15804             << 0;
15805         // Recover by ignoring the old declaration.
15806         Previous.clear();
15807         goto CreateNewDecl;
15808       }
15809     }
15810 
15811     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
15812       // If this is a use of a previous tag, or if the tag is already declared
15813       // in the same scope (so that the definition/declaration completes or
15814       // rementions the tag), reuse the decl.
15815       if (TUK == TUK_Reference || TUK == TUK_Friend ||
15816           isDeclInScope(DirectPrevDecl, SearchDC, S,
15817                         SS.isNotEmpty() || isMemberSpecialization)) {
15818         // Make sure that this wasn't declared as an enum and now used as a
15819         // struct or something similar.
15820         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
15821                                           TUK == TUK_Definition, KWLoc,
15822                                           Name)) {
15823           bool SafeToContinue
15824             = (PrevTagDecl->getTagKind() != TTK_Enum &&
15825                Kind != TTK_Enum);
15826           if (SafeToContinue)
15827             Diag(KWLoc, diag::err_use_with_wrong_tag)
15828               << Name
15829               << FixItHint::CreateReplacement(SourceRange(KWLoc),
15830                                               PrevTagDecl->getKindName());
15831           else
15832             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
15833           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
15834 
15835           if (SafeToContinue)
15836             Kind = PrevTagDecl->getTagKind();
15837           else {
15838             // Recover by making this an anonymous redefinition.
15839             Name = nullptr;
15840             Previous.clear();
15841             Invalid = true;
15842           }
15843         }
15844 
15845         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
15846           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
15847           if (TUK == TUK_Reference || TUK == TUK_Friend)
15848             return PrevTagDecl;
15849 
15850           QualType EnumUnderlyingTy;
15851           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15852             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
15853           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
15854             EnumUnderlyingTy = QualType(T, 0);
15855 
15856           // All conflicts with previous declarations are recovered by
15857           // returning the previous declaration, unless this is a definition,
15858           // in which case we want the caller to bail out.
15859           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
15860                                      ScopedEnum, EnumUnderlyingTy,
15861                                      IsFixed, PrevEnum))
15862             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
15863         }
15864 
15865         // C++11 [class.mem]p1:
15866         //   A member shall not be declared twice in the member-specification,
15867         //   except that a nested class or member class template can be declared
15868         //   and then later defined.
15869         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
15870             S->isDeclScope(PrevDecl)) {
15871           Diag(NameLoc, diag::ext_member_redeclared);
15872           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
15873         }
15874 
15875         if (!Invalid) {
15876           // If this is a use, just return the declaration we found, unless
15877           // we have attributes.
15878           if (TUK == TUK_Reference || TUK == TUK_Friend) {
15879             if (!Attrs.empty()) {
15880               // FIXME: Diagnose these attributes. For now, we create a new
15881               // declaration to hold them.
15882             } else if (TUK == TUK_Reference &&
15883                        (PrevTagDecl->getFriendObjectKind() ==
15884                             Decl::FOK_Undeclared ||
15885                         PrevDecl->getOwningModule() != getCurrentModule()) &&
15886                        SS.isEmpty()) {
15887               // This declaration is a reference to an existing entity, but
15888               // has different visibility from that entity: it either makes
15889               // a friend visible or it makes a type visible in a new module.
15890               // In either case, create a new declaration. We only do this if
15891               // the declaration would have meant the same thing if no prior
15892               // declaration were found, that is, if it was found in the same
15893               // scope where we would have injected a declaration.
15894               if (!getTagInjectionContext(CurContext)->getRedeclContext()
15895                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
15896                 return PrevTagDecl;
15897               // This is in the injected scope, create a new declaration in
15898               // that scope.
15899               S = getTagInjectionScope(S, getLangOpts());
15900             } else {
15901               return PrevTagDecl;
15902             }
15903           }
15904 
15905           // Diagnose attempts to redefine a tag.
15906           if (TUK == TUK_Definition) {
15907             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
15908               // If we're defining a specialization and the previous definition
15909               // is from an implicit instantiation, don't emit an error
15910               // here; we'll catch this in the general case below.
15911               bool IsExplicitSpecializationAfterInstantiation = false;
15912               if (isMemberSpecialization) {
15913                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
15914                   IsExplicitSpecializationAfterInstantiation =
15915                     RD->getTemplateSpecializationKind() !=
15916                     TSK_ExplicitSpecialization;
15917                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
15918                   IsExplicitSpecializationAfterInstantiation =
15919                     ED->getTemplateSpecializationKind() !=
15920                     TSK_ExplicitSpecialization;
15921               }
15922 
15923               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
15924               // not keep more that one definition around (merge them). However,
15925               // ensure the decl passes the structural compatibility check in
15926               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
15927               NamedDecl *Hidden = nullptr;
15928               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
15929                 // There is a definition of this tag, but it is not visible. We
15930                 // explicitly make use of C++'s one definition rule here, and
15931                 // assume that this definition is identical to the hidden one
15932                 // we already have. Make the existing definition visible and
15933                 // use it in place of this one.
15934                 if (!getLangOpts().CPlusPlus) {
15935                   // Postpone making the old definition visible until after we
15936                   // complete parsing the new one and do the structural
15937                   // comparison.
15938                   SkipBody->CheckSameAsPrevious = true;
15939                   SkipBody->New = createTagFromNewDecl();
15940                   SkipBody->Previous = Def;
15941                   return Def;
15942                 } else {
15943                   SkipBody->ShouldSkip = true;
15944                   SkipBody->Previous = Def;
15945                   makeMergedDefinitionVisible(Hidden);
15946                   // Carry on and handle it like a normal definition. We'll
15947                   // skip starting the definitiion later.
15948                 }
15949               } else if (!IsExplicitSpecializationAfterInstantiation) {
15950                 // A redeclaration in function prototype scope in C isn't
15951                 // visible elsewhere, so merely issue a warning.
15952                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
15953                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
15954                 else
15955                   Diag(NameLoc, diag::err_redefinition) << Name;
15956                 notePreviousDefinition(Def,
15957                                        NameLoc.isValid() ? NameLoc : KWLoc);
15958                 // If this is a redefinition, recover by making this
15959                 // struct be anonymous, which will make any later
15960                 // references get the previous definition.
15961                 Name = nullptr;
15962                 Previous.clear();
15963                 Invalid = true;
15964               }
15965             } else {
15966               // If the type is currently being defined, complain
15967               // about a nested redefinition.
15968               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
15969               if (TD->isBeingDefined()) {
15970                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
15971                 Diag(PrevTagDecl->getLocation(),
15972                      diag::note_previous_definition);
15973                 Name = nullptr;
15974                 Previous.clear();
15975                 Invalid = true;
15976               }
15977             }
15978 
15979             // Okay, this is definition of a previously declared or referenced
15980             // tag. We're going to create a new Decl for it.
15981           }
15982 
15983           // Okay, we're going to make a redeclaration.  If this is some kind
15984           // of reference, make sure we build the redeclaration in the same DC
15985           // as the original, and ignore the current access specifier.
15986           if (TUK == TUK_Friend || TUK == TUK_Reference) {
15987             SearchDC = PrevTagDecl->getDeclContext();
15988             AS = AS_none;
15989           }
15990         }
15991         // If we get here we have (another) forward declaration or we
15992         // have a definition.  Just create a new decl.
15993 
15994       } else {
15995         // If we get here, this is a definition of a new tag type in a nested
15996         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
15997         // new decl/type.  We set PrevDecl to NULL so that the entities
15998         // have distinct types.
15999         Previous.clear();
16000       }
16001       // If we get here, we're going to create a new Decl. If PrevDecl
16002       // is non-NULL, it's a definition of the tag declared by
16003       // PrevDecl. If it's NULL, we have a new definition.
16004 
16005     // Otherwise, PrevDecl is not a tag, but was found with tag
16006     // lookup.  This is only actually possible in C++, where a few
16007     // things like templates still live in the tag namespace.
16008     } else {
16009       // Use a better diagnostic if an elaborated-type-specifier
16010       // found the wrong kind of type on the first
16011       // (non-redeclaration) lookup.
16012       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
16013           !Previous.isForRedeclaration()) {
16014         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16015         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
16016                                                        << Kind;
16017         Diag(PrevDecl->getLocation(), diag::note_declared_at);
16018         Invalid = true;
16019 
16020       // Otherwise, only diagnose if the declaration is in scope.
16021       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
16022                                 SS.isNotEmpty() || isMemberSpecialization)) {
16023         // do nothing
16024 
16025       // Diagnose implicit declarations introduced by elaborated types.
16026       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
16027         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16028         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
16029         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16030         Invalid = true;
16031 
16032       // Otherwise it's a declaration.  Call out a particularly common
16033       // case here.
16034       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16035         unsigned Kind = 0;
16036         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
16037         Diag(NameLoc, diag::err_tag_definition_of_typedef)
16038           << Name << Kind << TND->getUnderlyingType();
16039         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16040         Invalid = true;
16041 
16042       // Otherwise, diagnose.
16043       } else {
16044         // The tag name clashes with something else in the target scope,
16045         // issue an error and recover by making this tag be anonymous.
16046         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
16047         notePreviousDefinition(PrevDecl, NameLoc);
16048         Name = nullptr;
16049         Invalid = true;
16050       }
16051 
16052       // The existing declaration isn't relevant to us; we're in a
16053       // new scope, so clear out the previous declaration.
16054       Previous.clear();
16055     }
16056   }
16057 
16058 CreateNewDecl:
16059 
16060   TagDecl *PrevDecl = nullptr;
16061   if (Previous.isSingleResult())
16062     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16063 
16064   // If there is an identifier, use the location of the identifier as the
16065   // location of the decl, otherwise use the location of the struct/union
16066   // keyword.
16067   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16068 
16069   // Otherwise, create a new declaration. If there is a previous
16070   // declaration of the same entity, the two will be linked via
16071   // PrevDecl.
16072   TagDecl *New;
16073 
16074   if (Kind == TTK_Enum) {
16075     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16076     // enum X { A, B, C } D;    D should chain to X.
16077     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16078                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16079                            ScopedEnumUsesClassTag, IsFixed);
16080 
16081     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16082       StdAlignValT = cast<EnumDecl>(New);
16083 
16084     // If this is an undefined enum, warn.
16085     if (TUK != TUK_Definition && !Invalid) {
16086       TagDecl *Def;
16087       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16088         // C++0x: 7.2p2: opaque-enum-declaration.
16089         // Conflicts are diagnosed above. Do nothing.
16090       }
16091       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16092         Diag(Loc, diag::ext_forward_ref_enum_def)
16093           << New;
16094         Diag(Def->getLocation(), diag::note_previous_definition);
16095       } else {
16096         unsigned DiagID = diag::ext_forward_ref_enum;
16097         if (getLangOpts().MSVCCompat)
16098           DiagID = diag::ext_ms_forward_ref_enum;
16099         else if (getLangOpts().CPlusPlus)
16100           DiagID = diag::err_forward_ref_enum;
16101         Diag(Loc, DiagID);
16102       }
16103     }
16104 
16105     if (EnumUnderlying) {
16106       EnumDecl *ED = cast<EnumDecl>(New);
16107       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16108         ED->setIntegerTypeSourceInfo(TI);
16109       else
16110         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
16111       ED->setPromotionType(ED->getIntegerType());
16112       assert(ED->isComplete() && "enum with type should be complete");
16113     }
16114   } else {
16115     // struct/union/class
16116 
16117     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16118     // struct X { int A; } D;    D should chain to X.
16119     if (getLangOpts().CPlusPlus) {
16120       // FIXME: Look for a way to use RecordDecl for simple structs.
16121       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16122                                   cast_or_null<CXXRecordDecl>(PrevDecl));
16123 
16124       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16125         StdBadAlloc = cast<CXXRecordDecl>(New);
16126     } else
16127       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16128                                cast_or_null<RecordDecl>(PrevDecl));
16129   }
16130 
16131   // C++11 [dcl.type]p3:
16132   //   A type-specifier-seq shall not define a class or enumeration [...].
16133   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16134       TUK == TUK_Definition) {
16135     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16136       << Context.getTagDeclType(New);
16137     Invalid = true;
16138   }
16139 
16140   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16141       DC->getDeclKind() == Decl::Enum) {
16142     Diag(New->getLocation(), diag::err_type_defined_in_enum)
16143       << Context.getTagDeclType(New);
16144     Invalid = true;
16145   }
16146 
16147   // Maybe add qualifier info.
16148   if (SS.isNotEmpty()) {
16149     if (SS.isSet()) {
16150       // If this is either a declaration or a definition, check the
16151       // nested-name-specifier against the current context.
16152       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16153           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16154                                        isMemberSpecialization))
16155         Invalid = true;
16156 
16157       New->setQualifierInfo(SS.getWithLocInContext(Context));
16158       if (TemplateParameterLists.size() > 0) {
16159         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16160       }
16161     }
16162     else
16163       Invalid = true;
16164   }
16165 
16166   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16167     // Add alignment attributes if necessary; these attributes are checked when
16168     // the ASTContext lays out the structure.
16169     //
16170     // It is important for implementing the correct semantics that this
16171     // happen here (in ActOnTag). The #pragma pack stack is
16172     // maintained as a result of parser callbacks which can occur at
16173     // many points during the parsing of a struct declaration (because
16174     // the #pragma tokens are effectively skipped over during the
16175     // parsing of the struct).
16176     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16177       AddAlignmentAttributesForRecord(RD);
16178       AddMsStructLayoutForRecord(RD);
16179     }
16180   }
16181 
16182   if (ModulePrivateLoc.isValid()) {
16183     if (isMemberSpecialization)
16184       Diag(New->getLocation(), diag::err_module_private_specialization)
16185         << 2
16186         << FixItHint::CreateRemoval(ModulePrivateLoc);
16187     // __module_private__ does not apply to local classes. However, we only
16188     // diagnose this as an error when the declaration specifiers are
16189     // freestanding. Here, we just ignore the __module_private__.
16190     else if (!SearchDC->isFunctionOrMethod())
16191       New->setModulePrivate();
16192   }
16193 
16194   // If this is a specialization of a member class (of a class template),
16195   // check the specialization.
16196   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16197     Invalid = true;
16198 
16199   // If we're declaring or defining a tag in function prototype scope in C,
16200   // note that this type can only be used within the function and add it to
16201   // the list of decls to inject into the function definition scope.
16202   if ((Name || Kind == TTK_Enum) &&
16203       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16204     if (getLangOpts().CPlusPlus) {
16205       // C++ [dcl.fct]p6:
16206       //   Types shall not be defined in return or parameter types.
16207       if (TUK == TUK_Definition && !IsTypeSpecifier) {
16208         Diag(Loc, diag::err_type_defined_in_param_type)
16209             << Name;
16210         Invalid = true;
16211       }
16212     } else if (!PrevDecl) {
16213       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16214     }
16215   }
16216 
16217   if (Invalid)
16218     New->setInvalidDecl();
16219 
16220   // Set the lexical context. If the tag has a C++ scope specifier, the
16221   // lexical context will be different from the semantic context.
16222   New->setLexicalDeclContext(CurContext);
16223 
16224   // Mark this as a friend decl if applicable.
16225   // In Microsoft mode, a friend declaration also acts as a forward
16226   // declaration so we always pass true to setObjectOfFriendDecl to make
16227   // the tag name visible.
16228   if (TUK == TUK_Friend)
16229     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16230 
16231   // Set the access specifier.
16232   if (!Invalid && SearchDC->isRecord())
16233     SetMemberAccessSpecifier(New, PrevDecl, AS);
16234 
16235   if (PrevDecl)
16236     CheckRedeclarationModuleOwnership(New, PrevDecl);
16237 
16238   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16239     New->startDefinition();
16240 
16241   ProcessDeclAttributeList(S, New, Attrs);
16242   AddPragmaAttributes(S, New);
16243 
16244   // If this has an identifier, add it to the scope stack.
16245   if (TUK == TUK_Friend) {
16246     // We might be replacing an existing declaration in the lookup tables;
16247     // if so, borrow its access specifier.
16248     if (PrevDecl)
16249       New->setAccess(PrevDecl->getAccess());
16250 
16251     DeclContext *DC = New->getDeclContext()->getRedeclContext();
16252     DC->makeDeclVisibleInContext(New);
16253     if (Name) // can be null along some error paths
16254       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16255         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16256   } else if (Name) {
16257     S = getNonFieldDeclScope(S);
16258     PushOnScopeChains(New, S, true);
16259   } else {
16260     CurContext->addDecl(New);
16261   }
16262 
16263   // If this is the C FILE type, notify the AST context.
16264   if (IdentifierInfo *II = New->getIdentifier())
16265     if (!New->isInvalidDecl() &&
16266         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16267         II->isStr("FILE"))
16268       Context.setFILEDecl(New);
16269 
16270   if (PrevDecl)
16271     mergeDeclAttributes(New, PrevDecl);
16272 
16273   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16274     inferGslOwnerPointerAttribute(CXXRD);
16275 
16276   // If there's a #pragma GCC visibility in scope, set the visibility of this
16277   // record.
16278   AddPushedVisibilityAttribute(New);
16279 
16280   if (isMemberSpecialization && !New->isInvalidDecl())
16281     CompleteMemberSpecialization(New, Previous);
16282 
16283   OwnedDecl = true;
16284   // In C++, don't return an invalid declaration. We can't recover well from
16285   // the cases where we make the type anonymous.
16286   if (Invalid && getLangOpts().CPlusPlus) {
16287     if (New->isBeingDefined())
16288       if (auto RD = dyn_cast<RecordDecl>(New))
16289         RD->completeDefinition();
16290     return nullptr;
16291   } else if (SkipBody && SkipBody->ShouldSkip) {
16292     return SkipBody->Previous;
16293   } else {
16294     return New;
16295   }
16296 }
16297 
16298 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
16299   AdjustDeclIfTemplate(TagD);
16300   TagDecl *Tag = cast<TagDecl>(TagD);
16301 
16302   // Enter the tag context.
16303   PushDeclContext(S, Tag);
16304 
16305   ActOnDocumentableDecl(TagD);
16306 
16307   // If there's a #pragma GCC visibility in scope, set the visibility of this
16308   // record.
16309   AddPushedVisibilityAttribute(Tag);
16310 }
16311 
16312 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
16313                                     SkipBodyInfo &SkipBody) {
16314   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16315     return false;
16316 
16317   // Make the previous decl visible.
16318   makeMergedDefinitionVisible(SkipBody.Previous);
16319   return true;
16320 }
16321 
16322 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
16323   assert(isa<ObjCContainerDecl>(IDecl) &&
16324          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
16325   DeclContext *OCD = cast<DeclContext>(IDecl);
16326   assert(OCD->getLexicalParent() == CurContext &&
16327       "The next DeclContext should be lexically contained in the current one.");
16328   CurContext = OCD;
16329   return IDecl;
16330 }
16331 
16332 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16333                                            SourceLocation FinalLoc,
16334                                            bool IsFinalSpelledSealed,
16335                                            SourceLocation LBraceLoc) {
16336   AdjustDeclIfTemplate(TagD);
16337   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
16338 
16339   FieldCollector->StartClass();
16340 
16341   if (!Record->getIdentifier())
16342     return;
16343 
16344   if (FinalLoc.isValid())
16345     Record->addAttr(FinalAttr::Create(
16346         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
16347         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
16348 
16349   // C++ [class]p2:
16350   //   [...] The class-name is also inserted into the scope of the
16351   //   class itself; this is known as the injected-class-name. For
16352   //   purposes of access checking, the injected-class-name is treated
16353   //   as if it were a public member name.
16354   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
16355       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
16356       Record->getLocation(), Record->getIdentifier(),
16357       /*PrevDecl=*/nullptr,
16358       /*DelayTypeCreation=*/true);
16359   Context.getTypeDeclType(InjectedClassName, Record);
16360   InjectedClassName->setImplicit();
16361   InjectedClassName->setAccess(AS_public);
16362   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
16363       InjectedClassName->setDescribedClassTemplate(Template);
16364   PushOnScopeChains(InjectedClassName, S);
16365   assert(InjectedClassName->isInjectedClassName() &&
16366          "Broken injected-class-name");
16367 }
16368 
16369 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
16370                                     SourceRange BraceRange) {
16371   AdjustDeclIfTemplate(TagD);
16372   TagDecl *Tag = cast<TagDecl>(TagD);
16373   Tag->setBraceRange(BraceRange);
16374 
16375   // Make sure we "complete" the definition even it is invalid.
16376   if (Tag->isBeingDefined()) {
16377     assert(Tag->isInvalidDecl() && "We should already have completed it");
16378     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16379       RD->completeDefinition();
16380   }
16381 
16382   if (isa<CXXRecordDecl>(Tag)) {
16383     FieldCollector->FinishClass();
16384   }
16385 
16386   // Exit this scope of this tag's definition.
16387   PopDeclContext();
16388 
16389   if (getCurLexicalContext()->isObjCContainer() &&
16390       Tag->getDeclContext()->isFileContext())
16391     Tag->setTopLevelDeclInObjCContainer();
16392 
16393   // Notify the consumer that we've defined a tag.
16394   if (!Tag->isInvalidDecl())
16395     Consumer.HandleTagDeclDefinition(Tag);
16396 }
16397 
16398 void Sema::ActOnObjCContainerFinishDefinition() {
16399   // Exit this scope of this interface definition.
16400   PopDeclContext();
16401 }
16402 
16403 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
16404   assert(DC == CurContext && "Mismatch of container contexts");
16405   OriginalLexicalContext = DC;
16406   ActOnObjCContainerFinishDefinition();
16407 }
16408 
16409 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
16410   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
16411   OriginalLexicalContext = nullptr;
16412 }
16413 
16414 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
16415   AdjustDeclIfTemplate(TagD);
16416   TagDecl *Tag = cast<TagDecl>(TagD);
16417   Tag->setInvalidDecl();
16418 
16419   // Make sure we "complete" the definition even it is invalid.
16420   if (Tag->isBeingDefined()) {
16421     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16422       RD->completeDefinition();
16423   }
16424 
16425   // We're undoing ActOnTagStartDefinition here, not
16426   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
16427   // the FieldCollector.
16428 
16429   PopDeclContext();
16430 }
16431 
16432 // Note that FieldName may be null for anonymous bitfields.
16433 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
16434                                 IdentifierInfo *FieldName,
16435                                 QualType FieldTy, bool IsMsStruct,
16436                                 Expr *BitWidth, bool *ZeroWidth) {
16437   assert(BitWidth);
16438   if (BitWidth->containsErrors())
16439     return ExprError();
16440 
16441   // Default to true; that shouldn't confuse checks for emptiness
16442   if (ZeroWidth)
16443     *ZeroWidth = true;
16444 
16445   // C99 6.7.2.1p4 - verify the field type.
16446   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
16447   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
16448     // Handle incomplete and sizeless types with a specific error.
16449     if (RequireCompleteSizedType(FieldLoc, FieldTy,
16450                                  diag::err_field_incomplete_or_sizeless))
16451       return ExprError();
16452     if (FieldName)
16453       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
16454         << FieldName << FieldTy << BitWidth->getSourceRange();
16455     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
16456       << FieldTy << BitWidth->getSourceRange();
16457   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
16458                                              UPPC_BitFieldWidth))
16459     return ExprError();
16460 
16461   // If the bit-width is type- or value-dependent, don't try to check
16462   // it now.
16463   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
16464     return BitWidth;
16465 
16466   llvm::APSInt Value;
16467   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
16468   if (ICE.isInvalid())
16469     return ICE;
16470   BitWidth = ICE.get();
16471 
16472   if (Value != 0 && ZeroWidth)
16473     *ZeroWidth = false;
16474 
16475   // Zero-width bitfield is ok for anonymous field.
16476   if (Value == 0 && FieldName)
16477     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
16478 
16479   if (Value.isSigned() && Value.isNegative()) {
16480     if (FieldName)
16481       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
16482                << FieldName << Value.toString(10);
16483     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
16484       << Value.toString(10);
16485   }
16486 
16487   // The size of the bit-field must not exceed our maximum permitted object
16488   // size.
16489   if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
16490     return Diag(FieldLoc, diag::err_bitfield_too_wide)
16491            << !FieldName << FieldName << Value.toString(10);
16492   }
16493 
16494   if (!FieldTy->isDependentType()) {
16495     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
16496     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
16497     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
16498 
16499     // Over-wide bitfields are an error in C or when using the MSVC bitfield
16500     // ABI.
16501     bool CStdConstraintViolation =
16502         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
16503     bool MSBitfieldViolation =
16504         Value.ugt(TypeStorageSize) &&
16505         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
16506     if (CStdConstraintViolation || MSBitfieldViolation) {
16507       unsigned DiagWidth =
16508           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
16509       if (FieldName)
16510         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
16511                << FieldName << Value.toString(10)
16512                << !CStdConstraintViolation << DiagWidth;
16513 
16514       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
16515              << Value.toString(10) << !CStdConstraintViolation
16516              << DiagWidth;
16517     }
16518 
16519     // Warn on types where the user might conceivably expect to get all
16520     // specified bits as value bits: that's all integral types other than
16521     // 'bool'.
16522     if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
16523       Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
16524           << FieldName << Value.toString(10)
16525           << (unsigned)TypeWidth;
16526     }
16527   }
16528 
16529   return BitWidth;
16530 }
16531 
16532 /// ActOnField - Each field of a C struct/union is passed into this in order
16533 /// to create a FieldDecl object for it.
16534 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
16535                        Declarator &D, Expr *BitfieldWidth) {
16536   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
16537                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
16538                                /*InitStyle=*/ICIS_NoInit, AS_public);
16539   return Res;
16540 }
16541 
16542 /// HandleField - Analyze a field of a C struct or a C++ data member.
16543 ///
16544 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
16545                              SourceLocation DeclStart,
16546                              Declarator &D, Expr *BitWidth,
16547                              InClassInitStyle InitStyle,
16548                              AccessSpecifier AS) {
16549   if (D.isDecompositionDeclarator()) {
16550     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
16551     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
16552       << Decomp.getSourceRange();
16553     return nullptr;
16554   }
16555 
16556   IdentifierInfo *II = D.getIdentifier();
16557   SourceLocation Loc = DeclStart;
16558   if (II) Loc = D.getIdentifierLoc();
16559 
16560   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16561   QualType T = TInfo->getType();
16562   if (getLangOpts().CPlusPlus) {
16563     CheckExtraCXXDefaultArguments(D);
16564 
16565     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16566                                         UPPC_DataMemberType)) {
16567       D.setInvalidType();
16568       T = Context.IntTy;
16569       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
16570     }
16571   }
16572 
16573   DiagnoseFunctionSpecifiers(D.getDeclSpec());
16574 
16575   if (D.getDeclSpec().isInlineSpecified())
16576     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
16577         << getLangOpts().CPlusPlus17;
16578   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
16579     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
16580          diag::err_invalid_thread)
16581       << DeclSpec::getSpecifierName(TSCS);
16582 
16583   // Check to see if this name was declared as a member previously
16584   NamedDecl *PrevDecl = nullptr;
16585   LookupResult Previous(*this, II, Loc, LookupMemberName,
16586                         ForVisibleRedeclaration);
16587   LookupName(Previous, S);
16588   switch (Previous.getResultKind()) {
16589     case LookupResult::Found:
16590     case LookupResult::FoundUnresolvedValue:
16591       PrevDecl = Previous.getAsSingle<NamedDecl>();
16592       break;
16593 
16594     case LookupResult::FoundOverloaded:
16595       PrevDecl = Previous.getRepresentativeDecl();
16596       break;
16597 
16598     case LookupResult::NotFound:
16599     case LookupResult::NotFoundInCurrentInstantiation:
16600     case LookupResult::Ambiguous:
16601       break;
16602   }
16603   Previous.suppressDiagnostics();
16604 
16605   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16606     // Maybe we will complain about the shadowed template parameter.
16607     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16608     // Just pretend that we didn't see the previous declaration.
16609     PrevDecl = nullptr;
16610   }
16611 
16612   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
16613     PrevDecl = nullptr;
16614 
16615   bool Mutable
16616     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
16617   SourceLocation TSSL = D.getBeginLoc();
16618   FieldDecl *NewFD
16619     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
16620                      TSSL, AS, PrevDecl, &D);
16621 
16622   if (NewFD->isInvalidDecl())
16623     Record->setInvalidDecl();
16624 
16625   if (D.getDeclSpec().isModulePrivateSpecified())
16626     NewFD->setModulePrivate();
16627 
16628   if (NewFD->isInvalidDecl() && PrevDecl) {
16629     // Don't introduce NewFD into scope; there's already something
16630     // with the same name in the same scope.
16631   } else if (II) {
16632     PushOnScopeChains(NewFD, S);
16633   } else
16634     Record->addDecl(NewFD);
16635 
16636   return NewFD;
16637 }
16638 
16639 /// Build a new FieldDecl and check its well-formedness.
16640 ///
16641 /// This routine builds a new FieldDecl given the fields name, type,
16642 /// record, etc. \p PrevDecl should refer to any previous declaration
16643 /// with the same name and in the same scope as the field to be
16644 /// created.
16645 ///
16646 /// \returns a new FieldDecl.
16647 ///
16648 /// \todo The Declarator argument is a hack. It will be removed once
16649 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
16650                                 TypeSourceInfo *TInfo,
16651                                 RecordDecl *Record, SourceLocation Loc,
16652                                 bool Mutable, Expr *BitWidth,
16653                                 InClassInitStyle InitStyle,
16654                                 SourceLocation TSSL,
16655                                 AccessSpecifier AS, NamedDecl *PrevDecl,
16656                                 Declarator *D) {
16657   IdentifierInfo *II = Name.getAsIdentifierInfo();
16658   bool InvalidDecl = false;
16659   if (D) InvalidDecl = D->isInvalidType();
16660 
16661   // If we receive a broken type, recover by assuming 'int' and
16662   // marking this declaration as invalid.
16663   if (T.isNull() || T->containsErrors()) {
16664     InvalidDecl = true;
16665     T = Context.IntTy;
16666   }
16667 
16668   QualType EltTy = Context.getBaseElementType(T);
16669   if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
16670     if (RequireCompleteSizedType(Loc, EltTy,
16671                                  diag::err_field_incomplete_or_sizeless)) {
16672       // Fields of incomplete type force their record to be invalid.
16673       Record->setInvalidDecl();
16674       InvalidDecl = true;
16675     } else {
16676       NamedDecl *Def;
16677       EltTy->isIncompleteType(&Def);
16678       if (Def && Def->isInvalidDecl()) {
16679         Record->setInvalidDecl();
16680         InvalidDecl = true;
16681       }
16682     }
16683   }
16684 
16685   // TR 18037 does not allow fields to be declared with address space
16686   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
16687       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
16688     Diag(Loc, diag::err_field_with_address_space);
16689     Record->setInvalidDecl();
16690     InvalidDecl = true;
16691   }
16692 
16693   if (LangOpts.OpenCL) {
16694     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
16695     // used as structure or union field: image, sampler, event or block types.
16696     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
16697         T->isBlockPointerType()) {
16698       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
16699       Record->setInvalidDecl();
16700       InvalidDecl = true;
16701     }
16702     // OpenCL v1.2 s6.9.c: bitfields are not supported.
16703     if (BitWidth) {
16704       Diag(Loc, diag::err_opencl_bitfields);
16705       InvalidDecl = true;
16706     }
16707   }
16708 
16709   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
16710   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
16711       T.hasQualifiers()) {
16712     InvalidDecl = true;
16713     Diag(Loc, diag::err_anon_bitfield_qualifiers);
16714   }
16715 
16716   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16717   // than a variably modified type.
16718   if (!InvalidDecl && T->isVariablyModifiedType()) {
16719     if (!tryToFixVariablyModifiedVarType(
16720             *this, TInfo, T, Loc, diag::err_typecheck_field_variable_size))
16721       InvalidDecl = true;
16722   }
16723 
16724   // Fields can not have abstract class types
16725   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
16726                                              diag::err_abstract_type_in_decl,
16727                                              AbstractFieldType))
16728     InvalidDecl = true;
16729 
16730   bool ZeroWidth = false;
16731   if (InvalidDecl)
16732     BitWidth = nullptr;
16733   // If this is declared as a bit-field, check the bit-field.
16734   if (BitWidth) {
16735     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
16736                               &ZeroWidth).get();
16737     if (!BitWidth) {
16738       InvalidDecl = true;
16739       BitWidth = nullptr;
16740       ZeroWidth = false;
16741     }
16742   }
16743 
16744   // Check that 'mutable' is consistent with the type of the declaration.
16745   if (!InvalidDecl && Mutable) {
16746     unsigned DiagID = 0;
16747     if (T->isReferenceType())
16748       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
16749                                         : diag::err_mutable_reference;
16750     else if (T.isConstQualified())
16751       DiagID = diag::err_mutable_const;
16752 
16753     if (DiagID) {
16754       SourceLocation ErrLoc = Loc;
16755       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
16756         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
16757       Diag(ErrLoc, DiagID);
16758       if (DiagID != diag::ext_mutable_reference) {
16759         Mutable = false;
16760         InvalidDecl = true;
16761       }
16762     }
16763   }
16764 
16765   // C++11 [class.union]p8 (DR1460):
16766   //   At most one variant member of a union may have a
16767   //   brace-or-equal-initializer.
16768   if (InitStyle != ICIS_NoInit)
16769     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
16770 
16771   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
16772                                        BitWidth, Mutable, InitStyle);
16773   if (InvalidDecl)
16774     NewFD->setInvalidDecl();
16775 
16776   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
16777     Diag(Loc, diag::err_duplicate_member) << II;
16778     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16779     NewFD->setInvalidDecl();
16780   }
16781 
16782   if (!InvalidDecl && getLangOpts().CPlusPlus) {
16783     if (Record->isUnion()) {
16784       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16785         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
16786         if (RDecl->getDefinition()) {
16787           // C++ [class.union]p1: An object of a class with a non-trivial
16788           // constructor, a non-trivial copy constructor, a non-trivial
16789           // destructor, or a non-trivial copy assignment operator
16790           // cannot be a member of a union, nor can an array of such
16791           // objects.
16792           if (CheckNontrivialField(NewFD))
16793             NewFD->setInvalidDecl();
16794         }
16795       }
16796 
16797       // C++ [class.union]p1: If a union contains a member of reference type,
16798       // the program is ill-formed, except when compiling with MSVC extensions
16799       // enabled.
16800       if (EltTy->isReferenceType()) {
16801         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
16802                                     diag::ext_union_member_of_reference_type :
16803                                     diag::err_union_member_of_reference_type)
16804           << NewFD->getDeclName() << EltTy;
16805         if (!getLangOpts().MicrosoftExt)
16806           NewFD->setInvalidDecl();
16807       }
16808     }
16809   }
16810 
16811   // FIXME: We need to pass in the attributes given an AST
16812   // representation, not a parser representation.
16813   if (D) {
16814     // FIXME: The current scope is almost... but not entirely... correct here.
16815     ProcessDeclAttributes(getCurScope(), NewFD, *D);
16816 
16817     if (NewFD->hasAttrs())
16818       CheckAlignasUnderalignment(NewFD);
16819   }
16820 
16821   // In auto-retain/release, infer strong retension for fields of
16822   // retainable type.
16823   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
16824     NewFD->setInvalidDecl();
16825 
16826   if (T.isObjCGCWeak())
16827     Diag(Loc, diag::warn_attribute_weak_on_field);
16828 
16829   // PPC MMA non-pointer types are not allowed as field types.
16830   if (Context.getTargetInfo().getTriple().isPPC64() &&
16831       CheckPPCMMAType(T, NewFD->getLocation()))
16832     NewFD->setInvalidDecl();
16833 
16834   NewFD->setAccess(AS);
16835   return NewFD;
16836 }
16837 
16838 bool Sema::CheckNontrivialField(FieldDecl *FD) {
16839   assert(FD);
16840   assert(getLangOpts().CPlusPlus && "valid check only for C++");
16841 
16842   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
16843     return false;
16844 
16845   QualType EltTy = Context.getBaseElementType(FD->getType());
16846   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16847     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
16848     if (RDecl->getDefinition()) {
16849       // We check for copy constructors before constructors
16850       // because otherwise we'll never get complaints about
16851       // copy constructors.
16852 
16853       CXXSpecialMember member = CXXInvalid;
16854       // We're required to check for any non-trivial constructors. Since the
16855       // implicit default constructor is suppressed if there are any
16856       // user-declared constructors, we just need to check that there is a
16857       // trivial default constructor and a trivial copy constructor. (We don't
16858       // worry about move constructors here, since this is a C++98 check.)
16859       if (RDecl->hasNonTrivialCopyConstructor())
16860         member = CXXCopyConstructor;
16861       else if (!RDecl->hasTrivialDefaultConstructor())
16862         member = CXXDefaultConstructor;
16863       else if (RDecl->hasNonTrivialCopyAssignment())
16864         member = CXXCopyAssignment;
16865       else if (RDecl->hasNonTrivialDestructor())
16866         member = CXXDestructor;
16867 
16868       if (member != CXXInvalid) {
16869         if (!getLangOpts().CPlusPlus11 &&
16870             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
16871           // Objective-C++ ARC: it is an error to have a non-trivial field of
16872           // a union. However, system headers in Objective-C programs
16873           // occasionally have Objective-C lifetime objects within unions,
16874           // and rather than cause the program to fail, we make those
16875           // members unavailable.
16876           SourceLocation Loc = FD->getLocation();
16877           if (getSourceManager().isInSystemHeader(Loc)) {
16878             if (!FD->hasAttr<UnavailableAttr>())
16879               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
16880                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
16881             return false;
16882           }
16883         }
16884 
16885         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
16886                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
16887                diag::err_illegal_union_or_anon_struct_member)
16888           << FD->getParent()->isUnion() << FD->getDeclName() << member;
16889         DiagnoseNontrivial(RDecl, member);
16890         return !getLangOpts().CPlusPlus11;
16891       }
16892     }
16893   }
16894 
16895   return false;
16896 }
16897 
16898 /// TranslateIvarVisibility - Translate visibility from a token ID to an
16899 ///  AST enum value.
16900 static ObjCIvarDecl::AccessControl
16901 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
16902   switch (ivarVisibility) {
16903   default: llvm_unreachable("Unknown visitibility kind");
16904   case tok::objc_private: return ObjCIvarDecl::Private;
16905   case tok::objc_public: return ObjCIvarDecl::Public;
16906   case tok::objc_protected: return ObjCIvarDecl::Protected;
16907   case tok::objc_package: return ObjCIvarDecl::Package;
16908   }
16909 }
16910 
16911 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
16912 /// in order to create an IvarDecl object for it.
16913 Decl *Sema::ActOnIvar(Scope *S,
16914                                 SourceLocation DeclStart,
16915                                 Declarator &D, Expr *BitfieldWidth,
16916                                 tok::ObjCKeywordKind Visibility) {
16917 
16918   IdentifierInfo *II = D.getIdentifier();
16919   Expr *BitWidth = (Expr*)BitfieldWidth;
16920   SourceLocation Loc = DeclStart;
16921   if (II) Loc = D.getIdentifierLoc();
16922 
16923   // FIXME: Unnamed fields can be handled in various different ways, for
16924   // example, unnamed unions inject all members into the struct namespace!
16925 
16926   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16927   QualType T = TInfo->getType();
16928 
16929   if (BitWidth) {
16930     // 6.7.2.1p3, 6.7.2.1p4
16931     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
16932     if (!BitWidth)
16933       D.setInvalidType();
16934   } else {
16935     // Not a bitfield.
16936 
16937     // validate II.
16938 
16939   }
16940   if (T->isReferenceType()) {
16941     Diag(Loc, diag::err_ivar_reference_type);
16942     D.setInvalidType();
16943   }
16944   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16945   // than a variably modified type.
16946   else if (T->isVariablyModifiedType()) {
16947     if (!tryToFixVariablyModifiedVarType(
16948             *this, TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
16949       D.setInvalidType();
16950   }
16951 
16952   // Get the visibility (access control) for this ivar.
16953   ObjCIvarDecl::AccessControl ac =
16954     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
16955                                         : ObjCIvarDecl::None;
16956   // Must set ivar's DeclContext to its enclosing interface.
16957   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
16958   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
16959     return nullptr;
16960   ObjCContainerDecl *EnclosingContext;
16961   if (ObjCImplementationDecl *IMPDecl =
16962       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16963     if (LangOpts.ObjCRuntime.isFragile()) {
16964     // Case of ivar declared in an implementation. Context is that of its class.
16965       EnclosingContext = IMPDecl->getClassInterface();
16966       assert(EnclosingContext && "Implementation has no class interface!");
16967     }
16968     else
16969       EnclosingContext = EnclosingDecl;
16970   } else {
16971     if (ObjCCategoryDecl *CDecl =
16972         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16973       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
16974         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
16975         return nullptr;
16976       }
16977     }
16978     EnclosingContext = EnclosingDecl;
16979   }
16980 
16981   // Construct the decl.
16982   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
16983                                              DeclStart, Loc, II, T,
16984                                              TInfo, ac, (Expr *)BitfieldWidth);
16985 
16986   if (II) {
16987     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
16988                                            ForVisibleRedeclaration);
16989     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
16990         && !isa<TagDecl>(PrevDecl)) {
16991       Diag(Loc, diag::err_duplicate_member) << II;
16992       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16993       NewID->setInvalidDecl();
16994     }
16995   }
16996 
16997   // Process attributes attached to the ivar.
16998   ProcessDeclAttributes(S, NewID, D);
16999 
17000   if (D.isInvalidType())
17001     NewID->setInvalidDecl();
17002 
17003   // In ARC, infer 'retaining' for ivars of retainable type.
17004   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
17005     NewID->setInvalidDecl();
17006 
17007   if (D.getDeclSpec().isModulePrivateSpecified())
17008     NewID->setModulePrivate();
17009 
17010   if (II) {
17011     // FIXME: When interfaces are DeclContexts, we'll need to add
17012     // these to the interface.
17013     S->AddDecl(NewID);
17014     IdResolver.AddDecl(NewID);
17015   }
17016 
17017   if (LangOpts.ObjCRuntime.isNonFragile() &&
17018       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
17019     Diag(Loc, diag::warn_ivars_in_interface);
17020 
17021   return NewID;
17022 }
17023 
17024 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
17025 /// class and class extensions. For every class \@interface and class
17026 /// extension \@interface, if the last ivar is a bitfield of any type,
17027 /// then add an implicit `char :0` ivar to the end of that interface.
17028 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
17029                              SmallVectorImpl<Decl *> &AllIvarDecls) {
17030   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
17031     return;
17032 
17033   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
17034   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
17035 
17036   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
17037     return;
17038   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
17039   if (!ID) {
17040     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
17041       if (!CD->IsClassExtension())
17042         return;
17043     }
17044     // No need to add this to end of @implementation.
17045     else
17046       return;
17047   }
17048   // All conditions are met. Add a new bitfield to the tail end of ivars.
17049   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
17050   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
17051 
17052   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17053                               DeclLoc, DeclLoc, nullptr,
17054                               Context.CharTy,
17055                               Context.getTrivialTypeSourceInfo(Context.CharTy,
17056                                                                DeclLoc),
17057                               ObjCIvarDecl::Private, BW,
17058                               true);
17059   AllIvarDecls.push_back(Ivar);
17060 }
17061 
17062 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17063                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
17064                        SourceLocation RBrac,
17065                        const ParsedAttributesView &Attrs) {
17066   assert(EnclosingDecl && "missing record or interface decl");
17067 
17068   // If this is an Objective-C @implementation or category and we have
17069   // new fields here we should reset the layout of the interface since
17070   // it will now change.
17071   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17072     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17073     switch (DC->getKind()) {
17074     default: break;
17075     case Decl::ObjCCategory:
17076       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17077       break;
17078     case Decl::ObjCImplementation:
17079       Context.
17080         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17081       break;
17082     }
17083   }
17084 
17085   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17086   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17087 
17088   // Start counting up the number of named members; make sure to include
17089   // members of anonymous structs and unions in the total.
17090   unsigned NumNamedMembers = 0;
17091   if (Record) {
17092     for (const auto *I : Record->decls()) {
17093       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17094         if (IFD->getDeclName())
17095           ++NumNamedMembers;
17096     }
17097   }
17098 
17099   // Verify that all the fields are okay.
17100   SmallVector<FieldDecl*, 32> RecFields;
17101 
17102   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17103        i != end; ++i) {
17104     FieldDecl *FD = cast<FieldDecl>(*i);
17105 
17106     // Get the type for the field.
17107     const Type *FDTy = FD->getType().getTypePtr();
17108 
17109     if (!FD->isAnonymousStructOrUnion()) {
17110       // Remember all fields written by the user.
17111       RecFields.push_back(FD);
17112     }
17113 
17114     // If the field is already invalid for some reason, don't emit more
17115     // diagnostics about it.
17116     if (FD->isInvalidDecl()) {
17117       EnclosingDecl->setInvalidDecl();
17118       continue;
17119     }
17120 
17121     // C99 6.7.2.1p2:
17122     //   A structure or union shall not contain a member with
17123     //   incomplete or function type (hence, a structure shall not
17124     //   contain an instance of itself, but may contain a pointer to
17125     //   an instance of itself), except that the last member of a
17126     //   structure with more than one named member may have incomplete
17127     //   array type; such a structure (and any union containing,
17128     //   possibly recursively, a member that is such a structure)
17129     //   shall not be a member of a structure or an element of an
17130     //   array.
17131     bool IsLastField = (i + 1 == Fields.end());
17132     if (FDTy->isFunctionType()) {
17133       // Field declared as a function.
17134       Diag(FD->getLocation(), diag::err_field_declared_as_function)
17135         << FD->getDeclName();
17136       FD->setInvalidDecl();
17137       EnclosingDecl->setInvalidDecl();
17138       continue;
17139     } else if (FDTy->isIncompleteArrayType() &&
17140                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17141       if (Record) {
17142         // Flexible array member.
17143         // Microsoft and g++ is more permissive regarding flexible array.
17144         // It will accept flexible array in union and also
17145         // as the sole element of a struct/class.
17146         unsigned DiagID = 0;
17147         if (!Record->isUnion() && !IsLastField) {
17148           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17149             << FD->getDeclName() << FD->getType() << Record->getTagKind();
17150           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17151           FD->setInvalidDecl();
17152           EnclosingDecl->setInvalidDecl();
17153           continue;
17154         } else if (Record->isUnion())
17155           DiagID = getLangOpts().MicrosoftExt
17156                        ? diag::ext_flexible_array_union_ms
17157                        : getLangOpts().CPlusPlus
17158                              ? diag::ext_flexible_array_union_gnu
17159                              : diag::err_flexible_array_union;
17160         else if (NumNamedMembers < 1)
17161           DiagID = getLangOpts().MicrosoftExt
17162                        ? diag::ext_flexible_array_empty_aggregate_ms
17163                        : getLangOpts().CPlusPlus
17164                              ? diag::ext_flexible_array_empty_aggregate_gnu
17165                              : diag::err_flexible_array_empty_aggregate;
17166 
17167         if (DiagID)
17168           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17169                                           << Record->getTagKind();
17170         // While the layout of types that contain virtual bases is not specified
17171         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17172         // virtual bases after the derived members.  This would make a flexible
17173         // array member declared at the end of an object not adjacent to the end
17174         // of the type.
17175         if (CXXRecord && CXXRecord->getNumVBases() != 0)
17176           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17177               << FD->getDeclName() << Record->getTagKind();
17178         if (!getLangOpts().C99)
17179           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17180             << FD->getDeclName() << Record->getTagKind();
17181 
17182         // If the element type has a non-trivial destructor, we would not
17183         // implicitly destroy the elements, so disallow it for now.
17184         //
17185         // FIXME: GCC allows this. We should probably either implicitly delete
17186         // the destructor of the containing class, or just allow this.
17187         QualType BaseElem = Context.getBaseElementType(FD->getType());
17188         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17189           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17190             << FD->getDeclName() << FD->getType();
17191           FD->setInvalidDecl();
17192           EnclosingDecl->setInvalidDecl();
17193           continue;
17194         }
17195         // Okay, we have a legal flexible array member at the end of the struct.
17196         Record->setHasFlexibleArrayMember(true);
17197       } else {
17198         // In ObjCContainerDecl ivars with incomplete array type are accepted,
17199         // unless they are followed by another ivar. That check is done
17200         // elsewhere, after synthesized ivars are known.
17201       }
17202     } else if (!FDTy->isDependentType() &&
17203                RequireCompleteSizedType(
17204                    FD->getLocation(), FD->getType(),
17205                    diag::err_field_incomplete_or_sizeless)) {
17206       // Incomplete type
17207       FD->setInvalidDecl();
17208       EnclosingDecl->setInvalidDecl();
17209       continue;
17210     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
17211       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
17212         // A type which contains a flexible array member is considered to be a
17213         // flexible array member.
17214         Record->setHasFlexibleArrayMember(true);
17215         if (!Record->isUnion()) {
17216           // If this is a struct/class and this is not the last element, reject
17217           // it.  Note that GCC supports variable sized arrays in the middle of
17218           // structures.
17219           if (!IsLastField)
17220             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
17221               << FD->getDeclName() << FD->getType();
17222           else {
17223             // We support flexible arrays at the end of structs in
17224             // other structs as an extension.
17225             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
17226               << FD->getDeclName();
17227           }
17228         }
17229       }
17230       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17231           RequireNonAbstractType(FD->getLocation(), FD->getType(),
17232                                  diag::err_abstract_type_in_decl,
17233                                  AbstractIvarType)) {
17234         // Ivars can not have abstract class types
17235         FD->setInvalidDecl();
17236       }
17237       if (Record && FDTTy->getDecl()->hasObjectMember())
17238         Record->setHasObjectMember(true);
17239       if (Record && FDTTy->getDecl()->hasVolatileMember())
17240         Record->setHasVolatileMember(true);
17241     } else if (FDTy->isObjCObjectType()) {
17242       /// A field cannot be an Objective-c object
17243       Diag(FD->getLocation(), diag::err_statically_allocated_object)
17244         << FixItHint::CreateInsertion(FD->getLocation(), "*");
17245       QualType T = Context.getObjCObjectPointerType(FD->getType());
17246       FD->setType(T);
17247     } else if (Record && Record->isUnion() &&
17248                FD->getType().hasNonTrivialObjCLifetime() &&
17249                getSourceManager().isInSystemHeader(FD->getLocation()) &&
17250                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
17251                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
17252                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
17253       // For backward compatibility, fields of C unions declared in system
17254       // headers that have non-trivial ObjC ownership qualifications are marked
17255       // as unavailable unless the qualifier is explicit and __strong. This can
17256       // break ABI compatibility between programs compiled with ARC and MRR, but
17257       // is a better option than rejecting programs using those unions under
17258       // ARC.
17259       FD->addAttr(UnavailableAttr::CreateImplicit(
17260           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
17261           FD->getLocation()));
17262     } else if (getLangOpts().ObjC &&
17263                getLangOpts().getGC() != LangOptions::NonGC && Record &&
17264                !Record->hasObjectMember()) {
17265       if (FD->getType()->isObjCObjectPointerType() ||
17266           FD->getType().isObjCGCStrong())
17267         Record->setHasObjectMember(true);
17268       else if (Context.getAsArrayType(FD->getType())) {
17269         QualType BaseType = Context.getBaseElementType(FD->getType());
17270         if (BaseType->isRecordType() &&
17271             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
17272           Record->setHasObjectMember(true);
17273         else if (BaseType->isObjCObjectPointerType() ||
17274                  BaseType.isObjCGCStrong())
17275                Record->setHasObjectMember(true);
17276       }
17277     }
17278 
17279     if (Record && !getLangOpts().CPlusPlus &&
17280         !shouldIgnoreForRecordTriviality(FD)) {
17281       QualType FT = FD->getType();
17282       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
17283         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
17284         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
17285             Record->isUnion())
17286           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
17287       }
17288       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
17289       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
17290         Record->setNonTrivialToPrimitiveCopy(true);
17291         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
17292           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
17293       }
17294       if (FT.isDestructedType()) {
17295         Record->setNonTrivialToPrimitiveDestroy(true);
17296         Record->setParamDestroyedInCallee(true);
17297         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
17298           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
17299       }
17300 
17301       if (const auto *RT = FT->getAs<RecordType>()) {
17302         if (RT->getDecl()->getArgPassingRestrictions() ==
17303             RecordDecl::APK_CanNeverPassInRegs)
17304           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17305       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
17306         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17307     }
17308 
17309     if (Record && FD->getType().isVolatileQualified())
17310       Record->setHasVolatileMember(true);
17311     // Keep track of the number of named members.
17312     if (FD->getIdentifier())
17313       ++NumNamedMembers;
17314   }
17315 
17316   // Okay, we successfully defined 'Record'.
17317   if (Record) {
17318     bool Completed = false;
17319     if (CXXRecord) {
17320       if (!CXXRecord->isInvalidDecl()) {
17321         // Set access bits correctly on the directly-declared conversions.
17322         for (CXXRecordDecl::conversion_iterator
17323                I = CXXRecord->conversion_begin(),
17324                E = CXXRecord->conversion_end(); I != E; ++I)
17325           I.setAccess((*I)->getAccess());
17326       }
17327 
17328       // Add any implicitly-declared members to this class.
17329       AddImplicitlyDeclaredMembersToClass(CXXRecord);
17330 
17331       if (!CXXRecord->isDependentType()) {
17332         if (!CXXRecord->isInvalidDecl()) {
17333           // If we have virtual base classes, we may end up finding multiple
17334           // final overriders for a given virtual function. Check for this
17335           // problem now.
17336           if (CXXRecord->getNumVBases()) {
17337             CXXFinalOverriderMap FinalOverriders;
17338             CXXRecord->getFinalOverriders(FinalOverriders);
17339 
17340             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
17341                                              MEnd = FinalOverriders.end();
17342                  M != MEnd; ++M) {
17343               for (OverridingMethods::iterator SO = M->second.begin(),
17344                                             SOEnd = M->second.end();
17345                    SO != SOEnd; ++SO) {
17346                 assert(SO->second.size() > 0 &&
17347                        "Virtual function without overriding functions?");
17348                 if (SO->second.size() == 1)
17349                   continue;
17350 
17351                 // C++ [class.virtual]p2:
17352                 //   In a derived class, if a virtual member function of a base
17353                 //   class subobject has more than one final overrider the
17354                 //   program is ill-formed.
17355                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
17356                   << (const NamedDecl *)M->first << Record;
17357                 Diag(M->first->getLocation(),
17358                      diag::note_overridden_virtual_function);
17359                 for (OverridingMethods::overriding_iterator
17360                           OM = SO->second.begin(),
17361                        OMEnd = SO->second.end();
17362                      OM != OMEnd; ++OM)
17363                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
17364                     << (const NamedDecl *)M->first << OM->Method->getParent();
17365 
17366                 Record->setInvalidDecl();
17367               }
17368             }
17369             CXXRecord->completeDefinition(&FinalOverriders);
17370             Completed = true;
17371           }
17372         }
17373       }
17374     }
17375 
17376     if (!Completed)
17377       Record->completeDefinition();
17378 
17379     // Handle attributes before checking the layout.
17380     ProcessDeclAttributeList(S, Record, Attrs);
17381 
17382     // We may have deferred checking for a deleted destructor. Check now.
17383     if (CXXRecord) {
17384       auto *Dtor = CXXRecord->getDestructor();
17385       if (Dtor && Dtor->isImplicit() &&
17386           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
17387         CXXRecord->setImplicitDestructorIsDeleted();
17388         SetDeclDeleted(Dtor, CXXRecord->getLocation());
17389       }
17390     }
17391 
17392     if (Record->hasAttrs()) {
17393       CheckAlignasUnderalignment(Record);
17394 
17395       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
17396         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
17397                                            IA->getRange(), IA->getBestCase(),
17398                                            IA->getInheritanceModel());
17399     }
17400 
17401     // Check if the structure/union declaration is a type that can have zero
17402     // size in C. For C this is a language extension, for C++ it may cause
17403     // compatibility problems.
17404     bool CheckForZeroSize;
17405     if (!getLangOpts().CPlusPlus) {
17406       CheckForZeroSize = true;
17407     } else {
17408       // For C++ filter out types that cannot be referenced in C code.
17409       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
17410       CheckForZeroSize =
17411           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
17412           !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
17413           CXXRecord->isCLike();
17414     }
17415     if (CheckForZeroSize) {
17416       bool ZeroSize = true;
17417       bool IsEmpty = true;
17418       unsigned NonBitFields = 0;
17419       for (RecordDecl::field_iterator I = Record->field_begin(),
17420                                       E = Record->field_end();
17421            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
17422         IsEmpty = false;
17423         if (I->isUnnamedBitfield()) {
17424           if (!I->isZeroLengthBitField(Context))
17425             ZeroSize = false;
17426         } else {
17427           ++NonBitFields;
17428           QualType FieldType = I->getType();
17429           if (FieldType->isIncompleteType() ||
17430               !Context.getTypeSizeInChars(FieldType).isZero())
17431             ZeroSize = false;
17432         }
17433       }
17434 
17435       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
17436       // allowed in C++, but warn if its declaration is inside
17437       // extern "C" block.
17438       if (ZeroSize) {
17439         Diag(RecLoc, getLangOpts().CPlusPlus ?
17440                          diag::warn_zero_size_struct_union_in_extern_c :
17441                          diag::warn_zero_size_struct_union_compat)
17442           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
17443       }
17444 
17445       // Structs without named members are extension in C (C99 6.7.2.1p7),
17446       // but are accepted by GCC.
17447       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
17448         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
17449                                diag::ext_no_named_members_in_struct_union)
17450           << Record->isUnion();
17451       }
17452     }
17453   } else {
17454     ObjCIvarDecl **ClsFields =
17455       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
17456     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
17457       ID->setEndOfDefinitionLoc(RBrac);
17458       // Add ivar's to class's DeclContext.
17459       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17460         ClsFields[i]->setLexicalDeclContext(ID);
17461         ID->addDecl(ClsFields[i]);
17462       }
17463       // Must enforce the rule that ivars in the base classes may not be
17464       // duplicates.
17465       if (ID->getSuperClass())
17466         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
17467     } else if (ObjCImplementationDecl *IMPDecl =
17468                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17469       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
17470       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
17471         // Ivar declared in @implementation never belongs to the implementation.
17472         // Only it is in implementation's lexical context.
17473         ClsFields[I]->setLexicalDeclContext(IMPDecl);
17474       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
17475       IMPDecl->setIvarLBraceLoc(LBrac);
17476       IMPDecl->setIvarRBraceLoc(RBrac);
17477     } else if (ObjCCategoryDecl *CDecl =
17478                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17479       // case of ivars in class extension; all other cases have been
17480       // reported as errors elsewhere.
17481       // FIXME. Class extension does not have a LocEnd field.
17482       // CDecl->setLocEnd(RBrac);
17483       // Add ivar's to class extension's DeclContext.
17484       // Diagnose redeclaration of private ivars.
17485       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
17486       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17487         if (IDecl) {
17488           if (const ObjCIvarDecl *ClsIvar =
17489               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
17490             Diag(ClsFields[i]->getLocation(),
17491                  diag::err_duplicate_ivar_declaration);
17492             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
17493             continue;
17494           }
17495           for (const auto *Ext : IDecl->known_extensions()) {
17496             if (const ObjCIvarDecl *ClsExtIvar
17497                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
17498               Diag(ClsFields[i]->getLocation(),
17499                    diag::err_duplicate_ivar_declaration);
17500               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
17501               continue;
17502             }
17503           }
17504         }
17505         ClsFields[i]->setLexicalDeclContext(CDecl);
17506         CDecl->addDecl(ClsFields[i]);
17507       }
17508       CDecl->setIvarLBraceLoc(LBrac);
17509       CDecl->setIvarRBraceLoc(RBrac);
17510     }
17511   }
17512 }
17513 
17514 /// Determine whether the given integral value is representable within
17515 /// the given type T.
17516 static bool isRepresentableIntegerValue(ASTContext &Context,
17517                                         llvm::APSInt &Value,
17518                                         QualType T) {
17519   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
17520          "Integral type required!");
17521   unsigned BitWidth = Context.getIntWidth(T);
17522 
17523   if (Value.isUnsigned() || Value.isNonNegative()) {
17524     if (T->isSignedIntegerOrEnumerationType())
17525       --BitWidth;
17526     return Value.getActiveBits() <= BitWidth;
17527   }
17528   return Value.getMinSignedBits() <= BitWidth;
17529 }
17530 
17531 // Given an integral type, return the next larger integral type
17532 // (or a NULL type of no such type exists).
17533 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
17534   // FIXME: Int128/UInt128 support, which also needs to be introduced into
17535   // enum checking below.
17536   assert((T->isIntegralType(Context) ||
17537          T->isEnumeralType()) && "Integral type required!");
17538   const unsigned NumTypes = 4;
17539   QualType SignedIntegralTypes[NumTypes] = {
17540     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
17541   };
17542   QualType UnsignedIntegralTypes[NumTypes] = {
17543     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
17544     Context.UnsignedLongLongTy
17545   };
17546 
17547   unsigned BitWidth = Context.getTypeSize(T);
17548   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
17549                                                         : UnsignedIntegralTypes;
17550   for (unsigned I = 0; I != NumTypes; ++I)
17551     if (Context.getTypeSize(Types[I]) > BitWidth)
17552       return Types[I];
17553 
17554   return QualType();
17555 }
17556 
17557 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
17558                                           EnumConstantDecl *LastEnumConst,
17559                                           SourceLocation IdLoc,
17560                                           IdentifierInfo *Id,
17561                                           Expr *Val) {
17562   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17563   llvm::APSInt EnumVal(IntWidth);
17564   QualType EltTy;
17565 
17566   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
17567     Val = nullptr;
17568 
17569   if (Val)
17570     Val = DefaultLvalueConversion(Val).get();
17571 
17572   if (Val) {
17573     if (Enum->isDependentType() || Val->isTypeDependent())
17574       EltTy = Context.DependentTy;
17575     else {
17576       // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
17577       // underlying type, but do allow it in all other contexts.
17578       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
17579         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
17580         // constant-expression in the enumerator-definition shall be a converted
17581         // constant expression of the underlying type.
17582         EltTy = Enum->getIntegerType();
17583         ExprResult Converted =
17584           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
17585                                            CCEK_Enumerator);
17586         if (Converted.isInvalid())
17587           Val = nullptr;
17588         else
17589           Val = Converted.get();
17590       } else if (!Val->isValueDependent() &&
17591                  !(Val =
17592                        VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
17593                            .get())) {
17594         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
17595       } else {
17596         if (Enum->isComplete()) {
17597           EltTy = Enum->getIntegerType();
17598 
17599           // In Obj-C and Microsoft mode, require the enumeration value to be
17600           // representable in the underlying type of the enumeration. In C++11,
17601           // we perform a non-narrowing conversion as part of converted constant
17602           // expression checking.
17603           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17604             if (Context.getTargetInfo()
17605                     .getTriple()
17606                     .isWindowsMSVCEnvironment()) {
17607               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
17608             } else {
17609               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
17610             }
17611           }
17612 
17613           // Cast to the underlying type.
17614           Val = ImpCastExprToType(Val, EltTy,
17615                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
17616                                                          : CK_IntegralCast)
17617                     .get();
17618         } else if (getLangOpts().CPlusPlus) {
17619           // C++11 [dcl.enum]p5:
17620           //   If the underlying type is not fixed, the type of each enumerator
17621           //   is the type of its initializing value:
17622           //     - If an initializer is specified for an enumerator, the
17623           //       initializing value has the same type as the expression.
17624           EltTy = Val->getType();
17625         } else {
17626           // C99 6.7.2.2p2:
17627           //   The expression that defines the value of an enumeration constant
17628           //   shall be an integer constant expression that has a value
17629           //   representable as an int.
17630 
17631           // Complain if the value is not representable in an int.
17632           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
17633             Diag(IdLoc, diag::ext_enum_value_not_int)
17634               << EnumVal.toString(10) << Val->getSourceRange()
17635               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
17636           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
17637             // Force the type of the expression to 'int'.
17638             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
17639           }
17640           EltTy = Val->getType();
17641         }
17642       }
17643     }
17644   }
17645 
17646   if (!Val) {
17647     if (Enum->isDependentType())
17648       EltTy = Context.DependentTy;
17649     else if (!LastEnumConst) {
17650       // C++0x [dcl.enum]p5:
17651       //   If the underlying type is not fixed, the type of each enumerator
17652       //   is the type of its initializing value:
17653       //     - If no initializer is specified for the first enumerator, the
17654       //       initializing value has an unspecified integral type.
17655       //
17656       // GCC uses 'int' for its unspecified integral type, as does
17657       // C99 6.7.2.2p3.
17658       if (Enum->isFixed()) {
17659         EltTy = Enum->getIntegerType();
17660       }
17661       else {
17662         EltTy = Context.IntTy;
17663       }
17664     } else {
17665       // Assign the last value + 1.
17666       EnumVal = LastEnumConst->getInitVal();
17667       ++EnumVal;
17668       EltTy = LastEnumConst->getType();
17669 
17670       // Check for overflow on increment.
17671       if (EnumVal < LastEnumConst->getInitVal()) {
17672         // C++0x [dcl.enum]p5:
17673         //   If the underlying type is not fixed, the type of each enumerator
17674         //   is the type of its initializing value:
17675         //
17676         //     - Otherwise the type of the initializing value is the same as
17677         //       the type of the initializing value of the preceding enumerator
17678         //       unless the incremented value is not representable in that type,
17679         //       in which case the type is an unspecified integral type
17680         //       sufficient to contain the incremented value. If no such type
17681         //       exists, the program is ill-formed.
17682         QualType T = getNextLargerIntegralType(Context, EltTy);
17683         if (T.isNull() || Enum->isFixed()) {
17684           // There is no integral type larger enough to represent this
17685           // value. Complain, then allow the value to wrap around.
17686           EnumVal = LastEnumConst->getInitVal();
17687           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
17688           ++EnumVal;
17689           if (Enum->isFixed())
17690             // When the underlying type is fixed, this is ill-formed.
17691             Diag(IdLoc, diag::err_enumerator_wrapped)
17692               << EnumVal.toString(10)
17693               << EltTy;
17694           else
17695             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
17696               << EnumVal.toString(10);
17697         } else {
17698           EltTy = T;
17699         }
17700 
17701         // Retrieve the last enumerator's value, extent that type to the
17702         // type that is supposed to be large enough to represent the incremented
17703         // value, then increment.
17704         EnumVal = LastEnumConst->getInitVal();
17705         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17706         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
17707         ++EnumVal;
17708 
17709         // If we're not in C++, diagnose the overflow of enumerator values,
17710         // which in C99 means that the enumerator value is not representable in
17711         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
17712         // permits enumerator values that are representable in some larger
17713         // integral type.
17714         if (!getLangOpts().CPlusPlus && !T.isNull())
17715           Diag(IdLoc, diag::warn_enum_value_overflow);
17716       } else if (!getLangOpts().CPlusPlus &&
17717                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17718         // Enforce C99 6.7.2.2p2 even when we compute the next value.
17719         Diag(IdLoc, diag::ext_enum_value_not_int)
17720           << EnumVal.toString(10) << 1;
17721       }
17722     }
17723   }
17724 
17725   if (!EltTy->isDependentType()) {
17726     // Make the enumerator value match the signedness and size of the
17727     // enumerator's type.
17728     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
17729     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17730   }
17731 
17732   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
17733                                   Val, EnumVal);
17734 }
17735 
17736 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
17737                                                 SourceLocation IILoc) {
17738   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
17739       !getLangOpts().CPlusPlus)
17740     return SkipBodyInfo();
17741 
17742   // We have an anonymous enum definition. Look up the first enumerator to
17743   // determine if we should merge the definition with an existing one and
17744   // skip the body.
17745   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
17746                                          forRedeclarationInCurContext());
17747   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
17748   if (!PrevECD)
17749     return SkipBodyInfo();
17750 
17751   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
17752   NamedDecl *Hidden;
17753   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
17754     SkipBodyInfo Skip;
17755     Skip.Previous = Hidden;
17756     return Skip;
17757   }
17758 
17759   return SkipBodyInfo();
17760 }
17761 
17762 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
17763                               SourceLocation IdLoc, IdentifierInfo *Id,
17764                               const ParsedAttributesView &Attrs,
17765                               SourceLocation EqualLoc, Expr *Val) {
17766   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
17767   EnumConstantDecl *LastEnumConst =
17768     cast_or_null<EnumConstantDecl>(lastEnumConst);
17769 
17770   // The scope passed in may not be a decl scope.  Zip up the scope tree until
17771   // we find one that is.
17772   S = getNonFieldDeclScope(S);
17773 
17774   // Verify that there isn't already something declared with this name in this
17775   // scope.
17776   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
17777   LookupName(R, S);
17778   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
17779 
17780   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17781     // Maybe we will complain about the shadowed template parameter.
17782     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
17783     // Just pretend that we didn't see the previous declaration.
17784     PrevDecl = nullptr;
17785   }
17786 
17787   // C++ [class.mem]p15:
17788   // If T is the name of a class, then each of the following shall have a name
17789   // different from T:
17790   // - every enumerator of every member of class T that is an unscoped
17791   // enumerated type
17792   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
17793     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
17794                             DeclarationNameInfo(Id, IdLoc));
17795 
17796   EnumConstantDecl *New =
17797     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
17798   if (!New)
17799     return nullptr;
17800 
17801   if (PrevDecl) {
17802     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
17803       // Check for other kinds of shadowing not already handled.
17804       CheckShadow(New, PrevDecl, R);
17805     }
17806 
17807     // When in C++, we may get a TagDecl with the same name; in this case the
17808     // enum constant will 'hide' the tag.
17809     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
17810            "Received TagDecl when not in C++!");
17811     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
17812       if (isa<EnumConstantDecl>(PrevDecl))
17813         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
17814       else
17815         Diag(IdLoc, diag::err_redefinition) << Id;
17816       notePreviousDefinition(PrevDecl, IdLoc);
17817       return nullptr;
17818     }
17819   }
17820 
17821   // Process attributes.
17822   ProcessDeclAttributeList(S, New, Attrs);
17823   AddPragmaAttributes(S, New);
17824 
17825   // Register this decl in the current scope stack.
17826   New->setAccess(TheEnumDecl->getAccess());
17827   PushOnScopeChains(New, S);
17828 
17829   ActOnDocumentableDecl(New);
17830 
17831   return New;
17832 }
17833 
17834 // Returns true when the enum initial expression does not trigger the
17835 // duplicate enum warning.  A few common cases are exempted as follows:
17836 // Element2 = Element1
17837 // Element2 = Element1 + 1
17838 // Element2 = Element1 - 1
17839 // Where Element2 and Element1 are from the same enum.
17840 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
17841   Expr *InitExpr = ECD->getInitExpr();
17842   if (!InitExpr)
17843     return true;
17844   InitExpr = InitExpr->IgnoreImpCasts();
17845 
17846   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
17847     if (!BO->isAdditiveOp())
17848       return true;
17849     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
17850     if (!IL)
17851       return true;
17852     if (IL->getValue() != 1)
17853       return true;
17854 
17855     InitExpr = BO->getLHS();
17856   }
17857 
17858   // This checks if the elements are from the same enum.
17859   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
17860   if (!DRE)
17861     return true;
17862 
17863   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
17864   if (!EnumConstant)
17865     return true;
17866 
17867   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
17868       Enum)
17869     return true;
17870 
17871   return false;
17872 }
17873 
17874 // Emits a warning when an element is implicitly set a value that
17875 // a previous element has already been set to.
17876 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
17877                                         EnumDecl *Enum, QualType EnumType) {
17878   // Avoid anonymous enums
17879   if (!Enum->getIdentifier())
17880     return;
17881 
17882   // Only check for small enums.
17883   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
17884     return;
17885 
17886   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
17887     return;
17888 
17889   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
17890   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
17891 
17892   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
17893 
17894   // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
17895   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
17896 
17897   // Use int64_t as a key to avoid needing special handling for map keys.
17898   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
17899     llvm::APSInt Val = D->getInitVal();
17900     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
17901   };
17902 
17903   DuplicatesVector DupVector;
17904   ValueToVectorMap EnumMap;
17905 
17906   // Populate the EnumMap with all values represented by enum constants without
17907   // an initializer.
17908   for (auto *Element : Elements) {
17909     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
17910 
17911     // Null EnumConstantDecl means a previous diagnostic has been emitted for
17912     // this constant.  Skip this enum since it may be ill-formed.
17913     if (!ECD) {
17914       return;
17915     }
17916 
17917     // Constants with initalizers are handled in the next loop.
17918     if (ECD->getInitExpr())
17919       continue;
17920 
17921     // Duplicate values are handled in the next loop.
17922     EnumMap.insert({EnumConstantToKey(ECD), ECD});
17923   }
17924 
17925   if (EnumMap.size() == 0)
17926     return;
17927 
17928   // Create vectors for any values that has duplicates.
17929   for (auto *Element : Elements) {
17930     // The last loop returned if any constant was null.
17931     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
17932     if (!ValidDuplicateEnum(ECD, Enum))
17933       continue;
17934 
17935     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
17936     if (Iter == EnumMap.end())
17937       continue;
17938 
17939     DeclOrVector& Entry = Iter->second;
17940     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
17941       // Ensure constants are different.
17942       if (D == ECD)
17943         continue;
17944 
17945       // Create new vector and push values onto it.
17946       auto Vec = std::make_unique<ECDVector>();
17947       Vec->push_back(D);
17948       Vec->push_back(ECD);
17949 
17950       // Update entry to point to the duplicates vector.
17951       Entry = Vec.get();
17952 
17953       // Store the vector somewhere we can consult later for quick emission of
17954       // diagnostics.
17955       DupVector.emplace_back(std::move(Vec));
17956       continue;
17957     }
17958 
17959     ECDVector *Vec = Entry.get<ECDVector*>();
17960     // Make sure constants are not added more than once.
17961     if (*Vec->begin() == ECD)
17962       continue;
17963 
17964     Vec->push_back(ECD);
17965   }
17966 
17967   // Emit diagnostics.
17968   for (const auto &Vec : DupVector) {
17969     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
17970 
17971     // Emit warning for one enum constant.
17972     auto *FirstECD = Vec->front();
17973     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
17974       << FirstECD << FirstECD->getInitVal().toString(10)
17975       << FirstECD->getSourceRange();
17976 
17977     // Emit one note for each of the remaining enum constants with
17978     // the same value.
17979     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
17980       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
17981         << ECD << ECD->getInitVal().toString(10)
17982         << ECD->getSourceRange();
17983   }
17984 }
17985 
17986 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
17987                              bool AllowMask) const {
17988   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
17989   assert(ED->isCompleteDefinition() && "expected enum definition");
17990 
17991   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
17992   llvm::APInt &FlagBits = R.first->second;
17993 
17994   if (R.second) {
17995     for (auto *E : ED->enumerators()) {
17996       const auto &EVal = E->getInitVal();
17997       // Only single-bit enumerators introduce new flag values.
17998       if (EVal.isPowerOf2())
17999         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
18000     }
18001   }
18002 
18003   // A value is in a flag enum if either its bits are a subset of the enum's
18004   // flag bits (the first condition) or we are allowing masks and the same is
18005   // true of its complement (the second condition). When masks are allowed, we
18006   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
18007   //
18008   // While it's true that any value could be used as a mask, the assumption is
18009   // that a mask will have all of the insignificant bits set. Anything else is
18010   // likely a logic error.
18011   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
18012   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
18013 }
18014 
18015 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
18016                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
18017                          const ParsedAttributesView &Attrs) {
18018   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
18019   QualType EnumType = Context.getTypeDeclType(Enum);
18020 
18021   ProcessDeclAttributeList(S, Enum, Attrs);
18022 
18023   if (Enum->isDependentType()) {
18024     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18025       EnumConstantDecl *ECD =
18026         cast_or_null<EnumConstantDecl>(Elements[i]);
18027       if (!ECD) continue;
18028 
18029       ECD->setType(EnumType);
18030     }
18031 
18032     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
18033     return;
18034   }
18035 
18036   // TODO: If the result value doesn't fit in an int, it must be a long or long
18037   // long value.  ISO C does not support this, but GCC does as an extension,
18038   // emit a warning.
18039   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18040   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
18041   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
18042 
18043   // Verify that all the values are okay, compute the size of the values, and
18044   // reverse the list.
18045   unsigned NumNegativeBits = 0;
18046   unsigned NumPositiveBits = 0;
18047 
18048   // Keep track of whether all elements have type int.
18049   bool AllElementsInt = true;
18050 
18051   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18052     EnumConstantDecl *ECD =
18053       cast_or_null<EnumConstantDecl>(Elements[i]);
18054     if (!ECD) continue;  // Already issued a diagnostic.
18055 
18056     const llvm::APSInt &InitVal = ECD->getInitVal();
18057 
18058     // Keep track of the size of positive and negative values.
18059     if (InitVal.isUnsigned() || InitVal.isNonNegative())
18060       NumPositiveBits = std::max(NumPositiveBits,
18061                                  (unsigned)InitVal.getActiveBits());
18062     else
18063       NumNegativeBits = std::max(NumNegativeBits,
18064                                  (unsigned)InitVal.getMinSignedBits());
18065 
18066     // Keep track of whether every enum element has type int (very common).
18067     if (AllElementsInt)
18068       AllElementsInt = ECD->getType() == Context.IntTy;
18069   }
18070 
18071   // Figure out the type that should be used for this enum.
18072   QualType BestType;
18073   unsigned BestWidth;
18074 
18075   // C++0x N3000 [conv.prom]p3:
18076   //   An rvalue of an unscoped enumeration type whose underlying
18077   //   type is not fixed can be converted to an rvalue of the first
18078   //   of the following types that can represent all the values of
18079   //   the enumeration: int, unsigned int, long int, unsigned long
18080   //   int, long long int, or unsigned long long int.
18081   // C99 6.4.4.3p2:
18082   //   An identifier declared as an enumeration constant has type int.
18083   // The C99 rule is modified by a gcc extension
18084   QualType BestPromotionType;
18085 
18086   bool Packed = Enum->hasAttr<PackedAttr>();
18087   // -fshort-enums is the equivalent to specifying the packed attribute on all
18088   // enum definitions.
18089   if (LangOpts.ShortEnums)
18090     Packed = true;
18091 
18092   // If the enum already has a type because it is fixed or dictated by the
18093   // target, promote that type instead of analyzing the enumerators.
18094   if (Enum->isComplete()) {
18095     BestType = Enum->getIntegerType();
18096     if (BestType->isPromotableIntegerType())
18097       BestPromotionType = Context.getPromotedIntegerType(BestType);
18098     else
18099       BestPromotionType = BestType;
18100 
18101     BestWidth = Context.getIntWidth(BestType);
18102   }
18103   else if (NumNegativeBits) {
18104     // If there is a negative value, figure out the smallest integer type (of
18105     // int/long/longlong) that fits.
18106     // If it's packed, check also if it fits a char or a short.
18107     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18108       BestType = Context.SignedCharTy;
18109       BestWidth = CharWidth;
18110     } else if (Packed && NumNegativeBits <= ShortWidth &&
18111                NumPositiveBits < ShortWidth) {
18112       BestType = Context.ShortTy;
18113       BestWidth = ShortWidth;
18114     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18115       BestType = Context.IntTy;
18116       BestWidth = IntWidth;
18117     } else {
18118       BestWidth = Context.getTargetInfo().getLongWidth();
18119 
18120       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18121         BestType = Context.LongTy;
18122       } else {
18123         BestWidth = Context.getTargetInfo().getLongLongWidth();
18124 
18125         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18126           Diag(Enum->getLocation(), diag::ext_enum_too_large);
18127         BestType = Context.LongLongTy;
18128       }
18129     }
18130     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18131   } else {
18132     // If there is no negative value, figure out the smallest type that fits
18133     // all of the enumerator values.
18134     // If it's packed, check also if it fits a char or a short.
18135     if (Packed && NumPositiveBits <= CharWidth) {
18136       BestType = Context.UnsignedCharTy;
18137       BestPromotionType = Context.IntTy;
18138       BestWidth = CharWidth;
18139     } else if (Packed && NumPositiveBits <= ShortWidth) {
18140       BestType = Context.UnsignedShortTy;
18141       BestPromotionType = Context.IntTy;
18142       BestWidth = ShortWidth;
18143     } else if (NumPositiveBits <= IntWidth) {
18144       BestType = Context.UnsignedIntTy;
18145       BestWidth = IntWidth;
18146       BestPromotionType
18147         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18148                            ? Context.UnsignedIntTy : Context.IntTy;
18149     } else if (NumPositiveBits <=
18150                (BestWidth = Context.getTargetInfo().getLongWidth())) {
18151       BestType = Context.UnsignedLongTy;
18152       BestPromotionType
18153         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18154                            ? Context.UnsignedLongTy : Context.LongTy;
18155     } else {
18156       BestWidth = Context.getTargetInfo().getLongLongWidth();
18157       assert(NumPositiveBits <= BestWidth &&
18158              "How could an initializer get larger than ULL?");
18159       BestType = Context.UnsignedLongLongTy;
18160       BestPromotionType
18161         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18162                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
18163     }
18164   }
18165 
18166   // Loop over all of the enumerator constants, changing their types to match
18167   // the type of the enum if needed.
18168   for (auto *D : Elements) {
18169     auto *ECD = cast_or_null<EnumConstantDecl>(D);
18170     if (!ECD) continue;  // Already issued a diagnostic.
18171 
18172     // Standard C says the enumerators have int type, but we allow, as an
18173     // extension, the enumerators to be larger than int size.  If each
18174     // enumerator value fits in an int, type it as an int, otherwise type it the
18175     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
18176     // that X has type 'int', not 'unsigned'.
18177 
18178     // Determine whether the value fits into an int.
18179     llvm::APSInt InitVal = ECD->getInitVal();
18180 
18181     // If it fits into an integer type, force it.  Otherwise force it to match
18182     // the enum decl type.
18183     QualType NewTy;
18184     unsigned NewWidth;
18185     bool NewSign;
18186     if (!getLangOpts().CPlusPlus &&
18187         !Enum->isFixed() &&
18188         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
18189       NewTy = Context.IntTy;
18190       NewWidth = IntWidth;
18191       NewSign = true;
18192     } else if (ECD->getType() == BestType) {
18193       // Already the right type!
18194       if (getLangOpts().CPlusPlus)
18195         // C++ [dcl.enum]p4: Following the closing brace of an
18196         // enum-specifier, each enumerator has the type of its
18197         // enumeration.
18198         ECD->setType(EnumType);
18199       continue;
18200     } else {
18201       NewTy = BestType;
18202       NewWidth = BestWidth;
18203       NewSign = BestType->isSignedIntegerOrEnumerationType();
18204     }
18205 
18206     // Adjust the APSInt value.
18207     InitVal = InitVal.extOrTrunc(NewWidth);
18208     InitVal.setIsSigned(NewSign);
18209     ECD->setInitVal(InitVal);
18210 
18211     // Adjust the Expr initializer and type.
18212     if (ECD->getInitExpr() &&
18213         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
18214       ECD->setInitExpr(ImplicitCastExpr::Create(
18215           Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
18216           /*base paths*/ nullptr, VK_RValue, FPOptionsOverride()));
18217     if (getLangOpts().CPlusPlus)
18218       // C++ [dcl.enum]p4: Following the closing brace of an
18219       // enum-specifier, each enumerator has the type of its
18220       // enumeration.
18221       ECD->setType(EnumType);
18222     else
18223       ECD->setType(NewTy);
18224   }
18225 
18226   Enum->completeDefinition(BestType, BestPromotionType,
18227                            NumPositiveBits, NumNegativeBits);
18228 
18229   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
18230 
18231   if (Enum->isClosedFlag()) {
18232     for (Decl *D : Elements) {
18233       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
18234       if (!ECD) continue;  // Already issued a diagnostic.
18235 
18236       llvm::APSInt InitVal = ECD->getInitVal();
18237       if (InitVal != 0 && !InitVal.isPowerOf2() &&
18238           !IsValueInFlagEnum(Enum, InitVal, true))
18239         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
18240           << ECD << Enum;
18241     }
18242   }
18243 
18244   // Now that the enum type is defined, ensure it's not been underaligned.
18245   if (Enum->hasAttrs())
18246     CheckAlignasUnderalignment(Enum);
18247 }
18248 
18249 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
18250                                   SourceLocation StartLoc,
18251                                   SourceLocation EndLoc) {
18252   StringLiteral *AsmString = cast<StringLiteral>(expr);
18253 
18254   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
18255                                                    AsmString, StartLoc,
18256                                                    EndLoc);
18257   CurContext->addDecl(New);
18258   return New;
18259 }
18260 
18261 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
18262                                       IdentifierInfo* AliasName,
18263                                       SourceLocation PragmaLoc,
18264                                       SourceLocation NameLoc,
18265                                       SourceLocation AliasNameLoc) {
18266   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
18267                                          LookupOrdinaryName);
18268   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
18269                            AttributeCommonInfo::AS_Pragma);
18270   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
18271       Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
18272 
18273   // If a declaration that:
18274   // 1) declares a function or a variable
18275   // 2) has external linkage
18276   // already exists, add a label attribute to it.
18277   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18278     if (isDeclExternC(PrevDecl))
18279       PrevDecl->addAttr(Attr);
18280     else
18281       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
18282           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
18283   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
18284   } else
18285     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
18286 }
18287 
18288 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
18289                              SourceLocation PragmaLoc,
18290                              SourceLocation NameLoc) {
18291   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
18292 
18293   if (PrevDecl) {
18294     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
18295   } else {
18296     (void)WeakUndeclaredIdentifiers.insert(
18297       std::pair<IdentifierInfo*,WeakInfo>
18298         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
18299   }
18300 }
18301 
18302 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
18303                                 IdentifierInfo* AliasName,
18304                                 SourceLocation PragmaLoc,
18305                                 SourceLocation NameLoc,
18306                                 SourceLocation AliasNameLoc) {
18307   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
18308                                     LookupOrdinaryName);
18309   WeakInfo W = WeakInfo(Name, NameLoc);
18310 
18311   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18312     if (!PrevDecl->hasAttr<AliasAttr>())
18313       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
18314         DeclApplyPragmaWeak(TUScope, ND, W);
18315   } else {
18316     (void)WeakUndeclaredIdentifiers.insert(
18317       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
18318   }
18319 }
18320 
18321 Decl *Sema::getObjCDeclContext() const {
18322   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
18323 }
18324 
18325 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
18326                                                      bool Final) {
18327   // SYCL functions can be template, so we check if they have appropriate
18328   // attribute prior to checking if it is a template.
18329   if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
18330     return FunctionEmissionStatus::Emitted;
18331 
18332   // Templates are emitted when they're instantiated.
18333   if (FD->isDependentContext())
18334     return FunctionEmissionStatus::TemplateDiscarded;
18335 
18336   // Check whether this function is an externally visible definition.
18337   auto IsEmittedForExternalSymbol = [this, FD]() {
18338     // We have to check the GVA linkage of the function's *definition* -- if we
18339     // only have a declaration, we don't know whether or not the function will
18340     // be emitted, because (say) the definition could include "inline".
18341     FunctionDecl *Def = FD->getDefinition();
18342 
18343     return Def && !isDiscardableGVALinkage(
18344                       getASTContext().GetGVALinkageForFunction(Def));
18345   };
18346 
18347   if (LangOpts.OpenMPIsDevice) {
18348     // In OpenMP device mode we will not emit host only functions, or functions
18349     // we don't need due to their linkage.
18350     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18351         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18352     // DevTy may be changed later by
18353     //  #pragma omp declare target to(*) device_type(*).
18354     // Therefore DevTyhaving no value does not imply host. The emission status
18355     // will be checked again at the end of compilation unit with Final = true.
18356     if (DevTy.hasValue())
18357       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
18358         return FunctionEmissionStatus::OMPDiscarded;
18359     // If we have an explicit value for the device type, or we are in a target
18360     // declare context, we need to emit all extern and used symbols.
18361     if (isInOpenMPDeclareTargetContext() || DevTy.hasValue())
18362       if (IsEmittedForExternalSymbol())
18363         return FunctionEmissionStatus::Emitted;
18364     // Device mode only emits what it must, if it wasn't tagged yet and needed,
18365     // we'll omit it.
18366     if (Final)
18367       return FunctionEmissionStatus::OMPDiscarded;
18368   } else if (LangOpts.OpenMP > 45) {
18369     // In OpenMP host compilation prior to 5.0 everything was an emitted host
18370     // function. In 5.0, no_host was introduced which might cause a function to
18371     // be ommitted.
18372     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18373         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18374     if (DevTy.hasValue())
18375       if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
18376         return FunctionEmissionStatus::OMPDiscarded;
18377   }
18378 
18379   if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
18380     return FunctionEmissionStatus::Emitted;
18381 
18382   if (LangOpts.CUDA) {
18383     // When compiling for device, host functions are never emitted.  Similarly,
18384     // when compiling for host, device and global functions are never emitted.
18385     // (Technically, we do emit a host-side stub for global functions, but this
18386     // doesn't count for our purposes here.)
18387     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
18388     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
18389       return FunctionEmissionStatus::CUDADiscarded;
18390     if (!LangOpts.CUDAIsDevice &&
18391         (T == Sema::CFT_Device || T == Sema::CFT_Global))
18392       return FunctionEmissionStatus::CUDADiscarded;
18393 
18394     if (IsEmittedForExternalSymbol())
18395       return FunctionEmissionStatus::Emitted;
18396   }
18397 
18398   // Otherwise, the function is known-emitted if it's in our set of
18399   // known-emitted functions.
18400   return FunctionEmissionStatus::Unknown;
18401 }
18402 
18403 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
18404   // Host-side references to a __global__ function refer to the stub, so the
18405   // function itself is never emitted and therefore should not be marked.
18406   // If we have host fn calls kernel fn calls host+device, the HD function
18407   // does not get instantiated on the host. We model this by omitting at the
18408   // call to the kernel from the callgraph. This ensures that, when compiling
18409   // for host, only HD functions actually called from the host get marked as
18410   // known-emitted.
18411   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
18412          IdentifyCUDATarget(Callee) == CFT_Global;
18413 }
18414