xref: /freebsd/contrib/llvm-project/clang/lib/Sema/SemaDecl.cpp (revision 6e516c87b6d779911edde7481d8aef165b837a03)
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/Decl.h"
21  #include "clang/AST/DeclCXX.h"
22  #include "clang/AST/DeclObjC.h"
23  #include "clang/AST/DeclTemplate.h"
24  #include "clang/AST/EvaluatedExprVisitor.h"
25  #include "clang/AST/Expr.h"
26  #include "clang/AST/ExprCXX.h"
27  #include "clang/AST/NonTrivialTypeVisitor.h"
28  #include "clang/AST/Randstruct.h"
29  #include "clang/AST/StmtCXX.h"
30  #include "clang/AST/Type.h"
31  #include "clang/Basic/Builtins.h"
32  #include "clang/Basic/HLSLRuntime.h"
33  #include "clang/Basic/PartialDiagnostic.h"
34  #include "clang/Basic/SourceManager.h"
35  #include "clang/Basic/TargetInfo.h"
36  #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
37  #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
38  #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
39  #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
40  #include "clang/Sema/CXXFieldCollector.h"
41  #include "clang/Sema/DeclSpec.h"
42  #include "clang/Sema/DelayedDiagnostic.h"
43  #include "clang/Sema/Initialization.h"
44  #include "clang/Sema/Lookup.h"
45  #include "clang/Sema/ParsedTemplate.h"
46  #include "clang/Sema/Scope.h"
47  #include "clang/Sema/ScopeInfo.h"
48  #include "clang/Sema/SemaCUDA.h"
49  #include "clang/Sema/SemaHLSL.h"
50  #include "clang/Sema/SemaInternal.h"
51  #include "clang/Sema/SemaObjC.h"
52  #include "clang/Sema/SemaOpenMP.h"
53  #include "clang/Sema/SemaPPC.h"
54  #include "clang/Sema/SemaRISCV.h"
55  #include "clang/Sema/SemaSwift.h"
56  #include "clang/Sema/SemaWasm.h"
57  #include "clang/Sema/Template.h"
58  #include "llvm/ADT/STLForwardCompat.h"
59  #include "llvm/ADT/SmallString.h"
60  #include "llvm/ADT/StringExtras.h"
61  #include "llvm/TargetParser/Triple.h"
62  #include <algorithm>
63  #include <cstring>
64  #include <functional>
65  #include <optional>
66  #include <unordered_map>
67  
68  using namespace clang;
69  using namespace sema;
70  
ConvertDeclToDeclGroup(Decl * Ptr,Decl * OwnedType)71  Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
72    if (OwnedType) {
73      Decl *Group[2] = { OwnedType, Ptr };
74      return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
75    }
76  
77    return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
78  }
79  
80  namespace {
81  
82  class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
83   public:
TypeNameValidatorCCC(bool AllowInvalid,bool WantClass=false,bool AllowTemplates=false,bool AllowNonTemplates=true)84     TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
85                          bool AllowTemplates = false,
86                          bool AllowNonTemplates = true)
87         : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
88           AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
89       WantExpressionKeywords = false;
90       WantCXXNamedCasts = false;
91       WantRemainingKeywords = false;
92    }
93  
ValidateCandidate(const TypoCorrection & candidate)94    bool ValidateCandidate(const TypoCorrection &candidate) override {
95      if (NamedDecl *ND = candidate.getCorrectionDecl()) {
96        if (!AllowInvalidDecl && ND->isInvalidDecl())
97          return false;
98  
99        if (getAsTypeTemplateDecl(ND))
100          return AllowTemplates;
101  
102        bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
103        if (!IsType)
104          return false;
105  
106        if (AllowNonTemplates)
107          return true;
108  
109        // An injected-class-name of a class template (specialization) is valid
110        // as a template or as a non-template.
111        if (AllowTemplates) {
112          auto *RD = dyn_cast<CXXRecordDecl>(ND);
113          if (!RD || !RD->isInjectedClassName())
114            return false;
115          RD = cast<CXXRecordDecl>(RD->getDeclContext());
116          return RD->getDescribedClassTemplate() ||
117                 isa<ClassTemplateSpecializationDecl>(RD);
118        }
119  
120        return false;
121      }
122  
123      return !WantClassName && candidate.isKeyword();
124    }
125  
clone()126    std::unique_ptr<CorrectionCandidateCallback> clone() override {
127      return std::make_unique<TypeNameValidatorCCC>(*this);
128    }
129  
130   private:
131    bool AllowInvalidDecl;
132    bool WantClassName;
133    bool AllowTemplates;
134    bool AllowNonTemplates;
135  };
136  
137  } // end anonymous namespace
138  
139  namespace {
140  enum class UnqualifiedTypeNameLookupResult {
141    NotFound,
142    FoundNonType,
143    FoundType
144  };
145  } // end anonymous namespace
146  
147  /// Tries to perform unqualified lookup of the type decls in bases for
148  /// dependent class.
149  /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
150  /// type decl, \a FoundType if only type decls are found.
151  static UnqualifiedTypeNameLookupResult
lookupUnqualifiedTypeNameInBase(Sema & S,const IdentifierInfo & II,SourceLocation NameLoc,const CXXRecordDecl * RD)152  lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
153                                  SourceLocation NameLoc,
154                                  const CXXRecordDecl *RD) {
155    if (!RD->hasDefinition())
156      return UnqualifiedTypeNameLookupResult::NotFound;
157    // Look for type decls in base classes.
158    UnqualifiedTypeNameLookupResult FoundTypeDecl =
159        UnqualifiedTypeNameLookupResult::NotFound;
160    for (const auto &Base : RD->bases()) {
161      const CXXRecordDecl *BaseRD = nullptr;
162      if (auto *BaseTT = Base.getType()->getAs<TagType>())
163        BaseRD = BaseTT->getAsCXXRecordDecl();
164      else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
165        // Look for type decls in dependent base classes that have known primary
166        // templates.
167        if (!TST || !TST->isDependentType())
168          continue;
169        auto *TD = TST->getTemplateName().getAsTemplateDecl();
170        if (!TD)
171          continue;
172        if (auto *BasePrimaryTemplate =
173            dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
174          if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
175            BaseRD = BasePrimaryTemplate;
176          else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
177            if (const ClassTemplatePartialSpecializationDecl *PS =
178                    CTD->findPartialSpecialization(Base.getType()))
179              if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
180                BaseRD = PS;
181          }
182        }
183      }
184      if (BaseRD) {
185        for (NamedDecl *ND : BaseRD->lookup(&II)) {
186          if (!isa<TypeDecl>(ND))
187            return UnqualifiedTypeNameLookupResult::FoundNonType;
188          FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
189        }
190        if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
191          switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
192          case UnqualifiedTypeNameLookupResult::FoundNonType:
193            return UnqualifiedTypeNameLookupResult::FoundNonType;
194          case UnqualifiedTypeNameLookupResult::FoundType:
195            FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
196            break;
197          case UnqualifiedTypeNameLookupResult::NotFound:
198            break;
199          }
200        }
201      }
202    }
203  
204    return FoundTypeDecl;
205  }
206  
recoverFromTypeInKnownDependentBase(Sema & S,const IdentifierInfo & II,SourceLocation NameLoc)207  static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
208                                                        const IdentifierInfo &II,
209                                                        SourceLocation NameLoc) {
210    // Lookup in the parent class template context, if any.
211    const CXXRecordDecl *RD = nullptr;
212    UnqualifiedTypeNameLookupResult FoundTypeDecl =
213        UnqualifiedTypeNameLookupResult::NotFound;
214    for (DeclContext *DC = S.CurContext;
215         DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
216         DC = DC->getParent()) {
217      // Look for type decls in dependent base classes that have known primary
218      // templates.
219      RD = dyn_cast<CXXRecordDecl>(DC);
220      if (RD && RD->getDescribedClassTemplate())
221        FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
222    }
223    if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
224      return nullptr;
225  
226    // We found some types in dependent base classes.  Recover as if the user
227    // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
228    // lookup during template instantiation.
229    S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
230  
231    ASTContext &Context = S.Context;
232    auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
233                                            cast<Type>(Context.getRecordType(RD)));
234    QualType T =
235        Context.getDependentNameType(ElaboratedTypeKeyword::Typename, NNS, &II);
236  
237    CXXScopeSpec SS;
238    SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
239  
240    TypeLocBuilder Builder;
241    DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
242    DepTL.setNameLoc(NameLoc);
243    DepTL.setElaboratedKeywordLoc(SourceLocation());
244    DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
245    return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
246  }
247  
248  /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
buildNamedType(Sema & S,const CXXScopeSpec * SS,QualType T,SourceLocation NameLoc,bool WantNontrivialTypeSourceInfo=true)249  static ParsedType buildNamedType(Sema &S, const CXXScopeSpec *SS, QualType T,
250                                   SourceLocation NameLoc,
251                                   bool WantNontrivialTypeSourceInfo = true) {
252    switch (T->getTypeClass()) {
253    case Type::DeducedTemplateSpecialization:
254    case Type::Enum:
255    case Type::InjectedClassName:
256    case Type::Record:
257    case Type::Typedef:
258    case Type::UnresolvedUsing:
259    case Type::Using:
260      break;
261    // These can never be qualified so an ElaboratedType node
262    // would carry no additional meaning.
263    case Type::ObjCInterface:
264    case Type::ObjCTypeParam:
265    case Type::TemplateTypeParm:
266      return ParsedType::make(T);
267    default:
268      llvm_unreachable("Unexpected Type Class");
269    }
270  
271    if (!SS || SS->isEmpty())
272      return ParsedType::make(S.Context.getElaboratedType(
273          ElaboratedTypeKeyword::None, nullptr, T, nullptr));
274  
275    QualType ElTy = S.getElaboratedType(ElaboratedTypeKeyword::None, *SS, T);
276    if (!WantNontrivialTypeSourceInfo)
277      return ParsedType::make(ElTy);
278  
279    TypeLocBuilder Builder;
280    Builder.pushTypeSpec(T).setNameLoc(NameLoc);
281    ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(ElTy);
282    ElabTL.setElaboratedKeywordLoc(SourceLocation());
283    ElabTL.setQualifierLoc(SS->getWithLocInContext(S.Context));
284    return S.CreateParsedType(ElTy, Builder.getTypeSourceInfo(S.Context, ElTy));
285  }
286  
getTypeName(const IdentifierInfo & II,SourceLocation NameLoc,Scope * S,CXXScopeSpec * SS,bool isClassName,bool HasTrailingDot,ParsedType ObjectTypePtr,bool IsCtorOrDtorName,bool WantNontrivialTypeSourceInfo,bool IsClassTemplateDeductionContext,ImplicitTypenameContext AllowImplicitTypename,IdentifierInfo ** CorrectedII)287  ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
288                               Scope *S, CXXScopeSpec *SS, bool isClassName,
289                               bool HasTrailingDot, ParsedType ObjectTypePtr,
290                               bool IsCtorOrDtorName,
291                               bool WantNontrivialTypeSourceInfo,
292                               bool IsClassTemplateDeductionContext,
293                               ImplicitTypenameContext AllowImplicitTypename,
294                               IdentifierInfo **CorrectedII) {
295    // FIXME: Consider allowing this outside C++1z mode as an extension.
296    bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
297                                getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
298                                !isClassName && !HasTrailingDot;
299  
300    // Determine where we will perform name lookup.
301    DeclContext *LookupCtx = nullptr;
302    if (ObjectTypePtr) {
303      QualType ObjectType = ObjectTypePtr.get();
304      if (ObjectType->isRecordType())
305        LookupCtx = computeDeclContext(ObjectType);
306    } else if (SS && SS->isNotEmpty()) {
307      LookupCtx = computeDeclContext(*SS, false);
308  
309      if (!LookupCtx) {
310        if (isDependentScopeSpecifier(*SS)) {
311          // C++ [temp.res]p3:
312          //   A qualified-id that refers to a type and in which the
313          //   nested-name-specifier depends on a template-parameter (14.6.2)
314          //   shall be prefixed by the keyword typename to indicate that the
315          //   qualified-id denotes a type, forming an
316          //   elaborated-type-specifier (7.1.5.3).
317          //
318          // We therefore do not perform any name lookup if the result would
319          // refer to a member of an unknown specialization.
320          // In C++2a, in several contexts a 'typename' is not required. Also
321          // allow this as an extension.
322          if (AllowImplicitTypename == ImplicitTypenameContext::No &&
323              !isClassName && !IsCtorOrDtorName)
324            return nullptr;
325          bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
326          if (IsImplicitTypename) {
327            SourceLocation QualifiedLoc = SS->getRange().getBegin();
328            if (getLangOpts().CPlusPlus20)
329              Diag(QualifiedLoc, diag::warn_cxx17_compat_implicit_typename);
330            else
331              Diag(QualifiedLoc, diag::ext_implicit_typename)
332                  << SS->getScopeRep() << II.getName()
333                  << FixItHint::CreateInsertion(QualifiedLoc, "typename ");
334          }
335  
336          // We know from the grammar that this name refers to a type,
337          // so build a dependent node to describe the type.
338          if (WantNontrivialTypeSourceInfo)
339            return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc,
340                                     (ImplicitTypenameContext)IsImplicitTypename)
341                .get();
342  
343          NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
344          QualType T = CheckTypenameType(
345              IsImplicitTypename ? ElaboratedTypeKeyword::Typename
346                                 : ElaboratedTypeKeyword::None,
347              SourceLocation(), QualifierLoc, II, NameLoc);
348          return ParsedType::make(T);
349        }
350  
351        return nullptr;
352      }
353  
354      if (!LookupCtx->isDependentContext() &&
355          RequireCompleteDeclContext(*SS, LookupCtx))
356        return nullptr;
357    }
358  
359    // FIXME: LookupNestedNameSpecifierName isn't the right kind of
360    // lookup for class-names.
361    LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
362                                        LookupOrdinaryName;
363    LookupResult Result(*this, &II, NameLoc, Kind);
364    if (LookupCtx) {
365      // Perform "qualified" name lookup into the declaration context we
366      // computed, which is either the type of the base of a member access
367      // expression or the declaration context associated with a prior
368      // nested-name-specifier.
369      LookupQualifiedName(Result, LookupCtx);
370  
371      if (ObjectTypePtr && Result.empty()) {
372        // C++ [basic.lookup.classref]p3:
373        //   If the unqualified-id is ~type-name, the type-name is looked up
374        //   in the context of the entire postfix-expression. If the type T of
375        //   the object expression is of a class type C, the type-name is also
376        //   looked up in the scope of class C. At least one of the lookups shall
377        //   find a name that refers to (possibly cv-qualified) T.
378        LookupName(Result, S);
379      }
380    } else {
381      // Perform unqualified name lookup.
382      LookupName(Result, S);
383  
384      // For unqualified lookup in a class template in MSVC mode, look into
385      // dependent base classes where the primary class template is known.
386      if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
387        if (ParsedType TypeInBase =
388                recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
389          return TypeInBase;
390      }
391    }
392  
393    NamedDecl *IIDecl = nullptr;
394    UsingShadowDecl *FoundUsingShadow = nullptr;
395    switch (Result.getResultKind()) {
396    case LookupResult::NotFound:
397      if (CorrectedII) {
398        TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
399                                 AllowDeducedTemplate);
400        TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
401                                                S, SS, CCC, CTK_ErrorRecovery);
402        IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
403        TemplateTy Template;
404        bool MemberOfUnknownSpecialization;
405        UnqualifiedId TemplateName;
406        TemplateName.setIdentifier(NewII, NameLoc);
407        NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
408        CXXScopeSpec NewSS, *NewSSPtr = SS;
409        if (SS && NNS) {
410          NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
411          NewSSPtr = &NewSS;
412        }
413        if (Correction && (NNS || NewII != &II) &&
414            // Ignore a correction to a template type as the to-be-corrected
415            // identifier is not a template (typo correction for template names
416            // is handled elsewhere).
417            !(getLangOpts().CPlusPlus && NewSSPtr &&
418              isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
419                             Template, MemberOfUnknownSpecialization))) {
420          ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
421                                      isClassName, HasTrailingDot, ObjectTypePtr,
422                                      IsCtorOrDtorName,
423                                      WantNontrivialTypeSourceInfo,
424                                      IsClassTemplateDeductionContext);
425          if (Ty) {
426            diagnoseTypo(Correction,
427                         PDiag(diag::err_unknown_type_or_class_name_suggest)
428                           << Result.getLookupName() << isClassName);
429            if (SS && NNS)
430              SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
431            *CorrectedII = NewII;
432            return Ty;
433          }
434        }
435      }
436      Result.suppressDiagnostics();
437      return nullptr;
438    case LookupResult::NotFoundInCurrentInstantiation:
439      if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
440        QualType T = Context.getDependentNameType(ElaboratedTypeKeyword::None,
441                                                  SS->getScopeRep(), &II);
442        TypeLocBuilder TLB;
443        DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T);
444        TL.setElaboratedKeywordLoc(SourceLocation());
445        TL.setQualifierLoc(SS->getWithLocInContext(Context));
446        TL.setNameLoc(NameLoc);
447        return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
448      }
449      [[fallthrough]];
450    case LookupResult::FoundOverloaded:
451    case LookupResult::FoundUnresolvedValue:
452      Result.suppressDiagnostics();
453      return nullptr;
454  
455    case LookupResult::Ambiguous:
456      // Recover from type-hiding ambiguities by hiding the type.  We'll
457      // do the lookup again when looking for an object, and we can
458      // diagnose the error then.  If we don't do this, then the error
459      // about hiding the type will be immediately followed by an error
460      // that only makes sense if the identifier was treated like a type.
461      if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
462        Result.suppressDiagnostics();
463        return nullptr;
464      }
465  
466      // Look to see if we have a type anywhere in the list of results.
467      for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
468           Res != ResEnd; ++Res) {
469        NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
470        if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
471                RealRes) ||
472            (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
473          if (!IIDecl ||
474              // Make the selection of the recovery decl deterministic.
475              RealRes->getLocation() < IIDecl->getLocation()) {
476            IIDecl = RealRes;
477            FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
478          }
479        }
480      }
481  
482      if (!IIDecl) {
483        // None of the entities we found is a type, so there is no way
484        // to even assume that the result is a type. In this case, don't
485        // complain about the ambiguity. The parser will either try to
486        // perform this lookup again (e.g., as an object name), which
487        // will produce the ambiguity, or will complain that it expected
488        // a type name.
489        Result.suppressDiagnostics();
490        return nullptr;
491      }
492  
493      // We found a type within the ambiguous lookup; diagnose the
494      // ambiguity and then return that type. This might be the right
495      // answer, or it might not be, but it suppresses any attempt to
496      // perform the name lookup again.
497      break;
498  
499    case LookupResult::Found:
500      IIDecl = Result.getFoundDecl();
501      FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
502      break;
503    }
504  
505    assert(IIDecl && "Didn't find decl");
506  
507    QualType T;
508    if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
509      // C++ [class.qual]p2: A lookup that would find the injected-class-name
510      // instead names the constructors of the class, except when naming a class.
511      // This is ill-formed when we're not actually forming a ctor or dtor name.
512      auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
513      auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
514      if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
515          FoundRD->isInjectedClassName() &&
516          declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
517        Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
518            << &II << /*Type*/1;
519  
520      DiagnoseUseOfDecl(IIDecl, NameLoc);
521  
522      T = Context.getTypeDeclType(TD);
523      MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
524    } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
525      (void)DiagnoseUseOfDecl(IDecl, NameLoc);
526      if (!HasTrailingDot)
527        T = Context.getObjCInterfaceType(IDecl);
528      FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
529    } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
530      (void)DiagnoseUseOfDecl(UD, NameLoc);
531      // Recover with 'int'
532      return ParsedType::make(Context.IntTy);
533    } else if (AllowDeducedTemplate) {
534      if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
535        assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
536        TemplateName Template = Context.getQualifiedTemplateName(
537            SS ? SS->getScopeRep() : nullptr, /*TemplateKeyword=*/false,
538            FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
539        T = Context.getDeducedTemplateSpecializationType(Template, QualType(),
540                                                         false);
541        // Don't wrap in a further UsingType.
542        FoundUsingShadow = nullptr;
543      }
544    }
545  
546    if (T.isNull()) {
547      // If it's not plausibly a type, suppress diagnostics.
548      Result.suppressDiagnostics();
549      return nullptr;
550    }
551  
552    if (FoundUsingShadow)
553      T = Context.getUsingType(FoundUsingShadow, T);
554  
555    return buildNamedType(*this, SS, T, NameLoc, WantNontrivialTypeSourceInfo);
556  }
557  
558  // Builds a fake NNS for the given decl context.
559  static NestedNameSpecifier *
synthesizeCurrentNestedNameSpecifier(ASTContext & Context,DeclContext * DC)560  synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
561    for (;; DC = DC->getLookupParent()) {
562      DC = DC->getPrimaryContext();
563      auto *ND = dyn_cast<NamespaceDecl>(DC);
564      if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
565        return NestedNameSpecifier::Create(Context, nullptr, ND);
566      else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
567        return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
568                                           RD->getTypeForDecl());
569      else if (isa<TranslationUnitDecl>(DC))
570        return NestedNameSpecifier::GlobalSpecifier(Context);
571    }
572    llvm_unreachable("something isn't in TU scope?");
573  }
574  
575  /// Find the parent class with dependent bases of the innermost enclosing method
576  /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
577  /// up allowing unqualified dependent type names at class-level, which MSVC
578  /// correctly rejects.
579  static const CXXRecordDecl *
findRecordWithDependentBasesOfEnclosingMethod(const DeclContext * DC)580  findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
581    for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
582      DC = DC->getPrimaryContext();
583      if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
584        if (MD->getParent()->hasAnyDependentBases())
585          return MD->getParent();
586    }
587    return nullptr;
588  }
589  
ActOnMSVCUnknownTypeName(const IdentifierInfo & II,SourceLocation NameLoc,bool IsTemplateTypeArg)590  ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
591                                            SourceLocation NameLoc,
592                                            bool IsTemplateTypeArg) {
593    assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
594  
595    NestedNameSpecifier *NNS = nullptr;
596    if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
597      // If we weren't able to parse a default template argument, delay lookup
598      // until instantiation time by making a non-dependent DependentTypeName. We
599      // pretend we saw a NestedNameSpecifier referring to the current scope, and
600      // lookup is retried.
601      // FIXME: This hurts our diagnostic quality, since we get errors like "no
602      // type named 'Foo' in 'current_namespace'" when the user didn't write any
603      // name specifiers.
604      NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
605      Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
606    } else if (const CXXRecordDecl *RD =
607                   findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
608      // Build a DependentNameType that will perform lookup into RD at
609      // instantiation time.
610      NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
611                                        RD->getTypeForDecl());
612  
613      // Diagnose that this identifier was undeclared, and retry the lookup during
614      // template instantiation.
615      Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
616                                                                        << RD;
617    } else {
618      // This is not a situation that we should recover from.
619      return ParsedType();
620    }
621  
622    QualType T =
623        Context.getDependentNameType(ElaboratedTypeKeyword::None, NNS, &II);
624  
625    // Build type location information.  We synthesized the qualifier, so we have
626    // to build a fake NestedNameSpecifierLoc.
627    NestedNameSpecifierLocBuilder NNSLocBuilder;
628    NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
629    NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
630  
631    TypeLocBuilder Builder;
632    DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
633    DepTL.setNameLoc(NameLoc);
634    DepTL.setElaboratedKeywordLoc(SourceLocation());
635    DepTL.setQualifierLoc(QualifierLoc);
636    return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
637  }
638  
isTagName(IdentifierInfo & II,Scope * S)639  DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
640    // Do a tag name lookup in this scope.
641    LookupResult R(*this, &II, SourceLocation(), LookupTagName);
642    LookupName(R, S, false);
643    R.suppressDiagnostics();
644    if (R.getResultKind() == LookupResult::Found)
645      if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
646        switch (TD->getTagKind()) {
647        case TagTypeKind::Struct:
648          return DeclSpec::TST_struct;
649        case TagTypeKind::Interface:
650          return DeclSpec::TST_interface;
651        case TagTypeKind::Union:
652          return DeclSpec::TST_union;
653        case TagTypeKind::Class:
654          return DeclSpec::TST_class;
655        case TagTypeKind::Enum:
656          return DeclSpec::TST_enum;
657        }
658      }
659  
660    return DeclSpec::TST_unspecified;
661  }
662  
isMicrosoftMissingTypename(const CXXScopeSpec * SS,Scope * S)663  bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
664    if (CurContext->isRecord()) {
665      if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
666        return true;
667  
668      const Type *Ty = SS->getScopeRep()->getAsType();
669  
670      CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
671      for (const auto &Base : RD->bases())
672        if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
673          return true;
674      return S->isFunctionPrototypeScope();
675    }
676    return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
677  }
678  
DiagnoseUnknownTypeName(IdentifierInfo * & II,SourceLocation IILoc,Scope * S,CXXScopeSpec * SS,ParsedType & SuggestedType,bool IsTemplateName)679  void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
680                                     SourceLocation IILoc,
681                                     Scope *S,
682                                     CXXScopeSpec *SS,
683                                     ParsedType &SuggestedType,
684                                     bool IsTemplateName) {
685    // Don't report typename errors for editor placeholders.
686    if (II->isEditorPlaceholder())
687      return;
688    // We don't have anything to suggest (yet).
689    SuggestedType = nullptr;
690  
691    // There may have been a typo in the name of the type. Look up typo
692    // results, in case we have something that we can suggest.
693    TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
694                             /*AllowTemplates=*/IsTemplateName,
695                             /*AllowNonTemplates=*/!IsTemplateName);
696    if (TypoCorrection Corrected =
697            CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
698                        CCC, CTK_ErrorRecovery)) {
699      // FIXME: Support error recovery for the template-name case.
700      bool CanRecover = !IsTemplateName;
701      if (Corrected.isKeyword()) {
702        // We corrected to a keyword.
703        diagnoseTypo(Corrected,
704                     PDiag(IsTemplateName ? diag::err_no_template_suggest
705                                          : diag::err_unknown_typename_suggest)
706                         << II);
707        II = Corrected.getCorrectionAsIdentifierInfo();
708      } else {
709        // We found a similarly-named type or interface; suggest that.
710        if (!SS || !SS->isSet()) {
711          diagnoseTypo(Corrected,
712                       PDiag(IsTemplateName ? diag::err_no_template_suggest
713                                            : diag::err_unknown_typename_suggest)
714                           << II, CanRecover);
715        } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
716          std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
717          bool DroppedSpecifier =
718              Corrected.WillReplaceSpecifier() && II->getName() == CorrectedStr;
719          diagnoseTypo(Corrected,
720                       PDiag(IsTemplateName
721                                 ? diag::err_no_member_template_suggest
722                                 : diag::err_unknown_nested_typename_suggest)
723                           << II << DC << DroppedSpecifier << SS->getRange(),
724                       CanRecover);
725        } else {
726          llvm_unreachable("could not have corrected a typo here");
727        }
728  
729        if (!CanRecover)
730          return;
731  
732        CXXScopeSpec tmpSS;
733        if (Corrected.getCorrectionSpecifier())
734          tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
735                            SourceRange(IILoc));
736        // FIXME: Support class template argument deduction here.
737        SuggestedType =
738            getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
739                        tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
740                        /*IsCtorOrDtorName=*/false,
741                        /*WantNontrivialTypeSourceInfo=*/true);
742      }
743      return;
744    }
745  
746    if (getLangOpts().CPlusPlus && !IsTemplateName) {
747      // See if II is a class template that the user forgot to pass arguments to.
748      UnqualifiedId Name;
749      Name.setIdentifier(II, IILoc);
750      CXXScopeSpec EmptySS;
751      TemplateTy TemplateResult;
752      bool MemberOfUnknownSpecialization;
753      if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
754                         Name, nullptr, true, TemplateResult,
755                         MemberOfUnknownSpecialization) == TNK_Type_template) {
756        diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
757        return;
758      }
759    }
760  
761    // FIXME: Should we move the logic that tries to recover from a missing tag
762    // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
763  
764    if (!SS || (!SS->isSet() && !SS->isInvalid()))
765      Diag(IILoc, IsTemplateName ? diag::err_no_template
766                                 : diag::err_unknown_typename)
767          << II;
768    else if (DeclContext *DC = computeDeclContext(*SS, false))
769      Diag(IILoc, IsTemplateName ? diag::err_no_member_template
770                                 : diag::err_typename_nested_not_found)
771          << II << DC << SS->getRange();
772    else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
773      SuggestedType =
774          ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
775    } else if (isDependentScopeSpecifier(*SS)) {
776      unsigned DiagID = diag::err_typename_missing;
777      if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
778        DiagID = diag::ext_typename_missing;
779  
780      Diag(SS->getRange().getBegin(), DiagID)
781        << SS->getScopeRep() << II->getName()
782        << SourceRange(SS->getRange().getBegin(), IILoc)
783        << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
784      SuggestedType = ActOnTypenameType(S, SourceLocation(),
785                                        *SS, *II, IILoc).get();
786    } else {
787      assert(SS && SS->isInvalid() &&
788             "Invalid scope specifier has already been diagnosed");
789    }
790  }
791  
792  /// Determine whether the given result set contains either a type name
793  /// or
isResultTypeOrTemplate(LookupResult & R,const Token & NextToken)794  static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
795    bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
796                         NextToken.is(tok::less);
797  
798    for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
799      if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
800        return true;
801  
802      if (CheckTemplate && isa<TemplateDecl>(*I))
803        return true;
804    }
805  
806    return false;
807  }
808  
isTagTypeWithMissingTag(Sema & SemaRef,LookupResult & Result,Scope * S,CXXScopeSpec & SS,IdentifierInfo * & Name,SourceLocation NameLoc)809  static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
810                                      Scope *S, CXXScopeSpec &SS,
811                                      IdentifierInfo *&Name,
812                                      SourceLocation NameLoc) {
813    LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
814    SemaRef.LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
815    if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
816      StringRef FixItTagName;
817      switch (Tag->getTagKind()) {
818      case TagTypeKind::Class:
819        FixItTagName = "class ";
820        break;
821  
822      case TagTypeKind::Enum:
823        FixItTagName = "enum ";
824        break;
825  
826      case TagTypeKind::Struct:
827        FixItTagName = "struct ";
828        break;
829  
830      case TagTypeKind::Interface:
831        FixItTagName = "__interface ";
832        break;
833  
834      case TagTypeKind::Union:
835        FixItTagName = "union ";
836        break;
837      }
838  
839      StringRef TagName = FixItTagName.drop_back();
840      SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
841        << Name << TagName << SemaRef.getLangOpts().CPlusPlus
842        << FixItHint::CreateInsertion(NameLoc, FixItTagName);
843  
844      for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
845           I != IEnd; ++I)
846        SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
847          << Name << TagName;
848  
849      // Replace lookup results with just the tag decl.
850      Result.clear(Sema::LookupTagName);
851      SemaRef.LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType());
852      return true;
853    }
854  
855    return false;
856  }
857  
ClassifyName(Scope * S,CXXScopeSpec & SS,IdentifierInfo * & Name,SourceLocation NameLoc,const Token & NextToken,CorrectionCandidateCallback * CCC)858  Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
859                                              IdentifierInfo *&Name,
860                                              SourceLocation NameLoc,
861                                              const Token &NextToken,
862                                              CorrectionCandidateCallback *CCC) {
863    DeclarationNameInfo NameInfo(Name, NameLoc);
864    ObjCMethodDecl *CurMethod = getCurMethodDecl();
865  
866    assert(NextToken.isNot(tok::coloncolon) &&
867           "parse nested name specifiers before calling ClassifyName");
868    if (getLangOpts().CPlusPlus && SS.isSet() &&
869        isCurrentClassName(*Name, S, &SS)) {
870      // Per [class.qual]p2, this names the constructors of SS, not the
871      // injected-class-name. We don't have a classification for that.
872      // There's not much point caching this result, since the parser
873      // will reject it later.
874      return NameClassification::Unknown();
875    }
876  
877    LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
878    LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType(),
879                     /*AllowBuiltinCreation=*/!CurMethod);
880  
881    if (SS.isInvalid())
882      return NameClassification::Error();
883  
884    // For unqualified lookup in a class template in MSVC mode, look into
885    // dependent base classes where the primary class template is known.
886    if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
887      if (ParsedType TypeInBase =
888              recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
889        return TypeInBase;
890    }
891  
892    // Perform lookup for Objective-C instance variables (including automatically
893    // synthesized instance variables), if we're in an Objective-C method.
894    // FIXME: This lookup really, really needs to be folded in to the normal
895    // unqualified lookup mechanism.
896    if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
897      DeclResult Ivar = ObjC().LookupIvarInObjCMethod(Result, S, Name);
898      if (Ivar.isInvalid())
899        return NameClassification::Error();
900      if (Ivar.isUsable())
901        return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
902  
903      // We defer builtin creation until after ivar lookup inside ObjC methods.
904      if (Result.empty())
905        LookupBuiltin(Result);
906    }
907  
908    bool SecondTry = false;
909    bool IsFilteredTemplateName = false;
910  
911  Corrected:
912    switch (Result.getResultKind()) {
913    case LookupResult::NotFound:
914      // If an unqualified-id is followed by a '(', then we have a function
915      // call.
916      if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
917        // In C++, this is an ADL-only call.
918        // FIXME: Reference?
919        if (getLangOpts().CPlusPlus)
920          return NameClassification::UndeclaredNonType();
921  
922        // C90 6.3.2.2:
923        //   If the expression that precedes the parenthesized argument list in a
924        //   function call consists solely of an identifier, and if no
925        //   declaration is visible for this identifier, the identifier is
926        //   implicitly declared exactly as if, in the innermost block containing
927        //   the function call, the declaration
928        //
929        //     extern int identifier ();
930        //
931        //   appeared.
932        //
933        // We also allow this in C99 as an extension. However, this is not
934        // allowed in all language modes as functions without prototypes may not
935        // be supported.
936        if (getLangOpts().implicitFunctionsAllowed()) {
937          if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
938            return NameClassification::NonType(D);
939        }
940      }
941  
942      if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
943        // In C++20 onwards, this could be an ADL-only call to a function
944        // template, and we're required to assume that this is a template name.
945        //
946        // FIXME: Find a way to still do typo correction in this case.
947        TemplateName Template =
948            Context.getAssumedTemplateName(NameInfo.getName());
949        return NameClassification::UndeclaredTemplate(Template);
950      }
951  
952      // In C, we first see whether there is a tag type by the same name, in
953      // which case it's likely that the user just forgot to write "enum",
954      // "struct", or "union".
955      if (!getLangOpts().CPlusPlus && !SecondTry &&
956          isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
957        break;
958      }
959  
960      // Perform typo correction to determine if there is another name that is
961      // close to this name.
962      if (!SecondTry && CCC) {
963        SecondTry = true;
964        if (TypoCorrection Corrected =
965                CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
966                            &SS, *CCC, CTK_ErrorRecovery)) {
967          unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
968          unsigned QualifiedDiag = diag::err_no_member_suggest;
969  
970          NamedDecl *FirstDecl = Corrected.getFoundDecl();
971          NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
972          if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
973              UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
974            UnqualifiedDiag = diag::err_no_template_suggest;
975            QualifiedDiag = diag::err_no_member_template_suggest;
976          } else if (UnderlyingFirstDecl &&
977                     (isa<TypeDecl>(UnderlyingFirstDecl) ||
978                      isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
979                      isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
980            UnqualifiedDiag = diag::err_unknown_typename_suggest;
981            QualifiedDiag = diag::err_unknown_nested_typename_suggest;
982          }
983  
984          if (SS.isEmpty()) {
985            diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
986          } else {// FIXME: is this even reachable? Test it.
987            std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
988            bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
989                                    Name->getName() == CorrectedStr;
990            diagnoseTypo(Corrected, PDiag(QualifiedDiag)
991                                      << Name << computeDeclContext(SS, false)
992                                      << DroppedSpecifier << SS.getRange());
993          }
994  
995          // Update the name, so that the caller has the new name.
996          Name = Corrected.getCorrectionAsIdentifierInfo();
997  
998          // Typo correction corrected to a keyword.
999          if (Corrected.isKeyword())
1000            return Name;
1001  
1002          // Also update the LookupResult...
1003          // FIXME: This should probably go away at some point
1004          Result.clear();
1005          Result.setLookupName(Corrected.getCorrection());
1006          if (FirstDecl)
1007            Result.addDecl(FirstDecl);
1008  
1009          // If we found an Objective-C instance variable, let
1010          // LookupInObjCMethod build the appropriate expression to
1011          // reference the ivar.
1012          // FIXME: This is a gross hack.
1013          if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1014            DeclResult R =
1015                ObjC().LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1016            if (R.isInvalid())
1017              return NameClassification::Error();
1018            if (R.isUsable())
1019              return NameClassification::NonType(Ivar);
1020          }
1021  
1022          goto Corrected;
1023        }
1024      }
1025  
1026      // We failed to correct; just fall through and let the parser deal with it.
1027      Result.suppressDiagnostics();
1028      return NameClassification::Unknown();
1029  
1030    case LookupResult::NotFoundInCurrentInstantiation: {
1031      // We performed name lookup into the current instantiation, and there were
1032      // dependent bases, so we treat this result the same way as any other
1033      // dependent nested-name-specifier.
1034  
1035      // C++ [temp.res]p2:
1036      //   A name used in a template declaration or definition and that is
1037      //   dependent on a template-parameter is assumed not to name a type
1038      //   unless the applicable name lookup finds a type name or the name is
1039      //   qualified by the keyword typename.
1040      //
1041      // FIXME: If the next token is '<', we might want to ask the parser to
1042      // perform some heroics to see if we actually have a
1043      // template-argument-list, which would indicate a missing 'template'
1044      // keyword here.
1045      return NameClassification::DependentNonType();
1046    }
1047  
1048    case LookupResult::Found:
1049    case LookupResult::FoundOverloaded:
1050    case LookupResult::FoundUnresolvedValue:
1051      break;
1052  
1053    case LookupResult::Ambiguous:
1054      if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1055          hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1056                                        /*AllowDependent=*/false)) {
1057        // C++ [temp.local]p3:
1058        //   A lookup that finds an injected-class-name (10.2) can result in an
1059        //   ambiguity in certain cases (for example, if it is found in more than
1060        //   one base class). If all of the injected-class-names that are found
1061        //   refer to specializations of the same class template, and if the name
1062        //   is followed by a template-argument-list, the reference refers to the
1063        //   class template itself and not a specialization thereof, and is not
1064        //   ambiguous.
1065        //
1066        // This filtering can make an ambiguous result into an unambiguous one,
1067        // so try again after filtering out template names.
1068        FilterAcceptableTemplateNames(Result);
1069        if (!Result.isAmbiguous()) {
1070          IsFilteredTemplateName = true;
1071          break;
1072        }
1073      }
1074  
1075      // Diagnose the ambiguity and return an error.
1076      return NameClassification::Error();
1077    }
1078  
1079    if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1080        (IsFilteredTemplateName ||
1081         hasAnyAcceptableTemplateNames(
1082             Result, /*AllowFunctionTemplates=*/true,
1083             /*AllowDependent=*/false,
1084             /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1085                 getLangOpts().CPlusPlus20))) {
1086      // C++ [temp.names]p3:
1087      //   After name lookup (3.4) finds that a name is a template-name or that
1088      //   an operator-function-id or a literal- operator-id refers to a set of
1089      //   overloaded functions any member of which is a function template if
1090      //   this is followed by a <, the < is always taken as the delimiter of a
1091      //   template-argument-list and never as the less-than operator.
1092      // C++2a [temp.names]p2:
1093      //   A name is also considered to refer to a template if it is an
1094      //   unqualified-id followed by a < and name lookup finds either one
1095      //   or more functions or finds nothing.
1096      if (!IsFilteredTemplateName)
1097        FilterAcceptableTemplateNames(Result);
1098  
1099      bool IsFunctionTemplate;
1100      bool IsVarTemplate;
1101      TemplateName Template;
1102      if (Result.end() - Result.begin() > 1) {
1103        IsFunctionTemplate = true;
1104        Template = Context.getOverloadedTemplateName(Result.begin(),
1105                                                     Result.end());
1106      } else if (!Result.empty()) {
1107        auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1108            *Result.begin(), /*AllowFunctionTemplates=*/true,
1109            /*AllowDependent=*/false));
1110        IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1111        IsVarTemplate = isa<VarTemplateDecl>(TD);
1112  
1113        UsingShadowDecl *FoundUsingShadow =
1114            dyn_cast<UsingShadowDecl>(*Result.begin());
1115        assert(!FoundUsingShadow ||
1116               TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1117        Template = Context.getQualifiedTemplateName(
1118            SS.getScopeRep(),
1119            /*TemplateKeyword=*/false,
1120            FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
1121      } else {
1122        // All results were non-template functions. This is a function template
1123        // name.
1124        IsFunctionTemplate = true;
1125        Template = Context.getAssumedTemplateName(NameInfo.getName());
1126      }
1127  
1128      if (IsFunctionTemplate) {
1129        // Function templates always go through overload resolution, at which
1130        // point we'll perform the various checks (e.g., accessibility) we need
1131        // to based on which function we selected.
1132        Result.suppressDiagnostics();
1133  
1134        return NameClassification::FunctionTemplate(Template);
1135      }
1136  
1137      return IsVarTemplate ? NameClassification::VarTemplate(Template)
1138                           : NameClassification::TypeTemplate(Template);
1139    }
1140  
1141    auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1142      QualType T = Context.getTypeDeclType(Type);
1143      if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))
1144        T = Context.getUsingType(USD, T);
1145      return buildNamedType(*this, &SS, T, NameLoc);
1146    };
1147  
1148    NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1149    if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1150      DiagnoseUseOfDecl(Type, NameLoc);
1151      MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1152      return BuildTypeFor(Type, *Result.begin());
1153    }
1154  
1155    ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1156    if (!Class) {
1157      // FIXME: It's unfortunate that we don't have a Type node for handling this.
1158      if (ObjCCompatibleAliasDecl *Alias =
1159              dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1160        Class = Alias->getClassInterface();
1161    }
1162  
1163    if (Class) {
1164      DiagnoseUseOfDecl(Class, NameLoc);
1165  
1166      if (NextToken.is(tok::period)) {
1167        // Interface. <something> is parsed as a property reference expression.
1168        // Just return "unknown" as a fall-through for now.
1169        Result.suppressDiagnostics();
1170        return NameClassification::Unknown();
1171      }
1172  
1173      QualType T = Context.getObjCInterfaceType(Class);
1174      return ParsedType::make(T);
1175    }
1176  
1177    if (isa<ConceptDecl>(FirstDecl)) {
1178      // We want to preserve the UsingShadowDecl for concepts.
1179      if (auto *USD = dyn_cast<UsingShadowDecl>(Result.getRepresentativeDecl()))
1180        return NameClassification::Concept(TemplateName(USD));
1181      return NameClassification::Concept(
1182          TemplateName(cast<TemplateDecl>(FirstDecl)));
1183    }
1184  
1185    if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1186      (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1187      return NameClassification::Error();
1188    }
1189  
1190    // We can have a type template here if we're classifying a template argument.
1191    if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1192        !isa<VarTemplateDecl>(FirstDecl))
1193      return NameClassification::TypeTemplate(
1194          TemplateName(cast<TemplateDecl>(FirstDecl)));
1195  
1196    // Check for a tag type hidden by a non-type decl in a few cases where it
1197    // seems likely a type is wanted instead of the non-type that was found.
1198    bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1199    if ((NextToken.is(tok::identifier) ||
1200         (NextIsOp &&
1201          FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1202        isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1203      TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1204      DiagnoseUseOfDecl(Type, NameLoc);
1205      return BuildTypeFor(Type, *Result.begin());
1206    }
1207  
1208    // If we already know which single declaration is referenced, just annotate
1209    // that declaration directly. Defer resolving even non-overloaded class
1210    // member accesses, as we need to defer certain access checks until we know
1211    // the context.
1212    bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1213    if (Result.isSingleResult() && !ADL &&
1214        (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl)))
1215      return NameClassification::NonType(Result.getRepresentativeDecl());
1216  
1217    // Otherwise, this is an overload set that we will need to resolve later.
1218    Result.suppressDiagnostics();
1219    return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1220        Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1221        Result.getLookupNameInfo(), ADL, Result.begin(), Result.end(),
1222        /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false));
1223  }
1224  
1225  ExprResult
ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo * Name,SourceLocation NameLoc)1226  Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1227                                               SourceLocation NameLoc) {
1228    assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1229    CXXScopeSpec SS;
1230    LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1231    return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1232  }
1233  
1234  ExprResult
ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec & SS,IdentifierInfo * Name,SourceLocation NameLoc,bool IsAddressOfOperand)1235  Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1236                                              IdentifierInfo *Name,
1237                                              SourceLocation NameLoc,
1238                                              bool IsAddressOfOperand) {
1239    DeclarationNameInfo NameInfo(Name, NameLoc);
1240    return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1241                                      NameInfo, IsAddressOfOperand,
1242                                      /*TemplateArgs=*/nullptr);
1243  }
1244  
ActOnNameClassifiedAsNonType(Scope * S,const CXXScopeSpec & SS,NamedDecl * Found,SourceLocation NameLoc,const Token & NextToken)1245  ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1246                                                NamedDecl *Found,
1247                                                SourceLocation NameLoc,
1248                                                const Token &NextToken) {
1249    if (getCurMethodDecl() && SS.isEmpty())
1250      if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1251        return ObjC().BuildIvarRefExpr(S, NameLoc, Ivar);
1252  
1253    // Reconstruct the lookup result.
1254    LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1255    Result.addDecl(Found);
1256    Result.resolveKind();
1257  
1258    bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1259    return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);
1260  }
1261  
ActOnNameClassifiedAsOverloadSet(Scope * S,Expr * E)1262  ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1263    // For an implicit class member access, transform the result into a member
1264    // access expression if necessary.
1265    auto *ULE = cast<UnresolvedLookupExpr>(E);
1266    if ((*ULE->decls_begin())->isCXXClassMember()) {
1267      CXXScopeSpec SS;
1268      SS.Adopt(ULE->getQualifierLoc());
1269  
1270      // Reconstruct the lookup result.
1271      LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1272                          LookupOrdinaryName);
1273      Result.setNamingClass(ULE->getNamingClass());
1274      for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1275        Result.addDecl(*I, I.getAccess());
1276      Result.resolveKind();
1277      return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1278                                             nullptr, S);
1279    }
1280  
1281    // Otherwise, this is already in the form we needed, and no further checks
1282    // are necessary.
1283    return ULE;
1284  }
1285  
1286  Sema::TemplateNameKindForDiagnostics
getTemplateNameKindForDiagnostics(TemplateName Name)1287  Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1288    auto *TD = Name.getAsTemplateDecl();
1289    if (!TD)
1290      return TemplateNameKindForDiagnostics::DependentTemplate;
1291    if (isa<ClassTemplateDecl>(TD))
1292      return TemplateNameKindForDiagnostics::ClassTemplate;
1293    if (isa<FunctionTemplateDecl>(TD))
1294      return TemplateNameKindForDiagnostics::FunctionTemplate;
1295    if (isa<VarTemplateDecl>(TD))
1296      return TemplateNameKindForDiagnostics::VarTemplate;
1297    if (isa<TypeAliasTemplateDecl>(TD))
1298      return TemplateNameKindForDiagnostics::AliasTemplate;
1299    if (isa<TemplateTemplateParmDecl>(TD))
1300      return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1301    if (isa<ConceptDecl>(TD))
1302      return TemplateNameKindForDiagnostics::Concept;
1303    return TemplateNameKindForDiagnostics::DependentTemplate;
1304  }
1305  
PushDeclContext(Scope * S,DeclContext * DC)1306  void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1307    assert(DC->getLexicalParent() == CurContext &&
1308        "The next DeclContext should be lexically contained in the current one.");
1309    CurContext = DC;
1310    S->setEntity(DC);
1311  }
1312  
PopDeclContext()1313  void Sema::PopDeclContext() {
1314    assert(CurContext && "DeclContext imbalance!");
1315  
1316    CurContext = CurContext->getLexicalParent();
1317    assert(CurContext && "Popped translation unit!");
1318  }
1319  
ActOnTagStartSkippedDefinition(Scope * S,Decl * D)1320  Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1321                                                                      Decl *D) {
1322    // Unlike PushDeclContext, the context to which we return is not necessarily
1323    // the containing DC of TD, because the new context will be some pre-existing
1324    // TagDecl definition instead of a fresh one.
1325    auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1326    CurContext = cast<TagDecl>(D)->getDefinition();
1327    assert(CurContext && "skipping definition of undefined tag");
1328    // Start lookups from the parent of the current context; we don't want to look
1329    // into the pre-existing complete definition.
1330    S->setEntity(CurContext->getLookupParent());
1331    return Result;
1332  }
1333  
ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context)1334  void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1335    CurContext = static_cast<decltype(CurContext)>(Context);
1336  }
1337  
EnterDeclaratorContext(Scope * S,DeclContext * DC)1338  void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1339    // C++0x [basic.lookup.unqual]p13:
1340    //   A name used in the definition of a static data member of class
1341    //   X (after the qualified-id of the static member) is looked up as
1342    //   if the name was used in a member function of X.
1343    // C++0x [basic.lookup.unqual]p14:
1344    //   If a variable member of a namespace is defined outside of the
1345    //   scope of its namespace then any name used in the definition of
1346    //   the variable member (after the declarator-id) is looked up as
1347    //   if the definition of the variable member occurred in its
1348    //   namespace.
1349    // Both of these imply that we should push a scope whose context
1350    // is the semantic context of the declaration.  We can't use
1351    // PushDeclContext here because that context is not necessarily
1352    // lexically contained in the current context.  Fortunately,
1353    // the containing scope should have the appropriate information.
1354  
1355    assert(!S->getEntity() && "scope already has entity");
1356  
1357  #ifndef NDEBUG
1358    Scope *Ancestor = S->getParent();
1359    while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1360    assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1361  #endif
1362  
1363    CurContext = DC;
1364    S->setEntity(DC);
1365  
1366    if (S->getParent()->isTemplateParamScope()) {
1367      // Also set the corresponding entities for all immediately-enclosing
1368      // template parameter scopes.
1369      EnterTemplatedContext(S->getParent(), DC);
1370    }
1371  }
1372  
ExitDeclaratorContext(Scope * S)1373  void Sema::ExitDeclaratorContext(Scope *S) {
1374    assert(S->getEntity() == CurContext && "Context imbalance!");
1375  
1376    // Switch back to the lexical context.  The safety of this is
1377    // enforced by an assert in EnterDeclaratorContext.
1378    Scope *Ancestor = S->getParent();
1379    while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1380    CurContext = Ancestor->getEntity();
1381  
1382    // We don't need to do anything with the scope, which is going to
1383    // disappear.
1384  }
1385  
EnterTemplatedContext(Scope * S,DeclContext * DC)1386  void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1387    assert(S->isTemplateParamScope() &&
1388           "expected to be initializing a template parameter scope");
1389  
1390    // C++20 [temp.local]p7:
1391    //   In the definition of a member of a class template that appears outside
1392    //   of the class template definition, the name of a member of the class
1393    //   template hides the name of a template-parameter of any enclosing class
1394    //   templates (but not a template-parameter of the member if the member is a
1395    //   class or function template).
1396    // C++20 [temp.local]p9:
1397    //   In the definition of a class template or in the definition of a member
1398    //   of such a template that appears outside of the template definition, for
1399    //   each non-dependent base class (13.8.2.1), if the name of the base class
1400    //   or the name of a member of the base class is the same as the name of a
1401    //   template-parameter, the base class name or member name hides the
1402    //   template-parameter name (6.4.10).
1403    //
1404    // This means that a template parameter scope should be searched immediately
1405    // after searching the DeclContext for which it is a template parameter
1406    // scope. For example, for
1407    //   template<typename T> template<typename U> template<typename V>
1408    //     void N::A<T>::B<U>::f(...)
1409    // we search V then B<U> (and base classes) then U then A<T> (and base
1410    // classes) then T then N then ::.
1411    unsigned ScopeDepth = getTemplateDepth(S);
1412    for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1413      DeclContext *SearchDCAfterScope = DC;
1414      for (; DC; DC = DC->getLookupParent()) {
1415        if (const TemplateParameterList *TPL =
1416                cast<Decl>(DC)->getDescribedTemplateParams()) {
1417          unsigned DCDepth = TPL->getDepth() + 1;
1418          if (DCDepth > ScopeDepth)
1419            continue;
1420          if (ScopeDepth == DCDepth)
1421            SearchDCAfterScope = DC = DC->getLookupParent();
1422          break;
1423        }
1424      }
1425      S->setLookupEntity(SearchDCAfterScope);
1426    }
1427  }
1428  
ActOnReenterFunctionContext(Scope * S,Decl * D)1429  void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1430    // We assume that the caller has already called
1431    // ActOnReenterTemplateScope so getTemplatedDecl() works.
1432    FunctionDecl *FD = D->getAsFunction();
1433    if (!FD)
1434      return;
1435  
1436    // Same implementation as PushDeclContext, but enters the context
1437    // from the lexical parent, rather than the top-level class.
1438    assert(CurContext == FD->getLexicalParent() &&
1439      "The next DeclContext should be lexically contained in the current one.");
1440    CurContext = FD;
1441    S->setEntity(CurContext);
1442  
1443    for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1444      ParmVarDecl *Param = FD->getParamDecl(P);
1445      // If the parameter has an identifier, then add it to the scope
1446      if (Param->getIdentifier()) {
1447        S->AddDecl(Param);
1448        IdResolver.AddDecl(Param);
1449      }
1450    }
1451  }
1452  
ActOnExitFunctionContext()1453  void Sema::ActOnExitFunctionContext() {
1454    // Same implementation as PopDeclContext, but returns to the lexical parent,
1455    // rather than the top-level class.
1456    assert(CurContext && "DeclContext imbalance!");
1457    CurContext = CurContext->getLexicalParent();
1458    assert(CurContext && "Popped translation unit!");
1459  }
1460  
1461  /// Determine whether overloading is allowed for a new function
1462  /// declaration considering prior declarations of the same name.
1463  ///
1464  /// This routine determines whether overloading is possible, not
1465  /// whether a new declaration actually overloads a previous one.
1466  /// It will return true in C++ (where overloads are always permitted)
1467  /// or, as a C extension, when either the new declaration or a
1468  /// previous one is declared with the 'overloadable' attribute.
AllowOverloadingOfFunction(const LookupResult & Previous,ASTContext & Context,const FunctionDecl * New)1469  static bool AllowOverloadingOfFunction(const LookupResult &Previous,
1470                                         ASTContext &Context,
1471                                         const FunctionDecl *New) {
1472    if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1473      return true;
1474  
1475    // Multiversion function declarations are not overloads in the
1476    // usual sense of that term, but lookup will report that an
1477    // overload set was found if more than one multiversion function
1478    // declaration is present for the same name. It is therefore
1479    // inadequate to assume that some prior declaration(s) had
1480    // the overloadable attribute; checking is required. Since one
1481    // declaration is permitted to omit the attribute, it is necessary
1482    // to check at least two; hence the 'any_of' check below. Note that
1483    // the overloadable attribute is implicitly added to declarations
1484    // that were required to have it but did not.
1485    if (Previous.getResultKind() == LookupResult::FoundOverloaded) {
1486      return llvm::any_of(Previous, [](const NamedDecl *ND) {
1487        return ND->hasAttr<OverloadableAttr>();
1488      });
1489    } else if (Previous.getResultKind() == LookupResult::Found)
1490      return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1491  
1492    return false;
1493  }
1494  
PushOnScopeChains(NamedDecl * D,Scope * S,bool AddToContext)1495  void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1496    // Move up the scope chain until we find the nearest enclosing
1497    // non-transparent context. The declaration will be introduced into this
1498    // scope.
1499    while (S->getEntity() && S->getEntity()->isTransparentContext())
1500      S = S->getParent();
1501  
1502    // Add scoped declarations into their context, so that they can be
1503    // found later. Declarations without a context won't be inserted
1504    // into any context.
1505    if (AddToContext)
1506      CurContext->addDecl(D);
1507  
1508    // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1509    // are function-local declarations.
1510    if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1511      return;
1512  
1513    // Template instantiations should also not be pushed into scope.
1514    if (isa<FunctionDecl>(D) &&
1515        cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1516      return;
1517  
1518    if (isa<UsingEnumDecl>(D) && D->getDeclName().isEmpty()) {
1519      S->AddDecl(D);
1520      return;
1521    }
1522    // If this replaces anything in the current scope,
1523    IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1524                                 IEnd = IdResolver.end();
1525    for (; I != IEnd; ++I) {
1526      if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1527        S->RemoveDecl(*I);
1528        IdResolver.RemoveDecl(*I);
1529  
1530        // Should only need to replace one decl.
1531        break;
1532      }
1533    }
1534  
1535    S->AddDecl(D);
1536  
1537    if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1538      // Implicitly-generated labels may end up getting generated in an order that
1539      // isn't strictly lexical, which breaks name lookup. Be careful to insert
1540      // the label at the appropriate place in the identifier chain.
1541      for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1542        DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1543        if (IDC == CurContext) {
1544          if (!S->isDeclScope(*I))
1545            continue;
1546        } else if (IDC->Encloses(CurContext))
1547          break;
1548      }
1549  
1550      IdResolver.InsertDeclAfter(I, D);
1551    } else {
1552      IdResolver.AddDecl(D);
1553    }
1554    warnOnReservedIdentifier(D);
1555  }
1556  
isDeclInScope(NamedDecl * D,DeclContext * Ctx,Scope * S,bool AllowInlineNamespace) const1557  bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1558                           bool AllowInlineNamespace) const {
1559    return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1560  }
1561  
getScopeForDeclContext(Scope * S,DeclContext * DC)1562  Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1563    DeclContext *TargetDC = DC->getPrimaryContext();
1564    do {
1565      if (DeclContext *ScopeDC = S->getEntity())
1566        if (ScopeDC->getPrimaryContext() == TargetDC)
1567          return S;
1568    } while ((S = S->getParent()));
1569  
1570    return nullptr;
1571  }
1572  
1573  static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1574                                              DeclContext*,
1575                                              ASTContext&);
1576  
FilterLookupForScope(LookupResult & R,DeclContext * Ctx,Scope * S,bool ConsiderLinkage,bool AllowInlineNamespace)1577  void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1578                                  bool ConsiderLinkage,
1579                                  bool AllowInlineNamespace) {
1580    LookupResult::Filter F = R.makeFilter();
1581    while (F.hasNext()) {
1582      NamedDecl *D = F.next();
1583  
1584      if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1585        continue;
1586  
1587      if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1588        continue;
1589  
1590      F.erase();
1591    }
1592  
1593    F.done();
1594  }
1595  
CheckRedeclarationModuleOwnership(NamedDecl * New,NamedDecl * Old)1596  bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1597    // [module.interface]p7:
1598    // A declaration is attached to a module as follows:
1599    // - If the declaration is a non-dependent friend declaration that nominates a
1600    // function with a declarator-id that is a qualified-id or template-id or that
1601    // nominates a class other than with an elaborated-type-specifier with neither
1602    // a nested-name-specifier nor a simple-template-id, it is attached to the
1603    // module to which the friend is attached ([basic.link]).
1604    if (New->getFriendObjectKind() &&
1605        Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1606      New->setLocalOwningModule(Old->getOwningModule());
1607      makeMergedDefinitionVisible(New);
1608      return false;
1609    }
1610  
1611    Module *NewM = New->getOwningModule();
1612    Module *OldM = Old->getOwningModule();
1613  
1614    if (NewM && NewM->isPrivateModule())
1615      NewM = NewM->Parent;
1616    if (OldM && OldM->isPrivateModule())
1617      OldM = OldM->Parent;
1618  
1619    if (NewM == OldM)
1620      return false;
1621  
1622    if (NewM && OldM) {
1623      // A module implementation unit has visibility of the decls in its
1624      // implicitly imported interface.
1625      if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1626        return false;
1627  
1628      // Partitions are part of the module, but a partition could import another
1629      // module, so verify that the PMIs agree.
1630      if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1631          getASTContext().isInSameModule(NewM, OldM))
1632        return false;
1633    }
1634  
1635    bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1636    bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1637    if (NewIsModuleInterface || OldIsModuleInterface) {
1638      // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1639      //   if a declaration of D [...] appears in the purview of a module, all
1640      //   other such declarations shall appear in the purview of the same module
1641      Diag(New->getLocation(), diag::err_mismatched_owning_module)
1642        << New
1643        << NewIsModuleInterface
1644        << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1645        << OldIsModuleInterface
1646        << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1647      Diag(Old->getLocation(), diag::note_previous_declaration);
1648      New->setInvalidDecl();
1649      return true;
1650    }
1651  
1652    return false;
1653  }
1654  
CheckRedeclarationExported(NamedDecl * New,NamedDecl * Old)1655  bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
1656    // [module.interface]p1:
1657    // An export-declaration shall inhabit a namespace scope.
1658    //
1659    // So it is meaningless to talk about redeclaration which is not at namespace
1660    // scope.
1661    if (!New->getLexicalDeclContext()
1662             ->getNonTransparentContext()
1663             ->isFileContext() ||
1664        !Old->getLexicalDeclContext()
1665             ->getNonTransparentContext()
1666             ->isFileContext())
1667      return false;
1668  
1669    bool IsNewExported = New->isInExportDeclContext();
1670    bool IsOldExported = Old->isInExportDeclContext();
1671  
1672    // It should be irrevelant if both of them are not exported.
1673    if (!IsNewExported && !IsOldExported)
1674      return false;
1675  
1676    if (IsOldExported)
1677      return false;
1678  
1679    // If the Old declaration are not attached to named modules
1680    // and the New declaration are attached to global module.
1681    // It should be fine to allow the export since it doesn't change
1682    // the linkage of declarations. See
1683    // https://github.com/llvm/llvm-project/issues/98583 for details.
1684    if (!Old->isInNamedModule() && New->getOwningModule() &&
1685        New->getOwningModule()->isImplicitGlobalModule())
1686      return false;
1687  
1688    assert(IsNewExported);
1689  
1690    auto Lk = Old->getFormalLinkage();
1691    int S = 0;
1692    if (Lk == Linkage::Internal)
1693      S = 1;
1694    else if (Lk == Linkage::Module)
1695      S = 2;
1696    Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1697    Diag(Old->getLocation(), diag::note_previous_declaration);
1698    return true;
1699  }
1700  
CheckRedeclarationInModule(NamedDecl * New,NamedDecl * Old)1701  bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
1702    if (CheckRedeclarationModuleOwnership(New, Old))
1703      return true;
1704  
1705    if (CheckRedeclarationExported(New, Old))
1706      return true;
1707  
1708    return false;
1709  }
1710  
IsRedefinitionInModule(const NamedDecl * New,const NamedDecl * Old) const1711  bool Sema::IsRedefinitionInModule(const NamedDecl *New,
1712                                       const NamedDecl *Old) const {
1713    assert(getASTContext().isSameEntity(New, Old) &&
1714           "New and Old are not the same definition, we should diagnostic it "
1715           "immediately instead of checking it.");
1716    assert(const_cast<Sema *>(this)->isReachable(New) &&
1717           const_cast<Sema *>(this)->isReachable(Old) &&
1718           "We shouldn't see unreachable definitions here.");
1719  
1720    Module *NewM = New->getOwningModule();
1721    Module *OldM = Old->getOwningModule();
1722  
1723    // We only checks for named modules here. The header like modules is skipped.
1724    // FIXME: This is not right if we import the header like modules in the module
1725    // purview.
1726    //
1727    // For example, assuming "header.h" provides definition for `D`.
1728    // ```C++
1729    // //--- M.cppm
1730    // export module M;
1731    // import "header.h"; // or #include "header.h" but import it by clang modules
1732    // actually.
1733    //
1734    // //--- Use.cpp
1735    // import M;
1736    // import "header.h"; // or uses clang modules.
1737    // ```
1738    //
1739    // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1740    // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1741    // reject it. But the current implementation couldn't detect the case since we
1742    // don't record the information about the importee modules.
1743    //
1744    // But this might not be painful in practice. Since the design of C++20 Named
1745    // Modules suggests us to use headers in global module fragment instead of
1746    // module purview.
1747    if (NewM && NewM->isHeaderLikeModule())
1748      NewM = nullptr;
1749    if (OldM && OldM->isHeaderLikeModule())
1750      OldM = nullptr;
1751  
1752    if (!NewM && !OldM)
1753      return true;
1754  
1755    // [basic.def.odr]p14.3
1756    // Each such definition shall not be attached to a named module
1757    // ([module.unit]).
1758    if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1759      return true;
1760  
1761    // Then New and Old lives in the same TU if their share one same module unit.
1762    if (NewM)
1763      NewM = NewM->getTopLevelModule();
1764    if (OldM)
1765      OldM = OldM->getTopLevelModule();
1766    return OldM == NewM;
1767  }
1768  
isUsingDeclNotAtClassScope(NamedDecl * D)1769  static bool isUsingDeclNotAtClassScope(NamedDecl *D) {
1770    if (D->getDeclContext()->isFileContext())
1771      return false;
1772  
1773    return isa<UsingShadowDecl>(D) ||
1774           isa<UnresolvedUsingTypenameDecl>(D) ||
1775           isa<UnresolvedUsingValueDecl>(D);
1776  }
1777  
1778  /// Removes using shadow declarations not at class scope from the lookup
1779  /// results.
RemoveUsingDecls(LookupResult & R)1780  static void RemoveUsingDecls(LookupResult &R) {
1781    LookupResult::Filter F = R.makeFilter();
1782    while (F.hasNext())
1783      if (isUsingDeclNotAtClassScope(F.next()))
1784        F.erase();
1785  
1786    F.done();
1787  }
1788  
1789  /// Check for this common pattern:
1790  /// @code
1791  /// class S {
1792  ///   S(const S&); // DO NOT IMPLEMENT
1793  ///   void operator=(const S&); // DO NOT IMPLEMENT
1794  /// };
1795  /// @endcode
IsDisallowedCopyOrAssign(const CXXMethodDecl * D)1796  static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1797    // FIXME: Should check for private access too but access is set after we get
1798    // the decl here.
1799    if (D->doesThisDeclarationHaveABody())
1800      return false;
1801  
1802    if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1803      return CD->isCopyConstructor();
1804    return D->isCopyAssignmentOperator();
1805  }
1806  
mightHaveNonExternalLinkage(const DeclaratorDecl * D)1807  bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1808    const DeclContext *DC = D->getDeclContext();
1809    while (!DC->isTranslationUnit()) {
1810      if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1811        if (!RD->hasNameForLinkage())
1812          return true;
1813      }
1814      DC = DC->getParent();
1815    }
1816  
1817    return !D->isExternallyVisible();
1818  }
1819  
1820  // FIXME: This needs to be refactored; some other isInMainFile users want
1821  // these semantics.
isMainFileLoc(const Sema & S,SourceLocation Loc)1822  static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1823    if (S.TUKind != TU_Complete || S.getLangOpts().IsHeaderFile)
1824      return false;
1825    return S.SourceMgr.isInMainFile(Loc);
1826  }
1827  
ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl * D) const1828  bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1829    assert(D);
1830  
1831    if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1832      return false;
1833  
1834    // Ignore all entities declared within templates, and out-of-line definitions
1835    // of members of class templates.
1836    if (D->getDeclContext()->isDependentContext() ||
1837        D->getLexicalDeclContext()->isDependentContext())
1838      return false;
1839  
1840    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1841      if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1842        return false;
1843      // A non-out-of-line declaration of a member specialization was implicitly
1844      // instantiated; it's the out-of-line declaration that we're interested in.
1845      if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1846          FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1847        return false;
1848  
1849      if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1850        if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1851          return false;
1852      } else {
1853        // 'static inline' functions are defined in headers; don't warn.
1854        if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1855          return false;
1856      }
1857  
1858      if (FD->doesThisDeclarationHaveABody() &&
1859          Context.DeclMustBeEmitted(FD))
1860        return false;
1861    } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1862      // Constants and utility variables are defined in headers with internal
1863      // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1864      // like "inline".)
1865      if (!isMainFileLoc(*this, VD->getLocation()))
1866        return false;
1867  
1868      if (Context.DeclMustBeEmitted(VD))
1869        return false;
1870  
1871      if (VD->isStaticDataMember() &&
1872          VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1873        return false;
1874      if (VD->isStaticDataMember() &&
1875          VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1876          VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1877        return false;
1878  
1879      if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1880        return false;
1881    } else {
1882      return false;
1883    }
1884  
1885    // Only warn for unused decls internal to the translation unit.
1886    // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1887    // for inline functions defined in the main source file, for instance.
1888    return mightHaveNonExternalLinkage(D);
1889  }
1890  
MarkUnusedFileScopedDecl(const DeclaratorDecl * D)1891  void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1892    if (!D)
1893      return;
1894  
1895    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1896      const FunctionDecl *First = FD->getFirstDecl();
1897      if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1898        return; // First should already be in the vector.
1899    }
1900  
1901    if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1902      const VarDecl *First = VD->getFirstDecl();
1903      if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1904        return; // First should already be in the vector.
1905    }
1906  
1907    if (ShouldWarnIfUnusedFileScopedDecl(D))
1908      UnusedFileScopedDecls.push_back(D);
1909  }
1910  
ShouldDiagnoseUnusedDecl(const LangOptions & LangOpts,const NamedDecl * D)1911  static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
1912                                       const NamedDecl *D) {
1913    if (D->isInvalidDecl())
1914      return false;
1915  
1916    if (const auto *DD = dyn_cast<DecompositionDecl>(D)) {
1917      // For a decomposition declaration, warn if none of the bindings are
1918      // referenced, instead of if the variable itself is referenced (which
1919      // it is, by the bindings' expressions).
1920      bool IsAllPlaceholders = true;
1921      for (const auto *BD : DD->bindings()) {
1922        if (BD->isReferenced() || BD->hasAttr<UnusedAttr>())
1923          return false;
1924        IsAllPlaceholders = IsAllPlaceholders && BD->isPlaceholderVar(LangOpts);
1925      }
1926      if (IsAllPlaceholders)
1927        return false;
1928    } else if (!D->getDeclName()) {
1929      return false;
1930    } else if (D->isReferenced() || D->isUsed()) {
1931      return false;
1932    }
1933  
1934    if (D->isPlaceholderVar(LangOpts))
1935      return false;
1936  
1937    if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
1938        D->hasAttr<CleanupAttr>())
1939      return false;
1940  
1941    if (isa<LabelDecl>(D))
1942      return true;
1943  
1944    // Except for labels, we only care about unused decls that are local to
1945    // functions.
1946    bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1947    if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1948      // For dependent types, the diagnostic is deferred.
1949      WithinFunction =
1950          WithinFunction || (R->isLocalClass() && !R->isDependentType());
1951    if (!WithinFunction)
1952      return false;
1953  
1954    if (isa<TypedefNameDecl>(D))
1955      return true;
1956  
1957    // White-list anything that isn't a local variable.
1958    if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1959      return false;
1960  
1961    // Types of valid local variables should be complete, so this should succeed.
1962    if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1963  
1964      const Expr *Init = VD->getInit();
1965      if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Init))
1966        Init = Cleanups->getSubExpr();
1967  
1968      const auto *Ty = VD->getType().getTypePtr();
1969  
1970      // Only look at the outermost level of typedef.
1971      if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1972        // Allow anything marked with __attribute__((unused)).
1973        if (TT->getDecl()->hasAttr<UnusedAttr>())
1974          return false;
1975      }
1976  
1977      // Warn for reference variables whose initializtion performs lifetime
1978      // extension.
1979      if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Init);
1980          MTE && MTE->getExtendingDecl()) {
1981        Ty = VD->getType().getNonReferenceType().getTypePtr();
1982        Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
1983      }
1984  
1985      // If we failed to complete the type for some reason, or if the type is
1986      // dependent, don't diagnose the variable.
1987      if (Ty->isIncompleteType() || Ty->isDependentType())
1988        return false;
1989  
1990      // Look at the element type to ensure that the warning behaviour is
1991      // consistent for both scalars and arrays.
1992      Ty = Ty->getBaseElementTypeUnsafe();
1993  
1994      if (const TagType *TT = Ty->getAs<TagType>()) {
1995        const TagDecl *Tag = TT->getDecl();
1996        if (Tag->hasAttr<UnusedAttr>())
1997          return false;
1998  
1999        if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2000          if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2001            return false;
2002  
2003          if (Init) {
2004            const auto *Construct =
2005                dyn_cast<CXXConstructExpr>(Init->IgnoreImpCasts());
2006            if (Construct && !Construct->isElidable()) {
2007              const CXXConstructorDecl *CD = Construct->getConstructor();
2008              if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2009                  (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2010                return false;
2011            }
2012  
2013            // Suppress the warning if we don't know how this is constructed, and
2014            // it could possibly be non-trivial constructor.
2015            if (Init->isTypeDependent()) {
2016              for (const CXXConstructorDecl *Ctor : RD->ctors())
2017                if (!Ctor->isTrivial())
2018                  return false;
2019            }
2020  
2021            // Suppress the warning if the constructor is unresolved because
2022            // its arguments are dependent.
2023            if (isa<CXXUnresolvedConstructExpr>(Init))
2024              return false;
2025          }
2026        }
2027      }
2028  
2029      // TODO: __attribute__((unused)) templates?
2030    }
2031  
2032    return true;
2033  }
2034  
GenerateFixForUnusedDecl(const NamedDecl * D,ASTContext & Ctx,FixItHint & Hint)2035  static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
2036                                       FixItHint &Hint) {
2037    if (isa<LabelDecl>(D)) {
2038      SourceLocation AfterColon = Lexer::findLocationAfterToken(
2039          D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2040          /*SkipTrailingWhitespaceAndNewline=*/false);
2041      if (AfterColon.isInvalid())
2042        return;
2043      Hint = FixItHint::CreateRemoval(
2044          CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
2045    }
2046  }
2047  
DiagnoseUnusedNestedTypedefs(const RecordDecl * D)2048  void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
2049    DiagnoseUnusedNestedTypedefs(
2050        D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2051  }
2052  
DiagnoseUnusedNestedTypedefs(const RecordDecl * D,DiagReceiverTy DiagReceiver)2053  void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D,
2054                                          DiagReceiverTy DiagReceiver) {
2055    if (D->getTypeForDecl()->isDependentType())
2056      return;
2057  
2058    for (auto *TmpD : D->decls()) {
2059      if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2060        DiagnoseUnusedDecl(T, DiagReceiver);
2061      else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2062        DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
2063    }
2064  }
2065  
DiagnoseUnusedDecl(const NamedDecl * D)2066  void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
2067    DiagnoseUnusedDecl(
2068        D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2069  }
2070  
DiagnoseUnusedDecl(const NamedDecl * D,DiagReceiverTy DiagReceiver)2071  void Sema::DiagnoseUnusedDecl(const NamedDecl *D, DiagReceiverTy DiagReceiver) {
2072    if (!ShouldDiagnoseUnusedDecl(getLangOpts(), D))
2073      return;
2074  
2075    if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2076      // typedefs can be referenced later on, so the diagnostics are emitted
2077      // at end-of-translation-unit.
2078      UnusedLocalTypedefNameCandidates.insert(TD);
2079      return;
2080    }
2081  
2082    FixItHint Hint;
2083    GenerateFixForUnusedDecl(D, Context, Hint);
2084  
2085    unsigned DiagID;
2086    if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2087      DiagID = diag::warn_unused_exception_param;
2088    else if (isa<LabelDecl>(D))
2089      DiagID = diag::warn_unused_label;
2090    else
2091      DiagID = diag::warn_unused_variable;
2092  
2093    SourceLocation DiagLoc = D->getLocation();
2094    DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2095  }
2096  
DiagnoseUnusedButSetDecl(const VarDecl * VD,DiagReceiverTy DiagReceiver)2097  void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD,
2098                                      DiagReceiverTy DiagReceiver) {
2099    // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2100    // it's not really unused.
2101    if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2102      return;
2103  
2104    //  In C++, `_` variables behave as if they were maybe_unused
2105    if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(getLangOpts()))
2106      return;
2107  
2108    const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2109  
2110    if (Ty->isReferenceType() || Ty->isDependentType())
2111      return;
2112  
2113    if (const TagType *TT = Ty->getAs<TagType>()) {
2114      const TagDecl *Tag = TT->getDecl();
2115      if (Tag->hasAttr<UnusedAttr>())
2116        return;
2117      // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2118      // mimic gcc's behavior.
2119      if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag);
2120          RD && !RD->hasAttr<WarnUnusedAttr>())
2121        return;
2122    }
2123  
2124    // Don't warn about __block Objective-C pointer variables, as they might
2125    // be assigned in the block but not used elsewhere for the purpose of lifetime
2126    // extension.
2127    if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2128      return;
2129  
2130    // Don't warn about Objective-C pointer variables with precise lifetime
2131    // semantics; they can be used to ensure ARC releases the object at a known
2132    // time, which may mean assignment but no other references.
2133    if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2134      return;
2135  
2136    auto iter = RefsMinusAssignments.find(VD);
2137    if (iter == RefsMinusAssignments.end())
2138      return;
2139  
2140    assert(iter->getSecond() >= 0 &&
2141           "Found a negative number of references to a VarDecl");
2142    if (int RefCnt = iter->getSecond(); RefCnt > 0) {
2143      // Assume the given VarDecl is "used" if its ref count stored in
2144      // `RefMinusAssignments` is positive, with one exception.
2145      //
2146      // For a C++ variable whose decl (with initializer) entirely consist the
2147      // condition expression of a if/while/for construct,
2148      // Clang creates a DeclRefExpr for the condition expression rather than a
2149      // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref
2150      // count stored in `RefMinusAssignment` equals 1 when the variable is never
2151      // used in the body of the if/while/for construct.
2152      bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);
2153      if (!UnusedCXXCondDecl)
2154        return;
2155    }
2156  
2157    unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2158                                           : diag::warn_unused_but_set_variable;
2159    DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2160  }
2161  
CheckPoppedLabel(LabelDecl * L,Sema & S,Sema::DiagReceiverTy DiagReceiver)2162  static void CheckPoppedLabel(LabelDecl *L, Sema &S,
2163                               Sema::DiagReceiverTy DiagReceiver) {
2164    // Verify that we have no forward references left.  If so, there was a goto
2165    // or address of a label taken, but no definition of it.  Label fwd
2166    // definitions are indicated with a null substmt which is also not a resolved
2167    // MS inline assembly label name.
2168    bool Diagnose = false;
2169    if (L->isMSAsmLabel())
2170      Diagnose = !L->isResolvedMSAsmLabel();
2171    else
2172      Diagnose = L->getStmt() == nullptr;
2173    if (Diagnose)
2174      DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2175                                         << L);
2176  }
2177  
ActOnPopScope(SourceLocation Loc,Scope * S)2178  void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
2179    S->applyNRVO();
2180  
2181    if (S->decl_empty()) return;
2182    assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2183           "Scope shouldn't contain decls!");
2184  
2185    /// We visit the decls in non-deterministic order, but we want diagnostics
2186    /// emitted in deterministic order. Collect any diagnostic that may be emitted
2187    /// and sort the diagnostics before emitting them, after we visited all decls.
2188    struct LocAndDiag {
2189      SourceLocation Loc;
2190      std::optional<SourceLocation> PreviousDeclLoc;
2191      PartialDiagnostic PD;
2192    };
2193    SmallVector<LocAndDiag, 16> DeclDiags;
2194    auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2195      DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)});
2196    };
2197    auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2198                                        SourceLocation PreviousDeclLoc,
2199                                        PartialDiagnostic PD) {
2200      DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});
2201    };
2202  
2203    for (auto *TmpD : S->decls()) {
2204      assert(TmpD && "This decl didn't get pushed??");
2205  
2206      assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2207      NamedDecl *D = cast<NamedDecl>(TmpD);
2208  
2209      // Diagnose unused variables in this scope.
2210      if (!S->hasUnrecoverableErrorOccurred()) {
2211        DiagnoseUnusedDecl(D, addDiag);
2212        if (const auto *RD = dyn_cast<RecordDecl>(D))
2213          DiagnoseUnusedNestedTypedefs(RD, addDiag);
2214        if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2215          DiagnoseUnusedButSetDecl(VD, addDiag);
2216          RefsMinusAssignments.erase(VD);
2217        }
2218      }
2219  
2220      if (!D->getDeclName()) continue;
2221  
2222      // If this was a forward reference to a label, verify it was defined.
2223      if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2224        CheckPoppedLabel(LD, *this, addDiag);
2225  
2226      // Partial translation units that are created in incremental processing must
2227      // not clean up the IdResolver because PTUs should take into account the
2228      // declarations that came from previous PTUs.
2229      if (!PP.isIncrementalProcessingEnabled() || getLangOpts().ObjC ||
2230          getLangOpts().CPlusPlus)
2231        IdResolver.RemoveDecl(D);
2232  
2233      // Warn on it if we are shadowing a declaration.
2234      auto ShadowI = ShadowingDecls.find(D);
2235      if (ShadowI != ShadowingDecls.end()) {
2236        if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2237          addDiagWithPrev(D->getLocation(), FD->getLocation(),
2238                          PDiag(diag::warn_ctor_parm_shadows_field)
2239                              << D << FD << FD->getParent());
2240        }
2241        ShadowingDecls.erase(ShadowI);
2242      }
2243    }
2244  
2245    llvm::sort(DeclDiags,
2246               [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2247                 // The particular order for diagnostics is not important, as long
2248                 // as the order is deterministic. Using the raw location is going
2249                 // to generally be in source order unless there are macro
2250                 // expansions involved.
2251                 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2252               });
2253    for (const LocAndDiag &D : DeclDiags) {
2254      Diag(D.Loc, D.PD);
2255      if (D.PreviousDeclLoc)
2256        Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
2257    }
2258  }
2259  
getNonFieldDeclScope(Scope * S)2260  Scope *Sema::getNonFieldDeclScope(Scope *S) {
2261    while (((S->getFlags() & Scope::DeclScope) == 0) ||
2262           (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2263           (S->isClassScope() && !getLangOpts().CPlusPlus))
2264      S = S->getParent();
2265    return S;
2266  }
2267  
getHeaderName(Builtin::Context & BuiltinInfo,unsigned ID,ASTContext::GetBuiltinTypeError Error)2268  static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2269                                 ASTContext::GetBuiltinTypeError Error) {
2270    switch (Error) {
2271    case ASTContext::GE_None:
2272      return "";
2273    case ASTContext::GE_Missing_type:
2274      return BuiltinInfo.getHeaderName(ID);
2275    case ASTContext::GE_Missing_stdio:
2276      return "stdio.h";
2277    case ASTContext::GE_Missing_setjmp:
2278      return "setjmp.h";
2279    case ASTContext::GE_Missing_ucontext:
2280      return "ucontext.h";
2281    }
2282    llvm_unreachable("unhandled error kind");
2283  }
2284  
CreateBuiltin(IdentifierInfo * II,QualType Type,unsigned ID,SourceLocation Loc)2285  FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2286                                    unsigned ID, SourceLocation Loc) {
2287    DeclContext *Parent = Context.getTranslationUnitDecl();
2288  
2289    if (getLangOpts().CPlusPlus) {
2290      LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2291          Context, Parent, Loc, Loc, LinkageSpecLanguageIDs::C, false);
2292      CLinkageDecl->setImplicit();
2293      Parent->addDecl(CLinkageDecl);
2294      Parent = CLinkageDecl;
2295    }
2296  
2297    ConstexprSpecKind ConstexprKind = ConstexprSpecKind::Unspecified;
2298    if (Context.BuiltinInfo.isImmediate(ID)) {
2299      assert(getLangOpts().CPlusPlus20 &&
2300             "consteval builtins should only be available in C++20 mode");
2301      ConstexprKind = ConstexprSpecKind::Consteval;
2302    }
2303  
2304    FunctionDecl *New = FunctionDecl::Create(
2305        Context, Parent, Loc, Loc, II, Type, /*TInfo=*/nullptr, SC_Extern,
2306        getCurFPFeatures().isFPConstrained(), /*isInlineSpecified=*/false,
2307        Type->isFunctionProtoType(), ConstexprKind);
2308    New->setImplicit();
2309    New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2310  
2311    // Create Decl objects for each parameter, adding them to the
2312    // FunctionDecl.
2313    if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2314      SmallVector<ParmVarDecl *, 16> Params;
2315      for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2316        ParmVarDecl *parm = ParmVarDecl::Create(
2317            Context, New, SourceLocation(), SourceLocation(), nullptr,
2318            FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2319        parm->setScopeInfo(0, i);
2320        Params.push_back(parm);
2321      }
2322      New->setParams(Params);
2323    }
2324  
2325    AddKnownFunctionAttributes(New);
2326    return New;
2327  }
2328  
LazilyCreateBuiltin(IdentifierInfo * II,unsigned ID,Scope * S,bool ForRedeclaration,SourceLocation Loc)2329  NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2330                                       Scope *S, bool ForRedeclaration,
2331                                       SourceLocation Loc) {
2332    LookupNecessaryTypesForBuiltin(S, ID);
2333  
2334    ASTContext::GetBuiltinTypeError Error;
2335    QualType R = Context.GetBuiltinType(ID, Error);
2336    if (Error) {
2337      if (!ForRedeclaration)
2338        return nullptr;
2339  
2340      // If we have a builtin without an associated type we should not emit a
2341      // warning when we were not able to find a type for it.
2342      if (Error == ASTContext::GE_Missing_type ||
2343          Context.BuiltinInfo.allowTypeMismatch(ID))
2344        return nullptr;
2345  
2346      // If we could not find a type for setjmp it is because the jmp_buf type was
2347      // not defined prior to the setjmp declaration.
2348      if (Error == ASTContext::GE_Missing_setjmp) {
2349        Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2350            << Context.BuiltinInfo.getName(ID);
2351        return nullptr;
2352      }
2353  
2354      // Generally, we emit a warning that the declaration requires the
2355      // appropriate header.
2356      Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2357          << getHeaderName(Context.BuiltinInfo, ID, Error)
2358          << Context.BuiltinInfo.getName(ID);
2359      return nullptr;
2360    }
2361  
2362    if (!ForRedeclaration &&
2363        (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2364         Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2365      Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2366                             : diag::ext_implicit_lib_function_decl)
2367          << Context.BuiltinInfo.getName(ID) << R;
2368      if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2369        Diag(Loc, diag::note_include_header_or_declare)
2370            << Header << Context.BuiltinInfo.getName(ID);
2371    }
2372  
2373    if (R.isNull())
2374      return nullptr;
2375  
2376    FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2377    RegisterLocallyScopedExternCDecl(New, S);
2378  
2379    // TUScope is the translation-unit scope to insert this function into.
2380    // FIXME: This is hideous. We need to teach PushOnScopeChains to
2381    // relate Scopes to DeclContexts, and probably eliminate CurContext
2382    // entirely, but we're not there yet.
2383    DeclContext *SavedContext = CurContext;
2384    CurContext = New->getDeclContext();
2385    PushOnScopeChains(New, TUScope);
2386    CurContext = SavedContext;
2387    return New;
2388  }
2389  
2390  /// Typedef declarations don't have linkage, but they still denote the same
2391  /// entity if their types are the same.
2392  /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2393  /// isSameEntity.
2394  static void
filterNonConflictingPreviousTypedefDecls(Sema & S,const TypedefNameDecl * Decl,LookupResult & Previous)2395  filterNonConflictingPreviousTypedefDecls(Sema &S, const TypedefNameDecl *Decl,
2396                                           LookupResult &Previous) {
2397    // This is only interesting when modules are enabled.
2398    if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2399      return;
2400  
2401    // Empty sets are uninteresting.
2402    if (Previous.empty())
2403      return;
2404  
2405    LookupResult::Filter Filter = Previous.makeFilter();
2406    while (Filter.hasNext()) {
2407      NamedDecl *Old = Filter.next();
2408  
2409      // Non-hidden declarations are never ignored.
2410      if (S.isVisible(Old))
2411        continue;
2412  
2413      // Declarations of the same entity are not ignored, even if they have
2414      // different linkages.
2415      if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2416        if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2417                                  Decl->getUnderlyingType()))
2418          continue;
2419  
2420        // If both declarations give a tag declaration a typedef name for linkage
2421        // purposes, then they declare the same entity.
2422        if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2423            Decl->getAnonDeclWithTypedefName())
2424          continue;
2425      }
2426  
2427      Filter.erase();
2428    }
2429  
2430    Filter.done();
2431  }
2432  
isIncompatibleTypedef(const TypeDecl * Old,TypedefNameDecl * New)2433  bool Sema::isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New) {
2434    QualType OldType;
2435    if (const TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2436      OldType = OldTypedef->getUnderlyingType();
2437    else
2438      OldType = Context.getTypeDeclType(Old);
2439    QualType NewType = New->getUnderlyingType();
2440  
2441    if (NewType->isVariablyModifiedType()) {
2442      // Must not redefine a typedef with a variably-modified type.
2443      int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2444      Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2445        << Kind << NewType;
2446      if (Old->getLocation().isValid())
2447        notePreviousDefinition(Old, New->getLocation());
2448      New->setInvalidDecl();
2449      return true;
2450    }
2451  
2452    if (OldType != NewType &&
2453        !OldType->isDependentType() &&
2454        !NewType->isDependentType() &&
2455        !Context.hasSameType(OldType, NewType)) {
2456      int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2457      Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2458        << Kind << NewType << OldType;
2459      if (Old->getLocation().isValid())
2460        notePreviousDefinition(Old, New->getLocation());
2461      New->setInvalidDecl();
2462      return true;
2463    }
2464    return false;
2465  }
2466  
MergeTypedefNameDecl(Scope * S,TypedefNameDecl * New,LookupResult & OldDecls)2467  void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2468                                  LookupResult &OldDecls) {
2469    // If the new decl is known invalid already, don't bother doing any
2470    // merging checks.
2471    if (New->isInvalidDecl()) return;
2472  
2473    // Allow multiple definitions for ObjC built-in typedefs.
2474    // FIXME: Verify the underlying types are equivalent!
2475    if (getLangOpts().ObjC) {
2476      const IdentifierInfo *TypeID = New->getIdentifier();
2477      switch (TypeID->getLength()) {
2478      default: break;
2479      case 2:
2480        {
2481          if (!TypeID->isStr("id"))
2482            break;
2483          QualType T = New->getUnderlyingType();
2484          if (!T->isPointerType())
2485            break;
2486          if (!T->isVoidPointerType()) {
2487            QualType PT = T->castAs<PointerType>()->getPointeeType();
2488            if (!PT->isStructureType())
2489              break;
2490          }
2491          Context.setObjCIdRedefinitionType(T);
2492          // Install the built-in type for 'id', ignoring the current definition.
2493          New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2494          return;
2495        }
2496      case 5:
2497        if (!TypeID->isStr("Class"))
2498          break;
2499        Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2500        // Install the built-in type for 'Class', ignoring the current definition.
2501        New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2502        return;
2503      case 3:
2504        if (!TypeID->isStr("SEL"))
2505          break;
2506        Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2507        // Install the built-in type for 'SEL', ignoring the current definition.
2508        New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2509        return;
2510      }
2511      // Fall through - the typedef name was not a builtin type.
2512    }
2513  
2514    // Verify the old decl was also a type.
2515    TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2516    if (!Old) {
2517      Diag(New->getLocation(), diag::err_redefinition_different_kind)
2518        << New->getDeclName();
2519  
2520      NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2521      if (OldD->getLocation().isValid())
2522        notePreviousDefinition(OldD, New->getLocation());
2523  
2524      return New->setInvalidDecl();
2525    }
2526  
2527    // If the old declaration is invalid, just give up here.
2528    if (Old->isInvalidDecl())
2529      return New->setInvalidDecl();
2530  
2531    if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2532      auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2533      auto *NewTag = New->getAnonDeclWithTypedefName();
2534      NamedDecl *Hidden = nullptr;
2535      if (OldTag && NewTag &&
2536          OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2537          !hasVisibleDefinition(OldTag, &Hidden)) {
2538        // There is a definition of this tag, but it is not visible. Use it
2539        // instead of our tag.
2540        New->setTypeForDecl(OldTD->getTypeForDecl());
2541        if (OldTD->isModed())
2542          New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2543                                      OldTD->getUnderlyingType());
2544        else
2545          New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2546  
2547        // Make the old tag definition visible.
2548        makeMergedDefinitionVisible(Hidden);
2549  
2550        // If this was an unscoped enumeration, yank all of its enumerators
2551        // out of the scope.
2552        if (isa<EnumDecl>(NewTag)) {
2553          Scope *EnumScope = getNonFieldDeclScope(S);
2554          for (auto *D : NewTag->decls()) {
2555            auto *ED = cast<EnumConstantDecl>(D);
2556            assert(EnumScope->isDeclScope(ED));
2557            EnumScope->RemoveDecl(ED);
2558            IdResolver.RemoveDecl(ED);
2559            ED->getLexicalDeclContext()->removeDecl(ED);
2560          }
2561        }
2562      }
2563    }
2564  
2565    // If the typedef types are not identical, reject them in all languages and
2566    // with any extensions enabled.
2567    if (isIncompatibleTypedef(Old, New))
2568      return;
2569  
2570    // The types match.  Link up the redeclaration chain and merge attributes if
2571    // the old declaration was a typedef.
2572    if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2573      New->setPreviousDecl(Typedef);
2574      mergeDeclAttributes(New, Old);
2575    }
2576  
2577    if (getLangOpts().MicrosoftExt)
2578      return;
2579  
2580    if (getLangOpts().CPlusPlus) {
2581      // C++ [dcl.typedef]p2:
2582      //   In a given non-class scope, a typedef specifier can be used to
2583      //   redefine the name of any type declared in that scope to refer
2584      //   to the type to which it already refers.
2585      if (!isa<CXXRecordDecl>(CurContext))
2586        return;
2587  
2588      // C++0x [dcl.typedef]p4:
2589      //   In a given class scope, a typedef specifier can be used to redefine
2590      //   any class-name declared in that scope that is not also a typedef-name
2591      //   to refer to the type to which it already refers.
2592      //
2593      // This wording came in via DR424, which was a correction to the
2594      // wording in DR56, which accidentally banned code like:
2595      //
2596      //   struct S {
2597      //     typedef struct A { } A;
2598      //   };
2599      //
2600      // in the C++03 standard. We implement the C++0x semantics, which
2601      // allow the above but disallow
2602      //
2603      //   struct S {
2604      //     typedef int I;
2605      //     typedef int I;
2606      //   };
2607      //
2608      // since that was the intent of DR56.
2609      if (!isa<TypedefNameDecl>(Old))
2610        return;
2611  
2612      Diag(New->getLocation(), diag::err_redefinition)
2613        << New->getDeclName();
2614      notePreviousDefinition(Old, New->getLocation());
2615      return New->setInvalidDecl();
2616    }
2617  
2618    // Modules always permit redefinition of typedefs, as does C11.
2619    if (getLangOpts().Modules || getLangOpts().C11)
2620      return;
2621  
2622    // If we have a redefinition of a typedef in C, emit a warning.  This warning
2623    // is normally mapped to an error, but can be controlled with
2624    // -Wtypedef-redefinition.  If either the original or the redefinition is
2625    // in a system header, don't emit this for compatibility with GCC.
2626    if (getDiagnostics().getSuppressSystemWarnings() &&
2627        // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2628        (Old->isImplicit() ||
2629         Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2630         Context.getSourceManager().isInSystemHeader(New->getLocation())))
2631      return;
2632  
2633    Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2634      << New->getDeclName();
2635    notePreviousDefinition(Old, New->getLocation());
2636  }
2637  
2638  /// DeclhasAttr - returns true if decl Declaration already has the target
2639  /// attribute.
DeclHasAttr(const Decl * D,const Attr * A)2640  static bool DeclHasAttr(const Decl *D, const Attr *A) {
2641    const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2642    const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2643    for (const auto *i : D->attrs())
2644      if (i->getKind() == A->getKind()) {
2645        if (Ann) {
2646          if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2647            return true;
2648          continue;
2649        }
2650        // FIXME: Don't hardcode this check
2651        if (OA && isa<OwnershipAttr>(i))
2652          return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2653        return true;
2654      }
2655  
2656    return false;
2657  }
2658  
isAttributeTargetADefinition(Decl * D)2659  static bool isAttributeTargetADefinition(Decl *D) {
2660    if (VarDecl *VD = dyn_cast<VarDecl>(D))
2661      return VD->isThisDeclarationADefinition();
2662    if (TagDecl *TD = dyn_cast<TagDecl>(D))
2663      return TD->isCompleteDefinition() || TD->isBeingDefined();
2664    return true;
2665  }
2666  
2667  /// Merge alignment attributes from \p Old to \p New, taking into account the
2668  /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2669  ///
2670  /// \return \c true if any attributes were added to \p New.
mergeAlignedAttrs(Sema & S,NamedDecl * New,Decl * Old)2671  static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2672    // Look for alignas attributes on Old, and pick out whichever attribute
2673    // specifies the strictest alignment requirement.
2674    AlignedAttr *OldAlignasAttr = nullptr;
2675    AlignedAttr *OldStrictestAlignAttr = nullptr;
2676    unsigned OldAlign = 0;
2677    for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2678      // FIXME: We have no way of representing inherited dependent alignments
2679      // in a case like:
2680      //   template<int A, int B> struct alignas(A) X;
2681      //   template<int A, int B> struct alignas(B) X {};
2682      // For now, we just ignore any alignas attributes which are not on the
2683      // definition in such a case.
2684      if (I->isAlignmentDependent())
2685        return false;
2686  
2687      if (I->isAlignas())
2688        OldAlignasAttr = I;
2689  
2690      unsigned Align = I->getAlignment(S.Context);
2691      if (Align > OldAlign) {
2692        OldAlign = Align;
2693        OldStrictestAlignAttr = I;
2694      }
2695    }
2696  
2697    // Look for alignas attributes on New.
2698    AlignedAttr *NewAlignasAttr = nullptr;
2699    unsigned NewAlign = 0;
2700    for (auto *I : New->specific_attrs<AlignedAttr>()) {
2701      if (I->isAlignmentDependent())
2702        return false;
2703  
2704      if (I->isAlignas())
2705        NewAlignasAttr = I;
2706  
2707      unsigned Align = I->getAlignment(S.Context);
2708      if (Align > NewAlign)
2709        NewAlign = Align;
2710    }
2711  
2712    if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2713      // Both declarations have 'alignas' attributes. We require them to match.
2714      // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2715      // fall short. (If two declarations both have alignas, they must both match
2716      // every definition, and so must match each other if there is a definition.)
2717  
2718      // If either declaration only contains 'alignas(0)' specifiers, then it
2719      // specifies the natural alignment for the type.
2720      if (OldAlign == 0 || NewAlign == 0) {
2721        QualType Ty;
2722        if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2723          Ty = VD->getType();
2724        else
2725          Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2726  
2727        if (OldAlign == 0)
2728          OldAlign = S.Context.getTypeAlign(Ty);
2729        if (NewAlign == 0)
2730          NewAlign = S.Context.getTypeAlign(Ty);
2731      }
2732  
2733      if (OldAlign != NewAlign) {
2734        S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2735          << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2736          << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2737        S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2738      }
2739    }
2740  
2741    if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2742      // C++11 [dcl.align]p6:
2743      //   if any declaration of an entity has an alignment-specifier,
2744      //   every defining declaration of that entity shall specify an
2745      //   equivalent alignment.
2746      // C11 6.7.5/7:
2747      //   If the definition of an object does not have an alignment
2748      //   specifier, any other declaration of that object shall also
2749      //   have no alignment specifier.
2750      S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2751        << OldAlignasAttr;
2752      S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2753        << OldAlignasAttr;
2754    }
2755  
2756    bool AnyAdded = false;
2757  
2758    // Ensure we have an attribute representing the strictest alignment.
2759    if (OldAlign > NewAlign) {
2760      AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2761      Clone->setInherited(true);
2762      New->addAttr(Clone);
2763      AnyAdded = true;
2764    }
2765  
2766    // Ensure we have an alignas attribute if the old declaration had one.
2767    if (OldAlignasAttr && !NewAlignasAttr &&
2768        !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2769      AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2770      Clone->setInherited(true);
2771      New->addAttr(Clone);
2772      AnyAdded = true;
2773    }
2774  
2775    return AnyAdded;
2776  }
2777  
2778  #define WANT_DECL_MERGE_LOGIC
2779  #include "clang/Sema/AttrParsedAttrImpl.inc"
2780  #undef WANT_DECL_MERGE_LOGIC
2781  
mergeDeclAttribute(Sema & S,NamedDecl * D,const InheritableAttr * Attr,Sema::AvailabilityMergeKind AMK)2782  static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2783                                 const InheritableAttr *Attr,
2784                                 Sema::AvailabilityMergeKind AMK) {
2785    // Diagnose any mutual exclusions between the attribute that we want to add
2786    // and attributes that already exist on the declaration.
2787    if (!DiagnoseMutualExclusions(S, D, Attr))
2788      return false;
2789  
2790    // This function copies an attribute Attr from a previous declaration to the
2791    // new declaration D if the new declaration doesn't itself have that attribute
2792    // yet or if that attribute allows duplicates.
2793    // If you're adding a new attribute that requires logic different from
2794    // "use explicit attribute on decl if present, else use attribute from
2795    // previous decl", for example if the attribute needs to be consistent
2796    // between redeclarations, you need to call a custom merge function here.
2797    InheritableAttr *NewAttr = nullptr;
2798    if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2799      NewAttr = S.mergeAvailabilityAttr(
2800          D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2801          AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2802          AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2803          AA->getPriority(), AA->getEnvironment());
2804    else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2805      NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2806    else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2807      NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2808    else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2809      NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2810    else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2811      NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2812    else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2813      NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2814    else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2815      NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2816                                  FA->getFirstArg());
2817    else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2818      NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2819    else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2820      NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2821    else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2822      NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2823                                         IA->getInheritanceModel());
2824    else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2825      NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2826                                        &S.Context.Idents.get(AA->getSpelling()));
2827    else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2828             (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2829              isa<CUDAGlobalAttr>(Attr))) {
2830      // CUDA target attributes are part of function signature for
2831      // overloading purposes and must not be merged.
2832      return false;
2833    } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2834      NewAttr = S.mergeMinSizeAttr(D, *MA);
2835    else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2836      NewAttr = S.Swift().mergeNameAttr(D, *SNA, SNA->getName());
2837    else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2838      NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2839    else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2840      NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2841    else if (isa<AlignedAttr>(Attr))
2842      // AlignedAttrs are handled separately, because we need to handle all
2843      // such attributes on a declaration at the same time.
2844      NewAttr = nullptr;
2845    else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2846             (AMK == Sema::AMK_Override ||
2847              AMK == Sema::AMK_ProtocolImplementation ||
2848              AMK == Sema::AMK_OptionalProtocolImplementation))
2849      NewAttr = nullptr;
2850    else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2851      NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2852    else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2853      NewAttr = S.Wasm().mergeImportModuleAttr(D, *IMA);
2854    else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2855      NewAttr = S.Wasm().mergeImportNameAttr(D, *INA);
2856    else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2857      NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2858    else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2859      NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2860    else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2861      NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2862    else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2863      NewAttr = S.HLSL().mergeNumThreadsAttr(D, *NT, NT->getX(), NT->getY(),
2864                                             NT->getZ());
2865    else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2866      NewAttr = S.HLSL().mergeShaderAttr(D, *SA, SA->getType());
2867    else if (isa<SuppressAttr>(Attr))
2868      // Do nothing. Each redeclaration should be suppressed separately.
2869      NewAttr = nullptr;
2870    else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2871      NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2872  
2873    if (NewAttr) {
2874      NewAttr->setInherited(true);
2875      D->addAttr(NewAttr);
2876      if (isa<MSInheritanceAttr>(NewAttr))
2877        S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2878      return true;
2879    }
2880  
2881    return false;
2882  }
2883  
getDefinition(const Decl * D)2884  static const NamedDecl *getDefinition(const Decl *D) {
2885    if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2886      return TD->getDefinition();
2887    if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2888      const VarDecl *Def = VD->getDefinition();
2889      if (Def)
2890        return Def;
2891      return VD->getActingDefinition();
2892    }
2893    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2894      const FunctionDecl *Def = nullptr;
2895      if (FD->isDefined(Def, true))
2896        return Def;
2897    }
2898    return nullptr;
2899  }
2900  
hasAttribute(const Decl * D,attr::Kind Kind)2901  static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2902    for (const auto *Attribute : D->attrs())
2903      if (Attribute->getKind() == Kind)
2904        return true;
2905    return false;
2906  }
2907  
2908  /// checkNewAttributesAfterDef - If we already have a definition, check that
2909  /// there are no new attributes in this declaration.
checkNewAttributesAfterDef(Sema & S,Decl * New,const Decl * Old)2910  static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2911    if (!New->hasAttrs())
2912      return;
2913  
2914    const NamedDecl *Def = getDefinition(Old);
2915    if (!Def || Def == New)
2916      return;
2917  
2918    AttrVec &NewAttributes = New->getAttrs();
2919    for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2920      const Attr *NewAttribute = NewAttributes[I];
2921  
2922      if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2923        if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2924          SkipBodyInfo SkipBody;
2925          S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2926  
2927          // If we're skipping this definition, drop the "alias" attribute.
2928          if (SkipBody.ShouldSkip) {
2929            NewAttributes.erase(NewAttributes.begin() + I);
2930            --E;
2931            continue;
2932          }
2933        } else {
2934          VarDecl *VD = cast<VarDecl>(New);
2935          unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2936                                  VarDecl::TentativeDefinition
2937                              ? diag::err_alias_after_tentative
2938                              : diag::err_redefinition;
2939          S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2940          if (Diag == diag::err_redefinition)
2941            S.notePreviousDefinition(Def, VD->getLocation());
2942          else
2943            S.Diag(Def->getLocation(), diag::note_previous_definition);
2944          VD->setInvalidDecl();
2945        }
2946        ++I;
2947        continue;
2948      }
2949  
2950      if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2951        // Tentative definitions are only interesting for the alias check above.
2952        if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2953          ++I;
2954          continue;
2955        }
2956      }
2957  
2958      if (hasAttribute(Def, NewAttribute->getKind())) {
2959        ++I;
2960        continue; // regular attr merging will take care of validating this.
2961      }
2962  
2963      if (isa<C11NoReturnAttr>(NewAttribute)) {
2964        // C's _Noreturn is allowed to be added to a function after it is defined.
2965        ++I;
2966        continue;
2967      } else if (isa<UuidAttr>(NewAttribute)) {
2968        // msvc will allow a subsequent definition to add an uuid to a class
2969        ++I;
2970        continue;
2971      } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2972        if (AA->isAlignas()) {
2973          // C++11 [dcl.align]p6:
2974          //   if any declaration of an entity has an alignment-specifier,
2975          //   every defining declaration of that entity shall specify an
2976          //   equivalent alignment.
2977          // C11 6.7.5/7:
2978          //   If the definition of an object does not have an alignment
2979          //   specifier, any other declaration of that object shall also
2980          //   have no alignment specifier.
2981          S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2982            << AA;
2983          S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2984            << AA;
2985          NewAttributes.erase(NewAttributes.begin() + I);
2986          --E;
2987          continue;
2988        }
2989      } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2990        // If there is a C definition followed by a redeclaration with this
2991        // attribute then there are two different definitions. In C++, prefer the
2992        // standard diagnostics.
2993        if (!S.getLangOpts().CPlusPlus) {
2994          S.Diag(NewAttribute->getLocation(),
2995                 diag::err_loader_uninitialized_redeclaration);
2996          S.Diag(Def->getLocation(), diag::note_previous_definition);
2997          NewAttributes.erase(NewAttributes.begin() + I);
2998          --E;
2999          continue;
3000        }
3001      } else if (isa<SelectAnyAttr>(NewAttribute) &&
3002                 cast<VarDecl>(New)->isInline() &&
3003                 !cast<VarDecl>(New)->isInlineSpecified()) {
3004        // Don't warn about applying selectany to implicitly inline variables.
3005        // Older compilers and language modes would require the use of selectany
3006        // to make such variables inline, and it would have no effect if we
3007        // honored it.
3008        ++I;
3009        continue;
3010      } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3011        // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3012        // declarations after definitions.
3013        ++I;
3014        continue;
3015      }
3016  
3017      S.Diag(NewAttribute->getLocation(),
3018             diag::warn_attribute_precede_definition);
3019      S.Diag(Def->getLocation(), diag::note_previous_definition);
3020      NewAttributes.erase(NewAttributes.begin() + I);
3021      --E;
3022    }
3023  }
3024  
diagnoseMissingConstinit(Sema & S,const VarDecl * InitDecl,const ConstInitAttr * CIAttr,bool AttrBeforeInit)3025  static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3026                                       const ConstInitAttr *CIAttr,
3027                                       bool AttrBeforeInit) {
3028    SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3029  
3030    // Figure out a good way to write this specifier on the old declaration.
3031    // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3032    // enough of the attribute list spelling information to extract that without
3033    // heroics.
3034    std::string SuitableSpelling;
3035    if (S.getLangOpts().CPlusPlus20)
3036      SuitableSpelling = std::string(
3037          S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
3038    if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3039      SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3040          InsertLoc, {tok::l_square, tok::l_square,
3041                      S.PP.getIdentifierInfo("clang"), tok::coloncolon,
3042                      S.PP.getIdentifierInfo("require_constant_initialization"),
3043                      tok::r_square, tok::r_square}));
3044    if (SuitableSpelling.empty())
3045      SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3046          InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
3047                      S.PP.getIdentifierInfo("require_constant_initialization"),
3048                      tok::r_paren, tok::r_paren}));
3049    if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3050      SuitableSpelling = "constinit";
3051    if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3052      SuitableSpelling = "[[clang::require_constant_initialization]]";
3053    if (SuitableSpelling.empty())
3054      SuitableSpelling = "__attribute__((require_constant_initialization))";
3055    SuitableSpelling += " ";
3056  
3057    if (AttrBeforeInit) {
3058      // extern constinit int a;
3059      // int a = 0; // error (missing 'constinit'), accepted as extension
3060      assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3061      S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3062          << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3063      S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3064    } else {
3065      // int a = 0;
3066      // constinit extern int a; // error (missing 'constinit')
3067      S.Diag(CIAttr->getLocation(),
3068             CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3069                                   : diag::warn_require_const_init_added_too_late)
3070          << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3071      S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3072          << CIAttr->isConstinit()
3073          << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3074    }
3075  }
3076  
mergeDeclAttributes(NamedDecl * New,Decl * Old,AvailabilityMergeKind AMK)3077  void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
3078                                 AvailabilityMergeKind AMK) {
3079    if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3080      UsedAttr *NewAttr = OldAttr->clone(Context);
3081      NewAttr->setInherited(true);
3082      New->addAttr(NewAttr);
3083    }
3084    if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3085      RetainAttr *NewAttr = OldAttr->clone(Context);
3086      NewAttr->setInherited(true);
3087      New->addAttr(NewAttr);
3088    }
3089  
3090    if (!Old->hasAttrs() && !New->hasAttrs())
3091      return;
3092  
3093    // [dcl.constinit]p1:
3094    //   If the [constinit] specifier is applied to any declaration of a
3095    //   variable, it shall be applied to the initializing declaration.
3096    const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3097    const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3098    if (bool(OldConstInit) != bool(NewConstInit)) {
3099      const auto *OldVD = cast<VarDecl>(Old);
3100      auto *NewVD = cast<VarDecl>(New);
3101  
3102      // Find the initializing declaration. Note that we might not have linked
3103      // the new declaration into the redeclaration chain yet.
3104      const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3105      if (!InitDecl &&
3106          (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3107        InitDecl = NewVD;
3108  
3109      if (InitDecl == NewVD) {
3110        // This is the initializing declaration. If it would inherit 'constinit',
3111        // that's ill-formed. (Note that we do not apply this to the attribute
3112        // form).
3113        if (OldConstInit && OldConstInit->isConstinit())
3114          diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3115                                   /*AttrBeforeInit=*/true);
3116      } else if (NewConstInit) {
3117        // This is the first time we've been told that this declaration should
3118        // have a constant initializer. If we already saw the initializing
3119        // declaration, this is too late.
3120        if (InitDecl && InitDecl != NewVD) {
3121          diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3122                                   /*AttrBeforeInit=*/false);
3123          NewVD->dropAttr<ConstInitAttr>();
3124        }
3125      }
3126    }
3127  
3128    // Attributes declared post-definition are currently ignored.
3129    checkNewAttributesAfterDef(*this, New, Old);
3130  
3131    if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3132      if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3133        if (!OldA->isEquivalent(NewA)) {
3134          // This redeclaration changes __asm__ label.
3135          Diag(New->getLocation(), diag::err_different_asm_label);
3136          Diag(OldA->getLocation(), diag::note_previous_declaration);
3137        }
3138      } else if (Old->isUsed()) {
3139        // This redeclaration adds an __asm__ label to a declaration that has
3140        // already been ODR-used.
3141        Diag(New->getLocation(), diag::err_late_asm_label_name)
3142          << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3143      }
3144    }
3145  
3146    // Re-declaration cannot add abi_tag's.
3147    if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3148      if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3149        for (const auto &NewTag : NewAbiTagAttr->tags()) {
3150          if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3151            Diag(NewAbiTagAttr->getLocation(),
3152                 diag::err_new_abi_tag_on_redeclaration)
3153                << NewTag;
3154            Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3155          }
3156        }
3157      } else {
3158        Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3159        Diag(Old->getLocation(), diag::note_previous_declaration);
3160      }
3161    }
3162  
3163    // This redeclaration adds a section attribute.
3164    if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3165      if (auto *VD = dyn_cast<VarDecl>(New)) {
3166        if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3167          Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3168          Diag(Old->getLocation(), diag::note_previous_declaration);
3169        }
3170      }
3171    }
3172  
3173    // Redeclaration adds code-seg attribute.
3174    const auto *NewCSA = New->getAttr<CodeSegAttr>();
3175    if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3176        !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3177      Diag(New->getLocation(), diag::warn_mismatched_section)
3178           << 0 /*codeseg*/;
3179      Diag(Old->getLocation(), diag::note_previous_declaration);
3180    }
3181  
3182    if (!Old->hasAttrs())
3183      return;
3184  
3185    bool foundAny = New->hasAttrs();
3186  
3187    // Ensure that any moving of objects within the allocated map is done before
3188    // we process them.
3189    if (!foundAny) New->setAttrs(AttrVec());
3190  
3191    for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3192      // Ignore deprecated/unavailable/availability attributes if requested.
3193      AvailabilityMergeKind LocalAMK = AMK_None;
3194      if (isa<DeprecatedAttr>(I) ||
3195          isa<UnavailableAttr>(I) ||
3196          isa<AvailabilityAttr>(I)) {
3197        switch (AMK) {
3198        case AMK_None:
3199          continue;
3200  
3201        case AMK_Redeclaration:
3202        case AMK_Override:
3203        case AMK_ProtocolImplementation:
3204        case AMK_OptionalProtocolImplementation:
3205          LocalAMK = AMK;
3206          break;
3207        }
3208      }
3209  
3210      // Already handled.
3211      if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3212        continue;
3213  
3214      if (mergeDeclAttribute(*this, New, I, LocalAMK))
3215        foundAny = true;
3216    }
3217  
3218    if (mergeAlignedAttrs(*this, New, Old))
3219      foundAny = true;
3220  
3221    if (!foundAny) New->dropAttrs();
3222  }
3223  
3224  /// mergeParamDeclAttributes - Copy attributes from the old parameter
3225  /// to the new one.
mergeParamDeclAttributes(ParmVarDecl * newDecl,const ParmVarDecl * oldDecl,Sema & S)3226  static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3227                                       const ParmVarDecl *oldDecl,
3228                                       Sema &S) {
3229    // C++11 [dcl.attr.depend]p2:
3230    //   The first declaration of a function shall specify the
3231    //   carries_dependency attribute for its declarator-id if any declaration
3232    //   of the function specifies the carries_dependency attribute.
3233    const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3234    if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3235      S.Diag(CDA->getLocation(),
3236             diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3237      // Find the first declaration of the parameter.
3238      // FIXME: Should we build redeclaration chains for function parameters?
3239      const FunctionDecl *FirstFD =
3240        cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3241      const ParmVarDecl *FirstVD =
3242        FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3243      S.Diag(FirstVD->getLocation(),
3244             diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3245    }
3246  
3247    // HLSL parameter declarations for inout and out must match between
3248    // declarations. In HLSL inout and out are ambiguous at the call site, but
3249    // have different calling behavior, so you cannot overload a method based on a
3250    // difference between inout and out annotations.
3251    if (S.getLangOpts().HLSL) {
3252      const auto *NDAttr = newDecl->getAttr<HLSLParamModifierAttr>();
3253      const auto *ODAttr = oldDecl->getAttr<HLSLParamModifierAttr>();
3254      // We don't need to cover the case where one declaration doesn't have an
3255      // attribute. The only possible case there is if one declaration has an `in`
3256      // attribute and the other declaration has no attribute. This case is
3257      // allowed since parameters are `in` by default.
3258      if (NDAttr && ODAttr &&
3259          NDAttr->getSpellingListIndex() != ODAttr->getSpellingListIndex()) {
3260        S.Diag(newDecl->getLocation(), diag::err_hlsl_param_qualifier_mismatch)
3261            << NDAttr << newDecl;
3262        S.Diag(oldDecl->getLocation(), diag::note_previous_declaration_as)
3263            << ODAttr;
3264      }
3265    }
3266  
3267    if (!oldDecl->hasAttrs())
3268      return;
3269  
3270    bool foundAny = newDecl->hasAttrs();
3271  
3272    // Ensure that any moving of objects within the allocated map is
3273    // done before we process them.
3274    if (!foundAny) newDecl->setAttrs(AttrVec());
3275  
3276    for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3277      if (!DeclHasAttr(newDecl, I)) {
3278        InheritableAttr *newAttr =
3279          cast<InheritableParamAttr>(I->clone(S.Context));
3280        newAttr->setInherited(true);
3281        newDecl->addAttr(newAttr);
3282        foundAny = true;
3283      }
3284    }
3285  
3286    if (!foundAny) newDecl->dropAttrs();
3287  }
3288  
EquivalentArrayTypes(QualType Old,QualType New,const ASTContext & Ctx)3289  static bool EquivalentArrayTypes(QualType Old, QualType New,
3290                                   const ASTContext &Ctx) {
3291  
3292    auto NoSizeInfo = [&Ctx](QualType Ty) {
3293      if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3294        return true;
3295      if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3296        return VAT->getSizeModifier() == ArraySizeModifier::Star;
3297      return false;
3298    };
3299  
3300    // `type[]` is equivalent to `type *` and `type[*]`.
3301    if (NoSizeInfo(Old) && NoSizeInfo(New))
3302      return true;
3303  
3304    // Don't try to compare VLA sizes, unless one of them has the star modifier.
3305    if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3306      const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3307      const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3308      if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3309          (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3310        return false;
3311      return true;
3312    }
3313  
3314    // Only compare size, ignore Size modifiers and CVR.
3315    if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3316      return Ctx.getAsConstantArrayType(Old)->getSize() ==
3317             Ctx.getAsConstantArrayType(New)->getSize();
3318    }
3319  
3320    // Don't try to compare dependent sized array
3321    if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3322      return true;
3323    }
3324  
3325    return Old == New;
3326  }
3327  
mergeParamDeclTypes(ParmVarDecl * NewParam,const ParmVarDecl * OldParam,Sema & S)3328  static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3329                                  const ParmVarDecl *OldParam,
3330                                  Sema &S) {
3331    if (auto Oldnullability = OldParam->getType()->getNullability()) {
3332      if (auto Newnullability = NewParam->getType()->getNullability()) {
3333        if (*Oldnullability != *Newnullability) {
3334          S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3335            << DiagNullabilityKind(
3336                 *Newnullability,
3337                 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3338                  != 0))
3339            << DiagNullabilityKind(
3340                 *Oldnullability,
3341                 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3342                  != 0));
3343          S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3344        }
3345      } else {
3346        QualType NewT = NewParam->getType();
3347        NewT = S.Context.getAttributedType(
3348                           AttributedType::getNullabilityAttrKind(*Oldnullability),
3349                           NewT, NewT);
3350        NewParam->setType(NewT);
3351      }
3352    }
3353    const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3354    const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3355    if (OldParamDT && NewParamDT &&
3356        OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3357      QualType OldParamOT = OldParamDT->getOriginalType();
3358      QualType NewParamOT = NewParamDT->getOriginalType();
3359      if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3360        S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3361            << NewParam << NewParamOT;
3362        S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3363            << OldParamOT;
3364      }
3365    }
3366  }
3367  
3368  namespace {
3369  
3370  /// Used in MergeFunctionDecl to keep track of function parameters in
3371  /// C.
3372  struct GNUCompatibleParamWarning {
3373    ParmVarDecl *OldParm;
3374    ParmVarDecl *NewParm;
3375    QualType PromotedType;
3376  };
3377  
3378  } // end anonymous namespace
3379  
3380  // Determine whether the previous declaration was a definition, implicit
3381  // declaration, or a declaration.
3382  template <typename T>
3383  static std::pair<diag::kind, SourceLocation>
getNoteDiagForInvalidRedeclaration(const T * Old,const T * New)3384  getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3385    diag::kind PrevDiag;
3386    SourceLocation OldLocation = Old->getLocation();
3387    if (Old->isThisDeclarationADefinition())
3388      PrevDiag = diag::note_previous_definition;
3389    else if (Old->isImplicit()) {
3390      PrevDiag = diag::note_previous_implicit_declaration;
3391      if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3392        if (FD->getBuiltinID())
3393          PrevDiag = diag::note_previous_builtin_declaration;
3394      }
3395      if (OldLocation.isInvalid())
3396        OldLocation = New->getLocation();
3397    } else
3398      PrevDiag = diag::note_previous_declaration;
3399    return std::make_pair(PrevDiag, OldLocation);
3400  }
3401  
3402  /// canRedefineFunction - checks if a function can be redefined. Currently,
3403  /// only extern inline functions can be redefined, and even then only in
3404  /// GNU89 mode.
canRedefineFunction(const FunctionDecl * FD,const LangOptions & LangOpts)3405  static bool canRedefineFunction(const FunctionDecl *FD,
3406                                  const LangOptions& LangOpts) {
3407    return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3408            !LangOpts.CPlusPlus &&
3409            FD->isInlineSpecified() &&
3410            FD->getStorageClass() == SC_Extern);
3411  }
3412  
getCallingConvAttributedType(QualType T) const3413  const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3414    const AttributedType *AT = T->getAs<AttributedType>();
3415    while (AT && !AT->isCallingConv())
3416      AT = AT->getModifiedType()->getAs<AttributedType>();
3417    return AT;
3418  }
3419  
3420  template <typename T>
haveIncompatibleLanguageLinkages(const T * Old,const T * New)3421  static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3422    const DeclContext *DC = Old->getDeclContext();
3423    if (DC->isRecord())
3424      return false;
3425  
3426    LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3427    if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3428      return true;
3429    if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3430      return true;
3431    return false;
3432  }
3433  
isExternC(T * D)3434  template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
isExternC(VarTemplateDecl *)3435  static bool isExternC(VarTemplateDecl *) { return false; }
isExternC(FunctionTemplateDecl *)3436  static bool isExternC(FunctionTemplateDecl *) { return false; }
3437  
3438  /// Check whether a redeclaration of an entity introduced by a
3439  /// using-declaration is valid, given that we know it's not an overload
3440  /// (nor a hidden tag declaration).
3441  template<typename ExpectedDecl>
checkUsingShadowRedecl(Sema & S,UsingShadowDecl * OldS,ExpectedDecl * New)3442  static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3443                                     ExpectedDecl *New) {
3444    // C++11 [basic.scope.declarative]p4:
3445    //   Given a set of declarations in a single declarative region, each of
3446    //   which specifies the same unqualified name,
3447    //   -- they shall all refer to the same entity, or all refer to functions
3448    //      and function templates; or
3449    //   -- exactly one declaration shall declare a class name or enumeration
3450    //      name that is not a typedef name and the other declarations shall all
3451    //      refer to the same variable or enumerator, or all refer to functions
3452    //      and function templates; in this case the class name or enumeration
3453    //      name is hidden (3.3.10).
3454  
3455    // C++11 [namespace.udecl]p14:
3456    //   If a function declaration in namespace scope or block scope has the
3457    //   same name and the same parameter-type-list as a function introduced
3458    //   by a using-declaration, and the declarations do not declare the same
3459    //   function, the program is ill-formed.
3460  
3461    auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3462    if (Old &&
3463        !Old->getDeclContext()->getRedeclContext()->Equals(
3464            New->getDeclContext()->getRedeclContext()) &&
3465        !(isExternC(Old) && isExternC(New)))
3466      Old = nullptr;
3467  
3468    if (!Old) {
3469      S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3470      S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3471      S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3472      return true;
3473    }
3474    return false;
3475  }
3476  
hasIdenticalPassObjectSizeAttrs(const FunctionDecl * A,const FunctionDecl * B)3477  static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3478                                              const FunctionDecl *B) {
3479    assert(A->getNumParams() == B->getNumParams());
3480  
3481    auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3482      const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3483      const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3484      if (AttrA == AttrB)
3485        return true;
3486      return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3487             AttrA->isDynamic() == AttrB->isDynamic();
3488    };
3489  
3490    return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3491  }
3492  
3493  /// If necessary, adjust the semantic declaration context for a qualified
3494  /// declaration to name the correct inline namespace within the qualifier.
adjustDeclContextForDeclaratorDecl(DeclaratorDecl * NewD,DeclaratorDecl * OldD)3495  static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3496                                                 DeclaratorDecl *OldD) {
3497    // The only case where we need to update the DeclContext is when
3498    // redeclaration lookup for a qualified name finds a declaration
3499    // in an inline namespace within the context named by the qualifier:
3500    //
3501    //   inline namespace N { int f(); }
3502    //   int ::f(); // Sema DC needs adjusting from :: to N::.
3503    //
3504    // For unqualified declarations, the semantic context *can* change
3505    // along the redeclaration chain (for local extern declarations,
3506    // extern "C" declarations, and friend declarations in particular).
3507    if (!NewD->getQualifier())
3508      return;
3509  
3510    // NewD is probably already in the right context.
3511    auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3512    auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3513    if (NamedDC->Equals(SemaDC))
3514      return;
3515  
3516    assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3517            NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3518           "unexpected context for redeclaration");
3519  
3520    auto *LexDC = NewD->getLexicalDeclContext();
3521    auto FixSemaDC = [=](NamedDecl *D) {
3522      if (!D)
3523        return;
3524      D->setDeclContext(SemaDC);
3525      D->setLexicalDeclContext(LexDC);
3526    };
3527  
3528    FixSemaDC(NewD);
3529    if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3530      FixSemaDC(FD->getDescribedFunctionTemplate());
3531    else if (auto *VD = dyn_cast<VarDecl>(NewD))
3532      FixSemaDC(VD->getDescribedVarTemplate());
3533  }
3534  
MergeFunctionDecl(FunctionDecl * New,NamedDecl * & OldD,Scope * S,bool MergeTypeWithOld,bool NewDeclIsDefn)3535  bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,
3536                               bool MergeTypeWithOld, bool NewDeclIsDefn) {
3537    // Verify the old decl was also a function.
3538    FunctionDecl *Old = OldD->getAsFunction();
3539    if (!Old) {
3540      if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3541        if (New->getFriendObjectKind()) {
3542          Diag(New->getLocation(), diag::err_using_decl_friend);
3543          Diag(Shadow->getTargetDecl()->getLocation(),
3544               diag::note_using_decl_target);
3545          Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3546              << 0;
3547          return true;
3548        }
3549  
3550        // Check whether the two declarations might declare the same function or
3551        // function template.
3552        if (FunctionTemplateDecl *NewTemplate =
3553                New->getDescribedFunctionTemplate()) {
3554          if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3555                                                           NewTemplate))
3556            return true;
3557          OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3558                           ->getAsFunction();
3559        } else {
3560          if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3561            return true;
3562          OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3563        }
3564      } else {
3565        Diag(New->getLocation(), diag::err_redefinition_different_kind)
3566          << New->getDeclName();
3567        notePreviousDefinition(OldD, New->getLocation());
3568        return true;
3569      }
3570    }
3571  
3572    // If the old declaration was found in an inline namespace and the new
3573    // declaration was qualified, update the DeclContext to match.
3574    adjustDeclContextForDeclaratorDecl(New, Old);
3575  
3576    // If the old declaration is invalid, just give up here.
3577    if (Old->isInvalidDecl())
3578      return true;
3579  
3580    // Disallow redeclaration of some builtins.
3581    if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3582      Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3583      Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3584          << Old << Old->getType();
3585      return true;
3586    }
3587  
3588    diag::kind PrevDiag;
3589    SourceLocation OldLocation;
3590    std::tie(PrevDiag, OldLocation) =
3591        getNoteDiagForInvalidRedeclaration(Old, New);
3592  
3593    // Don't complain about this if we're in GNU89 mode and the old function
3594    // is an extern inline function.
3595    // Don't complain about specializations. They are not supposed to have
3596    // storage classes.
3597    if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3598        New->getStorageClass() == SC_Static &&
3599        Old->hasExternalFormalLinkage() &&
3600        !New->getTemplateSpecializationInfo() &&
3601        !canRedefineFunction(Old, getLangOpts())) {
3602      if (getLangOpts().MicrosoftExt) {
3603        Diag(New->getLocation(), diag::ext_static_non_static) << New;
3604        Diag(OldLocation, PrevDiag) << Old << Old->getType();
3605      } else {
3606        Diag(New->getLocation(), diag::err_static_non_static) << New;
3607        Diag(OldLocation, PrevDiag) << Old << Old->getType();
3608        return true;
3609      }
3610    }
3611  
3612    if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3613      if (!Old->hasAttr<InternalLinkageAttr>()) {
3614        Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3615            << ILA;
3616        Diag(Old->getLocation(), diag::note_previous_declaration);
3617        New->dropAttr<InternalLinkageAttr>();
3618      }
3619  
3620    if (auto *EA = New->getAttr<ErrorAttr>()) {
3621      if (!Old->hasAttr<ErrorAttr>()) {
3622        Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3623        Diag(Old->getLocation(), diag::note_previous_declaration);
3624        New->dropAttr<ErrorAttr>();
3625      }
3626    }
3627  
3628    if (CheckRedeclarationInModule(New, Old))
3629      return true;
3630  
3631    if (!getLangOpts().CPlusPlus) {
3632      bool OldOvl = Old->hasAttr<OverloadableAttr>();
3633      if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3634        Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3635          << New << OldOvl;
3636  
3637        // Try our best to find a decl that actually has the overloadable
3638        // attribute for the note. In most cases (e.g. programs with only one
3639        // broken declaration/definition), this won't matter.
3640        //
3641        // FIXME: We could do this if we juggled some extra state in
3642        // OverloadableAttr, rather than just removing it.
3643        const Decl *DiagOld = Old;
3644        if (OldOvl) {
3645          auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3646            const auto *A = D->getAttr<OverloadableAttr>();
3647            return A && !A->isImplicit();
3648          });
3649          // If we've implicitly added *all* of the overloadable attrs to this
3650          // chain, emitting a "previous redecl" note is pointless.
3651          DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3652        }
3653  
3654        if (DiagOld)
3655          Diag(DiagOld->getLocation(),
3656               diag::note_attribute_overloadable_prev_overload)
3657            << OldOvl;
3658  
3659        if (OldOvl)
3660          New->addAttr(OverloadableAttr::CreateImplicit(Context));
3661        else
3662          New->dropAttr<OverloadableAttr>();
3663      }
3664    }
3665  
3666    // It is not permitted to redeclare an SME function with different SME
3667    // attributes.
3668    if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
3669      Diag(New->getLocation(), diag::err_sme_attr_mismatch)
3670          << New->getType() << Old->getType();
3671      Diag(OldLocation, diag::note_previous_declaration);
3672      return true;
3673    }
3674  
3675    // If a function is first declared with a calling convention, but is later
3676    // declared or defined without one, all following decls assume the calling
3677    // convention of the first.
3678    //
3679    // It's OK if a function is first declared without a calling convention,
3680    // but is later declared or defined with the default calling convention.
3681    //
3682    // To test if either decl has an explicit calling convention, we look for
3683    // AttributedType sugar nodes on the type as written.  If they are missing or
3684    // were canonicalized away, we assume the calling convention was implicit.
3685    //
3686    // Note also that we DO NOT return at this point, because we still have
3687    // other tests to run.
3688    QualType OldQType = Context.getCanonicalType(Old->getType());
3689    QualType NewQType = Context.getCanonicalType(New->getType());
3690    const FunctionType *OldType = cast<FunctionType>(OldQType);
3691    const FunctionType *NewType = cast<FunctionType>(NewQType);
3692    FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3693    FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3694    bool RequiresAdjustment = false;
3695  
3696    if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3697      FunctionDecl *First = Old->getFirstDecl();
3698      const FunctionType *FT =
3699          First->getType().getCanonicalType()->castAs<FunctionType>();
3700      FunctionType::ExtInfo FI = FT->getExtInfo();
3701      bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3702      if (!NewCCExplicit) {
3703        // Inherit the CC from the previous declaration if it was specified
3704        // there but not here.
3705        NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3706        RequiresAdjustment = true;
3707      } else if (Old->getBuiltinID()) {
3708        // Builtin attribute isn't propagated to the new one yet at this point,
3709        // so we check if the old one is a builtin.
3710  
3711        // Calling Conventions on a Builtin aren't really useful and setting a
3712        // default calling convention and cdecl'ing some builtin redeclarations is
3713        // common, so warn and ignore the calling convention on the redeclaration.
3714        Diag(New->getLocation(), diag::warn_cconv_unsupported)
3715            << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3716            << (int)CallingConventionIgnoredReason::BuiltinFunction;
3717        NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3718        RequiresAdjustment = true;
3719      } else {
3720        // Calling conventions aren't compatible, so complain.
3721        bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3722        Diag(New->getLocation(), diag::err_cconv_change)
3723          << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3724          << !FirstCCExplicit
3725          << (!FirstCCExplicit ? "" :
3726              FunctionType::getNameForCallConv(FI.getCC()));
3727  
3728        // Put the note on the first decl, since it is the one that matters.
3729        Diag(First->getLocation(), diag::note_previous_declaration);
3730        return true;
3731      }
3732    }
3733  
3734    // FIXME: diagnose the other way around?
3735    if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3736      NewTypeInfo = NewTypeInfo.withNoReturn(true);
3737      RequiresAdjustment = true;
3738    }
3739  
3740    // Merge regparm attribute.
3741    if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3742        OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3743      if (NewTypeInfo.getHasRegParm()) {
3744        Diag(New->getLocation(), diag::err_regparm_mismatch)
3745          << NewType->getRegParmType()
3746          << OldType->getRegParmType();
3747        Diag(OldLocation, diag::note_previous_declaration);
3748        return true;
3749      }
3750  
3751      NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3752      RequiresAdjustment = true;
3753    }
3754  
3755    // Merge ns_returns_retained attribute.
3756    if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3757      if (NewTypeInfo.getProducesResult()) {
3758        Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3759            << "'ns_returns_retained'";
3760        Diag(OldLocation, diag::note_previous_declaration);
3761        return true;
3762      }
3763  
3764      NewTypeInfo = NewTypeInfo.withProducesResult(true);
3765      RequiresAdjustment = true;
3766    }
3767  
3768    if (OldTypeInfo.getNoCallerSavedRegs() !=
3769        NewTypeInfo.getNoCallerSavedRegs()) {
3770      if (NewTypeInfo.getNoCallerSavedRegs()) {
3771        AnyX86NoCallerSavedRegistersAttr *Attr =
3772          New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3773        Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3774        Diag(OldLocation, diag::note_previous_declaration);
3775        return true;
3776      }
3777  
3778      NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3779      RequiresAdjustment = true;
3780    }
3781  
3782    if (RequiresAdjustment) {
3783      const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3784      AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3785      New->setType(QualType(AdjustedType, 0));
3786      NewQType = Context.getCanonicalType(New->getType());
3787    }
3788  
3789    // If this redeclaration makes the function inline, we may need to add it to
3790    // UndefinedButUsed.
3791    if (!Old->isInlined() && New->isInlined() &&
3792        !New->hasAttr<GNUInlineAttr>() &&
3793        !getLangOpts().GNUInline &&
3794        Old->isUsed(false) &&
3795        !Old->isDefined() && !New->isThisDeclarationADefinition())
3796      UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3797                                             SourceLocation()));
3798  
3799    // If this redeclaration makes it newly gnu_inline, we don't want to warn
3800    // about it.
3801    if (New->hasAttr<GNUInlineAttr>() &&
3802        Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3803      UndefinedButUsed.erase(Old->getCanonicalDecl());
3804    }
3805  
3806    // If pass_object_size params don't match up perfectly, this isn't a valid
3807    // redeclaration.
3808    if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3809        !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3810      Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3811          << New->getDeclName();
3812      Diag(OldLocation, PrevDiag) << Old << Old->getType();
3813      return true;
3814    }
3815  
3816    QualType OldQTypeForComparison = OldQType;
3817    if (Context.hasAnyFunctionEffects()) {
3818      const auto OldFX = Old->getFunctionEffects();
3819      const auto NewFX = New->getFunctionEffects();
3820      if (OldFX != NewFX) {
3821        const auto Diffs = FunctionEffectDifferences(OldFX, NewFX);
3822        for (const auto &Diff : Diffs) {
3823          if (Diff.shouldDiagnoseRedeclaration(*Old, OldFX, *New, NewFX)) {
3824            Diag(New->getLocation(),
3825                 diag::warn_mismatched_func_effect_redeclaration)
3826                << Diff.effectName();
3827            Diag(Old->getLocation(), diag::note_previous_declaration);
3828          }
3829        }
3830        // Following a warning, we could skip merging effects from the previous
3831        // declaration, but that would trigger an additional "conflicting types"
3832        // error.
3833        if (const auto *NewFPT = NewQType->getAs<FunctionProtoType>()) {
3834          FunctionEffectSet::Conflicts MergeErrs;
3835          FunctionEffectSet MergedFX =
3836              FunctionEffectSet::getUnion(OldFX, NewFX, MergeErrs);
3837          if (!MergeErrs.empty())
3838            diagnoseFunctionEffectMergeConflicts(MergeErrs, New->getLocation(),
3839                                                 Old->getLocation());
3840  
3841          FunctionProtoType::ExtProtoInfo EPI = NewFPT->getExtProtoInfo();
3842          EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
3843          QualType ModQT = Context.getFunctionType(NewFPT->getReturnType(),
3844                                                   NewFPT->getParamTypes(), EPI);
3845  
3846          New->setType(ModQT);
3847          NewQType = New->getType();
3848  
3849          // Revise OldQTForComparison to include the merged effects,
3850          // so as not to fail due to differences later.
3851          if (const auto *OldFPT = OldQType->getAs<FunctionProtoType>()) {
3852            EPI = OldFPT->getExtProtoInfo();
3853            EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
3854            OldQTypeForComparison = Context.getFunctionType(
3855                OldFPT->getReturnType(), OldFPT->getParamTypes(), EPI);
3856          }
3857        }
3858      }
3859    }
3860  
3861    if (getLangOpts().CPlusPlus) {
3862      OldQType = Context.getCanonicalType(Old->getType());
3863      NewQType = Context.getCanonicalType(New->getType());
3864  
3865      // Go back to the type source info to compare the declared return types,
3866      // per C++1y [dcl.type.auto]p13:
3867      //   Redeclarations or specializations of a function or function template
3868      //   with a declared return type that uses a placeholder type shall also
3869      //   use that placeholder, not a deduced type.
3870      QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3871      QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3872      if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3873          canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3874                                         OldDeclaredReturnType)) {
3875        QualType ResQT;
3876        if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3877            OldDeclaredReturnType->isObjCObjectPointerType())
3878          // FIXME: This does the wrong thing for a deduced return type.
3879          ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3880        if (ResQT.isNull()) {
3881          if (New->isCXXClassMember() && New->isOutOfLine())
3882            Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3883                << New << New->getReturnTypeSourceRange();
3884          else
3885            Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3886                << New->getReturnTypeSourceRange();
3887          Diag(OldLocation, PrevDiag) << Old << Old->getType()
3888                                      << Old->getReturnTypeSourceRange();
3889          return true;
3890        }
3891        else
3892          NewQType = ResQT;
3893      }
3894  
3895      QualType OldReturnType = OldType->getReturnType();
3896      QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3897      if (OldReturnType != NewReturnType) {
3898        // If this function has a deduced return type and has already been
3899        // defined, copy the deduced value from the old declaration.
3900        AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3901        if (OldAT && OldAT->isDeduced()) {
3902          QualType DT = OldAT->getDeducedType();
3903          if (DT.isNull()) {
3904            New->setType(SubstAutoTypeDependent(New->getType()));
3905            NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3906          } else {
3907            New->setType(SubstAutoType(New->getType(), DT));
3908            NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3909          }
3910        }
3911      }
3912  
3913      const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3914      CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3915      if (OldMethod && NewMethod) {
3916        // Preserve triviality.
3917        NewMethod->setTrivial(OldMethod->isTrivial());
3918  
3919        // MSVC allows explicit template specialization at class scope:
3920        // 2 CXXMethodDecls referring to the same function will be injected.
3921        // We don't want a redeclaration error.
3922        bool IsClassScopeExplicitSpecialization =
3923                                OldMethod->isFunctionTemplateSpecialization() &&
3924                                NewMethod->isFunctionTemplateSpecialization();
3925        bool isFriend = NewMethod->getFriendObjectKind();
3926  
3927        if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3928            !IsClassScopeExplicitSpecialization) {
3929          //    -- Member function declarations with the same name and the
3930          //       same parameter types cannot be overloaded if any of them
3931          //       is a static member function declaration.
3932          if (OldMethod->isStatic() != NewMethod->isStatic()) {
3933            Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3934            Diag(OldLocation, PrevDiag) << Old << Old->getType();
3935            return true;
3936          }
3937  
3938          // C++ [class.mem]p1:
3939          //   [...] A member shall not be declared twice in the
3940          //   member-specification, except that a nested class or member
3941          //   class template can be declared and then later defined.
3942          if (!inTemplateInstantiation()) {
3943            unsigned NewDiag;
3944            if (isa<CXXConstructorDecl>(OldMethod))
3945              NewDiag = diag::err_constructor_redeclared;
3946            else if (isa<CXXDestructorDecl>(NewMethod))
3947              NewDiag = diag::err_destructor_redeclared;
3948            else if (isa<CXXConversionDecl>(NewMethod))
3949              NewDiag = diag::err_conv_function_redeclared;
3950            else
3951              NewDiag = diag::err_member_redeclared;
3952  
3953            Diag(New->getLocation(), NewDiag);
3954          } else {
3955            Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3956              << New << New->getType();
3957          }
3958          Diag(OldLocation, PrevDiag) << Old << Old->getType();
3959          return true;
3960  
3961        // Complain if this is an explicit declaration of a special
3962        // member that was initially declared implicitly.
3963        //
3964        // As an exception, it's okay to befriend such methods in order
3965        // to permit the implicit constructor/destructor/operator calls.
3966        } else if (OldMethod->isImplicit()) {
3967          if (isFriend) {
3968            NewMethod->setImplicit();
3969          } else {
3970            Diag(NewMethod->getLocation(),
3971                 diag::err_definition_of_implicitly_declared_member)
3972                << New << llvm::to_underlying(getSpecialMember(OldMethod));
3973            return true;
3974          }
3975        } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3976          Diag(NewMethod->getLocation(),
3977               diag::err_definition_of_explicitly_defaulted_member)
3978              << llvm::to_underlying(getSpecialMember(OldMethod));
3979          return true;
3980        }
3981      }
3982  
3983      // C++1z [over.load]p2
3984      //   Certain function declarations cannot be overloaded:
3985      //     -- Function declarations that differ only in the return type,
3986      //        the exception specification, or both cannot be overloaded.
3987  
3988      // Check the exception specifications match. This may recompute the type of
3989      // both Old and New if it resolved exception specifications, so grab the
3990      // types again after this. Because this updates the type, we do this before
3991      // any of the other checks below, which may update the "de facto" NewQType
3992      // but do not necessarily update the type of New.
3993      if (CheckEquivalentExceptionSpec(Old, New))
3994        return true;
3995  
3996      // C++11 [dcl.attr.noreturn]p1:
3997      //   The first declaration of a function shall specify the noreturn
3998      //   attribute if any declaration of that function specifies the noreturn
3999      //   attribute.
4000      if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4001        if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4002          Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4003              << NRA;
4004          Diag(Old->getLocation(), diag::note_previous_declaration);
4005        }
4006  
4007      // C++11 [dcl.attr.depend]p2:
4008      //   The first declaration of a function shall specify the
4009      //   carries_dependency attribute for its declarator-id if any declaration
4010      //   of the function specifies the carries_dependency attribute.
4011      const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4012      if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4013        Diag(CDA->getLocation(),
4014             diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4015        Diag(Old->getFirstDecl()->getLocation(),
4016             diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4017      }
4018  
4019      // (C++98 8.3.5p3):
4020      //   All declarations for a function shall agree exactly in both the
4021      //   return type and the parameter-type-list.
4022      // We also want to respect all the extended bits except noreturn.
4023  
4024      // noreturn should now match unless the old type info didn't have it.
4025      if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4026        auto *OldType = OldQTypeForComparison->castAs<FunctionProtoType>();
4027        const FunctionType *OldTypeForComparison
4028          = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
4029        OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4030        assert(OldQTypeForComparison.isCanonical());
4031      }
4032  
4033      if (haveIncompatibleLanguageLinkages(Old, New)) {
4034        // As a special case, retain the language linkage from previous
4035        // declarations of a friend function as an extension.
4036        //
4037        // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4038        // and is useful because there's otherwise no way to specify language
4039        // linkage within class scope.
4040        //
4041        // Check cautiously as the friend object kind isn't yet complete.
4042        if (New->getFriendObjectKind() != Decl::FOK_None) {
4043          Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4044          Diag(OldLocation, PrevDiag);
4045        } else {
4046          Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4047          Diag(OldLocation, PrevDiag);
4048          return true;
4049        }
4050      }
4051  
4052      // If the function types are compatible, merge the declarations. Ignore the
4053      // exception specifier because it was already checked above in
4054      // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4055      // about incompatible types under -fms-compatibility.
4056      if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
4057                                                           NewQType))
4058        return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4059  
4060      // If the types are imprecise (due to dependent constructs in friends or
4061      // local extern declarations), it's OK if they differ. We'll check again
4062      // during instantiation.
4063      if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4064        return false;
4065  
4066      // Fall through for conflicting redeclarations and redefinitions.
4067    }
4068  
4069    // C: Function types need to be compatible, not identical. This handles
4070    // duplicate function decls like "void f(int); void f(enum X);" properly.
4071    if (!getLangOpts().CPlusPlus) {
4072      // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4073      // type is specified by a function definition that contains a (possibly
4074      // empty) identifier list, both shall agree in the number of parameters
4075      // and the type of each parameter shall be compatible with the type that
4076      // results from the application of default argument promotions to the
4077      // type of the corresponding identifier. ...
4078      // This cannot be handled by ASTContext::typesAreCompatible() because that
4079      // doesn't know whether the function type is for a definition or not when
4080      // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4081      // we need to cover here is that the number of arguments agree as the
4082      // default argument promotion rules were already checked by
4083      // ASTContext::typesAreCompatible().
4084      if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4085          Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4086        if (Old->hasInheritedPrototype())
4087          Old = Old->getCanonicalDecl();
4088        Diag(New->getLocation(), diag::err_conflicting_types) << New;
4089        Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4090        return true;
4091      }
4092  
4093      // If we are merging two functions where only one of them has a prototype,
4094      // we may have enough information to decide to issue a diagnostic that the
4095      // function without a prototype will change behavior in C23. This handles
4096      // cases like:
4097      //   void i(); void i(int j);
4098      //   void i(int j); void i();
4099      //   void i(); void i(int j) {}
4100      // See ActOnFinishFunctionBody() for other cases of the behavior change
4101      // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4102      // type without a prototype.
4103      if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4104          !New->isImplicit() && !Old->isImplicit()) {
4105        const FunctionDecl *WithProto, *WithoutProto;
4106        if (New->hasWrittenPrototype()) {
4107          WithProto = New;
4108          WithoutProto = Old;
4109        } else {
4110          WithProto = Old;
4111          WithoutProto = New;
4112        }
4113  
4114        if (WithProto->getNumParams() != 0) {
4115          if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4116            // The one without the prototype will be changing behavior in C23, so
4117            // warn about that one so long as it's a user-visible declaration.
4118            bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4119            if (WithoutProto == New)
4120              IsWithoutProtoADef = NewDeclIsDefn;
4121            else
4122              IsWithProtoADef = NewDeclIsDefn;
4123            Diag(WithoutProto->getLocation(),
4124                 diag::warn_non_prototype_changes_behavior)
4125                << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4126                << (WithoutProto == Old) << IsWithProtoADef;
4127  
4128            // The reason the one without the prototype will be changing behavior
4129            // is because of the one with the prototype, so note that so long as
4130            // it's a user-visible declaration. There is one exception to this:
4131            // when the new declaration is a definition without a prototype, the
4132            // old declaration with a prototype is not the cause of the issue,
4133            // and that does not need to be noted because the one with a
4134            // prototype will not change behavior in C23.
4135            if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4136                !IsWithoutProtoADef)
4137              Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4138          }
4139        }
4140      }
4141  
4142      if (Context.typesAreCompatible(OldQType, NewQType)) {
4143        const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4144        const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4145        const FunctionProtoType *OldProto = nullptr;
4146        if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4147            (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4148          // The old declaration provided a function prototype, but the
4149          // new declaration does not. Merge in the prototype.
4150          assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4151          NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
4152                                             OldProto->getParamTypes(),
4153                                             OldProto->getExtProtoInfo());
4154          New->setType(NewQType);
4155          New->setHasInheritedPrototype();
4156  
4157          // Synthesize parameters with the same types.
4158          SmallVector<ParmVarDecl *, 16> Params;
4159          for (const auto &ParamType : OldProto->param_types()) {
4160            ParmVarDecl *Param = ParmVarDecl::Create(
4161                Context, New, SourceLocation(), SourceLocation(), nullptr,
4162                ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4163            Param->setScopeInfo(0, Params.size());
4164            Param->setImplicit();
4165            Params.push_back(Param);
4166          }
4167  
4168          New->setParams(Params);
4169        }
4170  
4171        return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4172      }
4173    }
4174  
4175    // Check if the function types are compatible when pointer size address
4176    // spaces are ignored.
4177    if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4178      return false;
4179  
4180    // GNU C permits a K&R definition to follow a prototype declaration
4181    // if the declared types of the parameters in the K&R definition
4182    // match the types in the prototype declaration, even when the
4183    // promoted types of the parameters from the K&R definition differ
4184    // from the types in the prototype. GCC then keeps the types from
4185    // the prototype.
4186    //
4187    // If a variadic prototype is followed by a non-variadic K&R definition,
4188    // the K&R definition becomes variadic.  This is sort of an edge case, but
4189    // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4190    // C99 6.9.1p8.
4191    if (!getLangOpts().CPlusPlus &&
4192        Old->hasPrototype() && !New->hasPrototype() &&
4193        New->getType()->getAs<FunctionProtoType>() &&
4194        Old->getNumParams() == New->getNumParams()) {
4195      SmallVector<QualType, 16> ArgTypes;
4196      SmallVector<GNUCompatibleParamWarning, 16> Warnings;
4197      const FunctionProtoType *OldProto
4198        = Old->getType()->getAs<FunctionProtoType>();
4199      const FunctionProtoType *NewProto
4200        = New->getType()->getAs<FunctionProtoType>();
4201  
4202      // Determine whether this is the GNU C extension.
4203      QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4204                                                 NewProto->getReturnType());
4205      bool LooseCompatible = !MergedReturn.isNull();
4206      for (unsigned Idx = 0, End = Old->getNumParams();
4207           LooseCompatible && Idx != End; ++Idx) {
4208        ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4209        ParmVarDecl *NewParm = New->getParamDecl(Idx);
4210        if (Context.typesAreCompatible(OldParm->getType(),
4211                                       NewProto->getParamType(Idx))) {
4212          ArgTypes.push_back(NewParm->getType());
4213        } else if (Context.typesAreCompatible(OldParm->getType(),
4214                                              NewParm->getType(),
4215                                              /*CompareUnqualified=*/true)) {
4216          GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4217                                             NewProto->getParamType(Idx) };
4218          Warnings.push_back(Warn);
4219          ArgTypes.push_back(NewParm->getType());
4220        } else
4221          LooseCompatible = false;
4222      }
4223  
4224      if (LooseCompatible) {
4225        for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4226          Diag(Warnings[Warn].NewParm->getLocation(),
4227               diag::ext_param_promoted_not_compatible_with_prototype)
4228            << Warnings[Warn].PromotedType
4229            << Warnings[Warn].OldParm->getType();
4230          if (Warnings[Warn].OldParm->getLocation().isValid())
4231            Diag(Warnings[Warn].OldParm->getLocation(),
4232                 diag::note_previous_declaration);
4233        }
4234  
4235        if (MergeTypeWithOld)
4236          New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4237                                               OldProto->getExtProtoInfo()));
4238        return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4239      }
4240  
4241      // Fall through to diagnose conflicting types.
4242    }
4243  
4244    // A function that has already been declared has been redeclared or
4245    // defined with a different type; show an appropriate diagnostic.
4246  
4247    // If the previous declaration was an implicitly-generated builtin
4248    // declaration, then at the very least we should use a specialized note.
4249    unsigned BuiltinID;
4250    if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4251      // If it's actually a library-defined builtin function like 'malloc'
4252      // or 'printf', just warn about the incompatible redeclaration.
4253      if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4254        Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4255        Diag(OldLocation, diag::note_previous_builtin_declaration)
4256          << Old << Old->getType();
4257        return false;
4258      }
4259  
4260      PrevDiag = diag::note_previous_builtin_declaration;
4261    }
4262  
4263    Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4264    Diag(OldLocation, PrevDiag) << Old << Old->getType();
4265    return true;
4266  }
4267  
MergeCompatibleFunctionDecls(FunctionDecl * New,FunctionDecl * Old,Scope * S,bool MergeTypeWithOld)4268  bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4269                                          Scope *S, bool MergeTypeWithOld) {
4270    // Merge the attributes
4271    mergeDeclAttributes(New, Old);
4272  
4273    // Merge "pure" flag.
4274    if (Old->isPureVirtual())
4275      New->setIsPureVirtual();
4276  
4277    // Merge "used" flag.
4278    if (Old->getMostRecentDecl()->isUsed(false))
4279      New->setIsUsed();
4280  
4281    // Merge attributes from the parameters.  These can mismatch with K&R
4282    // declarations.
4283    if (New->getNumParams() == Old->getNumParams())
4284        for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4285          ParmVarDecl *NewParam = New->getParamDecl(i);
4286          ParmVarDecl *OldParam = Old->getParamDecl(i);
4287          mergeParamDeclAttributes(NewParam, OldParam, *this);
4288          mergeParamDeclTypes(NewParam, OldParam, *this);
4289        }
4290  
4291    if (getLangOpts().CPlusPlus)
4292      return MergeCXXFunctionDecl(New, Old, S);
4293  
4294    // Merge the function types so the we get the composite types for the return
4295    // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4296    // was visible.
4297    QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4298    if (!Merged.isNull() && MergeTypeWithOld)
4299      New->setType(Merged);
4300  
4301    return false;
4302  }
4303  
mergeObjCMethodDecls(ObjCMethodDecl * newMethod,ObjCMethodDecl * oldMethod)4304  void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4305                                  ObjCMethodDecl *oldMethod) {
4306    // Merge the attributes, including deprecated/unavailable
4307    AvailabilityMergeKind MergeKind =
4308        isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4309            ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
4310                                       : AMK_ProtocolImplementation)
4311            : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4312                                                             : AMK_Override;
4313  
4314    mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4315  
4316    // Merge attributes from the parameters.
4317    ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4318                                         oe = oldMethod->param_end();
4319    for (ObjCMethodDecl::param_iterator
4320           ni = newMethod->param_begin(), ne = newMethod->param_end();
4321         ni != ne && oi != oe; ++ni, ++oi)
4322      mergeParamDeclAttributes(*ni, *oi, *this);
4323  
4324    ObjC().CheckObjCMethodOverride(newMethod, oldMethod);
4325  }
4326  
diagnoseVarDeclTypeMismatch(Sema & S,VarDecl * New,VarDecl * Old)4327  static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4328    assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4329  
4330    S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4331           ? diag::err_redefinition_different_type
4332           : diag::err_redeclaration_different_type)
4333      << New->getDeclName() << New->getType() << Old->getType();
4334  
4335    diag::kind PrevDiag;
4336    SourceLocation OldLocation;
4337    std::tie(PrevDiag, OldLocation)
4338      = getNoteDiagForInvalidRedeclaration(Old, New);
4339    S.Diag(OldLocation, PrevDiag) << Old << Old->getType();
4340    New->setInvalidDecl();
4341  }
4342  
MergeVarDeclTypes(VarDecl * New,VarDecl * Old,bool MergeTypeWithOld)4343  void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4344                               bool MergeTypeWithOld) {
4345    if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4346      return;
4347  
4348    QualType MergedT;
4349    if (getLangOpts().CPlusPlus) {
4350      if (New->getType()->isUndeducedType()) {
4351        // We don't know what the new type is until the initializer is attached.
4352        return;
4353      } else if (Context.hasSameType(New->getType(), Old->getType())) {
4354        // These could still be something that needs exception specs checked.
4355        return MergeVarDeclExceptionSpecs(New, Old);
4356      }
4357      // C++ [basic.link]p10:
4358      //   [...] the types specified by all declarations referring to a given
4359      //   object or function shall be identical, except that declarations for an
4360      //   array object can specify array types that differ by the presence or
4361      //   absence of a major array bound (8.3.4).
4362      else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4363        const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4364        const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4365  
4366        // We are merging a variable declaration New into Old. If it has an array
4367        // bound, and that bound differs from Old's bound, we should diagnose the
4368        // mismatch.
4369        if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4370          for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4371               PrevVD = PrevVD->getPreviousDecl()) {
4372            QualType PrevVDTy = PrevVD->getType();
4373            if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4374              continue;
4375  
4376            if (!Context.hasSameType(New->getType(), PrevVDTy))
4377              return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4378          }
4379        }
4380  
4381        if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4382          if (Context.hasSameType(OldArray->getElementType(),
4383                                  NewArray->getElementType()))
4384            MergedT = New->getType();
4385        }
4386        // FIXME: Check visibility. New is hidden but has a complete type. If New
4387        // has no array bound, it should not inherit one from Old, if Old is not
4388        // visible.
4389        else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4390          if (Context.hasSameType(OldArray->getElementType(),
4391                                  NewArray->getElementType()))
4392            MergedT = Old->getType();
4393        }
4394      }
4395      else if (New->getType()->isObjCObjectPointerType() &&
4396                 Old->getType()->isObjCObjectPointerType()) {
4397        MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4398                                                Old->getType());
4399      }
4400    } else {
4401      // C 6.2.7p2:
4402      //   All declarations that refer to the same object or function shall have
4403      //   compatible type.
4404      MergedT = Context.mergeTypes(New->getType(), Old->getType());
4405    }
4406    if (MergedT.isNull()) {
4407      // It's OK if we couldn't merge types if either type is dependent, for a
4408      // block-scope variable. In other cases (static data members of class
4409      // templates, variable templates, ...), we require the types to be
4410      // equivalent.
4411      // FIXME: The C++ standard doesn't say anything about this.
4412      if ((New->getType()->isDependentType() ||
4413           Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4414        // If the old type was dependent, we can't merge with it, so the new type
4415        // becomes dependent for now. We'll reproduce the original type when we
4416        // instantiate the TypeSourceInfo for the variable.
4417        if (!New->getType()->isDependentType() && MergeTypeWithOld)
4418          New->setType(Context.DependentTy);
4419        return;
4420      }
4421      return diagnoseVarDeclTypeMismatch(*this, New, Old);
4422    }
4423  
4424    // Don't actually update the type on the new declaration if the old
4425    // declaration was an extern declaration in a different scope.
4426    if (MergeTypeWithOld)
4427      New->setType(MergedT);
4428  }
4429  
mergeTypeWithPrevious(Sema & S,VarDecl * NewVD,VarDecl * OldVD,LookupResult & Previous)4430  static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4431                                    LookupResult &Previous) {
4432    // C11 6.2.7p4:
4433    //   For an identifier with internal or external linkage declared
4434    //   in a scope in which a prior declaration of that identifier is
4435    //   visible, if the prior declaration specifies internal or
4436    //   external linkage, the type of the identifier at the later
4437    //   declaration becomes the composite type.
4438    //
4439    // If the variable isn't visible, we do not merge with its type.
4440    if (Previous.isShadowed())
4441      return false;
4442  
4443    if (S.getLangOpts().CPlusPlus) {
4444      // C++11 [dcl.array]p3:
4445      //   If there is a preceding declaration of the entity in the same
4446      //   scope in which the bound was specified, an omitted array bound
4447      //   is taken to be the same as in that earlier declaration.
4448      return NewVD->isPreviousDeclInSameBlockScope() ||
4449             (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4450              !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4451    } else {
4452      // If the old declaration was function-local, don't merge with its
4453      // type unless we're in the same function.
4454      return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4455             OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4456    }
4457  }
4458  
MergeVarDecl(VarDecl * New,LookupResult & Previous)4459  void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4460    // If the new decl is already invalid, don't do any other checking.
4461    if (New->isInvalidDecl())
4462      return;
4463  
4464    if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4465      return;
4466  
4467    VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4468  
4469    // Verify the old decl was also a variable or variable template.
4470    VarDecl *Old = nullptr;
4471    VarTemplateDecl *OldTemplate = nullptr;
4472    if (Previous.isSingleResult()) {
4473      if (NewTemplate) {
4474        OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4475        Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4476  
4477        if (auto *Shadow =
4478                dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4479          if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4480            return New->setInvalidDecl();
4481      } else {
4482        Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4483  
4484        if (auto *Shadow =
4485                dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4486          if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4487            return New->setInvalidDecl();
4488      }
4489    }
4490    if (!Old) {
4491      Diag(New->getLocation(), diag::err_redefinition_different_kind)
4492          << New->getDeclName();
4493      notePreviousDefinition(Previous.getRepresentativeDecl(),
4494                             New->getLocation());
4495      return New->setInvalidDecl();
4496    }
4497  
4498    // If the old declaration was found in an inline namespace and the new
4499    // declaration was qualified, update the DeclContext to match.
4500    adjustDeclContextForDeclaratorDecl(New, Old);
4501  
4502    // Ensure the template parameters are compatible.
4503    if (NewTemplate &&
4504        !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4505                                        OldTemplate->getTemplateParameters(),
4506                                        /*Complain=*/true, TPL_TemplateMatch))
4507      return New->setInvalidDecl();
4508  
4509    // C++ [class.mem]p1:
4510    //   A member shall not be declared twice in the member-specification [...]
4511    //
4512    // Here, we need only consider static data members.
4513    if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4514      Diag(New->getLocation(), diag::err_duplicate_member)
4515        << New->getIdentifier();
4516      Diag(Old->getLocation(), diag::note_previous_declaration);
4517      New->setInvalidDecl();
4518    }
4519  
4520    mergeDeclAttributes(New, Old);
4521    // Warn if an already-defined variable is made a weak_import in a subsequent
4522    // declaration
4523    if (New->hasAttr<WeakImportAttr>())
4524      for (auto *D = Old; D; D = D->getPreviousDecl()) {
4525        if (D->isThisDeclarationADefinition() != VarDecl::DeclarationOnly) {
4526          Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4527          Diag(D->getLocation(), diag::note_previous_definition);
4528          // Remove weak_import attribute on new declaration.
4529          New->dropAttr<WeakImportAttr>();
4530          break;
4531        }
4532      }
4533  
4534    if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4535      if (!Old->hasAttr<InternalLinkageAttr>()) {
4536        Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4537            << ILA;
4538        Diag(Old->getLocation(), diag::note_previous_declaration);
4539        New->dropAttr<InternalLinkageAttr>();
4540      }
4541  
4542    // Merge the types.
4543    VarDecl *MostRecent = Old->getMostRecentDecl();
4544    if (MostRecent != Old) {
4545      MergeVarDeclTypes(New, MostRecent,
4546                        mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4547      if (New->isInvalidDecl())
4548        return;
4549    }
4550  
4551    MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4552    if (New->isInvalidDecl())
4553      return;
4554  
4555    diag::kind PrevDiag;
4556    SourceLocation OldLocation;
4557    std::tie(PrevDiag, OldLocation) =
4558        getNoteDiagForInvalidRedeclaration(Old, New);
4559  
4560    // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4561    if (New->getStorageClass() == SC_Static &&
4562        !New->isStaticDataMember() &&
4563        Old->hasExternalFormalLinkage()) {
4564      if (getLangOpts().MicrosoftExt) {
4565        Diag(New->getLocation(), diag::ext_static_non_static)
4566            << New->getDeclName();
4567        Diag(OldLocation, PrevDiag);
4568      } else {
4569        Diag(New->getLocation(), diag::err_static_non_static)
4570            << New->getDeclName();
4571        Diag(OldLocation, PrevDiag);
4572        return New->setInvalidDecl();
4573      }
4574    }
4575    // C99 6.2.2p4:
4576    //   For an identifier declared with the storage-class specifier
4577    //   extern in a scope in which a prior declaration of that
4578    //   identifier is visible,23) if the prior declaration specifies
4579    //   internal or external linkage, the linkage of the identifier at
4580    //   the later declaration is the same as the linkage specified at
4581    //   the prior declaration. If no prior declaration is visible, or
4582    //   if the prior declaration specifies no linkage, then the
4583    //   identifier has external linkage.
4584    if (New->hasExternalStorage() && Old->hasLinkage())
4585      /* Okay */;
4586    else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4587             !New->isStaticDataMember() &&
4588             Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4589      Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4590      Diag(OldLocation, PrevDiag);
4591      return New->setInvalidDecl();
4592    }
4593  
4594    // Check if extern is followed by non-extern and vice-versa.
4595    if (New->hasExternalStorage() &&
4596        !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4597      Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4598      Diag(OldLocation, PrevDiag);
4599      return New->setInvalidDecl();
4600    }
4601    if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4602        !New->hasExternalStorage()) {
4603      Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4604      Diag(OldLocation, PrevDiag);
4605      return New->setInvalidDecl();
4606    }
4607  
4608    if (CheckRedeclarationInModule(New, Old))
4609      return;
4610  
4611    // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4612  
4613    // FIXME: The test for external storage here seems wrong? We still
4614    // need to check for mismatches.
4615    if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4616        // Don't complain about out-of-line definitions of static members.
4617        !(Old->getLexicalDeclContext()->isRecord() &&
4618          !New->getLexicalDeclContext()->isRecord())) {
4619      Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4620      Diag(OldLocation, PrevDiag);
4621      return New->setInvalidDecl();
4622    }
4623  
4624    if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4625      if (VarDecl *Def = Old->getDefinition()) {
4626        // C++1z [dcl.fcn.spec]p4:
4627        //   If the definition of a variable appears in a translation unit before
4628        //   its first declaration as inline, the program is ill-formed.
4629        Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4630        Diag(Def->getLocation(), diag::note_previous_definition);
4631      }
4632    }
4633  
4634    // If this redeclaration makes the variable inline, we may need to add it to
4635    // UndefinedButUsed.
4636    if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4637        !Old->getDefinition() && !New->isThisDeclarationADefinition())
4638      UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4639                                             SourceLocation()));
4640  
4641    if (New->getTLSKind() != Old->getTLSKind()) {
4642      if (!Old->getTLSKind()) {
4643        Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4644        Diag(OldLocation, PrevDiag);
4645      } else if (!New->getTLSKind()) {
4646        Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4647        Diag(OldLocation, PrevDiag);
4648      } else {
4649        // Do not allow redeclaration to change the variable between requiring
4650        // static and dynamic initialization.
4651        // FIXME: GCC allows this, but uses the TLS keyword on the first
4652        // declaration to determine the kind. Do we need to be compatible here?
4653        Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4654          << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4655        Diag(OldLocation, PrevDiag);
4656      }
4657    }
4658  
4659    // C++ doesn't have tentative definitions, so go right ahead and check here.
4660    if (getLangOpts().CPlusPlus) {
4661      if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4662          Old->getCanonicalDecl()->isConstexpr()) {
4663        // This definition won't be a definition any more once it's been merged.
4664        Diag(New->getLocation(),
4665             diag::warn_deprecated_redundant_constexpr_static_def);
4666      } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4667        VarDecl *Def = Old->getDefinition();
4668        if (Def && checkVarDeclRedefinition(Def, New))
4669          return;
4670      }
4671    }
4672  
4673    if (haveIncompatibleLanguageLinkages(Old, New)) {
4674      Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4675      Diag(OldLocation, PrevDiag);
4676      New->setInvalidDecl();
4677      return;
4678    }
4679  
4680    // Merge "used" flag.
4681    if (Old->getMostRecentDecl()->isUsed(false))
4682      New->setIsUsed();
4683  
4684    // Keep a chain of previous declarations.
4685    New->setPreviousDecl(Old);
4686    if (NewTemplate)
4687      NewTemplate->setPreviousDecl(OldTemplate);
4688  
4689    // Inherit access appropriately.
4690    New->setAccess(Old->getAccess());
4691    if (NewTemplate)
4692      NewTemplate->setAccess(New->getAccess());
4693  
4694    if (Old->isInline())
4695      New->setImplicitlyInline();
4696  }
4697  
notePreviousDefinition(const NamedDecl * Old,SourceLocation New)4698  void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4699    SourceManager &SrcMgr = getSourceManager();
4700    auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4701    auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4702    auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4703    auto FOld = SrcMgr.getFileEntryRefForID(FOldDecLoc.first);
4704    auto &HSI = PP.getHeaderSearchInfo();
4705    StringRef HdrFilename =
4706        SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4707  
4708    auto noteFromModuleOrInclude = [&](Module *Mod,
4709                                       SourceLocation IncLoc) -> bool {
4710      // Redefinition errors with modules are common with non modular mapped
4711      // headers, example: a non-modular header H in module A that also gets
4712      // included directly in a TU. Pointing twice to the same header/definition
4713      // is confusing, try to get better diagnostics when modules is on.
4714      if (IncLoc.isValid()) {
4715        if (Mod) {
4716          Diag(IncLoc, diag::note_redefinition_modules_same_file)
4717              << HdrFilename.str() << Mod->getFullModuleName();
4718          if (!Mod->DefinitionLoc.isInvalid())
4719            Diag(Mod->DefinitionLoc, diag::note_defined_here)
4720                << Mod->getFullModuleName();
4721        } else {
4722          Diag(IncLoc, diag::note_redefinition_include_same_file)
4723              << HdrFilename.str();
4724        }
4725        return true;
4726      }
4727  
4728      return false;
4729    };
4730  
4731    // Is it the same file and same offset? Provide more information on why
4732    // this leads to a redefinition error.
4733    if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4734      SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4735      SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4736      bool EmittedDiag =
4737          noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4738      EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4739  
4740      // If the header has no guards, emit a note suggesting one.
4741      if (FOld && !HSI.isFileMultipleIncludeGuarded(*FOld))
4742        Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4743  
4744      if (EmittedDiag)
4745        return;
4746    }
4747  
4748    // Redefinition coming from different files or couldn't do better above.
4749    if (Old->getLocation().isValid())
4750      Diag(Old->getLocation(), diag::note_previous_definition);
4751  }
4752  
checkVarDeclRedefinition(VarDecl * Old,VarDecl * New)4753  bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4754    if (!hasVisibleDefinition(Old) &&
4755        (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
4756         isa<VarTemplateSpecializationDecl>(New) ||
4757         New->getDescribedVarTemplate() || New->getNumTemplateParameterLists() ||
4758         New->getDeclContext()->isDependentContext())) {
4759      // The previous definition is hidden, and multiple definitions are
4760      // permitted (in separate TUs). Demote this to a declaration.
4761      New->demoteThisDefinitionToDeclaration();
4762  
4763      // Make the canonical definition visible.
4764      if (auto *OldTD = Old->getDescribedVarTemplate())
4765        makeMergedDefinitionVisible(OldTD);
4766      makeMergedDefinitionVisible(Old);
4767      return false;
4768    } else {
4769      Diag(New->getLocation(), diag::err_redefinition) << New;
4770      notePreviousDefinition(Old, New->getLocation());
4771      New->setInvalidDecl();
4772      return true;
4773    }
4774  }
4775  
ParsedFreeStandingDeclSpec(Scope * S,AccessSpecifier AS,DeclSpec & DS,const ParsedAttributesView & DeclAttrs,RecordDecl * & AnonRecord)4776  Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
4777                                         DeclSpec &DS,
4778                                         const ParsedAttributesView &DeclAttrs,
4779                                         RecordDecl *&AnonRecord) {
4780    return ParsedFreeStandingDeclSpec(
4781        S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
4782  }
4783  
4784  // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4785  // disambiguate entities defined in different scopes.
4786  // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4787  // compatibility.
4788  // We will pick our mangling number depending on which version of MSVC is being
4789  // targeted.
getMSManglingNumber(const LangOptions & LO,Scope * S)4790  static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4791    return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4792               ? S->getMSCurManglingNumber()
4793               : S->getMSLastManglingNumber();
4794  }
4795  
handleTagNumbering(const TagDecl * Tag,Scope * TagScope)4796  void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4797    if (!Context.getLangOpts().CPlusPlus)
4798      return;
4799  
4800    if (isa<CXXRecordDecl>(Tag->getParent())) {
4801      // If this tag is the direct child of a class, number it if
4802      // it is anonymous.
4803      if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4804        return;
4805      MangleNumberingContext &MCtx =
4806          Context.getManglingNumberContext(Tag->getParent());
4807      Context.setManglingNumber(
4808          Tag, MCtx.getManglingNumber(
4809                   Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4810      return;
4811    }
4812  
4813    // If this tag isn't a direct child of a class, number it if it is local.
4814    MangleNumberingContext *MCtx;
4815    Decl *ManglingContextDecl;
4816    std::tie(MCtx, ManglingContextDecl) =
4817        getCurrentMangleNumberContext(Tag->getDeclContext());
4818    if (MCtx) {
4819      Context.setManglingNumber(
4820          Tag, MCtx->getManglingNumber(
4821                   Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4822    }
4823  }
4824  
4825  namespace {
4826  struct NonCLikeKind {
4827    enum {
4828      None,
4829      BaseClass,
4830      DefaultMemberInit,
4831      Lambda,
4832      Friend,
4833      OtherMember,
4834      Invalid,
4835    } Kind = None;
4836    SourceRange Range;
4837  
operator bool__anondd060bcd1011::NonCLikeKind4838    explicit operator bool() { return Kind != None; }
4839  };
4840  }
4841  
4842  /// Determine whether a class is C-like, according to the rules of C++
4843  /// [dcl.typedef] for anonymous classes with typedef names for linkage.
getNonCLikeKindForAnonymousStruct(const CXXRecordDecl * RD)4844  static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4845    if (RD->isInvalidDecl())
4846      return {NonCLikeKind::Invalid, {}};
4847  
4848    // C++ [dcl.typedef]p9: [P1766R1]
4849    //   An unnamed class with a typedef name for linkage purposes shall not
4850    //
4851    //    -- have any base classes
4852    if (RD->getNumBases())
4853      return {NonCLikeKind::BaseClass,
4854              SourceRange(RD->bases_begin()->getBeginLoc(),
4855                          RD->bases_end()[-1].getEndLoc())};
4856    bool Invalid = false;
4857    for (Decl *D : RD->decls()) {
4858      // Don't complain about things we already diagnosed.
4859      if (D->isInvalidDecl()) {
4860        Invalid = true;
4861        continue;
4862      }
4863  
4864      //  -- have any [...] default member initializers
4865      if (auto *FD = dyn_cast<FieldDecl>(D)) {
4866        if (FD->hasInClassInitializer()) {
4867          auto *Init = FD->getInClassInitializer();
4868          return {NonCLikeKind::DefaultMemberInit,
4869                  Init ? Init->getSourceRange() : D->getSourceRange()};
4870        }
4871        continue;
4872      }
4873  
4874      // FIXME: We don't allow friend declarations. This violates the wording of
4875      // P1766, but not the intent.
4876      if (isa<FriendDecl>(D))
4877        return {NonCLikeKind::Friend, D->getSourceRange()};
4878  
4879      //  -- declare any members other than non-static data members, member
4880      //     enumerations, or member classes,
4881      if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4882          isa<EnumDecl>(D))
4883        continue;
4884      auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4885      if (!MemberRD) {
4886        if (D->isImplicit())
4887          continue;
4888        return {NonCLikeKind::OtherMember, D->getSourceRange()};
4889      }
4890  
4891      //  -- contain a lambda-expression,
4892      if (MemberRD->isLambda())
4893        return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4894  
4895      //  and all member classes shall also satisfy these requirements
4896      //  (recursively).
4897      if (MemberRD->isThisDeclarationADefinition()) {
4898        if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4899          return Kind;
4900      }
4901    }
4902  
4903    return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4904  }
4905  
setTagNameForLinkagePurposes(TagDecl * TagFromDeclSpec,TypedefNameDecl * NewTD)4906  void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4907                                          TypedefNameDecl *NewTD) {
4908    if (TagFromDeclSpec->isInvalidDecl())
4909      return;
4910  
4911    // Do nothing if the tag already has a name for linkage purposes.
4912    if (TagFromDeclSpec->hasNameForLinkage())
4913      return;
4914  
4915    // A well-formed anonymous tag must always be a TagUseKind::Definition.
4916    assert(TagFromDeclSpec->isThisDeclarationADefinition());
4917  
4918    // The type must match the tag exactly;  no qualifiers allowed.
4919    if (!Context.hasSameType(NewTD->getUnderlyingType(),
4920                             Context.getTagDeclType(TagFromDeclSpec))) {
4921      if (getLangOpts().CPlusPlus)
4922        Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4923      return;
4924    }
4925  
4926    // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4927    //   An unnamed class with a typedef name for linkage purposes shall [be
4928    //   C-like].
4929    //
4930    // FIXME: Also diagnose if we've already computed the linkage. That ideally
4931    // shouldn't happen, but there are constructs that the language rule doesn't
4932    // disallow for which we can't reasonably avoid computing linkage early.
4933    const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4934    NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4935                               : NonCLikeKind();
4936    bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4937    if (NonCLike || ChangesLinkage) {
4938      if (NonCLike.Kind == NonCLikeKind::Invalid)
4939        return;
4940  
4941      unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4942      if (ChangesLinkage) {
4943        // If the linkage changes, we can't accept this as an extension.
4944        if (NonCLike.Kind == NonCLikeKind::None)
4945          DiagID = diag::err_typedef_changes_linkage;
4946        else
4947          DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4948      }
4949  
4950      SourceLocation FixitLoc =
4951          getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4952      llvm::SmallString<40> TextToInsert;
4953      TextToInsert += ' ';
4954      TextToInsert += NewTD->getIdentifier()->getName();
4955  
4956      Diag(FixitLoc, DiagID)
4957        << isa<TypeAliasDecl>(NewTD)
4958        << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4959      if (NonCLike.Kind != NonCLikeKind::None) {
4960        Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4961          << NonCLike.Kind - 1 << NonCLike.Range;
4962      }
4963      Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4964        << NewTD << isa<TypeAliasDecl>(NewTD);
4965  
4966      if (ChangesLinkage)
4967        return;
4968    }
4969  
4970    // Otherwise, set this as the anon-decl typedef for the tag.
4971    TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4972  }
4973  
GetDiagnosticTypeSpecifierID(const DeclSpec & DS)4974  static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
4975    DeclSpec::TST T = DS.getTypeSpecType();
4976    switch (T) {
4977    case DeclSpec::TST_class:
4978      return 0;
4979    case DeclSpec::TST_struct:
4980      return 1;
4981    case DeclSpec::TST_interface:
4982      return 2;
4983    case DeclSpec::TST_union:
4984      return 3;
4985    case DeclSpec::TST_enum:
4986      if (const auto *ED = dyn_cast<EnumDecl>(DS.getRepAsDecl())) {
4987        if (ED->isScopedUsingClassTag())
4988          return 5;
4989        if (ED->isScoped())
4990          return 6;
4991      }
4992      return 4;
4993    default:
4994      llvm_unreachable("unexpected type specifier");
4995    }
4996  }
4997  
ParsedFreeStandingDeclSpec(Scope * S,AccessSpecifier AS,DeclSpec & DS,const ParsedAttributesView & DeclAttrs,MultiTemplateParamsArg TemplateParams,bool IsExplicitInstantiation,RecordDecl * & AnonRecord)4998  Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
4999                                         DeclSpec &DS,
5000                                         const ParsedAttributesView &DeclAttrs,
5001                                         MultiTemplateParamsArg TemplateParams,
5002                                         bool IsExplicitInstantiation,
5003                                         RecordDecl *&AnonRecord) {
5004    Decl *TagD = nullptr;
5005    TagDecl *Tag = nullptr;
5006    if (DS.getTypeSpecType() == DeclSpec::TST_class ||
5007        DS.getTypeSpecType() == DeclSpec::TST_struct ||
5008        DS.getTypeSpecType() == DeclSpec::TST_interface ||
5009        DS.getTypeSpecType() == DeclSpec::TST_union ||
5010        DS.getTypeSpecType() == DeclSpec::TST_enum) {
5011      TagD = DS.getRepAsDecl();
5012  
5013      if (!TagD) // We probably had an error
5014        return nullptr;
5015  
5016      // Note that the above type specs guarantee that the
5017      // type rep is a Decl, whereas in many of the others
5018      // it's a Type.
5019      if (isa<TagDecl>(TagD))
5020        Tag = cast<TagDecl>(TagD);
5021      else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
5022        Tag = CTD->getTemplatedDecl();
5023    }
5024  
5025    if (Tag) {
5026      handleTagNumbering(Tag, S);
5027      Tag->setFreeStanding();
5028      if (Tag->isInvalidDecl())
5029        return Tag;
5030    }
5031  
5032    if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5033      // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5034      // or incomplete types shall not be restrict-qualified."
5035      if (TypeQuals & DeclSpec::TQ_restrict)
5036        Diag(DS.getRestrictSpecLoc(),
5037             diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5038             << DS.getSourceRange();
5039    }
5040  
5041    if (DS.isInlineSpecified())
5042      Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5043          << getLangOpts().CPlusPlus17;
5044  
5045    if (DS.hasConstexprSpecifier()) {
5046      // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5047      // and definitions of functions and variables.
5048      // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5049      // the declaration of a function or function template
5050      if (Tag)
5051        Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5052            << GetDiagnosticTypeSpecifierID(DS)
5053            << static_cast<int>(DS.getConstexprSpecifier());
5054      else if (getLangOpts().C23)
5055        Diag(DS.getConstexprSpecLoc(), diag::err_c23_constexpr_not_variable);
5056      else
5057        Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5058            << static_cast<int>(DS.getConstexprSpecifier());
5059      // Don't emit warnings after this error.
5060      return TagD;
5061    }
5062  
5063    DiagnoseFunctionSpecifiers(DS);
5064  
5065    if (DS.isFriendSpecified()) {
5066      // If we're dealing with a decl but not a TagDecl, assume that
5067      // whatever routines created it handled the friendship aspect.
5068      if (TagD && !Tag)
5069        return nullptr;
5070      return ActOnFriendTypeDecl(S, DS, TemplateParams);
5071    }
5072  
5073    // Track whether this decl-specifier declares anything.
5074    bool DeclaresAnything = true;
5075  
5076    // Handle anonymous struct definitions.
5077    if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
5078      if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5079          DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
5080        if (getLangOpts().CPlusPlus ||
5081            Record->getDeclContext()->isRecord()) {
5082          // If CurContext is a DeclContext that can contain statements,
5083          // RecursiveASTVisitor won't visit the decls that
5084          // BuildAnonymousStructOrUnion() will put into CurContext.
5085          // Also store them here so that they can be part of the
5086          // DeclStmt that gets created in this case.
5087          // FIXME: Also return the IndirectFieldDecls created by
5088          // BuildAnonymousStructOr union, for the same reason?
5089          if (CurContext->isFunctionOrMethod())
5090            AnonRecord = Record;
5091          return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5092                                             Context.getPrintingPolicy());
5093        }
5094  
5095        DeclaresAnything = false;
5096      }
5097    }
5098  
5099    // C11 6.7.2.1p2:
5100    //   A struct-declaration that does not declare an anonymous structure or
5101    //   anonymous union shall contain a struct-declarator-list.
5102    //
5103    // This rule also existed in C89 and C99; the grammar for struct-declaration
5104    // did not permit a struct-declaration without a struct-declarator-list.
5105    if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5106        DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
5107      // Check for Microsoft C extension: anonymous struct/union member.
5108      // Handle 2 kinds of anonymous struct/union:
5109      //   struct STRUCT;
5110      //   union UNION;
5111      // and
5112      //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
5113      //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
5114      if ((Tag && Tag->getDeclName()) ||
5115          DS.getTypeSpecType() == DeclSpec::TST_typename) {
5116        RecordDecl *Record = nullptr;
5117        if (Tag)
5118          Record = dyn_cast<RecordDecl>(Tag);
5119        else if (const RecordType *RT =
5120                     DS.getRepAsType().get()->getAsStructureType())
5121          Record = RT->getDecl();
5122        else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
5123          Record = UT->getDecl();
5124  
5125        if (Record && getLangOpts().MicrosoftExt) {
5126          Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5127              << Record->isUnion() << DS.getSourceRange();
5128          return BuildMicrosoftCAnonymousStruct(S, DS, Record);
5129        }
5130  
5131        DeclaresAnything = false;
5132      }
5133    }
5134  
5135    // Skip all the checks below if we have a type error.
5136    if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5137        (TagD && TagD->isInvalidDecl()))
5138      return TagD;
5139  
5140    if (getLangOpts().CPlusPlus &&
5141        DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
5142      if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5143        if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5144            !Enum->getIdentifier() && !Enum->isInvalidDecl())
5145          DeclaresAnything = false;
5146  
5147    if (!DS.isMissingDeclaratorOk()) {
5148      // Customize diagnostic for a typedef missing a name.
5149      if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
5150        Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5151            << DS.getSourceRange();
5152      else
5153        DeclaresAnything = false;
5154    }
5155  
5156    if (DS.isModulePrivateSpecified() &&
5157        Tag && Tag->getDeclContext()->isFunctionOrMethod())
5158      Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5159          << llvm::to_underlying(Tag->getTagKind())
5160          << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
5161  
5162    ActOnDocumentableDecl(TagD);
5163  
5164    // C 6.7/2:
5165    //   A declaration [...] shall declare at least a declarator [...], a tag,
5166    //   or the members of an enumeration.
5167    // C++ [dcl.dcl]p3:
5168    //   [If there are no declarators], and except for the declaration of an
5169    //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5170    //   names into the program, or shall redeclare a name introduced by a
5171    //   previous declaration.
5172    if (!DeclaresAnything) {
5173      // In C, we allow this as a (popular) extension / bug. Don't bother
5174      // producing further diagnostics for redundant qualifiers after this.
5175      Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5176                                 ? diag::err_no_declarators
5177                                 : diag::ext_no_declarators)
5178          << DS.getSourceRange();
5179      return TagD;
5180    }
5181  
5182    // C++ [dcl.stc]p1:
5183    //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5184    //   init-declarator-list of the declaration shall not be empty.
5185    // C++ [dcl.fct.spec]p1:
5186    //   If a cv-qualifier appears in a decl-specifier-seq, the
5187    //   init-declarator-list of the declaration shall not be empty.
5188    //
5189    // Spurious qualifiers here appear to be valid in C.
5190    unsigned DiagID = diag::warn_standalone_specifier;
5191    if (getLangOpts().CPlusPlus)
5192      DiagID = diag::ext_standalone_specifier;
5193  
5194    // Note that a linkage-specification sets a storage class, but
5195    // 'extern "C" struct foo;' is actually valid and not theoretically
5196    // useless.
5197    if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5198      if (SCS == DeclSpec::SCS_mutable)
5199        // Since mutable is not a viable storage class specifier in C, there is
5200        // no reason to treat it as an extension. Instead, diagnose as an error.
5201        Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5202      else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5203        Diag(DS.getStorageClassSpecLoc(), DiagID)
5204          << DeclSpec::getSpecifierName(SCS);
5205    }
5206  
5207    if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5208      Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
5209        << DeclSpec::getSpecifierName(TSCS);
5210    if (DS.getTypeQualifiers()) {
5211      if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5212        Diag(DS.getConstSpecLoc(), DiagID) << "const";
5213      if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5214        Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5215      // Restrict is covered above.
5216      if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5217        Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5218      if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5219        Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5220    }
5221  
5222    // Warn about ignored type attributes, for example:
5223    // __attribute__((aligned)) struct A;
5224    // Attributes should be placed after tag to apply to type declaration.
5225    if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5226      DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5227      if (TypeSpecType == DeclSpec::TST_class ||
5228          TypeSpecType == DeclSpec::TST_struct ||
5229          TypeSpecType == DeclSpec::TST_interface ||
5230          TypeSpecType == DeclSpec::TST_union ||
5231          TypeSpecType == DeclSpec::TST_enum) {
5232  
5233        auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5234          unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5235          if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5236            DiagnosticId = diag::warn_attribute_ignored;
5237          else if (AL.isRegularKeywordAttribute())
5238            DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5239          else
5240            DiagnosticId = diag::warn_declspec_attribute_ignored;
5241          Diag(AL.getLoc(), DiagnosticId)
5242              << AL << GetDiagnosticTypeSpecifierID(DS);
5243        };
5244  
5245        llvm::for_each(DS.getAttributes(), EmitAttributeDiagnostic);
5246        llvm::for_each(DeclAttrs, EmitAttributeDiagnostic);
5247      }
5248    }
5249  
5250    return TagD;
5251  }
5252  
5253  /// We are trying to inject an anonymous member into the given scope;
5254  /// check if there's an existing declaration that can't be overloaded.
5255  ///
5256  /// \return true if this is a forbidden redeclaration
CheckAnonMemberRedeclaration(Sema & SemaRef,Scope * S,DeclContext * Owner,DeclarationName Name,SourceLocation NameLoc,bool IsUnion,StorageClass SC)5257  static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5258                                           DeclContext *Owner,
5259                                           DeclarationName Name,
5260                                           SourceLocation NameLoc, bool IsUnion,
5261                                           StorageClass SC) {
5262    LookupResult R(SemaRef, Name, NameLoc,
5263                   Owner->isRecord() ? Sema::LookupMemberName
5264                                     : Sema::LookupOrdinaryName,
5265                   RedeclarationKind::ForVisibleRedeclaration);
5266    if (!SemaRef.LookupName(R, S)) return false;
5267  
5268    // Pick a representative declaration.
5269    NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5270    assert(PrevDecl && "Expected a non-null Decl");
5271  
5272    if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5273      return false;
5274  
5275    if (SC == StorageClass::SC_None &&
5276        PrevDecl->isPlaceholderVar(SemaRef.getLangOpts()) &&
5277        (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5278      if (!Owner->isRecord())
5279        SemaRef.DiagPlaceholderVariableDefinition(NameLoc);
5280      return false;
5281    }
5282  
5283    SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5284      << IsUnion << Name;
5285    SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5286  
5287    return true;
5288  }
5289  
ActOnDefinedDeclarationSpecifier(Decl * D)5290  void Sema::ActOnDefinedDeclarationSpecifier(Decl *D) {
5291    if (auto *RD = dyn_cast_if_present<RecordDecl>(D))
5292      DiagPlaceholderFieldDeclDefinitions(RD);
5293  }
5294  
DiagPlaceholderFieldDeclDefinitions(RecordDecl * Record)5295  void Sema::DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record) {
5296    if (!getLangOpts().CPlusPlus)
5297      return;
5298  
5299    // This function can be parsed before we have validated the
5300    // structure as an anonymous struct
5301    if (Record->isAnonymousStructOrUnion())
5302      return;
5303  
5304    const NamedDecl *First = 0;
5305    for (const Decl *D : Record->decls()) {
5306      const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5307      if (!ND || !ND->isPlaceholderVar(getLangOpts()))
5308        continue;
5309      if (!First)
5310        First = ND;
5311      else
5312        DiagPlaceholderVariableDefinition(ND->getLocation());
5313    }
5314  }
5315  
5316  /// InjectAnonymousStructOrUnionMembers - Inject the members of the
5317  /// anonymous struct or union AnonRecord into the owning context Owner
5318  /// and scope S. This routine will be invoked just after we realize
5319  /// that an unnamed union or struct is actually an anonymous union or
5320  /// struct, e.g.,
5321  ///
5322  /// @code
5323  /// union {
5324  ///   int i;
5325  ///   float f;
5326  /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5327  ///    // f into the surrounding scope.x
5328  /// @endcode
5329  ///
5330  /// This routine is recursive, injecting the names of nested anonymous
5331  /// structs/unions into the owning context and scope as well.
5332  static bool
InjectAnonymousStructOrUnionMembers(Sema & SemaRef,Scope * S,DeclContext * Owner,RecordDecl * AnonRecord,AccessSpecifier AS,StorageClass SC,SmallVectorImpl<NamedDecl * > & Chaining)5333  InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5334                                      RecordDecl *AnonRecord, AccessSpecifier AS,
5335                                      StorageClass SC,
5336                                      SmallVectorImpl<NamedDecl *> &Chaining) {
5337    bool Invalid = false;
5338  
5339    // Look every FieldDecl and IndirectFieldDecl with a name.
5340    for (auto *D : AnonRecord->decls()) {
5341      if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5342          cast<NamedDecl>(D)->getDeclName()) {
5343        ValueDecl *VD = cast<ValueDecl>(D);
5344        if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5345                                         VD->getLocation(), AnonRecord->isUnion(),
5346                                         SC)) {
5347          // C++ [class.union]p2:
5348          //   The names of the members of an anonymous union shall be
5349          //   distinct from the names of any other entity in the
5350          //   scope in which the anonymous union is declared.
5351          Invalid = true;
5352        } else {
5353          // C++ [class.union]p2:
5354          //   For the purpose of name lookup, after the anonymous union
5355          //   definition, the members of the anonymous union are
5356          //   considered to have been defined in the scope in which the
5357          //   anonymous union is declared.
5358          unsigned OldChainingSize = Chaining.size();
5359          if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5360            Chaining.append(IF->chain_begin(), IF->chain_end());
5361          else
5362            Chaining.push_back(VD);
5363  
5364          assert(Chaining.size() >= 2);
5365          NamedDecl **NamedChain =
5366            new (SemaRef.Context)NamedDecl*[Chaining.size()];
5367          for (unsigned i = 0; i < Chaining.size(); i++)
5368            NamedChain[i] = Chaining[i];
5369  
5370          IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5371              SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5372              VD->getType(), {NamedChain, Chaining.size()});
5373  
5374          for (const auto *Attr : VD->attrs())
5375            IndirectField->addAttr(Attr->clone(SemaRef.Context));
5376  
5377          IndirectField->setAccess(AS);
5378          IndirectField->setImplicit();
5379          SemaRef.PushOnScopeChains(IndirectField, S);
5380  
5381          // That includes picking up the appropriate access specifier.
5382          if (AS != AS_none) IndirectField->setAccess(AS);
5383  
5384          Chaining.resize(OldChainingSize);
5385        }
5386      }
5387    }
5388  
5389    return Invalid;
5390  }
5391  
5392  /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5393  /// a VarDecl::StorageClass. Any error reporting is up to the caller:
5394  /// illegal input values are mapped to SC_None.
5395  static StorageClass
StorageClassSpecToVarDeclStorageClass(const DeclSpec & DS)5396  StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5397    DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5398    assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5399           "Parser allowed 'typedef' as storage class VarDecl.");
5400    switch (StorageClassSpec) {
5401    case DeclSpec::SCS_unspecified:    return SC_None;
5402    case DeclSpec::SCS_extern:
5403      if (DS.isExternInLinkageSpec())
5404        return SC_None;
5405      return SC_Extern;
5406    case DeclSpec::SCS_static:         return SC_Static;
5407    case DeclSpec::SCS_auto:           return SC_Auto;
5408    case DeclSpec::SCS_register:       return SC_Register;
5409    case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5410      // Illegal SCSs map to None: error reporting is up to the caller.
5411    case DeclSpec::SCS_mutable:        // Fall through.
5412    case DeclSpec::SCS_typedef:        return SC_None;
5413    }
5414    llvm_unreachable("unknown storage class specifier");
5415  }
5416  
findDefaultInitializer(const CXXRecordDecl * Record)5417  static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5418    assert(Record->hasInClassInitializer());
5419  
5420    for (const auto *I : Record->decls()) {
5421      const auto *FD = dyn_cast<FieldDecl>(I);
5422      if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5423        FD = IFD->getAnonField();
5424      if (FD && FD->hasInClassInitializer())
5425        return FD->getLocation();
5426    }
5427  
5428    llvm_unreachable("couldn't find in-class initializer");
5429  }
5430  
checkDuplicateDefaultInit(Sema & S,CXXRecordDecl * Parent,SourceLocation DefaultInitLoc)5431  static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5432                                        SourceLocation DefaultInitLoc) {
5433    if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5434      return;
5435  
5436    S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5437    S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5438  }
5439  
checkDuplicateDefaultInit(Sema & S,CXXRecordDecl * Parent,CXXRecordDecl * AnonUnion)5440  static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5441                                        CXXRecordDecl *AnonUnion) {
5442    if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5443      return;
5444  
5445    checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5446  }
5447  
BuildAnonymousStructOrUnion(Scope * S,DeclSpec & DS,AccessSpecifier AS,RecordDecl * Record,const PrintingPolicy & Policy)5448  Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5449                                          AccessSpecifier AS,
5450                                          RecordDecl *Record,
5451                                          const PrintingPolicy &Policy) {
5452    DeclContext *Owner = Record->getDeclContext();
5453  
5454    // Diagnose whether this anonymous struct/union is an extension.
5455    if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5456      Diag(Record->getLocation(), diag::ext_anonymous_union);
5457    else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5458      Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5459    else if (!Record->isUnion() && !getLangOpts().C11)
5460      Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5461  
5462    // C and C++ require different kinds of checks for anonymous
5463    // structs/unions.
5464    bool Invalid = false;
5465    if (getLangOpts().CPlusPlus) {
5466      const char *PrevSpec = nullptr;
5467      if (Record->isUnion()) {
5468        // C++ [class.union]p6:
5469        // C++17 [class.union.anon]p2:
5470        //   Anonymous unions declared in a named namespace or in the
5471        //   global namespace shall be declared static.
5472        unsigned DiagID;
5473        DeclContext *OwnerScope = Owner->getRedeclContext();
5474        if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5475            (OwnerScope->isTranslationUnit() ||
5476             (OwnerScope->isNamespace() &&
5477              !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5478          Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5479            << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5480  
5481          // Recover by adding 'static'.
5482          DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5483                                 PrevSpec, DiagID, Policy);
5484        }
5485        // C++ [class.union]p6:
5486        //   A storage class is not allowed in a declaration of an
5487        //   anonymous union in a class scope.
5488        else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5489                 isa<RecordDecl>(Owner)) {
5490          Diag(DS.getStorageClassSpecLoc(),
5491               diag::err_anonymous_union_with_storage_spec)
5492            << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5493  
5494          // Recover by removing the storage specifier.
5495          DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5496                                 SourceLocation(),
5497                                 PrevSpec, DiagID, Context.getPrintingPolicy());
5498        }
5499      }
5500  
5501      // Ignore const/volatile/restrict qualifiers.
5502      if (DS.getTypeQualifiers()) {
5503        if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5504          Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5505            << Record->isUnion() << "const"
5506            << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5507        if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5508          Diag(DS.getVolatileSpecLoc(),
5509               diag::ext_anonymous_struct_union_qualified)
5510            << Record->isUnion() << "volatile"
5511            << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5512        if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5513          Diag(DS.getRestrictSpecLoc(),
5514               diag::ext_anonymous_struct_union_qualified)
5515            << Record->isUnion() << "restrict"
5516            << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5517        if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5518          Diag(DS.getAtomicSpecLoc(),
5519               diag::ext_anonymous_struct_union_qualified)
5520            << Record->isUnion() << "_Atomic"
5521            << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5522        if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5523          Diag(DS.getUnalignedSpecLoc(),
5524               diag::ext_anonymous_struct_union_qualified)
5525            << Record->isUnion() << "__unaligned"
5526            << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5527  
5528        DS.ClearTypeQualifiers();
5529      }
5530  
5531      // C++ [class.union]p2:
5532      //   The member-specification of an anonymous union shall only
5533      //   define non-static data members. [Note: nested types and
5534      //   functions cannot be declared within an anonymous union. ]
5535      for (auto *Mem : Record->decls()) {
5536        // Ignore invalid declarations; we already diagnosed them.
5537        if (Mem->isInvalidDecl())
5538          continue;
5539  
5540        if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5541          // C++ [class.union]p3:
5542          //   An anonymous union shall not have private or protected
5543          //   members (clause 11).
5544          assert(FD->getAccess() != AS_none);
5545          if (FD->getAccess() != AS_public) {
5546            Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5547              << Record->isUnion() << (FD->getAccess() == AS_protected);
5548            Invalid = true;
5549          }
5550  
5551          // C++ [class.union]p1
5552          //   An object of a class with a non-trivial constructor, a non-trivial
5553          //   copy constructor, a non-trivial destructor, or a non-trivial copy
5554          //   assignment operator cannot be a member of a union, nor can an
5555          //   array of such objects.
5556          if (CheckNontrivialField(FD))
5557            Invalid = true;
5558        } else if (Mem->isImplicit()) {
5559          // Any implicit members are fine.
5560        } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5561          // This is a type that showed up in an
5562          // elaborated-type-specifier inside the anonymous struct or
5563          // union, but which actually declares a type outside of the
5564          // anonymous struct or union. It's okay.
5565        } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5566          if (!MemRecord->isAnonymousStructOrUnion() &&
5567              MemRecord->getDeclName()) {
5568            // Visual C++ allows type definition in anonymous struct or union.
5569            if (getLangOpts().MicrosoftExt)
5570              Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5571                << Record->isUnion();
5572            else {
5573              // This is a nested type declaration.
5574              Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5575                << Record->isUnion();
5576              Invalid = true;
5577            }
5578          } else {
5579            // This is an anonymous type definition within another anonymous type.
5580            // This is a popular extension, provided by Plan9, MSVC and GCC, but
5581            // not part of standard C++.
5582            Diag(MemRecord->getLocation(),
5583                 diag::ext_anonymous_record_with_anonymous_type)
5584              << Record->isUnion();
5585          }
5586        } else if (isa<AccessSpecDecl>(Mem)) {
5587          // Any access specifier is fine.
5588        } else if (isa<StaticAssertDecl>(Mem)) {
5589          // In C++1z, static_assert declarations are also fine.
5590        } else {
5591          // We have something that isn't a non-static data
5592          // member. Complain about it.
5593          unsigned DK = diag::err_anonymous_record_bad_member;
5594          if (isa<TypeDecl>(Mem))
5595            DK = diag::err_anonymous_record_with_type;
5596          else if (isa<FunctionDecl>(Mem))
5597            DK = diag::err_anonymous_record_with_function;
5598          else if (isa<VarDecl>(Mem))
5599            DK = diag::err_anonymous_record_with_static;
5600  
5601          // Visual C++ allows type definition in anonymous struct or union.
5602          if (getLangOpts().MicrosoftExt &&
5603              DK == diag::err_anonymous_record_with_type)
5604            Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5605              << Record->isUnion();
5606          else {
5607            Diag(Mem->getLocation(), DK) << Record->isUnion();
5608            Invalid = true;
5609          }
5610        }
5611      }
5612  
5613      // C++11 [class.union]p8 (DR1460):
5614      //   At most one variant member of a union may have a
5615      //   brace-or-equal-initializer.
5616      if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5617          Owner->isRecord())
5618        checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5619                                  cast<CXXRecordDecl>(Record));
5620    }
5621  
5622    if (!Record->isUnion() && !Owner->isRecord()) {
5623      Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5624        << getLangOpts().CPlusPlus;
5625      Invalid = true;
5626    }
5627  
5628    // C++ [dcl.dcl]p3:
5629    //   [If there are no declarators], and except for the declaration of an
5630    //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5631    //   names into the program
5632    // C++ [class.mem]p2:
5633    //   each such member-declaration shall either declare at least one member
5634    //   name of the class or declare at least one unnamed bit-field
5635    //
5636    // For C this is an error even for a named struct, and is diagnosed elsewhere.
5637    if (getLangOpts().CPlusPlus && Record->field_empty())
5638      Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5639  
5640    // Mock up a declarator.
5641    Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member);
5642    StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5643    TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc);
5644    assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5645  
5646    // Create a declaration for this anonymous struct/union.
5647    NamedDecl *Anon = nullptr;
5648    if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5649      Anon = FieldDecl::Create(
5650          Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5651          /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5652          /*BitWidth=*/nullptr, /*Mutable=*/false,
5653          /*InitStyle=*/ICIS_NoInit);
5654      Anon->setAccess(AS);
5655      ProcessDeclAttributes(S, Anon, Dc);
5656  
5657      if (getLangOpts().CPlusPlus)
5658        FieldCollector->Add(cast<FieldDecl>(Anon));
5659    } else {
5660      DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5661      if (SCSpec == DeclSpec::SCS_mutable) {
5662        // mutable can only appear on non-static class members, so it's always
5663        // an error here
5664        Diag(Record->getLocation(), diag::err_mutable_nonmember);
5665        Invalid = true;
5666        SC = SC_None;
5667      }
5668  
5669      Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5670                             Record->getLocation(), /*IdentifierInfo=*/nullptr,
5671                             Context.getTypeDeclType(Record), TInfo, SC);
5672      if (Invalid)
5673        Anon->setInvalidDecl();
5674  
5675      ProcessDeclAttributes(S, Anon, Dc);
5676  
5677      // Default-initialize the implicit variable. This initialization will be
5678      // trivial in almost all cases, except if a union member has an in-class
5679      // initializer:
5680      //   union { int n = 0; };
5681      ActOnUninitializedDecl(Anon);
5682    }
5683    Anon->setImplicit();
5684  
5685    // Mark this as an anonymous struct/union type.
5686    Record->setAnonymousStructOrUnion(true);
5687  
5688    // Add the anonymous struct/union object to the current
5689    // context. We'll be referencing this object when we refer to one of
5690    // its members.
5691    Owner->addDecl(Anon);
5692  
5693    // Inject the members of the anonymous struct/union into the owning
5694    // context and into the identifier resolver chain for name lookup
5695    // purposes.
5696    SmallVector<NamedDecl*, 2> Chain;
5697    Chain.push_back(Anon);
5698  
5699    if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, SC,
5700                                            Chain))
5701      Invalid = true;
5702  
5703    if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5704      if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5705        MangleNumberingContext *MCtx;
5706        Decl *ManglingContextDecl;
5707        std::tie(MCtx, ManglingContextDecl) =
5708            getCurrentMangleNumberContext(NewVD->getDeclContext());
5709        if (MCtx) {
5710          Context.setManglingNumber(
5711              NewVD, MCtx->getManglingNumber(
5712                         NewVD, getMSManglingNumber(getLangOpts(), S)));
5713          Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5714        }
5715      }
5716    }
5717  
5718    if (Invalid)
5719      Anon->setInvalidDecl();
5720  
5721    return Anon;
5722  }
5723  
BuildMicrosoftCAnonymousStruct(Scope * S,DeclSpec & DS,RecordDecl * Record)5724  Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5725                                             RecordDecl *Record) {
5726    assert(Record && "expected a record!");
5727  
5728    // Mock up a declarator.
5729    Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName);
5730    TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc);
5731    assert(TInfo && "couldn't build declarator info for anonymous struct");
5732  
5733    auto *ParentDecl = cast<RecordDecl>(CurContext);
5734    QualType RecTy = Context.getTypeDeclType(Record);
5735  
5736    // Create a declaration for this anonymous struct.
5737    NamedDecl *Anon =
5738        FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5739                          /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5740                          /*BitWidth=*/nullptr, /*Mutable=*/false,
5741                          /*InitStyle=*/ICIS_NoInit);
5742    Anon->setImplicit();
5743  
5744    // Add the anonymous struct object to the current context.
5745    CurContext->addDecl(Anon);
5746  
5747    // Inject the members of the anonymous struct into the current
5748    // context and into the identifier resolver chain for name lookup
5749    // purposes.
5750    SmallVector<NamedDecl*, 2> Chain;
5751    Chain.push_back(Anon);
5752  
5753    RecordDecl *RecordDef = Record->getDefinition();
5754    if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5755                                 diag::err_field_incomplete_or_sizeless) ||
5756        InjectAnonymousStructOrUnionMembers(
5757            *this, S, CurContext, RecordDef, AS_none,
5758            StorageClassSpecToVarDeclStorageClass(DS), Chain)) {
5759      Anon->setInvalidDecl();
5760      ParentDecl->setInvalidDecl();
5761    }
5762  
5763    return Anon;
5764  }
5765  
GetNameForDeclarator(Declarator & D)5766  DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5767    return GetNameFromUnqualifiedId(D.getName());
5768  }
5769  
5770  DeclarationNameInfo
GetNameFromUnqualifiedId(const UnqualifiedId & Name)5771  Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5772    DeclarationNameInfo NameInfo;
5773    NameInfo.setLoc(Name.StartLocation);
5774  
5775    switch (Name.getKind()) {
5776  
5777    case UnqualifiedIdKind::IK_ImplicitSelfParam:
5778    case UnqualifiedIdKind::IK_Identifier:
5779      NameInfo.setName(Name.Identifier);
5780      return NameInfo;
5781  
5782    case UnqualifiedIdKind::IK_DeductionGuideName: {
5783      // C++ [temp.deduct.guide]p3:
5784      //   The simple-template-id shall name a class template specialization.
5785      //   The template-name shall be the same identifier as the template-name
5786      //   of the simple-template-id.
5787      // These together intend to imply that the template-name shall name a
5788      // class template.
5789      // FIXME: template<typename T> struct X {};
5790      //        template<typename T> using Y = X<T>;
5791      //        Y(int) -> Y<int>;
5792      //   satisfies these rules but does not name a class template.
5793      TemplateName TN = Name.TemplateName.get().get();
5794      auto *Template = TN.getAsTemplateDecl();
5795      if (!Template || !isa<ClassTemplateDecl>(Template)) {
5796        Diag(Name.StartLocation,
5797             diag::err_deduction_guide_name_not_class_template)
5798          << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5799        if (Template)
5800          NoteTemplateLocation(*Template);
5801        return DeclarationNameInfo();
5802      }
5803  
5804      NameInfo.setName(
5805          Context.DeclarationNames.getCXXDeductionGuideName(Template));
5806      return NameInfo;
5807    }
5808  
5809    case UnqualifiedIdKind::IK_OperatorFunctionId:
5810      NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5811                                             Name.OperatorFunctionId.Operator));
5812      NameInfo.setCXXOperatorNameRange(SourceRange(
5813          Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5814      return NameInfo;
5815  
5816    case UnqualifiedIdKind::IK_LiteralOperatorId:
5817      NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5818                                                             Name.Identifier));
5819      NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5820      return NameInfo;
5821  
5822    case UnqualifiedIdKind::IK_ConversionFunctionId: {
5823      TypeSourceInfo *TInfo;
5824      QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5825      if (Ty.isNull())
5826        return DeclarationNameInfo();
5827      NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5828                                                 Context.getCanonicalType(Ty)));
5829      NameInfo.setNamedTypeInfo(TInfo);
5830      return NameInfo;
5831    }
5832  
5833    case UnqualifiedIdKind::IK_ConstructorName: {
5834      TypeSourceInfo *TInfo;
5835      QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5836      if (Ty.isNull())
5837        return DeclarationNameInfo();
5838      NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5839                                                Context.getCanonicalType(Ty)));
5840      NameInfo.setNamedTypeInfo(TInfo);
5841      return NameInfo;
5842    }
5843  
5844    case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5845      // In well-formed code, we can only have a constructor
5846      // template-id that refers to the current context, so go there
5847      // to find the actual type being constructed.
5848      CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5849      if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5850        return DeclarationNameInfo();
5851  
5852      // Determine the type of the class being constructed.
5853      QualType CurClassType = Context.getTypeDeclType(CurClass);
5854  
5855      // FIXME: Check two things: that the template-id names the same type as
5856      // CurClassType, and that the template-id does not occur when the name
5857      // was qualified.
5858  
5859      NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5860                                      Context.getCanonicalType(CurClassType)));
5861      // FIXME: should we retrieve TypeSourceInfo?
5862      NameInfo.setNamedTypeInfo(nullptr);
5863      return NameInfo;
5864    }
5865  
5866    case UnqualifiedIdKind::IK_DestructorName: {
5867      TypeSourceInfo *TInfo;
5868      QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5869      if (Ty.isNull())
5870        return DeclarationNameInfo();
5871      NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5872                                                Context.getCanonicalType(Ty)));
5873      NameInfo.setNamedTypeInfo(TInfo);
5874      return NameInfo;
5875    }
5876  
5877    case UnqualifiedIdKind::IK_TemplateId: {
5878      TemplateName TName = Name.TemplateId->Template.get();
5879      SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5880      return Context.getNameForTemplate(TName, TNameLoc);
5881    }
5882  
5883    } // switch (Name.getKind())
5884  
5885    llvm_unreachable("Unknown name kind");
5886  }
5887  
getCoreType(QualType Ty)5888  static QualType getCoreType(QualType Ty) {
5889    do {
5890      if (Ty->isPointerType() || Ty->isReferenceType())
5891        Ty = Ty->getPointeeType();
5892      else if (Ty->isArrayType())
5893        Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5894      else
5895        return Ty.withoutLocalFastQualifiers();
5896    } while (true);
5897  }
5898  
5899  /// hasSimilarParameters - Determine whether the C++ functions Declaration
5900  /// and Definition have "nearly" matching parameters. This heuristic is
5901  /// used to improve diagnostics in the case where an out-of-line function
5902  /// definition doesn't match any declaration within the class or namespace.
5903  /// Also sets Params to the list of indices to the parameters that differ
5904  /// between the declaration and the definition. If hasSimilarParameters
5905  /// returns true and Params is empty, then all of the parameters match.
hasSimilarParameters(ASTContext & Context,FunctionDecl * Declaration,FunctionDecl * Definition,SmallVectorImpl<unsigned> & Params)5906  static bool hasSimilarParameters(ASTContext &Context,
5907                                       FunctionDecl *Declaration,
5908                                       FunctionDecl *Definition,
5909                                       SmallVectorImpl<unsigned> &Params) {
5910    Params.clear();
5911    if (Declaration->param_size() != Definition->param_size())
5912      return false;
5913    for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5914      QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5915      QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5916  
5917      // The parameter types are identical
5918      if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5919        continue;
5920  
5921      QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5922      QualType DefParamBaseTy = getCoreType(DefParamTy);
5923      const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5924      const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5925  
5926      if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5927          (DeclTyName && DeclTyName == DefTyName))
5928        Params.push_back(Idx);
5929      else  // The two parameters aren't even close
5930        return false;
5931    }
5932  
5933    return true;
5934  }
5935  
5936  /// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
5937  /// declarator needs to be rebuilt in the current instantiation.
5938  /// Any bits of declarator which appear before the name are valid for
5939  /// consideration here.  That's specifically the type in the decl spec
5940  /// and the base type in any member-pointer chunks.
RebuildDeclaratorInCurrentInstantiation(Sema & S,Declarator & D,DeclarationName Name)5941  static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5942                                                      DeclarationName Name) {
5943    // The types we specifically need to rebuild are:
5944    //   - typenames, typeofs, and decltypes
5945    //   - types which will become injected class names
5946    // Of course, we also need to rebuild any type referencing such a
5947    // type.  It's safest to just say "dependent", but we call out a
5948    // few cases here.
5949  
5950    DeclSpec &DS = D.getMutableDeclSpec();
5951    switch (DS.getTypeSpecType()) {
5952    case DeclSpec::TST_typename:
5953    case DeclSpec::TST_typeofType:
5954    case DeclSpec::TST_typeof_unqualType:
5955  #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
5956  #include "clang/Basic/TransformTypeTraits.def"
5957    case DeclSpec::TST_atomic: {
5958      // Grab the type from the parser.
5959      TypeSourceInfo *TSI = nullptr;
5960      QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5961      if (T.isNull() || !T->isInstantiationDependentType()) break;
5962  
5963      // Make sure there's a type source info.  This isn't really much
5964      // of a waste; most dependent types should have type source info
5965      // attached already.
5966      if (!TSI)
5967        TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5968  
5969      // Rebuild the type in the current instantiation.
5970      TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5971      if (!TSI) return true;
5972  
5973      // Store the new type back in the decl spec.
5974      ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5975      DS.UpdateTypeRep(LocType);
5976      break;
5977    }
5978  
5979    case DeclSpec::TST_decltype:
5980    case DeclSpec::TST_typeof_unqualExpr:
5981    case DeclSpec::TST_typeofExpr: {
5982      Expr *E = DS.getRepAsExpr();
5983      ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5984      if (Result.isInvalid()) return true;
5985      DS.UpdateExprRep(Result.get());
5986      break;
5987    }
5988  
5989    default:
5990      // Nothing to do for these decl specs.
5991      break;
5992    }
5993  
5994    // It doesn't matter what order we do this in.
5995    for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5996      DeclaratorChunk &Chunk = D.getTypeObject(I);
5997  
5998      // The only type information in the declarator which can come
5999      // before the declaration name is the base type of a member
6000      // pointer.
6001      if (Chunk.Kind != DeclaratorChunk::MemberPointer)
6002        continue;
6003  
6004      // Rebuild the scope specifier in-place.
6005      CXXScopeSpec &SS = Chunk.Mem.Scope();
6006      if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
6007        return true;
6008    }
6009  
6010    return false;
6011  }
6012  
6013  /// Returns true if the declaration is declared in a system header or from a
6014  /// system macro.
isFromSystemHeader(SourceManager & SM,const Decl * D)6015  static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6016    return SM.isInSystemHeader(D->getLocation()) ||
6017           SM.isInSystemMacro(D->getLocation());
6018  }
6019  
warnOnReservedIdentifier(const NamedDecl * D)6020  void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
6021    // Avoid warning twice on the same identifier, and don't warn on redeclaration
6022    // of system decl.
6023    if (D->getPreviousDecl() || D->isImplicit())
6024      return;
6025    ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
6026    if (Status != ReservedIdentifierStatus::NotReserved &&
6027        !isFromSystemHeader(Context.getSourceManager(), D)) {
6028      Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
6029          << D << static_cast<int>(Status);
6030    }
6031  }
6032  
ActOnDeclarator(Scope * S,Declarator & D)6033  Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
6034    D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6035  
6036    // Check if we are in an `omp begin/end declare variant` scope. Handle this
6037    // declaration only if the `bind_to_declaration` extension is set.
6038    SmallVector<FunctionDecl *, 4> Bases;
6039    if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
6040      if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(
6041              llvm::omp::TraitProperty::
6042                  implementation_extension_bind_to_declaration))
6043        OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6044            S, D, MultiTemplateParamsArg(), Bases);
6045  
6046    Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
6047  
6048    if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6049        Dcl && Dcl->getDeclContext()->isFileContext())
6050      Dcl->setTopLevelDeclInObjCContainer();
6051  
6052    if (!Bases.empty())
6053      OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl,
6054                                                                          Bases);
6055  
6056    return Dcl;
6057  }
6058  
DiagnoseClassNameShadow(DeclContext * DC,DeclarationNameInfo NameInfo)6059  bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
6060                                     DeclarationNameInfo NameInfo) {
6061    DeclarationName Name = NameInfo.getName();
6062  
6063    CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
6064    while (Record && Record->isAnonymousStructOrUnion())
6065      Record = dyn_cast<CXXRecordDecl>(Record->getParent());
6066    if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6067      Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
6068      return true;
6069    }
6070  
6071    return false;
6072  }
6073  
diagnoseQualifiedDeclaration(CXXScopeSpec & SS,DeclContext * DC,DeclarationName Name,SourceLocation Loc,TemplateIdAnnotation * TemplateId,bool IsMemberSpecialization)6074  bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
6075                                          DeclarationName Name,
6076                                          SourceLocation Loc,
6077                                          TemplateIdAnnotation *TemplateId,
6078                                          bool IsMemberSpecialization) {
6079    assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "
6080                           "without nested-name-specifier");
6081    DeclContext *Cur = CurContext;
6082    while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
6083      Cur = Cur->getParent();
6084  
6085    // If the user provided a superfluous scope specifier that refers back to the
6086    // class in which the entity is already declared, diagnose and ignore it.
6087    //
6088    // class X {
6089    //   void X::f();
6090    // };
6091    //
6092    // Note, it was once ill-formed to give redundant qualification in all
6093    // contexts, but that rule was removed by DR482.
6094    if (Cur->Equals(DC)) {
6095      if (Cur->isRecord()) {
6096        Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6097                                        : diag::err_member_extra_qualification)
6098          << Name << FixItHint::CreateRemoval(SS.getRange());
6099        SS.clear();
6100      } else {
6101        Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6102      }
6103      return false;
6104    }
6105  
6106    // Check whether the qualifying scope encloses the scope of the original
6107    // declaration. For a template-id, we perform the checks in
6108    // CheckTemplateSpecializationScope.
6109    if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6110      if (Cur->isRecord())
6111        Diag(Loc, diag::err_member_qualification)
6112          << Name << SS.getRange();
6113      else if (isa<TranslationUnitDecl>(DC))
6114        Diag(Loc, diag::err_invalid_declarator_global_scope)
6115          << Name << SS.getRange();
6116      else if (isa<FunctionDecl>(Cur))
6117        Diag(Loc, diag::err_invalid_declarator_in_function)
6118          << Name << SS.getRange();
6119      else if (isa<BlockDecl>(Cur))
6120        Diag(Loc, diag::err_invalid_declarator_in_block)
6121          << Name << SS.getRange();
6122      else if (isa<ExportDecl>(Cur)) {
6123        if (!isa<NamespaceDecl>(DC))
6124          Diag(Loc, diag::err_export_non_namespace_scope_name)
6125              << Name << SS.getRange();
6126        else
6127          // The cases that DC is not NamespaceDecl should be handled in
6128          // CheckRedeclarationExported.
6129          return false;
6130      } else
6131        Diag(Loc, diag::err_invalid_declarator_scope)
6132        << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6133  
6134      return true;
6135    }
6136  
6137    if (Cur->isRecord()) {
6138      // Cannot qualify members within a class.
6139      Diag(Loc, diag::err_member_qualification)
6140        << Name << SS.getRange();
6141      SS.clear();
6142  
6143      // C++ constructors and destructors with incorrect scopes can break
6144      // our AST invariants by having the wrong underlying types. If
6145      // that's the case, then drop this declaration entirely.
6146      if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6147           Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6148          !Context.hasSameType(Name.getCXXNameType(),
6149                               Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
6150        return true;
6151  
6152      return false;
6153    }
6154  
6155    // C++23 [temp.names]p5:
6156    //   The keyword template shall not appear immediately after a declarative
6157    //   nested-name-specifier.
6158    //
6159    // First check the template-id (if any), and then check each component of the
6160    // nested-name-specifier in reverse order.
6161    //
6162    // FIXME: nested-name-specifiers in friend declarations are declarative,
6163    // but we don't call diagnoseQualifiedDeclaration for them. We should.
6164    if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6165      Diag(Loc, diag::ext_template_after_declarative_nns)
6166          << FixItHint::CreateRemoval(TemplateId->TemplateKWLoc);
6167  
6168    NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
6169    do {
6170      if (SpecLoc.getNestedNameSpecifier()->getKind() ==
6171          NestedNameSpecifier::TypeSpecWithTemplate)
6172        Diag(Loc, diag::ext_template_after_declarative_nns)
6173            << FixItHint::CreateRemoval(
6174                   SpecLoc.getTypeLoc().getTemplateKeywordLoc());
6175  
6176      if (const Type *T = SpecLoc.getNestedNameSpecifier()->getAsType()) {
6177        if (const auto *TST = T->getAsAdjusted<TemplateSpecializationType>()) {
6178          // C++23 [expr.prim.id.qual]p3:
6179          //   [...] If a nested-name-specifier N is declarative and has a
6180          //   simple-template-id with a template argument list A that involves a
6181          //   template parameter, let T be the template nominated by N without A.
6182          //   T shall be a class template.
6183          if (TST->isDependentType() && TST->isTypeAlias())
6184            Diag(Loc, diag::ext_alias_template_in_declarative_nns)
6185                << SpecLoc.getLocalSourceRange();
6186        } else if (T->isDecltypeType() || T->getAsAdjusted<PackIndexingType>()) {
6187          // C++23 [expr.prim.id.qual]p2:
6188          //   [...] A declarative nested-name-specifier shall not have a
6189          //   computed-type-specifier.
6190          //
6191          // CWG2858 changed this from 'decltype-specifier' to
6192          // 'computed-type-specifier'.
6193          Diag(Loc, diag::err_computed_type_in_declarative_nns)
6194              << T->isDecltypeType() << SpecLoc.getTypeLoc().getSourceRange();
6195        }
6196      }
6197    } while ((SpecLoc = SpecLoc.getPrefix()));
6198  
6199    return false;
6200  }
6201  
HandleDeclarator(Scope * S,Declarator & D,MultiTemplateParamsArg TemplateParamLists)6202  NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
6203                                    MultiTemplateParamsArg TemplateParamLists) {
6204    // TODO: consider using NameInfo for diagnostic.
6205    DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6206    DeclarationName Name = NameInfo.getName();
6207  
6208    // All of these full declarators require an identifier.  If it doesn't have
6209    // one, the ParsedFreeStandingDeclSpec action should be used.
6210    if (D.isDecompositionDeclarator()) {
6211      return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6212    } else if (!Name) {
6213      if (!D.isInvalidType())  // Reject this if we think it is valid.
6214        Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6215            << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6216      return nullptr;
6217    } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
6218      return nullptr;
6219  
6220    DeclContext *DC = CurContext;
6221    if (D.getCXXScopeSpec().isInvalid())
6222      D.setInvalidType();
6223    else if (D.getCXXScopeSpec().isSet()) {
6224      if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
6225                                          UPPC_DeclarationQualifier))
6226        return nullptr;
6227  
6228      bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6229      DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6230      if (!DC || isa<EnumDecl>(DC)) {
6231        // If we could not compute the declaration context, it's because the
6232        // declaration context is dependent but does not refer to a class,
6233        // class template, or class template partial specialization. Complain
6234        // and return early, to avoid the coming semantic disaster.
6235        Diag(D.getIdentifierLoc(),
6236             diag::err_template_qualified_declarator_no_match)
6237          << D.getCXXScopeSpec().getScopeRep()
6238          << D.getCXXScopeSpec().getRange();
6239        return nullptr;
6240      }
6241      bool IsDependentContext = DC->isDependentContext();
6242  
6243      if (!IsDependentContext &&
6244          RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
6245        return nullptr;
6246  
6247      // If a class is incomplete, do not parse entities inside it.
6248      if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
6249        Diag(D.getIdentifierLoc(),
6250             diag::err_member_def_undefined_record)
6251          << Name << DC << D.getCXXScopeSpec().getRange();
6252        return nullptr;
6253      }
6254      if (!D.getDeclSpec().isFriendSpecified()) {
6255        TemplateIdAnnotation *TemplateId =
6256            D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6257                ? D.getName().TemplateId
6258                : nullptr;
6259        if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, Name,
6260                                         D.getIdentifierLoc(), TemplateId,
6261                                         /*IsMemberSpecialization=*/false)) {
6262          if (DC->isRecord())
6263            return nullptr;
6264  
6265          D.setInvalidType();
6266        }
6267      }
6268  
6269      // Check whether we need to rebuild the type of the given
6270      // declaration in the current instantiation.
6271      if (EnteringContext && IsDependentContext &&
6272          TemplateParamLists.size() != 0) {
6273        ContextRAII SavedContext(*this, DC);
6274        if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6275          D.setInvalidType();
6276      }
6277    }
6278  
6279    TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
6280    QualType R = TInfo->getType();
6281  
6282    if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6283                                        UPPC_DeclarationType))
6284      D.setInvalidType();
6285  
6286    LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6287                          forRedeclarationInCurContext());
6288  
6289    // See if this is a redefinition of a variable in the same scope.
6290    if (!D.getCXXScopeSpec().isSet()) {
6291      bool IsLinkageLookup = false;
6292      bool CreateBuiltins = false;
6293  
6294      // If the declaration we're planning to build will be a function
6295      // or object with linkage, then look for another declaration with
6296      // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6297      //
6298      // If the declaration we're planning to build will be declared with
6299      // external linkage in the translation unit, create any builtin with
6300      // the same name.
6301      if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6302        /* Do nothing*/;
6303      else if (CurContext->isFunctionOrMethod() &&
6304               (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6305                R->isFunctionType())) {
6306        IsLinkageLookup = true;
6307        CreateBuiltins =
6308            CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6309      } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6310                 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6311        CreateBuiltins = true;
6312  
6313      if (IsLinkageLookup) {
6314        Previous.clear(LookupRedeclarationWithLinkage);
6315        Previous.setRedeclarationKind(
6316            RedeclarationKind::ForExternalRedeclaration);
6317      }
6318  
6319      LookupName(Previous, S, CreateBuiltins);
6320    } else { // Something like "int foo::x;"
6321      LookupQualifiedName(Previous, DC);
6322  
6323      // C++ [dcl.meaning]p1:
6324      //   When the declarator-id is qualified, the declaration shall refer to a
6325      //  previously declared member of the class or namespace to which the
6326      //  qualifier refers (or, in the case of a namespace, of an element of the
6327      //  inline namespace set of that namespace (7.3.1)) or to a specialization
6328      //  thereof; [...]
6329      //
6330      // Note that we already checked the context above, and that we do not have
6331      // enough information to make sure that Previous contains the declaration
6332      // we want to match. For example, given:
6333      //
6334      //   class X {
6335      //     void f();
6336      //     void f(float);
6337      //   };
6338      //
6339      //   void X::f(int) { } // ill-formed
6340      //
6341      // In this case, Previous will point to the overload set
6342      // containing the two f's declared in X, but neither of them
6343      // matches.
6344  
6345      RemoveUsingDecls(Previous);
6346    }
6347  
6348    if (auto *TPD = Previous.getAsSingle<NamedDecl>();
6349        TPD && TPD->isTemplateParameter()) {
6350      // Older versions of clang allowed the names of function/variable templates
6351      // to shadow the names of their template parameters. For the compatibility
6352      // purposes we detect such cases and issue a default-to-error warning that
6353      // can be disabled with -Wno-strict-primary-template-shadow.
6354      if (!D.isInvalidType()) {
6355        bool AllowForCompatibility = false;
6356        if (Scope *DeclParent = S->getDeclParent();
6357            Scope *TemplateParamParent = S->getTemplateParamParent()) {
6358          AllowForCompatibility = DeclParent->Contains(*TemplateParamParent) &&
6359                                  TemplateParamParent->isDeclScope(TPD);
6360        }
6361        DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), TPD,
6362                                        AllowForCompatibility);
6363      }
6364  
6365      // Just pretend that we didn't see the previous declaration.
6366      Previous.clear();
6367    }
6368  
6369    if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6370      // Forget that the previous declaration is the injected-class-name.
6371      Previous.clear();
6372  
6373    // In C++, the previous declaration we find might be a tag type
6374    // (class or enum). In this case, the new declaration will hide the
6375    // tag type. Note that this applies to functions, function templates, and
6376    // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6377    if (Previous.isSingleTagDecl() &&
6378        D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6379        (TemplateParamLists.size() == 0 || R->isFunctionType()))
6380      Previous.clear();
6381  
6382    // Check that there are no default arguments other than in the parameters
6383    // of a function declaration (C++ only).
6384    if (getLangOpts().CPlusPlus)
6385      CheckExtraCXXDefaultArguments(D);
6386  
6387    /// Get the innermost enclosing declaration scope.
6388    S = S->getDeclParent();
6389  
6390    NamedDecl *New;
6391  
6392    bool AddToScope = true;
6393    if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6394      if (TemplateParamLists.size()) {
6395        Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6396        return nullptr;
6397      }
6398  
6399      New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6400    } else if (R->isFunctionType()) {
6401      New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6402                                    TemplateParamLists,
6403                                    AddToScope);
6404    } else {
6405      New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6406                                    AddToScope);
6407    }
6408  
6409    if (!New)
6410      return nullptr;
6411  
6412    // If this has an identifier and is not a function template specialization,
6413    // add it to the scope stack.
6414    if (New->getDeclName() && AddToScope)
6415      PushOnScopeChains(New, S);
6416  
6417    if (OpenMP().isInOpenMPDeclareTargetContext())
6418      OpenMP().checkDeclIsAllowedInOpenMPTarget(nullptr, New);
6419  
6420    return New;
6421  }
6422  
6423  /// Helper method to turn variable array types into constant array
6424  /// types in certain situations which would otherwise be errors (for
6425  /// GCC compatibility).
TryToFixInvalidVariablyModifiedType(QualType T,ASTContext & Context,bool & SizeIsNegative,llvm::APSInt & Oversized)6426  static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6427                                                      ASTContext &Context,
6428                                                      bool &SizeIsNegative,
6429                                                      llvm::APSInt &Oversized) {
6430    // This method tries to turn a variable array into a constant
6431    // array even when the size isn't an ICE.  This is necessary
6432    // for compatibility with code that depends on gcc's buggy
6433    // constant expression folding, like struct {char x[(int)(char*)2];}
6434    SizeIsNegative = false;
6435    Oversized = 0;
6436  
6437    if (T->isDependentType())
6438      return QualType();
6439  
6440    QualifierCollector Qs;
6441    const Type *Ty = Qs.strip(T);
6442  
6443    if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6444      QualType Pointee = PTy->getPointeeType();
6445      QualType FixedType =
6446          TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6447                                              Oversized);
6448      if (FixedType.isNull()) return FixedType;
6449      FixedType = Context.getPointerType(FixedType);
6450      return Qs.apply(Context, FixedType);
6451    }
6452    if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6453      QualType Inner = PTy->getInnerType();
6454      QualType FixedType =
6455          TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6456                                              Oversized);
6457      if (FixedType.isNull()) return FixedType;
6458      FixedType = Context.getParenType(FixedType);
6459      return Qs.apply(Context, FixedType);
6460    }
6461  
6462    const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6463    if (!VLATy)
6464      return QualType();
6465  
6466    QualType ElemTy = VLATy->getElementType();
6467    if (ElemTy->isVariablyModifiedType()) {
6468      ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6469                                                   SizeIsNegative, Oversized);
6470      if (ElemTy.isNull())
6471        return QualType();
6472    }
6473  
6474    Expr::EvalResult Result;
6475    if (!VLATy->getSizeExpr() ||
6476        !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6477      return QualType();
6478  
6479    llvm::APSInt Res = Result.Val.getInt();
6480  
6481    // Check whether the array size is negative.
6482    if (Res.isSigned() && Res.isNegative()) {
6483      SizeIsNegative = true;
6484      return QualType();
6485    }
6486  
6487    // Check whether the array is too large to be addressed.
6488    unsigned ActiveSizeBits =
6489        (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6490         !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6491            ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6492            : Res.getActiveBits();
6493    if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6494      Oversized = Res;
6495      return QualType();
6496    }
6497  
6498    QualType FoldedArrayType = Context.getConstantArrayType(
6499        ElemTy, Res, VLATy->getSizeExpr(), ArraySizeModifier::Normal, 0);
6500    return Qs.apply(Context, FoldedArrayType);
6501  }
6502  
6503  static void
FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL,TypeLoc DstTL)6504  FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6505    SrcTL = SrcTL.getUnqualifiedLoc();
6506    DstTL = DstTL.getUnqualifiedLoc();
6507    if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6508      PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6509      FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6510                                        DstPTL.getPointeeLoc());
6511      DstPTL.setStarLoc(SrcPTL.getStarLoc());
6512      return;
6513    }
6514    if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6515      ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6516      FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6517                                        DstPTL.getInnerLoc());
6518      DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6519      DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6520      return;
6521    }
6522    ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6523    ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6524    TypeLoc SrcElemTL = SrcATL.getElementLoc();
6525    TypeLoc DstElemTL = DstATL.getElementLoc();
6526    if (VariableArrayTypeLoc SrcElemATL =
6527            SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6528      ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6529      FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6530    } else {
6531      DstElemTL.initializeFullCopy(SrcElemTL);
6532    }
6533    DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6534    DstATL.setSizeExpr(SrcATL.getSizeExpr());
6535    DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6536  }
6537  
6538  /// Helper method to turn variable array types into constant array
6539  /// types in certain situations which would otherwise be errors (for
6540  /// GCC compatibility).
6541  static TypeSourceInfo*
TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo * TInfo,ASTContext & Context,bool & SizeIsNegative,llvm::APSInt & Oversized)6542  TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6543                                                ASTContext &Context,
6544                                                bool &SizeIsNegative,
6545                                                llvm::APSInt &Oversized) {
6546    QualType FixedTy
6547      = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6548                                            SizeIsNegative, Oversized);
6549    if (FixedTy.isNull())
6550      return nullptr;
6551    TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6552    FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6553                                      FixedTInfo->getTypeLoc());
6554    return FixedTInfo;
6555  }
6556  
tryToFixVariablyModifiedVarType(TypeSourceInfo * & TInfo,QualType & T,SourceLocation Loc,unsigned FailedFoldDiagID)6557  bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6558                                             QualType &T, SourceLocation Loc,
6559                                             unsigned FailedFoldDiagID) {
6560    bool SizeIsNegative;
6561    llvm::APSInt Oversized;
6562    TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6563        TInfo, Context, SizeIsNegative, Oversized);
6564    if (FixedTInfo) {
6565      Diag(Loc, diag::ext_vla_folded_to_constant);
6566      TInfo = FixedTInfo;
6567      T = FixedTInfo->getType();
6568      return true;
6569    }
6570  
6571    if (SizeIsNegative)
6572      Diag(Loc, diag::err_typecheck_negative_array_size);
6573    else if (Oversized.getBoolValue())
6574      Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6575    else if (FailedFoldDiagID)
6576      Diag(Loc, FailedFoldDiagID);
6577    return false;
6578  }
6579  
6580  void
RegisterLocallyScopedExternCDecl(NamedDecl * ND,Scope * S)6581  Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6582    if (!getLangOpts().CPlusPlus &&
6583        ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6584      // Don't need to track declarations in the TU in C.
6585      return;
6586  
6587    // Note that we have a locally-scoped external with this name.
6588    Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6589  }
6590  
findLocallyScopedExternCDecl(DeclarationName Name)6591  NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6592    // FIXME: We can have multiple results via __attribute__((overloadable)).
6593    auto Result = Context.getExternCContextDecl()->lookup(Name);
6594    return Result.empty() ? nullptr : *Result.begin();
6595  }
6596  
DiagnoseFunctionSpecifiers(const DeclSpec & DS)6597  void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6598    // FIXME: We should probably indicate the identifier in question to avoid
6599    // confusion for constructs like "virtual int a(), b;"
6600    if (DS.isVirtualSpecified())
6601      Diag(DS.getVirtualSpecLoc(),
6602           diag::err_virtual_non_function);
6603  
6604    if (DS.hasExplicitSpecifier())
6605      Diag(DS.getExplicitSpecLoc(),
6606           diag::err_explicit_non_function);
6607  
6608    if (DS.isNoreturnSpecified())
6609      Diag(DS.getNoreturnSpecLoc(),
6610           diag::err_noreturn_non_function);
6611  }
6612  
6613  NamedDecl*
ActOnTypedefDeclarator(Scope * S,Declarator & D,DeclContext * DC,TypeSourceInfo * TInfo,LookupResult & Previous)6614  Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6615                               TypeSourceInfo *TInfo, LookupResult &Previous) {
6616    // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6617    if (D.getCXXScopeSpec().isSet()) {
6618      Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6619        << D.getCXXScopeSpec().getRange();
6620      D.setInvalidType();
6621      // Pretend we didn't see the scope specifier.
6622      DC = CurContext;
6623      Previous.clear();
6624    }
6625  
6626    DiagnoseFunctionSpecifiers(D.getDeclSpec());
6627  
6628    if (D.getDeclSpec().isInlineSpecified())
6629      Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6630          << getLangOpts().CPlusPlus17;
6631    if (D.getDeclSpec().hasConstexprSpecifier())
6632      Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6633          << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6634  
6635    if (D.getName().getKind() != UnqualifiedIdKind::IK_Identifier) {
6636      if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
6637        Diag(D.getName().StartLocation,
6638             diag::err_deduction_guide_invalid_specifier)
6639            << "typedef";
6640      else
6641        Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6642            << D.getName().getSourceRange();
6643      return nullptr;
6644    }
6645  
6646    TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6647    if (!NewTD) return nullptr;
6648  
6649    // Handle attributes prior to checking for duplicates in MergeVarDecl
6650    ProcessDeclAttributes(S, NewTD, D);
6651  
6652    CheckTypedefForVariablyModifiedType(S, NewTD);
6653  
6654    bool Redeclaration = D.isRedeclaration();
6655    NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6656    D.setRedeclaration(Redeclaration);
6657    return ND;
6658  }
6659  
6660  void
CheckTypedefForVariablyModifiedType(Scope * S,TypedefNameDecl * NewTD)6661  Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6662    // C99 6.7.7p2: If a typedef name specifies a variably modified type
6663    // then it shall have block scope.
6664    // Note that variably modified types must be fixed before merging the decl so
6665    // that redeclarations will match.
6666    TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6667    QualType T = TInfo->getType();
6668    if (T->isVariablyModifiedType()) {
6669      setFunctionHasBranchProtectedScope();
6670  
6671      if (S->getFnParent() == nullptr) {
6672        bool SizeIsNegative;
6673        llvm::APSInt Oversized;
6674        TypeSourceInfo *FixedTInfo =
6675          TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6676                                                        SizeIsNegative,
6677                                                        Oversized);
6678        if (FixedTInfo) {
6679          Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6680          NewTD->setTypeSourceInfo(FixedTInfo);
6681        } else {
6682          if (SizeIsNegative)
6683            Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6684          else if (T->isVariableArrayType())
6685            Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6686          else if (Oversized.getBoolValue())
6687            Diag(NewTD->getLocation(), diag::err_array_too_large)
6688              << toString(Oversized, 10);
6689          else
6690            Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6691          NewTD->setInvalidDecl();
6692        }
6693      }
6694    }
6695  }
6696  
6697  NamedDecl*
ActOnTypedefNameDecl(Scope * S,DeclContext * DC,TypedefNameDecl * NewTD,LookupResult & Previous,bool & Redeclaration)6698  Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6699                             LookupResult &Previous, bool &Redeclaration) {
6700  
6701    // Find the shadowed declaration before filtering for scope.
6702    NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6703  
6704    // Merge the decl with the existing one if appropriate. If the decl is
6705    // in an outer scope, it isn't the same thing.
6706    FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6707                         /*AllowInlineNamespace*/false);
6708    filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6709    if (!Previous.empty()) {
6710      Redeclaration = true;
6711      MergeTypedefNameDecl(S, NewTD, Previous);
6712    } else {
6713      inferGslPointerAttribute(NewTD);
6714    }
6715  
6716    if (ShadowedDecl && !Redeclaration)
6717      CheckShadow(NewTD, ShadowedDecl, Previous);
6718  
6719    // If this is the C FILE type, notify the AST context.
6720    if (IdentifierInfo *II = NewTD->getIdentifier())
6721      if (!NewTD->isInvalidDecl() &&
6722          NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6723        switch (II->getNotableIdentifierID()) {
6724        case tok::NotableIdentifierKind::FILE:
6725          Context.setFILEDecl(NewTD);
6726          break;
6727        case tok::NotableIdentifierKind::jmp_buf:
6728          Context.setjmp_bufDecl(NewTD);
6729          break;
6730        case tok::NotableIdentifierKind::sigjmp_buf:
6731          Context.setsigjmp_bufDecl(NewTD);
6732          break;
6733        case tok::NotableIdentifierKind::ucontext_t:
6734          Context.setucontext_tDecl(NewTD);
6735          break;
6736        case tok::NotableIdentifierKind::float_t:
6737        case tok::NotableIdentifierKind::double_t:
6738          NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context));
6739          break;
6740        default:
6741          break;
6742        }
6743      }
6744  
6745    return NewTD;
6746  }
6747  
6748  /// Determines whether the given declaration is an out-of-scope
6749  /// previous declaration.
6750  ///
6751  /// This routine should be invoked when name lookup has found a
6752  /// previous declaration (PrevDecl) that is not in the scope where a
6753  /// new declaration by the same name is being introduced. If the new
6754  /// declaration occurs in a local scope, previous declarations with
6755  /// linkage may still be considered previous declarations (C99
6756  /// 6.2.2p4-5, C++ [basic.link]p6).
6757  ///
6758  /// \param PrevDecl the previous declaration found by name
6759  /// lookup
6760  ///
6761  /// \param DC the context in which the new declaration is being
6762  /// declared.
6763  ///
6764  /// \returns true if PrevDecl is an out-of-scope previous declaration
6765  /// for a new delcaration with the same name.
6766  static bool
isOutOfScopePreviousDeclaration(NamedDecl * PrevDecl,DeclContext * DC,ASTContext & Context)6767  isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6768                                  ASTContext &Context) {
6769    if (!PrevDecl)
6770      return false;
6771  
6772    if (!PrevDecl->hasLinkage())
6773      return false;
6774  
6775    if (Context.getLangOpts().CPlusPlus) {
6776      // C++ [basic.link]p6:
6777      //   If there is a visible declaration of an entity with linkage
6778      //   having the same name and type, ignoring entities declared
6779      //   outside the innermost enclosing namespace scope, the block
6780      //   scope declaration declares that same entity and receives the
6781      //   linkage of the previous declaration.
6782      DeclContext *OuterContext = DC->getRedeclContext();
6783      if (!OuterContext->isFunctionOrMethod())
6784        // This rule only applies to block-scope declarations.
6785        return false;
6786  
6787      DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6788      if (PrevOuterContext->isRecord())
6789        // We found a member function: ignore it.
6790        return false;
6791  
6792      // Find the innermost enclosing namespace for the new and
6793      // previous declarations.
6794      OuterContext = OuterContext->getEnclosingNamespaceContext();
6795      PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6796  
6797      // The previous declaration is in a different namespace, so it
6798      // isn't the same function.
6799      if (!OuterContext->Equals(PrevOuterContext))
6800        return false;
6801    }
6802  
6803    return true;
6804  }
6805  
SetNestedNameSpecifier(Sema & S,DeclaratorDecl * DD,Declarator & D)6806  static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6807    CXXScopeSpec &SS = D.getCXXScopeSpec();
6808    if (!SS.isSet()) return;
6809    DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6810  }
6811  
deduceOpenCLAddressSpace(ValueDecl * Decl)6812  void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6813    if (Decl->getType().hasAddressSpace())
6814      return;
6815    if (Decl->getType()->isDependentType())
6816      return;
6817    if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6818      QualType Type = Var->getType();
6819      if (Type->isSamplerT() || Type->isVoidType())
6820        return;
6821      LangAS ImplAS = LangAS::opencl_private;
6822      // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6823      // __opencl_c_program_scope_global_variables feature, the address space
6824      // for a variable at program scope or a static or extern variable inside
6825      // a function are inferred to be __global.
6826      if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6827          Var->hasGlobalStorage())
6828        ImplAS = LangAS::opencl_global;
6829      // If the original type from a decayed type is an array type and that array
6830      // type has no address space yet, deduce it now.
6831      if (auto DT = dyn_cast<DecayedType>(Type)) {
6832        auto OrigTy = DT->getOriginalType();
6833        if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6834          // Add the address space to the original array type and then propagate
6835          // that to the element type through `getAsArrayType`.
6836          OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6837          OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6838          // Re-generate the decayed type.
6839          Type = Context.getDecayedType(OrigTy);
6840        }
6841      }
6842      Type = Context.getAddrSpaceQualType(Type, ImplAS);
6843      // Apply any qualifiers (including address space) from the array type to
6844      // the element type. This implements C99 6.7.3p8: "If the specification of
6845      // an array type includes any type qualifiers, the element type is so
6846      // qualified, not the array type."
6847      if (Type->isArrayType())
6848        Type = QualType(Context.getAsArrayType(Type), 0);
6849      Decl->setType(Type);
6850    }
6851  }
6852  
checkAttributesAfterMerging(Sema & S,NamedDecl & ND)6853  static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6854    // Ensure that an auto decl is deduced otherwise the checks below might cache
6855    // the wrong linkage.
6856    assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6857  
6858    // 'weak' only applies to declarations with external linkage.
6859    if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6860      if (!ND.isExternallyVisible()) {
6861        S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6862        ND.dropAttr<WeakAttr>();
6863      }
6864    }
6865    if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6866      if (ND.isExternallyVisible()) {
6867        S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6868        ND.dropAttrs<WeakRefAttr, AliasAttr>();
6869      }
6870    }
6871  
6872    if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6873      if (VD->hasInit()) {
6874        if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6875          assert(VD->isThisDeclarationADefinition() &&
6876                 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6877          S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6878          VD->dropAttr<AliasAttr>();
6879        }
6880      }
6881    }
6882  
6883    // 'selectany' only applies to externally visible variable declarations.
6884    // It does not apply to functions.
6885    if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6886      if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6887        S.Diag(Attr->getLocation(),
6888               diag::err_attribute_selectany_non_extern_data);
6889        ND.dropAttr<SelectAnyAttr>();
6890      }
6891    }
6892  
6893    if (HybridPatchableAttr *Attr = ND.getAttr<HybridPatchableAttr>()) {
6894      if (!ND.isExternallyVisible())
6895        S.Diag(Attr->getLocation(),
6896               diag::warn_attribute_hybrid_patchable_non_extern);
6897    }
6898    if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6899      auto *VD = dyn_cast<VarDecl>(&ND);
6900      bool IsAnonymousNS = false;
6901      bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6902      if (VD) {
6903        const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6904        while (NS && !IsAnonymousNS) {
6905          IsAnonymousNS = NS->isAnonymousNamespace();
6906          NS = dyn_cast<NamespaceDecl>(NS->getParent());
6907        }
6908      }
6909      // dll attributes require external linkage. Static locals may have external
6910      // linkage but still cannot be explicitly imported or exported.
6911      // In Microsoft mode, a variable defined in anonymous namespace must have
6912      // external linkage in order to be exported.
6913      bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6914      if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6915          (!AnonNSInMicrosoftMode &&
6916           (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6917        S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6918          << &ND << Attr;
6919        ND.setInvalidDecl();
6920      }
6921    }
6922  
6923    // Check the attributes on the function type, if any.
6924    if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6925      // Don't declare this variable in the second operand of the for-statement;
6926      // GCC miscompiles that by ending its lifetime before evaluating the
6927      // third operand. See gcc.gnu.org/PR86769.
6928      AttributedTypeLoc ATL;
6929      for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6930           (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6931           TL = ATL.getModifiedLoc()) {
6932        // The [[lifetimebound]] attribute can be applied to the implicit object
6933        // parameter of a non-static member function (other than a ctor or dtor)
6934        // by applying it to the function type.
6935        if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6936          const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6937          if (!MD || MD->isStatic()) {
6938            S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6939                << !MD << A->getRange();
6940          } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6941            S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6942                << isa<CXXDestructorDecl>(MD) << A->getRange();
6943          }
6944        }
6945      }
6946    }
6947  }
6948  
checkDLLAttributeRedeclaration(Sema & S,NamedDecl * OldDecl,NamedDecl * NewDecl,bool IsSpecialization,bool IsDefinition)6949  static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6950                                             NamedDecl *NewDecl,
6951                                             bool IsSpecialization,
6952                                             bool IsDefinition) {
6953    if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6954      return;
6955  
6956    bool IsTemplate = false;
6957    if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6958      OldDecl = OldTD->getTemplatedDecl();
6959      IsTemplate = true;
6960      if (!IsSpecialization)
6961        IsDefinition = false;
6962    }
6963    if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6964      NewDecl = NewTD->getTemplatedDecl();
6965      IsTemplate = true;
6966    }
6967  
6968    if (!OldDecl || !NewDecl)
6969      return;
6970  
6971    const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6972    const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6973    const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6974    const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6975  
6976    // dllimport and dllexport are inheritable attributes so we have to exclude
6977    // inherited attribute instances.
6978    bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6979                      (NewExportAttr && !NewExportAttr->isInherited());
6980  
6981    // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6982    // the only exception being explicit specializations.
6983    // Implicitly generated declarations are also excluded for now because there
6984    // is no other way to switch these to use dllimport or dllexport.
6985    bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6986  
6987    if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6988      // Allow with a warning for free functions and global variables.
6989      bool JustWarn = false;
6990      if (!OldDecl->isCXXClassMember()) {
6991        auto *VD = dyn_cast<VarDecl>(OldDecl);
6992        if (VD && !VD->getDescribedVarTemplate())
6993          JustWarn = true;
6994        auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6995        if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6996          JustWarn = true;
6997      }
6998  
6999      // We cannot change a declaration that's been used because IR has already
7000      // been emitted. Dllimported functions will still work though (modulo
7001      // address equality) as they can use the thunk.
7002      if (OldDecl->isUsed())
7003        if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
7004          JustWarn = false;
7005  
7006      unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7007                                 : diag::err_attribute_dll_redeclaration;
7008      S.Diag(NewDecl->getLocation(), DiagID)
7009          << NewDecl
7010          << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7011      S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7012      if (!JustWarn) {
7013        NewDecl->setInvalidDecl();
7014        return;
7015      }
7016    }
7017  
7018    // A redeclaration is not allowed to drop a dllimport attribute, the only
7019    // exceptions being inline function definitions (except for function
7020    // templates), local extern declarations, qualified friend declarations or
7021    // special MSVC extension: in the last case, the declaration is treated as if
7022    // it were marked dllexport.
7023    bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7024    bool IsMicrosoftABI  = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7025    if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
7026      // Ignore static data because out-of-line definitions are diagnosed
7027      // separately.
7028      IsStaticDataMember = VD->isStaticDataMember();
7029      IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7030                     VarDecl::DeclarationOnly;
7031    } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
7032      IsInline = FD->isInlined();
7033      IsQualifiedFriend = FD->getQualifier() &&
7034                          FD->getFriendObjectKind() == Decl::FOK_Declared;
7035    }
7036  
7037    if (OldImportAttr && !HasNewAttr &&
7038        (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7039        !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7040      if (IsMicrosoftABI && IsDefinition) {
7041        if (IsSpecialization) {
7042          S.Diag(
7043              NewDecl->getLocation(),
7044              diag::err_attribute_dllimport_function_specialization_definition);
7045          S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
7046          NewDecl->dropAttr<DLLImportAttr>();
7047        } else {
7048          S.Diag(NewDecl->getLocation(),
7049                 diag::warn_redeclaration_without_import_attribute)
7050              << NewDecl;
7051          S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7052          NewDecl->dropAttr<DLLImportAttr>();
7053          NewDecl->addAttr(DLLExportAttr::CreateImplicit(
7054              S.Context, NewImportAttr->getRange()));
7055        }
7056      } else if (IsMicrosoftABI && IsSpecialization) {
7057        assert(!IsDefinition);
7058        // MSVC allows this. Keep the inherited attribute.
7059      } else {
7060        S.Diag(NewDecl->getLocation(),
7061               diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7062            << NewDecl << OldImportAttr;
7063        S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7064        S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
7065        OldDecl->dropAttr<DLLImportAttr>();
7066        NewDecl->dropAttr<DLLImportAttr>();
7067      }
7068    } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7069      // In MinGW, seeing a function declared inline drops the dllimport
7070      // attribute.
7071      OldDecl->dropAttr<DLLImportAttr>();
7072      NewDecl->dropAttr<DLLImportAttr>();
7073      S.Diag(NewDecl->getLocation(),
7074             diag::warn_dllimport_dropped_from_inline_function)
7075          << NewDecl << OldImportAttr;
7076    }
7077  
7078    // A specialization of a class template member function is processed here
7079    // since it's a redeclaration. If the parent class is dllexport, the
7080    // specialization inherits that attribute. This doesn't happen automatically
7081    // since the parent class isn't instantiated until later.
7082    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
7083      if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7084          !NewImportAttr && !NewExportAttr) {
7085        if (const DLLExportAttr *ParentExportAttr =
7086                MD->getParent()->getAttr<DLLExportAttr>()) {
7087          DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
7088          NewAttr->setInherited(true);
7089          NewDecl->addAttr(NewAttr);
7090        }
7091      }
7092    }
7093  }
7094  
7095  /// Given that we are within the definition of the given function,
7096  /// will that definition behave like C99's 'inline', where the
7097  /// definition is discarded except for optimization purposes?
isFunctionDefinitionDiscarded(Sema & S,FunctionDecl * FD)7098  static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
7099    // Try to avoid calling GetGVALinkageForFunction.
7100  
7101    // All cases of this require the 'inline' keyword.
7102    if (!FD->isInlined()) return false;
7103  
7104    // This is only possible in C++ with the gnu_inline attribute.
7105    if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7106      return false;
7107  
7108    // Okay, go ahead and call the relatively-more-expensive function.
7109    return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
7110  }
7111  
7112  /// Determine whether a variable is extern "C" prior to attaching
7113  /// an initializer. We can't just call isExternC() here, because that
7114  /// will also compute and cache whether the declaration is externally
7115  /// visible, which might change when we attach the initializer.
7116  ///
7117  /// This can only be used if the declaration is known to not be a
7118  /// redeclaration of an internal linkage declaration.
7119  ///
7120  /// For instance:
7121  ///
7122  ///   auto x = []{};
7123  ///
7124  /// Attaching the initializer here makes this declaration not externally
7125  /// visible, because its type has internal linkage.
7126  ///
7127  /// FIXME: This is a hack.
7128  template<typename T>
isIncompleteDeclExternC(Sema & S,const T * D)7129  static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7130    if (S.getLangOpts().CPlusPlus) {
7131      // In C++, the overloadable attribute negates the effects of extern "C".
7132      if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7133        return false;
7134  
7135      // So do CUDA's host/device attributes.
7136      if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7137                                   D->template hasAttr<CUDAHostAttr>()))
7138        return false;
7139    }
7140    return D->isExternC();
7141  }
7142  
shouldConsiderLinkage(const VarDecl * VD)7143  static bool shouldConsiderLinkage(const VarDecl *VD) {
7144    const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7145    if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
7146        isa<OMPDeclareMapperDecl>(DC))
7147      return VD->hasExternalStorage();
7148    if (DC->isFileContext())
7149      return true;
7150    if (DC->isRecord())
7151      return false;
7152    if (DC->getDeclKind() == Decl::HLSLBuffer)
7153      return false;
7154  
7155    if (isa<RequiresExprBodyDecl>(DC))
7156      return false;
7157    llvm_unreachable("Unexpected context");
7158  }
7159  
shouldConsiderLinkage(const FunctionDecl * FD)7160  static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7161    const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7162    if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7163        isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
7164      return true;
7165    if (DC->isRecord())
7166      return false;
7167    llvm_unreachable("Unexpected context");
7168  }
7169  
hasParsedAttr(Scope * S,const Declarator & PD,ParsedAttr::Kind Kind)7170  static bool hasParsedAttr(Scope *S, const Declarator &PD,
7171                            ParsedAttr::Kind Kind) {
7172    // Check decl attributes on the DeclSpec.
7173    if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7174      return true;
7175  
7176    // Walk the declarator structure, checking decl attributes that were in a type
7177    // position to the decl itself.
7178    for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7179      if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7180        return true;
7181    }
7182  
7183    // Finally, check attributes on the decl itself.
7184    return PD.getAttributes().hasAttribute(Kind) ||
7185           PD.getDeclarationAttributes().hasAttribute(Kind);
7186  }
7187  
adjustContextForLocalExternDecl(DeclContext * & DC)7188  bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
7189    if (!DC->isFunctionOrMethod())
7190      return false;
7191  
7192    // If this is a local extern function or variable declared within a function
7193    // template, don't add it into the enclosing namespace scope until it is
7194    // instantiated; it might have a dependent type right now.
7195    if (DC->isDependentContext())
7196      return true;
7197  
7198    // C++11 [basic.link]p7:
7199    //   When a block scope declaration of an entity with linkage is not found to
7200    //   refer to some other declaration, then that entity is a member of the
7201    //   innermost enclosing namespace.
7202    //
7203    // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7204    // semantically-enclosing namespace, not a lexically-enclosing one.
7205    while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7206      DC = DC->getParent();
7207    return true;
7208  }
7209  
7210  /// Returns true if given declaration has external C language linkage.
isDeclExternC(const Decl * D)7211  static bool isDeclExternC(const Decl *D) {
7212    if (const auto *FD = dyn_cast<FunctionDecl>(D))
7213      return FD->isExternC();
7214    if (const auto *VD = dyn_cast<VarDecl>(D))
7215      return VD->isExternC();
7216  
7217    llvm_unreachable("Unknown type of decl!");
7218  }
7219  
7220  /// Returns true if there hasn't been any invalid type diagnosed.
diagnoseOpenCLTypes(Sema & Se,VarDecl * NewVD)7221  static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7222    DeclContext *DC = NewVD->getDeclContext();
7223    QualType R = NewVD->getType();
7224  
7225    // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7226    // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7227    // argument.
7228    if (R->isImageType() || R->isPipeType()) {
7229      Se.Diag(NewVD->getLocation(),
7230              diag::err_opencl_type_can_only_be_used_as_function_parameter)
7231          << R;
7232      NewVD->setInvalidDecl();
7233      return false;
7234    }
7235  
7236    // OpenCL v1.2 s6.9.r:
7237    // The event type cannot be used to declare a program scope variable.
7238    // OpenCL v2.0 s6.9.q:
7239    // The clk_event_t and reserve_id_t types cannot be declared in program
7240    // scope.
7241    if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7242      if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7243        Se.Diag(NewVD->getLocation(),
7244                diag::err_invalid_type_for_program_scope_var)
7245            << R;
7246        NewVD->setInvalidDecl();
7247        return false;
7248      }
7249    }
7250  
7251    // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7252    if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7253                                                 Se.getLangOpts())) {
7254      QualType NR = R.getCanonicalType();
7255      while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7256             NR->isReferenceType()) {
7257        if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
7258            NR->isFunctionReferenceType()) {
7259          Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7260              << NR->isReferenceType();
7261          NewVD->setInvalidDecl();
7262          return false;
7263        }
7264        NR = NR->getPointeeType();
7265      }
7266    }
7267  
7268    if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7269                                                 Se.getLangOpts())) {
7270      // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7271      // half array type (unless the cl_khr_fp16 extension is enabled).
7272      if (Se.Context.getBaseElementType(R)->isHalfType()) {
7273        Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7274        NewVD->setInvalidDecl();
7275        return false;
7276      }
7277    }
7278  
7279    // OpenCL v1.2 s6.9.r:
7280    // The event type cannot be used with the __local, __constant and __global
7281    // address space qualifiers.
7282    if (R->isEventT()) {
7283      if (R.getAddressSpace() != LangAS::opencl_private) {
7284        Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7285        NewVD->setInvalidDecl();
7286        return false;
7287      }
7288    }
7289  
7290    if (R->isSamplerT()) {
7291      // OpenCL v1.2 s6.9.b p4:
7292      // The sampler type cannot be used with the __local and __global address
7293      // space qualifiers.
7294      if (R.getAddressSpace() == LangAS::opencl_local ||
7295          R.getAddressSpace() == LangAS::opencl_global) {
7296        Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7297        NewVD->setInvalidDecl();
7298      }
7299  
7300      // OpenCL v1.2 s6.12.14.1:
7301      // A global sampler must be declared with either the constant address
7302      // space qualifier or with the const qualifier.
7303      if (DC->isTranslationUnit() &&
7304          !(R.getAddressSpace() == LangAS::opencl_constant ||
7305            R.isConstQualified())) {
7306        Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7307        NewVD->setInvalidDecl();
7308      }
7309      if (NewVD->isInvalidDecl())
7310        return false;
7311    }
7312  
7313    return true;
7314  }
7315  
7316  template <typename AttrTy>
copyAttrFromTypedefToDecl(Sema & S,Decl * D,const TypedefType * TT)7317  static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7318    const TypedefNameDecl *TND = TT->getDecl();
7319    if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7320      AttrTy *Clone = Attribute->clone(S.Context);
7321      Clone->setInherited(true);
7322      D->addAttr(Clone);
7323    }
7324  }
7325  
7326  // This function emits warning and a corresponding note based on the
7327  // ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7328  // declarations of an annotated type must be const qualified.
emitReadOnlyPlacementAttrWarning(Sema & S,const VarDecl * VD)7329  void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD) {
7330    QualType VarType = VD->getType().getCanonicalType();
7331  
7332    // Ignore local declarations (for now) and those with const qualification.
7333    // TODO: Local variables should not be allowed if their type declaration has
7334    // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7335    if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7336      return;
7337  
7338    if (VarType->isArrayType()) {
7339      // Retrieve element type for array declarations.
7340      VarType = S.getASTContext().getBaseElementType(VarType);
7341    }
7342  
7343    const RecordDecl *RD = VarType->getAsRecordDecl();
7344  
7345    // Check if the record declaration is present and if it has any attributes.
7346    if (RD == nullptr)
7347      return;
7348  
7349    if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7350      S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;
7351      S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);
7352      return;
7353    }
7354  }
7355  
ActOnVariableDeclarator(Scope * S,Declarator & D,DeclContext * DC,TypeSourceInfo * TInfo,LookupResult & Previous,MultiTemplateParamsArg TemplateParamLists,bool & AddToScope,ArrayRef<BindingDecl * > Bindings)7356  NamedDecl *Sema::ActOnVariableDeclarator(
7357      Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7358      LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7359      bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7360    QualType R = TInfo->getType();
7361    DeclarationName Name = GetNameForDeclarator(D).getName();
7362  
7363    IdentifierInfo *II = Name.getAsIdentifierInfo();
7364    bool IsPlaceholderVariable = false;
7365  
7366    if (D.isDecompositionDeclarator()) {
7367      // Take the name of the first declarator as our name for diagnostic
7368      // purposes.
7369      auto &Decomp = D.getDecompositionDeclarator();
7370      if (!Decomp.bindings().empty()) {
7371        II = Decomp.bindings()[0].Name;
7372        Name = II;
7373      }
7374    } else if (!II) {
7375      Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7376      return nullptr;
7377    }
7378  
7379  
7380    DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7381    StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
7382  
7383    if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7384        SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7385      IsPlaceholderVariable = true;
7386      if (!Previous.empty()) {
7387        NamedDecl *PrevDecl = *Previous.begin();
7388        bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7389            DC->getRedeclContext());
7390        if (SameDC && isDeclInScope(PrevDecl, CurContext, S, false))
7391          DiagPlaceholderVariableDefinition(D.getIdentifierLoc());
7392      }
7393    }
7394  
7395    // dllimport globals without explicit storage class are treated as extern. We
7396    // have to change the storage class this early to get the right DeclContext.
7397    if (SC == SC_None && !DC->isRecord() &&
7398        hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7399        !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7400      SC = SC_Extern;
7401  
7402    DeclContext *OriginalDC = DC;
7403    bool IsLocalExternDecl = SC == SC_Extern &&
7404                             adjustContextForLocalExternDecl(DC);
7405  
7406    if (SCSpec == DeclSpec::SCS_mutable) {
7407      // mutable can only appear on non-static class members, so it's always
7408      // an error here
7409      Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7410      D.setInvalidType();
7411      SC = SC_None;
7412    }
7413  
7414    if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7415        !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7416                                D.getDeclSpec().getStorageClassSpecLoc())) {
7417      // In C++11, the 'register' storage class specifier is deprecated.
7418      // Suppress the warning in system macros, it's used in macros in some
7419      // popular C system headers, such as in glibc's htonl() macro.
7420      Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7421           getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7422                                     : diag::warn_deprecated_register)
7423        << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7424    }
7425  
7426    DiagnoseFunctionSpecifiers(D.getDeclSpec());
7427  
7428    if (!DC->isRecord() && S->getFnParent() == nullptr) {
7429      // C99 6.9p2: The storage-class specifiers auto and register shall not
7430      // appear in the declaration specifiers in an external declaration.
7431      // Global Register+Asm is a GNU extension we support.
7432      if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7433        Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7434        D.setInvalidType();
7435      }
7436    }
7437  
7438    // If this variable has a VLA type and an initializer, try to
7439    // fold to a constant-sized type. This is otherwise invalid.
7440    if (D.hasInitializer() && R->isVariableArrayType())
7441      tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7442                                      /*DiagID=*/0);
7443  
7444    if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
7445      const AutoType *AT = TL.getTypePtr();
7446      CheckConstrainedAuto(AT, TL.getConceptNameLoc());
7447    }
7448  
7449    bool IsMemberSpecialization = false;
7450    bool IsVariableTemplateSpecialization = false;
7451    bool IsPartialSpecialization = false;
7452    bool IsVariableTemplate = false;
7453    VarDecl *NewVD = nullptr;
7454    VarTemplateDecl *NewTemplate = nullptr;
7455    TemplateParameterList *TemplateParams = nullptr;
7456    if (!getLangOpts().CPlusPlus) {
7457      NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7458                              II, R, TInfo, SC);
7459  
7460      if (R->getContainedDeducedType())
7461        ParsingInitForAutoVars.insert(NewVD);
7462  
7463      if (D.isInvalidType())
7464        NewVD->setInvalidDecl();
7465  
7466      if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7467          NewVD->hasLocalStorage())
7468        checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7469                              NTCUC_AutoVar, NTCUK_Destruct);
7470    } else {
7471      bool Invalid = false;
7472      // Match up the template parameter lists with the scope specifier, then
7473      // determine whether we have a template or a template specialization.
7474      TemplateParams = MatchTemplateParametersToScopeSpecifier(
7475          D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7476          D.getCXXScopeSpec(),
7477          D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7478              ? D.getName().TemplateId
7479              : nullptr,
7480          TemplateParamLists,
7481          /*never a friend*/ false, IsMemberSpecialization, Invalid);
7482  
7483      if (TemplateParams) {
7484        if (!TemplateParams->size() &&
7485            D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7486          // There is an extraneous 'template<>' for this variable. Complain
7487          // about it, but allow the declaration of the variable.
7488          Diag(TemplateParams->getTemplateLoc(),
7489               diag::err_template_variable_noparams)
7490            << II
7491            << SourceRange(TemplateParams->getTemplateLoc(),
7492                           TemplateParams->getRAngleLoc());
7493          TemplateParams = nullptr;
7494        } else {
7495          // Check that we can declare a template here.
7496          if (CheckTemplateDeclScope(S, TemplateParams))
7497            return nullptr;
7498  
7499          if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7500            // This is an explicit specialization or a partial specialization.
7501            IsVariableTemplateSpecialization = true;
7502            IsPartialSpecialization = TemplateParams->size() > 0;
7503          } else { // if (TemplateParams->size() > 0)
7504            // This is a template declaration.
7505            IsVariableTemplate = true;
7506  
7507            // Only C++1y supports variable templates (N3651).
7508            Diag(D.getIdentifierLoc(),
7509                 getLangOpts().CPlusPlus14
7510                     ? diag::warn_cxx11_compat_variable_template
7511                     : diag::ext_variable_template);
7512          }
7513        }
7514      } else {
7515        // Check that we can declare a member specialization here.
7516        if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7517            CheckTemplateDeclScope(S, TemplateParamLists.back()))
7518          return nullptr;
7519        assert((Invalid ||
7520                D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7521               "should have a 'template<>' for this decl");
7522      }
7523  
7524      bool IsExplicitSpecialization =
7525          IsVariableTemplateSpecialization && !IsPartialSpecialization;
7526  
7527      // C++ [temp.expl.spec]p2:
7528      //   The declaration in an explicit-specialization shall not be an
7529      //   export-declaration. An explicit specialization shall not use a
7530      //   storage-class-specifier other than thread_local.
7531      //
7532      // We use the storage-class-specifier from DeclSpec because we may have
7533      // added implicit 'extern' for declarations with __declspec(dllimport)!
7534      if (SCSpec != DeclSpec::SCS_unspecified &&
7535          (IsExplicitSpecialization || IsMemberSpecialization)) {
7536        Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7537             diag::ext_explicit_specialization_storage_class)
7538            << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7539      }
7540  
7541      if (CurContext->isRecord()) {
7542        if (SC == SC_Static) {
7543          if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7544            // Walk up the enclosing DeclContexts to check for any that are
7545            // incompatible with static data members.
7546            const DeclContext *FunctionOrMethod = nullptr;
7547            const CXXRecordDecl *AnonStruct = nullptr;
7548            for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7549              if (Ctxt->isFunctionOrMethod()) {
7550                FunctionOrMethod = Ctxt;
7551                break;
7552              }
7553              const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7554              if (ParentDecl && !ParentDecl->getDeclName()) {
7555                AnonStruct = ParentDecl;
7556                break;
7557              }
7558            }
7559            if (FunctionOrMethod) {
7560              // C++ [class.static.data]p5: A local class shall not have static
7561              // data members.
7562              Diag(D.getIdentifierLoc(),
7563                   diag::err_static_data_member_not_allowed_in_local_class)
7564                  << Name << RD->getDeclName()
7565                  << llvm::to_underlying(RD->getTagKind());
7566            } else if (AnonStruct) {
7567              // C++ [class.static.data]p4: Unnamed classes and classes contained
7568              // directly or indirectly within unnamed classes shall not contain
7569              // static data members.
7570              Diag(D.getIdentifierLoc(),
7571                   diag::err_static_data_member_not_allowed_in_anon_struct)
7572                  << Name << llvm::to_underlying(AnonStruct->getTagKind());
7573              Invalid = true;
7574            } else if (RD->isUnion()) {
7575              // C++98 [class.union]p1: If a union contains a static data member,
7576              // the program is ill-formed. C++11 drops this restriction.
7577              Diag(D.getIdentifierLoc(),
7578                   getLangOpts().CPlusPlus11
7579                       ? diag::warn_cxx98_compat_static_data_member_in_union
7580                       : diag::ext_static_data_member_in_union)
7581                  << Name;
7582            }
7583          }
7584        } else if (IsVariableTemplate || IsPartialSpecialization) {
7585          // There is no such thing as a member field template.
7586          Diag(D.getIdentifierLoc(), diag::err_template_member)
7587              << II << TemplateParams->getSourceRange();
7588          // Recover by pretending this is a static data member template.
7589          SC = SC_Static;
7590        }
7591      } else if (DC->isRecord()) {
7592        // This is an out-of-line definition of a static data member.
7593        switch (SC) {
7594        case SC_None:
7595          break;
7596        case SC_Static:
7597          Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7598               diag::err_static_out_of_line)
7599              << FixItHint::CreateRemoval(
7600                     D.getDeclSpec().getStorageClassSpecLoc());
7601          break;
7602        case SC_Auto:
7603        case SC_Register:
7604        case SC_Extern:
7605          // [dcl.stc] p2: The auto or register specifiers shall be applied only
7606          // to names of variables declared in a block or to function parameters.
7607          // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7608          // of class members
7609  
7610          Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7611               diag::err_storage_class_for_static_member)
7612              << FixItHint::CreateRemoval(
7613                     D.getDeclSpec().getStorageClassSpecLoc());
7614          break;
7615        case SC_PrivateExtern:
7616          llvm_unreachable("C storage class in c++!");
7617        }
7618      }
7619  
7620      if (IsVariableTemplateSpecialization) {
7621        SourceLocation TemplateKWLoc =
7622            TemplateParamLists.size() > 0
7623                ? TemplateParamLists[0]->getTemplateLoc()
7624                : SourceLocation();
7625        DeclResult Res = ActOnVarTemplateSpecialization(
7626            S, D, TInfo, Previous, TemplateKWLoc, TemplateParams, SC,
7627            IsPartialSpecialization);
7628        if (Res.isInvalid())
7629          return nullptr;
7630        NewVD = cast<VarDecl>(Res.get());
7631        AddToScope = false;
7632      } else if (D.isDecompositionDeclarator()) {
7633        NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7634                                          D.getIdentifierLoc(), R, TInfo, SC,
7635                                          Bindings);
7636      } else
7637        NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7638                                D.getIdentifierLoc(), II, R, TInfo, SC);
7639  
7640      // If this is supposed to be a variable template, create it as such.
7641      if (IsVariableTemplate) {
7642        NewTemplate =
7643            VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7644                                    TemplateParams, NewVD);
7645        NewVD->setDescribedVarTemplate(NewTemplate);
7646      }
7647  
7648      // If this decl has an auto type in need of deduction, make a note of the
7649      // Decl so we can diagnose uses of it in its own initializer.
7650      if (R->getContainedDeducedType())
7651        ParsingInitForAutoVars.insert(NewVD);
7652  
7653      if (D.isInvalidType() || Invalid) {
7654        NewVD->setInvalidDecl();
7655        if (NewTemplate)
7656          NewTemplate->setInvalidDecl();
7657      }
7658  
7659      SetNestedNameSpecifier(*this, NewVD, D);
7660  
7661      // If we have any template parameter lists that don't directly belong to
7662      // the variable (matching the scope specifier), store them.
7663      // An explicit variable template specialization does not own any template
7664      // parameter lists.
7665      unsigned VDTemplateParamLists =
7666          (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
7667      if (TemplateParamLists.size() > VDTemplateParamLists)
7668        NewVD->setTemplateParameterListsInfo(
7669            Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7670    }
7671  
7672    if (D.getDeclSpec().isInlineSpecified()) {
7673      if (!getLangOpts().CPlusPlus) {
7674        Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7675            << 0;
7676      } else if (CurContext->isFunctionOrMethod()) {
7677        // 'inline' is not allowed on block scope variable declaration.
7678        Diag(D.getDeclSpec().getInlineSpecLoc(),
7679             diag::err_inline_declaration_block_scope) << Name
7680          << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7681      } else {
7682        Diag(D.getDeclSpec().getInlineSpecLoc(),
7683             getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7684                                       : diag::ext_inline_variable);
7685        NewVD->setInlineSpecified();
7686      }
7687    }
7688  
7689    // Set the lexical context. If the declarator has a C++ scope specifier, the
7690    // lexical context will be different from the semantic context.
7691    NewVD->setLexicalDeclContext(CurContext);
7692    if (NewTemplate)
7693      NewTemplate->setLexicalDeclContext(CurContext);
7694  
7695    if (IsLocalExternDecl) {
7696      if (D.isDecompositionDeclarator())
7697        for (auto *B : Bindings)
7698          B->setLocalExternDecl();
7699      else
7700        NewVD->setLocalExternDecl();
7701    }
7702  
7703    bool EmitTLSUnsupportedError = false;
7704    if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7705      // C++11 [dcl.stc]p4:
7706      //   When thread_local is applied to a variable of block scope the
7707      //   storage-class-specifier static is implied if it does not appear
7708      //   explicitly.
7709      // Core issue: 'static' is not implied if the variable is declared
7710      //   'extern'.
7711      if (NewVD->hasLocalStorage() &&
7712          (SCSpec != DeclSpec::SCS_unspecified ||
7713           TSCS != DeclSpec::TSCS_thread_local ||
7714           !DC->isFunctionOrMethod()))
7715        Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7716             diag::err_thread_non_global)
7717          << DeclSpec::getSpecifierName(TSCS);
7718      else if (!Context.getTargetInfo().isTLSSupported()) {
7719        if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
7720            getLangOpts().SYCLIsDevice) {
7721          // Postpone error emission until we've collected attributes required to
7722          // figure out whether it's a host or device variable and whether the
7723          // error should be ignored.
7724          EmitTLSUnsupportedError = true;
7725          // We still need to mark the variable as TLS so it shows up in AST with
7726          // proper storage class for other tools to use even if we're not going
7727          // to emit any code for it.
7728          NewVD->setTSCSpec(TSCS);
7729        } else
7730          Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7731               diag::err_thread_unsupported);
7732      } else
7733        NewVD->setTSCSpec(TSCS);
7734    }
7735  
7736    switch (D.getDeclSpec().getConstexprSpecifier()) {
7737    case ConstexprSpecKind::Unspecified:
7738      break;
7739  
7740    case ConstexprSpecKind::Consteval:
7741      Diag(D.getDeclSpec().getConstexprSpecLoc(),
7742           diag::err_constexpr_wrong_decl_kind)
7743          << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7744      [[fallthrough]];
7745  
7746    case ConstexprSpecKind::Constexpr:
7747      NewVD->setConstexpr(true);
7748      // C++1z [dcl.spec.constexpr]p1:
7749      //   A static data member declared with the constexpr specifier is
7750      //   implicitly an inline variable.
7751      if (NewVD->isStaticDataMember() &&
7752          (getLangOpts().CPlusPlus17 ||
7753           Context.getTargetInfo().getCXXABI().isMicrosoft()))
7754        NewVD->setImplicitlyInline();
7755      break;
7756  
7757    case ConstexprSpecKind::Constinit:
7758      if (!NewVD->hasGlobalStorage())
7759        Diag(D.getDeclSpec().getConstexprSpecLoc(),
7760             diag::err_constinit_local_variable);
7761      else
7762        NewVD->addAttr(
7763            ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(),
7764                                  ConstInitAttr::Keyword_constinit));
7765      break;
7766    }
7767  
7768    // C99 6.7.4p3
7769    //   An inline definition of a function with external linkage shall
7770    //   not contain a definition of a modifiable object with static or
7771    //   thread storage duration...
7772    // We only apply this when the function is required to be defined
7773    // elsewhere, i.e. when the function is not 'extern inline'.  Note
7774    // that a local variable with thread storage duration still has to
7775    // be marked 'static'.  Also note that it's possible to get these
7776    // semantics in C++ using __attribute__((gnu_inline)).
7777    if (SC == SC_Static && S->getFnParent() != nullptr &&
7778        !NewVD->getType().isConstQualified()) {
7779      FunctionDecl *CurFD = getCurFunctionDecl();
7780      if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7781        Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7782             diag::warn_static_local_in_extern_inline);
7783        MaybeSuggestAddingStaticToDecl(CurFD);
7784      }
7785    }
7786  
7787    if (D.getDeclSpec().isModulePrivateSpecified()) {
7788      if (IsVariableTemplateSpecialization)
7789        Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7790            << (IsPartialSpecialization ? 1 : 0)
7791            << FixItHint::CreateRemoval(
7792                   D.getDeclSpec().getModulePrivateSpecLoc());
7793      else if (IsMemberSpecialization)
7794        Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7795          << 2
7796          << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7797      else if (NewVD->hasLocalStorage())
7798        Diag(NewVD->getLocation(), diag::err_module_private_local)
7799            << 0 << NewVD
7800            << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7801            << FixItHint::CreateRemoval(
7802                   D.getDeclSpec().getModulePrivateSpecLoc());
7803      else {
7804        NewVD->setModulePrivate();
7805        if (NewTemplate)
7806          NewTemplate->setModulePrivate();
7807        for (auto *B : Bindings)
7808          B->setModulePrivate();
7809      }
7810    }
7811  
7812    if (getLangOpts().OpenCL) {
7813      deduceOpenCLAddressSpace(NewVD);
7814  
7815      DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7816      if (TSC != TSCS_unspecified) {
7817        Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7818             diag::err_opencl_unknown_type_specifier)
7819            << getLangOpts().getOpenCLVersionString()
7820            << DeclSpec::getSpecifierName(TSC) << 1;
7821        NewVD->setInvalidDecl();
7822      }
7823    }
7824  
7825    // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
7826    // address space if the table has local storage (semantic checks elsewhere
7827    // will produce an error anyway).
7828    if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) {
7829      if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
7830          !NewVD->hasLocalStorage()) {
7831        QualType Type = Context.getAddrSpaceQualType(
7832            NewVD->getType(), Context.getLangASForBuiltinAddressSpace(1));
7833        NewVD->setType(Type);
7834      }
7835    }
7836  
7837    // Handle attributes prior to checking for duplicates in MergeVarDecl
7838    ProcessDeclAttributes(S, NewVD, D);
7839  
7840    // FIXME: This is probably the wrong location to be doing this and we should
7841    // probably be doing this for more attributes (especially for function
7842    // pointer attributes such as format, warn_unused_result, etc.). Ideally
7843    // the code to copy attributes would be generated by TableGen.
7844    if (R->isFunctionPointerType())
7845      if (const auto *TT = R->getAs<TypedefType>())
7846        copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7847  
7848    if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
7849        getLangOpts().SYCLIsDevice) {
7850      if (EmitTLSUnsupportedError &&
7851          ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7852           (getLangOpts().OpenMPIsTargetDevice &&
7853            OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7854        Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7855             diag::err_thread_unsupported);
7856  
7857      if (EmitTLSUnsupportedError &&
7858          (LangOpts.SYCLIsDevice ||
7859           (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
7860        targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7861      // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7862      // storage [duration]."
7863      if (SC == SC_None && S->getFnParent() != nullptr &&
7864          (NewVD->hasAttr<CUDASharedAttr>() ||
7865           NewVD->hasAttr<CUDAConstantAttr>())) {
7866        NewVD->setStorageClass(SC_Static);
7867      }
7868    }
7869  
7870    // Ensure that dllimport globals without explicit storage class are treated as
7871    // extern. The storage class is set above using parsed attributes. Now we can
7872    // check the VarDecl itself.
7873    assert(!NewVD->hasAttr<DLLImportAttr>() ||
7874           NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7875           NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7876  
7877    // In auto-retain/release, infer strong retension for variables of
7878    // retainable type.
7879    if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewVD))
7880      NewVD->setInvalidDecl();
7881  
7882    // Handle GNU asm-label extension (encoded as an attribute).
7883    if (Expr *E = (Expr*)D.getAsmLabel()) {
7884      // The parser guarantees this is a string.
7885      StringLiteral *SE = cast<StringLiteral>(E);
7886      StringRef Label = SE->getString();
7887      if (S->getFnParent() != nullptr) {
7888        switch (SC) {
7889        case SC_None:
7890        case SC_Auto:
7891          Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7892          break;
7893        case SC_Register:
7894          // Local Named register
7895          if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7896              DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7897            Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7898          break;
7899        case SC_Static:
7900        case SC_Extern:
7901        case SC_PrivateExtern:
7902          break;
7903        }
7904      } else if (SC == SC_Register) {
7905        // Global Named register
7906        if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7907          const auto &TI = Context.getTargetInfo();
7908          bool HasSizeMismatch;
7909  
7910          if (!TI.isValidGCCRegisterName(Label))
7911            Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7912          else if (!TI.validateGlobalRegisterVariable(Label,
7913                                                      Context.getTypeSize(R),
7914                                                      HasSizeMismatch))
7915            Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7916          else if (HasSizeMismatch)
7917            Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7918        }
7919  
7920        if (!R->isIntegralType(Context) && !R->isPointerType()) {
7921          Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7922          NewVD->setInvalidDecl(true);
7923        }
7924      }
7925  
7926      NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7927                                          /*IsLiteralLabel=*/true,
7928                                          SE->getStrTokenLoc(0)));
7929    } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7930      llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7931        ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7932      if (I != ExtnameUndeclaredIdentifiers.end()) {
7933        if (isDeclExternC(NewVD)) {
7934          NewVD->addAttr(I->second);
7935          ExtnameUndeclaredIdentifiers.erase(I);
7936        } else
7937          Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7938              << /*Variable*/1 << NewVD;
7939      }
7940    }
7941  
7942    // Find the shadowed declaration before filtering for scope.
7943    NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7944                                  ? getShadowedDeclaration(NewVD, Previous)
7945                                  : nullptr;
7946  
7947    // Don't consider existing declarations that are in a different
7948    // scope and are out-of-semantic-context declarations (if the new
7949    // declaration has linkage).
7950    FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7951                         D.getCXXScopeSpec().isNotEmpty() ||
7952                         IsMemberSpecialization ||
7953                         IsVariableTemplateSpecialization);
7954  
7955    // Check whether the previous declaration is in the same block scope. This
7956    // affects whether we merge types with it, per C++11 [dcl.array]p3.
7957    if (getLangOpts().CPlusPlus &&
7958        NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7959      NewVD->setPreviousDeclInSameBlockScope(
7960          Previous.isSingleResult() && !Previous.isShadowed() &&
7961          isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7962  
7963    if (!getLangOpts().CPlusPlus) {
7964      D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7965    } else {
7966      // If this is an explicit specialization of a static data member, check it.
7967      if (IsMemberSpecialization && !IsVariableTemplateSpecialization &&
7968          !NewVD->isInvalidDecl() && CheckMemberSpecialization(NewVD, Previous))
7969        NewVD->setInvalidDecl();
7970  
7971      // Merge the decl with the existing one if appropriate.
7972      if (!Previous.empty()) {
7973        if (Previous.isSingleResult() &&
7974            isa<FieldDecl>(Previous.getFoundDecl()) &&
7975            D.getCXXScopeSpec().isSet()) {
7976          // The user tried to define a non-static data member
7977          // out-of-line (C++ [dcl.meaning]p1).
7978          Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7979            << D.getCXXScopeSpec().getRange();
7980          Previous.clear();
7981          NewVD->setInvalidDecl();
7982        }
7983      } else if (D.getCXXScopeSpec().isSet() &&
7984                 !IsVariableTemplateSpecialization) {
7985        // No previous declaration in the qualifying scope.
7986        Diag(D.getIdentifierLoc(), diag::err_no_member)
7987          << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7988          << D.getCXXScopeSpec().getRange();
7989        NewVD->setInvalidDecl();
7990      }
7991  
7992      if (!IsPlaceholderVariable)
7993        D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7994  
7995      // CheckVariableDeclaration will set NewVD as invalid if something is in
7996      // error like WebAssembly tables being declared as arrays with a non-zero
7997      // size, but then parsing continues and emits further errors on that line.
7998      // To avoid that we check here if it happened and return nullptr.
7999      if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8000        return nullptr;
8001  
8002      if (NewTemplate) {
8003        VarTemplateDecl *PrevVarTemplate =
8004            NewVD->getPreviousDecl()
8005                ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
8006                : nullptr;
8007  
8008        // Check the template parameter list of this declaration, possibly
8009        // merging in the template parameter list from the previous variable
8010        // template declaration.
8011        if (CheckTemplateParameterList(
8012                TemplateParams,
8013                PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8014                                : nullptr,
8015                (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8016                 DC->isDependentContext())
8017                    ? TPC_ClassTemplateMember
8018                    : TPC_VarTemplate))
8019          NewVD->setInvalidDecl();
8020  
8021        // If we are providing an explicit specialization of a static variable
8022        // template, make a note of that.
8023        if (PrevVarTemplate &&
8024            PrevVarTemplate->getInstantiatedFromMemberTemplate())
8025          PrevVarTemplate->setMemberSpecialization();
8026      }
8027    }
8028  
8029    // Diagnose shadowed variables iff this isn't a redeclaration.
8030    if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8031      CheckShadow(NewVD, ShadowedDecl, Previous);
8032  
8033    ProcessPragmaWeak(S, NewVD);
8034  
8035    // If this is the first declaration of an extern C variable, update
8036    // the map of such variables.
8037    if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8038        isIncompleteDeclExternC(*this, NewVD))
8039      RegisterLocallyScopedExternCDecl(NewVD, S);
8040  
8041    if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8042      MangleNumberingContext *MCtx;
8043      Decl *ManglingContextDecl;
8044      std::tie(MCtx, ManglingContextDecl) =
8045          getCurrentMangleNumberContext(NewVD->getDeclContext());
8046      if (MCtx) {
8047        Context.setManglingNumber(
8048            NewVD, MCtx->getManglingNumber(
8049                       NewVD, getMSManglingNumber(getLangOpts(), S)));
8050        Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
8051      }
8052    }
8053  
8054    // Special handling of variable named 'main'.
8055    if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
8056        NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
8057        !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
8058  
8059      // C++ [basic.start.main]p3
8060      // A program that declares a variable main at global scope is ill-formed.
8061      if (getLangOpts().CPlusPlus)
8062        Diag(D.getBeginLoc(), diag::err_main_global_variable);
8063  
8064      // In C, and external-linkage variable named main results in undefined
8065      // behavior.
8066      else if (NewVD->hasExternalFormalLinkage())
8067        Diag(D.getBeginLoc(), diag::warn_main_redefined);
8068    }
8069  
8070    if (D.isRedeclaration() && !Previous.empty()) {
8071      NamedDecl *Prev = Previous.getRepresentativeDecl();
8072      checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
8073                                     D.isFunctionDefinition());
8074    }
8075  
8076    if (NewTemplate) {
8077      if (NewVD->isInvalidDecl())
8078        NewTemplate->setInvalidDecl();
8079      ActOnDocumentableDecl(NewTemplate);
8080      return NewTemplate;
8081    }
8082  
8083    if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8084      CompleteMemberSpecialization(NewVD, Previous);
8085  
8086    emitReadOnlyPlacementAttrWarning(*this, NewVD);
8087  
8088    return NewVD;
8089  }
8090  
8091  /// Enum describing the %select options in diag::warn_decl_shadow.
8092  enum ShadowedDeclKind {
8093    SDK_Local,
8094    SDK_Global,
8095    SDK_StaticMember,
8096    SDK_Field,
8097    SDK_Typedef,
8098    SDK_Using,
8099    SDK_StructuredBinding
8100  };
8101  
8102  /// Determine what kind of declaration we're shadowing.
computeShadowedDeclKind(const NamedDecl * ShadowedDecl,const DeclContext * OldDC)8103  static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
8104                                                  const DeclContext *OldDC) {
8105    if (isa<TypeAliasDecl>(ShadowedDecl))
8106      return SDK_Using;
8107    else if (isa<TypedefDecl>(ShadowedDecl))
8108      return SDK_Typedef;
8109    else if (isa<BindingDecl>(ShadowedDecl))
8110      return SDK_StructuredBinding;
8111    else if (isa<RecordDecl>(OldDC))
8112      return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8113  
8114    return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8115  }
8116  
8117  /// Return the location of the capture if the given lambda captures the given
8118  /// variable \p VD, or an invalid source location otherwise.
getCaptureLocation(const LambdaScopeInfo * LSI,const VarDecl * VD)8119  static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
8120                                           const VarDecl *VD) {
8121    for (const Capture &Capture : LSI->Captures) {
8122      if (Capture.isVariableCapture() && Capture.getVariable() == VD)
8123        return Capture.getLocation();
8124    }
8125    return SourceLocation();
8126  }
8127  
shouldWarnIfShadowedDecl(const DiagnosticsEngine & Diags,const LookupResult & R)8128  static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
8129                                       const LookupResult &R) {
8130    // Only diagnose if we're shadowing an unambiguous field or variable.
8131    if (R.getResultKind() != LookupResult::Found)
8132      return false;
8133  
8134    // Return false if warning is ignored.
8135    return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
8136  }
8137  
getShadowedDeclaration(const VarDecl * D,const LookupResult & R)8138  NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
8139                                          const LookupResult &R) {
8140    if (!shouldWarnIfShadowedDecl(Diags, R))
8141      return nullptr;
8142  
8143    // Don't diagnose declarations at file scope.
8144    if (D->hasGlobalStorage() && !D->isStaticLocal())
8145      return nullptr;
8146  
8147    NamedDecl *ShadowedDecl = R.getFoundDecl();
8148    return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8149                                                              : nullptr;
8150  }
8151  
getShadowedDeclaration(const TypedefNameDecl * D,const LookupResult & R)8152  NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
8153                                          const LookupResult &R) {
8154    // Don't warn if typedef declaration is part of a class
8155    if (D->getDeclContext()->isRecord())
8156      return nullptr;
8157  
8158    if (!shouldWarnIfShadowedDecl(Diags, R))
8159      return nullptr;
8160  
8161    NamedDecl *ShadowedDecl = R.getFoundDecl();
8162    return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
8163  }
8164  
getShadowedDeclaration(const BindingDecl * D,const LookupResult & R)8165  NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
8166                                          const LookupResult &R) {
8167    if (!shouldWarnIfShadowedDecl(Diags, R))
8168      return nullptr;
8169  
8170    NamedDecl *ShadowedDecl = R.getFoundDecl();
8171    return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8172                                                              : nullptr;
8173  }
8174  
CheckShadow(NamedDecl * D,NamedDecl * ShadowedDecl,const LookupResult & R)8175  void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
8176                         const LookupResult &R) {
8177    DeclContext *NewDC = D->getDeclContext();
8178  
8179    if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
8180      // Fields are not shadowed by variables in C++ static methods.
8181      if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
8182        if (MD->isStatic())
8183          return;
8184  
8185      // Fields shadowed by constructor parameters are a special case. Usually
8186      // the constructor initializes the field with the parameter.
8187      if (isa<CXXConstructorDecl>(NewDC))
8188        if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
8189          // Remember that this was shadowed so we can either warn about its
8190          // modification or its existence depending on warning settings.
8191          ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8192          return;
8193        }
8194    }
8195  
8196    if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
8197      if (shadowedVar->isExternC()) {
8198        // For shadowing external vars, make sure that we point to the global
8199        // declaration, not a locally scoped extern declaration.
8200        for (auto *I : shadowedVar->redecls())
8201          if (I->isFileVarDecl()) {
8202            ShadowedDecl = I;
8203            break;
8204          }
8205      }
8206  
8207    DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8208  
8209    unsigned WarningDiag = diag::warn_decl_shadow;
8210    SourceLocation CaptureLoc;
8211    if (isa<VarDecl>(D) && NewDC && isa<CXXMethodDecl>(NewDC)) {
8212      if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8213        if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
8214          if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl)) {
8215            const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
8216            if (RD->getLambdaCaptureDefault() == LCD_None) {
8217              // Try to avoid warnings for lambdas with an explicit capture
8218              // list. Warn only when the lambda captures the shadowed decl
8219              // explicitly.
8220              CaptureLoc = getCaptureLocation(LSI, VD);
8221              if (CaptureLoc.isInvalid())
8222                WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8223            } else {
8224              // Remember that this was shadowed so we can avoid the warning if
8225              // the shadowed decl isn't captured and the warning settings allow
8226              // it.
8227              cast<LambdaScopeInfo>(getCurFunction())
8228                  ->ShadowingDecls.push_back({D, VD});
8229              return;
8230            }
8231          }
8232          if (isa<FieldDecl>(ShadowedDecl)) {
8233            // If lambda can capture this, then emit default shadowing warning,
8234            // Otherwise it is not really a shadowing case since field is not
8235            // available in lambda's body.
8236            // At this point we don't know that lambda can capture this, so
8237            // remember that this was shadowed and delay until we know.
8238            cast<LambdaScopeInfo>(getCurFunction())
8239                ->ShadowingDecls.push_back({D, ShadowedDecl});
8240            return;
8241          }
8242        }
8243        if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl);
8244            VD && VD->hasLocalStorage()) {
8245          // A variable can't shadow a local variable in an enclosing scope, if
8246          // they are separated by a non-capturing declaration context.
8247          for (DeclContext *ParentDC = NewDC;
8248               ParentDC && !ParentDC->Equals(OldDC);
8249               ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8250            // Only block literals, captured statements, and lambda expressions
8251            // can capture; other scopes don't.
8252            if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8253                !isLambdaCallOperator(ParentDC)) {
8254              return;
8255            }
8256          }
8257        }
8258      }
8259    }
8260  
8261    // Never warn about shadowing a placeholder variable.
8262    if (ShadowedDecl->isPlaceholderVar(getLangOpts()))
8263      return;
8264  
8265    // Only warn about certain kinds of shadowing for class members.
8266    if (NewDC && NewDC->isRecord()) {
8267      // In particular, don't warn about shadowing non-class members.
8268      if (!OldDC->isRecord())
8269        return;
8270  
8271      // TODO: should we warn about static data members shadowing
8272      // static data members from base classes?
8273  
8274      // TODO: don't diagnose for inaccessible shadowed members.
8275      // This is hard to do perfectly because we might friend the
8276      // shadowing context, but that's just a false negative.
8277    }
8278  
8279  
8280    DeclarationName Name = R.getLookupName();
8281  
8282    // Emit warning and note.
8283    ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8284    Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8285    if (!CaptureLoc.isInvalid())
8286      Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8287          << Name << /*explicitly*/ 1;
8288    Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8289  }
8290  
DiagnoseShadowingLambdaDecls(const LambdaScopeInfo * LSI)8291  void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
8292    for (const auto &Shadow : LSI->ShadowingDecls) {
8293      const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;
8294      // Try to avoid the warning when the shadowed decl isn't captured.
8295      const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8296      if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl)) {
8297        SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);
8298        Diag(Shadow.VD->getLocation(),
8299             CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local
8300                                    : diag::warn_decl_shadow)
8301            << Shadow.VD->getDeclName()
8302            << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8303        if (CaptureLoc.isValid())
8304          Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8305              << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8306        Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8307      } else if (isa<FieldDecl>(ShadowedDecl)) {
8308        Diag(Shadow.VD->getLocation(),
8309             LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8310                                      : diag::warn_decl_shadow_uncaptured_local)
8311            << Shadow.VD->getDeclName()
8312            << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8313        Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8314      }
8315    }
8316  }
8317  
CheckShadow(Scope * S,VarDecl * D)8318  void Sema::CheckShadow(Scope *S, VarDecl *D) {
8319    if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8320      return;
8321  
8322    LookupResult R(*this, D->getDeclName(), D->getLocation(),
8323                   Sema::LookupOrdinaryName,
8324                   RedeclarationKind::ForVisibleRedeclaration);
8325    LookupName(R, S);
8326    if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8327      CheckShadow(D, ShadowedDecl, R);
8328  }
8329  
8330  /// Check if 'E', which is an expression that is about to be modified, refers
8331  /// to a constructor parameter that shadows a field.
CheckShadowingDeclModification(Expr * E,SourceLocation Loc)8332  void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
8333    // Quickly ignore expressions that can't be shadowing ctor parameters.
8334    if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8335      return;
8336    E = E->IgnoreParenImpCasts();
8337    auto *DRE = dyn_cast<DeclRefExpr>(E);
8338    if (!DRE)
8339      return;
8340    const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8341    auto I = ShadowingDecls.find(D);
8342    if (I == ShadowingDecls.end())
8343      return;
8344    const NamedDecl *ShadowedDecl = I->second;
8345    const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8346    Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8347    Diag(D->getLocation(), diag::note_var_declared_here) << D;
8348    Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8349  
8350    // Avoid issuing multiple warnings about the same decl.
8351    ShadowingDecls.erase(I);
8352  }
8353  
8354  /// Check for conflict between this global or extern "C" declaration and
8355  /// previous global or extern "C" declarations. This is only used in C++.
8356  template<typename T>
checkGlobalOrExternCConflict(Sema & S,const T * ND,bool IsGlobal,LookupResult & Previous)8357  static bool checkGlobalOrExternCConflict(
8358      Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8359    assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8360    NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8361  
8362    if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8363      // The common case: this global doesn't conflict with any extern "C"
8364      // declaration.
8365      return false;
8366    }
8367  
8368    if (Prev) {
8369      if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8370        // Both the old and new declarations have C language linkage. This is a
8371        // redeclaration.
8372        Previous.clear();
8373        Previous.addDecl(Prev);
8374        return true;
8375      }
8376  
8377      // This is a global, non-extern "C" declaration, and there is a previous
8378      // non-global extern "C" declaration. Diagnose if this is a variable
8379      // declaration.
8380      if (!isa<VarDecl>(ND))
8381        return false;
8382    } else {
8383      // The declaration is extern "C". Check for any declaration in the
8384      // translation unit which might conflict.
8385      if (IsGlobal) {
8386        // We have already performed the lookup into the translation unit.
8387        IsGlobal = false;
8388        for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8389             I != E; ++I) {
8390          if (isa<VarDecl>(*I)) {
8391            Prev = *I;
8392            break;
8393          }
8394        }
8395      } else {
8396        DeclContext::lookup_result R =
8397            S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8398        for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8399             I != E; ++I) {
8400          if (isa<VarDecl>(*I)) {
8401            Prev = *I;
8402            break;
8403          }
8404          // FIXME: If we have any other entity with this name in global scope,
8405          // the declaration is ill-formed, but that is a defect: it breaks the
8406          // 'stat' hack, for instance. Only variables can have mangled name
8407          // clashes with extern "C" declarations, so only they deserve a
8408          // diagnostic.
8409        }
8410      }
8411  
8412      if (!Prev)
8413        return false;
8414    }
8415  
8416    // Use the first declaration's location to ensure we point at something which
8417    // is lexically inside an extern "C" linkage-spec.
8418    assert(Prev && "should have found a previous declaration to diagnose");
8419    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8420      Prev = FD->getFirstDecl();
8421    else
8422      Prev = cast<VarDecl>(Prev)->getFirstDecl();
8423  
8424    S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8425      << IsGlobal << ND;
8426    S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8427      << IsGlobal;
8428    return false;
8429  }
8430  
8431  /// Apply special rules for handling extern "C" declarations. Returns \c true
8432  /// if we have found that this is a redeclaration of some prior entity.
8433  ///
8434  /// Per C++ [dcl.link]p6:
8435  ///   Two declarations [for a function or variable] with C language linkage
8436  ///   with the same name that appear in different scopes refer to the same
8437  ///   [entity]. An entity with C language linkage shall not be declared with
8438  ///   the same name as an entity in global scope.
8439  template<typename T>
checkForConflictWithNonVisibleExternC(Sema & S,const T * ND,LookupResult & Previous)8440  static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8441                                                    LookupResult &Previous) {
8442    if (!S.getLangOpts().CPlusPlus) {
8443      // In C, when declaring a global variable, look for a corresponding 'extern'
8444      // variable declared in function scope. We don't need this in C++, because
8445      // we find local extern decls in the surrounding file-scope DeclContext.
8446      if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8447        if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8448          Previous.clear();
8449          Previous.addDecl(Prev);
8450          return true;
8451        }
8452      }
8453      return false;
8454    }
8455  
8456    // A declaration in the translation unit can conflict with an extern "C"
8457    // declaration.
8458    if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8459      return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8460  
8461    // An extern "C" declaration can conflict with a declaration in the
8462    // translation unit or can be a redeclaration of an extern "C" declaration
8463    // in another scope.
8464    if (isIncompleteDeclExternC(S,ND))
8465      return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8466  
8467    // Neither global nor extern "C": nothing to do.
8468    return false;
8469  }
8470  
CheckC23ConstexprVarType(Sema & SemaRef,SourceLocation VarLoc,QualType T)8471  static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,
8472                                       QualType T) {
8473    QualType CanonT = SemaRef.Context.getCanonicalType(T);
8474    // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
8475    // any of its members, even recursively, shall not have an atomic type, or a
8476    // variably modified type, or a type that is volatile or restrict qualified.
8477    if (CanonT->isVariablyModifiedType()) {
8478      SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8479      return true;
8480    }
8481  
8482    // Arrays are qualified by their element type, so get the base type (this
8483    // works on non-arrays as well).
8484    CanonT = SemaRef.Context.getBaseElementType(CanonT);
8485  
8486    if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
8487        CanonT.isRestrictQualified()) {
8488      SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8489      return true;
8490    }
8491  
8492    if (CanonT->isRecordType()) {
8493      const RecordDecl *RD = CanonT->getAsRecordDecl();
8494      if (llvm::any_of(RD->fields(), [&SemaRef, VarLoc](const FieldDecl *F) {
8495            return CheckC23ConstexprVarType(SemaRef, VarLoc, F->getType());
8496          }))
8497        return true;
8498    }
8499  
8500    return false;
8501  }
8502  
CheckVariableDeclarationType(VarDecl * NewVD)8503  void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
8504    // If the decl is already known invalid, don't check it.
8505    if (NewVD->isInvalidDecl())
8506      return;
8507  
8508    QualType T = NewVD->getType();
8509  
8510    // Defer checking an 'auto' type until its initializer is attached.
8511    if (T->isUndeducedType())
8512      return;
8513  
8514    if (NewVD->hasAttrs())
8515      CheckAlignasUnderalignment(NewVD);
8516  
8517    if (T->isObjCObjectType()) {
8518      Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8519        << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8520      T = Context.getObjCObjectPointerType(T);
8521      NewVD->setType(T);
8522    }
8523  
8524    // Emit an error if an address space was applied to decl with local storage.
8525    // This includes arrays of objects with address space qualifiers, but not
8526    // automatic variables that point to other address spaces.
8527    // ISO/IEC TR 18037 S5.1.2
8528    if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8529        T.getAddressSpace() != LangAS::Default) {
8530      Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8531      NewVD->setInvalidDecl();
8532      return;
8533    }
8534  
8535    // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8536    // scope.
8537    if (getLangOpts().OpenCLVersion == 120 &&
8538        !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8539                                              getLangOpts()) &&
8540        NewVD->isStaticLocal()) {
8541      Diag(NewVD->getLocation(), diag::err_static_function_scope);
8542      NewVD->setInvalidDecl();
8543      return;
8544    }
8545  
8546    if (getLangOpts().OpenCL) {
8547      if (!diagnoseOpenCLTypes(*this, NewVD))
8548        return;
8549  
8550      // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8551      if (NewVD->hasAttr<BlocksAttr>()) {
8552        Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8553        return;
8554      }
8555  
8556      if (T->isBlockPointerType()) {
8557        // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8558        // can't use 'extern' storage class.
8559        if (!T.isConstQualified()) {
8560          Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8561              << 0 /*const*/;
8562          NewVD->setInvalidDecl();
8563          return;
8564        }
8565        if (NewVD->hasExternalStorage()) {
8566          Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8567          NewVD->setInvalidDecl();
8568          return;
8569        }
8570      }
8571  
8572      // FIXME: Adding local AS in C++ for OpenCL might make sense.
8573      if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8574          NewVD->hasExternalStorage()) {
8575        if (!T->isSamplerT() && !T->isDependentType() &&
8576            !(T.getAddressSpace() == LangAS::opencl_constant ||
8577              (T.getAddressSpace() == LangAS::opencl_global &&
8578               getOpenCLOptions().areProgramScopeVariablesSupported(
8579                   getLangOpts())))) {
8580          int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8581          if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8582            Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8583                << Scope << "global or constant";
8584          else
8585            Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8586                << Scope << "constant";
8587          NewVD->setInvalidDecl();
8588          return;
8589        }
8590      } else {
8591        if (T.getAddressSpace() == LangAS::opencl_global) {
8592          Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8593              << 1 /*is any function*/ << "global";
8594          NewVD->setInvalidDecl();
8595          return;
8596        }
8597        if (T.getAddressSpace() == LangAS::opencl_constant ||
8598            T.getAddressSpace() == LangAS::opencl_local) {
8599          FunctionDecl *FD = getCurFunctionDecl();
8600          // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8601          // in functions.
8602          if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8603            if (T.getAddressSpace() == LangAS::opencl_constant)
8604              Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8605                  << 0 /*non-kernel only*/ << "constant";
8606            else
8607              Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8608                  << 0 /*non-kernel only*/ << "local";
8609            NewVD->setInvalidDecl();
8610            return;
8611          }
8612          // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8613          // in the outermost scope of a kernel function.
8614          if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8615            if (!getCurScope()->isFunctionScope()) {
8616              if (T.getAddressSpace() == LangAS::opencl_constant)
8617                Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8618                    << "constant";
8619              else
8620                Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8621                    << "local";
8622              NewVD->setInvalidDecl();
8623              return;
8624            }
8625          }
8626        } else if (T.getAddressSpace() != LangAS::opencl_private &&
8627                   // If we are parsing a template we didn't deduce an addr
8628                   // space yet.
8629                   T.getAddressSpace() != LangAS::Default) {
8630          // Do not allow other address spaces on automatic variable.
8631          Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8632          NewVD->setInvalidDecl();
8633          return;
8634        }
8635      }
8636    }
8637  
8638    if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8639        && !NewVD->hasAttr<BlocksAttr>()) {
8640      if (getLangOpts().getGC() != LangOptions::NonGC)
8641        Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8642      else {
8643        assert(!getLangOpts().ObjCAutoRefCount);
8644        Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8645      }
8646    }
8647  
8648    // WebAssembly tables must be static with a zero length and can't be
8649    // declared within functions.
8650    if (T->isWebAssemblyTableType()) {
8651      if (getCurScope()->getParent()) { // Parent is null at top-level
8652        Diag(NewVD->getLocation(), diag::err_wasm_table_in_function);
8653        NewVD->setInvalidDecl();
8654        return;
8655      }
8656      if (NewVD->getStorageClass() != SC_Static) {
8657        Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static);
8658        NewVD->setInvalidDecl();
8659        return;
8660      }
8661      const auto *ATy = dyn_cast<ConstantArrayType>(T.getTypePtr());
8662      if (!ATy || ATy->getZExtSize() != 0) {
8663        Diag(NewVD->getLocation(),
8664             diag::err_typecheck_wasm_table_must_have_zero_length);
8665        NewVD->setInvalidDecl();
8666        return;
8667      }
8668    }
8669  
8670    bool isVM = T->isVariablyModifiedType();
8671    if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8672        NewVD->hasAttr<BlocksAttr>())
8673      setFunctionHasBranchProtectedScope();
8674  
8675    if ((isVM && NewVD->hasLinkage()) ||
8676        (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8677      bool SizeIsNegative;
8678      llvm::APSInt Oversized;
8679      TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8680          NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8681      QualType FixedT;
8682      if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
8683        FixedT = FixedTInfo->getType();
8684      else if (FixedTInfo) {
8685        // Type and type-as-written are canonically different. We need to fix up
8686        // both types separately.
8687        FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8688                                                     Oversized);
8689      }
8690      if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8691        const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8692        // FIXME: This won't give the correct result for
8693        // int a[10][n];
8694        SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8695  
8696        if (NewVD->isFileVarDecl())
8697          Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8698          << SizeRange;
8699        else if (NewVD->isStaticLocal())
8700          Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8701          << SizeRange;
8702        else
8703          Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8704          << SizeRange;
8705        NewVD->setInvalidDecl();
8706        return;
8707      }
8708  
8709      if (!FixedTInfo) {
8710        if (NewVD->isFileVarDecl())
8711          Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8712        else
8713          Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8714        NewVD->setInvalidDecl();
8715        return;
8716      }
8717  
8718      Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8719      NewVD->setType(FixedT);
8720      NewVD->setTypeSourceInfo(FixedTInfo);
8721    }
8722  
8723    if (T->isVoidType()) {
8724      // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8725      //                    of objects and functions.
8726      if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8727        Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8728          << T;
8729        NewVD->setInvalidDecl();
8730        return;
8731      }
8732    }
8733  
8734    if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8735      Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8736      NewVD->setInvalidDecl();
8737      return;
8738    }
8739  
8740    if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
8741        !T.isWebAssemblyReferenceType()) {
8742      Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8743      NewVD->setInvalidDecl();
8744      return;
8745    }
8746  
8747    if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8748      Diag(NewVD->getLocation(), diag::err_block_on_vm);
8749      NewVD->setInvalidDecl();
8750      return;
8751    }
8752  
8753    if (getLangOpts().C23 && NewVD->isConstexpr() &&
8754        CheckC23ConstexprVarType(*this, NewVD->getLocation(), T)) {
8755      NewVD->setInvalidDecl();
8756      return;
8757    }
8758  
8759    if (NewVD->isConstexpr() && !T->isDependentType() &&
8760        RequireLiteralType(NewVD->getLocation(), T,
8761                           diag::err_constexpr_var_non_literal)) {
8762      NewVD->setInvalidDecl();
8763      return;
8764    }
8765  
8766    // PPC MMA non-pointer types are not allowed as non-local variable types.
8767    if (Context.getTargetInfo().getTriple().isPPC64() &&
8768        !NewVD->isLocalVarDecl() &&
8769        PPC().CheckPPCMMAType(T, NewVD->getLocation())) {
8770      NewVD->setInvalidDecl();
8771      return;
8772    }
8773  
8774    // Check that SVE types are only used in functions with SVE available.
8775    if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
8776      const FunctionDecl *FD = cast<FunctionDecl>(CurContext);
8777      llvm::StringMap<bool> CallerFeatureMap;
8778      Context.getFunctionFeatureMap(CallerFeatureMap, FD);
8779  
8780      if (!Builtin::evaluateRequiredTargetFeatures("sve", CallerFeatureMap)) {
8781        if (!Builtin::evaluateRequiredTargetFeatures("sme", CallerFeatureMap)) {
8782          Diag(NewVD->getLocation(), diag::err_sve_vector_in_non_sve_target) << T;
8783          NewVD->setInvalidDecl();
8784          return;
8785        } else if (!IsArmStreamingFunction(FD,
8786                                           /*IncludeLocallyStreaming=*/true)) {
8787          Diag(NewVD->getLocation(),
8788               diag::err_sve_vector_in_non_streaming_function)
8789              << T;
8790          NewVD->setInvalidDecl();
8791          return;
8792        }
8793      }
8794    }
8795  
8796    if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
8797      const FunctionDecl *FD = cast<FunctionDecl>(CurContext);
8798      llvm::StringMap<bool> CallerFeatureMap;
8799      Context.getFunctionFeatureMap(CallerFeatureMap, FD);
8800      RISCV().checkRVVTypeSupport(T, NewVD->getLocation(), cast<Decl>(CurContext),
8801                                  CallerFeatureMap);
8802    }
8803  }
8804  
CheckVariableDeclaration(VarDecl * NewVD,LookupResult & Previous)8805  bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8806    CheckVariableDeclarationType(NewVD);
8807  
8808    // If the decl is already known invalid, don't check it.
8809    if (NewVD->isInvalidDecl())
8810      return false;
8811  
8812    // If we did not find anything by this name, look for a non-visible
8813    // extern "C" declaration with the same name.
8814    if (Previous.empty() &&
8815        checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8816      Previous.setShadowed();
8817  
8818    if (!Previous.empty()) {
8819      MergeVarDecl(NewVD, Previous);
8820      return true;
8821    }
8822    return false;
8823  }
8824  
AddOverriddenMethods(CXXRecordDecl * DC,CXXMethodDecl * MD)8825  bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8826    llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8827  
8828    // Look for methods in base classes that this method might override.
8829    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8830                       /*DetectVirtual=*/false);
8831    auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8832      CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8833      DeclarationName Name = MD->getDeclName();
8834  
8835      if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8836        // We really want to find the base class destructor here.
8837        QualType T = Context.getTypeDeclType(BaseRecord);
8838        CanQualType CT = Context.getCanonicalType(T);
8839        Name = Context.DeclarationNames.getCXXDestructorName(CT);
8840      }
8841  
8842      for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8843        CXXMethodDecl *BaseMD =
8844            dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8845        if (!BaseMD || !BaseMD->isVirtual() ||
8846            IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8847                       /*ConsiderCudaAttrs=*/true))
8848          continue;
8849        if (!CheckExplicitObjectOverride(MD, BaseMD))
8850          continue;
8851        if (Overridden.insert(BaseMD).second) {
8852          MD->addOverriddenMethod(BaseMD);
8853          CheckOverridingFunctionReturnType(MD, BaseMD);
8854          CheckOverridingFunctionAttributes(MD, BaseMD);
8855          CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8856          CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8857        }
8858  
8859        // A method can only override one function from each base class. We
8860        // don't track indirectly overridden methods from bases of bases.
8861        return true;
8862      }
8863  
8864      return false;
8865    };
8866  
8867    DC->lookupInBases(VisitBase, Paths);
8868    return !Overridden.empty();
8869  }
8870  
8871  namespace {
8872    // Struct for holding all of the extra arguments needed by
8873    // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8874    struct ActOnFDArgs {
8875      Scope *S;
8876      Declarator &D;
8877      MultiTemplateParamsArg TemplateParamLists;
8878      bool AddToScope;
8879    };
8880  } // end anonymous namespace
8881  
8882  namespace {
8883  
8884  // Callback to only accept typo corrections that have a non-zero edit distance.
8885  // Also only accept corrections that have the same parent decl.
8886  class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8887   public:
DifferentNameValidatorCCC(ASTContext & Context,FunctionDecl * TypoFD,CXXRecordDecl * Parent)8888    DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8889                              CXXRecordDecl *Parent)
8890        : Context(Context), OriginalFD(TypoFD),
8891          ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8892  
ValidateCandidate(const TypoCorrection & candidate)8893    bool ValidateCandidate(const TypoCorrection &candidate) override {
8894      if (candidate.getEditDistance() == 0)
8895        return false;
8896  
8897      SmallVector<unsigned, 1> MismatchedParams;
8898      for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8899                                            CDeclEnd = candidate.end();
8900           CDecl != CDeclEnd; ++CDecl) {
8901        FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8902  
8903        if (FD && !FD->hasBody() &&
8904            hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8905          if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8906            CXXRecordDecl *Parent = MD->getParent();
8907            if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8908              return true;
8909          } else if (!ExpectedParent) {
8910            return true;
8911          }
8912        }
8913      }
8914  
8915      return false;
8916    }
8917  
clone()8918    std::unique_ptr<CorrectionCandidateCallback> clone() override {
8919      return std::make_unique<DifferentNameValidatorCCC>(*this);
8920    }
8921  
8922   private:
8923    ASTContext &Context;
8924    FunctionDecl *OriginalFD;
8925    CXXRecordDecl *ExpectedParent;
8926  };
8927  
8928  } // end anonymous namespace
8929  
MarkTypoCorrectedFunctionDefinition(const NamedDecl * F)8930  void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8931    TypoCorrectedFunctionDefinitions.insert(F);
8932  }
8933  
8934  /// Generate diagnostics for an invalid function redeclaration.
8935  ///
8936  /// This routine handles generating the diagnostic messages for an invalid
8937  /// function redeclaration, including finding possible similar declarations
8938  /// or performing typo correction if there are no previous declarations with
8939  /// the same name.
8940  ///
8941  /// Returns a NamedDecl iff typo correction was performed and substituting in
8942  /// the new declaration name does not cause new errors.
DiagnoseInvalidRedeclaration(Sema & SemaRef,LookupResult & Previous,FunctionDecl * NewFD,ActOnFDArgs & ExtraArgs,bool IsLocalFriend,Scope * S)8943  static NamedDecl *DiagnoseInvalidRedeclaration(
8944      Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8945      ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8946    DeclarationName Name = NewFD->getDeclName();
8947    DeclContext *NewDC = NewFD->getDeclContext();
8948    SmallVector<unsigned, 1> MismatchedParams;
8949    SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8950    TypoCorrection Correction;
8951    bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8952    unsigned DiagMsg =
8953      IsLocalFriend ? diag::err_no_matching_local_friend :
8954      NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8955      diag::err_member_decl_does_not_match;
8956    LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8957                      IsLocalFriend ? Sema::LookupLocalFriendName
8958                                    : Sema::LookupOrdinaryName,
8959                      RedeclarationKind::ForVisibleRedeclaration);
8960  
8961    NewFD->setInvalidDecl();
8962    if (IsLocalFriend)
8963      SemaRef.LookupName(Prev, S);
8964    else
8965      SemaRef.LookupQualifiedName(Prev, NewDC);
8966    assert(!Prev.isAmbiguous() &&
8967           "Cannot have an ambiguity in previous-declaration lookup");
8968    CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8969    DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8970                                  MD ? MD->getParent() : nullptr);
8971    if (!Prev.empty()) {
8972      for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8973           Func != FuncEnd; ++Func) {
8974        FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8975        if (FD &&
8976            hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8977          // Add 1 to the index so that 0 can mean the mismatch didn't
8978          // involve a parameter
8979          unsigned ParamNum =
8980              MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8981          NearMatches.push_back(std::make_pair(FD, ParamNum));
8982        }
8983      }
8984    // If the qualified name lookup yielded nothing, try typo correction
8985    } else if ((Correction = SemaRef.CorrectTypo(
8986                    Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8987                    &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8988                    IsLocalFriend ? nullptr : NewDC))) {
8989      // Set up everything for the call to ActOnFunctionDeclarator
8990      ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8991                                ExtraArgs.D.getIdentifierLoc());
8992      Previous.clear();
8993      Previous.setLookupName(Correction.getCorrection());
8994      for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8995                                      CDeclEnd = Correction.end();
8996           CDecl != CDeclEnd; ++CDecl) {
8997        FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8998        if (FD && !FD->hasBody() &&
8999            hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9000          Previous.addDecl(FD);
9001        }
9002      }
9003      bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9004  
9005      NamedDecl *Result;
9006      // Retry building the function declaration with the new previous
9007      // declarations, and with errors suppressed.
9008      {
9009        // Trap errors.
9010        Sema::SFINAETrap Trap(SemaRef);
9011  
9012        // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9013        // pieces need to verify the typo-corrected C++ declaration and hopefully
9014        // eliminate the need for the parameter pack ExtraArgs.
9015        Result = SemaRef.ActOnFunctionDeclarator(
9016            ExtraArgs.S, ExtraArgs.D,
9017            Correction.getCorrectionDecl()->getDeclContext(),
9018            NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
9019            ExtraArgs.AddToScope);
9020  
9021        if (Trap.hasErrorOccurred())
9022          Result = nullptr;
9023      }
9024  
9025      if (Result) {
9026        // Determine which correction we picked.
9027        Decl *Canonical = Result->getCanonicalDecl();
9028        for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9029             I != E; ++I)
9030          if ((*I)->getCanonicalDecl() == Canonical)
9031            Correction.setCorrectionDecl(*I);
9032  
9033        // Let Sema know about the correction.
9034        SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
9035        SemaRef.diagnoseTypo(
9036            Correction,
9037            SemaRef.PDiag(IsLocalFriend
9038                            ? diag::err_no_matching_local_friend_suggest
9039                            : diag::err_member_decl_does_not_match_suggest)
9040              << Name << NewDC << IsDefinition);
9041        return Result;
9042      }
9043  
9044      // Pretend the typo correction never occurred
9045      ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
9046                                ExtraArgs.D.getIdentifierLoc());
9047      ExtraArgs.D.setRedeclaration(wasRedeclaration);
9048      Previous.clear();
9049      Previous.setLookupName(Name);
9050    }
9051  
9052    SemaRef.Diag(NewFD->getLocation(), DiagMsg)
9053        << Name << NewDC << IsDefinition << NewFD->getLocation();
9054  
9055    bool NewFDisConst = false;
9056    if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
9057      NewFDisConst = NewMD->isConst();
9058  
9059    for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9060         NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9061         NearMatch != NearMatchEnd; ++NearMatch) {
9062      FunctionDecl *FD = NearMatch->first;
9063      CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9064      bool FDisConst = MD && MD->isConst();
9065      bool IsMember = MD || !IsLocalFriend;
9066  
9067      // FIXME: These notes are poorly worded for the local friend case.
9068      if (unsigned Idx = NearMatch->second) {
9069        ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
9070        SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9071        if (Loc.isInvalid()) Loc = FD->getLocation();
9072        SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
9073                                   : diag::note_local_decl_close_param_match)
9074          << Idx << FDParam->getType()
9075          << NewFD->getParamDecl(Idx - 1)->getType();
9076      } else if (FDisConst != NewFDisConst) {
9077        auto DB = SemaRef.Diag(FD->getLocation(),
9078                               diag::note_member_def_close_const_match)
9079                  << NewFDisConst << FD->getSourceRange().getEnd();
9080        if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)
9081          DB << FixItHint::CreateInsertion(FTI.getRParenLoc().getLocWithOffset(1),
9082                                           " const");
9083        else if (FTI.hasMethodTypeQualifiers() &&
9084                 FTI.getConstQualifierLoc().isValid())
9085          DB << FixItHint::CreateRemoval(FTI.getConstQualifierLoc());
9086      } else {
9087        SemaRef.Diag(FD->getLocation(),
9088                     IsMember ? diag::note_member_def_close_match
9089                              : diag::note_local_decl_close_match);
9090      }
9091    }
9092    return nullptr;
9093  }
9094  
getFunctionStorageClass(Sema & SemaRef,Declarator & D)9095  static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
9096    switch (D.getDeclSpec().getStorageClassSpec()) {
9097    default: llvm_unreachable("Unknown storage class!");
9098    case DeclSpec::SCS_auto:
9099    case DeclSpec::SCS_register:
9100    case DeclSpec::SCS_mutable:
9101      SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9102                   diag::err_typecheck_sclass_func);
9103      D.getMutableDeclSpec().ClearStorageClassSpecs();
9104      D.setInvalidType();
9105      break;
9106    case DeclSpec::SCS_unspecified: break;
9107    case DeclSpec::SCS_extern:
9108      if (D.getDeclSpec().isExternInLinkageSpec())
9109        return SC_None;
9110      return SC_Extern;
9111    case DeclSpec::SCS_static: {
9112      if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
9113        // C99 6.7.1p5:
9114        //   The declaration of an identifier for a function that has
9115        //   block scope shall have no explicit storage-class specifier
9116        //   other than extern
9117        // See also (C++ [dcl.stc]p4).
9118        SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9119                     diag::err_static_block_func);
9120        break;
9121      } else
9122        return SC_Static;
9123    }
9124    case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
9125    }
9126  
9127    // No explicit storage class has already been returned
9128    return SC_None;
9129  }
9130  
CreateNewFunctionDecl(Sema & SemaRef,Declarator & D,DeclContext * DC,QualType & R,TypeSourceInfo * TInfo,StorageClass SC,bool & IsVirtualOkay)9131  static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
9132                                             DeclContext *DC, QualType &R,
9133                                             TypeSourceInfo *TInfo,
9134                                             StorageClass SC,
9135                                             bool &IsVirtualOkay) {
9136    DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9137    DeclarationName Name = NameInfo.getName();
9138  
9139    FunctionDecl *NewFD = nullptr;
9140    bool isInline = D.getDeclSpec().isInlineSpecified();
9141  
9142    ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9143    if (ConstexprKind == ConstexprSpecKind::Constinit ||
9144        (SemaRef.getLangOpts().C23 &&
9145         ConstexprKind == ConstexprSpecKind::Constexpr)) {
9146  
9147      if (SemaRef.getLangOpts().C23)
9148        SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9149                     diag::err_c23_constexpr_not_variable);
9150      else
9151        SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9152                     diag::err_constexpr_wrong_decl_kind)
9153            << static_cast<int>(ConstexprKind);
9154      ConstexprKind = ConstexprSpecKind::Unspecified;
9155      D.getMutableDeclSpec().ClearConstexprSpec();
9156    }
9157  
9158    if (!SemaRef.getLangOpts().CPlusPlus) {
9159      // Determine whether the function was written with a prototype. This is
9160      // true when:
9161      //   - there is a prototype in the declarator, or
9162      //   - the type R of the function is some kind of typedef or other non-
9163      //     attributed reference to a type name (which eventually refers to a
9164      //     function type). Note, we can't always look at the adjusted type to
9165      //     check this case because attributes may cause a non-function
9166      //     declarator to still have a function type. e.g.,
9167      //       typedef void func(int a);
9168      //       __attribute__((noreturn)) func other_func; // This has a prototype
9169      bool HasPrototype =
9170          (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
9171          (D.getDeclSpec().isTypeRep() &&
9172           SemaRef.GetTypeFromParser(D.getDeclSpec().getRepAsType(), nullptr)
9173               ->isFunctionProtoType()) ||
9174          (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
9175      assert(
9176          (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9177          "Strict prototypes are required");
9178  
9179      NewFD = FunctionDecl::Create(
9180          SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9181          SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
9182          ConstexprSpecKind::Unspecified,
9183          /*TrailingRequiresClause=*/nullptr);
9184      if (D.isInvalidType())
9185        NewFD->setInvalidDecl();
9186  
9187      return NewFD;
9188    }
9189  
9190    ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
9191    Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
9192  
9193    SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9194  
9195    if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
9196      // This is a C++ constructor declaration.
9197      assert(DC->isRecord() &&
9198             "Constructors can only be declared in a member context");
9199  
9200      R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9201      return CXXConstructorDecl::Create(
9202          SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9203          TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(),
9204          isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9205          InheritedConstructor(), TrailingRequiresClause);
9206  
9207    } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9208      // This is a C++ destructor declaration.
9209      if (DC->isRecord()) {
9210        R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9211        CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
9212        CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
9213            SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
9214            SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9215            /*isImplicitlyDeclared=*/false, ConstexprKind,
9216            TrailingRequiresClause);
9217        // User defined destructors start as not selected if the class definition is still
9218        // not done.
9219        if (Record->isBeingDefined())
9220          NewDD->setIneligibleOrNotSelected(true);
9221  
9222        // If the destructor needs an implicit exception specification, set it
9223        // now. FIXME: It'd be nice to be able to create the right type to start
9224        // with, but the type needs to reference the destructor declaration.
9225        if (SemaRef.getLangOpts().CPlusPlus11)
9226          SemaRef.AdjustDestructorExceptionSpec(NewDD);
9227  
9228        IsVirtualOkay = true;
9229        return NewDD;
9230  
9231      } else {
9232        SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
9233        D.setInvalidType();
9234  
9235        // Create a FunctionDecl to satisfy the function definition parsing
9236        // code path.
9237        return FunctionDecl::Create(
9238            SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
9239            TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9240            /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
9241      }
9242  
9243    } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
9244      if (!DC->isRecord()) {
9245        SemaRef.Diag(D.getIdentifierLoc(),
9246             diag::err_conv_function_not_member);
9247        return nullptr;
9248      }
9249  
9250      SemaRef.CheckConversionDeclarator(D, R, SC);
9251      if (D.isInvalidType())
9252        return nullptr;
9253  
9254      IsVirtualOkay = true;
9255      return CXXConversionDecl::Create(
9256          SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9257          TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9258          ExplicitSpecifier, ConstexprKind, SourceLocation(),
9259          TrailingRequiresClause);
9260  
9261    } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9262      if (TrailingRequiresClause)
9263        SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
9264                     diag::err_trailing_requires_clause_on_deduction_guide)
9265            << TrailingRequiresClause->getSourceRange();
9266      if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9267        return nullptr;
9268      return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
9269                                           ExplicitSpecifier, NameInfo, R, TInfo,
9270                                           D.getEndLoc());
9271    } else if (DC->isRecord()) {
9272      // If the name of the function is the same as the name of the record,
9273      // then this must be an invalid constructor that has a return type.
9274      // (The parser checks for a return type and makes the declarator a
9275      // constructor if it has no return type).
9276      if (Name.getAsIdentifierInfo() &&
9277          Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
9278        SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
9279          << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
9280          << SourceRange(D.getIdentifierLoc());
9281        return nullptr;
9282      }
9283  
9284      // This is a C++ method declaration.
9285      CXXMethodDecl *Ret = CXXMethodDecl::Create(
9286          SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9287          TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9288          ConstexprKind, SourceLocation(), TrailingRequiresClause);
9289      IsVirtualOkay = !Ret->isStatic();
9290      return Ret;
9291    } else {
9292      bool isFriend =
9293          SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9294      if (!isFriend && SemaRef.CurContext->isRecord())
9295        return nullptr;
9296  
9297      // Determine whether the function was written with a
9298      // prototype. This true when:
9299      //   - we're in C++ (where every function has a prototype),
9300      return FunctionDecl::Create(
9301          SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9302          SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9303          true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9304    }
9305  }
9306  
9307  enum OpenCLParamType {
9308    ValidKernelParam,
9309    PtrPtrKernelParam,
9310    PtrKernelParam,
9311    InvalidAddrSpacePtrKernelParam,
9312    InvalidKernelParam,
9313    RecordKernelParam
9314  };
9315  
isOpenCLSizeDependentType(ASTContext & C,QualType Ty)9316  static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
9317    // Size dependent types are just typedefs to normal integer types
9318    // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9319    // integers other than by their names.
9320    StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9321  
9322    // Remove typedefs one by one until we reach a typedef
9323    // for a size dependent type.
9324    QualType DesugaredTy = Ty;
9325    do {
9326      ArrayRef<StringRef> Names(SizeTypeNames);
9327      auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
9328      if (Names.end() != Match)
9329        return true;
9330  
9331      Ty = DesugaredTy;
9332      DesugaredTy = Ty.getSingleStepDesugaredType(C);
9333    } while (DesugaredTy != Ty);
9334  
9335    return false;
9336  }
9337  
getOpenCLKernelParameterType(Sema & S,QualType PT)9338  static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
9339    if (PT->isDependentType())
9340      return InvalidKernelParam;
9341  
9342    if (PT->isPointerType() || PT->isReferenceType()) {
9343      QualType PointeeType = PT->getPointeeType();
9344      if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9345          PointeeType.getAddressSpace() == LangAS::opencl_private ||
9346          PointeeType.getAddressSpace() == LangAS::Default)
9347        return InvalidAddrSpacePtrKernelParam;
9348  
9349      if (PointeeType->isPointerType()) {
9350        // This is a pointer to pointer parameter.
9351        // Recursively check inner type.
9352        OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9353        if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9354            ParamKind == InvalidKernelParam)
9355          return ParamKind;
9356  
9357        // OpenCL v3.0 s6.11.a:
9358        // A restriction to pass pointers to pointers only applies to OpenCL C
9359        // v1.2 or below.
9360        if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9361          return ValidKernelParam;
9362  
9363        return PtrPtrKernelParam;
9364      }
9365  
9366      // C++ for OpenCL v1.0 s2.4:
9367      // Moreover the types used in parameters of the kernel functions must be:
9368      // Standard layout types for pointer parameters. The same applies to
9369      // reference if an implementation supports them in kernel parameters.
9370      if (S.getLangOpts().OpenCLCPlusPlus &&
9371          !S.getOpenCLOptions().isAvailableOption(
9372              "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {
9373       auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9374       bool IsStandardLayoutType = true;
9375       if (CXXRec) {
9376         // If template type is not ODR-used its definition is only available
9377         // in the template definition not its instantiation.
9378         // FIXME: This logic doesn't work for types that depend on template
9379         // parameter (PR58590).
9380         if (!CXXRec->hasDefinition())
9381           CXXRec = CXXRec->getTemplateInstantiationPattern();
9382         if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9383           IsStandardLayoutType = false;
9384       }
9385       if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9386          !IsStandardLayoutType)
9387        return InvalidKernelParam;
9388      }
9389  
9390      // OpenCL v1.2 s6.9.p:
9391      // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9392      if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9393        return ValidKernelParam;
9394  
9395      return PtrKernelParam;
9396    }
9397  
9398    // OpenCL v1.2 s6.9.k:
9399    // Arguments to kernel functions in a program cannot be declared with the
9400    // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9401    // uintptr_t or a struct and/or union that contain fields declared to be one
9402    // of these built-in scalar types.
9403    if (isOpenCLSizeDependentType(S.getASTContext(), PT))
9404      return InvalidKernelParam;
9405  
9406    if (PT->isImageType())
9407      return PtrKernelParam;
9408  
9409    if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9410      return InvalidKernelParam;
9411  
9412    // OpenCL extension spec v1.2 s9.5:
9413    // This extension adds support for half scalar and vector types as built-in
9414    // types that can be used for arithmetic operations, conversions etc.
9415    if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9416        PT->isHalfType())
9417      return InvalidKernelParam;
9418  
9419    // Look into an array argument to check if it has a forbidden type.
9420    if (PT->isArrayType()) {
9421      const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9422      // Call ourself to check an underlying type of an array. Since the
9423      // getPointeeOrArrayElementType returns an innermost type which is not an
9424      // array, this recursive call only happens once.
9425      return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9426    }
9427  
9428    // C++ for OpenCL v1.0 s2.4:
9429    // Moreover the types used in parameters of the kernel functions must be:
9430    // Trivial and standard-layout types C++17 [basic.types] (plain old data
9431    // types) for parameters passed by value;
9432    if (S.getLangOpts().OpenCLCPlusPlus &&
9433        !S.getOpenCLOptions().isAvailableOption(
9434            "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9435        !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9436      return InvalidKernelParam;
9437  
9438    if (PT->isRecordType())
9439      return RecordKernelParam;
9440  
9441    return ValidKernelParam;
9442  }
9443  
checkIsValidOpenCLKernelParameter(Sema & S,Declarator & D,ParmVarDecl * Param,llvm::SmallPtrSetImpl<const Type * > & ValidTypes)9444  static void checkIsValidOpenCLKernelParameter(
9445    Sema &S,
9446    Declarator &D,
9447    ParmVarDecl *Param,
9448    llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9449    QualType PT = Param->getType();
9450  
9451    // Cache the valid types we encounter to avoid rechecking structs that are
9452    // used again
9453    if (ValidTypes.count(PT.getTypePtr()))
9454      return;
9455  
9456    switch (getOpenCLKernelParameterType(S, PT)) {
9457    case PtrPtrKernelParam:
9458      // OpenCL v3.0 s6.11.a:
9459      // A kernel function argument cannot be declared as a pointer to a pointer
9460      // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9461      S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9462      D.setInvalidType();
9463      return;
9464  
9465    case InvalidAddrSpacePtrKernelParam:
9466      // OpenCL v1.0 s6.5:
9467      // __kernel function arguments declared to be a pointer of a type can point
9468      // to one of the following address spaces only : __global, __local or
9469      // __constant.
9470      S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9471      D.setInvalidType();
9472      return;
9473  
9474      // OpenCL v1.2 s6.9.k:
9475      // Arguments to kernel functions in a program cannot be declared with the
9476      // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9477      // uintptr_t or a struct and/or union that contain fields declared to be
9478      // one of these built-in scalar types.
9479  
9480    case InvalidKernelParam:
9481      // OpenCL v1.2 s6.8 n:
9482      // A kernel function argument cannot be declared
9483      // of event_t type.
9484      // Do not diagnose half type since it is diagnosed as invalid argument
9485      // type for any function elsewhere.
9486      if (!PT->isHalfType()) {
9487        S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9488  
9489        // Explain what typedefs are involved.
9490        const TypedefType *Typedef = nullptr;
9491        while ((Typedef = PT->getAs<TypedefType>())) {
9492          SourceLocation Loc = Typedef->getDecl()->getLocation();
9493          // SourceLocation may be invalid for a built-in type.
9494          if (Loc.isValid())
9495            S.Diag(Loc, diag::note_entity_declared_at) << PT;
9496          PT = Typedef->desugar();
9497        }
9498      }
9499  
9500      D.setInvalidType();
9501      return;
9502  
9503    case PtrKernelParam:
9504    case ValidKernelParam:
9505      ValidTypes.insert(PT.getTypePtr());
9506      return;
9507  
9508    case RecordKernelParam:
9509      break;
9510    }
9511  
9512    // Track nested structs we will inspect
9513    SmallVector<const Decl *, 4> VisitStack;
9514  
9515    // Track where we are in the nested structs. Items will migrate from
9516    // VisitStack to HistoryStack as we do the DFS for bad field.
9517    SmallVector<const FieldDecl *, 4> HistoryStack;
9518    HistoryStack.push_back(nullptr);
9519  
9520    // At this point we already handled everything except of a RecordType or
9521    // an ArrayType of a RecordType.
9522    assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
9523    const RecordType *RecTy =
9524        PT->getPointeeOrArrayElementType()->getAs<RecordType>();
9525    const RecordDecl *OrigRecDecl = RecTy->getDecl();
9526  
9527    VisitStack.push_back(RecTy->getDecl());
9528    assert(VisitStack.back() && "First decl null?");
9529  
9530    do {
9531      const Decl *Next = VisitStack.pop_back_val();
9532      if (!Next) {
9533        assert(!HistoryStack.empty());
9534        // Found a marker, we have gone up a level
9535        if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9536          ValidTypes.insert(Hist->getType().getTypePtr());
9537  
9538        continue;
9539      }
9540  
9541      // Adds everything except the original parameter declaration (which is not a
9542      // field itself) to the history stack.
9543      const RecordDecl *RD;
9544      if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9545        HistoryStack.push_back(Field);
9546  
9547        QualType FieldTy = Field->getType();
9548        // Other field types (known to be valid or invalid) are handled while we
9549        // walk around RecordDecl::fields().
9550        assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9551               "Unexpected type.");
9552        const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9553  
9554        RD = FieldRecTy->castAs<RecordType>()->getDecl();
9555      } else {
9556        RD = cast<RecordDecl>(Next);
9557      }
9558  
9559      // Add a null marker so we know when we've gone back up a level
9560      VisitStack.push_back(nullptr);
9561  
9562      for (const auto *FD : RD->fields()) {
9563        QualType QT = FD->getType();
9564  
9565        if (ValidTypes.count(QT.getTypePtr()))
9566          continue;
9567  
9568        OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
9569        if (ParamType == ValidKernelParam)
9570          continue;
9571  
9572        if (ParamType == RecordKernelParam) {
9573          VisitStack.push_back(FD);
9574          continue;
9575        }
9576  
9577        // OpenCL v1.2 s6.9.p:
9578        // Arguments to kernel functions that are declared to be a struct or union
9579        // do not allow OpenCL objects to be passed as elements of the struct or
9580        // union. This restriction was lifted in OpenCL v2.0 with the introduction
9581        // of SVM.
9582        if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9583            ParamType == InvalidAddrSpacePtrKernelParam) {
9584          S.Diag(Param->getLocation(),
9585                 diag::err_record_with_pointers_kernel_param)
9586            << PT->isUnionType()
9587            << PT;
9588        } else {
9589          S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9590        }
9591  
9592        S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9593            << OrigRecDecl->getDeclName();
9594  
9595        // We have an error, now let's go back up through history and show where
9596        // the offending field came from
9597        for (ArrayRef<const FieldDecl *>::const_iterator
9598                 I = HistoryStack.begin() + 1,
9599                 E = HistoryStack.end();
9600             I != E; ++I) {
9601          const FieldDecl *OuterField = *I;
9602          S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9603            << OuterField->getType();
9604        }
9605  
9606        S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9607          << QT->isPointerType()
9608          << QT;
9609        D.setInvalidType();
9610        return;
9611      }
9612    } while (!VisitStack.empty());
9613  }
9614  
9615  /// Find the DeclContext in which a tag is implicitly declared if we see an
9616  /// elaborated type specifier in the specified context, and lookup finds
9617  /// nothing.
getTagInjectionContext(DeclContext * DC)9618  static DeclContext *getTagInjectionContext(DeclContext *DC) {
9619    while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9620      DC = DC->getParent();
9621    return DC;
9622  }
9623  
9624  /// Find the Scope in which a tag is implicitly declared if we see an
9625  /// elaborated type specifier in the specified context, and lookup finds
9626  /// nothing.
getTagInjectionScope(Scope * S,const LangOptions & LangOpts)9627  static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9628    while (S->isClassScope() ||
9629           (LangOpts.CPlusPlus &&
9630            S->isFunctionPrototypeScope()) ||
9631           ((S->getFlags() & Scope::DeclScope) == 0) ||
9632           (S->getEntity() && S->getEntity()->isTransparentContext()))
9633      S = S->getParent();
9634    return S;
9635  }
9636  
9637  /// Determine whether a declaration matches a known function in namespace std.
isStdBuiltin(ASTContext & Ctx,FunctionDecl * FD,unsigned BuiltinID)9638  static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,
9639                           unsigned BuiltinID) {
9640    switch (BuiltinID) {
9641    case Builtin::BI__GetExceptionInfo:
9642      // No type checking whatsoever.
9643      return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
9644  
9645    case Builtin::BIaddressof:
9646    case Builtin::BI__addressof:
9647    case Builtin::BIforward:
9648    case Builtin::BIforward_like:
9649    case Builtin::BImove:
9650    case Builtin::BImove_if_noexcept:
9651    case Builtin::BIas_const: {
9652      // Ensure that we don't treat the algorithm
9653      //   OutputIt std::move(InputIt, InputIt, OutputIt)
9654      // as the builtin std::move.
9655      const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9656      return FPT->getNumParams() == 1 && !FPT->isVariadic();
9657    }
9658  
9659    default:
9660      return false;
9661    }
9662  }
9663  
9664  NamedDecl*
ActOnFunctionDeclarator(Scope * S,Declarator & D,DeclContext * DC,TypeSourceInfo * TInfo,LookupResult & Previous,MultiTemplateParamsArg TemplateParamListsRef,bool & AddToScope)9665  Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9666                                TypeSourceInfo *TInfo, LookupResult &Previous,
9667                                MultiTemplateParamsArg TemplateParamListsRef,
9668                                bool &AddToScope) {
9669    QualType R = TInfo->getType();
9670  
9671    assert(R->isFunctionType());
9672    if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9673      Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9674  
9675    SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9676    llvm::append_range(TemplateParamLists, TemplateParamListsRef);
9677    if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9678      if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
9679          Invented->getDepth() == TemplateParamLists.back()->getDepth())
9680        TemplateParamLists.back() = Invented;
9681      else
9682        TemplateParamLists.push_back(Invented);
9683    }
9684  
9685    // TODO: consider using NameInfo for diagnostic.
9686    DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9687    DeclarationName Name = NameInfo.getName();
9688    StorageClass SC = getFunctionStorageClass(*this, D);
9689  
9690    if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9691      Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9692           diag::err_invalid_thread)
9693        << DeclSpec::getSpecifierName(TSCS);
9694  
9695    if (D.isFirstDeclarationOfMember())
9696      adjustMemberFunctionCC(
9697          R, !(D.isStaticMember() || D.isExplicitObjectMemberFunction()),
9698          D.isCtorOrDtor(), D.getIdentifierLoc());
9699  
9700    bool isFriend = false;
9701    FunctionTemplateDecl *FunctionTemplate = nullptr;
9702    bool isMemberSpecialization = false;
9703    bool isFunctionTemplateSpecialization = false;
9704  
9705    bool HasExplicitTemplateArgs = false;
9706    TemplateArgumentListInfo TemplateArgs;
9707  
9708    bool isVirtualOkay = false;
9709  
9710    DeclContext *OriginalDC = DC;
9711    bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9712  
9713    FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9714                                                isVirtualOkay);
9715    if (!NewFD) return nullptr;
9716  
9717    if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9718      NewFD->setTopLevelDeclInObjCContainer();
9719  
9720    // Set the lexical context. If this is a function-scope declaration, or has a
9721    // C++ scope specifier, or is the object of a friend declaration, the lexical
9722    // context will be different from the semantic context.
9723    NewFD->setLexicalDeclContext(CurContext);
9724  
9725    if (IsLocalExternDecl)
9726      NewFD->setLocalExternDecl();
9727  
9728    if (getLangOpts().CPlusPlus) {
9729      // The rules for implicit inlines changed in C++20 for methods and friends
9730      // with an in-class definition (when such a definition is not attached to
9731      // the global module).  User-specified 'inline' overrides this (set when
9732      // the function decl is created above).
9733      // FIXME: We need a better way to separate C++ standard and clang modules.
9734      bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
9735                                 NewFD->isConstexpr() || NewFD->isConsteval() ||
9736                                 !NewFD->getOwningModule() ||
9737                                 NewFD->isFromGlobalModule() ||
9738                                 NewFD->getOwningModule()->isHeaderLikeModule();
9739      bool isInline = D.getDeclSpec().isInlineSpecified();
9740      bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9741      bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9742      isFriend = D.getDeclSpec().isFriendSpecified();
9743      if (isFriend && !isInline && D.isFunctionDefinition()) {
9744        // Pre-C++20 [class.friend]p5
9745        //   A function can be defined in a friend declaration of a
9746        //   class . . . . Such a function is implicitly inline.
9747        // Post C++20 [class.friend]p7
9748        //   Such a function is implicitly an inline function if it is attached
9749        //   to the global module.
9750        NewFD->setImplicitlyInline(ImplicitInlineCXX20);
9751      }
9752  
9753      // If this is a method defined in an __interface, and is not a constructor
9754      // or an overloaded operator, then set the pure flag (isVirtual will already
9755      // return true).
9756      if (const CXXRecordDecl *Parent =
9757            dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9758        if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9759          NewFD->setIsPureVirtual(true);
9760  
9761        // C++ [class.union]p2
9762        //   A union can have member functions, but not virtual functions.
9763        if (isVirtual && Parent->isUnion()) {
9764          Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9765          NewFD->setInvalidDecl();
9766        }
9767        if ((Parent->isClass() || Parent->isStruct()) &&
9768            Parent->hasAttr<SYCLSpecialClassAttr>() &&
9769            NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9770            NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9771          if (auto *Def = Parent->getDefinition())
9772            Def->setInitMethod(true);
9773        }
9774      }
9775  
9776      SetNestedNameSpecifier(*this, NewFD, D);
9777      isMemberSpecialization = false;
9778      isFunctionTemplateSpecialization = false;
9779      if (D.isInvalidType())
9780        NewFD->setInvalidDecl();
9781  
9782      // Match up the template parameter lists with the scope specifier, then
9783      // determine whether we have a template or a template specialization.
9784      bool Invalid = false;
9785      TemplateIdAnnotation *TemplateId =
9786          D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9787              ? D.getName().TemplateId
9788              : nullptr;
9789      TemplateParameterList *TemplateParams =
9790          MatchTemplateParametersToScopeSpecifier(
9791              D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9792              D.getCXXScopeSpec(), TemplateId, TemplateParamLists, isFriend,
9793              isMemberSpecialization, Invalid);
9794      if (TemplateParams) {
9795        // Check that we can declare a template here.
9796        if (CheckTemplateDeclScope(S, TemplateParams))
9797          NewFD->setInvalidDecl();
9798  
9799        if (TemplateParams->size() > 0) {
9800          // This is a function template
9801  
9802          // A destructor cannot be a template.
9803          if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9804            Diag(NewFD->getLocation(), diag::err_destructor_template);
9805            NewFD->setInvalidDecl();
9806            // Function template with explicit template arguments.
9807          } else if (TemplateId) {
9808            Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9809                << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9810            NewFD->setInvalidDecl();
9811          }
9812  
9813          // If we're adding a template to a dependent context, we may need to
9814          // rebuilding some of the types used within the template parameter list,
9815          // now that we know what the current instantiation is.
9816          if (DC->isDependentContext()) {
9817            ContextRAII SavedContext(*this, DC);
9818            if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9819              Invalid = true;
9820          }
9821  
9822          FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9823                                                          NewFD->getLocation(),
9824                                                          Name, TemplateParams,
9825                                                          NewFD);
9826          FunctionTemplate->setLexicalDeclContext(CurContext);
9827          NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9828  
9829          // For source fidelity, store the other template param lists.
9830          if (TemplateParamLists.size() > 1) {
9831            NewFD->setTemplateParameterListsInfo(Context,
9832                ArrayRef<TemplateParameterList *>(TemplateParamLists)
9833                    .drop_back(1));
9834          }
9835        } else {
9836          // This is a function template specialization.
9837          isFunctionTemplateSpecialization = true;
9838          // For source fidelity, store all the template param lists.
9839          if (TemplateParamLists.size() > 0)
9840            NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9841  
9842          // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9843          if (isFriend) {
9844            // We want to remove the "template<>", found here.
9845            SourceRange RemoveRange = TemplateParams->getSourceRange();
9846  
9847            // If we remove the template<> and the name is not a
9848            // template-id, we're actually silently creating a problem:
9849            // the friend declaration will refer to an untemplated decl,
9850            // and clearly the user wants a template specialization.  So
9851            // we need to insert '<>' after the name.
9852            SourceLocation InsertLoc;
9853            if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9854              InsertLoc = D.getName().getSourceRange().getEnd();
9855              InsertLoc = getLocForEndOfToken(InsertLoc);
9856            }
9857  
9858            Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9859              << Name << RemoveRange
9860              << FixItHint::CreateRemoval(RemoveRange)
9861              << FixItHint::CreateInsertion(InsertLoc, "<>");
9862            Invalid = true;
9863  
9864            // Recover by faking up an empty template argument list.
9865            HasExplicitTemplateArgs = true;
9866            TemplateArgs.setLAngleLoc(InsertLoc);
9867            TemplateArgs.setRAngleLoc(InsertLoc);
9868          }
9869        }
9870      } else {
9871        // Check that we can declare a template here.
9872        if (!TemplateParamLists.empty() && isMemberSpecialization &&
9873            CheckTemplateDeclScope(S, TemplateParamLists.back()))
9874          NewFD->setInvalidDecl();
9875  
9876        // All template param lists were matched against the scope specifier:
9877        // this is NOT (an explicit specialization of) a template.
9878        if (TemplateParamLists.size() > 0)
9879          // For source fidelity, store all the template param lists.
9880          NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9881  
9882        // "friend void foo<>(int);" is an implicit specialization decl.
9883        if (isFriend && TemplateId)
9884          isFunctionTemplateSpecialization = true;
9885      }
9886  
9887      // If this is a function template specialization and the unqualified-id of
9888      // the declarator-id is a template-id, convert the template argument list
9889      // into our AST format and check for unexpanded packs.
9890      if (isFunctionTemplateSpecialization && TemplateId) {
9891        HasExplicitTemplateArgs = true;
9892  
9893        TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9894        TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9895        ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9896                                           TemplateId->NumArgs);
9897        translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
9898  
9899        // FIXME: Should we check for unexpanded packs if this was an (invalid)
9900        // declaration of a function template partial specialization? Should we
9901        // consider the unexpanded pack context to be a partial specialization?
9902        for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
9903          if (DiagnoseUnexpandedParameterPack(
9904                  ArgLoc, isFriend ? UPPC_FriendDeclaration
9905                                   : UPPC_ExplicitSpecialization))
9906            NewFD->setInvalidDecl();
9907        }
9908      }
9909  
9910      if (Invalid) {
9911        NewFD->setInvalidDecl();
9912        if (FunctionTemplate)
9913          FunctionTemplate->setInvalidDecl();
9914      }
9915  
9916      // C++ [dcl.fct.spec]p5:
9917      //   The virtual specifier shall only be used in declarations of
9918      //   nonstatic class member functions that appear within a
9919      //   member-specification of a class declaration; see 10.3.
9920      //
9921      if (isVirtual && !NewFD->isInvalidDecl()) {
9922        if (!isVirtualOkay) {
9923          Diag(D.getDeclSpec().getVirtualSpecLoc(),
9924               diag::err_virtual_non_function);
9925        } else if (!CurContext->isRecord()) {
9926          // 'virtual' was specified outside of the class.
9927          Diag(D.getDeclSpec().getVirtualSpecLoc(),
9928               diag::err_virtual_out_of_class)
9929            << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9930        } else if (NewFD->getDescribedFunctionTemplate()) {
9931          // C++ [temp.mem]p3:
9932          //  A member function template shall not be virtual.
9933          Diag(D.getDeclSpec().getVirtualSpecLoc(),
9934               diag::err_virtual_member_function_template)
9935            << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9936        } else {
9937          // Okay: Add virtual to the method.
9938          NewFD->setVirtualAsWritten(true);
9939        }
9940  
9941        if (getLangOpts().CPlusPlus14 &&
9942            NewFD->getReturnType()->isUndeducedType())
9943          Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9944      }
9945  
9946      // C++ [dcl.fct.spec]p3:
9947      //  The inline specifier shall not appear on a block scope function
9948      //  declaration.
9949      if (isInline && !NewFD->isInvalidDecl()) {
9950        if (CurContext->isFunctionOrMethod()) {
9951          // 'inline' is not allowed on block scope function declaration.
9952          Diag(D.getDeclSpec().getInlineSpecLoc(),
9953               diag::err_inline_declaration_block_scope) << Name
9954            << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9955        }
9956      }
9957  
9958      // C++ [dcl.fct.spec]p6:
9959      //  The explicit specifier shall be used only in the declaration of a
9960      //  constructor or conversion function within its class definition;
9961      //  see 12.3.1 and 12.3.2.
9962      if (hasExplicit && !NewFD->isInvalidDecl() &&
9963          !isa<CXXDeductionGuideDecl>(NewFD)) {
9964        if (!CurContext->isRecord()) {
9965          // 'explicit' was specified outside of the class.
9966          Diag(D.getDeclSpec().getExplicitSpecLoc(),
9967               diag::err_explicit_out_of_class)
9968              << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9969        } else if (!isa<CXXConstructorDecl>(NewFD) &&
9970                   !isa<CXXConversionDecl>(NewFD)) {
9971          // 'explicit' was specified on a function that wasn't a constructor
9972          // or conversion function.
9973          Diag(D.getDeclSpec().getExplicitSpecLoc(),
9974               diag::err_explicit_non_ctor_or_conv_function)
9975              << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9976        }
9977      }
9978  
9979      ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9980      if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9981        // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9982        // are implicitly inline.
9983        NewFD->setImplicitlyInline();
9984  
9985        // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9986        // be either constructors or to return a literal type. Therefore,
9987        // destructors cannot be declared constexpr.
9988        if (isa<CXXDestructorDecl>(NewFD) &&
9989            (!getLangOpts().CPlusPlus20 ||
9990             ConstexprKind == ConstexprSpecKind::Consteval)) {
9991          Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9992              << static_cast<int>(ConstexprKind);
9993          NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9994                                      ? ConstexprSpecKind::Unspecified
9995                                      : ConstexprSpecKind::Constexpr);
9996        }
9997        // C++20 [dcl.constexpr]p2: An allocation function, or a
9998        // deallocation function shall not be declared with the consteval
9999        // specifier.
10000        if (ConstexprKind == ConstexprSpecKind::Consteval &&
10001            (NewFD->getOverloadedOperator() == OO_New ||
10002             NewFD->getOverloadedOperator() == OO_Array_New ||
10003             NewFD->getOverloadedOperator() == OO_Delete ||
10004             NewFD->getOverloadedOperator() == OO_Array_Delete)) {
10005          Diag(D.getDeclSpec().getConstexprSpecLoc(),
10006               diag::err_invalid_consteval_decl_kind)
10007              << NewFD;
10008          NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
10009        }
10010      }
10011  
10012      // If __module_private__ was specified, mark the function accordingly.
10013      if (D.getDeclSpec().isModulePrivateSpecified()) {
10014        if (isFunctionTemplateSpecialization) {
10015          SourceLocation ModulePrivateLoc
10016            = D.getDeclSpec().getModulePrivateSpecLoc();
10017          Diag(ModulePrivateLoc, diag::err_module_private_specialization)
10018            << 0
10019            << FixItHint::CreateRemoval(ModulePrivateLoc);
10020        } else {
10021          NewFD->setModulePrivate();
10022          if (FunctionTemplate)
10023            FunctionTemplate->setModulePrivate();
10024        }
10025      }
10026  
10027      if (isFriend) {
10028        if (FunctionTemplate) {
10029          FunctionTemplate->setObjectOfFriendDecl();
10030          FunctionTemplate->setAccess(AS_public);
10031        }
10032        NewFD->setObjectOfFriendDecl();
10033        NewFD->setAccess(AS_public);
10034      }
10035  
10036      // If a function is defined as defaulted or deleted, mark it as such now.
10037      // We'll do the relevant checks on defaulted / deleted functions later.
10038      switch (D.getFunctionDefinitionKind()) {
10039      case FunctionDefinitionKind::Declaration:
10040      case FunctionDefinitionKind::Definition:
10041        break;
10042  
10043      case FunctionDefinitionKind::Defaulted:
10044        NewFD->setDefaulted();
10045        break;
10046  
10047      case FunctionDefinitionKind::Deleted:
10048        NewFD->setDeletedAsWritten();
10049        break;
10050      }
10051  
10052      if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
10053          D.isFunctionDefinition() && !isInline) {
10054        // Pre C++20 [class.mfct]p2:
10055        //   A member function may be defined (8.4) in its class definition, in
10056        //   which case it is an inline member function (7.1.2)
10057        // Post C++20 [class.mfct]p1:
10058        //   If a member function is attached to the global module and is defined
10059        //   in its class definition, it is inline.
10060        NewFD->setImplicitlyInline(ImplicitInlineCXX20);
10061      }
10062  
10063      if (!isFriend && SC != SC_None) {
10064        // C++ [temp.expl.spec]p2:
10065        //   The declaration in an explicit-specialization shall not be an
10066        //   export-declaration. An explicit specialization shall not use a
10067        //   storage-class-specifier other than thread_local.
10068        //
10069        // We diagnose friend declarations with storage-class-specifiers
10070        // elsewhere.
10071        if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10072          Diag(D.getDeclSpec().getStorageClassSpecLoc(),
10073               diag::ext_explicit_specialization_storage_class)
10074              << FixItHint::CreateRemoval(
10075                     D.getDeclSpec().getStorageClassSpecLoc());
10076        }
10077  
10078        if (SC == SC_Static && !CurContext->isRecord() && DC->isRecord()) {
10079          assert(isa<CXXMethodDecl>(NewFD) &&
10080                 "Out-of-line member function should be a CXXMethodDecl");
10081          // C++ [class.static]p1:
10082          //   A data or function member of a class may be declared static
10083          //   in a class definition, in which case it is a static member of
10084          //   the class.
10085  
10086          // Complain about the 'static' specifier if it's on an out-of-line
10087          // member function definition.
10088  
10089          // MSVC permits the use of a 'static' storage specifier on an
10090          // out-of-line member function template declaration and class member
10091          // template declaration (MSVC versions before 2015), warn about this.
10092          Diag(D.getDeclSpec().getStorageClassSpecLoc(),
10093               ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
10094                 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
10095                (getLangOpts().MSVCCompat &&
10096                 NewFD->getDescribedFunctionTemplate()))
10097                   ? diag::ext_static_out_of_line
10098                   : diag::err_static_out_of_line)
10099              << FixItHint::CreateRemoval(
10100                     D.getDeclSpec().getStorageClassSpecLoc());
10101        }
10102      }
10103  
10104      // C++11 [except.spec]p15:
10105      //   A deallocation function with no exception-specification is treated
10106      //   as if it were specified with noexcept(true).
10107      const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10108      if ((Name.getCXXOverloadedOperator() == OO_Delete ||
10109           Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
10110          getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
10111        NewFD->setType(Context.getFunctionType(
10112            FPT->getReturnType(), FPT->getParamTypes(),
10113            FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
10114  
10115      // C++20 [dcl.inline]/7
10116      // If an inline function or variable that is attached to a named module
10117      // is declared in a definition domain, it shall be defined in that
10118      // domain.
10119      // So, if the current declaration does not have a definition, we must
10120      // check at the end of the TU (or when the PMF starts) to see that we
10121      // have a definition at that point.
10122      if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10123          NewFD->isInNamedModule()) {
10124        PendingInlineFuncDecls.insert(NewFD);
10125      }
10126    }
10127  
10128    // Filter out previous declarations that don't match the scope.
10129    FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
10130                         D.getCXXScopeSpec().isNotEmpty() ||
10131                         isMemberSpecialization ||
10132                         isFunctionTemplateSpecialization);
10133  
10134    // Handle GNU asm-label extension (encoded as an attribute).
10135    if (Expr *E = (Expr*) D.getAsmLabel()) {
10136      // The parser guarantees this is a string.
10137      StringLiteral *SE = cast<StringLiteral>(E);
10138      NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
10139                                          /*IsLiteralLabel=*/true,
10140                                          SE->getStrTokenLoc(0)));
10141    } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10142      llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
10143        ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
10144      if (I != ExtnameUndeclaredIdentifiers.end()) {
10145        if (isDeclExternC(NewFD)) {
10146          NewFD->addAttr(I->second);
10147          ExtnameUndeclaredIdentifiers.erase(I);
10148        } else
10149          Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
10150              << /*Variable*/0 << NewFD;
10151      }
10152    }
10153  
10154    // Copy the parameter declarations from the declarator D to the function
10155    // declaration NewFD, if they are available.  First scavenge them into Params.
10156    SmallVector<ParmVarDecl*, 16> Params;
10157    unsigned FTIIdx;
10158    if (D.isFunctionDeclarator(FTIIdx)) {
10159      DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
10160  
10161      // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10162      // function that takes no arguments, not a function that takes a
10163      // single void argument.
10164      // We let through "const void" here because Sema::GetTypeForDeclarator
10165      // already checks for that case.
10166      if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10167        for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10168          ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
10169          assert(Param->getDeclContext() != NewFD && "Was set before ?");
10170          Param->setDeclContext(NewFD);
10171          Params.push_back(Param);
10172  
10173          if (Param->isInvalidDecl())
10174            NewFD->setInvalidDecl();
10175        }
10176      }
10177  
10178      if (!getLangOpts().CPlusPlus) {
10179        // In C, find all the tag declarations from the prototype and move them
10180        // into the function DeclContext. Remove them from the surrounding tag
10181        // injection context of the function, which is typically but not always
10182        // the TU.
10183        DeclContext *PrototypeTagContext =
10184            getTagInjectionContext(NewFD->getLexicalDeclContext());
10185        for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10186          auto *TD = dyn_cast<TagDecl>(NonParmDecl);
10187  
10188          // We don't want to reparent enumerators. Look at their parent enum
10189          // instead.
10190          if (!TD) {
10191            if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
10192              TD = cast<EnumDecl>(ECD->getDeclContext());
10193          }
10194          if (!TD)
10195            continue;
10196          DeclContext *TagDC = TD->getLexicalDeclContext();
10197          if (!TagDC->containsDecl(TD))
10198            continue;
10199          TagDC->removeDecl(TD);
10200          TD->setDeclContext(NewFD);
10201          NewFD->addDecl(TD);
10202  
10203          // Preserve the lexical DeclContext if it is not the surrounding tag
10204          // injection context of the FD. In this example, the semantic context of
10205          // E will be f and the lexical context will be S, while both the
10206          // semantic and lexical contexts of S will be f:
10207          //   void f(struct S { enum E { a } f; } s);
10208          if (TagDC != PrototypeTagContext)
10209            TD->setLexicalDeclContext(TagDC);
10210        }
10211      }
10212    } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10213      // When we're declaring a function with a typedef, typeof, etc as in the
10214      // following example, we'll need to synthesize (unnamed)
10215      // parameters for use in the declaration.
10216      //
10217      // @code
10218      // typedef void fn(int);
10219      // fn f;
10220      // @endcode
10221  
10222      // Synthesize a parameter for each argument type.
10223      for (const auto &AI : FT->param_types()) {
10224        ParmVarDecl *Param =
10225            BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
10226        Param->setScopeInfo(0, Params.size());
10227        Params.push_back(Param);
10228      }
10229    } else {
10230      assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10231             "Should not need args for typedef of non-prototype fn");
10232    }
10233  
10234    // Finally, we know we have the right number of parameters, install them.
10235    NewFD->setParams(Params);
10236  
10237    if (D.getDeclSpec().isNoreturnSpecified())
10238      NewFD->addAttr(
10239          C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc()));
10240  
10241    // Functions returning a variably modified type violate C99 6.7.5.2p2
10242    // because all functions have linkage.
10243    if (!NewFD->isInvalidDecl() &&
10244        NewFD->getReturnType()->isVariablyModifiedType()) {
10245      Diag(NewFD->getLocation(), diag::err_vm_func_decl);
10246      NewFD->setInvalidDecl();
10247    }
10248  
10249    // Apply an implicit SectionAttr if '#pragma clang section text' is active
10250    if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
10251        !NewFD->hasAttr<SectionAttr>())
10252      NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10253          Context, PragmaClangTextSection.SectionName,
10254          PragmaClangTextSection.PragmaLocation));
10255  
10256    // Apply an implicit SectionAttr if #pragma code_seg is active.
10257    if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10258        !NewFD->hasAttr<SectionAttr>()) {
10259      NewFD->addAttr(SectionAttr::CreateImplicit(
10260          Context, CodeSegStack.CurrentValue->getString(),
10261          CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate));
10262      if (UnifySection(CodeSegStack.CurrentValue->getString(),
10263                       ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
10264                           ASTContext::PSF_Read,
10265                       NewFD))
10266        NewFD->dropAttr<SectionAttr>();
10267    }
10268  
10269    // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10270    // active.
10271    if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10272        !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10273      NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10274          Context, PragmaClangTextSection.PragmaLocation));
10275  
10276    // Apply an implicit CodeSegAttr from class declspec or
10277    // apply an implicit SectionAttr from #pragma code_seg if active.
10278    if (!NewFD->hasAttr<CodeSegAttr>()) {
10279      if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
10280                                                                   D.isFunctionDefinition())) {
10281        NewFD->addAttr(SAttr);
10282      }
10283    }
10284  
10285    // Handle attributes.
10286    ProcessDeclAttributes(S, NewFD, D);
10287    const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10288    if (NewTVA && !NewTVA->isDefaultVersion() &&
10289        !Context.getTargetInfo().hasFeature("fmv")) {
10290      // Don't add to scope fmv functions declarations if fmv disabled
10291      AddToScope = false;
10292      return NewFD;
10293    }
10294  
10295    if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10296      // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10297      // type.
10298      //
10299      // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10300      // type declaration will generate a compilation error.
10301      LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10302      if (AddressSpace != LangAS::Default) {
10303        Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10304        NewFD->setInvalidDecl();
10305      }
10306    }
10307  
10308    if (!getLangOpts().CPlusPlus) {
10309      // Perform semantic checking on the function declaration.
10310      if (!NewFD->isInvalidDecl() && NewFD->isMain())
10311        CheckMain(NewFD, D.getDeclSpec());
10312  
10313      if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10314        CheckMSVCRTEntryPoint(NewFD);
10315  
10316      if (!NewFD->isInvalidDecl())
10317        D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10318                                                    isMemberSpecialization,
10319                                                    D.isFunctionDefinition()));
10320      else if (!Previous.empty())
10321        // Recover gracefully from an invalid redeclaration.
10322        D.setRedeclaration(true);
10323      assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10324              Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10325             "previous declaration set still overloaded");
10326  
10327      // Diagnose no-prototype function declarations with calling conventions that
10328      // don't support variadic calls. Only do this in C and do it after merging
10329      // possibly prototyped redeclarations.
10330      const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10331      if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
10332        CallingConv CC = FT->getExtInfo().getCC();
10333        if (!supportsVariadicCall(CC)) {
10334          // Windows system headers sometimes accidentally use stdcall without
10335          // (void) parameters, so we relax this to a warning.
10336          int DiagID =
10337              CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10338          Diag(NewFD->getLocation(), DiagID)
10339              << FunctionType::getNameForCallConv(CC);
10340        }
10341      }
10342  
10343     if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
10344         NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
10345       checkNonTrivialCUnion(NewFD->getReturnType(),
10346                             NewFD->getReturnTypeSourceRange().getBegin(),
10347                             NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
10348    } else {
10349      // C++11 [replacement.functions]p3:
10350      //  The program's definitions shall not be specified as inline.
10351      //
10352      // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10353      //
10354      // Suppress the diagnostic if the function is __attribute__((used)), since
10355      // that forces an external definition to be emitted.
10356      if (D.getDeclSpec().isInlineSpecified() &&
10357          NewFD->isReplaceableGlobalAllocationFunction() &&
10358          !NewFD->hasAttr<UsedAttr>())
10359        Diag(D.getDeclSpec().getInlineSpecLoc(),
10360             diag::ext_operator_new_delete_declared_inline)
10361          << NewFD->getDeclName();
10362  
10363      if (Expr *TRC = NewFD->getTrailingRequiresClause()) {
10364        // C++20 [dcl.decl.general]p4:
10365        //   The optional requires-clause in an init-declarator or
10366        //   member-declarator shall be present only if the declarator declares a
10367        //   templated function.
10368        //
10369        // C++20 [temp.pre]p8:
10370        //   An entity is templated if it is
10371        //     - a template,
10372        //     - an entity defined or created in a templated entity,
10373        //     - a member of a templated entity,
10374        //     - an enumerator for an enumeration that is a templated entity, or
10375        //     - the closure type of a lambda-expression appearing in the
10376        //       declaration of a templated entity.
10377        //
10378        //   [Note 6: A local class, a local or block variable, or a friend
10379        //   function defined in a templated entity is a templated entity.
10380        //   — end note]
10381        //
10382        //   A templated function is a function template or a function that is
10383        //   templated. A templated class is a class template or a class that is
10384        //   templated. A templated variable is a variable template or a variable
10385        //   that is templated.
10386        if (!FunctionTemplate) {
10387          if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10388            // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):
10389            //   An explicit specialization shall not have a trailing
10390            //   requires-clause unless it declares a function template.
10391            //
10392            // Since a friend function template specialization cannot be
10393            // definition, and since a non-template friend declaration with a
10394            // trailing requires-clause must be a definition, we diagnose
10395            // friend function template specializations with trailing
10396            // requires-clauses on the same path as explicit specializations
10397            // even though they aren't necessarily prohibited by the same
10398            // language rule.
10399            Diag(TRC->getBeginLoc(), diag::err_non_temp_spec_requires_clause)
10400                << isFriend;
10401          } else if (isFriend && NewFD->isTemplated() &&
10402                     !D.isFunctionDefinition()) {
10403            // C++ [temp.friend]p9:
10404            //   A non-template friend declaration with a requires-clause shall be
10405            //   a definition.
10406            Diag(NewFD->getBeginLoc(),
10407                 diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
10408            NewFD->setInvalidDecl();
10409          } else if (!NewFD->isTemplated() ||
10410                     !(isa<CXXMethodDecl>(NewFD) || D.isFunctionDefinition())) {
10411            Diag(TRC->getBeginLoc(),
10412                 diag::err_constrained_non_templated_function);
10413          }
10414        }
10415      }
10416  
10417      // We do not add HD attributes to specializations here because
10418      // they may have different constexpr-ness compared to their
10419      // templates and, after maybeAddHostDeviceAttrs() is applied,
10420      // may end up with different effective targets. Instead, a
10421      // specialization inherits its target attributes from its template
10422      // in the CheckFunctionTemplateSpecialization() call below.
10423      if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10424        CUDA().maybeAddHostDeviceAttrs(NewFD, Previous);
10425  
10426      // Handle explicit specializations of function templates
10427      // and friend function declarations with an explicit
10428      // template argument list.
10429      if (isFunctionTemplateSpecialization) {
10430        bool isDependentSpecialization = false;
10431        if (isFriend) {
10432          // For friend function specializations, this is a dependent
10433          // specialization if its semantic context is dependent, its
10434          // type is dependent, or if its template-id is dependent.
10435          isDependentSpecialization =
10436              DC->isDependentContext() || NewFD->getType()->isDependentType() ||
10437              (HasExplicitTemplateArgs &&
10438               TemplateSpecializationType::
10439                   anyInstantiationDependentTemplateArguments(
10440                       TemplateArgs.arguments()));
10441          assert((!isDependentSpecialization ||
10442                  (HasExplicitTemplateArgs == isDependentSpecialization)) &&
10443                 "dependent friend function specialization without template "
10444                 "args");
10445        } else {
10446          // For class-scope explicit specializations of function templates,
10447          // if the lexical context is dependent, then the specialization
10448          // is dependent.
10449          isDependentSpecialization =
10450              CurContext->isRecord() && CurContext->isDependentContext();
10451        }
10452  
10453        TemplateArgumentListInfo *ExplicitTemplateArgs =
10454            HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
10455        if (isDependentSpecialization) {
10456          // If it's a dependent specialization, it may not be possible
10457          // to determine the primary template (for explicit specializations)
10458          // or befriended declaration (for friends) until the enclosing
10459          // template is instantiated. In such cases, we store the declarations
10460          // found by name lookup and defer resolution until instantiation.
10461          if (CheckDependentFunctionTemplateSpecialization(
10462                  NewFD, ExplicitTemplateArgs, Previous))
10463            NewFD->setInvalidDecl();
10464        } else if (!NewFD->isInvalidDecl()) {
10465          if (CheckFunctionTemplateSpecialization(NewFD, ExplicitTemplateArgs,
10466                                                  Previous))
10467            NewFD->setInvalidDecl();
10468        }
10469      } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
10470        if (CheckMemberSpecialization(NewFD, Previous))
10471            NewFD->setInvalidDecl();
10472      }
10473  
10474      // Perform semantic checking on the function declaration.
10475      if (!NewFD->isInvalidDecl() && NewFD->isMain())
10476        CheckMain(NewFD, D.getDeclSpec());
10477  
10478      if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10479        CheckMSVCRTEntryPoint(NewFD);
10480  
10481      if (!NewFD->isInvalidDecl())
10482        D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10483                                                    isMemberSpecialization,
10484                                                    D.isFunctionDefinition()));
10485      else if (!Previous.empty())
10486        // Recover gracefully from an invalid redeclaration.
10487        D.setRedeclaration(true);
10488  
10489      assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10490              !D.isRedeclaration() ||
10491              Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10492             "previous declaration set still overloaded");
10493  
10494      NamedDecl *PrincipalDecl = (FunctionTemplate
10495                                  ? cast<NamedDecl>(FunctionTemplate)
10496                                  : NewFD);
10497  
10498      if (isFriend && NewFD->getPreviousDecl()) {
10499        AccessSpecifier Access = AS_public;
10500        if (!NewFD->isInvalidDecl())
10501          Access = NewFD->getPreviousDecl()->getAccess();
10502  
10503        NewFD->setAccess(Access);
10504        if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10505      }
10506  
10507      if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10508          PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
10509        PrincipalDecl->setNonMemberOperator();
10510  
10511      // If we have a function template, check the template parameter
10512      // list. This will check and merge default template arguments.
10513      if (FunctionTemplate) {
10514        FunctionTemplateDecl *PrevTemplate =
10515                                       FunctionTemplate->getPreviousDecl();
10516        CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10517                         PrevTemplate ? PrevTemplate->getTemplateParameters()
10518                                      : nullptr,
10519                              D.getDeclSpec().isFriendSpecified()
10520                                ? (D.isFunctionDefinition()
10521                                     ? TPC_FriendFunctionTemplateDefinition
10522                                     : TPC_FriendFunctionTemplate)
10523                                : (D.getCXXScopeSpec().isSet() &&
10524                                   DC && DC->isRecord() &&
10525                                   DC->isDependentContext())
10526                                    ? TPC_ClassTemplateMember
10527                                    : TPC_FunctionTemplate);
10528      }
10529  
10530      if (NewFD->isInvalidDecl()) {
10531        // Ignore all the rest of this.
10532      } else if (!D.isRedeclaration()) {
10533        struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10534                                         AddToScope };
10535        // Fake up an access specifier if it's supposed to be a class member.
10536        if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10537          NewFD->setAccess(AS_public);
10538  
10539        // Qualified decls generally require a previous declaration.
10540        if (D.getCXXScopeSpec().isSet()) {
10541          // ...with the major exception of templated-scope or
10542          // dependent-scope friend declarations.
10543  
10544          // TODO: we currently also suppress this check in dependent
10545          // contexts because (1) the parameter depth will be off when
10546          // matching friend templates and (2) we might actually be
10547          // selecting a friend based on a dependent factor.  But there
10548          // are situations where these conditions don't apply and we
10549          // can actually do this check immediately.
10550          //
10551          // Unless the scope is dependent, it's always an error if qualified
10552          // redeclaration lookup found nothing at all. Diagnose that now;
10553          // nothing will diagnose that error later.
10554          if (isFriend &&
10555              (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
10556               (!Previous.empty() && CurContext->isDependentContext()))) {
10557            // ignore these
10558          } else if (NewFD->isCPUDispatchMultiVersion() ||
10559                     NewFD->isCPUSpecificMultiVersion()) {
10560            // ignore this, we allow the redeclaration behavior here to create new
10561            // versions of the function.
10562          } else {
10563            // The user tried to provide an out-of-line definition for a
10564            // function that is a member of a class or namespace, but there
10565            // was no such member function declared (C++ [class.mfct]p2,
10566            // C++ [namespace.memdef]p2). For example:
10567            //
10568            // class X {
10569            //   void f() const;
10570            // };
10571            //
10572            // void X::f() { } // ill-formed
10573            //
10574            // Complain about this problem, and attempt to suggest close
10575            // matches (e.g., those that differ only in cv-qualifiers and
10576            // whether the parameter types are references).
10577  
10578            if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10579                    *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10580              AddToScope = ExtraArgs.AddToScope;
10581              return Result;
10582            }
10583          }
10584  
10585          // Unqualified local friend declarations are required to resolve
10586          // to something.
10587        } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10588          if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10589                  *this, Previous, NewFD, ExtraArgs, true, S)) {
10590            AddToScope = ExtraArgs.AddToScope;
10591            return Result;
10592          }
10593        }
10594      } else if (!D.isFunctionDefinition() &&
10595                 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10596                 !isFriend && !isFunctionTemplateSpecialization &&
10597                 !isMemberSpecialization) {
10598        // An out-of-line member function declaration must also be a
10599        // definition (C++ [class.mfct]p2).
10600        // Note that this is not the case for explicit specializations of
10601        // function templates or member functions of class templates, per
10602        // C++ [temp.expl.spec]p2. We also allow these declarations as an
10603        // extension for compatibility with old SWIG code which likes to
10604        // generate them.
10605        Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10606          << D.getCXXScopeSpec().getRange();
10607      }
10608    }
10609  
10610    if (getLangOpts().HLSL && D.isFunctionDefinition()) {
10611      // Any top level function could potentially be specified as an entry.
10612      if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
10613        HLSL().ActOnTopLevelFunction(NewFD);
10614  
10615      if (NewFD->hasAttr<HLSLShaderAttr>())
10616        HLSL().CheckEntryPoint(NewFD);
10617    }
10618  
10619    // If this is the first declaration of a library builtin function, add
10620    // attributes as appropriate.
10621    if (!D.isRedeclaration()) {
10622      if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10623        if (unsigned BuiltinID = II->getBuiltinID()) {
10624          bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
10625          if (!InStdNamespace &&
10626              NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
10627            if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10628              // Validate the type matches unless this builtin is specified as
10629              // matching regardless of its declared type.
10630              if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10631                NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10632              } else {
10633                ASTContext::GetBuiltinTypeError Error;
10634                LookupNecessaryTypesForBuiltin(S, BuiltinID);
10635                QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10636  
10637                if (!Error && !BuiltinType.isNull() &&
10638                    Context.hasSameFunctionTypeIgnoringExceptionSpec(
10639                        NewFD->getType(), BuiltinType))
10640                  NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10641              }
10642            }
10643          } else if (InStdNamespace && NewFD->isInStdNamespace() &&
10644                     isStdBuiltin(Context, NewFD, BuiltinID)) {
10645            NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10646          }
10647        }
10648      }
10649    }
10650  
10651    ProcessPragmaWeak(S, NewFD);
10652    checkAttributesAfterMerging(*this, *NewFD);
10653  
10654    AddKnownFunctionAttributes(NewFD);
10655  
10656    if (NewFD->hasAttr<OverloadableAttr>() &&
10657        !NewFD->getType()->getAs<FunctionProtoType>()) {
10658      Diag(NewFD->getLocation(),
10659           diag::err_attribute_overloadable_no_prototype)
10660        << NewFD;
10661      NewFD->dropAttr<OverloadableAttr>();
10662    }
10663  
10664    // If there's a #pragma GCC visibility in scope, and this isn't a class
10665    // member, set the visibility of this function.
10666    if (!DC->isRecord() && NewFD->isExternallyVisible())
10667      AddPushedVisibilityAttribute(NewFD);
10668  
10669    // If there's a #pragma clang arc_cf_code_audited in scope, consider
10670    // marking the function.
10671    ObjC().AddCFAuditedAttribute(NewFD);
10672  
10673    // If this is a function definition, check if we have to apply any
10674    // attributes (i.e. optnone and no_builtin) due to a pragma.
10675    if (D.isFunctionDefinition()) {
10676      AddRangeBasedOptnone(NewFD);
10677      AddImplicitMSFunctionNoBuiltinAttr(NewFD);
10678      AddSectionMSAllocText(NewFD);
10679      ModifyFnAttributesMSPragmaOptimize(NewFD);
10680    }
10681  
10682    // If this is the first declaration of an extern C variable, update
10683    // the map of such variables.
10684    if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10685        isIncompleteDeclExternC(*this, NewFD))
10686      RegisterLocallyScopedExternCDecl(NewFD, S);
10687  
10688    // Set this FunctionDecl's range up to the right paren.
10689    NewFD->setRangeEnd(D.getSourceRange().getEnd());
10690  
10691    if (D.isRedeclaration() && !Previous.empty()) {
10692      NamedDecl *Prev = Previous.getRepresentativeDecl();
10693      checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10694                                     isMemberSpecialization ||
10695                                         isFunctionTemplateSpecialization,
10696                                     D.isFunctionDefinition());
10697    }
10698  
10699    if (getLangOpts().CUDA) {
10700      IdentifierInfo *II = NewFD->getIdentifier();
10701      if (II && II->isStr(CUDA().getConfigureFuncName()) &&
10702          !NewFD->isInvalidDecl() &&
10703          NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
10704        if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
10705          Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10706              << CUDA().getConfigureFuncName();
10707        Context.setcudaConfigureCallDecl(NewFD);
10708      }
10709  
10710      // Variadic functions, other than a *declaration* of printf, are not allowed
10711      // in device-side CUDA code, unless someone passed
10712      // -fcuda-allow-variadic-functions.
10713      if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10714          (NewFD->hasAttr<CUDADeviceAttr>() ||
10715           NewFD->hasAttr<CUDAGlobalAttr>()) &&
10716          !(II && II->isStr("printf") && NewFD->isExternC() &&
10717            !D.isFunctionDefinition())) {
10718        Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10719      }
10720    }
10721  
10722    MarkUnusedFileScopedDecl(NewFD);
10723  
10724  
10725  
10726    if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
10727      // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10728      if (SC == SC_Static) {
10729        Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10730        D.setInvalidType();
10731      }
10732  
10733      // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10734      if (!NewFD->getReturnType()->isVoidType()) {
10735        SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10736        Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10737            << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10738                                  : FixItHint());
10739        D.setInvalidType();
10740      }
10741  
10742      llvm::SmallPtrSet<const Type *, 16> ValidTypes;
10743      for (auto *Param : NewFD->parameters())
10744        checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
10745  
10746      if (getLangOpts().OpenCLCPlusPlus) {
10747        if (DC->isRecord()) {
10748          Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10749          D.setInvalidType();
10750        }
10751        if (FunctionTemplate) {
10752          Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10753          D.setInvalidType();
10754        }
10755      }
10756    }
10757  
10758    if (getLangOpts().CPlusPlus) {
10759      // Precalculate whether this is a friend function template with a constraint
10760      // that depends on an enclosing template, per [temp.friend]p9.
10761      if (isFriend && FunctionTemplate &&
10762          FriendConstraintsDependOnEnclosingTemplate(NewFD)) {
10763        NewFD->setFriendConstraintRefersToEnclosingTemplate(true);
10764  
10765        // C++ [temp.friend]p9:
10766        //    A friend function template with a constraint that depends on a
10767        //    template parameter from an enclosing template shall be a definition.
10768        if (!D.isFunctionDefinition()) {
10769          Diag(NewFD->getBeginLoc(),
10770               diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
10771          NewFD->setInvalidDecl();
10772        }
10773      }
10774  
10775      if (FunctionTemplate) {
10776        if (NewFD->isInvalidDecl())
10777          FunctionTemplate->setInvalidDecl();
10778        return FunctionTemplate;
10779      }
10780  
10781      if (isMemberSpecialization && !NewFD->isInvalidDecl())
10782        CompleteMemberSpecialization(NewFD, Previous);
10783    }
10784  
10785    for (const ParmVarDecl *Param : NewFD->parameters()) {
10786      QualType PT = Param->getType();
10787  
10788      // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10789      // types.
10790      if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10791        if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10792          QualType ElemTy = PipeTy->getElementType();
10793            if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10794              Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10795              D.setInvalidType();
10796            }
10797        }
10798      }
10799      // WebAssembly tables can't be used as function parameters.
10800      if (Context.getTargetInfo().getTriple().isWasm()) {
10801        if (PT->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) {
10802          Diag(Param->getTypeSpecStartLoc(),
10803               diag::err_wasm_table_as_function_parameter);
10804          D.setInvalidType();
10805        }
10806      }
10807    }
10808  
10809    // Diagnose availability attributes. Availability cannot be used on functions
10810    // that are run during load/unload.
10811    if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10812      if (NewFD->hasAttr<ConstructorAttr>()) {
10813        Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10814            << 1;
10815        NewFD->dropAttr<AvailabilityAttr>();
10816      }
10817      if (NewFD->hasAttr<DestructorAttr>()) {
10818        Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10819            << 2;
10820        NewFD->dropAttr<AvailabilityAttr>();
10821      }
10822    }
10823  
10824    // Diagnose no_builtin attribute on function declaration that are not a
10825    // definition.
10826    // FIXME: We should really be doing this in
10827    // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10828    // the FunctionDecl and at this point of the code
10829    // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10830    // because Sema::ActOnStartOfFunctionDef has not been called yet.
10831    if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10832      switch (D.getFunctionDefinitionKind()) {
10833      case FunctionDefinitionKind::Defaulted:
10834      case FunctionDefinitionKind::Deleted:
10835        Diag(NBA->getLocation(),
10836             diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10837            << NBA->getSpelling();
10838        break;
10839      case FunctionDefinitionKind::Declaration:
10840        Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10841            << NBA->getSpelling();
10842        break;
10843      case FunctionDefinitionKind::Definition:
10844        break;
10845      }
10846  
10847    // Similar to no_builtin logic above, at this point of the code
10848    // FunctionDecl::isThisDeclarationADefinition() always returns `false`
10849    // because Sema::ActOnStartOfFunctionDef has not been called yet.
10850    if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
10851        !NewFD->isInvalidDecl() &&
10852        D.getFunctionDefinitionKind() == FunctionDefinitionKind::Declaration)
10853      ExternalDeclarations.push_back(NewFD);
10854  
10855    return NewFD;
10856  }
10857  
10858  /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
10859  /// when __declspec(code_seg) "is applied to a class, all member functions of
10860  /// the class and nested classes -- this includes compiler-generated special
10861  /// member functions -- are put in the specified segment."
10862  /// The actual behavior is a little more complicated. The Microsoft compiler
10863  /// won't check outer classes if there is an active value from #pragma code_seg.
10864  /// The CodeSeg is always applied from the direct parent but only from outer
10865  /// classes when the #pragma code_seg stack is empty. See:
10866  /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10867  /// available since MS has removed the page.
getImplicitCodeSegAttrFromClass(Sema & S,const FunctionDecl * FD)10868  static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
10869    const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10870    if (!Method)
10871      return nullptr;
10872    const CXXRecordDecl *Parent = Method->getParent();
10873    if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10874      Attr *NewAttr = SAttr->clone(S.getASTContext());
10875      NewAttr->setImplicit(true);
10876      return NewAttr;
10877    }
10878  
10879    // The Microsoft compiler won't check outer classes for the CodeSeg
10880    // when the #pragma code_seg stack is active.
10881    if (S.CodeSegStack.CurrentValue)
10882     return nullptr;
10883  
10884    while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10885      if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10886        Attr *NewAttr = SAttr->clone(S.getASTContext());
10887        NewAttr->setImplicit(true);
10888        return NewAttr;
10889      }
10890    }
10891    return nullptr;
10892  }
10893  
getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl * FD,bool IsDefinition)10894  Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
10895                                                         bool IsDefinition) {
10896    if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10897      return A;
10898    if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10899        CodeSegStack.CurrentValue)
10900      return SectionAttr::CreateImplicit(
10901          getASTContext(), CodeSegStack.CurrentValue->getString(),
10902          CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate);
10903    return nullptr;
10904  }
10905  
canFullyTypeCheckRedeclaration(ValueDecl * NewD,ValueDecl * OldD,QualType NewT,QualType OldT)10906  bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10907                                            QualType NewT, QualType OldT) {
10908    if (!NewD->getLexicalDeclContext()->isDependentContext())
10909      return true;
10910  
10911    // For dependently-typed local extern declarations and friends, we can't
10912    // perform a correct type check in general until instantiation:
10913    //
10914    //   int f();
10915    //   template<typename T> void g() { T f(); }
10916    //
10917    // (valid if g() is only instantiated with T = int).
10918    if (NewT->isDependentType() &&
10919        (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10920      return false;
10921  
10922    // Similarly, if the previous declaration was a dependent local extern
10923    // declaration, we don't really know its type yet.
10924    if (OldT->isDependentType() && OldD->isLocalExternDecl())
10925      return false;
10926  
10927    return true;
10928  }
10929  
shouldLinkDependentDeclWithPrevious(Decl * D,Decl * PrevDecl)10930  bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10931    if (!D->getLexicalDeclContext()->isDependentContext())
10932      return true;
10933  
10934    // Don't chain dependent friend function definitions until instantiation, to
10935    // permit cases like
10936    //
10937    //   void func();
10938    //   template<typename T> class C1 { friend void func() {} };
10939    //   template<typename T> class C2 { friend void func() {} };
10940    //
10941    // ... which is valid if only one of C1 and C2 is ever instantiated.
10942    //
10943    // FIXME: This need only apply to function definitions. For now, we proxy
10944    // this by checking for a file-scope function. We do not want this to apply
10945    // to friend declarations nominating member functions, because that gets in
10946    // the way of access checks.
10947    if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10948      return false;
10949  
10950    auto *VD = dyn_cast<ValueDecl>(D);
10951    auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10952    return !VD || !PrevVD ||
10953           canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10954                                          PrevVD->getType());
10955  }
10956  
10957  /// Check the target or target_version attribute of the function for
10958  /// MultiVersion validity.
10959  ///
10960  /// Returns true if there was an error, false otherwise.
CheckMultiVersionValue(Sema & S,const FunctionDecl * FD)10961  static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10962    const auto *TA = FD->getAttr<TargetAttr>();
10963    const auto *TVA = FD->getAttr<TargetVersionAttr>();
10964    assert(
10965        (TA || TVA) &&
10966        "MultiVersion candidate requires a target or target_version attribute");
10967    const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10968    enum ErrType { Feature = 0, Architecture = 1 };
10969  
10970    if (TA) {
10971      ParsedTargetAttr ParseInfo =
10972          S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr());
10973      if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) {
10974        S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10975            << Architecture << ParseInfo.CPU;
10976        return true;
10977      }
10978      for (const auto &Feat : ParseInfo.Features) {
10979        auto BareFeat = StringRef{Feat}.substr(1);
10980        if (Feat[0] == '-') {
10981          S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10982              << Feature << ("no-" + BareFeat).str();
10983          return true;
10984        }
10985  
10986        if (!TargetInfo.validateCpuSupports(BareFeat) ||
10987            !TargetInfo.isValidFeatureName(BareFeat)) {
10988          S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10989              << Feature << BareFeat;
10990          return true;
10991        }
10992      }
10993    }
10994  
10995    if (TVA) {
10996      llvm::SmallVector<StringRef, 8> Feats;
10997      TVA->getFeatures(Feats);
10998      for (const auto &Feat : Feats) {
10999        if (!TargetInfo.validateCpuSupports(Feat)) {
11000          S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11001              << Feature << Feat;
11002          return true;
11003        }
11004      }
11005    }
11006    return false;
11007  }
11008  
11009  // Provide a white-list of attributes that are allowed to be combined with
11010  // multiversion functions.
AttrCompatibleWithMultiVersion(attr::Kind Kind,MultiVersionKind MVKind)11011  static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
11012                                             MultiVersionKind MVKind) {
11013    // Note: this list/diagnosis must match the list in
11014    // checkMultiversionAttributesAllSame.
11015    switch (Kind) {
11016    default:
11017      return false;
11018    case attr::ArmLocallyStreaming:
11019      return MVKind == MultiVersionKind::TargetVersion ||
11020             MVKind == MultiVersionKind::TargetClones;
11021    case attr::Used:
11022      return MVKind == MultiVersionKind::Target;
11023    case attr::NonNull:
11024    case attr::NoThrow:
11025      return true;
11026    }
11027  }
11028  
checkNonMultiVersionCompatAttributes(Sema & S,const FunctionDecl * FD,const FunctionDecl * CausedFD,MultiVersionKind MVKind)11029  static bool checkNonMultiVersionCompatAttributes(Sema &S,
11030                                                   const FunctionDecl *FD,
11031                                                   const FunctionDecl *CausedFD,
11032                                                   MultiVersionKind MVKind) {
11033    const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11034      S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
11035          << static_cast<unsigned>(MVKind) << A;
11036      if (CausedFD)
11037        S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
11038      return true;
11039    };
11040  
11041    for (const Attr *A : FD->attrs()) {
11042      switch (A->getKind()) {
11043      case attr::CPUDispatch:
11044      case attr::CPUSpecific:
11045        if (MVKind != MultiVersionKind::CPUDispatch &&
11046            MVKind != MultiVersionKind::CPUSpecific)
11047          return Diagnose(S, A);
11048        break;
11049      case attr::Target:
11050        if (MVKind != MultiVersionKind::Target)
11051          return Diagnose(S, A);
11052        break;
11053      case attr::TargetVersion:
11054        if (MVKind != MultiVersionKind::TargetVersion &&
11055            MVKind != MultiVersionKind::TargetClones)
11056          return Diagnose(S, A);
11057        break;
11058      case attr::TargetClones:
11059        if (MVKind != MultiVersionKind::TargetClones &&
11060            MVKind != MultiVersionKind::TargetVersion)
11061          return Diagnose(S, A);
11062        break;
11063      default:
11064        if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
11065          return Diagnose(S, A);
11066        break;
11067      }
11068    }
11069    return false;
11070  }
11071  
areMultiversionVariantFunctionsCompatible(const FunctionDecl * OldFD,const FunctionDecl * NewFD,const PartialDiagnostic & NoProtoDiagID,const PartialDiagnosticAt & NoteCausedDiagIDAt,const PartialDiagnosticAt & NoSupportDiagIDAt,const PartialDiagnosticAt & DiffDiagIDAt,bool TemplatesSupported,bool ConstexprSupported,bool CLinkageMayDiffer)11072  bool Sema::areMultiversionVariantFunctionsCompatible(
11073      const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11074      const PartialDiagnostic &NoProtoDiagID,
11075      const PartialDiagnosticAt &NoteCausedDiagIDAt,
11076      const PartialDiagnosticAt &NoSupportDiagIDAt,
11077      const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11078      bool ConstexprSupported, bool CLinkageMayDiffer) {
11079    enum DoesntSupport {
11080      FuncTemplates = 0,
11081      VirtFuncs = 1,
11082      DeducedReturn = 2,
11083      Constructors = 3,
11084      Destructors = 4,
11085      DeletedFuncs = 5,
11086      DefaultedFuncs = 6,
11087      ConstexprFuncs = 7,
11088      ConstevalFuncs = 8,
11089      Lambda = 9,
11090    };
11091    enum Different {
11092      CallingConv = 0,
11093      ReturnType = 1,
11094      ConstexprSpec = 2,
11095      InlineSpec = 3,
11096      Linkage = 4,
11097      LanguageLinkage = 5,
11098    };
11099  
11100    if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11101        !OldFD->getType()->getAs<FunctionProtoType>()) {
11102      Diag(OldFD->getLocation(), NoProtoDiagID);
11103      Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
11104      return true;
11105    }
11106  
11107    if (NoProtoDiagID.getDiagID() != 0 &&
11108        !NewFD->getType()->getAs<FunctionProtoType>())
11109      return Diag(NewFD->getLocation(), NoProtoDiagID);
11110  
11111    if (!TemplatesSupported &&
11112        NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11113      return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11114             << FuncTemplates;
11115  
11116    if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
11117      if (NewCXXFD->isVirtual())
11118        return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11119               << VirtFuncs;
11120  
11121      if (isa<CXXConstructorDecl>(NewCXXFD))
11122        return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11123               << Constructors;
11124  
11125      if (isa<CXXDestructorDecl>(NewCXXFD))
11126        return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11127               << Destructors;
11128    }
11129  
11130    if (NewFD->isDeleted())
11131      return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11132             << DeletedFuncs;
11133  
11134    if (NewFD->isDefaulted())
11135      return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11136             << DefaultedFuncs;
11137  
11138    if (!ConstexprSupported && NewFD->isConstexpr())
11139      return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11140             << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11141  
11142    QualType NewQType = Context.getCanonicalType(NewFD->getType());
11143    const auto *NewType = cast<FunctionType>(NewQType);
11144    QualType NewReturnType = NewType->getReturnType();
11145  
11146    if (NewReturnType->isUndeducedType())
11147      return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11148             << DeducedReturn;
11149  
11150    // Ensure the return type is identical.
11151    if (OldFD) {
11152      QualType OldQType = Context.getCanonicalType(OldFD->getType());
11153      const auto *OldType = cast<FunctionType>(OldQType);
11154      FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11155      FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11156  
11157      const auto *OldFPT = OldFD->getType()->getAs<FunctionProtoType>();
11158      const auto *NewFPT = NewFD->getType()->getAs<FunctionProtoType>();
11159  
11160      bool ArmStreamingCCMismatched = false;
11161      if (OldFPT && NewFPT) {
11162        unsigned Diff =
11163            OldFPT->getAArch64SMEAttributes() ^ NewFPT->getAArch64SMEAttributes();
11164        // Arm-streaming, arm-streaming-compatible and non-streaming versions
11165        // cannot be mixed.
11166        if (Diff & (FunctionType::SME_PStateSMEnabledMask |
11167                    FunctionType::SME_PStateSMCompatibleMask))
11168          ArmStreamingCCMismatched = true;
11169      }
11170  
11171      if (OldTypeInfo.getCC() != NewTypeInfo.getCC() || ArmStreamingCCMismatched)
11172        return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
11173  
11174      QualType OldReturnType = OldType->getReturnType();
11175  
11176      if (OldReturnType != NewReturnType)
11177        return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
11178  
11179      if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11180        return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
11181  
11182      if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11183        return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
11184  
11185      if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11186        return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
11187  
11188      if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11189        return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
11190  
11191      if (CheckEquivalentExceptionSpec(OldFPT, OldFD->getLocation(), NewFPT,
11192                                       NewFD->getLocation()))
11193        return true;
11194    }
11195    return false;
11196  }
11197  
CheckMultiVersionAdditionalRules(Sema & S,const FunctionDecl * OldFD,const FunctionDecl * NewFD,bool CausesMV,MultiVersionKind MVKind)11198  static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
11199                                               const FunctionDecl *NewFD,
11200                                               bool CausesMV,
11201                                               MultiVersionKind MVKind) {
11202    if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
11203      S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
11204      if (OldFD)
11205        S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11206      return true;
11207    }
11208  
11209    bool IsCPUSpecificCPUDispatchMVKind =
11210        MVKind == MultiVersionKind::CPUDispatch ||
11211        MVKind == MultiVersionKind::CPUSpecific;
11212  
11213    if (CausesMV && OldFD &&
11214        checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
11215      return true;
11216  
11217    if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
11218      return true;
11219  
11220    // Only allow transition to MultiVersion if it hasn't been used.
11221    if (OldFD && CausesMV && OldFD->isUsed(false))
11222      return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11223  
11224    return S.areMultiversionVariantFunctionsCompatible(
11225        OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
11226        PartialDiagnosticAt(NewFD->getLocation(),
11227                            S.PDiag(diag::note_multiversioning_caused_here)),
11228        PartialDiagnosticAt(NewFD->getLocation(),
11229                            S.PDiag(diag::err_multiversion_doesnt_support)
11230                                << static_cast<unsigned>(MVKind)),
11231        PartialDiagnosticAt(NewFD->getLocation(),
11232                            S.PDiag(diag::err_multiversion_diff)),
11233        /*TemplatesSupported=*/false,
11234        /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11235        /*CLinkageMayDiffer=*/false);
11236  }
11237  
11238  /// Check the validity of a multiversion function declaration that is the
11239  /// first of its kind. Also sets the multiversion'ness' of the function itself.
11240  ///
11241  /// This sets NewFD->isInvalidDecl() to true if there was an error.
11242  ///
11243  /// Returns true if there was an error, false otherwise.
CheckMultiVersionFirstFunction(Sema & S,FunctionDecl * FD)11244  static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD) {
11245    MultiVersionKind MVKind = FD->getMultiVersionKind();
11246    assert(MVKind != MultiVersionKind::None &&
11247           "Function lacks multiversion attribute");
11248    const auto *TA = FD->getAttr<TargetAttr>();
11249    const auto *TVA = FD->getAttr<TargetVersionAttr>();
11250    // The target attribute only causes MV if this declaration is the default,
11251    // otherwise it is treated as a normal function.
11252    if (TA && !TA->isDefaultVersion())
11253      return false;
11254    // The target_version attribute only causes Multiversioning if this
11255    // declaration is NOT the default version.
11256    if (TVA && TVA->isDefaultVersion())
11257      return false;
11258  
11259    if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11260      FD->setInvalidDecl();
11261      return true;
11262    }
11263  
11264    if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
11265      FD->setInvalidDecl();
11266      return true;
11267    }
11268  
11269    FD->setIsMultiVersion();
11270    return false;
11271  }
11272  
PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl * FD)11273  static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
11274    for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11275      if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
11276        return true;
11277    }
11278  
11279    return false;
11280  }
11281  
patchDefaultTargetVersion(FunctionDecl * From,FunctionDecl * To)11282  static void patchDefaultTargetVersion(FunctionDecl *From, FunctionDecl *To) {
11283    if (!From->getASTContext().getTargetInfo().getTriple().isAArch64())
11284      return;
11285  
11286    MultiVersionKind MVKindFrom = From->getMultiVersionKind();
11287    MultiVersionKind MVKindTo = To->getMultiVersionKind();
11288  
11289    if (MVKindTo == MultiVersionKind::None &&
11290        (MVKindFrom == MultiVersionKind::TargetVersion ||
11291         MVKindFrom == MultiVersionKind::TargetClones))
11292      To->addAttr(TargetVersionAttr::CreateImplicit(
11293          To->getASTContext(), "default", To->getSourceRange()));
11294  }
11295  
CheckDeclarationCausesMultiVersioning(Sema & S,FunctionDecl * OldFD,FunctionDecl * NewFD,bool & Redeclaration,NamedDecl * & OldDecl,LookupResult & Previous)11296  static bool CheckDeclarationCausesMultiVersioning(Sema &S, FunctionDecl *OldFD,
11297                                                    FunctionDecl *NewFD,
11298                                                    bool &Redeclaration,
11299                                                    NamedDecl *&OldDecl,
11300                                                    LookupResult &Previous) {
11301    assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11302  
11303    // The definitions should be allowed in any order. If we have discovered
11304    // a new target version and the preceeding was the default, then add the
11305    // corresponding attribute to it.
11306    patchDefaultTargetVersion(NewFD, OldFD);
11307  
11308    const auto *NewTA = NewFD->getAttr<TargetAttr>();
11309    const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11310    const auto *OldTA = OldFD->getAttr<TargetAttr>();
11311  
11312    // If the old decl is NOT MultiVersioned yet, and we don't cause that
11313    // to change, this is a simple redeclaration.
11314    if (NewTA && !NewTA->isDefaultVersion() &&
11315        (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
11316      return false;
11317  
11318    // The target_version attribute only causes Multiversioning if this
11319    // declaration is NOT the default version.
11320    if (NewTVA && NewTVA->isDefaultVersion())
11321      return false;
11322  
11323    // Otherwise, this decl causes MultiVersioning.
11324    if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
11325                                         NewTVA ? MultiVersionKind::TargetVersion
11326                                                : MultiVersionKind::Target)) {
11327      NewFD->setInvalidDecl();
11328      return true;
11329    }
11330  
11331    if (CheckMultiVersionValue(S, NewFD)) {
11332      NewFD->setInvalidDecl();
11333      return true;
11334    }
11335  
11336    // If this is 'default', permit the forward declaration.
11337    if (NewTA && NewTA->isDefaultVersion() && !OldTA) {
11338      Redeclaration = true;
11339      OldDecl = OldFD;
11340      OldFD->setIsMultiVersion();
11341      NewFD->setIsMultiVersion();
11342      return false;
11343    }
11344  
11345    if (CheckMultiVersionValue(S, OldFD)) {
11346      S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11347      NewFD->setInvalidDecl();
11348      return true;
11349    }
11350  
11351    if (NewTA) {
11352      ParsedTargetAttr OldParsed =
11353          S.getASTContext().getTargetInfo().parseTargetAttr(
11354              OldTA->getFeaturesStr());
11355      llvm::sort(OldParsed.Features);
11356      ParsedTargetAttr NewParsed =
11357          S.getASTContext().getTargetInfo().parseTargetAttr(
11358              NewTA->getFeaturesStr());
11359      // Sort order doesn't matter, it just needs to be consistent.
11360      llvm::sort(NewParsed.Features);
11361      if (OldParsed == NewParsed) {
11362        S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11363        S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11364        NewFD->setInvalidDecl();
11365        return true;
11366      }
11367    }
11368  
11369    for (const auto *FD : OldFD->redecls()) {
11370      const auto *CurTA = FD->getAttr<TargetAttr>();
11371      const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11372      // We allow forward declarations before ANY multiversioning attributes, but
11373      // nothing after the fact.
11374      if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
11375          ((NewTA && (!CurTA || CurTA->isInherited())) ||
11376           (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11377        S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
11378            << (NewTA ? 0 : 2);
11379        S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11380        NewFD->setInvalidDecl();
11381        return true;
11382      }
11383    }
11384  
11385    OldFD->setIsMultiVersion();
11386    NewFD->setIsMultiVersion();
11387    Redeclaration = false;
11388    OldDecl = nullptr;
11389    Previous.clear();
11390    return false;
11391  }
11392  
MultiVersionTypesCompatible(FunctionDecl * Old,FunctionDecl * New)11393  static bool MultiVersionTypesCompatible(FunctionDecl *Old, FunctionDecl *New) {
11394    MultiVersionKind OldKind = Old->getMultiVersionKind();
11395    MultiVersionKind NewKind = New->getMultiVersionKind();
11396  
11397    if (OldKind == NewKind || OldKind == MultiVersionKind::None ||
11398        NewKind == MultiVersionKind::None)
11399      return true;
11400  
11401    if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {
11402      switch (OldKind) {
11403      case MultiVersionKind::TargetVersion:
11404        return NewKind == MultiVersionKind::TargetClones;
11405      case MultiVersionKind::TargetClones:
11406        return NewKind == MultiVersionKind::TargetVersion;
11407      default:
11408        return false;
11409      }
11410    } else {
11411      switch (OldKind) {
11412      case MultiVersionKind::CPUDispatch:
11413        return NewKind == MultiVersionKind::CPUSpecific;
11414      case MultiVersionKind::CPUSpecific:
11415        return NewKind == MultiVersionKind::CPUDispatch;
11416      default:
11417        return false;
11418      }
11419    }
11420  }
11421  
11422  /// Check the validity of a new function declaration being added to an existing
11423  /// multiversioned declaration collection.
CheckMultiVersionAdditionalDecl(Sema & S,FunctionDecl * OldFD,FunctionDecl * NewFD,const CPUDispatchAttr * NewCPUDisp,const CPUSpecificAttr * NewCPUSpec,const TargetClonesAttr * NewClones,bool & Redeclaration,NamedDecl * & OldDecl,LookupResult & Previous)11424  static bool CheckMultiVersionAdditionalDecl(
11425      Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11426      const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
11427      const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
11428      LookupResult &Previous) {
11429  
11430    // Disallow mixing of multiversioning types.
11431    if (!MultiVersionTypesCompatible(OldFD, NewFD)) {
11432      S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
11433      S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11434      NewFD->setInvalidDecl();
11435      return true;
11436    }
11437  
11438    // Add the default target_version attribute if it's missing.
11439    patchDefaultTargetVersion(OldFD, NewFD);
11440    patchDefaultTargetVersion(NewFD, OldFD);
11441  
11442    const auto *NewTA = NewFD->getAttr<TargetAttr>();
11443    const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11444    MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();
11445    [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11446  
11447    ParsedTargetAttr NewParsed;
11448    if (NewTA) {
11449      NewParsed = S.getASTContext().getTargetInfo().parseTargetAttr(
11450          NewTA->getFeaturesStr());
11451      llvm::sort(NewParsed.Features);
11452    }
11453    llvm::SmallVector<StringRef, 8> NewFeats;
11454    if (NewTVA) {
11455      NewTVA->getFeatures(NewFeats);
11456      llvm::sort(NewFeats);
11457    }
11458  
11459    bool UseMemberUsingDeclRules =
11460        S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11461  
11462    bool MayNeedOverloadableChecks =
11463        AllowOverloadingOfFunction(Previous, S.Context, NewFD);
11464  
11465    // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11466    // of a previous member of the MultiVersion set.
11467    for (NamedDecl *ND : Previous) {
11468      FunctionDecl *CurFD = ND->getAsFunction();
11469      if (!CurFD || CurFD->isInvalidDecl())
11470        continue;
11471      if (MayNeedOverloadableChecks &&
11472          S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
11473        continue;
11474  
11475      switch (NewMVKind) {
11476      case MultiVersionKind::None:
11477        assert(OldMVKind == MultiVersionKind::TargetClones &&
11478               "Only target_clones can be omitted in subsequent declarations");
11479        break;
11480      case MultiVersionKind::Target: {
11481        const auto *CurTA = CurFD->getAttr<TargetAttr>();
11482        if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11483          NewFD->setIsMultiVersion();
11484          Redeclaration = true;
11485          OldDecl = ND;
11486          return false;
11487        }
11488  
11489        ParsedTargetAttr CurParsed =
11490            S.getASTContext().getTargetInfo().parseTargetAttr(
11491                CurTA->getFeaturesStr());
11492        llvm::sort(CurParsed.Features);
11493        if (CurParsed == NewParsed) {
11494          S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11495          S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11496          NewFD->setInvalidDecl();
11497          return true;
11498        }
11499        break;
11500      }
11501      case MultiVersionKind::TargetVersion: {
11502        if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11503          if (CurTVA->getName() == NewTVA->getName()) {
11504            NewFD->setIsMultiVersion();
11505            Redeclaration = true;
11506            OldDecl = ND;
11507            return false;
11508          }
11509          llvm::SmallVector<StringRef, 8> CurFeats;
11510          CurTVA->getFeatures(CurFeats);
11511          llvm::sort(CurFeats);
11512  
11513          if (CurFeats == NewFeats) {
11514            S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11515            S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11516            NewFD->setInvalidDecl();
11517            return true;
11518          }
11519        } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11520          // Default
11521          if (NewFeats.empty())
11522            break;
11523  
11524          for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {
11525            llvm::SmallVector<StringRef, 8> CurFeats;
11526            CurClones->getFeatures(CurFeats, I);
11527            llvm::sort(CurFeats);
11528  
11529            if (CurFeats == NewFeats) {
11530              S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11531              S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11532              NewFD->setInvalidDecl();
11533              return true;
11534            }
11535          }
11536        }
11537        break;
11538      }
11539      case MultiVersionKind::TargetClones: {
11540        assert(NewClones && "MultiVersionKind does not match attribute type");
11541        if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11542          if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11543              !std::equal(CurClones->featuresStrs_begin(),
11544                          CurClones->featuresStrs_end(),
11545                          NewClones->featuresStrs_begin())) {
11546            S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
11547            S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11548            NewFD->setInvalidDecl();
11549            return true;
11550          }
11551        } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11552          llvm::SmallVector<StringRef, 8> CurFeats;
11553          CurTVA->getFeatures(CurFeats);
11554          llvm::sort(CurFeats);
11555  
11556          // Default
11557          if (CurFeats.empty())
11558            break;
11559  
11560          for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {
11561            NewFeats.clear();
11562            NewClones->getFeatures(NewFeats, I);
11563            llvm::sort(NewFeats);
11564  
11565            if (CurFeats == NewFeats) {
11566              S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11567              S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11568              NewFD->setInvalidDecl();
11569              return true;
11570            }
11571          }
11572          break;
11573        }
11574        Redeclaration = true;
11575        OldDecl = CurFD;
11576        NewFD->setIsMultiVersion();
11577        return false;
11578      }
11579      case MultiVersionKind::CPUSpecific:
11580      case MultiVersionKind::CPUDispatch: {
11581        const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
11582        const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
11583        // Handle CPUDispatch/CPUSpecific versions.
11584        // Only 1 CPUDispatch function is allowed, this will make it go through
11585        // the redeclaration errors.
11586        if (NewMVKind == MultiVersionKind::CPUDispatch &&
11587            CurFD->hasAttr<CPUDispatchAttr>()) {
11588          if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
11589              std::equal(
11590                  CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
11591                  NewCPUDisp->cpus_begin(),
11592                  [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11593                    return Cur->getName() == New->getName();
11594                  })) {
11595            NewFD->setIsMultiVersion();
11596            Redeclaration = true;
11597            OldDecl = ND;
11598            return false;
11599          }
11600  
11601          // If the declarations don't match, this is an error condition.
11602          S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
11603          S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11604          NewFD->setInvalidDecl();
11605          return true;
11606        }
11607        if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
11608          if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
11609              std::equal(
11610                  CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
11611                  NewCPUSpec->cpus_begin(),
11612                  [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11613                    return Cur->getName() == New->getName();
11614                  })) {
11615            NewFD->setIsMultiVersion();
11616            Redeclaration = true;
11617            OldDecl = ND;
11618            return false;
11619          }
11620  
11621          // Only 1 version of CPUSpecific is allowed for each CPU.
11622          for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
11623            for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
11624              if (CurII == NewII) {
11625                S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
11626                    << NewII;
11627                S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11628                NewFD->setInvalidDecl();
11629                return true;
11630              }
11631            }
11632          }
11633        }
11634        break;
11635      }
11636      }
11637    }
11638  
11639    // Else, this is simply a non-redecl case.  Checking the 'value' is only
11640    // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11641    // handled in the attribute adding step.
11642    if ((NewMVKind == MultiVersionKind::TargetVersion ||
11643         NewMVKind == MultiVersionKind::Target) &&
11644        CheckMultiVersionValue(S, NewFD)) {
11645      NewFD->setInvalidDecl();
11646      return true;
11647    }
11648  
11649    if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
11650                                         !OldFD->isMultiVersion(), NewMVKind)) {
11651      NewFD->setInvalidDecl();
11652      return true;
11653    }
11654  
11655    // Permit forward declarations in the case where these two are compatible.
11656    if (!OldFD->isMultiVersion()) {
11657      OldFD->setIsMultiVersion();
11658      NewFD->setIsMultiVersion();
11659      Redeclaration = true;
11660      OldDecl = OldFD;
11661      return false;
11662    }
11663  
11664    NewFD->setIsMultiVersion();
11665    Redeclaration = false;
11666    OldDecl = nullptr;
11667    Previous.clear();
11668    return false;
11669  }
11670  
11671  /// Check the validity of a mulitversion function declaration.
11672  /// Also sets the multiversion'ness' of the function itself.
11673  ///
11674  /// This sets NewFD->isInvalidDecl() to true if there was an error.
11675  ///
11676  /// Returns true if there was an error, false otherwise.
CheckMultiVersionFunction(Sema & S,FunctionDecl * NewFD,bool & Redeclaration,NamedDecl * & OldDecl,LookupResult & Previous)11677  static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
11678                                        bool &Redeclaration, NamedDecl *&OldDecl,
11679                                        LookupResult &Previous) {
11680    const auto *NewTA = NewFD->getAttr<TargetAttr>();
11681    const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11682    const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
11683    const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
11684    const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
11685    MultiVersionKind MVKind = NewFD->getMultiVersionKind();
11686  
11687    // Main isn't allowed to become a multiversion function, however it IS
11688    // permitted to have 'main' be marked with the 'target' optimization hint,
11689    // for 'target_version' only default is allowed.
11690    if (NewFD->isMain()) {
11691      if (MVKind != MultiVersionKind::None &&
11692          !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
11693          !(MVKind == MultiVersionKind::TargetVersion &&
11694            NewTVA->isDefaultVersion())) {
11695        S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
11696        NewFD->setInvalidDecl();
11697        return true;
11698      }
11699      return false;
11700    }
11701  
11702    const llvm::Triple &T = S.getASTContext().getTargetInfo().getTriple();
11703  
11704    // Target attribute on AArch64 is not used for multiversioning
11705    if (NewTA && T.isAArch64())
11706      return false;
11707  
11708    // Target attribute on RISCV is not used for multiversioning
11709    if (NewTA && T.isRISCV())
11710      return false;
11711  
11712    if (!OldDecl || !OldDecl->getAsFunction() ||
11713        !OldDecl->getDeclContext()->getRedeclContext()->Equals(
11714            NewFD->getDeclContext()->getRedeclContext())) {
11715      // If there's no previous declaration, AND this isn't attempting to cause
11716      // multiversioning, this isn't an error condition.
11717      if (MVKind == MultiVersionKind::None)
11718        return false;
11719      return CheckMultiVersionFirstFunction(S, NewFD);
11720    }
11721  
11722    FunctionDecl *OldFD = OldDecl->getAsFunction();
11723  
11724    if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
11725      return false;
11726  
11727    // Multiversioned redeclarations aren't allowed to omit the attribute, except
11728    // for target_clones and target_version.
11729    if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
11730        OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones &&
11731        OldFD->getMultiVersionKind() != MultiVersionKind::TargetVersion) {
11732      S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
11733          << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
11734      NewFD->setInvalidDecl();
11735      return true;
11736    }
11737  
11738    if (!OldFD->isMultiVersion()) {
11739      switch (MVKind) {
11740      case MultiVersionKind::Target:
11741      case MultiVersionKind::TargetVersion:
11742        return CheckDeclarationCausesMultiVersioning(
11743            S, OldFD, NewFD, Redeclaration, OldDecl, Previous);
11744      case MultiVersionKind::TargetClones:
11745        if (OldFD->isUsed(false)) {
11746          NewFD->setInvalidDecl();
11747          return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11748        }
11749        OldFD->setIsMultiVersion();
11750        break;
11751  
11752      case MultiVersionKind::CPUDispatch:
11753      case MultiVersionKind::CPUSpecific:
11754      case MultiVersionKind::None:
11755        break;
11756      }
11757    }
11758  
11759    // At this point, we have a multiversion function decl (in OldFD) AND an
11760    // appropriate attribute in the current function decl.  Resolve that these are
11761    // still compatible with previous declarations.
11762    return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,
11763                                           NewCPUSpec, NewClones, Redeclaration,
11764                                           OldDecl, Previous);
11765  }
11766  
CheckConstPureAttributesUsage(Sema & S,FunctionDecl * NewFD)11767  static void CheckConstPureAttributesUsage(Sema &S, FunctionDecl *NewFD) {
11768    bool IsPure = NewFD->hasAttr<PureAttr>();
11769    bool IsConst = NewFD->hasAttr<ConstAttr>();
11770  
11771    // If there are no pure or const attributes, there's nothing to check.
11772    if (!IsPure && !IsConst)
11773      return;
11774  
11775    // If the function is marked both pure and const, we retain the const
11776    // attribute because it makes stronger guarantees than the pure attribute, and
11777    // we drop the pure attribute explicitly to prevent later confusion about
11778    // semantics.
11779    if (IsPure && IsConst) {
11780      S.Diag(NewFD->getLocation(), diag::warn_const_attr_with_pure_attr);
11781      NewFD->dropAttrs<PureAttr>();
11782    }
11783  
11784    // Constructors and destructors are functions which return void, so are
11785    // handled here as well.
11786    if (NewFD->getReturnType()->isVoidType()) {
11787      S.Diag(NewFD->getLocation(), diag::warn_pure_function_returns_void)
11788          << IsConst;
11789      NewFD->dropAttrs<PureAttr, ConstAttr>();
11790    }
11791  }
11792  
CheckFunctionDeclaration(Scope * S,FunctionDecl * NewFD,LookupResult & Previous,bool IsMemberSpecialization,bool DeclIsDefn)11793  bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
11794                                      LookupResult &Previous,
11795                                      bool IsMemberSpecialization,
11796                                      bool DeclIsDefn) {
11797    assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
11798           "Variably modified return types are not handled here");
11799  
11800    // Determine whether the type of this function should be merged with
11801    // a previous visible declaration. This never happens for functions in C++,
11802    // and always happens in C if the previous declaration was visible.
11803    bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
11804                                 !Previous.isShadowed();
11805  
11806    bool Redeclaration = false;
11807    NamedDecl *OldDecl = nullptr;
11808    bool MayNeedOverloadableChecks = false;
11809  
11810    // Merge or overload the declaration with an existing declaration of
11811    // the same name, if appropriate.
11812    if (!Previous.empty()) {
11813      // Determine whether NewFD is an overload of PrevDecl or
11814      // a declaration that requires merging. If it's an overload,
11815      // there's no more work to do here; we'll just add the new
11816      // function to the scope.
11817      if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
11818        NamedDecl *Candidate = Previous.getRepresentativeDecl();
11819        if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
11820          Redeclaration = true;
11821          OldDecl = Candidate;
11822        }
11823      } else {
11824        MayNeedOverloadableChecks = true;
11825        switch (CheckOverload(S, NewFD, Previous, OldDecl,
11826                              /*NewIsUsingDecl*/ false)) {
11827        case Ovl_Match:
11828          Redeclaration = true;
11829          break;
11830  
11831        case Ovl_NonFunction:
11832          Redeclaration = true;
11833          break;
11834  
11835        case Ovl_Overload:
11836          Redeclaration = false;
11837          break;
11838        }
11839      }
11840    }
11841  
11842    // Check for a previous extern "C" declaration with this name.
11843    if (!Redeclaration &&
11844        checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
11845      if (!Previous.empty()) {
11846        // This is an extern "C" declaration with the same name as a previous
11847        // declaration, and thus redeclares that entity...
11848        Redeclaration = true;
11849        OldDecl = Previous.getFoundDecl();
11850        MergeTypeWithPrevious = false;
11851  
11852        // ... except in the presence of __attribute__((overloadable)).
11853        if (OldDecl->hasAttr<OverloadableAttr>() ||
11854            NewFD->hasAttr<OverloadableAttr>()) {
11855          if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
11856            MayNeedOverloadableChecks = true;
11857            Redeclaration = false;
11858            OldDecl = nullptr;
11859          }
11860        }
11861      }
11862    }
11863  
11864    if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
11865      return Redeclaration;
11866  
11867    // PPC MMA non-pointer types are not allowed as function return types.
11868    if (Context.getTargetInfo().getTriple().isPPC64() &&
11869        PPC().CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
11870      NewFD->setInvalidDecl();
11871    }
11872  
11873    CheckConstPureAttributesUsage(*this, NewFD);
11874  
11875    // C++ [dcl.spec.auto.general]p12:
11876    //   Return type deduction for a templated function with a placeholder in its
11877    //   declared type occurs when the definition is instantiated even if the
11878    //   function body contains a return statement with a non-type-dependent
11879    //   operand.
11880    //
11881    // C++ [temp.dep.expr]p3:
11882    //   An id-expression is type-dependent if it is a template-id that is not a
11883    //   concept-id and is dependent; or if its terminal name is:
11884    //   - [...]
11885    //   - associated by name lookup with one or more declarations of member
11886    //     functions of a class that is the current instantiation declared with a
11887    //     return type that contains a placeholder type,
11888    //   - [...]
11889    //
11890    // If this is a templated function with a placeholder in its return type,
11891    // make the placeholder type dependent since it won't be deduced until the
11892    // definition is instantiated. We do this here because it needs to happen
11893    // for implicitly instantiated member functions/member function templates.
11894    if (getLangOpts().CPlusPlus14 &&
11895        (NewFD->isDependentContext() &&
11896         NewFD->getReturnType()->isUndeducedType())) {
11897      const FunctionProtoType *FPT =
11898          NewFD->getType()->castAs<FunctionProtoType>();
11899      QualType NewReturnType = SubstAutoTypeDependent(FPT->getReturnType());
11900      NewFD->setType(Context.getFunctionType(NewReturnType, FPT->getParamTypes(),
11901                                             FPT->getExtProtoInfo()));
11902    }
11903  
11904    // C++11 [dcl.constexpr]p8:
11905    //   A constexpr specifier for a non-static member function that is not
11906    //   a constructor declares that member function to be const.
11907    //
11908    // This needs to be delayed until we know whether this is an out-of-line
11909    // definition of a static member function.
11910    //
11911    // This rule is not present in C++1y, so we produce a backwards
11912    // compatibility warning whenever it happens in C++11.
11913    CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
11914    if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
11915        !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
11916        !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
11917      CXXMethodDecl *OldMD = nullptr;
11918      if (OldDecl)
11919        OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
11920      if (!OldMD || !OldMD->isStatic()) {
11921        const FunctionProtoType *FPT =
11922          MD->getType()->castAs<FunctionProtoType>();
11923        FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11924        EPI.TypeQuals.addConst();
11925        MD->setType(Context.getFunctionType(FPT->getReturnType(),
11926                                            FPT->getParamTypes(), EPI));
11927  
11928        // Warn that we did this, if we're not performing template instantiation.
11929        // In that case, we'll have warned already when the template was defined.
11930        if (!inTemplateInstantiation()) {
11931          SourceLocation AddConstLoc;
11932          if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
11933                  .IgnoreParens().getAs<FunctionTypeLoc>())
11934            AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
11935  
11936          Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
11937            << FixItHint::CreateInsertion(AddConstLoc, " const");
11938        }
11939      }
11940    }
11941  
11942    if (Redeclaration) {
11943      // NewFD and OldDecl represent declarations that need to be
11944      // merged.
11945      if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
11946                            DeclIsDefn)) {
11947        NewFD->setInvalidDecl();
11948        return Redeclaration;
11949      }
11950  
11951      Previous.clear();
11952      Previous.addDecl(OldDecl);
11953  
11954      if (FunctionTemplateDecl *OldTemplateDecl =
11955              dyn_cast<FunctionTemplateDecl>(OldDecl)) {
11956        auto *OldFD = OldTemplateDecl->getTemplatedDecl();
11957        FunctionTemplateDecl *NewTemplateDecl
11958          = NewFD->getDescribedFunctionTemplate();
11959        assert(NewTemplateDecl && "Template/non-template mismatch");
11960  
11961        // The call to MergeFunctionDecl above may have created some state in
11962        // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
11963        // can add it as a redeclaration.
11964        NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
11965  
11966        NewFD->setPreviousDeclaration(OldFD);
11967        if (NewFD->isCXXClassMember()) {
11968          NewFD->setAccess(OldTemplateDecl->getAccess());
11969          NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
11970        }
11971  
11972        // If this is an explicit specialization of a member that is a function
11973        // template, mark it as a member specialization.
11974        if (IsMemberSpecialization &&
11975            NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
11976          NewTemplateDecl->setMemberSpecialization();
11977          assert(OldTemplateDecl->isMemberSpecialization());
11978          // Explicit specializations of a member template do not inherit deleted
11979          // status from the parent member template that they are specializing.
11980          if (OldFD->isDeleted()) {
11981            // FIXME: This assert will not hold in the presence of modules.
11982            assert(OldFD->getCanonicalDecl() == OldFD);
11983            // FIXME: We need an update record for this AST mutation.
11984            OldFD->setDeletedAsWritten(false);
11985          }
11986        }
11987  
11988      } else {
11989        if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
11990          auto *OldFD = cast<FunctionDecl>(OldDecl);
11991          // This needs to happen first so that 'inline' propagates.
11992          NewFD->setPreviousDeclaration(OldFD);
11993          if (NewFD->isCXXClassMember())
11994            NewFD->setAccess(OldFD->getAccess());
11995        }
11996      }
11997    } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
11998               !NewFD->getAttr<OverloadableAttr>()) {
11999      assert((Previous.empty() ||
12000              llvm::any_of(Previous,
12001                           [](const NamedDecl *ND) {
12002                             return ND->hasAttr<OverloadableAttr>();
12003                           })) &&
12004             "Non-redecls shouldn't happen without overloadable present");
12005  
12006      auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
12007        const auto *FD = dyn_cast<FunctionDecl>(ND);
12008        return FD && !FD->hasAttr<OverloadableAttr>();
12009      });
12010  
12011      if (OtherUnmarkedIter != Previous.end()) {
12012        Diag(NewFD->getLocation(),
12013             diag::err_attribute_overloadable_multiple_unmarked_overloads);
12014        Diag((*OtherUnmarkedIter)->getLocation(),
12015             diag::note_attribute_overloadable_prev_overload)
12016            << false;
12017  
12018        NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
12019      }
12020    }
12021  
12022    if (LangOpts.OpenMP)
12023      OpenMP().ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
12024  
12025    // Semantic checking for this function declaration (in isolation).
12026  
12027    if (getLangOpts().CPlusPlus) {
12028      // C++-specific checks.
12029      if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
12030        CheckConstructor(Constructor);
12031      } else if (CXXDestructorDecl *Destructor =
12032                     dyn_cast<CXXDestructorDecl>(NewFD)) {
12033        // We check here for invalid destructor names.
12034        // If we have a friend destructor declaration that is dependent, we can't
12035        // diagnose right away because cases like this are still valid:
12036        // template <class T> struct A { friend T::X::~Y(); };
12037        // struct B { struct Y { ~Y(); }; using X = Y; };
12038        // template struct A<B>;
12039        if (NewFD->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None ||
12040            !Destructor->getFunctionObjectParameterType()->isDependentType()) {
12041          CXXRecordDecl *Record = Destructor->getParent();
12042          QualType ClassType = Context.getTypeDeclType(Record);
12043  
12044          DeclarationName Name = Context.DeclarationNames.getCXXDestructorName(
12045              Context.getCanonicalType(ClassType));
12046          if (NewFD->getDeclName() != Name) {
12047            Diag(NewFD->getLocation(), diag::err_destructor_name);
12048            NewFD->setInvalidDecl();
12049            return Redeclaration;
12050          }
12051        }
12052      } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
12053        if (auto *TD = Guide->getDescribedFunctionTemplate())
12054          CheckDeductionGuideTemplate(TD);
12055  
12056        // A deduction guide is not on the list of entities that can be
12057        // explicitly specialized.
12058        if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12059          Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
12060              << /*explicit specialization*/ 1;
12061      }
12062  
12063      // Find any virtual functions that this function overrides.
12064      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
12065        if (!Method->isFunctionTemplateSpecialization() &&
12066            !Method->getDescribedFunctionTemplate() &&
12067            Method->isCanonicalDecl()) {
12068          AddOverriddenMethods(Method->getParent(), Method);
12069        }
12070        if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12071          // C++2a [class.virtual]p6
12072          // A virtual method shall not have a requires-clause.
12073          Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
12074               diag::err_constrained_virtual_method);
12075  
12076        if (Method->isStatic())
12077          checkThisInStaticMemberFunctionType(Method);
12078      }
12079  
12080      if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
12081        ActOnConversionDeclarator(Conversion);
12082  
12083      // Extra checking for C++ overloaded operators (C++ [over.oper]).
12084      if (NewFD->isOverloadedOperator() &&
12085          CheckOverloadedOperatorDeclaration(NewFD)) {
12086        NewFD->setInvalidDecl();
12087        return Redeclaration;
12088      }
12089  
12090      // Extra checking for C++0x literal operators (C++0x [over.literal]).
12091      if (NewFD->getLiteralIdentifier() &&
12092          CheckLiteralOperatorDeclaration(NewFD)) {
12093        NewFD->setInvalidDecl();
12094        return Redeclaration;
12095      }
12096  
12097      // In C++, check default arguments now that we have merged decls. Unless
12098      // the lexical context is the class, because in this case this is done
12099      // during delayed parsing anyway.
12100      if (!CurContext->isRecord())
12101        CheckCXXDefaultArguments(NewFD);
12102  
12103      // If this function is declared as being extern "C", then check to see if
12104      // the function returns a UDT (class, struct, or union type) that is not C
12105      // compatible, and if it does, warn the user.
12106      // But, issue any diagnostic on the first declaration only.
12107      if (Previous.empty() && NewFD->isExternC()) {
12108        QualType R = NewFD->getReturnType();
12109        if (R->isIncompleteType() && !R->isVoidType())
12110          Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
12111              << NewFD << R;
12112        else if (!R.isPODType(Context) && !R->isVoidType() &&
12113                 !R->isObjCObjectPointerType())
12114          Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
12115      }
12116  
12117      // C++1z [dcl.fct]p6:
12118      //   [...] whether the function has a non-throwing exception-specification
12119      //   [is] part of the function type
12120      //
12121      // This results in an ABI break between C++14 and C++17 for functions whose
12122      // declared type includes an exception-specification in a parameter or
12123      // return type. (Exception specifications on the function itself are OK in
12124      // most cases, and exception specifications are not permitted in most other
12125      // contexts where they could make it into a mangling.)
12126      if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12127        auto HasNoexcept = [&](QualType T) -> bool {
12128          // Strip off declarator chunks that could be between us and a function
12129          // type. We don't need to look far, exception specifications are very
12130          // restricted prior to C++17.
12131          if (auto *RT = T->getAs<ReferenceType>())
12132            T = RT->getPointeeType();
12133          else if (T->isAnyPointerType())
12134            T = T->getPointeeType();
12135          else if (auto *MPT = T->getAs<MemberPointerType>())
12136            T = MPT->getPointeeType();
12137          if (auto *FPT = T->getAs<FunctionProtoType>())
12138            if (FPT->isNothrow())
12139              return true;
12140          return false;
12141        };
12142  
12143        auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12144        bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12145        for (QualType T : FPT->param_types())
12146          AnyNoexcept |= HasNoexcept(T);
12147        if (AnyNoexcept)
12148          Diag(NewFD->getLocation(),
12149               diag::warn_cxx17_compat_exception_spec_in_signature)
12150              << NewFD;
12151      }
12152  
12153      if (!Redeclaration && LangOpts.CUDA)
12154        CUDA().checkTargetOverload(NewFD, Previous);
12155    }
12156  
12157    // Check if the function definition uses any AArch64 SME features without
12158    // having the '+sme' feature enabled and warn user if sme locally streaming
12159    // function returns or uses arguments with VL-based types.
12160    if (DeclIsDefn) {
12161      const auto *Attr = NewFD->getAttr<ArmNewAttr>();
12162      bool UsesSM = NewFD->hasAttr<ArmLocallyStreamingAttr>();
12163      bool UsesZA = Attr && Attr->isNewZA();
12164      bool UsesZT0 = Attr && Attr->isNewZT0();
12165  
12166      if (NewFD->hasAttr<ArmLocallyStreamingAttr>()) {
12167        if (NewFD->getReturnType()->isSizelessVectorType())
12168          Diag(NewFD->getLocation(),
12169               diag::warn_sme_locally_streaming_has_vl_args_returns)
12170              << /*IsArg=*/false;
12171        if (llvm::any_of(NewFD->parameters(), [](ParmVarDecl *P) {
12172              return P->getOriginalType()->isSizelessVectorType();
12173            }))
12174          Diag(NewFD->getLocation(),
12175               diag::warn_sme_locally_streaming_has_vl_args_returns)
12176              << /*IsArg=*/true;
12177      }
12178      if (const auto *FPT = NewFD->getType()->getAs<FunctionProtoType>()) {
12179        FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12180        UsesSM |=
12181            EPI.AArch64SMEAttributes & FunctionType::SME_PStateSMEnabledMask;
12182        UsesZA |= FunctionType::getArmZAState(EPI.AArch64SMEAttributes) !=
12183                  FunctionType::ARM_None;
12184        UsesZT0 |= FunctionType::getArmZT0State(EPI.AArch64SMEAttributes) !=
12185                   FunctionType::ARM_None;
12186      }
12187  
12188      if (UsesSM || UsesZA) {
12189        llvm::StringMap<bool> FeatureMap;
12190        Context.getFunctionFeatureMap(FeatureMap, NewFD);
12191        if (!FeatureMap.contains("sme")) {
12192          if (UsesSM)
12193            Diag(NewFD->getLocation(),
12194                 diag::err_sme_definition_using_sm_in_non_sme_target);
12195          else
12196            Diag(NewFD->getLocation(),
12197                 diag::err_sme_definition_using_za_in_non_sme_target);
12198        }
12199      }
12200      if (UsesZT0) {
12201        llvm::StringMap<bool> FeatureMap;
12202        Context.getFunctionFeatureMap(FeatureMap, NewFD);
12203        if (!FeatureMap.contains("sme2")) {
12204          Diag(NewFD->getLocation(),
12205               diag::err_sme_definition_using_zt0_in_non_sme2_target);
12206        }
12207      }
12208    }
12209  
12210    return Redeclaration;
12211  }
12212  
CheckMain(FunctionDecl * FD,const DeclSpec & DS)12213  void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
12214    // C++11 [basic.start.main]p3:
12215    //   A program that [...] declares main to be inline, static or
12216    //   constexpr is ill-formed.
12217    // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
12218    //   appear in a declaration of main.
12219    // static main is not an error under C99, but we should warn about it.
12220    // We accept _Noreturn main as an extension.
12221    if (FD->getStorageClass() == SC_Static)
12222      Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
12223           ? diag::err_static_main : diag::warn_static_main)
12224        << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
12225    if (FD->isInlineSpecified())
12226      Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
12227        << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
12228    if (DS.isNoreturnSpecified()) {
12229      SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12230      SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
12231      Diag(NoreturnLoc, diag::ext_noreturn_main);
12232      Diag(NoreturnLoc, diag::note_main_remove_noreturn)
12233        << FixItHint::CreateRemoval(NoreturnRange);
12234    }
12235    if (FD->isConstexpr()) {
12236      Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
12237          << FD->isConsteval()
12238          << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
12239      FD->setConstexprKind(ConstexprSpecKind::Unspecified);
12240    }
12241  
12242    if (getLangOpts().OpenCL) {
12243      Diag(FD->getLocation(), diag::err_opencl_no_main)
12244          << FD->hasAttr<OpenCLKernelAttr>();
12245      FD->setInvalidDecl();
12246      return;
12247    }
12248  
12249    // Functions named main in hlsl are default entries, but don't have specific
12250    // signatures they are required to conform to.
12251    if (getLangOpts().HLSL)
12252      return;
12253  
12254    QualType T = FD->getType();
12255    assert(T->isFunctionType() && "function decl is not of function type");
12256    const FunctionType* FT = T->castAs<FunctionType>();
12257  
12258    // Set default calling convention for main()
12259    if (FT->getCallConv() != CC_C) {
12260      FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
12261      FD->setType(QualType(FT, 0));
12262      T = Context.getCanonicalType(FD->getType());
12263    }
12264  
12265    if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
12266      // In C with GNU extensions we allow main() to have non-integer return
12267      // type, but we should warn about the extension, and we disable the
12268      // implicit-return-zero rule.
12269  
12270      // GCC in C mode accepts qualified 'int'.
12271      if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
12272        FD->setHasImplicitReturnZero(true);
12273      else {
12274        Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
12275        SourceRange RTRange = FD->getReturnTypeSourceRange();
12276        if (RTRange.isValid())
12277          Diag(RTRange.getBegin(), diag::note_main_change_return_type)
12278              << FixItHint::CreateReplacement(RTRange, "int");
12279      }
12280    } else {
12281      // In C and C++, main magically returns 0 if you fall off the end;
12282      // set the flag which tells us that.
12283      // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12284  
12285      // All the standards say that main() should return 'int'.
12286      if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
12287        FD->setHasImplicitReturnZero(true);
12288      else {
12289        // Otherwise, this is just a flat-out error.
12290        SourceRange RTRange = FD->getReturnTypeSourceRange();
12291        Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
12292            << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
12293                                  : FixItHint());
12294        FD->setInvalidDecl(true);
12295      }
12296    }
12297  
12298    // Treat protoless main() as nullary.
12299    if (isa<FunctionNoProtoType>(FT)) return;
12300  
12301    const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
12302    unsigned nparams = FTP->getNumParams();
12303    assert(FD->getNumParams() == nparams);
12304  
12305    bool HasExtraParameters = (nparams > 3);
12306  
12307    if (FTP->isVariadic()) {
12308      Diag(FD->getLocation(), diag::ext_variadic_main);
12309      // FIXME: if we had information about the location of the ellipsis, we
12310      // could add a FixIt hint to remove it as a parameter.
12311    }
12312  
12313    // Darwin passes an undocumented fourth argument of type char**.  If
12314    // other platforms start sprouting these, the logic below will start
12315    // getting shifty.
12316    if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12317      HasExtraParameters = false;
12318  
12319    if (HasExtraParameters) {
12320      Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
12321      FD->setInvalidDecl(true);
12322      nparams = 3;
12323    }
12324  
12325    // FIXME: a lot of the following diagnostics would be improved
12326    // if we had some location information about types.
12327  
12328    QualType CharPP =
12329      Context.getPointerType(Context.getPointerType(Context.CharTy));
12330    QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12331  
12332    for (unsigned i = 0; i < nparams; ++i) {
12333      QualType AT = FTP->getParamType(i);
12334  
12335      bool mismatch = true;
12336  
12337      if (Context.hasSameUnqualifiedType(AT, Expected[i]))
12338        mismatch = false;
12339      else if (Expected[i] == CharPP) {
12340        // As an extension, the following forms are okay:
12341        //   char const **
12342        //   char const * const *
12343        //   char * const *
12344  
12345        QualifierCollector qs;
12346        const PointerType* PT;
12347        if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
12348            (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
12349            Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
12350                                Context.CharTy)) {
12351          qs.removeConst();
12352          mismatch = !qs.empty();
12353        }
12354      }
12355  
12356      if (mismatch) {
12357        Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
12358        // TODO: suggest replacing given type with expected type
12359        FD->setInvalidDecl(true);
12360      }
12361    }
12362  
12363    if (nparams == 1 && !FD->isInvalidDecl()) {
12364      Diag(FD->getLocation(), diag::warn_main_one_arg);
12365    }
12366  
12367    if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12368      Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12369      FD->setInvalidDecl();
12370    }
12371  }
12372  
isDefaultStdCall(FunctionDecl * FD,Sema & S)12373  static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12374  
12375    // Default calling convention for main and wmain is __cdecl
12376    if (FD->getName() == "main" || FD->getName() == "wmain")
12377      return false;
12378  
12379    // Default calling convention for MinGW is __cdecl
12380    const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12381    if (T.isWindowsGNUEnvironment())
12382      return false;
12383  
12384    // Default calling convention for WinMain, wWinMain and DllMain
12385    // is __stdcall on 32 bit Windows
12386    if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12387      return true;
12388  
12389    return false;
12390  }
12391  
CheckMSVCRTEntryPoint(FunctionDecl * FD)12392  void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
12393    QualType T = FD->getType();
12394    assert(T->isFunctionType() && "function decl is not of function type");
12395    const FunctionType *FT = T->castAs<FunctionType>();
12396  
12397    // Set an implicit return of 'zero' if the function can return some integral,
12398    // enumeration, pointer or nullptr type.
12399    if (FT->getReturnType()->isIntegralOrEnumerationType() ||
12400        FT->getReturnType()->isAnyPointerType() ||
12401        FT->getReturnType()->isNullPtrType())
12402      // DllMain is exempt because a return value of zero means it failed.
12403      if (FD->getName() != "DllMain")
12404        FD->setHasImplicitReturnZero(true);
12405  
12406    // Explicitly specified calling conventions are applied to MSVC entry points
12407    if (!hasExplicitCallingConv(T)) {
12408      if (isDefaultStdCall(FD, *this)) {
12409        if (FT->getCallConv() != CC_X86StdCall) {
12410          FT = Context.adjustFunctionType(
12411              FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
12412          FD->setType(QualType(FT, 0));
12413        }
12414      } else if (FT->getCallConv() != CC_C) {
12415        FT = Context.adjustFunctionType(FT,
12416                                        FT->getExtInfo().withCallingConv(CC_C));
12417        FD->setType(QualType(FT, 0));
12418      }
12419    }
12420  
12421    if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12422      Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12423      FD->setInvalidDecl();
12424    }
12425  }
12426  
CheckForConstantInitializer(Expr * Init,unsigned DiagID)12427  bool Sema::CheckForConstantInitializer(Expr *Init, unsigned DiagID) {
12428    // FIXME: Need strict checking.  In C89, we need to check for
12429    // any assignment, increment, decrement, function-calls, or
12430    // commas outside of a sizeof.  In C99, it's the same list,
12431    // except that the aforementioned are allowed in unevaluated
12432    // expressions.  Everything else falls under the
12433    // "may accept other forms of constant expressions" exception.
12434    //
12435    // Regular C++ code will not end up here (exceptions: language extensions,
12436    // OpenCL C++ etc), so the constant expression rules there don't matter.
12437    if (Init->isValueDependent()) {
12438      assert(Init->containsErrors() &&
12439             "Dependent code should only occur in error-recovery path.");
12440      return true;
12441    }
12442    const Expr *Culprit;
12443    if (Init->isConstantInitializer(Context, false, &Culprit))
12444      return false;
12445    Diag(Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();
12446    return true;
12447  }
12448  
12449  namespace {
12450    // Visits an initialization expression to see if OrigDecl is evaluated in
12451    // its own initialization and throws a warning if it does.
12452    class SelfReferenceChecker
12453        : public EvaluatedExprVisitor<SelfReferenceChecker> {
12454      Sema &S;
12455      Decl *OrigDecl;
12456      bool isRecordType;
12457      bool isPODType;
12458      bool isReferenceType;
12459  
12460      bool isInitList;
12461      llvm::SmallVector<unsigned, 4> InitFieldIndex;
12462  
12463    public:
12464      typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
12465  
SelfReferenceChecker(Sema & S,Decl * OrigDecl)12466      SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12467                                                      S(S), OrigDecl(OrigDecl) {
12468        isPODType = false;
12469        isRecordType = false;
12470        isReferenceType = false;
12471        isInitList = false;
12472        if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
12473          isPODType = VD->getType().isPODType(S.Context);
12474          isRecordType = VD->getType()->isRecordType();
12475          isReferenceType = VD->getType()->isReferenceType();
12476        }
12477      }
12478  
12479      // For most expressions, just call the visitor.  For initializer lists,
12480      // track the index of the field being initialized since fields are
12481      // initialized in order allowing use of previously initialized fields.
CheckExpr(Expr * E)12482      void CheckExpr(Expr *E) {
12483        InitListExpr *InitList = dyn_cast<InitListExpr>(E);
12484        if (!InitList) {
12485          Visit(E);
12486          return;
12487        }
12488  
12489        // Track and increment the index here.
12490        isInitList = true;
12491        InitFieldIndex.push_back(0);
12492        for (auto *Child : InitList->children()) {
12493          CheckExpr(cast<Expr>(Child));
12494          ++InitFieldIndex.back();
12495        }
12496        InitFieldIndex.pop_back();
12497      }
12498  
12499      // Returns true if MemberExpr is checked and no further checking is needed.
12500      // Returns false if additional checking is required.
CheckInitListMemberExpr(MemberExpr * E,bool CheckReference)12501      bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12502        llvm::SmallVector<FieldDecl*, 4> Fields;
12503        Expr *Base = E;
12504        bool ReferenceField = false;
12505  
12506        // Get the field members used.
12507        while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12508          FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
12509          if (!FD)
12510            return false;
12511          Fields.push_back(FD);
12512          if (FD->getType()->isReferenceType())
12513            ReferenceField = true;
12514          Base = ME->getBase()->IgnoreParenImpCasts();
12515        }
12516  
12517        // Keep checking only if the base Decl is the same.
12518        DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
12519        if (!DRE || DRE->getDecl() != OrigDecl)
12520          return false;
12521  
12522        // A reference field can be bound to an unininitialized field.
12523        if (CheckReference && !ReferenceField)
12524          return true;
12525  
12526        // Convert FieldDecls to their index number.
12527        llvm::SmallVector<unsigned, 4> UsedFieldIndex;
12528        for (const FieldDecl *I : llvm::reverse(Fields))
12529          UsedFieldIndex.push_back(I->getFieldIndex());
12530  
12531        // See if a warning is needed by checking the first difference in index
12532        // numbers.  If field being used has index less than the field being
12533        // initialized, then the use is safe.
12534        for (auto UsedIter = UsedFieldIndex.begin(),
12535                  UsedEnd = UsedFieldIndex.end(),
12536                  OrigIter = InitFieldIndex.begin(),
12537                  OrigEnd = InitFieldIndex.end();
12538             UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
12539          if (*UsedIter < *OrigIter)
12540            return true;
12541          if (*UsedIter > *OrigIter)
12542            break;
12543        }
12544  
12545        // TODO: Add a different warning which will print the field names.
12546        HandleDeclRefExpr(DRE);
12547        return true;
12548      }
12549  
12550      // For most expressions, the cast is directly above the DeclRefExpr.
12551      // For conditional operators, the cast can be outside the conditional
12552      // operator if both expressions are DeclRefExpr's.
HandleValue(Expr * E)12553      void HandleValue(Expr *E) {
12554        E = E->IgnoreParens();
12555        if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
12556          HandleDeclRefExpr(DRE);
12557          return;
12558        }
12559  
12560        if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
12561          Visit(CO->getCond());
12562          HandleValue(CO->getTrueExpr());
12563          HandleValue(CO->getFalseExpr());
12564          return;
12565        }
12566  
12567        if (BinaryConditionalOperator *BCO =
12568                dyn_cast<BinaryConditionalOperator>(E)) {
12569          Visit(BCO->getCond());
12570          HandleValue(BCO->getFalseExpr());
12571          return;
12572        }
12573  
12574        if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
12575          if (Expr *SE = OVE->getSourceExpr())
12576            HandleValue(SE);
12577          return;
12578        }
12579  
12580        if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12581          if (BO->getOpcode() == BO_Comma) {
12582            Visit(BO->getLHS());
12583            HandleValue(BO->getRHS());
12584            return;
12585          }
12586        }
12587  
12588        if (isa<MemberExpr>(E)) {
12589          if (isInitList) {
12590            if (CheckInitListMemberExpr(cast<MemberExpr>(E),
12591                                        false /*CheckReference*/))
12592              return;
12593          }
12594  
12595          Expr *Base = E->IgnoreParenImpCasts();
12596          while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12597            // Check for static member variables and don't warn on them.
12598            if (!isa<FieldDecl>(ME->getMemberDecl()))
12599              return;
12600            Base = ME->getBase()->IgnoreParenImpCasts();
12601          }
12602          if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
12603            HandleDeclRefExpr(DRE);
12604          return;
12605        }
12606  
12607        Visit(E);
12608      }
12609  
12610      // Reference types not handled in HandleValue are handled here since all
12611      // uses of references are bad, not just r-value uses.
VisitDeclRefExpr(DeclRefExpr * E)12612      void VisitDeclRefExpr(DeclRefExpr *E) {
12613        if (isReferenceType)
12614          HandleDeclRefExpr(E);
12615      }
12616  
VisitImplicitCastExpr(ImplicitCastExpr * E)12617      void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12618        if (E->getCastKind() == CK_LValueToRValue) {
12619          HandleValue(E->getSubExpr());
12620          return;
12621        }
12622  
12623        Inherited::VisitImplicitCastExpr(E);
12624      }
12625  
VisitMemberExpr(MemberExpr * E)12626      void VisitMemberExpr(MemberExpr *E) {
12627        if (isInitList) {
12628          if (CheckInitListMemberExpr(E, true /*CheckReference*/))
12629            return;
12630        }
12631  
12632        // Don't warn on arrays since they can be treated as pointers.
12633        if (E->getType()->canDecayToPointerType()) return;
12634  
12635        // Warn when a non-static method call is followed by non-static member
12636        // field accesses, which is followed by a DeclRefExpr.
12637        CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
12638        bool Warn = (MD && !MD->isStatic());
12639        Expr *Base = E->getBase()->IgnoreParenImpCasts();
12640        while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12641          if (!isa<FieldDecl>(ME->getMemberDecl()))
12642            Warn = false;
12643          Base = ME->getBase()->IgnoreParenImpCasts();
12644        }
12645  
12646        if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
12647          if (Warn)
12648            HandleDeclRefExpr(DRE);
12649          return;
12650        }
12651  
12652        // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
12653        // Visit that expression.
12654        Visit(Base);
12655      }
12656  
VisitCXXOperatorCallExpr(CXXOperatorCallExpr * E)12657      void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
12658        Expr *Callee = E->getCallee();
12659  
12660        if (isa<UnresolvedLookupExpr>(Callee))
12661          return Inherited::VisitCXXOperatorCallExpr(E);
12662  
12663        Visit(Callee);
12664        for (auto Arg: E->arguments())
12665          HandleValue(Arg->IgnoreParenImpCasts());
12666      }
12667  
VisitUnaryOperator(UnaryOperator * E)12668      void VisitUnaryOperator(UnaryOperator *E) {
12669        // For POD record types, addresses of its own members are well-defined.
12670        if (E->getOpcode() == UO_AddrOf && isRecordType &&
12671            isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
12672          if (!isPODType)
12673            HandleValue(E->getSubExpr());
12674          return;
12675        }
12676  
12677        if (E->isIncrementDecrementOp()) {
12678          HandleValue(E->getSubExpr());
12679          return;
12680        }
12681  
12682        Inherited::VisitUnaryOperator(E);
12683      }
12684  
VisitObjCMessageExpr(ObjCMessageExpr * E)12685      void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
12686  
VisitCXXConstructExpr(CXXConstructExpr * E)12687      void VisitCXXConstructExpr(CXXConstructExpr *E) {
12688        if (E->getConstructor()->isCopyConstructor()) {
12689          Expr *ArgExpr = E->getArg(0);
12690          if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
12691            if (ILE->getNumInits() == 1)
12692              ArgExpr = ILE->getInit(0);
12693          if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
12694            if (ICE->getCastKind() == CK_NoOp)
12695              ArgExpr = ICE->getSubExpr();
12696          HandleValue(ArgExpr);
12697          return;
12698        }
12699        Inherited::VisitCXXConstructExpr(E);
12700      }
12701  
VisitCallExpr(CallExpr * E)12702      void VisitCallExpr(CallExpr *E) {
12703        // Treat std::move as a use.
12704        if (E->isCallToStdMove()) {
12705          HandleValue(E->getArg(0));
12706          return;
12707        }
12708  
12709        Inherited::VisitCallExpr(E);
12710      }
12711  
VisitBinaryOperator(BinaryOperator * E)12712      void VisitBinaryOperator(BinaryOperator *E) {
12713        if (E->isCompoundAssignmentOp()) {
12714          HandleValue(E->getLHS());
12715          Visit(E->getRHS());
12716          return;
12717        }
12718  
12719        Inherited::VisitBinaryOperator(E);
12720      }
12721  
12722      // A custom visitor for BinaryConditionalOperator is needed because the
12723      // regular visitor would check the condition and true expression separately
12724      // but both point to the same place giving duplicate diagnostics.
VisitBinaryConditionalOperator(BinaryConditionalOperator * E)12725      void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
12726        Visit(E->getCond());
12727        Visit(E->getFalseExpr());
12728      }
12729  
HandleDeclRefExpr(DeclRefExpr * DRE)12730      void HandleDeclRefExpr(DeclRefExpr *DRE) {
12731        Decl* ReferenceDecl = DRE->getDecl();
12732        if (OrigDecl != ReferenceDecl) return;
12733        unsigned diag;
12734        if (isReferenceType) {
12735          diag = diag::warn_uninit_self_reference_in_reference_init;
12736        } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
12737          diag = diag::warn_static_self_reference_in_init;
12738        } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
12739                   isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
12740                   DRE->getDecl()->getType()->isRecordType()) {
12741          diag = diag::warn_uninit_self_reference_in_init;
12742        } else {
12743          // Local variables will be handled by the CFG analysis.
12744          return;
12745        }
12746  
12747        S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
12748                              S.PDiag(diag)
12749                                  << DRE->getDecl() << OrigDecl->getLocation()
12750                                  << DRE->getSourceRange());
12751      }
12752    };
12753  
12754    /// CheckSelfReference - Warns if OrigDecl is used in expression E.
CheckSelfReference(Sema & S,Decl * OrigDecl,Expr * E,bool DirectInit)12755    static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
12756                                   bool DirectInit) {
12757      // Parameters arguments are occassionially constructed with itself,
12758      // for instance, in recursive functions.  Skip them.
12759      if (isa<ParmVarDecl>(OrigDecl))
12760        return;
12761  
12762      E = E->IgnoreParens();
12763  
12764      // Skip checking T a = a where T is not a record or reference type.
12765      // Doing so is a way to silence uninitialized warnings.
12766      if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
12767        if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
12768          if (ICE->getCastKind() == CK_LValueToRValue)
12769            if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
12770              if (DRE->getDecl() == OrigDecl)
12771                return;
12772  
12773      SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
12774    }
12775  } // end anonymous namespace
12776  
12777  namespace {
12778    // Simple wrapper to add the name of a variable or (if no variable is
12779    // available) a DeclarationName into a diagnostic.
12780    struct VarDeclOrName {
12781      VarDecl *VDecl;
12782      DeclarationName Name;
12783  
12784      friend const Sema::SemaDiagnosticBuilder &
operator <<(const Sema::SemaDiagnosticBuilder & Diag,VarDeclOrName VN)12785      operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
12786        return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
12787      }
12788    };
12789  } // end anonymous namespace
12790  
deduceVarTypeFromInitializer(VarDecl * VDecl,DeclarationName Name,QualType Type,TypeSourceInfo * TSI,SourceRange Range,bool DirectInit,Expr * Init)12791  QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
12792                                              DeclarationName Name, QualType Type,
12793                                              TypeSourceInfo *TSI,
12794                                              SourceRange Range, bool DirectInit,
12795                                              Expr *Init) {
12796    bool IsInitCapture = !VDecl;
12797    assert((!VDecl || !VDecl->isInitCapture()) &&
12798           "init captures are expected to be deduced prior to initialization");
12799  
12800    VarDeclOrName VN{VDecl, Name};
12801  
12802    DeducedType *Deduced = Type->getContainedDeducedType();
12803    assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
12804  
12805    // Diagnose auto array declarations in C23, unless it's a supported extension.
12806    if (getLangOpts().C23 && Type->isArrayType() &&
12807        !isa_and_present<StringLiteral, InitListExpr>(Init)) {
12808        Diag(Range.getBegin(), diag::err_auto_not_allowed)
12809            << (int)Deduced->getContainedAutoType()->getKeyword()
12810            << /*in array decl*/ 23 << Range;
12811      return QualType();
12812    }
12813  
12814    // C++11 [dcl.spec.auto]p3
12815    if (!Init) {
12816      assert(VDecl && "no init for init capture deduction?");
12817  
12818      // Except for class argument deduction, and then for an initializing
12819      // declaration only, i.e. no static at class scope or extern.
12820      if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
12821          VDecl->hasExternalStorage() ||
12822          VDecl->isStaticDataMember()) {
12823        Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
12824          << VDecl->getDeclName() << Type;
12825        return QualType();
12826      }
12827    }
12828  
12829    ArrayRef<Expr*> DeduceInits;
12830    if (Init)
12831      DeduceInits = Init;
12832  
12833    auto *PL = dyn_cast_if_present<ParenListExpr>(Init);
12834    if (DirectInit && PL)
12835      DeduceInits = PL->exprs();
12836  
12837    if (isa<DeducedTemplateSpecializationType>(Deduced)) {
12838      assert(VDecl && "non-auto type for init capture deduction?");
12839      InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12840      InitializationKind Kind = InitializationKind::CreateForInit(
12841          VDecl->getLocation(), DirectInit, Init);
12842      // FIXME: Initialization should not be taking a mutable list of inits.
12843      SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
12844      return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
12845                                                         InitsCopy);
12846    }
12847  
12848    if (DirectInit) {
12849      if (auto *IL = dyn_cast<InitListExpr>(Init))
12850        DeduceInits = IL->inits();
12851    }
12852  
12853    // Deduction only works if we have exactly one source expression.
12854    if (DeduceInits.empty()) {
12855      // It isn't possible to write this directly, but it is possible to
12856      // end up in this situation with "auto x(some_pack...);"
12857      Diag(Init->getBeginLoc(), IsInitCapture
12858                                    ? diag::err_init_capture_no_expression
12859                                    : diag::err_auto_var_init_no_expression)
12860          << VN << Type << Range;
12861      return QualType();
12862    }
12863  
12864    if (DeduceInits.size() > 1) {
12865      Diag(DeduceInits[1]->getBeginLoc(),
12866           IsInitCapture ? diag::err_init_capture_multiple_expressions
12867                         : diag::err_auto_var_init_multiple_expressions)
12868          << VN << Type << Range;
12869      return QualType();
12870    }
12871  
12872    Expr *DeduceInit = DeduceInits[0];
12873    if (DirectInit && isa<InitListExpr>(DeduceInit)) {
12874      Diag(Init->getBeginLoc(), IsInitCapture
12875                                    ? diag::err_init_capture_paren_braces
12876                                    : diag::err_auto_var_init_paren_braces)
12877          << isa<InitListExpr>(Init) << VN << Type << Range;
12878      return QualType();
12879    }
12880  
12881    // Expressions default to 'id' when we're in a debugger.
12882    bool DefaultedAnyToId = false;
12883    if (getLangOpts().DebuggerCastResultToId &&
12884        Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
12885      ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12886      if (Result.isInvalid()) {
12887        return QualType();
12888      }
12889      Init = Result.get();
12890      DefaultedAnyToId = true;
12891    }
12892  
12893    // C++ [dcl.decomp]p1:
12894    //   If the assignment-expression [...] has array type A and no ref-qualifier
12895    //   is present, e has type cv A
12896    if (VDecl && isa<DecompositionDecl>(VDecl) &&
12897        Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
12898        DeduceInit->getType()->isConstantArrayType())
12899      return Context.getQualifiedType(DeduceInit->getType(),
12900                                      Type.getQualifiers());
12901  
12902    QualType DeducedType;
12903    TemplateDeductionInfo Info(DeduceInit->getExprLoc());
12904    TemplateDeductionResult Result =
12905        DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info);
12906    if (Result != TemplateDeductionResult::Success &&
12907        Result != TemplateDeductionResult::AlreadyDiagnosed) {
12908      if (!IsInitCapture)
12909        DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
12910      else if (isa<InitListExpr>(Init))
12911        Diag(Range.getBegin(),
12912             diag::err_init_capture_deduction_failure_from_init_list)
12913            << VN
12914            << (DeduceInit->getType().isNull() ? TSI->getType()
12915                                               : DeduceInit->getType())
12916            << DeduceInit->getSourceRange();
12917      else
12918        Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
12919            << VN << TSI->getType()
12920            << (DeduceInit->getType().isNull() ? TSI->getType()
12921                                               : DeduceInit->getType())
12922            << DeduceInit->getSourceRange();
12923    }
12924  
12925    // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
12926    // 'id' instead of a specific object type prevents most of our usual
12927    // checks.
12928    // We only want to warn outside of template instantiations, though:
12929    // inside a template, the 'id' could have come from a parameter.
12930    if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
12931        !DeducedType.isNull() && DeducedType->isObjCIdType()) {
12932      SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
12933      Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
12934    }
12935  
12936    return DeducedType;
12937  }
12938  
DeduceVariableDeclarationType(VarDecl * VDecl,bool DirectInit,Expr * Init)12939  bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
12940                                           Expr *Init) {
12941    assert(!Init || !Init->containsErrors());
12942    QualType DeducedType = deduceVarTypeFromInitializer(
12943        VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
12944        VDecl->getSourceRange(), DirectInit, Init);
12945    if (DeducedType.isNull()) {
12946      VDecl->setInvalidDecl();
12947      return true;
12948    }
12949  
12950    VDecl->setType(DeducedType);
12951    assert(VDecl->isLinkageValid());
12952  
12953    // In ARC, infer lifetime.
12954    if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(VDecl))
12955      VDecl->setInvalidDecl();
12956  
12957    if (getLangOpts().OpenCL)
12958      deduceOpenCLAddressSpace(VDecl);
12959  
12960    // If this is a redeclaration, check that the type we just deduced matches
12961    // the previously declared type.
12962    if (VarDecl *Old = VDecl->getPreviousDecl()) {
12963      // We never need to merge the type, because we cannot form an incomplete
12964      // array of auto, nor deduce such a type.
12965      MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
12966    }
12967  
12968    // Check the deduced type is valid for a variable declaration.
12969    CheckVariableDeclarationType(VDecl);
12970    return VDecl->isInvalidDecl();
12971  }
12972  
checkNonTrivialCUnionInInitializer(const Expr * Init,SourceLocation Loc)12973  void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
12974                                                SourceLocation Loc) {
12975    if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
12976      Init = EWC->getSubExpr();
12977  
12978    if (auto *CE = dyn_cast<ConstantExpr>(Init))
12979      Init = CE->getSubExpr();
12980  
12981    QualType InitType = Init->getType();
12982    assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12983            InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
12984           "shouldn't be called if type doesn't have a non-trivial C struct");
12985    if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
12986      for (auto *I : ILE->inits()) {
12987        if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
12988            !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
12989          continue;
12990        SourceLocation SL = I->getExprLoc();
12991        checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
12992      }
12993      return;
12994    }
12995  
12996    if (isa<ImplicitValueInitExpr>(Init)) {
12997      if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12998        checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
12999                              NTCUK_Init);
13000    } else {
13001      // Assume all other explicit initializers involving copying some existing
13002      // object.
13003      // TODO: ignore any explicit initializers where we can guarantee
13004      // copy-elision.
13005      if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
13006        checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
13007    }
13008  }
13009  
13010  namespace {
13011  
shouldIgnoreForRecordTriviality(const FieldDecl * FD)13012  bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13013    // Ignore unavailable fields. A field can be marked as unavailable explicitly
13014    // in the source code or implicitly by the compiler if it is in a union
13015    // defined in a system header and has non-trivial ObjC ownership
13016    // qualifications. We don't want those fields to participate in determining
13017    // whether the containing union is non-trivial.
13018    return FD->hasAttr<UnavailableAttr>();
13019  }
13020  
13021  struct DiagNonTrivalCUnionDefaultInitializeVisitor
13022      : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13023                                      void> {
13024    using Super =
13025        DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13026                                      void>;
13027  
DiagNonTrivalCUnionDefaultInitializeVisitor__anondd060bcd2011::DiagNonTrivalCUnionDefaultInitializeVisitor13028    DiagNonTrivalCUnionDefaultInitializeVisitor(
13029        QualType OrigTy, SourceLocation OrigLoc,
13030        Sema::NonTrivialCUnionContext UseContext, Sema &S)
13031        : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13032  
visitWithKind__anondd060bcd2011::DiagNonTrivalCUnionDefaultInitializeVisitor13033    void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13034                       const FieldDecl *FD, bool InNonTrivialUnion) {
13035      if (const auto *AT = S.Context.getAsArrayType(QT))
13036        return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13037                                       InNonTrivialUnion);
13038      return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
13039    }
13040  
visitARCStrong__anondd060bcd2011::DiagNonTrivalCUnionDefaultInitializeVisitor13041    void visitARCStrong(QualType QT, const FieldDecl *FD,
13042                        bool InNonTrivialUnion) {
13043      if (InNonTrivialUnion)
13044        S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13045            << 1 << 0 << QT << FD->getName();
13046    }
13047  
visitARCWeak__anondd060bcd2011::DiagNonTrivalCUnionDefaultInitializeVisitor13048    void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13049      if (InNonTrivialUnion)
13050        S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13051            << 1 << 0 << QT << FD->getName();
13052    }
13053  
visitStruct__anondd060bcd2011::DiagNonTrivalCUnionDefaultInitializeVisitor13054    void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13055      const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13056      if (RD->isUnion()) {
13057        if (OrigLoc.isValid()) {
13058          bool IsUnion = false;
13059          if (auto *OrigRD = OrigTy->getAsRecordDecl())
13060            IsUnion = OrigRD->isUnion();
13061          S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13062              << 0 << OrigTy << IsUnion << UseContext;
13063          // Reset OrigLoc so that this diagnostic is emitted only once.
13064          OrigLoc = SourceLocation();
13065        }
13066        InNonTrivialUnion = true;
13067      }
13068  
13069      if (InNonTrivialUnion)
13070        S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13071            << 0 << 0 << QT.getUnqualifiedType() << "";
13072  
13073      for (const FieldDecl *FD : RD->fields())
13074        if (!shouldIgnoreForRecordTriviality(FD))
13075          asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13076    }
13077  
visitTrivial__anondd060bcd2011::DiagNonTrivalCUnionDefaultInitializeVisitor13078    void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13079  
13080    // The non-trivial C union type or the struct/union type that contains a
13081    // non-trivial C union.
13082    QualType OrigTy;
13083    SourceLocation OrigLoc;
13084    Sema::NonTrivialCUnionContext UseContext;
13085    Sema &S;
13086  };
13087  
13088  struct DiagNonTrivalCUnionDestructedTypeVisitor
13089      : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13090    using Super =
13091        DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
13092  
DiagNonTrivalCUnionDestructedTypeVisitor__anondd060bcd2011::DiagNonTrivalCUnionDestructedTypeVisitor13093    DiagNonTrivalCUnionDestructedTypeVisitor(
13094        QualType OrigTy, SourceLocation OrigLoc,
13095        Sema::NonTrivialCUnionContext UseContext, Sema &S)
13096        : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13097  
visitWithKind__anondd060bcd2011::DiagNonTrivalCUnionDestructedTypeVisitor13098    void visitWithKind(QualType::DestructionKind DK, QualType QT,
13099                       const FieldDecl *FD, bool InNonTrivialUnion) {
13100      if (const auto *AT = S.Context.getAsArrayType(QT))
13101        return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13102                                       InNonTrivialUnion);
13103      return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
13104    }
13105  
visitARCStrong__anondd060bcd2011::DiagNonTrivalCUnionDestructedTypeVisitor13106    void visitARCStrong(QualType QT, const FieldDecl *FD,
13107                        bool InNonTrivialUnion) {
13108      if (InNonTrivialUnion)
13109        S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13110            << 1 << 1 << QT << FD->getName();
13111    }
13112  
visitARCWeak__anondd060bcd2011::DiagNonTrivalCUnionDestructedTypeVisitor13113    void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13114      if (InNonTrivialUnion)
13115        S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13116            << 1 << 1 << QT << FD->getName();
13117    }
13118  
visitStruct__anondd060bcd2011::DiagNonTrivalCUnionDestructedTypeVisitor13119    void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13120      const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13121      if (RD->isUnion()) {
13122        if (OrigLoc.isValid()) {
13123          bool IsUnion = false;
13124          if (auto *OrigRD = OrigTy->getAsRecordDecl())
13125            IsUnion = OrigRD->isUnion();
13126          S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13127              << 1 << OrigTy << IsUnion << UseContext;
13128          // Reset OrigLoc so that this diagnostic is emitted only once.
13129          OrigLoc = SourceLocation();
13130        }
13131        InNonTrivialUnion = true;
13132      }
13133  
13134      if (InNonTrivialUnion)
13135        S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13136            << 0 << 1 << QT.getUnqualifiedType() << "";
13137  
13138      for (const FieldDecl *FD : RD->fields())
13139        if (!shouldIgnoreForRecordTriviality(FD))
13140          asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13141    }
13142  
visitTrivial__anondd060bcd2011::DiagNonTrivalCUnionDestructedTypeVisitor13143    void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
visitCXXDestructor__anondd060bcd2011::DiagNonTrivalCUnionDestructedTypeVisitor13144    void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13145                            bool InNonTrivialUnion) {}
13146  
13147    // The non-trivial C union type or the struct/union type that contains a
13148    // non-trivial C union.
13149    QualType OrigTy;
13150    SourceLocation OrigLoc;
13151    Sema::NonTrivialCUnionContext UseContext;
13152    Sema &S;
13153  };
13154  
13155  struct DiagNonTrivalCUnionCopyVisitor
13156      : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13157    using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
13158  
DiagNonTrivalCUnionCopyVisitor__anondd060bcd2011::DiagNonTrivalCUnionCopyVisitor13159    DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13160                                   Sema::NonTrivialCUnionContext UseContext,
13161                                   Sema &S)
13162        : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13163  
visitWithKind__anondd060bcd2011::DiagNonTrivalCUnionCopyVisitor13164    void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13165                       const FieldDecl *FD, bool InNonTrivialUnion) {
13166      if (const auto *AT = S.Context.getAsArrayType(QT))
13167        return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13168                                       InNonTrivialUnion);
13169      return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
13170    }
13171  
visitARCStrong__anondd060bcd2011::DiagNonTrivalCUnionCopyVisitor13172    void visitARCStrong(QualType QT, const FieldDecl *FD,
13173                        bool InNonTrivialUnion) {
13174      if (InNonTrivialUnion)
13175        S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13176            << 1 << 2 << QT << FD->getName();
13177    }
13178  
visitARCWeak__anondd060bcd2011::DiagNonTrivalCUnionCopyVisitor13179    void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13180      if (InNonTrivialUnion)
13181        S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13182            << 1 << 2 << QT << FD->getName();
13183    }
13184  
visitStruct__anondd060bcd2011::DiagNonTrivalCUnionCopyVisitor13185    void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13186      const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13187      if (RD->isUnion()) {
13188        if (OrigLoc.isValid()) {
13189          bool IsUnion = false;
13190          if (auto *OrigRD = OrigTy->getAsRecordDecl())
13191            IsUnion = OrigRD->isUnion();
13192          S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13193              << 2 << OrigTy << IsUnion << UseContext;
13194          // Reset OrigLoc so that this diagnostic is emitted only once.
13195          OrigLoc = SourceLocation();
13196        }
13197        InNonTrivialUnion = true;
13198      }
13199  
13200      if (InNonTrivialUnion)
13201        S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13202            << 0 << 2 << QT.getUnqualifiedType() << "";
13203  
13204      for (const FieldDecl *FD : RD->fields())
13205        if (!shouldIgnoreForRecordTriviality(FD))
13206          asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13207    }
13208  
preVisit__anondd060bcd2011::DiagNonTrivalCUnionCopyVisitor13209    void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13210                  const FieldDecl *FD, bool InNonTrivialUnion) {}
visitTrivial__anondd060bcd2011::DiagNonTrivalCUnionCopyVisitor13211    void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
visitVolatileTrivial__anondd060bcd2011::DiagNonTrivalCUnionCopyVisitor13212    void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13213                              bool InNonTrivialUnion) {}
13214  
13215    // The non-trivial C union type or the struct/union type that contains a
13216    // non-trivial C union.
13217    QualType OrigTy;
13218    SourceLocation OrigLoc;
13219    Sema::NonTrivialCUnionContext UseContext;
13220    Sema &S;
13221  };
13222  
13223  } // namespace
13224  
checkNonTrivialCUnion(QualType QT,SourceLocation Loc,NonTrivialCUnionContext UseContext,unsigned NonTrivialKind)13225  void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
13226                                   NonTrivialCUnionContext UseContext,
13227                                   unsigned NonTrivialKind) {
13228    assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13229            QT.hasNonTrivialToPrimitiveDestructCUnion() ||
13230            QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
13231           "shouldn't be called if type doesn't have a non-trivial C union");
13232  
13233    if ((NonTrivialKind & NTCUK_Init) &&
13234        QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13235      DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13236          .visit(QT, nullptr, false);
13237    if ((NonTrivialKind & NTCUK_Destruct) &&
13238        QT.hasNonTrivialToPrimitiveDestructCUnion())
13239      DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13240          .visit(QT, nullptr, false);
13241    if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13242      DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13243          .visit(QT, nullptr, false);
13244  }
13245  
AddInitializerToDecl(Decl * RealDecl,Expr * Init,bool DirectInit)13246  void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
13247    // If there is no declaration, there was an error parsing it.  Just ignore
13248    // the initializer.
13249    if (!RealDecl) {
13250      CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
13251      return;
13252    }
13253  
13254    if (auto *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
13255      if (!Method->isInvalidDecl()) {
13256        // Pure-specifiers are handled in ActOnPureSpecifier.
13257        Diag(Method->getLocation(), diag::err_member_function_initialization)
13258            << Method->getDeclName() << Init->getSourceRange();
13259        Method->setInvalidDecl();
13260      }
13261      return;
13262    }
13263  
13264    VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
13265    if (!VDecl) {
13266      assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13267      Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
13268      RealDecl->setInvalidDecl();
13269      return;
13270    }
13271  
13272    if (VDecl->isInvalidDecl()) {
13273      ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
13274      SmallVector<Expr *> SubExprs;
13275      if (Res.isUsable())
13276        SubExprs.push_back(Res.get());
13277      ExprResult Recovery =
13278          CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), SubExprs);
13279      if (Expr *E = Recovery.get())
13280        VDecl->setInit(E);
13281      return;
13282    }
13283  
13284    // WebAssembly tables can't be used to initialise a variable.
13285    if (Init && !Init->getType().isNull() &&
13286        Init->getType()->isWebAssemblyTableType()) {
13287      Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0;
13288      VDecl->setInvalidDecl();
13289      return;
13290    }
13291  
13292    // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13293    if (VDecl->getType()->isUndeducedType()) {
13294      // Attempt typo correction early so that the type of the init expression can
13295      // be deduced based on the chosen correction if the original init contains a
13296      // TypoExpr.
13297      ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
13298      if (!Res.isUsable()) {
13299        // There are unresolved typos in Init, just drop them.
13300        // FIXME: improve the recovery strategy to preserve the Init.
13301        RealDecl->setInvalidDecl();
13302        return;
13303      }
13304      if (Res.get()->containsErrors()) {
13305        // Invalidate the decl as we don't know the type for recovery-expr yet.
13306        RealDecl->setInvalidDecl();
13307        VDecl->setInit(Res.get());
13308        return;
13309      }
13310      Init = Res.get();
13311  
13312      if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
13313        return;
13314    }
13315  
13316    // dllimport cannot be used on variable definitions.
13317    if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13318      Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
13319      VDecl->setInvalidDecl();
13320      return;
13321    }
13322  
13323    // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13324    // the identifier has external or internal linkage, the declaration shall
13325    // have no initializer for the identifier.
13326    // C++14 [dcl.init]p5 is the same restriction for C++.
13327    if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
13328      Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
13329      VDecl->setInvalidDecl();
13330      return;
13331    }
13332  
13333    if (!VDecl->getType()->isDependentType()) {
13334      // A definition must end up with a complete type, which means it must be
13335      // complete with the restriction that an array type might be completed by
13336      // the initializer; note that later code assumes this restriction.
13337      QualType BaseDeclType = VDecl->getType();
13338      if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
13339        BaseDeclType = Array->getElementType();
13340      if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
13341                              diag::err_typecheck_decl_incomplete_type)) {
13342        RealDecl->setInvalidDecl();
13343        return;
13344      }
13345  
13346      // The variable can not have an abstract class type.
13347      if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
13348                                 diag::err_abstract_type_in_decl,
13349                                 AbstractVariableType))
13350        VDecl->setInvalidDecl();
13351    }
13352  
13353    // C++ [module.import/6] external definitions are not permitted in header
13354    // units.
13355    if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
13356        !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
13357        VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
13358        !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(VDecl) &&
13359        !VDecl->getInstantiatedFromStaticDataMember()) {
13360      Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
13361      VDecl->setInvalidDecl();
13362    }
13363  
13364    // If adding the initializer will turn this declaration into a definition,
13365    // and we already have a definition for this variable, diagnose or otherwise
13366    // handle the situation.
13367    if (VarDecl *Def = VDecl->getDefinition())
13368      if (Def != VDecl &&
13369          (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
13370          !VDecl->isThisDeclarationADemotedDefinition() &&
13371          checkVarDeclRedefinition(Def, VDecl))
13372        return;
13373  
13374    if (getLangOpts().CPlusPlus) {
13375      // C++ [class.static.data]p4
13376      //   If a static data member is of const integral or const
13377      //   enumeration type, its declaration in the class definition can
13378      //   specify a constant-initializer which shall be an integral
13379      //   constant expression (5.19). In that case, the member can appear
13380      //   in integral constant expressions. The member shall still be
13381      //   defined in a namespace scope if it is used in the program and the
13382      //   namespace scope definition shall not contain an initializer.
13383      //
13384      // We already performed a redefinition check above, but for static
13385      // data members we also need to check whether there was an in-class
13386      // declaration with an initializer.
13387      if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
13388        Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
13389            << VDecl->getDeclName();
13390        Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
13391             diag::note_previous_initializer)
13392            << 0;
13393        return;
13394      }
13395  
13396      if (VDecl->hasLocalStorage())
13397        setFunctionHasBranchProtectedScope();
13398  
13399      if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
13400        VDecl->setInvalidDecl();
13401        return;
13402      }
13403    }
13404  
13405    // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
13406    // a kernel function cannot be initialized."
13407    if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
13408      Diag(VDecl->getLocation(), diag::err_local_cant_init);
13409      VDecl->setInvalidDecl();
13410      return;
13411    }
13412  
13413    // The LoaderUninitialized attribute acts as a definition (of undef).
13414    if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
13415      Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
13416      VDecl->setInvalidDecl();
13417      return;
13418    }
13419  
13420    // Get the decls type and save a reference for later, since
13421    // CheckInitializerTypes may change it.
13422    QualType DclT = VDecl->getType(), SavT = DclT;
13423  
13424    // Expressions default to 'id' when we're in a debugger
13425    // and we are assigning it to a variable of Objective-C pointer type.
13426    if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
13427        Init->getType() == Context.UnknownAnyTy) {
13428      ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
13429      if (Result.isInvalid()) {
13430        VDecl->setInvalidDecl();
13431        return;
13432      }
13433      Init = Result.get();
13434    }
13435  
13436    // Perform the initialization.
13437    ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
13438    bool IsParenListInit = false;
13439    if (!VDecl->isInvalidDecl()) {
13440      InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
13441      InitializationKind Kind = InitializationKind::CreateForInit(
13442          VDecl->getLocation(), DirectInit, Init);
13443  
13444      MultiExprArg Args = Init;
13445      if (CXXDirectInit)
13446        Args = MultiExprArg(CXXDirectInit->getExprs(),
13447                            CXXDirectInit->getNumExprs());
13448  
13449      // Try to correct any TypoExprs in the initialization arguments.
13450      for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
13451        ExprResult Res = CorrectDelayedTyposInExpr(
13452            Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
13453            [this, Entity, Kind](Expr *E) {
13454              InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
13455              return Init.Failed() ? ExprError() : E;
13456            });
13457        if (Res.isInvalid()) {
13458          VDecl->setInvalidDecl();
13459        } else if (Res.get() != Args[Idx]) {
13460          Args[Idx] = Res.get();
13461        }
13462      }
13463      if (VDecl->isInvalidDecl())
13464        return;
13465  
13466      InitializationSequence InitSeq(*this, Entity, Kind, Args,
13467                                     /*TopLevelOfInitList=*/false,
13468                                     /*TreatUnavailableAsInvalid=*/false);
13469      ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
13470      if (Result.isInvalid()) {
13471        // If the provided initializer fails to initialize the var decl,
13472        // we attach a recovery expr for better recovery.
13473        auto RecoveryExpr =
13474            CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
13475        if (RecoveryExpr.get())
13476          VDecl->setInit(RecoveryExpr.get());
13477        // In general, for error recovery purposes, the initializer doesn't play
13478        // part in the valid bit of the declaration. There are a few exceptions:
13479        //  1) if the var decl has a deduced auto type, and the type cannot be
13480        //     deduced by an invalid initializer;
13481        //  2) if the var decl is a decomposition decl with a non-deduced type,
13482        //      and the initialization fails (e.g. `int [a] = {1, 2};`);
13483        // Case 1) was already handled elsewhere.
13484        if (isa<DecompositionDecl>(VDecl)) // Case 2)
13485          VDecl->setInvalidDecl();
13486        return;
13487      }
13488  
13489      Init = Result.getAs<Expr>();
13490      IsParenListInit = !InitSeq.steps().empty() &&
13491                        InitSeq.step_begin()->Kind ==
13492                            InitializationSequence::SK_ParenthesizedListInit;
13493      QualType VDeclType = VDecl->getType();
13494      if (Init && !Init->getType().isNull() &&
13495          !Init->getType()->isDependentType() && !VDeclType->isDependentType() &&
13496          Context.getAsIncompleteArrayType(VDeclType) &&
13497          Context.getAsIncompleteArrayType(Init->getType())) {
13498        // Bail out if it is not possible to deduce array size from the
13499        // initializer.
13500        Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
13501            << VDeclType;
13502        VDecl->setInvalidDecl();
13503        return;
13504      }
13505    }
13506  
13507    // Check for self-references within variable initializers.
13508    // Variables declared within a function/method body (except for references)
13509    // are handled by a dataflow analysis.
13510    // This is undefined behavior in C++, but valid in C.
13511    if (getLangOpts().CPlusPlus)
13512      if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
13513          VDecl->getType()->isReferenceType())
13514        CheckSelfReference(*this, RealDecl, Init, DirectInit);
13515  
13516    // If the type changed, it means we had an incomplete type that was
13517    // completed by the initializer. For example:
13518    //   int ary[] = { 1, 3, 5 };
13519    // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
13520    if (!VDecl->isInvalidDecl() && (DclT != SavT))
13521      VDecl->setType(DclT);
13522  
13523    if (!VDecl->isInvalidDecl()) {
13524      checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
13525  
13526      if (VDecl->hasAttr<BlocksAttr>())
13527        ObjC().checkRetainCycles(VDecl, Init);
13528  
13529      // It is safe to assign a weak reference into a strong variable.
13530      // Although this code can still have problems:
13531      //   id x = self.weakProp;
13532      //   id y = self.weakProp;
13533      // we do not warn to warn spuriously when 'x' and 'y' are on separate
13534      // paths through the function. This should be revisited if
13535      // -Wrepeated-use-of-weak is made flow-sensitive.
13536      if (FunctionScopeInfo *FSI = getCurFunction())
13537        if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
13538             VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
13539            !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13540                             Init->getBeginLoc()))
13541          FSI->markSafeWeakUse(Init);
13542    }
13543  
13544    // The initialization is usually a full-expression.
13545    //
13546    // FIXME: If this is a braced initialization of an aggregate, it is not
13547    // an expression, and each individual field initializer is a separate
13548    // full-expression. For instance, in:
13549    //
13550    //   struct Temp { ~Temp(); };
13551    //   struct S { S(Temp); };
13552    //   struct T { S a, b; } t = { Temp(), Temp() }
13553    //
13554    // we should destroy the first Temp before constructing the second.
13555    ExprResult Result =
13556        ActOnFinishFullExpr(Init, VDecl->getLocation(),
13557                            /*DiscardedValue*/ false, VDecl->isConstexpr());
13558    if (Result.isInvalid()) {
13559      VDecl->setInvalidDecl();
13560      return;
13561    }
13562    Init = Result.get();
13563  
13564    // Attach the initializer to the decl.
13565    VDecl->setInit(Init);
13566  
13567    if (VDecl->isLocalVarDecl()) {
13568      // Don't check the initializer if the declaration is malformed.
13569      if (VDecl->isInvalidDecl()) {
13570        // do nothing
13571  
13572      // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
13573      // This is true even in C++ for OpenCL.
13574      } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
13575        CheckForConstantInitializer(Init);
13576  
13577        // Otherwise, C++ does not restrict the initializer.
13578      } else if (getLangOpts().CPlusPlus) {
13579        // do nothing
13580  
13581      // C99 6.7.8p4: All the expressions in an initializer for an object that has
13582      // static storage duration shall be constant expressions or string literals.
13583      } else if (VDecl->getStorageClass() == SC_Static) {
13584        CheckForConstantInitializer(Init);
13585  
13586        // C89 is stricter than C99 for aggregate initializers.
13587        // C89 6.5.7p3: All the expressions [...] in an initializer list
13588        // for an object that has aggregate or union type shall be
13589        // constant expressions.
13590      } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
13591                 isa<InitListExpr>(Init)) {
13592        CheckForConstantInitializer(Init, diag::ext_aggregate_init_not_constant);
13593      }
13594  
13595      if (auto *E = dyn_cast<ExprWithCleanups>(Init))
13596        if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
13597          if (VDecl->hasLocalStorage())
13598            BE->getBlockDecl()->setCanAvoidCopyToHeap();
13599    } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
13600               VDecl->getLexicalDeclContext()->isRecord()) {
13601      // This is an in-class initialization for a static data member, e.g.,
13602      //
13603      // struct S {
13604      //   static const int value = 17;
13605      // };
13606  
13607      // C++ [class.mem]p4:
13608      //   A member-declarator can contain a constant-initializer only
13609      //   if it declares a static member (9.4) of const integral or
13610      //   const enumeration type, see 9.4.2.
13611      //
13612      // C++11 [class.static.data]p3:
13613      //   If a non-volatile non-inline const static data member is of integral
13614      //   or enumeration type, its declaration in the class definition can
13615      //   specify a brace-or-equal-initializer in which every initializer-clause
13616      //   that is an assignment-expression is a constant expression. A static
13617      //   data member of literal type can be declared in the class definition
13618      //   with the constexpr specifier; if so, its declaration shall specify a
13619      //   brace-or-equal-initializer in which every initializer-clause that is
13620      //   an assignment-expression is a constant expression.
13621  
13622      // Do nothing on dependent types.
13623      if (DclT->isDependentType()) {
13624  
13625      // Allow any 'static constexpr' members, whether or not they are of literal
13626      // type. We separately check that every constexpr variable is of literal
13627      // type.
13628      } else if (VDecl->isConstexpr()) {
13629  
13630      // Require constness.
13631      } else if (!DclT.isConstQualified()) {
13632        Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
13633          << Init->getSourceRange();
13634        VDecl->setInvalidDecl();
13635  
13636      // We allow integer constant expressions in all cases.
13637      } else if (DclT->isIntegralOrEnumerationType()) {
13638        // Check whether the expression is a constant expression.
13639        SourceLocation Loc;
13640        if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
13641          // In C++11, a non-constexpr const static data member with an
13642          // in-class initializer cannot be volatile.
13643          Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
13644        else if (Init->isValueDependent())
13645          ; // Nothing to check.
13646        else if (Init->isIntegerConstantExpr(Context, &Loc))
13647          ; // Ok, it's an ICE!
13648        else if (Init->getType()->isScopedEnumeralType() &&
13649                 Init->isCXX11ConstantExpr(Context))
13650          ; // Ok, it is a scoped-enum constant expression.
13651        else if (Init->isEvaluatable(Context)) {
13652          // If we can constant fold the initializer through heroics, accept it,
13653          // but report this as a use of an extension for -pedantic.
13654          Diag(Loc, diag::ext_in_class_initializer_non_constant)
13655            << Init->getSourceRange();
13656        } else {
13657          // Otherwise, this is some crazy unknown case.  Report the issue at the
13658          // location provided by the isIntegerConstantExpr failed check.
13659          Diag(Loc, diag::err_in_class_initializer_non_constant)
13660            << Init->getSourceRange();
13661          VDecl->setInvalidDecl();
13662        }
13663  
13664      // We allow foldable floating-point constants as an extension.
13665      } else if (DclT->isFloatingType()) { // also permits complex, which is ok
13666        // In C++98, this is a GNU extension. In C++11, it is not, but we support
13667        // it anyway and provide a fixit to add the 'constexpr'.
13668        if (getLangOpts().CPlusPlus11) {
13669          Diag(VDecl->getLocation(),
13670               diag::ext_in_class_initializer_float_type_cxx11)
13671              << DclT << Init->getSourceRange();
13672          Diag(VDecl->getBeginLoc(),
13673               diag::note_in_class_initializer_float_type_cxx11)
13674              << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13675        } else {
13676          Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
13677            << DclT << Init->getSourceRange();
13678  
13679          if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
13680            Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
13681              << Init->getSourceRange();
13682            VDecl->setInvalidDecl();
13683          }
13684        }
13685  
13686      // Suggest adding 'constexpr' in C++11 for literal types.
13687      } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
13688        Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
13689            << DclT << Init->getSourceRange()
13690            << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13691        VDecl->setConstexpr(true);
13692  
13693      } else {
13694        Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
13695          << DclT << Init->getSourceRange();
13696        VDecl->setInvalidDecl();
13697      }
13698    } else if (VDecl->isFileVarDecl()) {
13699      // In C, extern is typically used to avoid tentative definitions when
13700      // declaring variables in headers, but adding an initializer makes it a
13701      // definition. This is somewhat confusing, so GCC and Clang both warn on it.
13702      // In C++, extern is often used to give implicitly static const variables
13703      // external linkage, so don't warn in that case. If selectany is present,
13704      // this might be header code intended for C and C++ inclusion, so apply the
13705      // C++ rules.
13706      if (VDecl->getStorageClass() == SC_Extern &&
13707          ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
13708           !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
13709          !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
13710          !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
13711        Diag(VDecl->getLocation(), diag::warn_extern_init);
13712  
13713      // In Microsoft C++ mode, a const variable defined in namespace scope has
13714      // external linkage by default if the variable is declared with
13715      // __declspec(dllexport).
13716      if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13717          getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
13718          VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
13719        VDecl->setStorageClass(SC_Extern);
13720  
13721      // C99 6.7.8p4. All file scoped initializers need to be constant.
13722      // Avoid duplicate diagnostics for constexpr variables.
13723      if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
13724          !VDecl->isConstexpr())
13725        CheckForConstantInitializer(Init);
13726    }
13727  
13728    QualType InitType = Init->getType();
13729    if (!InitType.isNull() &&
13730        (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13731         InitType.hasNonTrivialToPrimitiveCopyCUnion()))
13732      checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
13733  
13734    // We will represent direct-initialization similarly to copy-initialization:
13735    //    int x(1);  -as-> int x = 1;
13736    //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
13737    //
13738    // Clients that want to distinguish between the two forms, can check for
13739    // direct initializer using VarDecl::getInitStyle().
13740    // A major benefit is that clients that don't particularly care about which
13741    // exactly form was it (like the CodeGen) can handle both cases without
13742    // special case code.
13743  
13744    // C++ 8.5p11:
13745    // The form of initialization (using parentheses or '=') is generally
13746    // insignificant, but does matter when the entity being initialized has a
13747    // class type.
13748    if (CXXDirectInit) {
13749      assert(DirectInit && "Call-style initializer must be direct init.");
13750      VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
13751                                          : VarDecl::CallInit);
13752    } else if (DirectInit) {
13753      // This must be list-initialization. No other way is direct-initialization.
13754      VDecl->setInitStyle(VarDecl::ListInit);
13755    }
13756  
13757    if (LangOpts.OpenMP &&
13758        (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
13759        VDecl->isFileVarDecl())
13760      DeclsToCheckForDeferredDiags.insert(VDecl);
13761    CheckCompleteVariableDeclaration(VDecl);
13762  }
13763  
ActOnInitializerError(Decl * D)13764  void Sema::ActOnInitializerError(Decl *D) {
13765    // Our main concern here is re-establishing invariants like "a
13766    // variable's type is either dependent or complete".
13767    if (!D || D->isInvalidDecl()) return;
13768  
13769    VarDecl *VD = dyn_cast<VarDecl>(D);
13770    if (!VD) return;
13771  
13772    // Bindings are not usable if we can't make sense of the initializer.
13773    if (auto *DD = dyn_cast<DecompositionDecl>(D))
13774      for (auto *BD : DD->bindings())
13775        BD->setInvalidDecl();
13776  
13777    // Auto types are meaningless if we can't make sense of the initializer.
13778    if (VD->getType()->isUndeducedType()) {
13779      D->setInvalidDecl();
13780      return;
13781    }
13782  
13783    QualType Ty = VD->getType();
13784    if (Ty->isDependentType()) return;
13785  
13786    // Require a complete type.
13787    if (RequireCompleteType(VD->getLocation(),
13788                            Context.getBaseElementType(Ty),
13789                            diag::err_typecheck_decl_incomplete_type)) {
13790      VD->setInvalidDecl();
13791      return;
13792    }
13793  
13794    // Require a non-abstract type.
13795    if (RequireNonAbstractType(VD->getLocation(), Ty,
13796                               diag::err_abstract_type_in_decl,
13797                               AbstractVariableType)) {
13798      VD->setInvalidDecl();
13799      return;
13800    }
13801  
13802    // Don't bother complaining about constructors or destructors,
13803    // though.
13804  }
13805  
ActOnUninitializedDecl(Decl * RealDecl)13806  void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
13807    // If there is no declaration, there was an error parsing it. Just ignore it.
13808    if (!RealDecl)
13809      return;
13810  
13811    if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
13812      QualType Type = Var->getType();
13813  
13814      // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
13815      if (isa<DecompositionDecl>(RealDecl)) {
13816        Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
13817        Var->setInvalidDecl();
13818        return;
13819      }
13820  
13821      if (Type->isUndeducedType() &&
13822          DeduceVariableDeclarationType(Var, false, nullptr))
13823        return;
13824  
13825      // C++11 [class.static.data]p3: A static data member can be declared with
13826      // the constexpr specifier; if so, its declaration shall specify
13827      // a brace-or-equal-initializer.
13828      // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
13829      // the definition of a variable [...] or the declaration of a static data
13830      // member.
13831      if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
13832          !Var->isThisDeclarationADemotedDefinition()) {
13833        if (Var->isStaticDataMember()) {
13834          // C++1z removes the relevant rule; the in-class declaration is always
13835          // a definition there.
13836          if (!getLangOpts().CPlusPlus17 &&
13837              !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13838            Diag(Var->getLocation(),
13839                 diag::err_constexpr_static_mem_var_requires_init)
13840                << Var;
13841            Var->setInvalidDecl();
13842            return;
13843          }
13844        } else {
13845          Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
13846          Var->setInvalidDecl();
13847          return;
13848        }
13849      }
13850  
13851      // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
13852      // be initialized.
13853      if (!Var->isInvalidDecl() &&
13854          Var->getType().getAddressSpace() == LangAS::opencl_constant &&
13855          Var->getStorageClass() != SC_Extern && !Var->getInit()) {
13856        bool HasConstExprDefaultConstructor = false;
13857        if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13858          for (auto *Ctor : RD->ctors()) {
13859            if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
13860                Ctor->getMethodQualifiers().getAddressSpace() ==
13861                    LangAS::opencl_constant) {
13862              HasConstExprDefaultConstructor = true;
13863            }
13864          }
13865        }
13866        if (!HasConstExprDefaultConstructor) {
13867          Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
13868          Var->setInvalidDecl();
13869          return;
13870        }
13871      }
13872  
13873      if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
13874        if (Var->getStorageClass() == SC_Extern) {
13875          Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
13876              << Var;
13877          Var->setInvalidDecl();
13878          return;
13879        }
13880        if (RequireCompleteType(Var->getLocation(), Var->getType(),
13881                                diag::err_typecheck_decl_incomplete_type)) {
13882          Var->setInvalidDecl();
13883          return;
13884        }
13885        if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13886          if (!RD->hasTrivialDefaultConstructor()) {
13887            Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
13888            Var->setInvalidDecl();
13889            return;
13890          }
13891        }
13892        // The declaration is uninitialized, no need for further checks.
13893        return;
13894      }
13895  
13896      VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
13897      if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
13898          Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13899        checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
13900                              NTCUC_DefaultInitializedObject, NTCUK_Init);
13901  
13902  
13903      switch (DefKind) {
13904      case VarDecl::Definition:
13905        if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
13906          break;
13907  
13908        // We have an out-of-line definition of a static data member
13909        // that has an in-class initializer, so we type-check this like
13910        // a declaration.
13911        //
13912        [[fallthrough]];
13913  
13914      case VarDecl::DeclarationOnly:
13915        // It's only a declaration.
13916  
13917        // Block scope. C99 6.7p7: If an identifier for an object is
13918        // declared with no linkage (C99 6.2.2p6), the type for the
13919        // object shall be complete.
13920        if (!Type->isDependentType() && Var->isLocalVarDecl() &&
13921            !Var->hasLinkage() && !Var->isInvalidDecl() &&
13922            RequireCompleteType(Var->getLocation(), Type,
13923                                diag::err_typecheck_decl_incomplete_type))
13924          Var->setInvalidDecl();
13925  
13926        // Make sure that the type is not abstract.
13927        if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13928            RequireNonAbstractType(Var->getLocation(), Type,
13929                                   diag::err_abstract_type_in_decl,
13930                                   AbstractVariableType))
13931          Var->setInvalidDecl();
13932        if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13933            Var->getStorageClass() == SC_PrivateExtern) {
13934          Diag(Var->getLocation(), diag::warn_private_extern);
13935          Diag(Var->getLocation(), diag::note_private_extern);
13936        }
13937  
13938        if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
13939            !Var->isInvalidDecl())
13940          ExternalDeclarations.push_back(Var);
13941  
13942        return;
13943  
13944      case VarDecl::TentativeDefinition:
13945        // File scope. C99 6.9.2p2: A declaration of an identifier for an
13946        // object that has file scope without an initializer, and without a
13947        // storage-class specifier or with the storage-class specifier "static",
13948        // constitutes a tentative definition. Note: A tentative definition with
13949        // external linkage is valid (C99 6.2.2p5).
13950        if (!Var->isInvalidDecl()) {
13951          if (const IncompleteArrayType *ArrayT
13952                                      = Context.getAsIncompleteArrayType(Type)) {
13953            if (RequireCompleteSizedType(
13954                    Var->getLocation(), ArrayT->getElementType(),
13955                    diag::err_array_incomplete_or_sizeless_type))
13956              Var->setInvalidDecl();
13957          } else if (Var->getStorageClass() == SC_Static) {
13958            // C99 6.9.2p3: If the declaration of an identifier for an object is
13959            // a tentative definition and has internal linkage (C99 6.2.2p3), the
13960            // declared type shall not be an incomplete type.
13961            // NOTE: code such as the following
13962            //     static struct s;
13963            //     struct s { int a; };
13964            // is accepted by gcc. Hence here we issue a warning instead of
13965            // an error and we do not invalidate the static declaration.
13966            // NOTE: to avoid multiple warnings, only check the first declaration.
13967            if (Var->isFirstDecl())
13968              RequireCompleteType(Var->getLocation(), Type,
13969                                  diag::ext_typecheck_decl_incomplete_type);
13970          }
13971        }
13972  
13973        // Record the tentative definition; we're done.
13974        if (!Var->isInvalidDecl())
13975          TentativeDefinitions.push_back(Var);
13976        return;
13977      }
13978  
13979      // Provide a specific diagnostic for uninitialized variable
13980      // definitions with incomplete array type.
13981      if (Type->isIncompleteArrayType()) {
13982        if (Var->isConstexpr())
13983          Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
13984              << Var;
13985        else
13986          Diag(Var->getLocation(),
13987               diag::err_typecheck_incomplete_array_needs_initializer);
13988        Var->setInvalidDecl();
13989        return;
13990      }
13991  
13992      // Provide a specific diagnostic for uninitialized variable
13993      // definitions with reference type.
13994      if (Type->isReferenceType()) {
13995        Diag(Var->getLocation(), diag::err_reference_var_requires_init)
13996            << Var << SourceRange(Var->getLocation(), Var->getLocation());
13997        return;
13998      }
13999  
14000      // Do not attempt to type-check the default initializer for a
14001      // variable with dependent type.
14002      if (Type->isDependentType())
14003        return;
14004  
14005      if (Var->isInvalidDecl())
14006        return;
14007  
14008      if (!Var->hasAttr<AliasAttr>()) {
14009        if (RequireCompleteType(Var->getLocation(),
14010                                Context.getBaseElementType(Type),
14011                                diag::err_typecheck_decl_incomplete_type)) {
14012          Var->setInvalidDecl();
14013          return;
14014        }
14015      } else {
14016        return;
14017      }
14018  
14019      // The variable can not have an abstract class type.
14020      if (RequireNonAbstractType(Var->getLocation(), Type,
14021                                 diag::err_abstract_type_in_decl,
14022                                 AbstractVariableType)) {
14023        Var->setInvalidDecl();
14024        return;
14025      }
14026  
14027      // Check for jumps past the implicit initializer.  C++0x
14028      // clarifies that this applies to a "variable with automatic
14029      // storage duration", not a "local variable".
14030      // C++11 [stmt.dcl]p3
14031      //   A program that jumps from a point where a variable with automatic
14032      //   storage duration is not in scope to a point where it is in scope is
14033      //   ill-formed unless the variable has scalar type, class type with a
14034      //   trivial default constructor and a trivial destructor, a cv-qualified
14035      //   version of one of these types, or an array of one of the preceding
14036      //   types and is declared without an initializer.
14037      if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14038        if (const RecordType *Record
14039              = Context.getBaseElementType(Type)->getAs<RecordType>()) {
14040          CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
14041          // Mark the function (if we're in one) for further checking even if the
14042          // looser rules of C++11 do not require such checks, so that we can
14043          // diagnose incompatibilities with C++98.
14044          if (!CXXRecord->isPOD())
14045            setFunctionHasBranchProtectedScope();
14046        }
14047      }
14048      // In OpenCL, we can't initialize objects in the __local address space,
14049      // even implicitly, so don't synthesize an implicit initializer.
14050      if (getLangOpts().OpenCL &&
14051          Var->getType().getAddressSpace() == LangAS::opencl_local)
14052        return;
14053      // C++03 [dcl.init]p9:
14054      //   If no initializer is specified for an object, and the
14055      //   object is of (possibly cv-qualified) non-POD class type (or
14056      //   array thereof), the object shall be default-initialized; if
14057      //   the object is of const-qualified type, the underlying class
14058      //   type shall have a user-declared default
14059      //   constructor. Otherwise, if no initializer is specified for
14060      //   a non- static object, the object and its subobjects, if
14061      //   any, have an indeterminate initial value); if the object
14062      //   or any of its subobjects are of const-qualified type, the
14063      //   program is ill-formed.
14064      // C++0x [dcl.init]p11:
14065      //   If no initializer is specified for an object, the object is
14066      //   default-initialized; [...].
14067      InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
14068      InitializationKind Kind
14069        = InitializationKind::CreateDefault(Var->getLocation());
14070  
14071      InitializationSequence InitSeq(*this, Entity, Kind, std::nullopt);
14072      ExprResult Init = InitSeq.Perform(*this, Entity, Kind, std::nullopt);
14073  
14074      if (Init.get()) {
14075        Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
14076        // This is important for template substitution.
14077        Var->setInitStyle(VarDecl::CallInit);
14078      } else if (Init.isInvalid()) {
14079        // If default-init fails, attach a recovery-expr initializer to track
14080        // that initialization was attempted and failed.
14081        auto RecoveryExpr =
14082            CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
14083        if (RecoveryExpr.get())
14084          Var->setInit(RecoveryExpr.get());
14085      }
14086  
14087      CheckCompleteVariableDeclaration(Var);
14088    }
14089  }
14090  
ActOnCXXForRangeDecl(Decl * D)14091  void Sema::ActOnCXXForRangeDecl(Decl *D) {
14092    // If there is no declaration, there was an error parsing it. Ignore it.
14093    if (!D)
14094      return;
14095  
14096    VarDecl *VD = dyn_cast<VarDecl>(D);
14097    if (!VD) {
14098      Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
14099      D->setInvalidDecl();
14100      return;
14101    }
14102  
14103    VD->setCXXForRangeDecl(true);
14104  
14105    // for-range-declaration cannot be given a storage class specifier.
14106    int Error = -1;
14107    switch (VD->getStorageClass()) {
14108    case SC_None:
14109      break;
14110    case SC_Extern:
14111      Error = 0;
14112      break;
14113    case SC_Static:
14114      Error = 1;
14115      break;
14116    case SC_PrivateExtern:
14117      Error = 2;
14118      break;
14119    case SC_Auto:
14120      Error = 3;
14121      break;
14122    case SC_Register:
14123      Error = 4;
14124      break;
14125    }
14126  
14127    // for-range-declaration cannot be given a storage class specifier con't.
14128    switch (VD->getTSCSpec()) {
14129    case TSCS_thread_local:
14130      Error = 6;
14131      break;
14132    case TSCS___thread:
14133    case TSCS__Thread_local:
14134    case TSCS_unspecified:
14135      break;
14136    }
14137  
14138    if (Error != -1) {
14139      Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
14140          << VD << Error;
14141      D->setInvalidDecl();
14142    }
14143  }
14144  
ActOnCXXForRangeIdentifier(Scope * S,SourceLocation IdentLoc,IdentifierInfo * Ident,ParsedAttributes & Attrs)14145  StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
14146                                              IdentifierInfo *Ident,
14147                                              ParsedAttributes &Attrs) {
14148    // C++1y [stmt.iter]p1:
14149    //   A range-based for statement of the form
14150    //      for ( for-range-identifier : for-range-initializer ) statement
14151    //   is equivalent to
14152    //      for ( auto&& for-range-identifier : for-range-initializer ) statement
14153    DeclSpec DS(Attrs.getPool().getFactory());
14154  
14155    const char *PrevSpec;
14156    unsigned DiagID;
14157    DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
14158                       getPrintingPolicy());
14159  
14160    Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit);
14161    D.SetIdentifier(Ident, IdentLoc);
14162    D.takeAttributes(Attrs);
14163  
14164    D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
14165                  IdentLoc);
14166    Decl *Var = ActOnDeclarator(S, D);
14167    cast<VarDecl>(Var)->setCXXForRangeDecl(true);
14168    FinalizeDeclaration(Var);
14169    return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
14170                         Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
14171                                                        : IdentLoc);
14172  }
14173  
CheckCompleteVariableDeclaration(VarDecl * var)14174  void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
14175    if (var->isInvalidDecl()) return;
14176  
14177    CUDA().MaybeAddConstantAttr(var);
14178  
14179    if (getLangOpts().OpenCL) {
14180      // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14181      // initialiser
14182      if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14183          !var->hasInit()) {
14184        Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
14185            << 1 /*Init*/;
14186        var->setInvalidDecl();
14187        return;
14188      }
14189    }
14190  
14191    // In Objective-C, don't allow jumps past the implicit initialization of a
14192    // local retaining variable.
14193    if (getLangOpts().ObjC &&
14194        var->hasLocalStorage()) {
14195      switch (var->getType().getObjCLifetime()) {
14196      case Qualifiers::OCL_None:
14197      case Qualifiers::OCL_ExplicitNone:
14198      case Qualifiers::OCL_Autoreleasing:
14199        break;
14200  
14201      case Qualifiers::OCL_Weak:
14202      case Qualifiers::OCL_Strong:
14203        setFunctionHasBranchProtectedScope();
14204        break;
14205      }
14206    }
14207  
14208    if (var->hasLocalStorage() &&
14209        var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
14210      setFunctionHasBranchProtectedScope();
14211  
14212    // Warn about externally-visible variables being defined without a
14213    // prior declaration.  We only want to do this for global
14214    // declarations, but we also specifically need to avoid doing it for
14215    // class members because the linkage of an anonymous class can
14216    // change if it's later given a typedef name.
14217    if (var->isThisDeclarationADefinition() &&
14218        var->getDeclContext()->getRedeclContext()->isFileContext() &&
14219        var->isExternallyVisible() && var->hasLinkage() &&
14220        !var->isInline() && !var->getDescribedVarTemplate() &&
14221        var->getStorageClass() != SC_Register &&
14222        !isa<VarTemplatePartialSpecializationDecl>(var) &&
14223        !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
14224        !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
14225                                    var->getLocation())) {
14226      // Find a previous declaration that's not a definition.
14227      VarDecl *prev = var->getPreviousDecl();
14228      while (prev && prev->isThisDeclarationADefinition())
14229        prev = prev->getPreviousDecl();
14230  
14231      if (!prev) {
14232        Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
14233        Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14234            << /* variable */ 0;
14235      }
14236    }
14237  
14238    // Cache the result of checking for constant initialization.
14239    std::optional<bool> CacheHasConstInit;
14240    const Expr *CacheCulprit = nullptr;
14241    auto checkConstInit = [&]() mutable {
14242      if (!CacheHasConstInit)
14243        CacheHasConstInit = var->getInit()->isConstantInitializer(
14244              Context, var->getType()->isReferenceType(), &CacheCulprit);
14245      return *CacheHasConstInit;
14246    };
14247  
14248    if (var->getTLSKind() == VarDecl::TLS_Static) {
14249      if (var->getType().isDestructedType()) {
14250        // GNU C++98 edits for __thread, [basic.start.term]p3:
14251        //   The type of an object with thread storage duration shall not
14252        //   have a non-trivial destructor.
14253        Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
14254        if (getLangOpts().CPlusPlus11)
14255          Diag(var->getLocation(), diag::note_use_thread_local);
14256      } else if (getLangOpts().CPlusPlus && var->hasInit()) {
14257        if (!checkConstInit()) {
14258          // GNU C++98 edits for __thread, [basic.start.init]p4:
14259          //   An object of thread storage duration shall not require dynamic
14260          //   initialization.
14261          // FIXME: Need strict checking here.
14262          Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
14263            << CacheCulprit->getSourceRange();
14264          if (getLangOpts().CPlusPlus11)
14265            Diag(var->getLocation(), diag::note_use_thread_local);
14266        }
14267      }
14268    }
14269  
14270  
14271    if (!var->getType()->isStructureType() && var->hasInit() &&
14272        isa<InitListExpr>(var->getInit())) {
14273      const auto *ILE = cast<InitListExpr>(var->getInit());
14274      unsigned NumInits = ILE->getNumInits();
14275      if (NumInits > 2)
14276        for (unsigned I = 0; I < NumInits; ++I) {
14277          const auto *Init = ILE->getInit(I);
14278          if (!Init)
14279            break;
14280          const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14281          if (!SL)
14282            break;
14283  
14284          unsigned NumConcat = SL->getNumConcatenated();
14285          // Diagnose missing comma in string array initialization.
14286          // Do not warn when all the elements in the initializer are concatenated
14287          // together. Do not warn for macros too.
14288          if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
14289            bool OnlyOneMissingComma = true;
14290            for (unsigned J = I + 1; J < NumInits; ++J) {
14291              const auto *Init = ILE->getInit(J);
14292              if (!Init)
14293                break;
14294              const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14295              if (!SLJ || SLJ->getNumConcatenated() > 1) {
14296                OnlyOneMissingComma = false;
14297                break;
14298              }
14299            }
14300  
14301            if (OnlyOneMissingComma) {
14302              SmallVector<FixItHint, 1> Hints;
14303              for (unsigned i = 0; i < NumConcat - 1; ++i)
14304                Hints.push_back(FixItHint::CreateInsertion(
14305                    PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
14306  
14307              Diag(SL->getStrTokenLoc(1),
14308                   diag::warn_concatenated_literal_array_init)
14309                  << Hints;
14310              Diag(SL->getBeginLoc(),
14311                   diag::note_concatenated_string_literal_silence);
14312            }
14313            // In any case, stop now.
14314            break;
14315          }
14316        }
14317    }
14318  
14319  
14320    QualType type = var->getType();
14321  
14322    if (var->hasAttr<BlocksAttr>())
14323      getCurFunction()->addByrefBlockVar(var);
14324  
14325    Expr *Init = var->getInit();
14326    bool GlobalStorage = var->hasGlobalStorage();
14327    bool IsGlobal = GlobalStorage && !var->isStaticLocal();
14328    QualType baseType = Context.getBaseElementType(type);
14329    bool HasConstInit = true;
14330  
14331    if (getLangOpts().C23 && var->isConstexpr() && !Init)
14332      Diag(var->getLocation(), diag::err_constexpr_var_requires_const_init)
14333          << var;
14334  
14335    // Check whether the initializer is sufficiently constant.
14336    if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
14337        !type->isDependentType() && Init && !Init->isValueDependent() &&
14338        (GlobalStorage || var->isConstexpr() ||
14339         var->mightBeUsableInConstantExpressions(Context))) {
14340      // If this variable might have a constant initializer or might be usable in
14341      // constant expressions, check whether or not it actually is now.  We can't
14342      // do this lazily, because the result might depend on things that change
14343      // later, such as which constexpr functions happen to be defined.
14344      SmallVector<PartialDiagnosticAt, 8> Notes;
14345      if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
14346        // Prior to C++11, in contexts where a constant initializer is required,
14347        // the set of valid constant initializers is described by syntactic rules
14348        // in [expr.const]p2-6.
14349        // FIXME: Stricter checking for these rules would be useful for constinit /
14350        // -Wglobal-constructors.
14351        HasConstInit = checkConstInit();
14352  
14353        // Compute and cache the constant value, and remember that we have a
14354        // constant initializer.
14355        if (HasConstInit) {
14356          (void)var->checkForConstantInitialization(Notes);
14357          Notes.clear();
14358        } else if (CacheCulprit) {
14359          Notes.emplace_back(CacheCulprit->getExprLoc(),
14360                             PDiag(diag::note_invalid_subexpr_in_const_expr));
14361          Notes.back().second << CacheCulprit->getSourceRange();
14362        }
14363      } else {
14364        // Evaluate the initializer to see if it's a constant initializer.
14365        HasConstInit = var->checkForConstantInitialization(Notes);
14366      }
14367  
14368      if (HasConstInit) {
14369        // FIXME: Consider replacing the initializer with a ConstantExpr.
14370      } else if (var->isConstexpr()) {
14371        SourceLocation DiagLoc = var->getLocation();
14372        // If the note doesn't add any useful information other than a source
14373        // location, fold it into the primary diagnostic.
14374        if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14375                                     diag::note_invalid_subexpr_in_const_expr) {
14376          DiagLoc = Notes[0].first;
14377          Notes.clear();
14378        }
14379        Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
14380            << var << Init->getSourceRange();
14381        for (unsigned I = 0, N = Notes.size(); I != N; ++I)
14382          Diag(Notes[I].first, Notes[I].second);
14383      } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
14384        auto *Attr = var->getAttr<ConstInitAttr>();
14385        Diag(var->getLocation(), diag::err_require_constant_init_failed)
14386            << Init->getSourceRange();
14387        Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
14388            << Attr->getRange() << Attr->isConstinit();
14389        for (auto &it : Notes)
14390          Diag(it.first, it.second);
14391      } else if (IsGlobal &&
14392                 !getDiagnostics().isIgnored(diag::warn_global_constructor,
14393                                             var->getLocation())) {
14394        // Warn about globals which don't have a constant initializer.  Don't
14395        // warn about globals with a non-trivial destructor because we already
14396        // warned about them.
14397        CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
14398        if (!(RD && !RD->hasTrivialDestructor())) {
14399          // checkConstInit() here permits trivial default initialization even in
14400          // C++11 onwards, where such an initializer is not a constant initializer
14401          // but nonetheless doesn't require a global constructor.
14402          if (!checkConstInit())
14403            Diag(var->getLocation(), diag::warn_global_constructor)
14404                << Init->getSourceRange();
14405        }
14406      }
14407    }
14408  
14409    // Apply section attributes and pragmas to global variables.
14410    if (GlobalStorage && var->isThisDeclarationADefinition() &&
14411        !inTemplateInstantiation()) {
14412      PragmaStack<StringLiteral *> *Stack = nullptr;
14413      int SectionFlags = ASTContext::PSF_Read;
14414      bool MSVCEnv =
14415          Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
14416      std::optional<QualType::NonConstantStorageReason> Reason;
14417      if (HasConstInit &&
14418          !(Reason = var->getType().isNonConstantStorage(Context, true, false))) {
14419        Stack = &ConstSegStack;
14420      } else {
14421        SectionFlags |= ASTContext::PSF_Write;
14422        Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
14423      }
14424      if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
14425        if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
14426          SectionFlags |= ASTContext::PSF_Implicit;
14427        UnifySection(SA->getName(), SectionFlags, var);
14428      } else if (Stack->CurrentValue) {
14429        if (Stack != &ConstSegStack && MSVCEnv &&
14430            ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
14431            var->getType().isConstQualified()) {
14432          assert((!Reason || Reason != QualType::NonConstantStorageReason::
14433                                           NonConstNonReferenceType) &&
14434                 "This case should've already been handled elsewhere");
14435          Diag(var->getLocation(), diag::warn_section_msvc_compat)
14436                  << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
14437              ? QualType::NonConstantStorageReason::NonTrivialCtor
14438              : *Reason);
14439        }
14440        SectionFlags |= ASTContext::PSF_Implicit;
14441        auto SectionName = Stack->CurrentValue->getString();
14442        var->addAttr(SectionAttr::CreateImplicit(Context, SectionName,
14443                                                 Stack->CurrentPragmaLocation,
14444                                                 SectionAttr::Declspec_allocate));
14445        if (UnifySection(SectionName, SectionFlags, var))
14446          var->dropAttr<SectionAttr>();
14447      }
14448  
14449      // Apply the init_seg attribute if this has an initializer.  If the
14450      // initializer turns out to not be dynamic, we'll end up ignoring this
14451      // attribute.
14452      if (CurInitSeg && var->getInit())
14453        var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
14454                                                 CurInitSegLoc));
14455    }
14456  
14457    // All the following checks are C++ only.
14458    if (!getLangOpts().CPlusPlus) {
14459      // If this variable must be emitted, add it as an initializer for the
14460      // current module.
14461      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14462        Context.addModuleInitializer(ModuleScopes.back().Module, var);
14463      return;
14464    }
14465  
14466    // Require the destructor.
14467    if (!type->isDependentType())
14468      if (const RecordType *recordType = baseType->getAs<RecordType>())
14469        FinalizeVarWithDestructor(var, recordType);
14470  
14471    // If this variable must be emitted, add it as an initializer for the current
14472    // module.
14473    if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14474      Context.addModuleInitializer(ModuleScopes.back().Module, var);
14475  
14476    // Build the bindings if this is a structured binding declaration.
14477    if (auto *DD = dyn_cast<DecompositionDecl>(var))
14478      CheckCompleteDecompositionDeclaration(DD);
14479  }
14480  
CheckStaticLocalForDllExport(VarDecl * VD)14481  void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
14482    assert(VD->isStaticLocal());
14483  
14484    auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14485  
14486    // Find outermost function when VD is in lambda function.
14487    while (FD && !getDLLAttr(FD) &&
14488           !FD->hasAttr<DLLExportStaticLocalAttr>() &&
14489           !FD->hasAttr<DLLImportStaticLocalAttr>()) {
14490      FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
14491    }
14492  
14493    if (!FD)
14494      return;
14495  
14496    // Static locals inherit dll attributes from their function.
14497    if (Attr *A = getDLLAttr(FD)) {
14498      auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
14499      NewAttr->setInherited(true);
14500      VD->addAttr(NewAttr);
14501    } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
14502      auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
14503      NewAttr->setInherited(true);
14504      VD->addAttr(NewAttr);
14505  
14506      // Export this function to enforce exporting this static variable even
14507      // if it is not used in this compilation unit.
14508      if (!FD->hasAttr<DLLExportAttr>())
14509        FD->addAttr(NewAttr);
14510  
14511    } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
14512      auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
14513      NewAttr->setInherited(true);
14514      VD->addAttr(NewAttr);
14515    }
14516  }
14517  
CheckThreadLocalForLargeAlignment(VarDecl * VD)14518  void Sema::CheckThreadLocalForLargeAlignment(VarDecl *VD) {
14519    assert(VD->getTLSKind());
14520  
14521    // Perform TLS alignment check here after attributes attached to the variable
14522    // which may affect the alignment have been processed. Only perform the check
14523    // if the target has a maximum TLS alignment (zero means no constraints).
14524    if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
14525      // Protect the check so that it's not performed on dependent types and
14526      // dependent alignments (we can't determine the alignment in that case).
14527      if (!VD->hasDependentAlignment()) {
14528        CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
14529        if (Context.getDeclAlign(VD) > MaxAlignChars) {
14530          Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
14531              << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
14532              << (unsigned)MaxAlignChars.getQuantity();
14533        }
14534      }
14535    }
14536  }
14537  
FinalizeDeclaration(Decl * ThisDecl)14538  void Sema::FinalizeDeclaration(Decl *ThisDecl) {
14539    // Note that we are no longer parsing the initializer for this declaration.
14540    ParsingInitForAutoVars.erase(ThisDecl);
14541  
14542    VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
14543    if (!VD)
14544      return;
14545  
14546    // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
14547    if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
14548        !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
14549      if (PragmaClangBSSSection.Valid)
14550        VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
14551            Context, PragmaClangBSSSection.SectionName,
14552            PragmaClangBSSSection.PragmaLocation));
14553      if (PragmaClangDataSection.Valid)
14554        VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
14555            Context, PragmaClangDataSection.SectionName,
14556            PragmaClangDataSection.PragmaLocation));
14557      if (PragmaClangRodataSection.Valid)
14558        VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
14559            Context, PragmaClangRodataSection.SectionName,
14560            PragmaClangRodataSection.PragmaLocation));
14561      if (PragmaClangRelroSection.Valid)
14562        VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
14563            Context, PragmaClangRelroSection.SectionName,
14564            PragmaClangRelroSection.PragmaLocation));
14565    }
14566  
14567    if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
14568      for (auto *BD : DD->bindings()) {
14569        FinalizeDeclaration(BD);
14570      }
14571    }
14572  
14573    checkAttributesAfterMerging(*this, *VD);
14574  
14575    if (VD->isStaticLocal())
14576      CheckStaticLocalForDllExport(VD);
14577  
14578    if (VD->getTLSKind())
14579      CheckThreadLocalForLargeAlignment(VD);
14580  
14581    // Perform check for initializers of device-side global variables.
14582    // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
14583    // 7.5). We must also apply the same checks to all __shared__
14584    // variables whether they are local or not. CUDA also allows
14585    // constant initializers for __constant__ and __device__ variables.
14586    if (getLangOpts().CUDA)
14587      CUDA().checkAllowedInitializer(VD);
14588  
14589    // Grab the dllimport or dllexport attribute off of the VarDecl.
14590    const InheritableAttr *DLLAttr = getDLLAttr(VD);
14591  
14592    // Imported static data members cannot be defined out-of-line.
14593    if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
14594      if (VD->isStaticDataMember() && VD->isOutOfLine() &&
14595          VD->isThisDeclarationADefinition()) {
14596        // We allow definitions of dllimport class template static data members
14597        // with a warning.
14598        CXXRecordDecl *Context =
14599          cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
14600        bool IsClassTemplateMember =
14601            isa<ClassTemplatePartialSpecializationDecl>(Context) ||
14602            Context->getDescribedClassTemplate();
14603  
14604        Diag(VD->getLocation(),
14605             IsClassTemplateMember
14606                 ? diag::warn_attribute_dllimport_static_field_definition
14607                 : diag::err_attribute_dllimport_static_field_definition);
14608        Diag(IA->getLocation(), diag::note_attribute);
14609        if (!IsClassTemplateMember)
14610          VD->setInvalidDecl();
14611      }
14612    }
14613  
14614    // dllimport/dllexport variables cannot be thread local, their TLS index
14615    // isn't exported with the variable.
14616    if (DLLAttr && VD->getTLSKind()) {
14617      auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14618      if (F && getDLLAttr(F)) {
14619        assert(VD->isStaticLocal());
14620        // But if this is a static local in a dlimport/dllexport function, the
14621        // function will never be inlined, which means the var would never be
14622        // imported, so having it marked import/export is safe.
14623      } else {
14624        Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
14625                                                                      << DLLAttr;
14626        VD->setInvalidDecl();
14627      }
14628    }
14629  
14630    if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
14631      if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14632        Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14633            << Attr;
14634        VD->dropAttr<UsedAttr>();
14635      }
14636    }
14637    if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
14638      if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14639        Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14640            << Attr;
14641        VD->dropAttr<RetainAttr>();
14642      }
14643    }
14644  
14645    const DeclContext *DC = VD->getDeclContext();
14646    // If there's a #pragma GCC visibility in scope, and this isn't a class
14647    // member, set the visibility of this variable.
14648    if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
14649      AddPushedVisibilityAttribute(VD);
14650  
14651    // FIXME: Warn on unused var template partial specializations.
14652    if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
14653      MarkUnusedFileScopedDecl(VD);
14654  
14655    // Now we have parsed the initializer and can update the table of magic
14656    // tag values.
14657    if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
14658        !VD->getType()->isIntegralOrEnumerationType())
14659      return;
14660  
14661    for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
14662      const Expr *MagicValueExpr = VD->getInit();
14663      if (!MagicValueExpr) {
14664        continue;
14665      }
14666      std::optional<llvm::APSInt> MagicValueInt;
14667      if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
14668        Diag(I->getRange().getBegin(),
14669             diag::err_type_tag_for_datatype_not_ice)
14670          << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14671        continue;
14672      }
14673      if (MagicValueInt->getActiveBits() > 64) {
14674        Diag(I->getRange().getBegin(),
14675             diag::err_type_tag_for_datatype_too_large)
14676          << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14677        continue;
14678      }
14679      uint64_t MagicValue = MagicValueInt->getZExtValue();
14680      RegisterTypeTagForDatatype(I->getArgumentKind(),
14681                                 MagicValue,
14682                                 I->getMatchingCType(),
14683                                 I->getLayoutCompatible(),
14684                                 I->getMustBeNull());
14685    }
14686  }
14687  
hasDeducedAuto(DeclaratorDecl * DD)14688  static bool hasDeducedAuto(DeclaratorDecl *DD) {
14689    auto *VD = dyn_cast<VarDecl>(DD);
14690    return VD && !VD->getType()->hasAutoForTrailingReturnType();
14691  }
14692  
FinalizeDeclaratorGroup(Scope * S,const DeclSpec & DS,ArrayRef<Decl * > Group)14693  Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
14694                                                     ArrayRef<Decl *> Group) {
14695    SmallVector<Decl*, 8> Decls;
14696  
14697    if (DS.isTypeSpecOwned())
14698      Decls.push_back(DS.getRepAsDecl());
14699  
14700    DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
14701    DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
14702    bool DiagnosedMultipleDecomps = false;
14703    DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
14704    bool DiagnosedNonDeducedAuto = false;
14705  
14706    for (Decl *D : Group) {
14707      if (!D)
14708        continue;
14709      // Check if the Decl has been declared in '#pragma omp declare target'
14710      // directive and has static storage duration.
14711      if (auto *VD = dyn_cast<VarDecl>(D);
14712          LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
14713          VD->hasGlobalStorage())
14714        OpenMP().ActOnOpenMPDeclareTargetInitializer(D);
14715      // For declarators, there are some additional syntactic-ish checks we need
14716      // to perform.
14717      if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
14718        if (!FirstDeclaratorInGroup)
14719          FirstDeclaratorInGroup = DD;
14720        if (!FirstDecompDeclaratorInGroup)
14721          FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
14722        if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
14723            !hasDeducedAuto(DD))
14724          FirstNonDeducedAutoInGroup = DD;
14725  
14726        if (FirstDeclaratorInGroup != DD) {
14727          // A decomposition declaration cannot be combined with any other
14728          // declaration in the same group.
14729          if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
14730            Diag(FirstDecompDeclaratorInGroup->getLocation(),
14731                 diag::err_decomp_decl_not_alone)
14732                << FirstDeclaratorInGroup->getSourceRange()
14733                << DD->getSourceRange();
14734            DiagnosedMultipleDecomps = true;
14735          }
14736  
14737          // A declarator that uses 'auto' in any way other than to declare a
14738          // variable with a deduced type cannot be combined with any other
14739          // declarator in the same group.
14740          if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
14741            Diag(FirstNonDeducedAutoInGroup->getLocation(),
14742                 diag::err_auto_non_deduced_not_alone)
14743                << FirstNonDeducedAutoInGroup->getType()
14744                       ->hasAutoForTrailingReturnType()
14745                << FirstDeclaratorInGroup->getSourceRange()
14746                << DD->getSourceRange();
14747            DiagnosedNonDeducedAuto = true;
14748          }
14749        }
14750      }
14751  
14752      Decls.push_back(D);
14753    }
14754  
14755    if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
14756      if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
14757        handleTagNumbering(Tag, S);
14758        if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
14759            getLangOpts().CPlusPlus)
14760          Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
14761      }
14762    }
14763  
14764    return BuildDeclaratorGroup(Decls);
14765  }
14766  
14767  Sema::DeclGroupPtrTy
BuildDeclaratorGroup(MutableArrayRef<Decl * > Group)14768  Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
14769    // C++14 [dcl.spec.auto]p7: (DR1347)
14770    //   If the type that replaces the placeholder type is not the same in each
14771    //   deduction, the program is ill-formed.
14772    if (Group.size() > 1) {
14773      QualType Deduced;
14774      VarDecl *DeducedDecl = nullptr;
14775      for (unsigned i = 0, e = Group.size(); i != e; ++i) {
14776        VarDecl *D = dyn_cast<VarDecl>(Group[i]);
14777        if (!D || D->isInvalidDecl())
14778          break;
14779        DeducedType *DT = D->getType()->getContainedDeducedType();
14780        if (!DT || DT->getDeducedType().isNull())
14781          continue;
14782        if (Deduced.isNull()) {
14783          Deduced = DT->getDeducedType();
14784          DeducedDecl = D;
14785        } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
14786          auto *AT = dyn_cast<AutoType>(DT);
14787          auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
14788                          diag::err_auto_different_deductions)
14789                     << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
14790                     << DeducedDecl->getDeclName() << DT->getDeducedType()
14791                     << D->getDeclName();
14792          if (DeducedDecl->hasInit())
14793            Dia << DeducedDecl->getInit()->getSourceRange();
14794          if (D->getInit())
14795            Dia << D->getInit()->getSourceRange();
14796          D->setInvalidDecl();
14797          break;
14798        }
14799      }
14800    }
14801  
14802    ActOnDocumentableDecls(Group);
14803  
14804    return DeclGroupPtrTy::make(
14805        DeclGroupRef::Create(Context, Group.data(), Group.size()));
14806  }
14807  
ActOnDocumentableDecl(Decl * D)14808  void Sema::ActOnDocumentableDecl(Decl *D) {
14809    ActOnDocumentableDecls(D);
14810  }
14811  
ActOnDocumentableDecls(ArrayRef<Decl * > Group)14812  void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
14813    // Don't parse the comment if Doxygen diagnostics are ignored.
14814    if (Group.empty() || !Group[0])
14815      return;
14816  
14817    if (Diags.isIgnored(diag::warn_doc_param_not_found,
14818                        Group[0]->getLocation()) &&
14819        Diags.isIgnored(diag::warn_unknown_comment_command_name,
14820                        Group[0]->getLocation()))
14821      return;
14822  
14823    if (Group.size() >= 2) {
14824      // This is a decl group.  Normally it will contain only declarations
14825      // produced from declarator list.  But in case we have any definitions or
14826      // additional declaration references:
14827      //   'typedef struct S {} S;'
14828      //   'typedef struct S *S;'
14829      //   'struct S *pS;'
14830      // FinalizeDeclaratorGroup adds these as separate declarations.
14831      Decl *MaybeTagDecl = Group[0];
14832      if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
14833        Group = Group.slice(1);
14834      }
14835    }
14836  
14837    // FIMXE: We assume every Decl in the group is in the same file.
14838    // This is false when preprocessor constructs the group from decls in
14839    // different files (e. g. macros or #include).
14840    Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
14841  }
14842  
CheckFunctionOrTemplateParamDeclarator(Scope * S,Declarator & D)14843  void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
14844    // Check that there are no default arguments inside the type of this
14845    // parameter.
14846    if (getLangOpts().CPlusPlus)
14847      CheckExtraCXXDefaultArguments(D);
14848  
14849    // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
14850    if (D.getCXXScopeSpec().isSet()) {
14851      Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
14852        << D.getCXXScopeSpec().getRange();
14853    }
14854  
14855    // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
14856    // simple identifier except [...irrelevant cases...].
14857    switch (D.getName().getKind()) {
14858    case UnqualifiedIdKind::IK_Identifier:
14859      break;
14860  
14861    case UnqualifiedIdKind::IK_OperatorFunctionId:
14862    case UnqualifiedIdKind::IK_ConversionFunctionId:
14863    case UnqualifiedIdKind::IK_LiteralOperatorId:
14864    case UnqualifiedIdKind::IK_ConstructorName:
14865    case UnqualifiedIdKind::IK_DestructorName:
14866    case UnqualifiedIdKind::IK_ImplicitSelfParam:
14867    case UnqualifiedIdKind::IK_DeductionGuideName:
14868      Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
14869        << GetNameForDeclarator(D).getName();
14870      break;
14871  
14872    case UnqualifiedIdKind::IK_TemplateId:
14873    case UnqualifiedIdKind::IK_ConstructorTemplateId:
14874      // GetNameForDeclarator would not produce a useful name in this case.
14875      Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
14876      break;
14877    }
14878  }
14879  
CheckExplicitObjectParameter(Sema & S,ParmVarDecl * P,SourceLocation ExplicitThisLoc)14880  static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P,
14881                                           SourceLocation ExplicitThisLoc) {
14882    if (!ExplicitThisLoc.isValid())
14883      return;
14884    assert(S.getLangOpts().CPlusPlus &&
14885           "explicit parameter in non-cplusplus mode");
14886    if (!S.getLangOpts().CPlusPlus23)
14887      S.Diag(ExplicitThisLoc, diag::err_cxx20_deducing_this)
14888          << P->getSourceRange();
14889  
14890    // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
14891    // parameter pack.
14892    if (P->isParameterPack()) {
14893      S.Diag(P->getBeginLoc(), diag::err_explicit_object_parameter_pack)
14894          << P->getSourceRange();
14895      return;
14896    }
14897    P->setExplicitObjectParameterLoc(ExplicitThisLoc);
14898    if (LambdaScopeInfo *LSI = S.getCurLambda())
14899      LSI->ExplicitObjectParameter = P;
14900  }
14901  
ActOnParamDeclarator(Scope * S,Declarator & D,SourceLocation ExplicitThisLoc)14902  Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D,
14903                                   SourceLocation ExplicitThisLoc) {
14904    const DeclSpec &DS = D.getDeclSpec();
14905  
14906    // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
14907  
14908    // C++03 [dcl.stc]p2 also permits 'auto'.
14909    StorageClass SC = SC_None;
14910    if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
14911      SC = SC_Register;
14912      // In C++11, the 'register' storage class specifier is deprecated.
14913      // In C++17, it is not allowed, but we tolerate it as an extension.
14914      if (getLangOpts().CPlusPlus11) {
14915        Diag(DS.getStorageClassSpecLoc(),
14916             getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
14917                                       : diag::warn_deprecated_register)
14918          << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
14919      }
14920    } else if (getLangOpts().CPlusPlus &&
14921               DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
14922      SC = SC_Auto;
14923    } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
14924      Diag(DS.getStorageClassSpecLoc(),
14925           diag::err_invalid_storage_class_in_func_decl);
14926      D.getMutableDeclSpec().ClearStorageClassSpecs();
14927    }
14928  
14929    if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
14930      Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
14931        << DeclSpec::getSpecifierName(TSCS);
14932    if (DS.isInlineSpecified())
14933      Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
14934          << getLangOpts().CPlusPlus17;
14935    if (DS.hasConstexprSpecifier())
14936      Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
14937          << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
14938  
14939    DiagnoseFunctionSpecifiers(DS);
14940  
14941    CheckFunctionOrTemplateParamDeclarator(S, D);
14942  
14943    TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
14944    QualType parmDeclType = TInfo->getType();
14945  
14946    // Check for redeclaration of parameters, e.g. int foo(int x, int x);
14947    const IdentifierInfo *II = D.getIdentifier();
14948    if (II) {
14949      LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
14950                     RedeclarationKind::ForVisibleRedeclaration);
14951      LookupName(R, S);
14952      if (!R.empty()) {
14953        NamedDecl *PrevDecl = *R.begin();
14954        if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
14955          // Maybe we will complain about the shadowed template parameter.
14956          DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14957          // Just pretend that we didn't see the previous declaration.
14958          PrevDecl = nullptr;
14959        }
14960        if (PrevDecl && S->isDeclScope(PrevDecl)) {
14961          Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
14962          Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14963          // Recover by removing the name
14964          II = nullptr;
14965          D.SetIdentifier(nullptr, D.getIdentifierLoc());
14966          D.setInvalidType(true);
14967        }
14968      }
14969    }
14970  
14971    // Temporarily put parameter variables in the translation unit, not
14972    // the enclosing context.  This prevents them from accidentally
14973    // looking like class members in C++.
14974    ParmVarDecl *New =
14975        CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
14976                       D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
14977  
14978    if (D.isInvalidType())
14979      New->setInvalidDecl();
14980  
14981    CheckExplicitObjectParameter(*this, New, ExplicitThisLoc);
14982  
14983    assert(S->isFunctionPrototypeScope());
14984    assert(S->getFunctionPrototypeDepth() >= 1);
14985    New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
14986                      S->getNextFunctionPrototypeIndex());
14987  
14988    // Add the parameter declaration into this scope.
14989    S->AddDecl(New);
14990    if (II)
14991      IdResolver.AddDecl(New);
14992  
14993    ProcessDeclAttributes(S, New, D);
14994  
14995    if (D.getDeclSpec().isModulePrivateSpecified())
14996      Diag(New->getLocation(), diag::err_module_private_local)
14997          << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14998          << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
14999  
15000    if (New->hasAttr<BlocksAttr>()) {
15001      Diag(New->getLocation(), diag::err_block_on_nonlocal);
15002    }
15003  
15004    if (getLangOpts().OpenCL)
15005      deduceOpenCLAddressSpace(New);
15006  
15007    return New;
15008  }
15009  
BuildParmVarDeclForTypedef(DeclContext * DC,SourceLocation Loc,QualType T)15010  ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
15011                                                SourceLocation Loc,
15012                                                QualType T) {
15013    /* FIXME: setting StartLoc == Loc.
15014       Would it be worth to modify callers so as to provide proper source
15015       location for the unnamed parameters, embedding the parameter's type? */
15016    ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
15017                                  T, Context.getTrivialTypeSourceInfo(T, Loc),
15018                                             SC_None, nullptr);
15019    Param->setImplicit();
15020    return Param;
15021  }
15022  
DiagnoseUnusedParameters(ArrayRef<ParmVarDecl * > Parameters)15023  void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
15024    // Don't diagnose unused-parameter errors in template instantiations; we
15025    // will already have done so in the template itself.
15026    if (inTemplateInstantiation())
15027      return;
15028  
15029    for (const ParmVarDecl *Parameter : Parameters) {
15030      if (!Parameter->isReferenced() && Parameter->getDeclName() &&
15031          !Parameter->hasAttr<UnusedAttr>() &&
15032          !Parameter->getIdentifier()->isPlaceholder()) {
15033        Diag(Parameter->getLocation(), diag::warn_unused_parameter)
15034          << Parameter->getDeclName();
15035      }
15036    }
15037  }
15038  
DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl * > Parameters,QualType ReturnTy,NamedDecl * D)15039  void Sema::DiagnoseSizeOfParametersAndReturnValue(
15040      ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
15041    if (LangOpts.NumLargeByValueCopy == 0) // No check.
15042      return;
15043  
15044    // Warn if the return value is pass-by-value and larger than the specified
15045    // threshold.
15046    if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
15047      unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
15048      if (Size > LangOpts.NumLargeByValueCopy)
15049        Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
15050    }
15051  
15052    // Warn if any parameter is pass-by-value and larger than the specified
15053    // threshold.
15054    for (const ParmVarDecl *Parameter : Parameters) {
15055      QualType T = Parameter->getType();
15056      if (T->isDependentType() || !T.isPODType(Context))
15057        continue;
15058      unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
15059      if (Size > LangOpts.NumLargeByValueCopy)
15060        Diag(Parameter->getLocation(), diag::warn_parameter_size)
15061            << Parameter << Size;
15062    }
15063  }
15064  
CheckParameter(DeclContext * DC,SourceLocation StartLoc,SourceLocation NameLoc,const IdentifierInfo * Name,QualType T,TypeSourceInfo * TSInfo,StorageClass SC)15065  ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
15066                                    SourceLocation NameLoc,
15067                                    const IdentifierInfo *Name, QualType T,
15068                                    TypeSourceInfo *TSInfo, StorageClass SC) {
15069    // In ARC, infer a lifetime qualifier for appropriate parameter types.
15070    if (getLangOpts().ObjCAutoRefCount &&
15071        T.getObjCLifetime() == Qualifiers::OCL_None &&
15072        T->isObjCLifetimeType()) {
15073  
15074      Qualifiers::ObjCLifetime lifetime;
15075  
15076      // Special cases for arrays:
15077      //   - if it's const, use __unsafe_unretained
15078      //   - otherwise, it's an error
15079      if (T->isArrayType()) {
15080        if (!T.isConstQualified()) {
15081          if (DelayedDiagnostics.shouldDelayDiagnostics())
15082            DelayedDiagnostics.add(
15083                sema::DelayedDiagnostic::makeForbiddenType(
15084                NameLoc, diag::err_arc_array_param_no_ownership, T, false));
15085          else
15086            Diag(NameLoc, diag::err_arc_array_param_no_ownership)
15087                << TSInfo->getTypeLoc().getSourceRange();
15088        }
15089        lifetime = Qualifiers::OCL_ExplicitNone;
15090      } else {
15091        lifetime = T->getObjCARCImplicitLifetime();
15092      }
15093      T = Context.getLifetimeQualifiedType(T, lifetime);
15094    }
15095  
15096    ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
15097                                           Context.getAdjustedParameterType(T),
15098                                           TSInfo, SC, nullptr);
15099  
15100    // Make a note if we created a new pack in the scope of a lambda, so that
15101    // we know that references to that pack must also be expanded within the
15102    // lambda scope.
15103    if (New->isParameterPack())
15104      if (auto *LSI = getEnclosingLambda())
15105        LSI->LocalPacks.push_back(New);
15106  
15107    if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
15108        New->getType().hasNonTrivialToPrimitiveCopyCUnion())
15109      checkNonTrivialCUnion(New->getType(), New->getLocation(),
15110                            NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
15111  
15112    // Parameter declarators cannot be interface types. All ObjC objects are
15113    // passed by reference.
15114    if (T->isObjCObjectType()) {
15115      SourceLocation TypeEndLoc =
15116          getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
15117      Diag(NameLoc,
15118           diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
15119        << FixItHint::CreateInsertion(TypeEndLoc, "*");
15120      T = Context.getObjCObjectPointerType(T);
15121      New->setType(T);
15122    }
15123  
15124    // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
15125    // duration shall not be qualified by an address-space qualifier."
15126    // Since all parameters have automatic store duration, they can not have
15127    // an address space.
15128    if (T.getAddressSpace() != LangAS::Default &&
15129        // OpenCL allows function arguments declared to be an array of a type
15130        // to be qualified with an address space.
15131        !(getLangOpts().OpenCL &&
15132          (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
15133        // WebAssembly allows reference types as parameters. Funcref in particular
15134        // lives in a different address space.
15135        !(T->isFunctionPointerType() &&
15136          T.getAddressSpace() == LangAS::wasm_funcref)) {
15137      Diag(NameLoc, diag::err_arg_with_address_space);
15138      New->setInvalidDecl();
15139    }
15140  
15141    // PPC MMA non-pointer types are not allowed as function argument types.
15142    if (Context.getTargetInfo().getTriple().isPPC64() &&
15143        PPC().CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
15144      New->setInvalidDecl();
15145    }
15146  
15147    return New;
15148  }
15149  
ActOnFinishKNRParamDeclarations(Scope * S,Declarator & D,SourceLocation LocAfterDecls)15150  void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
15151                                             SourceLocation LocAfterDecls) {
15152    DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
15153  
15154    // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
15155    // in the declaration list shall have at least one declarator, those
15156    // declarators shall only declare identifiers from the identifier list, and
15157    // every identifier in the identifier list shall be declared.
15158    //
15159    // C89 3.7.1p5 "If a declarator includes an identifier list, only the
15160    // identifiers it names shall be declared in the declaration list."
15161    //
15162    // This is why we only diagnose in C99 and later. Note, the other conditions
15163    // listed are checked elsewhere.
15164    if (!FTI.hasPrototype) {
15165      for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
15166        --i;
15167        if (FTI.Params[i].Param == nullptr) {
15168          if (getLangOpts().C99) {
15169            SmallString<256> Code;
15170            llvm::raw_svector_ostream(Code)
15171                << "  int " << FTI.Params[i].Ident->getName() << ";\n";
15172            Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
15173                << FTI.Params[i].Ident
15174                << FixItHint::CreateInsertion(LocAfterDecls, Code);
15175          }
15176  
15177          // Implicitly declare the argument as type 'int' for lack of a better
15178          // type.
15179          AttributeFactory attrs;
15180          DeclSpec DS(attrs);
15181          const char* PrevSpec; // unused
15182          unsigned DiagID; // unused
15183          DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
15184                             DiagID, Context.getPrintingPolicy());
15185          // Use the identifier location for the type source range.
15186          DS.SetRangeStart(FTI.Params[i].IdentLoc);
15187          DS.SetRangeEnd(FTI.Params[i].IdentLoc);
15188          Declarator ParamD(DS, ParsedAttributesView::none(),
15189                            DeclaratorContext::KNRTypeList);
15190          ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
15191          FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
15192        }
15193      }
15194    }
15195  }
15196  
15197  Decl *
ActOnStartOfFunctionDef(Scope * FnBodyScope,Declarator & D,MultiTemplateParamsArg TemplateParameterLists,SkipBodyInfo * SkipBody,FnBodyKind BodyKind)15198  Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
15199                                MultiTemplateParamsArg TemplateParameterLists,
15200                                SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
15201    assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
15202    assert(D.isFunctionDeclarator() && "Not a function declarator!");
15203    Scope *ParentScope = FnBodyScope->getParent();
15204  
15205    // Check if we are in an `omp begin/end declare variant` scope. If we are, and
15206    // we define a non-templated function definition, we will create a declaration
15207    // instead (=BaseFD), and emit the definition with a mangled name afterwards.
15208    // The base function declaration will have the equivalent of an `omp declare
15209    // variant` annotation which specifies the mangled definition as a
15210    // specialization function under the OpenMP context defined as part of the
15211    // `omp begin declare variant`.
15212    SmallVector<FunctionDecl *, 4> Bases;
15213    if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
15214      OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
15215          ParentScope, D, TemplateParameterLists, Bases);
15216  
15217    D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
15218    Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
15219    Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
15220  
15221    if (!Bases.empty())
15222      OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl,
15223                                                                          Bases);
15224  
15225    return Dcl;
15226  }
15227  
ActOnFinishInlineFunctionDef(FunctionDecl * D)15228  void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
15229    Consumer.HandleInlineFunctionDefinition(D);
15230  }
15231  
FindPossiblePrototype(const FunctionDecl * FD,const FunctionDecl * & PossiblePrototype)15232  static bool FindPossiblePrototype(const FunctionDecl *FD,
15233                                    const FunctionDecl *&PossiblePrototype) {
15234    for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
15235         Prev = Prev->getPreviousDecl()) {
15236      // Ignore any declarations that occur in function or method
15237      // scope, because they aren't visible from the header.
15238      if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
15239        continue;
15240  
15241      PossiblePrototype = Prev;
15242      return Prev->getType()->isFunctionProtoType();
15243    }
15244    return false;
15245  }
15246  
15247  static bool
ShouldWarnAboutMissingPrototype(const FunctionDecl * FD,const FunctionDecl * & PossiblePrototype)15248  ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
15249                                  const FunctionDecl *&PossiblePrototype) {
15250    // Don't warn about invalid declarations.
15251    if (FD->isInvalidDecl())
15252      return false;
15253  
15254    // Or declarations that aren't global.
15255    if (!FD->isGlobal())
15256      return false;
15257  
15258    // Don't warn about C++ member functions.
15259    if (isa<CXXMethodDecl>(FD))
15260      return false;
15261  
15262    // Don't warn about 'main'.
15263    if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
15264      if (IdentifierInfo *II = FD->getIdentifier())
15265        if (II->isStr("main") || II->isStr("efi_main"))
15266          return false;
15267  
15268    if (FD->isMSVCRTEntryPoint())
15269      return false;
15270  
15271    // Don't warn about inline functions.
15272    if (FD->isInlined())
15273      return false;
15274  
15275    // Don't warn about function templates.
15276    if (FD->getDescribedFunctionTemplate())
15277      return false;
15278  
15279    // Don't warn about function template specializations.
15280    if (FD->isFunctionTemplateSpecialization())
15281      return false;
15282  
15283    // Don't warn for OpenCL kernels.
15284    if (FD->hasAttr<OpenCLKernelAttr>())
15285      return false;
15286  
15287    // Don't warn on explicitly deleted functions.
15288    if (FD->isDeleted())
15289      return false;
15290  
15291    // Don't warn on implicitly local functions (such as having local-typed
15292    // parameters).
15293    if (!FD->isExternallyVisible())
15294      return false;
15295  
15296    // If we were able to find a potential prototype, don't warn.
15297    if (FindPossiblePrototype(FD, PossiblePrototype))
15298      return false;
15299  
15300    return true;
15301  }
15302  
15303  void
CheckForFunctionRedefinition(FunctionDecl * FD,const FunctionDecl * EffectiveDefinition,SkipBodyInfo * SkipBody)15304  Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
15305                                     const FunctionDecl *EffectiveDefinition,
15306                                     SkipBodyInfo *SkipBody) {
15307    const FunctionDecl *Definition = EffectiveDefinition;
15308    if (!Definition &&
15309        !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
15310      return;
15311  
15312    if (Definition->getFriendObjectKind() != Decl::FOK_None) {
15313      if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
15314        if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
15315          // A merged copy of the same function, instantiated as a member of
15316          // the same class, is OK.
15317          if (declaresSameEntity(OrigFD, OrigDef) &&
15318              declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
15319                                 cast<Decl>(FD->getLexicalDeclContext())))
15320            return;
15321        }
15322      }
15323    }
15324  
15325    if (canRedefineFunction(Definition, getLangOpts()))
15326      return;
15327  
15328    // Don't emit an error when this is redefinition of a typo-corrected
15329    // definition.
15330    if (TypoCorrectedFunctionDefinitions.count(Definition))
15331      return;
15332  
15333    // If we don't have a visible definition of the function, and it's inline or
15334    // a template, skip the new definition.
15335    if (SkipBody && !hasVisibleDefinition(Definition) &&
15336        (Definition->getFormalLinkage() == Linkage::Internal ||
15337         Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
15338         Definition->getNumTemplateParameterLists())) {
15339      SkipBody->ShouldSkip = true;
15340      SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
15341      if (auto *TD = Definition->getDescribedFunctionTemplate())
15342        makeMergedDefinitionVisible(TD);
15343      makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
15344      return;
15345    }
15346  
15347    if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
15348        Definition->getStorageClass() == SC_Extern)
15349      Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
15350          << FD << getLangOpts().CPlusPlus;
15351    else
15352      Diag(FD->getLocation(), diag::err_redefinition) << FD;
15353  
15354    Diag(Definition->getLocation(), diag::note_previous_definition);
15355    FD->setInvalidDecl();
15356  }
15357  
RebuildLambdaScopeInfo(CXXMethodDecl * CallOperator)15358  LambdaScopeInfo *Sema::RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator) {
15359    CXXRecordDecl *LambdaClass = CallOperator->getParent();
15360  
15361    LambdaScopeInfo *LSI = PushLambdaScope();
15362    LSI->CallOperator = CallOperator;
15363    LSI->Lambda = LambdaClass;
15364    LSI->ReturnType = CallOperator->getReturnType();
15365    // This function in calls in situation where the context of the call operator
15366    // is not entered, so we set AfterParameterList to false, so that
15367    // `tryCaptureVariable` finds explicit captures in the appropriate context.
15368    LSI->AfterParameterList = false;
15369    const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
15370  
15371    if (LCD == LCD_None)
15372      LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
15373    else if (LCD == LCD_ByCopy)
15374      LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
15375    else if (LCD == LCD_ByRef)
15376      LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
15377    DeclarationNameInfo DNI = CallOperator->getNameInfo();
15378  
15379    LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
15380    LSI->Mutable = !CallOperator->isConst();
15381    if (CallOperator->isExplicitObjectMemberFunction())
15382      LSI->ExplicitObjectParameter = CallOperator->getParamDecl(0);
15383  
15384    // Add the captures to the LSI so they can be noted as already
15385    // captured within tryCaptureVar.
15386    auto I = LambdaClass->field_begin();
15387    for (const auto &C : LambdaClass->captures()) {
15388      if (C.capturesVariable()) {
15389        ValueDecl *VD = C.getCapturedVar();
15390        if (VD->isInitCapture())
15391          CurrentInstantiationScope->InstantiatedLocal(VD, VD);
15392        const bool ByRef = C.getCaptureKind() == LCK_ByRef;
15393        LSI->addCapture(VD, /*IsBlock*/false, ByRef,
15394            /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
15395            /*EllipsisLoc*/C.isPackExpansion()
15396                           ? C.getEllipsisLoc() : SourceLocation(),
15397            I->getType(), /*Invalid*/false);
15398  
15399      } else if (C.capturesThis()) {
15400        LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
15401                            C.getCaptureKind() == LCK_StarThis);
15402      } else {
15403        LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
15404                               I->getType());
15405      }
15406      ++I;
15407    }
15408    return LSI;
15409  }
15410  
ActOnStartOfFunctionDef(Scope * FnBodyScope,Decl * D,SkipBodyInfo * SkipBody,FnBodyKind BodyKind)15411  Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
15412                                      SkipBodyInfo *SkipBody,
15413                                      FnBodyKind BodyKind) {
15414    if (!D) {
15415      // Parsing the function declaration failed in some way. Push on a fake scope
15416      // anyway so we can try to parse the function body.
15417      PushFunctionScope();
15418      PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
15419      return D;
15420    }
15421  
15422    FunctionDecl *FD = nullptr;
15423  
15424    if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
15425      FD = FunTmpl->getTemplatedDecl();
15426    else
15427      FD = cast<FunctionDecl>(D);
15428  
15429    // Do not push if it is a lambda because one is already pushed when building
15430    // the lambda in ActOnStartOfLambdaDefinition().
15431    if (!isLambdaCallOperator(FD))
15432      // [expr.const]/p14.1
15433      // An expression or conversion is in an immediate function context if it is
15434      // potentially evaluated and either: its innermost enclosing non-block scope
15435      // is a function parameter scope of an immediate function.
15436      PushExpressionEvaluationContext(
15437          FD->isConsteval() ? ExpressionEvaluationContext::ImmediateFunctionContext
15438                            : ExprEvalContexts.back().Context);
15439  
15440    // Each ExpressionEvaluationContextRecord also keeps track of whether the
15441    // context is nested in an immediate function context, so smaller contexts
15442    // that appear inside immediate functions (like variable initializers) are
15443    // considered to be inside an immediate function context even though by
15444    // themselves they are not immediate function contexts. But when a new
15445    // function is entered, we need to reset this tracking, since the entered
15446    // function might be not an immediate function.
15447    ExprEvalContexts.back().InImmediateFunctionContext = FD->isConsteval();
15448    ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
15449        getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
15450  
15451    // Check for defining attributes before the check for redefinition.
15452    if (const auto *Attr = FD->getAttr<AliasAttr>()) {
15453      Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
15454      FD->dropAttr<AliasAttr>();
15455      FD->setInvalidDecl();
15456    }
15457    if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
15458      Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
15459      FD->dropAttr<IFuncAttr>();
15460      FD->setInvalidDecl();
15461    }
15462    if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
15463      if (!Context.getTargetInfo().hasFeature("fmv") &&
15464          !Attr->isDefaultVersion()) {
15465        // If function multi versioning disabled skip parsing function body
15466        // defined with non-default target_version attribute
15467        if (SkipBody)
15468          SkipBody->ShouldSkip = true;
15469        return nullptr;
15470      }
15471    }
15472  
15473    if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
15474      if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
15475          Ctor->isDefaultConstructor() &&
15476          Context.getTargetInfo().getCXXABI().isMicrosoft()) {
15477        // If this is an MS ABI dllexport default constructor, instantiate any
15478        // default arguments.
15479        InstantiateDefaultCtorDefaultArgs(Ctor);
15480      }
15481    }
15482  
15483    // See if this is a redefinition. If 'will have body' (or similar) is already
15484    // set, then these checks were already performed when it was set.
15485    if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
15486        !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
15487      CheckForFunctionRedefinition(FD, nullptr, SkipBody);
15488  
15489      // If we're skipping the body, we're done. Don't enter the scope.
15490      if (SkipBody && SkipBody->ShouldSkip)
15491        return D;
15492    }
15493  
15494    // Mark this function as "will have a body eventually".  This lets users to
15495    // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
15496    // this function.
15497    FD->setWillHaveBody();
15498  
15499    // If we are instantiating a generic lambda call operator, push
15500    // a LambdaScopeInfo onto the function stack.  But use the information
15501    // that's already been calculated (ActOnLambdaExpr) to prime the current
15502    // LambdaScopeInfo.
15503    // When the template operator is being specialized, the LambdaScopeInfo,
15504    // has to be properly restored so that tryCaptureVariable doesn't try
15505    // and capture any new variables. In addition when calculating potential
15506    // captures during transformation of nested lambdas, it is necessary to
15507    // have the LSI properly restored.
15508    if (isGenericLambdaCallOperatorSpecialization(FD)) {
15509      // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly
15510      // instantiated, explicitly specialized.
15511      if (FD->getTemplateSpecializationInfo()
15512              ->isExplicitInstantiationOrSpecialization()) {
15513        Diag(FD->getLocation(), diag::err_lambda_explicit_spec);
15514        FD->setInvalidDecl();
15515        PushFunctionScope();
15516      } else {
15517        assert(inTemplateInstantiation() &&
15518               "There should be an active template instantiation on the stack "
15519               "when instantiating a generic lambda!");
15520        RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D));
15521      }
15522    } else {
15523      // Enter a new function scope
15524      PushFunctionScope();
15525    }
15526  
15527    // Builtin functions cannot be defined.
15528    if (unsigned BuiltinID = FD->getBuiltinID()) {
15529      if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
15530          !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
15531        Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
15532        FD->setInvalidDecl();
15533      }
15534    }
15535  
15536    // The return type of a function definition must be complete (C99 6.9.1p3).
15537    // C++23 [dcl.fct.def.general]/p2
15538    // The type of [...] the return for a function definition
15539    // shall not be a (possibly cv-qualified) class type that is incomplete
15540    // or abstract within the function body unless the function is deleted.
15541    QualType ResultType = FD->getReturnType();
15542    if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
15543        !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
15544        (RequireCompleteType(FD->getLocation(), ResultType,
15545                             diag::err_func_def_incomplete_result) ||
15546         RequireNonAbstractType(FD->getLocation(), FD->getReturnType(),
15547                                diag::err_abstract_type_in_decl,
15548                                AbstractReturnType)))
15549      FD->setInvalidDecl();
15550  
15551    if (FnBodyScope)
15552      PushDeclContext(FnBodyScope, FD);
15553  
15554    // Check the validity of our function parameters
15555    if (BodyKind != FnBodyKind::Delete)
15556      CheckParmsForFunctionDef(FD->parameters(),
15557                               /*CheckParameterNames=*/true);
15558  
15559    // Add non-parameter declarations already in the function to the current
15560    // scope.
15561    if (FnBodyScope) {
15562      for (Decl *NPD : FD->decls()) {
15563        auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
15564        if (!NonParmDecl)
15565          continue;
15566        assert(!isa<ParmVarDecl>(NonParmDecl) &&
15567               "parameters should not be in newly created FD yet");
15568  
15569        // If the decl has a name, make it accessible in the current scope.
15570        if (NonParmDecl->getDeclName())
15571          PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
15572  
15573        // Similarly, dive into enums and fish their constants out, making them
15574        // accessible in this scope.
15575        if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
15576          for (auto *EI : ED->enumerators())
15577            PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
15578        }
15579      }
15580    }
15581  
15582    // Introduce our parameters into the function scope
15583    for (auto *Param : FD->parameters()) {
15584      Param->setOwningFunction(FD);
15585  
15586      // If this has an identifier, add it to the scope stack.
15587      if (Param->getIdentifier() && FnBodyScope) {
15588        CheckShadow(FnBodyScope, Param);
15589  
15590        PushOnScopeChains(Param, FnBodyScope);
15591      }
15592    }
15593  
15594    // C++ [module.import/6] external definitions are not permitted in header
15595    // units.  Deleted and Defaulted functions are implicitly inline (but the
15596    // inline state is not set at this point, so check the BodyKind explicitly).
15597    // FIXME: Consider an alternate location for the test where the inlined()
15598    // state is complete.
15599    if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
15600        !FD->isInvalidDecl() && !FD->isInlined() &&
15601        BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
15602        FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
15603        !FD->isTemplateInstantiation()) {
15604      assert(FD->isThisDeclarationADefinition());
15605      Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
15606      FD->setInvalidDecl();
15607    }
15608  
15609    // Ensure that the function's exception specification is instantiated.
15610    if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
15611      ResolveExceptionSpec(D->getLocation(), FPT);
15612  
15613    // dllimport cannot be applied to non-inline function definitions.
15614    if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
15615        !FD->isTemplateInstantiation()) {
15616      assert(!FD->hasAttr<DLLExportAttr>());
15617      Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
15618      FD->setInvalidDecl();
15619      return D;
15620    }
15621  
15622    // Some function attributes (like OptimizeNoneAttr) need actions before
15623    // parsing body started.
15624    applyFunctionAttributesBeforeParsingBody(D);
15625  
15626    // We want to attach documentation to original Decl (which might be
15627    // a function template).
15628    ActOnDocumentableDecl(D);
15629    if (getCurLexicalContext()->isObjCContainer() &&
15630        getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
15631        getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
15632      Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
15633  
15634    return D;
15635  }
15636  
applyFunctionAttributesBeforeParsingBody(Decl * FD)15637  void Sema::applyFunctionAttributesBeforeParsingBody(Decl *FD) {
15638    if (!FD || FD->isInvalidDecl())
15639      return;
15640    if (auto *TD = dyn_cast<FunctionTemplateDecl>(FD))
15641      FD = TD->getTemplatedDecl();
15642    if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
15643      FPOptionsOverride FPO;
15644      FPO.setDisallowOptimizations();
15645      CurFPFeatures.applyChanges(FPO);
15646      FpPragmaStack.CurrentValue =
15647          CurFPFeatures.getChangesFrom(FPOptions(LangOpts));
15648    }
15649  }
15650  
computeNRVO(Stmt * Body,FunctionScopeInfo * Scope)15651  void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
15652    ReturnStmt **Returns = Scope->Returns.data();
15653  
15654    for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
15655      if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
15656        if (!NRVOCandidate->isNRVOVariable())
15657          Returns[I]->setNRVOCandidate(nullptr);
15658      }
15659    }
15660  }
15661  
canDelayFunctionBody(const Declarator & D)15662  bool Sema::canDelayFunctionBody(const Declarator &D) {
15663    // We can't delay parsing the body of a constexpr function template (yet).
15664    if (D.getDeclSpec().hasConstexprSpecifier())
15665      return false;
15666  
15667    // We can't delay parsing the body of a function template with a deduced
15668    // return type (yet).
15669    if (D.getDeclSpec().hasAutoTypeSpec()) {
15670      // If the placeholder introduces a non-deduced trailing return type,
15671      // we can still delay parsing it.
15672      if (D.getNumTypeObjects()) {
15673        const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
15674        if (Outer.Kind == DeclaratorChunk::Function &&
15675            Outer.Fun.hasTrailingReturnType()) {
15676          QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
15677          return Ty.isNull() || !Ty->isUndeducedType();
15678        }
15679      }
15680      return false;
15681    }
15682  
15683    return true;
15684  }
15685  
canSkipFunctionBody(Decl * D)15686  bool Sema::canSkipFunctionBody(Decl *D) {
15687    // We cannot skip the body of a function (or function template) which is
15688    // constexpr, since we may need to evaluate its body in order to parse the
15689    // rest of the file.
15690    // We cannot skip the body of a function with an undeduced return type,
15691    // because any callers of that function need to know the type.
15692    if (const FunctionDecl *FD = D->getAsFunction()) {
15693      if (FD->isConstexpr())
15694        return false;
15695      // We can't simply call Type::isUndeducedType here, because inside template
15696      // auto can be deduced to a dependent type, which is not considered
15697      // "undeduced".
15698      if (FD->getReturnType()->getContainedDeducedType())
15699        return false;
15700    }
15701    return Consumer.shouldSkipFunctionBody(D);
15702  }
15703  
ActOnSkippedFunctionBody(Decl * Decl)15704  Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
15705    if (!Decl)
15706      return nullptr;
15707    if (FunctionDecl *FD = Decl->getAsFunction())
15708      FD->setHasSkippedBody();
15709    else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
15710      MD->setHasSkippedBody();
15711    return Decl;
15712  }
15713  
ActOnFinishFunctionBody(Decl * D,Stmt * BodyArg)15714  Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
15715    return ActOnFinishFunctionBody(D, BodyArg, /*IsInstantiation=*/false);
15716  }
15717  
15718  /// RAII object that pops an ExpressionEvaluationContext when exiting a function
15719  /// body.
15720  class ExitFunctionBodyRAII {
15721  public:
ExitFunctionBodyRAII(Sema & S,bool IsLambda)15722    ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
~ExitFunctionBodyRAII()15723    ~ExitFunctionBodyRAII() {
15724      if (!IsLambda)
15725        S.PopExpressionEvaluationContext();
15726    }
15727  
15728  private:
15729    Sema &S;
15730    bool IsLambda = false;
15731  };
15732  
diagnoseImplicitlyRetainedSelf(Sema & S)15733  static void diagnoseImplicitlyRetainedSelf(Sema &S) {
15734    llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
15735  
15736    auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
15737      if (EscapeInfo.count(BD))
15738        return EscapeInfo[BD];
15739  
15740      bool R = false;
15741      const BlockDecl *CurBD = BD;
15742  
15743      do {
15744        R = !CurBD->doesNotEscape();
15745        if (R)
15746          break;
15747        CurBD = CurBD->getParent()->getInnermostBlockDecl();
15748      } while (CurBD);
15749  
15750      return EscapeInfo[BD] = R;
15751    };
15752  
15753    // If the location where 'self' is implicitly retained is inside a escaping
15754    // block, emit a diagnostic.
15755    for (const std::pair<SourceLocation, const BlockDecl *> &P :
15756         S.ImplicitlyRetainedSelfLocs)
15757      if (IsOrNestedInEscapingBlock(P.second))
15758        S.Diag(P.first, diag::warn_implicitly_retains_self)
15759            << FixItHint::CreateInsertion(P.first, "self->");
15760  }
15761  
methodHasName(const FunctionDecl * FD,StringRef Name)15762  static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
15763    return isa<CXXMethodDecl>(FD) && FD->param_empty() &&
15764           FD->getDeclName().isIdentifier() && FD->getName() == Name;
15765  }
15766  
CanBeGetReturnObject(const FunctionDecl * FD)15767  bool Sema::CanBeGetReturnObject(const FunctionDecl *FD) {
15768    return methodHasName(FD, "get_return_object");
15769  }
15770  
CanBeGetReturnTypeOnAllocFailure(const FunctionDecl * FD)15771  bool Sema::CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD) {
15772    return FD->isStatic() &&
15773           methodHasName(FD, "get_return_object_on_allocation_failure");
15774  }
15775  
CheckCoroutineWrapper(FunctionDecl * FD)15776  void Sema::CheckCoroutineWrapper(FunctionDecl *FD) {
15777    RecordDecl *RD = FD->getReturnType()->getAsRecordDecl();
15778    if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
15779      return;
15780    // Allow some_promise_type::get_return_object().
15781    if (CanBeGetReturnObject(FD) || CanBeGetReturnTypeOnAllocFailure(FD))
15782      return;
15783    if (!FD->hasAttr<CoroWrapperAttr>())
15784      Diag(FD->getLocation(), diag::err_coroutine_return_type) << RD;
15785  }
15786  
ActOnFinishFunctionBody(Decl * dcl,Stmt * Body,bool IsInstantiation)15787  Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
15788                                      bool IsInstantiation) {
15789    FunctionScopeInfo *FSI = getCurFunction();
15790    FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
15791  
15792    if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
15793      FD->addAttr(StrictFPAttr::CreateImplicit(Context));
15794  
15795    sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
15796    sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
15797  
15798    // If we skip function body, we can't tell if a function is a coroutine.
15799    if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
15800      if (FSI->isCoroutine())
15801        CheckCompletedCoroutineBody(FD, Body);
15802      else
15803        CheckCoroutineWrapper(FD);
15804    }
15805  
15806    {
15807      // Do not call PopExpressionEvaluationContext() if it is a lambda because
15808      // one is already popped when finishing the lambda in BuildLambdaExpr().
15809      // This is meant to pop the context added in ActOnStartOfFunctionDef().
15810      ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
15811      if (FD) {
15812        // If this is called by Parser::ParseFunctionDefinition() after marking
15813        // the declaration as deleted, and if the deleted-function-body contains
15814        // a message (C++26), then a DefaultedOrDeletedInfo will have already been
15815        // added to store that message; do not overwrite it in that case.
15816        //
15817        // Since this would always set the body to 'nullptr' in that case anyway,
15818        // which is already done when the function decl is initially created,
15819        // always skipping this irrespective of whether there is a delete message
15820        // should not be a problem.
15821        if (!FD->isDeletedAsWritten())
15822          FD->setBody(Body);
15823        FD->setWillHaveBody(false);
15824        CheckImmediateEscalatingFunctionDefinition(FD, FSI);
15825  
15826        if (getLangOpts().CPlusPlus14) {
15827          if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
15828              FD->getReturnType()->isUndeducedType()) {
15829            // For a function with a deduced result type to return void,
15830            // the result type as written must be 'auto' or 'decltype(auto)',
15831            // possibly cv-qualified or constrained, but not ref-qualified.
15832            if (!FD->getReturnType()->getAs<AutoType>()) {
15833              Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
15834                  << FD->getReturnType();
15835              FD->setInvalidDecl();
15836            } else {
15837              // Falling off the end of the function is the same as 'return;'.
15838              Expr *Dummy = nullptr;
15839              if (DeduceFunctionTypeFromReturnExpr(
15840                      FD, dcl->getLocation(), Dummy,
15841                      FD->getReturnType()->getAs<AutoType>()))
15842                FD->setInvalidDecl();
15843            }
15844          }
15845        } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(FD)) {
15846          // In C++11, we don't use 'auto' deduction rules for lambda call
15847          // operators because we don't support return type deduction.
15848          auto *LSI = getCurLambda();
15849          if (LSI->HasImplicitReturnType) {
15850            deduceClosureReturnType(*LSI);
15851  
15852            // C++11 [expr.prim.lambda]p4:
15853            //   [...] if there are no return statements in the compound-statement
15854            //   [the deduced type is] the type void
15855            QualType RetType =
15856                LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
15857  
15858            // Update the return type to the deduced type.
15859            const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
15860            FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
15861                                                Proto->getExtProtoInfo()));
15862          }
15863        }
15864  
15865        // If the function implicitly returns zero (like 'main') or is naked,
15866        // don't complain about missing return statements.
15867        if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
15868          WP.disableCheckFallThrough();
15869  
15870        // MSVC permits the use of pure specifier (=0) on function definition,
15871        // defined at class scope, warn about this non-standard construct.
15872        if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
15873            !FD->isOutOfLine())
15874          Diag(FD->getLocation(), diag::ext_pure_function_definition);
15875  
15876        if (!FD->isInvalidDecl()) {
15877          // Don't diagnose unused parameters of defaulted, deleted or naked
15878          // functions.
15879          if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
15880              !FD->hasAttr<NakedAttr>())
15881            DiagnoseUnusedParameters(FD->parameters());
15882          DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
15883                                                 FD->getReturnType(), FD);
15884  
15885          // If this is a structor, we need a vtable.
15886          if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
15887            MarkVTableUsed(FD->getLocation(), Constructor->getParent());
15888          else if (CXXDestructorDecl *Destructor =
15889                       dyn_cast<CXXDestructorDecl>(FD))
15890            MarkVTableUsed(FD->getLocation(), Destructor->getParent());
15891  
15892          // Try to apply the named return value optimization. We have to check
15893          // if we can do this here because lambdas keep return statements around
15894          // to deduce an implicit return type.
15895          if (FD->getReturnType()->isRecordType() &&
15896              (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
15897            computeNRVO(Body, FSI);
15898        }
15899  
15900        // GNU warning -Wmissing-prototypes:
15901        //   Warn if a global function is defined without a previous
15902        //   prototype declaration. This warning is issued even if the
15903        //   definition itself provides a prototype. The aim is to detect
15904        //   global functions that fail to be declared in header files.
15905        const FunctionDecl *PossiblePrototype = nullptr;
15906        if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
15907          Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
15908  
15909          if (PossiblePrototype) {
15910            // We found a declaration that is not a prototype,
15911            // but that could be a zero-parameter prototype
15912            if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
15913              TypeLoc TL = TI->getTypeLoc();
15914              if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
15915                Diag(PossiblePrototype->getLocation(),
15916                     diag::note_declaration_not_a_prototype)
15917                    << (FD->getNumParams() != 0)
15918                    << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
15919                                                      FTL.getRParenLoc(), "void")
15920                                                : FixItHint{});
15921            }
15922          } else {
15923            // Returns true if the token beginning at this Loc is `const`.
15924            auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
15925                                    const LangOptions &LangOpts) {
15926              std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
15927              if (LocInfo.first.isInvalid())
15928                return false;
15929  
15930              bool Invalid = false;
15931              StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
15932              if (Invalid)
15933                return false;
15934  
15935              if (LocInfo.second > Buffer.size())
15936                return false;
15937  
15938              const char *LexStart = Buffer.data() + LocInfo.second;
15939              StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
15940  
15941              return StartTok.consume_front("const") &&
15942                     (StartTok.empty() || isWhitespace(StartTok[0]) ||
15943                      StartTok.starts_with("/*") || StartTok.starts_with("//"));
15944            };
15945  
15946            auto findBeginLoc = [&]() {
15947              // If the return type has `const` qualifier, we want to insert
15948              // `static` before `const` (and not before the typename).
15949              if ((FD->getReturnType()->isAnyPointerType() &&
15950                   FD->getReturnType()->getPointeeType().isConstQualified()) ||
15951                  FD->getReturnType().isConstQualified()) {
15952                // But only do this if we can determine where the `const` is.
15953  
15954                if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
15955                                 getLangOpts()))
15956  
15957                  return FD->getBeginLoc();
15958              }
15959              return FD->getTypeSpecStartLoc();
15960            };
15961            Diag(FD->getTypeSpecStartLoc(),
15962                 diag::note_static_for_internal_linkage)
15963                << /* function */ 1
15964                << (FD->getStorageClass() == SC_None
15965                        ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
15966                        : FixItHint{});
15967          }
15968        }
15969  
15970        // We might not have found a prototype because we didn't wish to warn on
15971        // the lack of a missing prototype. Try again without the checks for
15972        // whether we want to warn on the missing prototype.
15973        if (!PossiblePrototype)
15974          (void)FindPossiblePrototype(FD, PossiblePrototype);
15975  
15976        // If the function being defined does not have a prototype, then we may
15977        // need to diagnose it as changing behavior in C23 because we now know
15978        // whether the function accepts arguments or not. This only handles the
15979        // case where the definition has no prototype but does have parameters
15980        // and either there is no previous potential prototype, or the previous
15981        // potential prototype also has no actual prototype. This handles cases
15982        // like:
15983        //   void f(); void f(a) int a; {}
15984        //   void g(a) int a; {}
15985        // See MergeFunctionDecl() for other cases of the behavior change
15986        // diagnostic. See GetFullTypeForDeclarator() for handling of a function
15987        // type without a prototype.
15988        if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
15989            (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
15990                                    !PossiblePrototype->isImplicit()))) {
15991          // The function definition has parameters, so this will change behavior
15992          // in C23. If there is a possible prototype, it comes before the
15993          // function definition.
15994          // FIXME: The declaration may have already been diagnosed as being
15995          // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
15996          // there's no way to test for the "changes behavior" condition in
15997          // SemaType.cpp when forming the declaration's function type. So, we do
15998          // this awkward dance instead.
15999          //
16000          // If we have a possible prototype and it declares a function with a
16001          // prototype, we don't want to diagnose it; if we have a possible
16002          // prototype and it has no prototype, it may have already been
16003          // diagnosed in SemaType.cpp as deprecated depending on whether
16004          // -Wstrict-prototypes is enabled. If we already warned about it being
16005          // deprecated, add a note that it also changes behavior. If we didn't
16006          // warn about it being deprecated (because the diagnostic is not
16007          // enabled), warn now that it is deprecated and changes behavior.
16008  
16009          // This K&R C function definition definitely changes behavior in C23,
16010          // so diagnose it.
16011          Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
16012              << /*definition*/ 1 << /* not supported in C23 */ 0;
16013  
16014          // If we have a possible prototype for the function which is a user-
16015          // visible declaration, we already tested that it has no prototype.
16016          // This will change behavior in C23. This gets a warning rather than a
16017          // note because it's the same behavior-changing problem as with the
16018          // definition.
16019          if (PossiblePrototype)
16020            Diag(PossiblePrototype->getLocation(),
16021                 diag::warn_non_prototype_changes_behavior)
16022                << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
16023                << /*definition*/ 1;
16024        }
16025  
16026        // Warn on CPUDispatch with an actual body.
16027        if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
16028          if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
16029            if (!CmpndBody->body_empty())
16030              Diag(CmpndBody->body_front()->getBeginLoc(),
16031                   diag::warn_dispatch_body_ignored);
16032  
16033        if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
16034          const CXXMethodDecl *KeyFunction;
16035          if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
16036              MD->isVirtual() &&
16037              (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
16038              MD == KeyFunction->getCanonicalDecl()) {
16039            // Update the key-function state if necessary for this ABI.
16040            if (FD->isInlined() &&
16041                !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
16042              Context.setNonKeyFunction(MD);
16043  
16044              // If the newly-chosen key function is already defined, then we
16045              // need to mark the vtable as used retroactively.
16046              KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
16047              const FunctionDecl *Definition;
16048              if (KeyFunction && KeyFunction->isDefined(Definition))
16049                MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
16050            } else {
16051              // We just defined they key function; mark the vtable as used.
16052              MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
16053            }
16054          }
16055        }
16056  
16057        assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&
16058               "Function parsing confused");
16059      } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
16060        assert(MD == getCurMethodDecl() && "Method parsing confused");
16061        MD->setBody(Body);
16062        if (!MD->isInvalidDecl()) {
16063          DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
16064                                                 MD->getReturnType(), MD);
16065  
16066          if (Body)
16067            computeNRVO(Body, FSI);
16068        }
16069        if (FSI->ObjCShouldCallSuper) {
16070          Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
16071              << MD->getSelector().getAsString();
16072          FSI->ObjCShouldCallSuper = false;
16073        }
16074        if (FSI->ObjCWarnForNoDesignatedInitChain) {
16075          const ObjCMethodDecl *InitMethod = nullptr;
16076          bool isDesignated =
16077              MD->isDesignatedInitializerForTheInterface(&InitMethod);
16078          assert(isDesignated && InitMethod);
16079          (void)isDesignated;
16080  
16081          auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
16082            auto IFace = MD->getClassInterface();
16083            if (!IFace)
16084              return false;
16085            auto SuperD = IFace->getSuperClass();
16086            if (!SuperD)
16087              return false;
16088            return SuperD->getIdentifier() ==
16089                   ObjC().NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
16090          };
16091          // Don't issue this warning for unavailable inits or direct subclasses
16092          // of NSObject.
16093          if (!MD->isUnavailable() && !superIsNSObject(MD)) {
16094            Diag(MD->getLocation(),
16095                 diag::warn_objc_designated_init_missing_super_call);
16096            Diag(InitMethod->getLocation(),
16097                 diag::note_objc_designated_init_marked_here);
16098          }
16099          FSI->ObjCWarnForNoDesignatedInitChain = false;
16100        }
16101        if (FSI->ObjCWarnForNoInitDelegation) {
16102          // Don't issue this warning for unavailable inits.
16103          if (!MD->isUnavailable())
16104            Diag(MD->getLocation(),
16105                 diag::warn_objc_secondary_init_missing_init_call);
16106          FSI->ObjCWarnForNoInitDelegation = false;
16107        }
16108  
16109        diagnoseImplicitlyRetainedSelf(*this);
16110      } else {
16111        // Parsing the function declaration failed in some way. Pop the fake scope
16112        // we pushed on.
16113        PopFunctionScopeInfo(ActivePolicy, dcl);
16114        return nullptr;
16115      }
16116  
16117      if (Body && FSI->HasPotentialAvailabilityViolations)
16118        DiagnoseUnguardedAvailabilityViolations(dcl);
16119  
16120      assert(!FSI->ObjCShouldCallSuper &&
16121             "This should only be set for ObjC methods, which should have been "
16122             "handled in the block above.");
16123  
16124      // Verify and clean out per-function state.
16125      if (Body && (!FD || !FD->isDefaulted())) {
16126        // C++ constructors that have function-try-blocks can't have return
16127        // statements in the handlers of that block. (C++ [except.handle]p14)
16128        // Verify this.
16129        if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
16130          DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
16131  
16132        // Verify that gotos and switch cases don't jump into scopes illegally.
16133        if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
16134          DiagnoseInvalidJumps(Body);
16135  
16136        if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
16137          if (!Destructor->getParent()->isDependentType())
16138            CheckDestructor(Destructor);
16139  
16140          MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
16141                                                 Destructor->getParent());
16142        }
16143  
16144        // If any errors have occurred, clear out any temporaries that may have
16145        // been leftover. This ensures that these temporaries won't be picked up
16146        // for deletion in some later function.
16147        if (hasUncompilableErrorOccurred() ||
16148            hasAnyUnrecoverableErrorsInThisFunction() ||
16149            getDiagnostics().getSuppressAllDiagnostics()) {
16150          DiscardCleanupsInEvaluationContext();
16151        }
16152        if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
16153          // Since the body is valid, issue any analysis-based warnings that are
16154          // enabled.
16155          ActivePolicy = &WP;
16156        }
16157  
16158        if (!IsInstantiation && FD &&
16159            (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
16160            !FD->isInvalidDecl() &&
16161            !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
16162          FD->setInvalidDecl();
16163  
16164        if (FD && FD->hasAttr<NakedAttr>()) {
16165          for (const Stmt *S : Body->children()) {
16166            // Allow local register variables without initializer as they don't
16167            // require prologue.
16168            bool RegisterVariables = false;
16169            if (auto *DS = dyn_cast<DeclStmt>(S)) {
16170              for (const auto *Decl : DS->decls()) {
16171                if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
16172                  RegisterVariables =
16173                      Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
16174                  if (!RegisterVariables)
16175                    break;
16176                }
16177              }
16178            }
16179            if (RegisterVariables)
16180              continue;
16181            if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
16182              Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
16183              Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
16184              FD->setInvalidDecl();
16185              break;
16186            }
16187          }
16188        }
16189  
16190        assert(ExprCleanupObjects.size() ==
16191                   ExprEvalContexts.back().NumCleanupObjects &&
16192               "Leftover temporaries in function");
16193        assert(!Cleanup.exprNeedsCleanups() &&
16194               "Unaccounted cleanups in function");
16195        assert(MaybeODRUseExprs.empty() &&
16196               "Leftover expressions for odr-use checking");
16197      }
16198    } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
16199      // the declaration context below. Otherwise, we're unable to transform
16200      // 'this' expressions when transforming immediate context functions.
16201  
16202    if (!IsInstantiation)
16203      PopDeclContext();
16204  
16205    PopFunctionScopeInfo(ActivePolicy, dcl);
16206    // If any errors have occurred, clear out any temporaries that may have
16207    // been leftover. This ensures that these temporaries won't be picked up for
16208    // deletion in some later function.
16209    if (hasUncompilableErrorOccurred()) {
16210      DiscardCleanupsInEvaluationContext();
16211    }
16212  
16213    if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsTargetDevice ||
16214                                    !LangOpts.OMPTargetTriples.empty())) ||
16215               LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
16216      auto ES = getEmissionStatus(FD);
16217      if (ES == Sema::FunctionEmissionStatus::Emitted ||
16218          ES == Sema::FunctionEmissionStatus::Unknown)
16219        DeclsToCheckForDeferredDiags.insert(FD);
16220    }
16221  
16222    if (FD && !FD->isDeleted())
16223      checkTypeSupport(FD->getType(), FD->getLocation(), FD);
16224  
16225    return dcl;
16226  }
16227  
16228  /// When we finish delayed parsing of an attribute, we must attach it to the
16229  /// relevant Decl.
ActOnFinishDelayedAttribute(Scope * S,Decl * D,ParsedAttributes & Attrs)16230  void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
16231                                         ParsedAttributes &Attrs) {
16232    // Always attach attributes to the underlying decl.
16233    if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
16234      D = TD->getTemplatedDecl();
16235    ProcessDeclAttributeList(S, D, Attrs);
16236    ProcessAPINotes(D);
16237  
16238    if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
16239      if (Method->isStatic())
16240        checkThisInStaticMemberFunctionAttributes(Method);
16241  }
16242  
ImplicitlyDefineFunction(SourceLocation Loc,IdentifierInfo & II,Scope * S)16243  NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
16244                                            IdentifierInfo &II, Scope *S) {
16245    // It is not valid to implicitly define a function in C23.
16246    assert(LangOpts.implicitFunctionsAllowed() &&
16247           "Implicit function declarations aren't allowed in this language mode");
16248  
16249    // Find the scope in which the identifier is injected and the corresponding
16250    // DeclContext.
16251    // FIXME: C89 does not say what happens if there is no enclosing block scope.
16252    // In that case, we inject the declaration into the translation unit scope
16253    // instead.
16254    Scope *BlockScope = S;
16255    while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
16256      BlockScope = BlockScope->getParent();
16257  
16258    // Loop until we find a DeclContext that is either a function/method or the
16259    // translation unit, which are the only two valid places to implicitly define
16260    // a function. This avoids accidentally defining the function within a tag
16261    // declaration, for example.
16262    Scope *ContextScope = BlockScope;
16263    while (!ContextScope->getEntity() ||
16264           (!ContextScope->getEntity()->isFunctionOrMethod() &&
16265            !ContextScope->getEntity()->isTranslationUnit()))
16266      ContextScope = ContextScope->getParent();
16267    ContextRAII SavedContext(*this, ContextScope->getEntity());
16268  
16269    // Before we produce a declaration for an implicitly defined
16270    // function, see whether there was a locally-scoped declaration of
16271    // this name as a function or variable. If so, use that
16272    // (non-visible) declaration, and complain about it.
16273    NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
16274    if (ExternCPrev) {
16275      // We still need to inject the function into the enclosing block scope so
16276      // that later (non-call) uses can see it.
16277      PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
16278  
16279      // C89 footnote 38:
16280      //   If in fact it is not defined as having type "function returning int",
16281      //   the behavior is undefined.
16282      if (!isa<FunctionDecl>(ExternCPrev) ||
16283          !Context.typesAreCompatible(
16284              cast<FunctionDecl>(ExternCPrev)->getType(),
16285              Context.getFunctionNoProtoType(Context.IntTy))) {
16286        Diag(Loc, diag::ext_use_out_of_scope_declaration)
16287            << ExternCPrev << !getLangOpts().C99;
16288        Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
16289        return ExternCPrev;
16290      }
16291    }
16292  
16293    // Extension in C99 (defaults to error). Legal in C89, but warn about it.
16294    unsigned diag_id;
16295    if (II.getName().starts_with("__builtin_"))
16296      diag_id = diag::warn_builtin_unknown;
16297    // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
16298    else if (getLangOpts().C99)
16299      diag_id = diag::ext_implicit_function_decl_c99;
16300    else
16301      diag_id = diag::warn_implicit_function_decl;
16302  
16303    TypoCorrection Corrected;
16304    // Because typo correction is expensive, only do it if the implicit
16305    // function declaration is going to be treated as an error.
16306    //
16307    // Perform the correction before issuing the main diagnostic, as some
16308    // consumers use typo-correction callbacks to enhance the main diagnostic.
16309    if (S && !ExternCPrev &&
16310        (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
16311      DeclFilterCCC<FunctionDecl> CCC{};
16312      Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
16313                              S, nullptr, CCC, CTK_NonError);
16314    }
16315  
16316    Diag(Loc, diag_id) << &II;
16317    if (Corrected) {
16318      // If the correction is going to suggest an implicitly defined function,
16319      // skip the correction as not being a particularly good idea.
16320      bool Diagnose = true;
16321      if (const auto *D = Corrected.getCorrectionDecl())
16322        Diagnose = !D->isImplicit();
16323      if (Diagnose)
16324        diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
16325                     /*ErrorRecovery*/ false);
16326    }
16327  
16328    // If we found a prior declaration of this function, don't bother building
16329    // another one. We've already pushed that one into scope, so there's nothing
16330    // more to do.
16331    if (ExternCPrev)
16332      return ExternCPrev;
16333  
16334    // Set a Declarator for the implicit definition: int foo();
16335    const char *Dummy;
16336    AttributeFactory attrFactory;
16337    DeclSpec DS(attrFactory);
16338    unsigned DiagID;
16339    bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
16340                                    Context.getPrintingPolicy());
16341    (void)Error; // Silence warning.
16342    assert(!Error && "Error setting up implicit decl!");
16343    SourceLocation NoLoc;
16344    Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block);
16345    D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
16346                                               /*IsAmbiguous=*/false,
16347                                               /*LParenLoc=*/NoLoc,
16348                                               /*Params=*/nullptr,
16349                                               /*NumParams=*/0,
16350                                               /*EllipsisLoc=*/NoLoc,
16351                                               /*RParenLoc=*/NoLoc,
16352                                               /*RefQualifierIsLvalueRef=*/true,
16353                                               /*RefQualifierLoc=*/NoLoc,
16354                                               /*MutableLoc=*/NoLoc, EST_None,
16355                                               /*ESpecRange=*/SourceRange(),
16356                                               /*Exceptions=*/nullptr,
16357                                               /*ExceptionRanges=*/nullptr,
16358                                               /*NumExceptions=*/0,
16359                                               /*NoexceptExpr=*/nullptr,
16360                                               /*ExceptionSpecTokens=*/nullptr,
16361                                               /*DeclsInPrototype=*/std::nullopt,
16362                                               Loc, Loc, D),
16363                  std::move(DS.getAttributes()), SourceLocation());
16364    D.SetIdentifier(&II, Loc);
16365  
16366    // Insert this function into the enclosing block scope.
16367    FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
16368    FD->setImplicit();
16369  
16370    AddKnownFunctionAttributes(FD);
16371  
16372    return FD;
16373  }
16374  
AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FunctionDecl * FD)16375  void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
16376      FunctionDecl *FD) {
16377    if (FD->isInvalidDecl())
16378      return;
16379  
16380    if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
16381        FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
16382      return;
16383  
16384    std::optional<unsigned> AlignmentParam;
16385    bool IsNothrow = false;
16386    if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
16387      return;
16388  
16389    // C++2a [basic.stc.dynamic.allocation]p4:
16390    //   An allocation function that has a non-throwing exception specification
16391    //   indicates failure by returning a null pointer value. Any other allocation
16392    //   function never returns a null pointer value and indicates failure only by
16393    //   throwing an exception [...]
16394    //
16395    // However, -fcheck-new invalidates this possible assumption, so don't add
16396    // NonNull when that is enabled.
16397    if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
16398        !getLangOpts().CheckNew)
16399      FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
16400  
16401    // C++2a [basic.stc.dynamic.allocation]p2:
16402    //   An allocation function attempts to allocate the requested amount of
16403    //   storage. [...] If the request succeeds, the value returned by a
16404    //   replaceable allocation function is a [...] pointer value p0 different
16405    //   from any previously returned value p1 [...]
16406    //
16407    // However, this particular information is being added in codegen,
16408    // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
16409  
16410    // C++2a [basic.stc.dynamic.allocation]p2:
16411    //   An allocation function attempts to allocate the requested amount of
16412    //   storage. If it is successful, it returns the address of the start of a
16413    //   block of storage whose length in bytes is at least as large as the
16414    //   requested size.
16415    if (!FD->hasAttr<AllocSizeAttr>()) {
16416      FD->addAttr(AllocSizeAttr::CreateImplicit(
16417          Context, /*ElemSizeParam=*/ParamIdx(1, FD),
16418          /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
16419    }
16420  
16421    // C++2a [basic.stc.dynamic.allocation]p3:
16422    //   For an allocation function [...], the pointer returned on a successful
16423    //   call shall represent the address of storage that is aligned as follows:
16424    //   (3.1) If the allocation function takes an argument of type
16425    //         std​::​align_­val_­t, the storage will have the alignment
16426    //         specified by the value of this argument.
16427    if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
16428      FD->addAttr(AllocAlignAttr::CreateImplicit(
16429          Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
16430    }
16431  
16432    // FIXME:
16433    // C++2a [basic.stc.dynamic.allocation]p3:
16434    //   For an allocation function [...], the pointer returned on a successful
16435    //   call shall represent the address of storage that is aligned as follows:
16436    //   (3.2) Otherwise, if the allocation function is named operator new[],
16437    //         the storage is aligned for any object that does not have
16438    //         new-extended alignment ([basic.align]) and is no larger than the
16439    //         requested size.
16440    //   (3.3) Otherwise, the storage is aligned for any object that does not
16441    //         have new-extended alignment and is of the requested size.
16442  }
16443  
AddKnownFunctionAttributes(FunctionDecl * FD)16444  void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
16445    if (FD->isInvalidDecl())
16446      return;
16447  
16448    // If this is a built-in function, map its builtin attributes to
16449    // actual attributes.
16450    if (unsigned BuiltinID = FD->getBuiltinID()) {
16451      // Handle printf-formatting attributes.
16452      unsigned FormatIdx;
16453      bool HasVAListArg;
16454      if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
16455        if (!FD->hasAttr<FormatAttr>()) {
16456          const char *fmt = "printf";
16457          unsigned int NumParams = FD->getNumParams();
16458          if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
16459              FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
16460            fmt = "NSString";
16461          FD->addAttr(FormatAttr::CreateImplicit(Context,
16462                                                 &Context.Idents.get(fmt),
16463                                                 FormatIdx+1,
16464                                                 HasVAListArg ? 0 : FormatIdx+2,
16465                                                 FD->getLocation()));
16466        }
16467      }
16468      if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
16469                                               HasVAListArg)) {
16470       if (!FD->hasAttr<FormatAttr>())
16471         FD->addAttr(FormatAttr::CreateImplicit(Context,
16472                                                &Context.Idents.get("scanf"),
16473                                                FormatIdx+1,
16474                                                HasVAListArg ? 0 : FormatIdx+2,
16475                                                FD->getLocation()));
16476      }
16477  
16478      // Handle automatically recognized callbacks.
16479      SmallVector<int, 4> Encoding;
16480      if (!FD->hasAttr<CallbackAttr>() &&
16481          Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
16482        FD->addAttr(CallbackAttr::CreateImplicit(
16483            Context, Encoding.data(), Encoding.size(), FD->getLocation()));
16484  
16485      // Mark const if we don't care about errno and/or floating point exceptions
16486      // that are the only thing preventing the function from being const. This
16487      // allows IRgen to use LLVM intrinsics for such functions.
16488      bool NoExceptions =
16489          getLangOpts().getDefaultExceptionMode() == LangOptions::FPE_Ignore;
16490      bool ConstWithoutErrnoAndExceptions =
16491          Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(BuiltinID);
16492      bool ConstWithoutExceptions =
16493          Context.BuiltinInfo.isConstWithoutExceptions(BuiltinID);
16494      if (!FD->hasAttr<ConstAttr>() &&
16495          (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
16496          (!ConstWithoutErrnoAndExceptions ||
16497           (!getLangOpts().MathErrno && NoExceptions)) &&
16498          (!ConstWithoutExceptions || NoExceptions))
16499        FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16500  
16501      // We make "fma" on GNU or Windows const because we know it does not set
16502      // errno in those environments even though it could set errno based on the
16503      // C standard.
16504      const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
16505      if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
16506          !FD->hasAttr<ConstAttr>()) {
16507        switch (BuiltinID) {
16508        case Builtin::BI__builtin_fma:
16509        case Builtin::BI__builtin_fmaf:
16510        case Builtin::BI__builtin_fmal:
16511        case Builtin::BIfma:
16512        case Builtin::BIfmaf:
16513        case Builtin::BIfmal:
16514          FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16515          break;
16516        default:
16517          break;
16518        }
16519      }
16520  
16521      if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
16522          !FD->hasAttr<ReturnsTwiceAttr>())
16523        FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
16524                                           FD->getLocation()));
16525      if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
16526        FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16527      if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
16528        FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
16529      if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
16530        FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16531      if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
16532          !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
16533        // Add the appropriate attribute, depending on the CUDA compilation mode
16534        // and which target the builtin belongs to. For example, during host
16535        // compilation, aux builtins are __device__, while the rest are __host__.
16536        if (getLangOpts().CUDAIsDevice !=
16537            Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
16538          FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
16539        else
16540          FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
16541      }
16542  
16543      // Add known guaranteed alignment for allocation functions.
16544      switch (BuiltinID) {
16545      case Builtin::BImemalign:
16546      case Builtin::BIaligned_alloc:
16547        if (!FD->hasAttr<AllocAlignAttr>())
16548          FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
16549                                                     FD->getLocation()));
16550        break;
16551      default:
16552        break;
16553      }
16554  
16555      // Add allocsize attribute for allocation functions.
16556      switch (BuiltinID) {
16557      case Builtin::BIcalloc:
16558        FD->addAttr(AllocSizeAttr::CreateImplicit(
16559            Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
16560        break;
16561      case Builtin::BImemalign:
16562      case Builtin::BIaligned_alloc:
16563      case Builtin::BIrealloc:
16564        FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
16565                                                  ParamIdx(), FD->getLocation()));
16566        break;
16567      case Builtin::BImalloc:
16568        FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
16569                                                  ParamIdx(), FD->getLocation()));
16570        break;
16571      default:
16572        break;
16573      }
16574  
16575      // Add lifetime attribute to std::move, std::fowrard et al.
16576      switch (BuiltinID) {
16577      case Builtin::BIaddressof:
16578      case Builtin::BI__addressof:
16579      case Builtin::BI__builtin_addressof:
16580      case Builtin::BIas_const:
16581      case Builtin::BIforward:
16582      case Builtin::BIforward_like:
16583      case Builtin::BImove:
16584      case Builtin::BImove_if_noexcept:
16585        if (ParmVarDecl *P = FD->getParamDecl(0u);
16586            !P->hasAttr<LifetimeBoundAttr>())
16587          P->addAttr(
16588              LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation()));
16589        break;
16590      default:
16591        break;
16592      }
16593    }
16594  
16595    AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
16596  
16597    // If C++ exceptions are enabled but we are told extern "C" functions cannot
16598    // throw, add an implicit nothrow attribute to any extern "C" function we come
16599    // across.
16600    if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
16601        FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
16602      const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
16603      if (!FPT || FPT->getExceptionSpecType() == EST_None)
16604        FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16605    }
16606  
16607    IdentifierInfo *Name = FD->getIdentifier();
16608    if (!Name)
16609      return;
16610    if ((!getLangOpts().CPlusPlus && FD->getDeclContext()->isTranslationUnit()) ||
16611        (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
16612         cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
16613             LinkageSpecLanguageIDs::C)) {
16614      // Okay: this could be a libc/libm/Objective-C function we know
16615      // about.
16616    } else
16617      return;
16618  
16619    if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
16620      // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
16621      // target-specific builtins, perhaps?
16622      if (!FD->hasAttr<FormatAttr>())
16623        FD->addAttr(FormatAttr::CreateImplicit(Context,
16624                                               &Context.Idents.get("printf"), 2,
16625                                               Name->isStr("vasprintf") ? 0 : 3,
16626                                               FD->getLocation()));
16627    }
16628  
16629    if (Name->isStr("__CFStringMakeConstantString")) {
16630      // We already have a __builtin___CFStringMakeConstantString,
16631      // but builds that use -fno-constant-cfstrings don't go through that.
16632      if (!FD->hasAttr<FormatArgAttr>())
16633        FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
16634                                                  FD->getLocation()));
16635    }
16636  }
16637  
ParseTypedefDecl(Scope * S,Declarator & D,QualType T,TypeSourceInfo * TInfo)16638  TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
16639                                      TypeSourceInfo *TInfo) {
16640    assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
16641    assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
16642  
16643    if (!TInfo) {
16644      assert(D.isInvalidType() && "no declarator info for valid type");
16645      TInfo = Context.getTrivialTypeSourceInfo(T);
16646    }
16647  
16648    // Scope manipulation handled by caller.
16649    TypedefDecl *NewTD =
16650        TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
16651                            D.getIdentifierLoc(), D.getIdentifier(), TInfo);
16652  
16653    // Bail out immediately if we have an invalid declaration.
16654    if (D.isInvalidType()) {
16655      NewTD->setInvalidDecl();
16656      return NewTD;
16657    }
16658  
16659    if (D.getDeclSpec().isModulePrivateSpecified()) {
16660      if (CurContext->isFunctionOrMethod())
16661        Diag(NewTD->getLocation(), diag::err_module_private_local)
16662            << 2 << NewTD
16663            << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
16664            << FixItHint::CreateRemoval(
16665                   D.getDeclSpec().getModulePrivateSpecLoc());
16666      else
16667        NewTD->setModulePrivate();
16668    }
16669  
16670    // C++ [dcl.typedef]p8:
16671    //   If the typedef declaration defines an unnamed class (or
16672    //   enum), the first typedef-name declared by the declaration
16673    //   to be that class type (or enum type) is used to denote the
16674    //   class type (or enum type) for linkage purposes only.
16675    // We need to check whether the type was declared in the declaration.
16676    switch (D.getDeclSpec().getTypeSpecType()) {
16677    case TST_enum:
16678    case TST_struct:
16679    case TST_interface:
16680    case TST_union:
16681    case TST_class: {
16682      TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
16683      setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
16684      break;
16685    }
16686  
16687    default:
16688      break;
16689    }
16690  
16691    return NewTD;
16692  }
16693  
CheckEnumUnderlyingType(TypeSourceInfo * TI)16694  bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
16695    SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
16696    QualType T = TI->getType();
16697  
16698    if (T->isDependentType())
16699      return false;
16700  
16701    // This doesn't use 'isIntegralType' despite the error message mentioning
16702    // integral type because isIntegralType would also allow enum types in C.
16703    if (const BuiltinType *BT = T->getAs<BuiltinType>())
16704      if (BT->isInteger())
16705        return false;
16706  
16707    return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
16708           << T << T->isBitIntType();
16709  }
16710  
CheckEnumRedeclaration(SourceLocation EnumLoc,bool IsScoped,QualType EnumUnderlyingTy,bool IsFixed,const EnumDecl * Prev)16711  bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
16712                                    QualType EnumUnderlyingTy, bool IsFixed,
16713                                    const EnumDecl *Prev) {
16714    if (IsScoped != Prev->isScoped()) {
16715      Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
16716        << Prev->isScoped();
16717      Diag(Prev->getLocation(), diag::note_previous_declaration);
16718      return true;
16719    }
16720  
16721    if (IsFixed && Prev->isFixed()) {
16722      if (!EnumUnderlyingTy->isDependentType() &&
16723          !Prev->getIntegerType()->isDependentType() &&
16724          !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
16725                                          Prev->getIntegerType())) {
16726        // TODO: Highlight the underlying type of the redeclaration.
16727        Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
16728          << EnumUnderlyingTy << Prev->getIntegerType();
16729        Diag(Prev->getLocation(), diag::note_previous_declaration)
16730            << Prev->getIntegerTypeRange();
16731        return true;
16732      }
16733    } else if (IsFixed != Prev->isFixed()) {
16734      Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
16735        << Prev->isFixed();
16736      Diag(Prev->getLocation(), diag::note_previous_declaration);
16737      return true;
16738    }
16739  
16740    return false;
16741  }
16742  
16743  /// Get diagnostic %select index for tag kind for
16744  /// redeclaration diagnostic message.
16745  /// WARNING: Indexes apply to particular diagnostics only!
16746  ///
16747  /// \returns diagnostic %select index.
getRedeclDiagFromTagKind(TagTypeKind Tag)16748  static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
16749    switch (Tag) {
16750    case TagTypeKind::Struct:
16751      return 0;
16752    case TagTypeKind::Interface:
16753      return 1;
16754    case TagTypeKind::Class:
16755      return 2;
16756    default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
16757    }
16758  }
16759  
16760  /// Determine if tag kind is a class-key compatible with
16761  /// class for redeclaration (class, struct, or __interface).
16762  ///
16763  /// \returns true iff the tag kind is compatible.
isClassCompatTagKind(TagTypeKind Tag)16764  static bool isClassCompatTagKind(TagTypeKind Tag)
16765  {
16766    return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
16767           Tag == TagTypeKind::Interface;
16768  }
16769  
getNonTagTypeDeclKind(const Decl * PrevDecl,TagTypeKind TTK)16770  Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
16771                                               TagTypeKind TTK) {
16772    if (isa<TypedefDecl>(PrevDecl))
16773      return NTK_Typedef;
16774    else if (isa<TypeAliasDecl>(PrevDecl))
16775      return NTK_TypeAlias;
16776    else if (isa<ClassTemplateDecl>(PrevDecl))
16777      return NTK_Template;
16778    else if (isa<TypeAliasTemplateDecl>(PrevDecl))
16779      return NTK_TypeAliasTemplate;
16780    else if (isa<TemplateTemplateParmDecl>(PrevDecl))
16781      return NTK_TemplateTemplateArgument;
16782    switch (TTK) {
16783    case TagTypeKind::Struct:
16784    case TagTypeKind::Interface:
16785    case TagTypeKind::Class:
16786      return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
16787    case TagTypeKind::Union:
16788      return NTK_NonUnion;
16789    case TagTypeKind::Enum:
16790      return NTK_NonEnum;
16791    }
16792    llvm_unreachable("invalid TTK");
16793  }
16794  
isAcceptableTagRedeclaration(const TagDecl * Previous,TagTypeKind NewTag,bool isDefinition,SourceLocation NewTagLoc,const IdentifierInfo * Name)16795  bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
16796                                          TagTypeKind NewTag, bool isDefinition,
16797                                          SourceLocation NewTagLoc,
16798                                          const IdentifierInfo *Name) {
16799    // C++ [dcl.type.elab]p3:
16800    //   The class-key or enum keyword present in the
16801    //   elaborated-type-specifier shall agree in kind with the
16802    //   declaration to which the name in the elaborated-type-specifier
16803    //   refers. This rule also applies to the form of
16804    //   elaborated-type-specifier that declares a class-name or
16805    //   friend class since it can be construed as referring to the
16806    //   definition of the class. Thus, in any
16807    //   elaborated-type-specifier, the enum keyword shall be used to
16808    //   refer to an enumeration (7.2), the union class-key shall be
16809    //   used to refer to a union (clause 9), and either the class or
16810    //   struct class-key shall be used to refer to a class (clause 9)
16811    //   declared using the class or struct class-key.
16812    TagTypeKind OldTag = Previous->getTagKind();
16813    if (OldTag != NewTag &&
16814        !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
16815      return false;
16816  
16817    // Tags are compatible, but we might still want to warn on mismatched tags.
16818    // Non-class tags can't be mismatched at this point.
16819    if (!isClassCompatTagKind(NewTag))
16820      return true;
16821  
16822    // Declarations for which -Wmismatched-tags is disabled are entirely ignored
16823    // by our warning analysis. We don't want to warn about mismatches with (eg)
16824    // declarations in system headers that are designed to be specialized, but if
16825    // a user asks us to warn, we should warn if their code contains mismatched
16826    // declarations.
16827    auto IsIgnoredLoc = [&](SourceLocation Loc) {
16828      return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
16829                                        Loc);
16830    };
16831    if (IsIgnoredLoc(NewTagLoc))
16832      return true;
16833  
16834    auto IsIgnored = [&](const TagDecl *Tag) {
16835      return IsIgnoredLoc(Tag->getLocation());
16836    };
16837    while (IsIgnored(Previous)) {
16838      Previous = Previous->getPreviousDecl();
16839      if (!Previous)
16840        return true;
16841      OldTag = Previous->getTagKind();
16842    }
16843  
16844    bool isTemplate = false;
16845    if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
16846      isTemplate = Record->getDescribedClassTemplate();
16847  
16848    if (inTemplateInstantiation()) {
16849      if (OldTag != NewTag) {
16850        // In a template instantiation, do not offer fix-its for tag mismatches
16851        // since they usually mess up the template instead of fixing the problem.
16852        Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
16853          << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16854          << getRedeclDiagFromTagKind(OldTag);
16855        // FIXME: Note previous location?
16856      }
16857      return true;
16858    }
16859  
16860    if (isDefinition) {
16861      // On definitions, check all previous tags and issue a fix-it for each
16862      // one that doesn't match the current tag.
16863      if (Previous->getDefinition()) {
16864        // Don't suggest fix-its for redefinitions.
16865        return true;
16866      }
16867  
16868      bool previousMismatch = false;
16869      for (const TagDecl *I : Previous->redecls()) {
16870        if (I->getTagKind() != NewTag) {
16871          // Ignore previous declarations for which the warning was disabled.
16872          if (IsIgnored(I))
16873            continue;
16874  
16875          if (!previousMismatch) {
16876            previousMismatch = true;
16877            Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
16878              << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16879              << getRedeclDiagFromTagKind(I->getTagKind());
16880          }
16881          Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
16882            << getRedeclDiagFromTagKind(NewTag)
16883            << FixItHint::CreateReplacement(I->getInnerLocStart(),
16884                 TypeWithKeyword::getTagTypeKindName(NewTag));
16885        }
16886      }
16887      return true;
16888    }
16889  
16890    // Identify the prevailing tag kind: this is the kind of the definition (if
16891    // there is a non-ignored definition), or otherwise the kind of the prior
16892    // (non-ignored) declaration.
16893    const TagDecl *PrevDef = Previous->getDefinition();
16894    if (PrevDef && IsIgnored(PrevDef))
16895      PrevDef = nullptr;
16896    const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
16897    if (Redecl->getTagKind() != NewTag) {
16898      Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
16899        << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16900        << getRedeclDiagFromTagKind(OldTag);
16901      Diag(Redecl->getLocation(), diag::note_previous_use);
16902  
16903      // If there is a previous definition, suggest a fix-it.
16904      if (PrevDef) {
16905        Diag(NewTagLoc, diag::note_struct_class_suggestion)
16906          << getRedeclDiagFromTagKind(Redecl->getTagKind())
16907          << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
16908               TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
16909      }
16910    }
16911  
16912    return true;
16913  }
16914  
16915  /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
16916  /// from an outer enclosing namespace or file scope inside a friend declaration.
16917  /// This should provide the commented out code in the following snippet:
16918  ///   namespace N {
16919  ///     struct X;
16920  ///     namespace M {
16921  ///       struct Y { friend struct /*N::*/ X; };
16922  ///     }
16923  ///   }
createFriendTagNNSFixIt(Sema & SemaRef,NamedDecl * ND,Scope * S,SourceLocation NameLoc)16924  static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
16925                                           SourceLocation NameLoc) {
16926    // While the decl is in a namespace, do repeated lookup of that name and see
16927    // if we get the same namespace back.  If we do not, continue until
16928    // translation unit scope, at which point we have a fully qualified NNS.
16929    SmallVector<IdentifierInfo *, 4> Namespaces;
16930    DeclContext *DC = ND->getDeclContext()->getRedeclContext();
16931    for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
16932      // This tag should be declared in a namespace, which can only be enclosed by
16933      // other namespaces.  Bail if there's an anonymous namespace in the chain.
16934      NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
16935      if (!Namespace || Namespace->isAnonymousNamespace())
16936        return FixItHint();
16937      IdentifierInfo *II = Namespace->getIdentifier();
16938      Namespaces.push_back(II);
16939      NamedDecl *Lookup = SemaRef.LookupSingleName(
16940          S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
16941      if (Lookup == Namespace)
16942        break;
16943    }
16944  
16945    // Once we have all the namespaces, reverse them to go outermost first, and
16946    // build an NNS.
16947    SmallString<64> Insertion;
16948    llvm::raw_svector_ostream OS(Insertion);
16949    if (DC->isTranslationUnit())
16950      OS << "::";
16951    std::reverse(Namespaces.begin(), Namespaces.end());
16952    for (auto *II : Namespaces)
16953      OS << II->getName() << "::";
16954    return FixItHint::CreateInsertion(NameLoc, Insertion);
16955  }
16956  
16957  /// Determine whether a tag originally declared in context \p OldDC can
16958  /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
16959  /// found a declaration in \p OldDC as a previous decl, perhaps through a
16960  /// using-declaration).
isAcceptableTagRedeclContext(Sema & S,DeclContext * OldDC,DeclContext * NewDC)16961  static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
16962                                           DeclContext *NewDC) {
16963    OldDC = OldDC->getRedeclContext();
16964    NewDC = NewDC->getRedeclContext();
16965  
16966    if (OldDC->Equals(NewDC))
16967      return true;
16968  
16969    // In MSVC mode, we allow a redeclaration if the contexts are related (either
16970    // encloses the other).
16971    if (S.getLangOpts().MSVCCompat &&
16972        (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
16973      return true;
16974  
16975    return false;
16976  }
16977  
16978  DeclResult
ActOnTag(Scope * S,unsigned TagSpec,TagUseKind TUK,SourceLocation KWLoc,CXXScopeSpec & SS,IdentifierInfo * Name,SourceLocation NameLoc,const ParsedAttributesView & Attrs,AccessSpecifier AS,SourceLocation ModulePrivateLoc,MultiTemplateParamsArg TemplateParameterLists,bool & OwnedDecl,bool & IsDependent,SourceLocation ScopedEnumKWLoc,bool ScopedEnumUsesClassTag,TypeResult UnderlyingType,bool IsTypeSpecifier,bool IsTemplateParamOrArg,OffsetOfKind OOK,SkipBodyInfo * SkipBody)16979  Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
16980                 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
16981                 const ParsedAttributesView &Attrs, AccessSpecifier AS,
16982                 SourceLocation ModulePrivateLoc,
16983                 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
16984                 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
16985                 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
16986                 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
16987                 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
16988    // If this is not a definition, it must have a name.
16989    IdentifierInfo *OrigName = Name;
16990    assert((Name != nullptr || TUK == TagUseKind::Definition) &&
16991           "Nameless record must be a definition!");
16992    assert(TemplateParameterLists.size() == 0 || TUK != TagUseKind::Reference);
16993  
16994    OwnedDecl = false;
16995    TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16996    bool ScopedEnum = ScopedEnumKWLoc.isValid();
16997  
16998    // FIXME: Check member specializations more carefully.
16999    bool isMemberSpecialization = false;
17000    bool Invalid = false;
17001  
17002    // We only need to do this matching if we have template parameters
17003    // or a scope specifier, which also conveniently avoids this work
17004    // for non-C++ cases.
17005    if (TemplateParameterLists.size() > 0 ||
17006        (SS.isNotEmpty() && TUK != TagUseKind::Reference)) {
17007      TemplateParameterList *TemplateParams =
17008          MatchTemplateParametersToScopeSpecifier(
17009              KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
17010              TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
17011  
17012      // C++23 [dcl.type.elab] p2:
17013      //   If an elaborated-type-specifier is the sole constituent of a
17014      //   declaration, the declaration is ill-formed unless it is an explicit
17015      //   specialization, an explicit instantiation or it has one of the
17016      //   following forms: [...]
17017      // C++23 [dcl.enum] p1:
17018      //   If the enum-head-name of an opaque-enum-declaration contains a
17019      //   nested-name-specifier, the declaration shall be an explicit
17020      //   specialization.
17021      //
17022      // FIXME: Class template partial specializations can be forward declared
17023      // per CWG2213, but the resolution failed to allow qualified forward
17024      // declarations. This is almost certainly unintentional, so we allow them.
17025      if (TUK == TagUseKind::Declaration && SS.isNotEmpty() &&
17026          !isMemberSpecialization)
17027        Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
17028            << TypeWithKeyword::getTagTypeKindName(Kind) << SS.getRange();
17029  
17030      if (TemplateParams) {
17031        if (Kind == TagTypeKind::Enum) {
17032          Diag(KWLoc, diag::err_enum_template);
17033          return true;
17034        }
17035  
17036        if (TemplateParams->size() > 0) {
17037          // This is a declaration or definition of a class template (which may
17038          // be a member of another template).
17039  
17040          if (Invalid)
17041            return true;
17042  
17043          OwnedDecl = false;
17044          DeclResult Result = CheckClassTemplate(
17045              S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
17046              AS, ModulePrivateLoc,
17047              /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
17048              TemplateParameterLists.data(), SkipBody);
17049          return Result.get();
17050        } else {
17051          // The "template<>" header is extraneous.
17052          Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17053            << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17054          isMemberSpecialization = true;
17055        }
17056      }
17057  
17058      if (!TemplateParameterLists.empty() && isMemberSpecialization &&
17059          CheckTemplateDeclScope(S, TemplateParameterLists.back()))
17060        return true;
17061    }
17062  
17063    if (TUK == TagUseKind::Friend && Kind == TagTypeKind::Enum) {
17064      // C++23 [dcl.type.elab]p4:
17065      //   If an elaborated-type-specifier appears with the friend specifier as
17066      //   an entire member-declaration, the member-declaration shall have one
17067      //   of the following forms:
17068      //     friend class-key nested-name-specifier(opt) identifier ;
17069      //     friend class-key simple-template-id ;
17070      //     friend class-key nested-name-specifier template(opt)
17071      //       simple-template-id ;
17072      //
17073      // Since enum is not a class-key, so declarations like "friend enum E;"
17074      // are ill-formed. Although CWG2363 reaffirms that such declarations are
17075      // invalid, most implementations accept so we issue a pedantic warning.
17076      Diag(KWLoc, diag::ext_enum_friend) << FixItHint::CreateRemoval(
17077          ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
17078      assert(ScopedEnum || !ScopedEnumUsesClassTag);
17079      Diag(KWLoc, diag::note_enum_friend)
17080          << (ScopedEnum + ScopedEnumUsesClassTag);
17081    }
17082  
17083    // Figure out the underlying type if this a enum declaration. We need to do
17084    // this early, because it's needed to detect if this is an incompatible
17085    // redeclaration.
17086    llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
17087    bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
17088  
17089    if (Kind == TagTypeKind::Enum) {
17090      if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
17091        // No underlying type explicitly specified, or we failed to parse the
17092        // type, default to int.
17093        EnumUnderlying = Context.IntTy.getTypePtr();
17094      } else if (UnderlyingType.get()) {
17095        // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17096        // integral type; any cv-qualification is ignored.
17097        TypeSourceInfo *TI = nullptr;
17098        GetTypeFromParser(UnderlyingType.get(), &TI);
17099        EnumUnderlying = TI;
17100  
17101        if (CheckEnumUnderlyingType(TI))
17102          // Recover by falling back to int.
17103          EnumUnderlying = Context.IntTy.getTypePtr();
17104  
17105        if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
17106                                            UPPC_FixedUnderlyingType))
17107          EnumUnderlying = Context.IntTy.getTypePtr();
17108  
17109      } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
17110        // For MSVC ABI compatibility, unfixed enums must use an underlying type
17111        // of 'int'. However, if this is an unfixed forward declaration, don't set
17112        // the underlying type unless the user enables -fms-compatibility. This
17113        // makes unfixed forward declared enums incomplete and is more conforming.
17114        if (TUK == TagUseKind::Definition || getLangOpts().MSVCCompat)
17115          EnumUnderlying = Context.IntTy.getTypePtr();
17116      }
17117    }
17118  
17119    DeclContext *SearchDC = CurContext;
17120    DeclContext *DC = CurContext;
17121    bool isStdBadAlloc = false;
17122    bool isStdAlignValT = false;
17123  
17124    RedeclarationKind Redecl = forRedeclarationInCurContext();
17125    if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference)
17126      Redecl = RedeclarationKind::NotForRedeclaration;
17127  
17128    /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
17129    /// implemented asks for structural equivalence checking, the returned decl
17130    /// here is passed back to the parser, allowing the tag body to be parsed.
17131    auto createTagFromNewDecl = [&]() -> TagDecl * {
17132      assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
17133      // If there is an identifier, use the location of the identifier as the
17134      // location of the decl, otherwise use the location of the struct/union
17135      // keyword.
17136      SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17137      TagDecl *New = nullptr;
17138  
17139      if (Kind == TagTypeKind::Enum) {
17140        New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
17141                               ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
17142        // If this is an undefined enum, bail.
17143        if (TUK != TagUseKind::Definition && !Invalid)
17144          return nullptr;
17145        if (EnumUnderlying) {
17146          EnumDecl *ED = cast<EnumDecl>(New);
17147          if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
17148            ED->setIntegerTypeSourceInfo(TI);
17149          else
17150            ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
17151          QualType EnumTy = ED->getIntegerType();
17152          ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
17153                                   ? Context.getPromotedIntegerType(EnumTy)
17154                                   : EnumTy);
17155        }
17156      } else { // struct/union
17157        New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17158                                 nullptr);
17159      }
17160  
17161      if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
17162        // Add alignment attributes if necessary; these attributes are checked
17163        // when the ASTContext lays out the structure.
17164        //
17165        // It is important for implementing the correct semantics that this
17166        // happen here (in ActOnTag). The #pragma pack stack is
17167        // maintained as a result of parser callbacks which can occur at
17168        // many points during the parsing of a struct declaration (because
17169        // the #pragma tokens are effectively skipped over during the
17170        // parsing of the struct).
17171        if (TUK == TagUseKind::Definition &&
17172            (!SkipBody || !SkipBody->ShouldSkip)) {
17173          AddAlignmentAttributesForRecord(RD);
17174          AddMsStructLayoutForRecord(RD);
17175        }
17176      }
17177      New->setLexicalDeclContext(CurContext);
17178      return New;
17179    };
17180  
17181    LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
17182    if (Name && SS.isNotEmpty()) {
17183      // We have a nested-name tag ('struct foo::bar').
17184  
17185      // Check for invalid 'foo::'.
17186      if (SS.isInvalid()) {
17187        Name = nullptr;
17188        goto CreateNewDecl;
17189      }
17190  
17191      // If this is a friend or a reference to a class in a dependent
17192      // context, don't try to make a decl for it.
17193      if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
17194        DC = computeDeclContext(SS, false);
17195        if (!DC) {
17196          IsDependent = true;
17197          return true;
17198        }
17199      } else {
17200        DC = computeDeclContext(SS, true);
17201        if (!DC) {
17202          Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
17203            << SS.getRange();
17204          return true;
17205        }
17206      }
17207  
17208      if (RequireCompleteDeclContext(SS, DC))
17209        return true;
17210  
17211      SearchDC = DC;
17212      // Look-up name inside 'foo::'.
17213      LookupQualifiedName(Previous, DC);
17214  
17215      if (Previous.isAmbiguous())
17216        return true;
17217  
17218      if (Previous.empty()) {
17219        // Name lookup did not find anything. However, if the
17220        // nested-name-specifier refers to the current instantiation,
17221        // and that current instantiation has any dependent base
17222        // classes, we might find something at instantiation time: treat
17223        // this as a dependent elaborated-type-specifier.
17224        // But this only makes any sense for reference-like lookups.
17225        if (Previous.wasNotFoundInCurrentInstantiation() &&
17226            (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)) {
17227          IsDependent = true;
17228          return true;
17229        }
17230  
17231        // A tag 'foo::bar' must already exist.
17232        Diag(NameLoc, diag::err_not_tag_in_scope)
17233            << llvm::to_underlying(Kind) << Name << DC << SS.getRange();
17234        Name = nullptr;
17235        Invalid = true;
17236        goto CreateNewDecl;
17237      }
17238    } else if (Name) {
17239      // C++14 [class.mem]p14:
17240      //   If T is the name of a class, then each of the following shall have a
17241      //   name different from T:
17242      //    -- every member of class T that is itself a type
17243      if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
17244          DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
17245        return true;
17246  
17247      // If this is a named struct, check to see if there was a previous forward
17248      // declaration or definition.
17249      // FIXME: We're looking into outer scopes here, even when we
17250      // shouldn't be. Doing so can result in ambiguities that we
17251      // shouldn't be diagnosing.
17252      LookupName(Previous, S);
17253  
17254      // When declaring or defining a tag, ignore ambiguities introduced
17255      // by types using'ed into this scope.
17256      if (Previous.isAmbiguous() &&
17257          (TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration)) {
17258        LookupResult::Filter F = Previous.makeFilter();
17259        while (F.hasNext()) {
17260          NamedDecl *ND = F.next();
17261          if (!ND->getDeclContext()->getRedeclContext()->Equals(
17262                  SearchDC->getRedeclContext()))
17263            F.erase();
17264        }
17265        F.done();
17266      }
17267  
17268      // C++11 [namespace.memdef]p3:
17269      //   If the name in a friend declaration is neither qualified nor
17270      //   a template-id and the declaration is a function or an
17271      //   elaborated-type-specifier, the lookup to determine whether
17272      //   the entity has been previously declared shall not consider
17273      //   any scopes outside the innermost enclosing namespace.
17274      //
17275      // MSVC doesn't implement the above rule for types, so a friend tag
17276      // declaration may be a redeclaration of a type declared in an enclosing
17277      // scope.  They do implement this rule for friend functions.
17278      //
17279      // Does it matter that this should be by scope instead of by
17280      // semantic context?
17281      if (!Previous.empty() && TUK == TagUseKind::Friend) {
17282        DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
17283        LookupResult::Filter F = Previous.makeFilter();
17284        bool FriendSawTagOutsideEnclosingNamespace = false;
17285        while (F.hasNext()) {
17286          NamedDecl *ND = F.next();
17287          DeclContext *DC = ND->getDeclContext()->getRedeclContext();
17288          if (DC->isFileContext() &&
17289              !EnclosingNS->Encloses(ND->getDeclContext())) {
17290            if (getLangOpts().MSVCCompat)
17291              FriendSawTagOutsideEnclosingNamespace = true;
17292            else
17293              F.erase();
17294          }
17295        }
17296        F.done();
17297  
17298        // Diagnose this MSVC extension in the easy case where lookup would have
17299        // unambiguously found something outside the enclosing namespace.
17300        if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
17301          NamedDecl *ND = Previous.getFoundDecl();
17302          Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
17303              << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
17304        }
17305      }
17306  
17307      // Note:  there used to be some attempt at recovery here.
17308      if (Previous.isAmbiguous())
17309        return true;
17310  
17311      if (!getLangOpts().CPlusPlus && TUK != TagUseKind::Reference) {
17312        // FIXME: This makes sure that we ignore the contexts associated
17313        // with C structs, unions, and enums when looking for a matching
17314        // tag declaration or definition. See the similar lookup tweak
17315        // in Sema::LookupName; is there a better way to deal with this?
17316        while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))
17317          SearchDC = SearchDC->getParent();
17318      } else if (getLangOpts().CPlusPlus) {
17319        // Inside ObjCContainer want to keep it as a lexical decl context but go
17320        // past it (most often to TranslationUnit) to find the semantic decl
17321        // context.
17322        while (isa<ObjCContainerDecl>(SearchDC))
17323          SearchDC = SearchDC->getParent();
17324      }
17325    } else if (getLangOpts().CPlusPlus) {
17326      // Don't use ObjCContainerDecl as the semantic decl context for anonymous
17327      // TagDecl the same way as we skip it for named TagDecl.
17328      while (isa<ObjCContainerDecl>(SearchDC))
17329        SearchDC = SearchDC->getParent();
17330    }
17331  
17332    if (Previous.isSingleResult() &&
17333        Previous.getFoundDecl()->isTemplateParameter()) {
17334      // Maybe we will complain about the shadowed template parameter.
17335      DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
17336      // Just pretend that we didn't see the previous declaration.
17337      Previous.clear();
17338    }
17339  
17340    if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
17341        DC->Equals(getStdNamespace())) {
17342      if (Name->isStr("bad_alloc")) {
17343        // This is a declaration of or a reference to "std::bad_alloc".
17344        isStdBadAlloc = true;
17345  
17346        // If std::bad_alloc has been implicitly declared (but made invisible to
17347        // name lookup), fill in this implicit declaration as the previous
17348        // declaration, so that the declarations get chained appropriately.
17349        if (Previous.empty() && StdBadAlloc)
17350          Previous.addDecl(getStdBadAlloc());
17351      } else if (Name->isStr("align_val_t")) {
17352        isStdAlignValT = true;
17353        if (Previous.empty() && StdAlignValT)
17354          Previous.addDecl(getStdAlignValT());
17355      }
17356    }
17357  
17358    // If we didn't find a previous declaration, and this is a reference
17359    // (or friend reference), move to the correct scope.  In C++, we
17360    // also need to do a redeclaration lookup there, just in case
17361    // there's a shadow friend decl.
17362    if (Name && Previous.empty() &&
17363        (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
17364         IsTemplateParamOrArg)) {
17365      if (Invalid) goto CreateNewDecl;
17366      assert(SS.isEmpty());
17367  
17368      if (TUK == TagUseKind::Reference || IsTemplateParamOrArg) {
17369        // C++ [basic.scope.pdecl]p5:
17370        //   -- for an elaborated-type-specifier of the form
17371        //
17372        //          class-key identifier
17373        //
17374        //      if the elaborated-type-specifier is used in the
17375        //      decl-specifier-seq or parameter-declaration-clause of a
17376        //      function defined in namespace scope, the identifier is
17377        //      declared as a class-name in the namespace that contains
17378        //      the declaration; otherwise, except as a friend
17379        //      declaration, the identifier is declared in the smallest
17380        //      non-class, non-function-prototype scope that contains the
17381        //      declaration.
17382        //
17383        // C99 6.7.2.3p8 has a similar (but not identical!) provision for
17384        // C structs and unions.
17385        //
17386        // It is an error in C++ to declare (rather than define) an enum
17387        // type, including via an elaborated type specifier.  We'll
17388        // diagnose that later; for now, declare the enum in the same
17389        // scope as we would have picked for any other tag type.
17390        //
17391        // GNU C also supports this behavior as part of its incomplete
17392        // enum types extension, while GNU C++ does not.
17393        //
17394        // Find the context where we'll be declaring the tag.
17395        // FIXME: We would like to maintain the current DeclContext as the
17396        // lexical context,
17397        SearchDC = getTagInjectionContext(SearchDC);
17398  
17399        // Find the scope where we'll be declaring the tag.
17400        S = getTagInjectionScope(S, getLangOpts());
17401      } else {
17402        assert(TUK == TagUseKind::Friend);
17403        CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(SearchDC);
17404  
17405        // C++ [namespace.memdef]p3:
17406        //   If a friend declaration in a non-local class first declares a
17407        //   class or function, the friend class or function is a member of
17408        //   the innermost enclosing namespace.
17409        SearchDC = RD->isLocalClass() ? RD->isLocalClass()
17410                                      : SearchDC->getEnclosingNamespaceContext();
17411      }
17412  
17413      // In C++, we need to do a redeclaration lookup to properly
17414      // diagnose some problems.
17415      // FIXME: redeclaration lookup is also used (with and without C++) to find a
17416      // hidden declaration so that we don't get ambiguity errors when using a
17417      // type declared by an elaborated-type-specifier.  In C that is not correct
17418      // and we should instead merge compatible types found by lookup.
17419      if (getLangOpts().CPlusPlus) {
17420        // FIXME: This can perform qualified lookups into function contexts,
17421        // which are meaningless.
17422        Previous.setRedeclarationKind(forRedeclarationInCurContext());
17423        LookupQualifiedName(Previous, SearchDC);
17424      } else {
17425        Previous.setRedeclarationKind(forRedeclarationInCurContext());
17426        LookupName(Previous, S);
17427      }
17428    }
17429  
17430    // If we have a known previous declaration to use, then use it.
17431    if (Previous.empty() && SkipBody && SkipBody->Previous)
17432      Previous.addDecl(SkipBody->Previous);
17433  
17434    if (!Previous.empty()) {
17435      NamedDecl *PrevDecl = Previous.getFoundDecl();
17436      NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
17437  
17438      // It's okay to have a tag decl in the same scope as a typedef
17439      // which hides a tag decl in the same scope.  Finding this
17440      // with a redeclaration lookup can only actually happen in C++.
17441      //
17442      // This is also okay for elaborated-type-specifiers, which is
17443      // technically forbidden by the current standard but which is
17444      // okay according to the likely resolution of an open issue;
17445      // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
17446      if (getLangOpts().CPlusPlus) {
17447        if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17448          if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
17449            TagDecl *Tag = TT->getDecl();
17450            if (Tag->getDeclName() == Name &&
17451                Tag->getDeclContext()->getRedeclContext()
17452                            ->Equals(TD->getDeclContext()->getRedeclContext())) {
17453              PrevDecl = Tag;
17454              Previous.clear();
17455              Previous.addDecl(Tag);
17456              Previous.resolveKind();
17457            }
17458          }
17459        }
17460      }
17461  
17462      // If this is a redeclaration of a using shadow declaration, it must
17463      // declare a tag in the same context. In MSVC mode, we allow a
17464      // redefinition if either context is within the other.
17465      if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
17466        auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
17467        if (SS.isEmpty() && TUK != TagUseKind::Reference &&
17468            TUK != TagUseKind::Friend &&
17469            isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
17470            !(OldTag && isAcceptableTagRedeclContext(
17471                            *this, OldTag->getDeclContext(), SearchDC))) {
17472          Diag(KWLoc, diag::err_using_decl_conflict_reverse);
17473          Diag(Shadow->getTargetDecl()->getLocation(),
17474               diag::note_using_decl_target);
17475          Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
17476              << 0;
17477          // Recover by ignoring the old declaration.
17478          Previous.clear();
17479          goto CreateNewDecl;
17480        }
17481      }
17482  
17483      if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
17484        // If this is a use of a previous tag, or if the tag is already declared
17485        // in the same scope (so that the definition/declaration completes or
17486        // rementions the tag), reuse the decl.
17487        if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
17488            isDeclInScope(DirectPrevDecl, SearchDC, S,
17489                          SS.isNotEmpty() || isMemberSpecialization)) {
17490          // Make sure that this wasn't declared as an enum and now used as a
17491          // struct or something similar.
17492          if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
17493                                            TUK == TagUseKind::Definition, KWLoc,
17494                                            Name)) {
17495            bool SafeToContinue =
17496                (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
17497                 Kind != TagTypeKind::Enum);
17498            if (SafeToContinue)
17499              Diag(KWLoc, diag::err_use_with_wrong_tag)
17500                << Name
17501                << FixItHint::CreateReplacement(SourceRange(KWLoc),
17502                                                PrevTagDecl->getKindName());
17503            else
17504              Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
17505            Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
17506  
17507            if (SafeToContinue)
17508              Kind = PrevTagDecl->getTagKind();
17509            else {
17510              // Recover by making this an anonymous redefinition.
17511              Name = nullptr;
17512              Previous.clear();
17513              Invalid = true;
17514            }
17515          }
17516  
17517          if (Kind == TagTypeKind::Enum &&
17518              PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
17519            const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
17520            if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)
17521              return PrevTagDecl;
17522  
17523            QualType EnumUnderlyingTy;
17524            if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
17525              EnumUnderlyingTy = TI->getType().getUnqualifiedType();
17526            else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
17527              EnumUnderlyingTy = QualType(T, 0);
17528  
17529            // All conflicts with previous declarations are recovered by
17530            // returning the previous declaration, unless this is a definition,
17531            // in which case we want the caller to bail out.
17532            if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
17533                                       ScopedEnum, EnumUnderlyingTy,
17534                                       IsFixed, PrevEnum))
17535              return TUK == TagUseKind::Declaration ? PrevTagDecl : nullptr;
17536          }
17537  
17538          // C++11 [class.mem]p1:
17539          //   A member shall not be declared twice in the member-specification,
17540          //   except that a nested class or member class template can be declared
17541          //   and then later defined.
17542          if (TUK == TagUseKind::Declaration && PrevDecl->isCXXClassMember() &&
17543              S->isDeclScope(PrevDecl)) {
17544            Diag(NameLoc, diag::ext_member_redeclared);
17545            Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
17546          }
17547  
17548          if (!Invalid) {
17549            // If this is a use, just return the declaration we found, unless
17550            // we have attributes.
17551            if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
17552              if (!Attrs.empty()) {
17553                // FIXME: Diagnose these attributes. For now, we create a new
17554                // declaration to hold them.
17555              } else if (TUK == TagUseKind::Reference &&
17556                         (PrevTagDecl->getFriendObjectKind() ==
17557                              Decl::FOK_Undeclared ||
17558                          PrevDecl->getOwningModule() != getCurrentModule()) &&
17559                         SS.isEmpty()) {
17560                // This declaration is a reference to an existing entity, but
17561                // has different visibility from that entity: it either makes
17562                // a friend visible or it makes a type visible in a new module.
17563                // In either case, create a new declaration. We only do this if
17564                // the declaration would have meant the same thing if no prior
17565                // declaration were found, that is, if it was found in the same
17566                // scope where we would have injected a declaration.
17567                if (!getTagInjectionContext(CurContext)->getRedeclContext()
17568                         ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
17569                  return PrevTagDecl;
17570                // This is in the injected scope, create a new declaration in
17571                // that scope.
17572                S = getTagInjectionScope(S, getLangOpts());
17573              } else {
17574                return PrevTagDecl;
17575              }
17576            }
17577  
17578            // Diagnose attempts to redefine a tag.
17579            if (TUK == TagUseKind::Definition) {
17580              if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
17581                // If we're defining a specialization and the previous definition
17582                // is from an implicit instantiation, don't emit an error
17583                // here; we'll catch this in the general case below.
17584                bool IsExplicitSpecializationAfterInstantiation = false;
17585                if (isMemberSpecialization) {
17586                  if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
17587                    IsExplicitSpecializationAfterInstantiation =
17588                      RD->getTemplateSpecializationKind() !=
17589                      TSK_ExplicitSpecialization;
17590                  else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
17591                    IsExplicitSpecializationAfterInstantiation =
17592                      ED->getTemplateSpecializationKind() !=
17593                      TSK_ExplicitSpecialization;
17594                }
17595  
17596                // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
17597                // not keep more that one definition around (merge them). However,
17598                // ensure the decl passes the structural compatibility check in
17599                // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
17600                NamedDecl *Hidden = nullptr;
17601                if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
17602                  // There is a definition of this tag, but it is not visible. We
17603                  // explicitly make use of C++'s one definition rule here, and
17604                  // assume that this definition is identical to the hidden one
17605                  // we already have. Make the existing definition visible and
17606                  // use it in place of this one.
17607                  if (!getLangOpts().CPlusPlus) {
17608                    // Postpone making the old definition visible until after we
17609                    // complete parsing the new one and do the structural
17610                    // comparison.
17611                    SkipBody->CheckSameAsPrevious = true;
17612                    SkipBody->New = createTagFromNewDecl();
17613                    SkipBody->Previous = Def;
17614                    return Def;
17615                  } else {
17616                    SkipBody->ShouldSkip = true;
17617                    SkipBody->Previous = Def;
17618                    makeMergedDefinitionVisible(Hidden);
17619                    // Carry on and handle it like a normal definition. We'll
17620                    // skip starting the definition later.
17621                  }
17622                } else if (!IsExplicitSpecializationAfterInstantiation) {
17623                  // A redeclaration in function prototype scope in C isn't
17624                  // visible elsewhere, so merely issue a warning.
17625                  if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
17626                    Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
17627                  else
17628                    Diag(NameLoc, diag::err_redefinition) << Name;
17629                  notePreviousDefinition(Def,
17630                                         NameLoc.isValid() ? NameLoc : KWLoc);
17631                  // If this is a redefinition, recover by making this
17632                  // struct be anonymous, which will make any later
17633                  // references get the previous definition.
17634                  Name = nullptr;
17635                  Previous.clear();
17636                  Invalid = true;
17637                }
17638              } else {
17639                // If the type is currently being defined, complain
17640                // about a nested redefinition.
17641                auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
17642                if (TD->isBeingDefined()) {
17643                  Diag(NameLoc, diag::err_nested_redefinition) << Name;
17644                  Diag(PrevTagDecl->getLocation(),
17645                       diag::note_previous_definition);
17646                  Name = nullptr;
17647                  Previous.clear();
17648                  Invalid = true;
17649                }
17650              }
17651  
17652              // Okay, this is definition of a previously declared or referenced
17653              // tag. We're going to create a new Decl for it.
17654            }
17655  
17656            // Okay, we're going to make a redeclaration.  If this is some kind
17657            // of reference, make sure we build the redeclaration in the same DC
17658            // as the original, and ignore the current access specifier.
17659            if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
17660              SearchDC = PrevTagDecl->getDeclContext();
17661              AS = AS_none;
17662            }
17663          }
17664          // If we get here we have (another) forward declaration or we
17665          // have a definition.  Just create a new decl.
17666  
17667        } else {
17668          // If we get here, this is a definition of a new tag type in a nested
17669          // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
17670          // new decl/type.  We set PrevDecl to NULL so that the entities
17671          // have distinct types.
17672          Previous.clear();
17673        }
17674        // If we get here, we're going to create a new Decl. If PrevDecl
17675        // is non-NULL, it's a definition of the tag declared by
17676        // PrevDecl. If it's NULL, we have a new definition.
17677  
17678      // Otherwise, PrevDecl is not a tag, but was found with tag
17679      // lookup.  This is only actually possible in C++, where a few
17680      // things like templates still live in the tag namespace.
17681      } else {
17682        // Use a better diagnostic if an elaborated-type-specifier
17683        // found the wrong kind of type on the first
17684        // (non-redeclaration) lookup.
17685        if ((TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) &&
17686            !Previous.isForRedeclaration()) {
17687          NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17688          Diag(NameLoc, diag::err_tag_reference_non_tag)
17689              << PrevDecl << NTK << llvm::to_underlying(Kind);
17690          Diag(PrevDecl->getLocation(), diag::note_declared_at);
17691          Invalid = true;
17692  
17693        // Otherwise, only diagnose if the declaration is in scope.
17694        } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
17695                                  SS.isNotEmpty() || isMemberSpecialization)) {
17696          // do nothing
17697  
17698        // Diagnose implicit declarations introduced by elaborated types.
17699        } else if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
17700          NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17701          Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
17702          Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17703          Invalid = true;
17704  
17705        // Otherwise it's a declaration.  Call out a particularly common
17706        // case here.
17707        } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17708          unsigned Kind = 0;
17709          if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
17710          Diag(NameLoc, diag::err_tag_definition_of_typedef)
17711            << Name << Kind << TND->getUnderlyingType();
17712          Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17713          Invalid = true;
17714  
17715        // Otherwise, diagnose.
17716        } else {
17717          // The tag name clashes with something else in the target scope,
17718          // issue an error and recover by making this tag be anonymous.
17719          Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
17720          notePreviousDefinition(PrevDecl, NameLoc);
17721          Name = nullptr;
17722          Invalid = true;
17723        }
17724  
17725        // The existing declaration isn't relevant to us; we're in a
17726        // new scope, so clear out the previous declaration.
17727        Previous.clear();
17728      }
17729    }
17730  
17731  CreateNewDecl:
17732  
17733    TagDecl *PrevDecl = nullptr;
17734    if (Previous.isSingleResult())
17735      PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
17736  
17737    // If there is an identifier, use the location of the identifier as the
17738    // location of the decl, otherwise use the location of the struct/union
17739    // keyword.
17740    SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17741  
17742    // Otherwise, create a new declaration. If there is a previous
17743    // declaration of the same entity, the two will be linked via
17744    // PrevDecl.
17745    TagDecl *New;
17746  
17747    if (Kind == TagTypeKind::Enum) {
17748      // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17749      // enum X { A, B, C } D;    D should chain to X.
17750      New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
17751                             cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
17752                             ScopedEnumUsesClassTag, IsFixed);
17753  
17754      if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
17755        StdAlignValT = cast<EnumDecl>(New);
17756  
17757      // If this is an undefined enum, warn.
17758      if (TUK != TagUseKind::Definition && !Invalid) {
17759        TagDecl *Def;
17760        if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
17761          // C++0x: 7.2p2: opaque-enum-declaration.
17762          // Conflicts are diagnosed above. Do nothing.
17763        }
17764        else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
17765          Diag(Loc, diag::ext_forward_ref_enum_def)
17766            << New;
17767          Diag(Def->getLocation(), diag::note_previous_definition);
17768        } else {
17769          unsigned DiagID = diag::ext_forward_ref_enum;
17770          if (getLangOpts().MSVCCompat)
17771            DiagID = diag::ext_ms_forward_ref_enum;
17772          else if (getLangOpts().CPlusPlus)
17773            DiagID = diag::err_forward_ref_enum;
17774          Diag(Loc, DiagID);
17775        }
17776      }
17777  
17778      if (EnumUnderlying) {
17779        EnumDecl *ED = cast<EnumDecl>(New);
17780        if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
17781          ED->setIntegerTypeSourceInfo(TI);
17782        else
17783          ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
17784        QualType EnumTy = ED->getIntegerType();
17785        ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
17786                                 ? Context.getPromotedIntegerType(EnumTy)
17787                                 : EnumTy);
17788        assert(ED->isComplete() && "enum with type should be complete");
17789      }
17790    } else {
17791      // struct/union/class
17792  
17793      // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17794      // struct X { int A; } D;    D should chain to X.
17795      if (getLangOpts().CPlusPlus) {
17796        // FIXME: Look for a way to use RecordDecl for simple structs.
17797        New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17798                                    cast_or_null<CXXRecordDecl>(PrevDecl));
17799  
17800        if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
17801          StdBadAlloc = cast<CXXRecordDecl>(New);
17802      } else
17803        New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17804                                 cast_or_null<RecordDecl>(PrevDecl));
17805    }
17806  
17807    // Only C23 and later allow defining new types in 'offsetof()'.
17808    if (OOK != OOK_Outside && TUK == TagUseKind::Definition &&
17809        !getLangOpts().CPlusPlus && !getLangOpts().C23)
17810      Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
17811          << (OOK == OOK_Macro) << New->getSourceRange();
17812  
17813    // C++11 [dcl.type]p3:
17814    //   A type-specifier-seq shall not define a class or enumeration [...].
17815    if (!Invalid && getLangOpts().CPlusPlus &&
17816        (IsTypeSpecifier || IsTemplateParamOrArg) &&
17817        TUK == TagUseKind::Definition) {
17818      Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
17819        << Context.getTagDeclType(New);
17820      Invalid = true;
17821    }
17822  
17823    if (!Invalid && getLangOpts().CPlusPlus && TUK == TagUseKind::Definition &&
17824        DC->getDeclKind() == Decl::Enum) {
17825      Diag(New->getLocation(), diag::err_type_defined_in_enum)
17826        << Context.getTagDeclType(New);
17827      Invalid = true;
17828    }
17829  
17830    // Maybe add qualifier info.
17831    if (SS.isNotEmpty()) {
17832      if (SS.isSet()) {
17833        // If this is either a declaration or a definition, check the
17834        // nested-name-specifier against the current context.
17835        if ((TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration) &&
17836            diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
17837                                         /*TemplateId=*/nullptr,
17838                                         isMemberSpecialization))
17839          Invalid = true;
17840  
17841        New->setQualifierInfo(SS.getWithLocInContext(Context));
17842        if (TemplateParameterLists.size() > 0) {
17843          New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
17844        }
17845      }
17846      else
17847        Invalid = true;
17848    }
17849  
17850    if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
17851      // Add alignment attributes if necessary; these attributes are checked when
17852      // the ASTContext lays out the structure.
17853      //
17854      // It is important for implementing the correct semantics that this
17855      // happen here (in ActOnTag). The #pragma pack stack is
17856      // maintained as a result of parser callbacks which can occur at
17857      // many points during the parsing of a struct declaration (because
17858      // the #pragma tokens are effectively skipped over during the
17859      // parsing of the struct).
17860      if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
17861        AddAlignmentAttributesForRecord(RD);
17862        AddMsStructLayoutForRecord(RD);
17863      }
17864    }
17865  
17866    if (ModulePrivateLoc.isValid()) {
17867      if (isMemberSpecialization)
17868        Diag(New->getLocation(), diag::err_module_private_specialization)
17869          << 2
17870          << FixItHint::CreateRemoval(ModulePrivateLoc);
17871      // __module_private__ does not apply to local classes. However, we only
17872      // diagnose this as an error when the declaration specifiers are
17873      // freestanding. Here, we just ignore the __module_private__.
17874      else if (!SearchDC->isFunctionOrMethod())
17875        New->setModulePrivate();
17876    }
17877  
17878    // If this is a specialization of a member class (of a class template),
17879    // check the specialization.
17880    if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
17881      Invalid = true;
17882  
17883    // If we're declaring or defining a tag in function prototype scope in C,
17884    // note that this type can only be used within the function and add it to
17885    // the list of decls to inject into the function definition scope.
17886    if ((Name || Kind == TagTypeKind::Enum) &&
17887        getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
17888      if (getLangOpts().CPlusPlus) {
17889        // C++ [dcl.fct]p6:
17890        //   Types shall not be defined in return or parameter types.
17891        if (TUK == TagUseKind::Definition && !IsTypeSpecifier) {
17892          Diag(Loc, diag::err_type_defined_in_param_type)
17893              << Name;
17894          Invalid = true;
17895        }
17896      } else if (!PrevDecl) {
17897        Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
17898      }
17899    }
17900  
17901    if (Invalid)
17902      New->setInvalidDecl();
17903  
17904    // Set the lexical context. If the tag has a C++ scope specifier, the
17905    // lexical context will be different from the semantic context.
17906    New->setLexicalDeclContext(CurContext);
17907  
17908    // Mark this as a friend decl if applicable.
17909    // In Microsoft mode, a friend declaration also acts as a forward
17910    // declaration so we always pass true to setObjectOfFriendDecl to make
17911    // the tag name visible.
17912    if (TUK == TagUseKind::Friend)
17913      New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
17914  
17915    // Set the access specifier.
17916    if (!Invalid && SearchDC->isRecord())
17917      SetMemberAccessSpecifier(New, PrevDecl, AS);
17918  
17919    if (PrevDecl)
17920      CheckRedeclarationInModule(New, PrevDecl);
17921  
17922    if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
17923      New->startDefinition();
17924  
17925    ProcessDeclAttributeList(S, New, Attrs);
17926    AddPragmaAttributes(S, New);
17927  
17928    // If this has an identifier, add it to the scope stack.
17929    if (TUK == TagUseKind::Friend) {
17930      // We might be replacing an existing declaration in the lookup tables;
17931      // if so, borrow its access specifier.
17932      if (PrevDecl)
17933        New->setAccess(PrevDecl->getAccess());
17934  
17935      DeclContext *DC = New->getDeclContext()->getRedeclContext();
17936      DC->makeDeclVisibleInContext(New);
17937      if (Name) // can be null along some error paths
17938        if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
17939          PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
17940    } else if (Name) {
17941      S = getNonFieldDeclScope(S);
17942      PushOnScopeChains(New, S, true);
17943    } else {
17944      CurContext->addDecl(New);
17945    }
17946  
17947    // If this is the C FILE type, notify the AST context.
17948    if (IdentifierInfo *II = New->getIdentifier())
17949      if (!New->isInvalidDecl() &&
17950          New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
17951          II->isStr("FILE"))
17952        Context.setFILEDecl(New);
17953  
17954    if (PrevDecl)
17955      mergeDeclAttributes(New, PrevDecl);
17956  
17957    if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) {
17958      inferGslOwnerPointerAttribute(CXXRD);
17959      inferNullableClassAttribute(CXXRD);
17960    }
17961  
17962    // If there's a #pragma GCC visibility in scope, set the visibility of this
17963    // record.
17964    AddPushedVisibilityAttribute(New);
17965  
17966    if (isMemberSpecialization && !New->isInvalidDecl())
17967      CompleteMemberSpecialization(New, Previous);
17968  
17969    OwnedDecl = true;
17970    // In C++, don't return an invalid declaration. We can't recover well from
17971    // the cases where we make the type anonymous.
17972    if (Invalid && getLangOpts().CPlusPlus) {
17973      if (New->isBeingDefined())
17974        if (auto RD = dyn_cast<RecordDecl>(New))
17975          RD->completeDefinition();
17976      return true;
17977    } else if (SkipBody && SkipBody->ShouldSkip) {
17978      return SkipBody->Previous;
17979    } else {
17980      return New;
17981    }
17982  }
17983  
ActOnTagStartDefinition(Scope * S,Decl * TagD)17984  void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
17985    AdjustDeclIfTemplate(TagD);
17986    TagDecl *Tag = cast<TagDecl>(TagD);
17987  
17988    // Enter the tag context.
17989    PushDeclContext(S, Tag);
17990  
17991    ActOnDocumentableDecl(TagD);
17992  
17993    // If there's a #pragma GCC visibility in scope, set the visibility of this
17994    // record.
17995    AddPushedVisibilityAttribute(Tag);
17996  }
17997  
ActOnDuplicateDefinition(Decl * Prev,SkipBodyInfo & SkipBody)17998  bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody) {
17999    if (!hasStructuralCompatLayout(Prev, SkipBody.New))
18000      return false;
18001  
18002    // Make the previous decl visible.
18003    makeMergedDefinitionVisible(SkipBody.Previous);
18004    return true;
18005  }
18006  
ActOnStartCXXMemberDeclarations(Scope * S,Decl * TagD,SourceLocation FinalLoc,bool IsFinalSpelledSealed,bool IsAbstract,SourceLocation LBraceLoc)18007  void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
18008                                             SourceLocation FinalLoc,
18009                                             bool IsFinalSpelledSealed,
18010                                             bool IsAbstract,
18011                                             SourceLocation LBraceLoc) {
18012    AdjustDeclIfTemplate(TagD);
18013    CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
18014  
18015    FieldCollector->StartClass();
18016  
18017    if (!Record->getIdentifier())
18018      return;
18019  
18020    if (IsAbstract)
18021      Record->markAbstract();
18022  
18023    if (FinalLoc.isValid()) {
18024      Record->addAttr(FinalAttr::Create(Context, FinalLoc,
18025                                        IsFinalSpelledSealed
18026                                            ? FinalAttr::Keyword_sealed
18027                                            : FinalAttr::Keyword_final));
18028    }
18029    // C++ [class]p2:
18030    //   [...] The class-name is also inserted into the scope of the
18031    //   class itself; this is known as the injected-class-name. For
18032    //   purposes of access checking, the injected-class-name is treated
18033    //   as if it were a public member name.
18034    CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
18035        Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
18036        Record->getLocation(), Record->getIdentifier(),
18037        /*PrevDecl=*/nullptr,
18038        /*DelayTypeCreation=*/true);
18039    Context.getTypeDeclType(InjectedClassName, Record);
18040    InjectedClassName->setImplicit();
18041    InjectedClassName->setAccess(AS_public);
18042    if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
18043        InjectedClassName->setDescribedClassTemplate(Template);
18044    PushOnScopeChains(InjectedClassName, S);
18045    assert(InjectedClassName->isInjectedClassName() &&
18046           "Broken injected-class-name");
18047  }
18048  
ActOnTagFinishDefinition(Scope * S,Decl * TagD,SourceRange BraceRange)18049  void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
18050                                      SourceRange BraceRange) {
18051    AdjustDeclIfTemplate(TagD);
18052    TagDecl *Tag = cast<TagDecl>(TagD);
18053    Tag->setBraceRange(BraceRange);
18054  
18055    // Make sure we "complete" the definition even it is invalid.
18056    if (Tag->isBeingDefined()) {
18057      assert(Tag->isInvalidDecl() && "We should already have completed it");
18058      if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18059        RD->completeDefinition();
18060    }
18061  
18062    if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
18063      FieldCollector->FinishClass();
18064      if (RD->hasAttr<SYCLSpecialClassAttr>()) {
18065        auto *Def = RD->getDefinition();
18066        assert(Def && "The record is expected to have a completed definition");
18067        unsigned NumInitMethods = 0;
18068        for (auto *Method : Def->methods()) {
18069          if (!Method->getIdentifier())
18070              continue;
18071          if (Method->getName() == "__init")
18072            NumInitMethods++;
18073        }
18074        if (NumInitMethods > 1 || !Def->hasInitMethod())
18075          Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
18076      }
18077  
18078      // If we're defining a dynamic class in a module interface unit, we always
18079      // need to produce the vtable for it, even if the vtable is not used in the
18080      // current TU.
18081      //
18082      // The case where the current class is not dynamic is handled in
18083      // MarkVTableUsed.
18084      if (getCurrentModule() && getCurrentModule()->isInterfaceOrPartition())
18085        MarkVTableUsed(RD->getLocation(), RD, /*DefinitionRequired=*/true);
18086    }
18087  
18088    // Exit this scope of this tag's definition.
18089    PopDeclContext();
18090  
18091    if (getCurLexicalContext()->isObjCContainer() &&
18092        Tag->getDeclContext()->isFileContext())
18093      Tag->setTopLevelDeclInObjCContainer();
18094  
18095    // Notify the consumer that we've defined a tag.
18096    if (!Tag->isInvalidDecl())
18097      Consumer.HandleTagDeclDefinition(Tag);
18098  
18099    // Clangs implementation of #pragma align(packed) differs in bitfield layout
18100    // from XLs and instead matches the XL #pragma pack(1) behavior.
18101    if (Context.getTargetInfo().getTriple().isOSAIX() &&
18102        AlignPackStack.hasValue()) {
18103      AlignPackInfo APInfo = AlignPackStack.CurrentValue;
18104      // Only diagnose #pragma align(packed).
18105      if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
18106        return;
18107      const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
18108      if (!RD)
18109        return;
18110      // Only warn if there is at least 1 bitfield member.
18111      if (llvm::any_of(RD->fields(),
18112                       [](const FieldDecl *FD) { return FD->isBitField(); }))
18113        Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
18114    }
18115  }
18116  
ActOnTagDefinitionError(Scope * S,Decl * TagD)18117  void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
18118    AdjustDeclIfTemplate(TagD);
18119    TagDecl *Tag = cast<TagDecl>(TagD);
18120    Tag->setInvalidDecl();
18121  
18122    // Make sure we "complete" the definition even it is invalid.
18123    if (Tag->isBeingDefined()) {
18124      if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18125        RD->completeDefinition();
18126    }
18127  
18128    // We're undoing ActOnTagStartDefinition here, not
18129    // ActOnStartCXXMemberDeclarations, so we don't have to mess with
18130    // the FieldCollector.
18131  
18132    PopDeclContext();
18133  }
18134  
18135  // Note that FieldName may be null for anonymous bitfields.
VerifyBitField(SourceLocation FieldLoc,const IdentifierInfo * FieldName,QualType FieldTy,bool IsMsStruct,Expr * BitWidth)18136  ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
18137                                  const IdentifierInfo *FieldName,
18138                                  QualType FieldTy, bool IsMsStruct,
18139                                  Expr *BitWidth) {
18140    assert(BitWidth);
18141    if (BitWidth->containsErrors())
18142      return ExprError();
18143  
18144    // C99 6.7.2.1p4 - verify the field type.
18145    // C++ 9.6p3: A bit-field shall have integral or enumeration type.
18146    if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
18147      // Handle incomplete and sizeless types with a specific error.
18148      if (RequireCompleteSizedType(FieldLoc, FieldTy,
18149                                   diag::err_field_incomplete_or_sizeless))
18150        return ExprError();
18151      if (FieldName)
18152        return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
18153          << FieldName << FieldTy << BitWidth->getSourceRange();
18154      return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
18155        << FieldTy << BitWidth->getSourceRange();
18156    } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
18157                                               UPPC_BitFieldWidth))
18158      return ExprError();
18159  
18160    // If the bit-width is type- or value-dependent, don't try to check
18161    // it now.
18162    if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
18163      return BitWidth;
18164  
18165    llvm::APSInt Value;
18166    ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
18167    if (ICE.isInvalid())
18168      return ICE;
18169    BitWidth = ICE.get();
18170  
18171    // Zero-width bitfield is ok for anonymous field.
18172    if (Value == 0 && FieldName)
18173      return Diag(FieldLoc, diag::err_bitfield_has_zero_width)
18174             << FieldName << BitWidth->getSourceRange();
18175  
18176    if (Value.isSigned() && Value.isNegative()) {
18177      if (FieldName)
18178        return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
18179                 << FieldName << toString(Value, 10);
18180      return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
18181        << toString(Value, 10);
18182    }
18183  
18184    // The size of the bit-field must not exceed our maximum permitted object
18185    // size.
18186    if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
18187      return Diag(FieldLoc, diag::err_bitfield_too_wide)
18188             << !FieldName << FieldName << toString(Value, 10);
18189    }
18190  
18191    if (!FieldTy->isDependentType()) {
18192      uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
18193      uint64_t TypeWidth = Context.getIntWidth(FieldTy);
18194      bool BitfieldIsOverwide = Value.ugt(TypeWidth);
18195  
18196      // Over-wide bitfields are an error in C or when using the MSVC bitfield
18197      // ABI.
18198      bool CStdConstraintViolation =
18199          BitfieldIsOverwide && !getLangOpts().CPlusPlus;
18200      bool MSBitfieldViolation =
18201          Value.ugt(TypeStorageSize) &&
18202          (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
18203      if (CStdConstraintViolation || MSBitfieldViolation) {
18204        unsigned DiagWidth =
18205            CStdConstraintViolation ? TypeWidth : TypeStorageSize;
18206        return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
18207               << (bool)FieldName << FieldName << toString(Value, 10)
18208               << !CStdConstraintViolation << DiagWidth;
18209      }
18210  
18211      // Warn on types where the user might conceivably expect to get all
18212      // specified bits as value bits: that's all integral types other than
18213      // 'bool'.
18214      if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
18215        Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
18216            << FieldName << toString(Value, 10)
18217            << (unsigned)TypeWidth;
18218      }
18219    }
18220  
18221    return BitWidth;
18222  }
18223  
ActOnField(Scope * S,Decl * TagD,SourceLocation DeclStart,Declarator & D,Expr * BitfieldWidth)18224  Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
18225                         Declarator &D, Expr *BitfieldWidth) {
18226    FieldDecl *Res = HandleField(S, cast_if_present<RecordDecl>(TagD), DeclStart,
18227                                 D, BitfieldWidth,
18228                                 /*InitStyle=*/ICIS_NoInit, AS_public);
18229    return Res;
18230  }
18231  
HandleField(Scope * S,RecordDecl * Record,SourceLocation DeclStart,Declarator & D,Expr * BitWidth,InClassInitStyle InitStyle,AccessSpecifier AS)18232  FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
18233                               SourceLocation DeclStart,
18234                               Declarator &D, Expr *BitWidth,
18235                               InClassInitStyle InitStyle,
18236                               AccessSpecifier AS) {
18237    if (D.isDecompositionDeclarator()) {
18238      const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
18239      Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
18240        << Decomp.getSourceRange();
18241      return nullptr;
18242    }
18243  
18244    const IdentifierInfo *II = D.getIdentifier();
18245    SourceLocation Loc = DeclStart;
18246    if (II) Loc = D.getIdentifierLoc();
18247  
18248    TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
18249    QualType T = TInfo->getType();
18250    if (getLangOpts().CPlusPlus) {
18251      CheckExtraCXXDefaultArguments(D);
18252  
18253      if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
18254                                          UPPC_DataMemberType)) {
18255        D.setInvalidType();
18256        T = Context.IntTy;
18257        TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
18258      }
18259    }
18260  
18261    DiagnoseFunctionSpecifiers(D.getDeclSpec());
18262  
18263    if (D.getDeclSpec().isInlineSpecified())
18264      Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18265          << getLangOpts().CPlusPlus17;
18266    if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
18267      Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
18268           diag::err_invalid_thread)
18269        << DeclSpec::getSpecifierName(TSCS);
18270  
18271    // Check to see if this name was declared as a member previously
18272    NamedDecl *PrevDecl = nullptr;
18273    LookupResult Previous(*this, II, Loc, LookupMemberName,
18274                          RedeclarationKind::ForVisibleRedeclaration);
18275    LookupName(Previous, S);
18276    switch (Previous.getResultKind()) {
18277      case LookupResult::Found:
18278      case LookupResult::FoundUnresolvedValue:
18279        PrevDecl = Previous.getAsSingle<NamedDecl>();
18280        break;
18281  
18282      case LookupResult::FoundOverloaded:
18283        PrevDecl = Previous.getRepresentativeDecl();
18284        break;
18285  
18286      case LookupResult::NotFound:
18287      case LookupResult::NotFoundInCurrentInstantiation:
18288      case LookupResult::Ambiguous:
18289        break;
18290    }
18291    Previous.suppressDiagnostics();
18292  
18293    if (PrevDecl && PrevDecl->isTemplateParameter()) {
18294      // Maybe we will complain about the shadowed template parameter.
18295      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
18296      // Just pretend that we didn't see the previous declaration.
18297      PrevDecl = nullptr;
18298    }
18299  
18300    if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18301      PrevDecl = nullptr;
18302  
18303    bool Mutable
18304      = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
18305    SourceLocation TSSL = D.getBeginLoc();
18306    FieldDecl *NewFD
18307      = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
18308                       TSSL, AS, PrevDecl, &D);
18309  
18310    if (NewFD->isInvalidDecl())
18311      Record->setInvalidDecl();
18312  
18313    if (D.getDeclSpec().isModulePrivateSpecified())
18314      NewFD->setModulePrivate();
18315  
18316    if (NewFD->isInvalidDecl() && PrevDecl) {
18317      // Don't introduce NewFD into scope; there's already something
18318      // with the same name in the same scope.
18319    } else if (II) {
18320      PushOnScopeChains(NewFD, S);
18321    } else
18322      Record->addDecl(NewFD);
18323  
18324    return NewFD;
18325  }
18326  
CheckFieldDecl(DeclarationName Name,QualType T,TypeSourceInfo * TInfo,RecordDecl * Record,SourceLocation Loc,bool Mutable,Expr * BitWidth,InClassInitStyle InitStyle,SourceLocation TSSL,AccessSpecifier AS,NamedDecl * PrevDecl,Declarator * D)18327  FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
18328                                  TypeSourceInfo *TInfo,
18329                                  RecordDecl *Record, SourceLocation Loc,
18330                                  bool Mutable, Expr *BitWidth,
18331                                  InClassInitStyle InitStyle,
18332                                  SourceLocation TSSL,
18333                                  AccessSpecifier AS, NamedDecl *PrevDecl,
18334                                  Declarator *D) {
18335    const IdentifierInfo *II = Name.getAsIdentifierInfo();
18336    bool InvalidDecl = false;
18337    if (D) InvalidDecl = D->isInvalidType();
18338  
18339    // If we receive a broken type, recover by assuming 'int' and
18340    // marking this declaration as invalid.
18341    if (T.isNull() || T->containsErrors()) {
18342      InvalidDecl = true;
18343      T = Context.IntTy;
18344    }
18345  
18346    QualType EltTy = Context.getBaseElementType(T);
18347    if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
18348      if (RequireCompleteSizedType(Loc, EltTy,
18349                                   diag::err_field_incomplete_or_sizeless)) {
18350        // Fields of incomplete type force their record to be invalid.
18351        Record->setInvalidDecl();
18352        InvalidDecl = true;
18353      } else {
18354        NamedDecl *Def;
18355        EltTy->isIncompleteType(&Def);
18356        if (Def && Def->isInvalidDecl()) {
18357          Record->setInvalidDecl();
18358          InvalidDecl = true;
18359        }
18360      }
18361    }
18362  
18363    // TR 18037 does not allow fields to be declared with address space
18364    if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
18365        T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
18366      Diag(Loc, diag::err_field_with_address_space);
18367      Record->setInvalidDecl();
18368      InvalidDecl = true;
18369    }
18370  
18371    if (LangOpts.OpenCL) {
18372      // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
18373      // used as structure or union field: image, sampler, event or block types.
18374      if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
18375          T->isBlockPointerType()) {
18376        Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
18377        Record->setInvalidDecl();
18378        InvalidDecl = true;
18379      }
18380      // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
18381      // is enabled.
18382      if (BitWidth && !getOpenCLOptions().isAvailableOption(
18383                          "__cl_clang_bitfields", LangOpts)) {
18384        Diag(Loc, diag::err_opencl_bitfields);
18385        InvalidDecl = true;
18386      }
18387    }
18388  
18389    // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
18390    if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
18391        T.hasQualifiers()) {
18392      InvalidDecl = true;
18393      Diag(Loc, diag::err_anon_bitfield_qualifiers);
18394    }
18395  
18396    // C99 6.7.2.1p8: A member of a structure or union may have any type other
18397    // than a variably modified type.
18398    if (!InvalidDecl && T->isVariablyModifiedType()) {
18399      if (!tryToFixVariablyModifiedVarType(
18400              TInfo, T, Loc, diag::err_typecheck_field_variable_size))
18401        InvalidDecl = true;
18402    }
18403  
18404    // Fields can not have abstract class types
18405    if (!InvalidDecl && RequireNonAbstractType(Loc, T,
18406                                               diag::err_abstract_type_in_decl,
18407                                               AbstractFieldType))
18408      InvalidDecl = true;
18409  
18410    if (InvalidDecl)
18411      BitWidth = nullptr;
18412    // If this is declared as a bit-field, check the bit-field.
18413    if (BitWidth) {
18414      BitWidth =
18415          VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
18416      if (!BitWidth) {
18417        InvalidDecl = true;
18418        BitWidth = nullptr;
18419      }
18420    }
18421  
18422    // Check that 'mutable' is consistent with the type of the declaration.
18423    if (!InvalidDecl && Mutable) {
18424      unsigned DiagID = 0;
18425      if (T->isReferenceType())
18426        DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
18427                                          : diag::err_mutable_reference;
18428      else if (T.isConstQualified())
18429        DiagID = diag::err_mutable_const;
18430  
18431      if (DiagID) {
18432        SourceLocation ErrLoc = Loc;
18433        if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
18434          ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
18435        Diag(ErrLoc, DiagID);
18436        if (DiagID != diag::ext_mutable_reference) {
18437          Mutable = false;
18438          InvalidDecl = true;
18439        }
18440      }
18441    }
18442  
18443    // C++11 [class.union]p8 (DR1460):
18444    //   At most one variant member of a union may have a
18445    //   brace-or-equal-initializer.
18446    if (InitStyle != ICIS_NoInit)
18447      checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
18448  
18449    FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
18450                                         BitWidth, Mutable, InitStyle);
18451    if (InvalidDecl)
18452      NewFD->setInvalidDecl();
18453  
18454    if (PrevDecl && !isa<TagDecl>(PrevDecl) &&
18455        !PrevDecl->isPlaceholderVar(getLangOpts())) {
18456      Diag(Loc, diag::err_duplicate_member) << II;
18457      Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
18458      NewFD->setInvalidDecl();
18459    }
18460  
18461    if (!InvalidDecl && getLangOpts().CPlusPlus) {
18462      if (Record->isUnion()) {
18463        if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18464          CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
18465          if (RDecl->getDefinition()) {
18466            // C++ [class.union]p1: An object of a class with a non-trivial
18467            // constructor, a non-trivial copy constructor, a non-trivial
18468            // destructor, or a non-trivial copy assignment operator
18469            // cannot be a member of a union, nor can an array of such
18470            // objects.
18471            if (CheckNontrivialField(NewFD))
18472              NewFD->setInvalidDecl();
18473          }
18474        }
18475  
18476        // C++ [class.union]p1: If a union contains a member of reference type,
18477        // the program is ill-formed, except when compiling with MSVC extensions
18478        // enabled.
18479        if (EltTy->isReferenceType()) {
18480          Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
18481                                      diag::ext_union_member_of_reference_type :
18482                                      diag::err_union_member_of_reference_type)
18483            << NewFD->getDeclName() << EltTy;
18484          if (!getLangOpts().MicrosoftExt)
18485            NewFD->setInvalidDecl();
18486        }
18487      }
18488    }
18489  
18490    // FIXME: We need to pass in the attributes given an AST
18491    // representation, not a parser representation.
18492    if (D) {
18493      // FIXME: The current scope is almost... but not entirely... correct here.
18494      ProcessDeclAttributes(getCurScope(), NewFD, *D);
18495  
18496      if (NewFD->hasAttrs())
18497        CheckAlignasUnderalignment(NewFD);
18498    }
18499  
18500    // In auto-retain/release, infer strong retension for fields of
18501    // retainable type.
18502    if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewFD))
18503      NewFD->setInvalidDecl();
18504  
18505    if (T.isObjCGCWeak())
18506      Diag(Loc, diag::warn_attribute_weak_on_field);
18507  
18508    // PPC MMA non-pointer types are not allowed as field types.
18509    if (Context.getTargetInfo().getTriple().isPPC64() &&
18510        PPC().CheckPPCMMAType(T, NewFD->getLocation()))
18511      NewFD->setInvalidDecl();
18512  
18513    NewFD->setAccess(AS);
18514    return NewFD;
18515  }
18516  
CheckNontrivialField(FieldDecl * FD)18517  bool Sema::CheckNontrivialField(FieldDecl *FD) {
18518    assert(FD);
18519    assert(getLangOpts().CPlusPlus && "valid check only for C++");
18520  
18521    if (FD->isInvalidDecl() || FD->getType()->isDependentType())
18522      return false;
18523  
18524    QualType EltTy = Context.getBaseElementType(FD->getType());
18525    if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18526      CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
18527      if (RDecl->getDefinition()) {
18528        // We check for copy constructors before constructors
18529        // because otherwise we'll never get complaints about
18530        // copy constructors.
18531  
18532        CXXSpecialMemberKind member = CXXSpecialMemberKind::Invalid;
18533        // We're required to check for any non-trivial constructors. Since the
18534        // implicit default constructor is suppressed if there are any
18535        // user-declared constructors, we just need to check that there is a
18536        // trivial default constructor and a trivial copy constructor. (We don't
18537        // worry about move constructors here, since this is a C++98 check.)
18538        if (RDecl->hasNonTrivialCopyConstructor())
18539          member = CXXSpecialMemberKind::CopyConstructor;
18540        else if (!RDecl->hasTrivialDefaultConstructor())
18541          member = CXXSpecialMemberKind::DefaultConstructor;
18542        else if (RDecl->hasNonTrivialCopyAssignment())
18543          member = CXXSpecialMemberKind::CopyAssignment;
18544        else if (RDecl->hasNonTrivialDestructor())
18545          member = CXXSpecialMemberKind::Destructor;
18546  
18547        if (member != CXXSpecialMemberKind::Invalid) {
18548          if (!getLangOpts().CPlusPlus11 &&
18549              getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
18550            // Objective-C++ ARC: it is an error to have a non-trivial field of
18551            // a union. However, system headers in Objective-C programs
18552            // occasionally have Objective-C lifetime objects within unions,
18553            // and rather than cause the program to fail, we make those
18554            // members unavailable.
18555            SourceLocation Loc = FD->getLocation();
18556            if (getSourceManager().isInSystemHeader(Loc)) {
18557              if (!FD->hasAttr<UnavailableAttr>())
18558                FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
18559                              UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
18560              return false;
18561            }
18562          }
18563  
18564          Diag(
18565              FD->getLocation(),
18566              getLangOpts().CPlusPlus11
18567                  ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
18568                  : diag::err_illegal_union_or_anon_struct_member)
18569              << FD->getParent()->isUnion() << FD->getDeclName()
18570              << llvm::to_underlying(member);
18571          DiagnoseNontrivial(RDecl, member);
18572          return !getLangOpts().CPlusPlus11;
18573        }
18574      }
18575    }
18576  
18577    return false;
18578  }
18579  
ActOnLastBitfield(SourceLocation DeclLoc,SmallVectorImpl<Decl * > & AllIvarDecls)18580  void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
18581                               SmallVectorImpl<Decl *> &AllIvarDecls) {
18582    if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
18583      return;
18584  
18585    Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
18586    ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
18587  
18588    if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
18589      return;
18590    ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
18591    if (!ID) {
18592      if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
18593        if (!CD->IsClassExtension())
18594          return;
18595      }
18596      // No need to add this to end of @implementation.
18597      else
18598        return;
18599    }
18600    // All conditions are met. Add a new bitfield to the tail end of ivars.
18601    llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
18602    Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
18603  
18604    Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
18605                                DeclLoc, DeclLoc, nullptr,
18606                                Context.CharTy,
18607                                Context.getTrivialTypeSourceInfo(Context.CharTy,
18608                                                                 DeclLoc),
18609                                ObjCIvarDecl::Private, BW,
18610                                true);
18611    AllIvarDecls.push_back(Ivar);
18612  }
18613  
18614  /// [class.dtor]p4:
18615  ///   At the end of the definition of a class, overload resolution is
18616  ///   performed among the prospective destructors declared in that class with
18617  ///   an empty argument list to select the destructor for the class, also
18618  ///   known as the selected destructor.
18619  ///
18620  /// We do the overload resolution here, then mark the selected constructor in the AST.
18621  /// Later CXXRecordDecl::getDestructor() will return the selected constructor.
ComputeSelectedDestructor(Sema & S,CXXRecordDecl * Record)18622  static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) {
18623    if (!Record->hasUserDeclaredDestructor()) {
18624      return;
18625    }
18626  
18627    SourceLocation Loc = Record->getLocation();
18628    OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal);
18629  
18630    for (auto *Decl : Record->decls()) {
18631      if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
18632        if (DD->isInvalidDecl())
18633          continue;
18634        S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
18635                               OCS);
18636        assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
18637      }
18638    }
18639  
18640    if (OCS.empty()) {
18641      return;
18642    }
18643    OverloadCandidateSet::iterator Best;
18644    unsigned Msg = 0;
18645    OverloadCandidateDisplayKind DisplayKind;
18646  
18647    switch (OCS.BestViableFunction(S, Loc, Best)) {
18648    case OR_Success:
18649    case OR_Deleted:
18650      Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
18651      break;
18652  
18653    case OR_Ambiguous:
18654      Msg = diag::err_ambiguous_destructor;
18655      DisplayKind = OCD_AmbiguousCandidates;
18656      break;
18657  
18658    case OR_No_Viable_Function:
18659      Msg = diag::err_no_viable_destructor;
18660      DisplayKind = OCD_AllCandidates;
18661      break;
18662    }
18663  
18664    if (Msg) {
18665      // OpenCL have got their own thing going with destructors. It's slightly broken,
18666      // but we allow it.
18667      if (!S.LangOpts.OpenCL) {
18668        PartialDiagnostic Diag = S.PDiag(Msg) << Record;
18669        OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
18670        Record->setInvalidDecl();
18671      }
18672      // It's a bit hacky: At this point we've raised an error but we want the
18673      // rest of the compiler to continue somehow working. However almost
18674      // everything we'll try to do with the class will depend on there being a
18675      // destructor. So let's pretend the first one is selected and hope for the
18676      // best.
18677      Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
18678    }
18679  }
18680  
18681  /// [class.mem.special]p5
18682  /// Two special member functions are of the same kind if:
18683  /// - they are both default constructors,
18684  /// - they are both copy or move constructors with the same first parameter
18685  ///   type, or
18686  /// - they are both copy or move assignment operators with the same first
18687  ///   parameter type and the same cv-qualifiers and ref-qualifier, if any.
AreSpecialMemberFunctionsSameKind(ASTContext & Context,CXXMethodDecl * M1,CXXMethodDecl * M2,CXXSpecialMemberKind CSM)18688  static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context,
18689                                                CXXMethodDecl *M1,
18690                                                CXXMethodDecl *M2,
18691                                                CXXSpecialMemberKind CSM) {
18692    // We don't want to compare templates to non-templates: See
18693    // https://github.com/llvm/llvm-project/issues/59206
18694    if (CSM == CXXSpecialMemberKind::DefaultConstructor)
18695      return bool(M1->getDescribedFunctionTemplate()) ==
18696             bool(M2->getDescribedFunctionTemplate());
18697    // FIXME: better resolve CWG
18698    // https://cplusplus.github.io/CWG/issues/2787.html
18699    if (!Context.hasSameType(M1->getNonObjectParameter(0)->getType(),
18700                             M2->getNonObjectParameter(0)->getType()))
18701      return false;
18702    if (!Context.hasSameType(M1->getFunctionObjectParameterReferenceType(),
18703                             M2->getFunctionObjectParameterReferenceType()))
18704      return false;
18705  
18706    return true;
18707  }
18708  
18709  /// [class.mem.special]p6:
18710  /// An eligible special member function is a special member function for which:
18711  /// - the function is not deleted,
18712  /// - the associated constraints, if any, are satisfied, and
18713  /// - no special member function of the same kind whose associated constraints
18714  ///   [CWG2595], if any, are satisfied is more constrained.
SetEligibleMethods(Sema & S,CXXRecordDecl * Record,ArrayRef<CXXMethodDecl * > Methods,CXXSpecialMemberKind CSM)18715  static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record,
18716                                 ArrayRef<CXXMethodDecl *> Methods,
18717                                 CXXSpecialMemberKind CSM) {
18718    SmallVector<bool, 4> SatisfactionStatus;
18719  
18720    for (CXXMethodDecl *Method : Methods) {
18721      const Expr *Constraints = Method->getTrailingRequiresClause();
18722      if (!Constraints)
18723        SatisfactionStatus.push_back(true);
18724      else {
18725        ConstraintSatisfaction Satisfaction;
18726        if (S.CheckFunctionConstraints(Method, Satisfaction))
18727          SatisfactionStatus.push_back(false);
18728        else
18729          SatisfactionStatus.push_back(Satisfaction.IsSatisfied);
18730      }
18731    }
18732  
18733    for (size_t i = 0; i < Methods.size(); i++) {
18734      if (!SatisfactionStatus[i])
18735        continue;
18736      CXXMethodDecl *Method = Methods[i];
18737      CXXMethodDecl *OrigMethod = Method;
18738      if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
18739        OrigMethod = cast<CXXMethodDecl>(MF);
18740  
18741      const Expr *Constraints = OrigMethod->getTrailingRequiresClause();
18742      bool AnotherMethodIsMoreConstrained = false;
18743      for (size_t j = 0; j < Methods.size(); j++) {
18744        if (i == j || !SatisfactionStatus[j])
18745          continue;
18746        CXXMethodDecl *OtherMethod = Methods[j];
18747        if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
18748          OtherMethod = cast<CXXMethodDecl>(MF);
18749  
18750        if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod,
18751                                               CSM))
18752          continue;
18753  
18754        const Expr *OtherConstraints = OtherMethod->getTrailingRequiresClause();
18755        if (!OtherConstraints)
18756          continue;
18757        if (!Constraints) {
18758          AnotherMethodIsMoreConstrained = true;
18759          break;
18760        }
18761        if (S.IsAtLeastAsConstrained(OtherMethod, {OtherConstraints}, OrigMethod,
18762                                     {Constraints},
18763                                     AnotherMethodIsMoreConstrained)) {
18764          // There was an error with the constraints comparison. Exit the loop
18765          // and don't consider this function eligible.
18766          AnotherMethodIsMoreConstrained = true;
18767        }
18768        if (AnotherMethodIsMoreConstrained)
18769          break;
18770      }
18771      // FIXME: Do not consider deleted methods as eligible after implementing
18772      // DR1734 and DR1496.
18773      if (!AnotherMethodIsMoreConstrained) {
18774        Method->setIneligibleOrNotSelected(false);
18775        Record->addedEligibleSpecialMemberFunction(Method,
18776                                                   1 << llvm::to_underlying(CSM));
18777      }
18778    }
18779  }
18780  
ComputeSpecialMemberFunctionsEligiblity(Sema & S,CXXRecordDecl * Record)18781  static void ComputeSpecialMemberFunctionsEligiblity(Sema &S,
18782                                                      CXXRecordDecl *Record) {
18783    SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
18784    SmallVector<CXXMethodDecl *, 4> CopyConstructors;
18785    SmallVector<CXXMethodDecl *, 4> MoveConstructors;
18786    SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
18787    SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
18788  
18789    for (auto *Decl : Record->decls()) {
18790      auto *MD = dyn_cast<CXXMethodDecl>(Decl);
18791      if (!MD) {
18792        auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);
18793        if (FTD)
18794          MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());
18795      }
18796      if (!MD)
18797        continue;
18798      if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
18799        if (CD->isInvalidDecl())
18800          continue;
18801        if (CD->isDefaultConstructor())
18802          DefaultConstructors.push_back(MD);
18803        else if (CD->isCopyConstructor())
18804          CopyConstructors.push_back(MD);
18805        else if (CD->isMoveConstructor())
18806          MoveConstructors.push_back(MD);
18807      } else if (MD->isCopyAssignmentOperator()) {
18808        CopyAssignmentOperators.push_back(MD);
18809      } else if (MD->isMoveAssignmentOperator()) {
18810        MoveAssignmentOperators.push_back(MD);
18811      }
18812    }
18813  
18814    SetEligibleMethods(S, Record, DefaultConstructors,
18815                       CXXSpecialMemberKind::DefaultConstructor);
18816    SetEligibleMethods(S, Record, CopyConstructors,
18817                       CXXSpecialMemberKind::CopyConstructor);
18818    SetEligibleMethods(S, Record, MoveConstructors,
18819                       CXXSpecialMemberKind::MoveConstructor);
18820    SetEligibleMethods(S, Record, CopyAssignmentOperators,
18821                       CXXSpecialMemberKind::CopyAssignment);
18822    SetEligibleMethods(S, Record, MoveAssignmentOperators,
18823                       CXXSpecialMemberKind::MoveAssignment);
18824  }
18825  
ActOnFields(Scope * S,SourceLocation RecLoc,Decl * EnclosingDecl,ArrayRef<Decl * > Fields,SourceLocation LBrac,SourceLocation RBrac,const ParsedAttributesView & Attrs)18826  void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
18827                         ArrayRef<Decl *> Fields, SourceLocation LBrac,
18828                         SourceLocation RBrac,
18829                         const ParsedAttributesView &Attrs) {
18830    assert(EnclosingDecl && "missing record or interface decl");
18831  
18832    // If this is an Objective-C @implementation or category and we have
18833    // new fields here we should reset the layout of the interface since
18834    // it will now change.
18835    if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
18836      ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
18837      switch (DC->getKind()) {
18838      default: break;
18839      case Decl::ObjCCategory:
18840        Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
18841        break;
18842      case Decl::ObjCImplementation:
18843        Context.
18844          ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
18845        break;
18846      }
18847    }
18848  
18849    RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
18850    CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
18851  
18852    // Start counting up the number of named members; make sure to include
18853    // members of anonymous structs and unions in the total.
18854    unsigned NumNamedMembers = 0;
18855    if (Record) {
18856      for (const auto *I : Record->decls()) {
18857        if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
18858          if (IFD->getDeclName())
18859            ++NumNamedMembers;
18860      }
18861    }
18862  
18863    // Verify that all the fields are okay.
18864    SmallVector<FieldDecl*, 32> RecFields;
18865  
18866    for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
18867         i != end; ++i) {
18868      FieldDecl *FD = cast<FieldDecl>(*i);
18869  
18870      // Get the type for the field.
18871      const Type *FDTy = FD->getType().getTypePtr();
18872  
18873      if (!FD->isAnonymousStructOrUnion()) {
18874        // Remember all fields written by the user.
18875        RecFields.push_back(FD);
18876      }
18877  
18878      // If the field is already invalid for some reason, don't emit more
18879      // diagnostics about it.
18880      if (FD->isInvalidDecl()) {
18881        EnclosingDecl->setInvalidDecl();
18882        continue;
18883      }
18884  
18885      // C99 6.7.2.1p2:
18886      //   A structure or union shall not contain a member with
18887      //   incomplete or function type (hence, a structure shall not
18888      //   contain an instance of itself, but may contain a pointer to
18889      //   an instance of itself), except that the last member of a
18890      //   structure with more than one named member may have incomplete
18891      //   array type; such a structure (and any union containing,
18892      //   possibly recursively, a member that is such a structure)
18893      //   shall not be a member of a structure or an element of an
18894      //   array.
18895      bool IsLastField = (i + 1 == Fields.end());
18896      if (FDTy->isFunctionType()) {
18897        // Field declared as a function.
18898        Diag(FD->getLocation(), diag::err_field_declared_as_function)
18899          << FD->getDeclName();
18900        FD->setInvalidDecl();
18901        EnclosingDecl->setInvalidDecl();
18902        continue;
18903      } else if (FDTy->isIncompleteArrayType() &&
18904                 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
18905        if (Record) {
18906          // Flexible array member.
18907          // Microsoft and g++ is more permissive regarding flexible array.
18908          // It will accept flexible array in union and also
18909          // as the sole element of a struct/class.
18910          unsigned DiagID = 0;
18911          if (!Record->isUnion() && !IsLastField) {
18912            Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
18913                << FD->getDeclName() << FD->getType()
18914                << llvm::to_underlying(Record->getTagKind());
18915            Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
18916            FD->setInvalidDecl();
18917            EnclosingDecl->setInvalidDecl();
18918            continue;
18919          } else if (Record->isUnion())
18920            DiagID = getLangOpts().MicrosoftExt
18921                         ? diag::ext_flexible_array_union_ms
18922                         : diag::ext_flexible_array_union_gnu;
18923          else if (NumNamedMembers < 1)
18924            DiagID = getLangOpts().MicrosoftExt
18925                         ? diag::ext_flexible_array_empty_aggregate_ms
18926                         : diag::ext_flexible_array_empty_aggregate_gnu;
18927  
18928          if (DiagID)
18929            Diag(FD->getLocation(), DiagID)
18930                << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
18931          // While the layout of types that contain virtual bases is not specified
18932          // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
18933          // virtual bases after the derived members.  This would make a flexible
18934          // array member declared at the end of an object not adjacent to the end
18935          // of the type.
18936          if (CXXRecord && CXXRecord->getNumVBases() != 0)
18937            Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
18938                << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
18939          if (!getLangOpts().C99)
18940            Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
18941                << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
18942  
18943          // If the element type has a non-trivial destructor, we would not
18944          // implicitly destroy the elements, so disallow it for now.
18945          //
18946          // FIXME: GCC allows this. We should probably either implicitly delete
18947          // the destructor of the containing class, or just allow this.
18948          QualType BaseElem = Context.getBaseElementType(FD->getType());
18949          if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
18950            Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
18951              << FD->getDeclName() << FD->getType();
18952            FD->setInvalidDecl();
18953            EnclosingDecl->setInvalidDecl();
18954            continue;
18955          }
18956          // Okay, we have a legal flexible array member at the end of the struct.
18957          Record->setHasFlexibleArrayMember(true);
18958        } else {
18959          // In ObjCContainerDecl ivars with incomplete array type are accepted,
18960          // unless they are followed by another ivar. That check is done
18961          // elsewhere, after synthesized ivars are known.
18962        }
18963      } else if (!FDTy->isDependentType() &&
18964                 RequireCompleteSizedType(
18965                     FD->getLocation(), FD->getType(),
18966                     diag::err_field_incomplete_or_sizeless)) {
18967        // Incomplete type
18968        FD->setInvalidDecl();
18969        EnclosingDecl->setInvalidDecl();
18970        continue;
18971      } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
18972        if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
18973          // A type which contains a flexible array member is considered to be a
18974          // flexible array member.
18975          Record->setHasFlexibleArrayMember(true);
18976          if (!Record->isUnion()) {
18977            // If this is a struct/class and this is not the last element, reject
18978            // it.  Note that GCC supports variable sized arrays in the middle of
18979            // structures.
18980            if (!IsLastField)
18981              Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
18982                << FD->getDeclName() << FD->getType();
18983            else {
18984              // We support flexible arrays at the end of structs in
18985              // other structs as an extension.
18986              Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
18987                << FD->getDeclName();
18988            }
18989          }
18990        }
18991        if (isa<ObjCContainerDecl>(EnclosingDecl) &&
18992            RequireNonAbstractType(FD->getLocation(), FD->getType(),
18993                                   diag::err_abstract_type_in_decl,
18994                                   AbstractIvarType)) {
18995          // Ivars can not have abstract class types
18996          FD->setInvalidDecl();
18997        }
18998        if (Record && FDTTy->getDecl()->hasObjectMember())
18999          Record->setHasObjectMember(true);
19000        if (Record && FDTTy->getDecl()->hasVolatileMember())
19001          Record->setHasVolatileMember(true);
19002      } else if (FDTy->isObjCObjectType()) {
19003        /// A field cannot be an Objective-c object
19004        Diag(FD->getLocation(), diag::err_statically_allocated_object)
19005          << FixItHint::CreateInsertion(FD->getLocation(), "*");
19006        QualType T = Context.getObjCObjectPointerType(FD->getType());
19007        FD->setType(T);
19008      } else if (Record && Record->isUnion() &&
19009                 FD->getType().hasNonTrivialObjCLifetime() &&
19010                 getSourceManager().isInSystemHeader(FD->getLocation()) &&
19011                 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
19012                 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
19013                  !Context.hasDirectOwnershipQualifier(FD->getType()))) {
19014        // For backward compatibility, fields of C unions declared in system
19015        // headers that have non-trivial ObjC ownership qualifications are marked
19016        // as unavailable unless the qualifier is explicit and __strong. This can
19017        // break ABI compatibility between programs compiled with ARC and MRR, but
19018        // is a better option than rejecting programs using those unions under
19019        // ARC.
19020        FD->addAttr(UnavailableAttr::CreateImplicit(
19021            Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
19022            FD->getLocation()));
19023      } else if (getLangOpts().ObjC &&
19024                 getLangOpts().getGC() != LangOptions::NonGC && Record &&
19025                 !Record->hasObjectMember()) {
19026        if (FD->getType()->isObjCObjectPointerType() ||
19027            FD->getType().isObjCGCStrong())
19028          Record->setHasObjectMember(true);
19029        else if (Context.getAsArrayType(FD->getType())) {
19030          QualType BaseType = Context.getBaseElementType(FD->getType());
19031          if (BaseType->isRecordType() &&
19032              BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
19033            Record->setHasObjectMember(true);
19034          else if (BaseType->isObjCObjectPointerType() ||
19035                   BaseType.isObjCGCStrong())
19036                 Record->setHasObjectMember(true);
19037        }
19038      }
19039  
19040      if (Record && !getLangOpts().CPlusPlus &&
19041          !shouldIgnoreForRecordTriviality(FD)) {
19042        QualType FT = FD->getType();
19043        if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
19044          Record->setNonTrivialToPrimitiveDefaultInitialize(true);
19045          if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
19046              Record->isUnion())
19047            Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
19048        }
19049        QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
19050        if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
19051          Record->setNonTrivialToPrimitiveCopy(true);
19052          if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
19053            Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
19054        }
19055        if (FT.isDestructedType()) {
19056          Record->setNonTrivialToPrimitiveDestroy(true);
19057          Record->setParamDestroyedInCallee(true);
19058          if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
19059            Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
19060        }
19061  
19062        if (const auto *RT = FT->getAs<RecordType>()) {
19063          if (RT->getDecl()->getArgPassingRestrictions() ==
19064              RecordArgPassingKind::CanNeverPassInRegs)
19065            Record->setArgPassingRestrictions(
19066                RecordArgPassingKind::CanNeverPassInRegs);
19067        } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
19068          Record->setArgPassingRestrictions(
19069              RecordArgPassingKind::CanNeverPassInRegs);
19070      }
19071  
19072      if (Record && FD->getType().isVolatileQualified())
19073        Record->setHasVolatileMember(true);
19074      // Keep track of the number of named members.
19075      if (FD->getIdentifier())
19076        ++NumNamedMembers;
19077    }
19078  
19079    // Okay, we successfully defined 'Record'.
19080    if (Record) {
19081      bool Completed = false;
19082      if (S) {
19083        Scope *Parent = S->getParent();
19084        if (Parent && Parent->isTypeAliasScope() &&
19085            Parent->isTemplateParamScope())
19086          Record->setInvalidDecl();
19087      }
19088  
19089      if (CXXRecord) {
19090        if (!CXXRecord->isInvalidDecl()) {
19091          // Set access bits correctly on the directly-declared conversions.
19092          for (CXXRecordDecl::conversion_iterator
19093                 I = CXXRecord->conversion_begin(),
19094                 E = CXXRecord->conversion_end(); I != E; ++I)
19095            I.setAccess((*I)->getAccess());
19096        }
19097  
19098        // Add any implicitly-declared members to this class.
19099        AddImplicitlyDeclaredMembersToClass(CXXRecord);
19100  
19101        if (!CXXRecord->isDependentType()) {
19102          if (!CXXRecord->isInvalidDecl()) {
19103            // If we have virtual base classes, we may end up finding multiple
19104            // final overriders for a given virtual function. Check for this
19105            // problem now.
19106            if (CXXRecord->getNumVBases()) {
19107              CXXFinalOverriderMap FinalOverriders;
19108              CXXRecord->getFinalOverriders(FinalOverriders);
19109  
19110              for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
19111                                               MEnd = FinalOverriders.end();
19112                   M != MEnd; ++M) {
19113                for (OverridingMethods::iterator SO = M->second.begin(),
19114                                              SOEnd = M->second.end();
19115                     SO != SOEnd; ++SO) {
19116                  assert(SO->second.size() > 0 &&
19117                         "Virtual function without overriding functions?");
19118                  if (SO->second.size() == 1)
19119                    continue;
19120  
19121                  // C++ [class.virtual]p2:
19122                  //   In a derived class, if a virtual member function of a base
19123                  //   class subobject has more than one final overrider the
19124                  //   program is ill-formed.
19125                  Diag(Record->getLocation(), diag::err_multiple_final_overriders)
19126                    << (const NamedDecl *)M->first << Record;
19127                  Diag(M->first->getLocation(),
19128                       diag::note_overridden_virtual_function);
19129                  for (OverridingMethods::overriding_iterator
19130                            OM = SO->second.begin(),
19131                         OMEnd = SO->second.end();
19132                       OM != OMEnd; ++OM)
19133                    Diag(OM->Method->getLocation(), diag::note_final_overrider)
19134                      << (const NamedDecl *)M->first << OM->Method->getParent();
19135  
19136                  Record->setInvalidDecl();
19137                }
19138              }
19139              CXXRecord->completeDefinition(&FinalOverriders);
19140              Completed = true;
19141            }
19142          }
19143          ComputeSelectedDestructor(*this, CXXRecord);
19144          ComputeSpecialMemberFunctionsEligiblity(*this, CXXRecord);
19145        }
19146      }
19147  
19148      if (!Completed)
19149        Record->completeDefinition();
19150  
19151      // Handle attributes before checking the layout.
19152      ProcessDeclAttributeList(S, Record, Attrs);
19153  
19154      // Check to see if a FieldDecl is a pointer to a function.
19155      auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
19156        const FieldDecl *FD = dyn_cast<FieldDecl>(D);
19157        if (!FD) {
19158          // Check whether this is a forward declaration that was inserted by
19159          // Clang. This happens when a non-forward declared / defined type is
19160          // used, e.g.:
19161          //
19162          //   struct foo {
19163          //     struct bar *(*f)();
19164          //     struct bar *(*g)();
19165          //   };
19166          //
19167          // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19168          // incomplete definition.
19169          if (const auto *TD = dyn_cast<TagDecl>(D))
19170            return !TD->isCompleteDefinition();
19171          return false;
19172        }
19173        QualType FieldType = FD->getType().getDesugaredType(Context);
19174        if (isa<PointerType>(FieldType)) {
19175          QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
19176          return PointeeType.getDesugaredType(Context)->isFunctionType();
19177        }
19178        return false;
19179      };
19180  
19181      // Maybe randomize the record's decls. We automatically randomize a record
19182      // of function pointers, unless it has the "no_randomize_layout" attribute.
19183      if (!getLangOpts().CPlusPlus &&
19184          (Record->hasAttr<RandomizeLayoutAttr>() ||
19185           (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
19186            llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl))) &&
19187          !Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&
19188          !Record->isRandomized()) {
19189        SmallVector<Decl *, 32> NewDeclOrdering;
19190        if (randstruct::randomizeStructureLayout(Context, Record,
19191                                                 NewDeclOrdering))
19192          Record->reorderDecls(NewDeclOrdering);
19193      }
19194  
19195      // We may have deferred checking for a deleted destructor. Check now.
19196      if (CXXRecord) {
19197        auto *Dtor = CXXRecord->getDestructor();
19198        if (Dtor && Dtor->isImplicit() &&
19199            ShouldDeleteSpecialMember(Dtor, CXXSpecialMemberKind::Destructor)) {
19200          CXXRecord->setImplicitDestructorIsDeleted();
19201          SetDeclDeleted(Dtor, CXXRecord->getLocation());
19202        }
19203      }
19204  
19205      if (Record->hasAttrs()) {
19206        CheckAlignasUnderalignment(Record);
19207  
19208        if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
19209          checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
19210                                             IA->getRange(), IA->getBestCase(),
19211                                             IA->getInheritanceModel());
19212      }
19213  
19214      // Check if the structure/union declaration is a type that can have zero
19215      // size in C. For C this is a language extension, for C++ it may cause
19216      // compatibility problems.
19217      bool CheckForZeroSize;
19218      if (!getLangOpts().CPlusPlus) {
19219        CheckForZeroSize = true;
19220      } else {
19221        // For C++ filter out types that cannot be referenced in C code.
19222        CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
19223        CheckForZeroSize =
19224            CXXRecord->getLexicalDeclContext()->isExternCContext() &&
19225            !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
19226            CXXRecord->isCLike();
19227      }
19228      if (CheckForZeroSize) {
19229        bool ZeroSize = true;
19230        bool IsEmpty = true;
19231        unsigned NonBitFields = 0;
19232        for (RecordDecl::field_iterator I = Record->field_begin(),
19233                                        E = Record->field_end();
19234             (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
19235          IsEmpty = false;
19236          if (I->isUnnamedBitField()) {
19237            if (!I->isZeroLengthBitField(Context))
19238              ZeroSize = false;
19239          } else {
19240            ++NonBitFields;
19241            QualType FieldType = I->getType();
19242            if (FieldType->isIncompleteType() ||
19243                !Context.getTypeSizeInChars(FieldType).isZero())
19244              ZeroSize = false;
19245          }
19246        }
19247  
19248        // Empty structs are an extension in C (C99 6.7.2.1p7). They are
19249        // allowed in C++, but warn if its declaration is inside
19250        // extern "C" block.
19251        if (ZeroSize) {
19252          Diag(RecLoc, getLangOpts().CPlusPlus ?
19253                           diag::warn_zero_size_struct_union_in_extern_c :
19254                           diag::warn_zero_size_struct_union_compat)
19255            << IsEmpty << Record->isUnion() << (NonBitFields > 1);
19256        }
19257  
19258        // Structs without named members are extension in C (C99 6.7.2.1p7),
19259        // but are accepted by GCC.
19260        if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
19261          Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
19262                                 diag::ext_no_named_members_in_struct_union)
19263            << Record->isUnion();
19264        }
19265      }
19266    } else {
19267      ObjCIvarDecl **ClsFields =
19268        reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
19269      if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
19270        ID->setEndOfDefinitionLoc(RBrac);
19271        // Add ivar's to class's DeclContext.
19272        for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19273          ClsFields[i]->setLexicalDeclContext(ID);
19274          ID->addDecl(ClsFields[i]);
19275        }
19276        // Must enforce the rule that ivars in the base classes may not be
19277        // duplicates.
19278        if (ID->getSuperClass())
19279          ObjC().DiagnoseDuplicateIvars(ID, ID->getSuperClass());
19280      } else if (ObjCImplementationDecl *IMPDecl =
19281                    dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
19282        assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
19283        for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
19284          // Ivar declared in @implementation never belongs to the implementation.
19285          // Only it is in implementation's lexical context.
19286          ClsFields[I]->setLexicalDeclContext(IMPDecl);
19287        ObjC().CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(),
19288                                        RBrac);
19289        IMPDecl->setIvarLBraceLoc(LBrac);
19290        IMPDecl->setIvarRBraceLoc(RBrac);
19291      } else if (ObjCCategoryDecl *CDecl =
19292                  dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
19293        // case of ivars in class extension; all other cases have been
19294        // reported as errors elsewhere.
19295        // FIXME. Class extension does not have a LocEnd field.
19296        // CDecl->setLocEnd(RBrac);
19297        // Add ivar's to class extension's DeclContext.
19298        // Diagnose redeclaration of private ivars.
19299        ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
19300        for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19301          if (IDecl) {
19302            if (const ObjCIvarDecl *ClsIvar =
19303                IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
19304              Diag(ClsFields[i]->getLocation(),
19305                   diag::err_duplicate_ivar_declaration);
19306              Diag(ClsIvar->getLocation(), diag::note_previous_definition);
19307              continue;
19308            }
19309            for (const auto *Ext : IDecl->known_extensions()) {
19310              if (const ObjCIvarDecl *ClsExtIvar
19311                    = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
19312                Diag(ClsFields[i]->getLocation(),
19313                     diag::err_duplicate_ivar_declaration);
19314                Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
19315                continue;
19316              }
19317            }
19318          }
19319          ClsFields[i]->setLexicalDeclContext(CDecl);
19320          CDecl->addDecl(ClsFields[i]);
19321        }
19322        CDecl->setIvarLBraceLoc(LBrac);
19323        CDecl->setIvarRBraceLoc(RBrac);
19324      }
19325    }
19326    ProcessAPINotes(Record);
19327  }
19328  
19329  /// Determine whether the given integral value is representable within
19330  /// the given type T.
isRepresentableIntegerValue(ASTContext & Context,llvm::APSInt & Value,QualType T)19331  static bool isRepresentableIntegerValue(ASTContext &Context,
19332                                          llvm::APSInt &Value,
19333                                          QualType T) {
19334    assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
19335           "Integral type required!");
19336    unsigned BitWidth = Context.getIntWidth(T);
19337  
19338    if (Value.isUnsigned() || Value.isNonNegative()) {
19339      if (T->isSignedIntegerOrEnumerationType())
19340        --BitWidth;
19341      return Value.getActiveBits() <= BitWidth;
19342    }
19343    return Value.getSignificantBits() <= BitWidth;
19344  }
19345  
19346  // Given an integral type, return the next larger integral type
19347  // (or a NULL type of no such type exists).
getNextLargerIntegralType(ASTContext & Context,QualType T)19348  static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
19349    // FIXME: Int128/UInt128 support, which also needs to be introduced into
19350    // enum checking below.
19351    assert((T->isIntegralType(Context) ||
19352           T->isEnumeralType()) && "Integral type required!");
19353    const unsigned NumTypes = 4;
19354    QualType SignedIntegralTypes[NumTypes] = {
19355      Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
19356    };
19357    QualType UnsignedIntegralTypes[NumTypes] = {
19358      Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
19359      Context.UnsignedLongLongTy
19360    };
19361  
19362    unsigned BitWidth = Context.getTypeSize(T);
19363    QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
19364                                                          : UnsignedIntegralTypes;
19365    for (unsigned I = 0; I != NumTypes; ++I)
19366      if (Context.getTypeSize(Types[I]) > BitWidth)
19367        return Types[I];
19368  
19369    return QualType();
19370  }
19371  
CheckEnumConstant(EnumDecl * Enum,EnumConstantDecl * LastEnumConst,SourceLocation IdLoc,IdentifierInfo * Id,Expr * Val)19372  EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
19373                                            EnumConstantDecl *LastEnumConst,
19374                                            SourceLocation IdLoc,
19375                                            IdentifierInfo *Id,
19376                                            Expr *Val) {
19377    unsigned IntWidth = Context.getTargetInfo().getIntWidth();
19378    llvm::APSInt EnumVal(IntWidth);
19379    QualType EltTy;
19380  
19381    if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
19382      Val = nullptr;
19383  
19384    if (Val)
19385      Val = DefaultLvalueConversion(Val).get();
19386  
19387    if (Val) {
19388      if (Enum->isDependentType() || Val->isTypeDependent() ||
19389          Val->containsErrors())
19390        EltTy = Context.DependentTy;
19391      else {
19392        // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
19393        // underlying type, but do allow it in all other contexts.
19394        if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
19395          // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
19396          // constant-expression in the enumerator-definition shall be a converted
19397          // constant expression of the underlying type.
19398          EltTy = Enum->getIntegerType();
19399          ExprResult Converted =
19400            CheckConvertedConstantExpression(Val, EltTy, EnumVal,
19401                                             CCEK_Enumerator);
19402          if (Converted.isInvalid())
19403            Val = nullptr;
19404          else
19405            Val = Converted.get();
19406        } else if (!Val->isValueDependent() &&
19407                   !(Val =
19408                         VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
19409                             .get())) {
19410          // C99 6.7.2.2p2: Make sure we have an integer constant expression.
19411        } else {
19412          if (Enum->isComplete()) {
19413            EltTy = Enum->getIntegerType();
19414  
19415            // In Obj-C and Microsoft mode, require the enumeration value to be
19416            // representable in the underlying type of the enumeration. In C++11,
19417            // we perform a non-narrowing conversion as part of converted constant
19418            // expression checking.
19419            if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
19420              if (Context.getTargetInfo()
19421                      .getTriple()
19422                      .isWindowsMSVCEnvironment()) {
19423                Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
19424              } else {
19425                Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
19426              }
19427            }
19428  
19429            // Cast to the underlying type.
19430            Val = ImpCastExprToType(Val, EltTy,
19431                                    EltTy->isBooleanType() ? CK_IntegralToBoolean
19432                                                           : CK_IntegralCast)
19433                      .get();
19434          } else if (getLangOpts().CPlusPlus) {
19435            // C++11 [dcl.enum]p5:
19436            //   If the underlying type is not fixed, the type of each enumerator
19437            //   is the type of its initializing value:
19438            //     - If an initializer is specified for an enumerator, the
19439            //       initializing value has the same type as the expression.
19440            EltTy = Val->getType();
19441          } else {
19442            // C99 6.7.2.2p2:
19443            //   The expression that defines the value of an enumeration constant
19444            //   shall be an integer constant expression that has a value
19445            //   representable as an int.
19446  
19447            // Complain if the value is not representable in an int.
19448            if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
19449              Diag(IdLoc, diag::ext_enum_value_not_int)
19450                << toString(EnumVal, 10) << Val->getSourceRange()
19451                << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
19452            else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
19453              // Force the type of the expression to 'int'.
19454              Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
19455            }
19456            EltTy = Val->getType();
19457          }
19458        }
19459      }
19460    }
19461  
19462    if (!Val) {
19463      if (Enum->isDependentType())
19464        EltTy = Context.DependentTy;
19465      else if (!LastEnumConst) {
19466        // C++0x [dcl.enum]p5:
19467        //   If the underlying type is not fixed, the type of each enumerator
19468        //   is the type of its initializing value:
19469        //     - If no initializer is specified for the first enumerator, the
19470        //       initializing value has an unspecified integral type.
19471        //
19472        // GCC uses 'int' for its unspecified integral type, as does
19473        // C99 6.7.2.2p3.
19474        if (Enum->isFixed()) {
19475          EltTy = Enum->getIntegerType();
19476        }
19477        else {
19478          EltTy = Context.IntTy;
19479        }
19480      } else {
19481        // Assign the last value + 1.
19482        EnumVal = LastEnumConst->getInitVal();
19483        ++EnumVal;
19484        EltTy = LastEnumConst->getType();
19485  
19486        // Check for overflow on increment.
19487        if (EnumVal < LastEnumConst->getInitVal()) {
19488          // C++0x [dcl.enum]p5:
19489          //   If the underlying type is not fixed, the type of each enumerator
19490          //   is the type of its initializing value:
19491          //
19492          //     - Otherwise the type of the initializing value is the same as
19493          //       the type of the initializing value of the preceding enumerator
19494          //       unless the incremented value is not representable in that type,
19495          //       in which case the type is an unspecified integral type
19496          //       sufficient to contain the incremented value. If no such type
19497          //       exists, the program is ill-formed.
19498          QualType T = getNextLargerIntegralType(Context, EltTy);
19499          if (T.isNull() || Enum->isFixed()) {
19500            // There is no integral type larger enough to represent this
19501            // value. Complain, then allow the value to wrap around.
19502            EnumVal = LastEnumConst->getInitVal();
19503            EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
19504            ++EnumVal;
19505            if (Enum->isFixed())
19506              // When the underlying type is fixed, this is ill-formed.
19507              Diag(IdLoc, diag::err_enumerator_wrapped)
19508                << toString(EnumVal, 10)
19509                << EltTy;
19510            else
19511              Diag(IdLoc, diag::ext_enumerator_increment_too_large)
19512                << toString(EnumVal, 10);
19513          } else {
19514            EltTy = T;
19515          }
19516  
19517          // Retrieve the last enumerator's value, extent that type to the
19518          // type that is supposed to be large enough to represent the incremented
19519          // value, then increment.
19520          EnumVal = LastEnumConst->getInitVal();
19521          EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19522          EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
19523          ++EnumVal;
19524  
19525          // If we're not in C++, diagnose the overflow of enumerator values,
19526          // which in C99 means that the enumerator value is not representable in
19527          // an int (C99 6.7.2.2p2). However, we support GCC's extension that
19528          // permits enumerator values that are representable in some larger
19529          // integral type.
19530          if (!getLangOpts().CPlusPlus && !T.isNull())
19531            Diag(IdLoc, diag::warn_enum_value_overflow);
19532        } else if (!getLangOpts().CPlusPlus &&
19533                   !EltTy->isDependentType() &&
19534                   !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
19535          // Enforce C99 6.7.2.2p2 even when we compute the next value.
19536          Diag(IdLoc, diag::ext_enum_value_not_int)
19537            << toString(EnumVal, 10) << 1;
19538        }
19539      }
19540    }
19541  
19542    if (!EltTy->isDependentType()) {
19543      // Make the enumerator value match the signedness and size of the
19544      // enumerator's type.
19545      EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
19546      EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19547    }
19548  
19549    return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
19550                                    Val, EnumVal);
19551  }
19552  
shouldSkipAnonEnumBody(Scope * S,IdentifierInfo * II,SourceLocation IILoc)19553  SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
19554                                                  SourceLocation IILoc) {
19555    if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
19556        !getLangOpts().CPlusPlus)
19557      return SkipBodyInfo();
19558  
19559    // We have an anonymous enum definition. Look up the first enumerator to
19560    // determine if we should merge the definition with an existing one and
19561    // skip the body.
19562    NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
19563                                           forRedeclarationInCurContext());
19564    auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
19565    if (!PrevECD)
19566      return SkipBodyInfo();
19567  
19568    EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
19569    NamedDecl *Hidden;
19570    if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
19571      SkipBodyInfo Skip;
19572      Skip.Previous = Hidden;
19573      return Skip;
19574    }
19575  
19576    return SkipBodyInfo();
19577  }
19578  
ActOnEnumConstant(Scope * S,Decl * theEnumDecl,Decl * lastEnumConst,SourceLocation IdLoc,IdentifierInfo * Id,const ParsedAttributesView & Attrs,SourceLocation EqualLoc,Expr * Val)19579  Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
19580                                SourceLocation IdLoc, IdentifierInfo *Id,
19581                                const ParsedAttributesView &Attrs,
19582                                SourceLocation EqualLoc, Expr *Val) {
19583    EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
19584    EnumConstantDecl *LastEnumConst =
19585      cast_or_null<EnumConstantDecl>(lastEnumConst);
19586  
19587    // The scope passed in may not be a decl scope.  Zip up the scope tree until
19588    // we find one that is.
19589    S = getNonFieldDeclScope(S);
19590  
19591    // Verify that there isn't already something declared with this name in this
19592    // scope.
19593    LookupResult R(*this, Id, IdLoc, LookupOrdinaryName,
19594                   RedeclarationKind::ForVisibleRedeclaration);
19595    LookupName(R, S);
19596    NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
19597  
19598    if (PrevDecl && PrevDecl->isTemplateParameter()) {
19599      // Maybe we will complain about the shadowed template parameter.
19600      DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
19601      // Just pretend that we didn't see the previous declaration.
19602      PrevDecl = nullptr;
19603    }
19604  
19605    // C++ [class.mem]p15:
19606    // If T is the name of a class, then each of the following shall have a name
19607    // different from T:
19608    // - every enumerator of every member of class T that is an unscoped
19609    // enumerated type
19610    if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
19611      DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
19612                              DeclarationNameInfo(Id, IdLoc));
19613  
19614    EnumConstantDecl *New =
19615      CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
19616    if (!New)
19617      return nullptr;
19618  
19619    if (PrevDecl) {
19620      if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
19621        // Check for other kinds of shadowing not already handled.
19622        CheckShadow(New, PrevDecl, R);
19623      }
19624  
19625      // When in C++, we may get a TagDecl with the same name; in this case the
19626      // enum constant will 'hide' the tag.
19627      assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
19628             "Received TagDecl when not in C++!");
19629      if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
19630        if (isa<EnumConstantDecl>(PrevDecl))
19631          Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
19632        else
19633          Diag(IdLoc, diag::err_redefinition) << Id;
19634        notePreviousDefinition(PrevDecl, IdLoc);
19635        return nullptr;
19636      }
19637    }
19638  
19639    // Process attributes.
19640    ProcessDeclAttributeList(S, New, Attrs);
19641    AddPragmaAttributes(S, New);
19642    ProcessAPINotes(New);
19643  
19644    // Register this decl in the current scope stack.
19645    New->setAccess(TheEnumDecl->getAccess());
19646    PushOnScopeChains(New, S);
19647  
19648    ActOnDocumentableDecl(New);
19649  
19650    return New;
19651  }
19652  
19653  // Returns true when the enum initial expression does not trigger the
19654  // duplicate enum warning.  A few common cases are exempted as follows:
19655  // Element2 = Element1
19656  // Element2 = Element1 + 1
19657  // Element2 = Element1 - 1
19658  // Where Element2 and Element1 are from the same enum.
ValidDuplicateEnum(EnumConstantDecl * ECD,EnumDecl * Enum)19659  static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
19660    Expr *InitExpr = ECD->getInitExpr();
19661    if (!InitExpr)
19662      return true;
19663    InitExpr = InitExpr->IgnoreImpCasts();
19664  
19665    if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
19666      if (!BO->isAdditiveOp())
19667        return true;
19668      IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
19669      if (!IL)
19670        return true;
19671      if (IL->getValue() != 1)
19672        return true;
19673  
19674      InitExpr = BO->getLHS();
19675    }
19676  
19677    // This checks if the elements are from the same enum.
19678    DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
19679    if (!DRE)
19680      return true;
19681  
19682    EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
19683    if (!EnumConstant)
19684      return true;
19685  
19686    if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
19687        Enum)
19688      return true;
19689  
19690    return false;
19691  }
19692  
19693  // Emits a warning when an element is implicitly set a value that
19694  // a previous element has already been set to.
CheckForDuplicateEnumValues(Sema & S,ArrayRef<Decl * > Elements,EnumDecl * Enum,QualType EnumType)19695  static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
19696                                          EnumDecl *Enum, QualType EnumType) {
19697    // Avoid anonymous enums
19698    if (!Enum->getIdentifier())
19699      return;
19700  
19701    // Only check for small enums.
19702    if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
19703      return;
19704  
19705    if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
19706      return;
19707  
19708    typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
19709    typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
19710  
19711    typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
19712  
19713    // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
19714    typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
19715  
19716    // Use int64_t as a key to avoid needing special handling for map keys.
19717    auto EnumConstantToKey = [](const EnumConstantDecl *D) {
19718      llvm::APSInt Val = D->getInitVal();
19719      return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
19720    };
19721  
19722    DuplicatesVector DupVector;
19723    ValueToVectorMap EnumMap;
19724  
19725    // Populate the EnumMap with all values represented by enum constants without
19726    // an initializer.
19727    for (auto *Element : Elements) {
19728      EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
19729  
19730      // Null EnumConstantDecl means a previous diagnostic has been emitted for
19731      // this constant.  Skip this enum since it may be ill-formed.
19732      if (!ECD) {
19733        return;
19734      }
19735  
19736      // Constants with initializers are handled in the next loop.
19737      if (ECD->getInitExpr())
19738        continue;
19739  
19740      // Duplicate values are handled in the next loop.
19741      EnumMap.insert({EnumConstantToKey(ECD), ECD});
19742    }
19743  
19744    if (EnumMap.size() == 0)
19745      return;
19746  
19747    // Create vectors for any values that has duplicates.
19748    for (auto *Element : Elements) {
19749      // The last loop returned if any constant was null.
19750      EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
19751      if (!ValidDuplicateEnum(ECD, Enum))
19752        continue;
19753  
19754      auto Iter = EnumMap.find(EnumConstantToKey(ECD));
19755      if (Iter == EnumMap.end())
19756        continue;
19757  
19758      DeclOrVector& Entry = Iter->second;
19759      if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
19760        // Ensure constants are different.
19761        if (D == ECD)
19762          continue;
19763  
19764        // Create new vector and push values onto it.
19765        auto Vec = std::make_unique<ECDVector>();
19766        Vec->push_back(D);
19767        Vec->push_back(ECD);
19768  
19769        // Update entry to point to the duplicates vector.
19770        Entry = Vec.get();
19771  
19772        // Store the vector somewhere we can consult later for quick emission of
19773        // diagnostics.
19774        DupVector.emplace_back(std::move(Vec));
19775        continue;
19776      }
19777  
19778      ECDVector *Vec = Entry.get<ECDVector*>();
19779      // Make sure constants are not added more than once.
19780      if (*Vec->begin() == ECD)
19781        continue;
19782  
19783      Vec->push_back(ECD);
19784    }
19785  
19786    // Emit diagnostics.
19787    for (const auto &Vec : DupVector) {
19788      assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
19789  
19790      // Emit warning for one enum constant.
19791      auto *FirstECD = Vec->front();
19792      S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
19793        << FirstECD << toString(FirstECD->getInitVal(), 10)
19794        << FirstECD->getSourceRange();
19795  
19796      // Emit one note for each of the remaining enum constants with
19797      // the same value.
19798      for (auto *ECD : llvm::drop_begin(*Vec))
19799        S.Diag(ECD->getLocation(), diag::note_duplicate_element)
19800          << ECD << toString(ECD->getInitVal(), 10)
19801          << ECD->getSourceRange();
19802    }
19803  }
19804  
IsValueInFlagEnum(const EnumDecl * ED,const llvm::APInt & Val,bool AllowMask) const19805  bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
19806                               bool AllowMask) const {
19807    assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
19808    assert(ED->isCompleteDefinition() && "expected enum definition");
19809  
19810    auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
19811    llvm::APInt &FlagBits = R.first->second;
19812  
19813    if (R.second) {
19814      for (auto *E : ED->enumerators()) {
19815        const auto &EVal = E->getInitVal();
19816        // Only single-bit enumerators introduce new flag values.
19817        if (EVal.isPowerOf2())
19818          FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
19819      }
19820    }
19821  
19822    // A value is in a flag enum if either its bits are a subset of the enum's
19823    // flag bits (the first condition) or we are allowing masks and the same is
19824    // true of its complement (the second condition). When masks are allowed, we
19825    // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
19826    //
19827    // While it's true that any value could be used as a mask, the assumption is
19828    // that a mask will have all of the insignificant bits set. Anything else is
19829    // likely a logic error.
19830    llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
19831    return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
19832  }
19833  
ActOnEnumBody(SourceLocation EnumLoc,SourceRange BraceRange,Decl * EnumDeclX,ArrayRef<Decl * > Elements,Scope * S,const ParsedAttributesView & Attrs)19834  void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
19835                           Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
19836                           const ParsedAttributesView &Attrs) {
19837    EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
19838    QualType EnumType = Context.getTypeDeclType(Enum);
19839  
19840    ProcessDeclAttributeList(S, Enum, Attrs);
19841    ProcessAPINotes(Enum);
19842  
19843    if (Enum->isDependentType()) {
19844      for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
19845        EnumConstantDecl *ECD =
19846          cast_or_null<EnumConstantDecl>(Elements[i]);
19847        if (!ECD) continue;
19848  
19849        ECD->setType(EnumType);
19850      }
19851  
19852      Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
19853      return;
19854    }
19855  
19856    // TODO: If the result value doesn't fit in an int, it must be a long or long
19857    // long value.  ISO C does not support this, but GCC does as an extension,
19858    // emit a warning.
19859    unsigned IntWidth = Context.getTargetInfo().getIntWidth();
19860    unsigned CharWidth = Context.getTargetInfo().getCharWidth();
19861    unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
19862  
19863    // Verify that all the values are okay, compute the size of the values, and
19864    // reverse the list.
19865    unsigned NumNegativeBits = 0;
19866    unsigned NumPositiveBits = 0;
19867  
19868    for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
19869      EnumConstantDecl *ECD =
19870        cast_or_null<EnumConstantDecl>(Elements[i]);
19871      if (!ECD) continue;  // Already issued a diagnostic.
19872  
19873      const llvm::APSInt &InitVal = ECD->getInitVal();
19874  
19875      // Keep track of the size of positive and negative values.
19876      if (InitVal.isUnsigned() || InitVal.isNonNegative()) {
19877        // If the enumerator is zero that should still be counted as a positive
19878        // bit since we need a bit to store the value zero.
19879        unsigned ActiveBits = InitVal.getActiveBits();
19880        NumPositiveBits = std::max({NumPositiveBits, ActiveBits, 1u});
19881      } else {
19882        NumNegativeBits =
19883            std::max(NumNegativeBits, (unsigned)InitVal.getSignificantBits());
19884      }
19885    }
19886  
19887    // If we have an empty set of enumerators we still need one bit.
19888    // From [dcl.enum]p8
19889    // If the enumerator-list is empty, the values of the enumeration are as if
19890    // the enumeration had a single enumerator with value 0
19891    if (!NumPositiveBits && !NumNegativeBits)
19892      NumPositiveBits = 1;
19893  
19894    // Figure out the type that should be used for this enum.
19895    QualType BestType;
19896    unsigned BestWidth;
19897  
19898    // C++0x N3000 [conv.prom]p3:
19899    //   An rvalue of an unscoped enumeration type whose underlying
19900    //   type is not fixed can be converted to an rvalue of the first
19901    //   of the following types that can represent all the values of
19902    //   the enumeration: int, unsigned int, long int, unsigned long
19903    //   int, long long int, or unsigned long long int.
19904    // C99 6.4.4.3p2:
19905    //   An identifier declared as an enumeration constant has type int.
19906    // The C99 rule is modified by a gcc extension
19907    QualType BestPromotionType;
19908  
19909    bool Packed = Enum->hasAttr<PackedAttr>();
19910    // -fshort-enums is the equivalent to specifying the packed attribute on all
19911    // enum definitions.
19912    if (LangOpts.ShortEnums)
19913      Packed = true;
19914  
19915    // If the enum already has a type because it is fixed or dictated by the
19916    // target, promote that type instead of analyzing the enumerators.
19917    if (Enum->isComplete()) {
19918      BestType = Enum->getIntegerType();
19919      if (Context.isPromotableIntegerType(BestType))
19920        BestPromotionType = Context.getPromotedIntegerType(BestType);
19921      else
19922        BestPromotionType = BestType;
19923  
19924      BestWidth = Context.getIntWidth(BestType);
19925    }
19926    else if (NumNegativeBits) {
19927      // If there is a negative value, figure out the smallest integer type (of
19928      // int/long/longlong) that fits.
19929      // If it's packed, check also if it fits a char or a short.
19930      if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
19931        BestType = Context.SignedCharTy;
19932        BestWidth = CharWidth;
19933      } else if (Packed && NumNegativeBits <= ShortWidth &&
19934                 NumPositiveBits < ShortWidth) {
19935        BestType = Context.ShortTy;
19936        BestWidth = ShortWidth;
19937      } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
19938        BestType = Context.IntTy;
19939        BestWidth = IntWidth;
19940      } else {
19941        BestWidth = Context.getTargetInfo().getLongWidth();
19942  
19943        if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
19944          BestType = Context.LongTy;
19945        } else {
19946          BestWidth = Context.getTargetInfo().getLongLongWidth();
19947  
19948          if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
19949            Diag(Enum->getLocation(), diag::ext_enum_too_large);
19950          BestType = Context.LongLongTy;
19951        }
19952      }
19953      BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
19954    } else {
19955      // If there is no negative value, figure out the smallest type that fits
19956      // all of the enumerator values.
19957      // If it's packed, check also if it fits a char or a short.
19958      if (Packed && NumPositiveBits <= CharWidth) {
19959        BestType = Context.UnsignedCharTy;
19960        BestPromotionType = Context.IntTy;
19961        BestWidth = CharWidth;
19962      } else if (Packed && NumPositiveBits <= ShortWidth) {
19963        BestType = Context.UnsignedShortTy;
19964        BestPromotionType = Context.IntTy;
19965        BestWidth = ShortWidth;
19966      } else if (NumPositiveBits <= IntWidth) {
19967        BestType = Context.UnsignedIntTy;
19968        BestWidth = IntWidth;
19969        BestPromotionType
19970          = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
19971                             ? Context.UnsignedIntTy : Context.IntTy;
19972      } else if (NumPositiveBits <=
19973                 (BestWidth = Context.getTargetInfo().getLongWidth())) {
19974        BestType = Context.UnsignedLongTy;
19975        BestPromotionType
19976          = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
19977                             ? Context.UnsignedLongTy : Context.LongTy;
19978      } else {
19979        BestWidth = Context.getTargetInfo().getLongLongWidth();
19980        if (NumPositiveBits > BestWidth) {
19981          // This can happen with bit-precise integer types, but those are not
19982          // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.
19983          // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within
19984          // a 128-bit integer, we should consider doing the same.
19985          Diag(Enum->getLocation(), diag::ext_enum_too_large);
19986        }
19987        BestType = Context.UnsignedLongLongTy;
19988        BestPromotionType
19989          = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
19990                             ? Context.UnsignedLongLongTy : Context.LongLongTy;
19991      }
19992    }
19993  
19994    // Loop over all of the enumerator constants, changing their types to match
19995    // the type of the enum if needed.
19996    for (auto *D : Elements) {
19997      auto *ECD = cast_or_null<EnumConstantDecl>(D);
19998      if (!ECD) continue;  // Already issued a diagnostic.
19999  
20000      // Standard C says the enumerators have int type, but we allow, as an
20001      // extension, the enumerators to be larger than int size.  If each
20002      // enumerator value fits in an int, type it as an int, otherwise type it the
20003      // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
20004      // that X has type 'int', not 'unsigned'.
20005  
20006      // Determine whether the value fits into an int.
20007      llvm::APSInt InitVal = ECD->getInitVal();
20008  
20009      // If it fits into an integer type, force it.  Otherwise force it to match
20010      // the enum decl type.
20011      QualType NewTy;
20012      unsigned NewWidth;
20013      bool NewSign;
20014      if (!getLangOpts().CPlusPlus &&
20015          !Enum->isFixed() &&
20016          isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
20017        NewTy = Context.IntTy;
20018        NewWidth = IntWidth;
20019        NewSign = true;
20020      } else if (ECD->getType() == BestType) {
20021        // Already the right type!
20022        if (getLangOpts().CPlusPlus)
20023          // C++ [dcl.enum]p4: Following the closing brace of an
20024          // enum-specifier, each enumerator has the type of its
20025          // enumeration.
20026          ECD->setType(EnumType);
20027        continue;
20028      } else {
20029        NewTy = BestType;
20030        NewWidth = BestWidth;
20031        NewSign = BestType->isSignedIntegerOrEnumerationType();
20032      }
20033  
20034      // Adjust the APSInt value.
20035      InitVal = InitVal.extOrTrunc(NewWidth);
20036      InitVal.setIsSigned(NewSign);
20037      ECD->setInitVal(Context, InitVal);
20038  
20039      // Adjust the Expr initializer and type.
20040      if (ECD->getInitExpr() &&
20041          !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
20042        ECD->setInitExpr(ImplicitCastExpr::Create(
20043            Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
20044            /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
20045      if (getLangOpts().CPlusPlus)
20046        // C++ [dcl.enum]p4: Following the closing brace of an
20047        // enum-specifier, each enumerator has the type of its
20048        // enumeration.
20049        ECD->setType(EnumType);
20050      else
20051        ECD->setType(NewTy);
20052    }
20053  
20054    Enum->completeDefinition(BestType, BestPromotionType,
20055                             NumPositiveBits, NumNegativeBits);
20056  
20057    CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
20058  
20059    if (Enum->isClosedFlag()) {
20060      for (Decl *D : Elements) {
20061        EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
20062        if (!ECD) continue;  // Already issued a diagnostic.
20063  
20064        llvm::APSInt InitVal = ECD->getInitVal();
20065        if (InitVal != 0 && !InitVal.isPowerOf2() &&
20066            !IsValueInFlagEnum(Enum, InitVal, true))
20067          Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
20068            << ECD << Enum;
20069      }
20070    }
20071  
20072    // Now that the enum type is defined, ensure it's not been underaligned.
20073    if (Enum->hasAttrs())
20074      CheckAlignasUnderalignment(Enum);
20075  }
20076  
ActOnFileScopeAsmDecl(Expr * expr,SourceLocation StartLoc,SourceLocation EndLoc)20077  Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
20078                                    SourceLocation StartLoc,
20079                                    SourceLocation EndLoc) {
20080    StringLiteral *AsmString = cast<StringLiteral>(expr);
20081  
20082    FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
20083                                                     AsmString, StartLoc,
20084                                                     EndLoc);
20085    CurContext->addDecl(New);
20086    return New;
20087  }
20088  
ActOnStartTopLevelStmtDecl(Scope * S)20089  TopLevelStmtDecl *Sema::ActOnStartTopLevelStmtDecl(Scope *S) {
20090    auto *New = TopLevelStmtDecl::Create(Context, /*Statement=*/nullptr);
20091    CurContext->addDecl(New);
20092    PushDeclContext(S, New);
20093    PushFunctionScope();
20094    PushCompoundScope(false);
20095    return New;
20096  }
20097  
ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl * D,Stmt * Statement)20098  void Sema::ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement) {
20099    D->setStmt(Statement);
20100    PopCompoundScope();
20101    PopFunctionScopeInfo();
20102    PopDeclContext();
20103  }
20104  
ActOnPragmaRedefineExtname(IdentifierInfo * Name,IdentifierInfo * AliasName,SourceLocation PragmaLoc,SourceLocation NameLoc,SourceLocation AliasNameLoc)20105  void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
20106                                        IdentifierInfo* AliasName,
20107                                        SourceLocation PragmaLoc,
20108                                        SourceLocation NameLoc,
20109                                        SourceLocation AliasNameLoc) {
20110    NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
20111                                           LookupOrdinaryName);
20112    AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
20113                             AttributeCommonInfo::Form::Pragma());
20114    AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
20115        Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
20116  
20117    // If a declaration that:
20118    // 1) declares a function or a variable
20119    // 2) has external linkage
20120    // already exists, add a label attribute to it.
20121    if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20122      if (isDeclExternC(PrevDecl))
20123        PrevDecl->addAttr(Attr);
20124      else
20125        Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
20126            << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
20127      // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
20128    } else
20129      (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
20130  }
20131  
ActOnPragmaWeakID(IdentifierInfo * Name,SourceLocation PragmaLoc,SourceLocation NameLoc)20132  void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
20133                               SourceLocation PragmaLoc,
20134                               SourceLocation NameLoc) {
20135    Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
20136  
20137    if (PrevDecl) {
20138      PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
20139    } else {
20140      (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
20141    }
20142  }
20143  
ActOnPragmaWeakAlias(IdentifierInfo * Name,IdentifierInfo * AliasName,SourceLocation PragmaLoc,SourceLocation NameLoc,SourceLocation AliasNameLoc)20144  void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
20145                                  IdentifierInfo* AliasName,
20146                                  SourceLocation PragmaLoc,
20147                                  SourceLocation NameLoc,
20148                                  SourceLocation AliasNameLoc) {
20149    Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
20150                                      LookupOrdinaryName);
20151    WeakInfo W = WeakInfo(Name, NameLoc);
20152  
20153    if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20154      if (!PrevDecl->hasAttr<AliasAttr>())
20155        if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
20156          DeclApplyPragmaWeak(TUScope, ND, W);
20157    } else {
20158      (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
20159    }
20160  }
20161  
getEmissionStatus(const FunctionDecl * FD,bool Final)20162  Sema::FunctionEmissionStatus Sema::getEmissionStatus(const FunctionDecl *FD,
20163                                                       bool Final) {
20164    assert(FD && "Expected non-null FunctionDecl");
20165  
20166    // SYCL functions can be template, so we check if they have appropriate
20167    // attribute prior to checking if it is a template.
20168    if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
20169      return FunctionEmissionStatus::Emitted;
20170  
20171    // Templates are emitted when they're instantiated.
20172    if (FD->isDependentContext())
20173      return FunctionEmissionStatus::TemplateDiscarded;
20174  
20175    // Check whether this function is an externally visible definition.
20176    auto IsEmittedForExternalSymbol = [this, FD]() {
20177      // We have to check the GVA linkage of the function's *definition* -- if we
20178      // only have a declaration, we don't know whether or not the function will
20179      // be emitted, because (say) the definition could include "inline".
20180      const FunctionDecl *Def = FD->getDefinition();
20181  
20182      return Def && !isDiscardableGVALinkage(
20183                        getASTContext().GetGVALinkageForFunction(Def));
20184    };
20185  
20186    if (LangOpts.OpenMPIsTargetDevice) {
20187      // In OpenMP device mode we will not emit host only functions, or functions
20188      // we don't need due to their linkage.
20189      std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20190          OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20191      // DevTy may be changed later by
20192      //  #pragma omp declare target to(*) device_type(*).
20193      // Therefore DevTy having no value does not imply host. The emission status
20194      // will be checked again at the end of compilation unit with Final = true.
20195      if (DevTy)
20196        if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
20197          return FunctionEmissionStatus::OMPDiscarded;
20198      // If we have an explicit value for the device type, or we are in a target
20199      // declare context, we need to emit all extern and used symbols.
20200      if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy)
20201        if (IsEmittedForExternalSymbol())
20202          return FunctionEmissionStatus::Emitted;
20203      // Device mode only emits what it must, if it wasn't tagged yet and needed,
20204      // we'll omit it.
20205      if (Final)
20206        return FunctionEmissionStatus::OMPDiscarded;
20207    } else if (LangOpts.OpenMP > 45) {
20208      // In OpenMP host compilation prior to 5.0 everything was an emitted host
20209      // function. In 5.0, no_host was introduced which might cause a function to
20210      // be omitted.
20211      std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20212          OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20213      if (DevTy)
20214        if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
20215          return FunctionEmissionStatus::OMPDiscarded;
20216    }
20217  
20218    if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
20219      return FunctionEmissionStatus::Emitted;
20220  
20221    if (LangOpts.CUDA) {
20222      // When compiling for device, host functions are never emitted.  Similarly,
20223      // when compiling for host, device and global functions are never emitted.
20224      // (Technically, we do emit a host-side stub for global functions, but this
20225      // doesn't count for our purposes here.)
20226      CUDAFunctionTarget T = CUDA().IdentifyTarget(FD);
20227      if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host)
20228        return FunctionEmissionStatus::CUDADiscarded;
20229      if (!LangOpts.CUDAIsDevice &&
20230          (T == CUDAFunctionTarget::Device || T == CUDAFunctionTarget::Global))
20231        return FunctionEmissionStatus::CUDADiscarded;
20232  
20233      if (IsEmittedForExternalSymbol())
20234        return FunctionEmissionStatus::Emitted;
20235    }
20236  
20237    // Otherwise, the function is known-emitted if it's in our set of
20238    // known-emitted functions.
20239    return FunctionEmissionStatus::Unknown;
20240  }
20241  
shouldIgnoreInHostDeviceCheck(FunctionDecl * Callee)20242  bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
20243    // Host-side references to a __global__ function refer to the stub, so the
20244    // function itself is never emitted and therefore should not be marked.
20245    // If we have host fn calls kernel fn calls host+device, the HD function
20246    // does not get instantiated on the host. We model this by omitting at the
20247    // call to the kernel from the callgraph. This ensures that, when compiling
20248    // for host, only HD functions actually called from the host get marked as
20249    // known-emitted.
20250    return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
20251           CUDA().IdentifyTarget(Callee) == CUDAFunctionTarget::Global;
20252  }
20253  
diagnoseFunctionEffectMergeConflicts(const FunctionEffectSet::Conflicts & Errs,SourceLocation NewLoc,SourceLocation OldLoc)20254  void Sema::diagnoseFunctionEffectMergeConflicts(
20255      const FunctionEffectSet::Conflicts &Errs, SourceLocation NewLoc,
20256      SourceLocation OldLoc) {
20257    for (const FunctionEffectSet::Conflict &Conflict : Errs) {
20258      Diag(NewLoc, diag::warn_conflicting_func_effects)
20259          << Conflict.Kept.description() << Conflict.Rejected.description();
20260      Diag(OldLoc, diag::note_previous_declaration);
20261    }
20262  }
20263  
diagnoseConflictingFunctionEffect(const FunctionEffectsRef & FX,const FunctionEffectWithCondition & NewEC,SourceLocation NewAttrLoc)20264  bool Sema::diagnoseConflictingFunctionEffect(
20265      const FunctionEffectsRef &FX, const FunctionEffectWithCondition &NewEC,
20266      SourceLocation NewAttrLoc) {
20267    // If the new effect has a condition, we can't detect conflicts until the
20268    // condition is resolved.
20269    if (NewEC.Cond.getCondition() != nullptr)
20270      return false;
20271  
20272    // Diagnose the new attribute as incompatible with a previous one.
20273    auto Incompatible = [&](const FunctionEffectWithCondition &PrevEC) {
20274      Diag(NewAttrLoc, diag::err_attributes_are_not_compatible)
20275          << ("'" + NewEC.description() + "'")
20276          << ("'" + PrevEC.description() + "'") << false;
20277      // We don't necessarily have the location of the previous attribute,
20278      // so no note.
20279      return true;
20280    };
20281  
20282    // Compare against previous attributes.
20283    FunctionEffect::Kind NewKind = NewEC.Effect.kind();
20284  
20285    for (const FunctionEffectWithCondition &PrevEC : FX) {
20286      // Again, can't check yet when the effect is conditional.
20287      if (PrevEC.Cond.getCondition() != nullptr)
20288        continue;
20289  
20290      FunctionEffect::Kind PrevKind = PrevEC.Effect.kind();
20291      // Note that we allow PrevKind == NewKind; it's redundant and ignored.
20292  
20293      if (PrevEC.Effect.oppositeKind() == NewKind)
20294        return Incompatible(PrevEC);
20295  
20296      // A new allocating is incompatible with a previous nonblocking.
20297      if (PrevKind == FunctionEffect::Kind::NonBlocking &&
20298          NewKind == FunctionEffect::Kind::Allocating)
20299        return Incompatible(PrevEC);
20300  
20301      // A new nonblocking is incompatible with a previous allocating.
20302      if (PrevKind == FunctionEffect::Kind::Allocating &&
20303          NewKind == FunctionEffect::Kind::NonBlocking)
20304        return Incompatible(PrevEC);
20305    }
20306  
20307    return false;
20308  }
20309