diff options
| author | Dimitry Andric <dim@FreeBSD.org> | 2023-04-17 17:14:23 +0000 |
|---|---|---|
| committer | Dimitry Andric <dim@FreeBSD.org> | 2023-06-22 18:22:20 +0000 |
| commit | 1ac55f4cb0001fed92329746c730aa9a947c09a5 (patch) | |
| tree | 78b2d7f739b7a4b29aa297366416bf701b6ebde8 /contrib/llvm-project/clang/lib | |
| parent | bdd1243df58e60e85101c09001d9812a789b6bc4 (diff) | |
| parent | 8a37c71e9d8855c91b9ef296ed389248f960bb52 (diff) | |
Diffstat (limited to 'contrib/llvm-project/clang/lib')
58 files changed, 716 insertions, 608 deletions
diff --git a/contrib/llvm-project/clang/lib/AST/ExprConstant.cpp b/contrib/llvm-project/clang/lib/AST/ExprConstant.cpp index 0403165a8e55..464104139cb2 100644 --- a/contrib/llvm-project/clang/lib/AST/ExprConstant.cpp +++ b/contrib/llvm-project/clang/lib/AST/ExprConstant.cpp @@ -10916,7 +10916,7 @@ bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, for (unsigned I = OldElts; I < N; ++I) Value->getArrayInitializedElt(I) = Filler; - if (HasTrivialConstructor && N == FinalSize) { + if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) { // If we have a trivial constructor, only evaluate it once and copy // the result into all the array elements. APValue &FirstResult = Value->getArrayInitializedElt(0); diff --git a/contrib/llvm-project/clang/lib/AST/Type.cpp b/contrib/llvm-project/clang/lib/AST/Type.cpp index a713d6e3bd03..54e62a1939f7 100644 --- a/contrib/llvm-project/clang/lib/AST/Type.cpp +++ b/contrib/llvm-project/clang/lib/AST/Type.cpp @@ -2487,11 +2487,13 @@ bool QualType::isTrivialType(const ASTContext &Context) const { return true; if (const auto *RT = CanonicalType->getAs<RecordType>()) { if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) { - // C++11 [class]p6: - // A trivial class is a class that has a default constructor, - // has no non-trivial default constructors, and is trivially - // copyable. - return ClassDecl->hasDefaultConstructor() && + // C++20 [class]p6: + // A trivial class is a class that is trivially copyable, and + // has one or more eligible default constructors such that each is + // trivial. + // FIXME: We should merge this definition of triviality into + // CXXRecordDecl::isTrivial. Currently it computes the wrong thing. + return ClassDecl->hasTrivialDefaultConstructor() && !ClassDecl->hasNonTrivialDefaultConstructor() && ClassDecl->isTriviallyCopyable(); } diff --git a/contrib/llvm-project/clang/lib/Basic/Targets/AArch64.cpp b/contrib/llvm-project/clang/lib/Basic/Targets/AArch64.cpp index dfed95f0513f..997398da7972 100644 --- a/contrib/llvm-project/clang/lib/Basic/Targets/AArch64.cpp +++ b/contrib/llvm-project/clang/lib/Basic/Targets/AArch64.cpp @@ -687,9 +687,13 @@ void AArch64TargetInfo::setFeatureEnabled(llvm::StringMap<bool> &Features, if (ArchInfo == llvm::AArch64::INVALID) return; // Not an architecure, nothing more to do. + // Disabling an architecture feature does not affect dependent features + if (!Enabled) + return; + for (const auto *OtherArch : llvm::AArch64::ArchInfos) if (ArchInfo.implies(*OtherArch)) - Features[OtherArch->getSubArch()] = Enabled; + Features[OtherArch->getSubArch()] = true; // Set any features implied by the architecture uint64_t Extensions = diff --git a/contrib/llvm-project/clang/lib/Basic/Targets/ARM.cpp b/contrib/llvm-project/clang/lib/Basic/Targets/ARM.cpp index f11751a76073..b85d5dc2d347 100644 --- a/contrib/llvm-project/clang/lib/Basic/Targets/ARM.cpp +++ b/contrib/llvm-project/clang/lib/Basic/Targets/ARM.cpp @@ -254,6 +254,7 @@ ARMTargetInfo::ARMTargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts) : TargetInfo(Triple), FPMath(FP_Default), IsAAPCS(true), LDREX(0), HW_FP(0) { + bool IsFreeBSD = Triple.isOSFreeBSD(); bool IsOpenBSD = Triple.isOSOpenBSD(); bool IsNetBSD = Triple.isOSNetBSD(); @@ -321,7 +322,7 @@ ARMTargetInfo::ARMTargetInfo(const llvm::Triple &Triple, default: if (IsNetBSD) setABI("apcs-gnu"); - else if (IsOpenBSD) + else if (IsFreeBSD || IsOpenBSD) setABI("aapcs-linux"); else setABI("aapcs"); diff --git a/contrib/llvm-project/clang/lib/Basic/Targets/PPC.h b/contrib/llvm-project/clang/lib/Basic/Targets/PPC.h index 6951119e729c..c8197154fff7 100644 --- a/contrib/llvm-project/clang/lib/Basic/Targets/PPC.h +++ b/contrib/llvm-project/clang/lib/Basic/Targets/PPC.h @@ -426,12 +426,12 @@ public: } else if ((Triple.getArch() == llvm::Triple::ppc64le)) { DataLayout = "e-m:e-i64:64-n32:64"; ABI = "elfv2"; - } else if (Triple.isOSFreeBSD() && (Triple.getOSMajorVersion() == 0 || Triple.getOSMajorVersion() >= 13)) { - DataLayout = "E-m:e-i64:64-n32:64"; - ABI = "elfv2"; } else { DataLayout = "E-m:e-i64:64-n32:64"; - ABI = "elfv1"; + if (Triple.isPPC64ELFv2ABI()) + ABI = "elfv2"; + else + ABI = "elfv1"; } if (Triple.isOSFreeBSD() || Triple.isOSOpenBSD() || Triple.isMusl()) { diff --git a/contrib/llvm-project/clang/lib/Basic/Targets/RISCV.cpp b/contrib/llvm-project/clang/lib/Basic/Targets/RISCV.cpp index 25fda05da033..7c801657b6ac 100644 --- a/contrib/llvm-project/clang/lib/Basic/Targets/RISCV.cpp +++ b/contrib/llvm-project/clang/lib/Basic/Targets/RISCV.cpp @@ -197,8 +197,8 @@ void RISCVTargetInfo::getTargetDefines(const LangOptions &Opts, if (ISAInfo->hasExtension("zve32x")) { Builder.defineMacro("__riscv_vector"); - // Currently we support the v0.10 RISC-V V intrinsics. - Builder.defineMacro("__riscv_v_intrinsic", Twine(getVersionValue(0, 10))); + // Currently we support the v0.11 RISC-V V intrinsics. + Builder.defineMacro("__riscv_v_intrinsic", Twine(getVersionValue(0, 11))); } } diff --git a/contrib/llvm-project/clang/lib/Basic/Targets/X86.cpp b/contrib/llvm-project/clang/lib/Basic/Targets/X86.cpp index cb3171227530..490e20ce4514 100644 --- a/contrib/llvm-project/clang/lib/Basic/Targets/X86.cpp +++ b/contrib/llvm-project/clang/lib/Basic/Targets/X86.cpp @@ -795,13 +795,13 @@ void X86TargetInfo::getTargetDefines(const LangOptions &Opts, if (HasHRESET) Builder.defineMacro("__HRESET__"); if (HasAMXTILE) - Builder.defineMacro("__AMXTILE__"); + Builder.defineMacro("__AMX_TILE__"); if (HasAMXINT8) - Builder.defineMacro("__AMXINT8__"); + Builder.defineMacro("__AMX_INT8__"); if (HasAMXBF16) - Builder.defineMacro("__AMXBF16__"); + Builder.defineMacro("__AMX_BF16__"); if (HasAMXFP16) - Builder.defineMacro("__AMXFP16__"); + Builder.defineMacro("__AMX_FP16__"); if (HasCMPCCXADD) Builder.defineMacro("__CMPCCXADD__"); if (HasRAOINT) diff --git a/contrib/llvm-project/clang/lib/CodeGen/CGCXXABI.h b/contrib/llvm-project/clang/lib/CodeGen/CGCXXABI.h index a600768b2074..78646996eac2 100644 --- a/contrib/llvm-project/clang/lib/CodeGen/CGCXXABI.h +++ b/contrib/llvm-project/clang/lib/CodeGen/CGCXXABI.h @@ -379,9 +379,8 @@ public: /// zero if no specific type is applicable, e.g. if the ABI expects the "this" /// parameter to point to some artificial offset in a complete object due to /// vbases being reordered. - virtual const CXXRecordDecl * - getThisArgumentTypeForMethod(const CXXMethodDecl *MD) { - return MD->getParent(); + virtual const CXXRecordDecl *getThisArgumentTypeForMethod(GlobalDecl GD) { + return cast<CXXMethodDecl>(GD.getDecl())->getParent(); } /// Perform ABI-specific "this" argument adjustment required prior to diff --git a/contrib/llvm-project/clang/lib/CodeGen/CGCall.cpp b/contrib/llvm-project/clang/lib/CodeGen/CGCall.cpp index dfa552161d7c..ee5b76ab2120 100644 --- a/contrib/llvm-project/clang/lib/CodeGen/CGCall.cpp +++ b/contrib/llvm-project/clang/lib/CodeGen/CGCall.cpp @@ -322,7 +322,9 @@ CodeGenTypes::arrangeCXXStructorDeclaration(GlobalDecl GD) { SmallVector<CanQualType, 16> argTypes; SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos; - argTypes.push_back(DeriveThisType(MD->getParent(), MD)); + + const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(GD); + argTypes.push_back(DeriveThisType(ThisType, MD)); bool PassParams = true; diff --git a/contrib/llvm-project/clang/lib/CodeGen/CGExprCXX.cpp b/contrib/llvm-project/clang/lib/CodeGen/CGExprCXX.cpp index b889a4e05ee1..a9f3434589f2 100644 --- a/contrib/llvm-project/clang/lib/CodeGen/CGExprCXX.cpp +++ b/contrib/llvm-project/clang/lib/CodeGen/CGExprCXX.cpp @@ -33,10 +33,12 @@ struct MemberCallInfo { } static MemberCallInfo -commonEmitCXXMemberOrOperatorCall(CodeGenFunction &CGF, const CXXMethodDecl *MD, +commonEmitCXXMemberOrOperatorCall(CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy, const CallExpr *CE, CallArgList &Args, CallArgList *RtlArgs) { + auto *MD = cast<CXXMethodDecl>(GD.getDecl()); + assert(CE == nullptr || isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr>(CE)); assert(MD->isInstance() && @@ -44,7 +46,7 @@ commonEmitCXXMemberOrOperatorCall(CodeGenFunction &CGF, const CXXMethodDecl *MD, // Push the this ptr. const CXXRecordDecl *RD = - CGF.CGM.getCXXABI().getThisArgumentTypeForMethod(MD); + CGF.CGM.getCXXABI().getThisArgumentTypeForMethod(GD); Args.add(RValue::get(This), CGF.getTypes().DeriveThisType(RD, MD)); // If there is an implicit parameter (e.g. VTT), emit it. @@ -110,7 +112,7 @@ RValue CodeGenFunction::EmitCXXDestructorCall( } CallArgList Args; - commonEmitCXXMemberOrOperatorCall(*this, DtorDecl, This, ImplicitParam, + commonEmitCXXMemberOrOperatorCall(*this, Dtor, This, ImplicitParam, ImplicitParamTy, CE, Args, nullptr); return EmitCall(CGM.getTypes().arrangeCXXStructorDeclaration(Dtor), Callee, ReturnValueSlot(), Args, nullptr, CE && CE == MustTailCall, @@ -285,7 +287,8 @@ RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr( assert(ReturnValue.isNull() && "Constructor shouldn't have return value"); CallArgList Args; commonEmitCXXMemberOrOperatorCall( - *this, Ctor, This.getPointer(*this), /*ImplicitParam=*/nullptr, + *this, {Ctor, Ctor_Complete}, This.getPointer(*this), + /*ImplicitParam=*/nullptr, /*ImplicitParamTy=*/QualType(), CE, Args, nullptr); EmitCXXConstructorCall(Ctor, Ctor_Complete, /*ForVirtualBase=*/false, diff --git a/contrib/llvm-project/clang/lib/CodeGen/MicrosoftCXXABI.cpp b/contrib/llvm-project/clang/lib/CodeGen/MicrosoftCXXABI.cpp index ae785cce09f9..52d442cc587f 100644 --- a/contrib/llvm-project/clang/lib/CodeGen/MicrosoftCXXABI.cpp +++ b/contrib/llvm-project/clang/lib/CodeGen/MicrosoftCXXABI.cpp @@ -235,11 +235,24 @@ public: void EmitCXXDestructors(const CXXDestructorDecl *D) override; - const CXXRecordDecl * - getThisArgumentTypeForMethod(const CXXMethodDecl *MD) override { - if (MD->isVirtual() && !isa<CXXDestructorDecl>(MD)) { + const CXXRecordDecl *getThisArgumentTypeForMethod(GlobalDecl GD) override { + auto *MD = cast<CXXMethodDecl>(GD.getDecl()); + + if (MD->isVirtual()) { + GlobalDecl LookupGD = GD; + if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) { + // Complete dtors take a pointer to the complete object, + // thus don't need adjustment. + if (GD.getDtorType() == Dtor_Complete) + return MD->getParent(); + + // There's only Dtor_Deleting in vftable but it shares the this + // adjustment with the base one, so look up the deleting one instead. + LookupGD = GlobalDecl(DD, Dtor_Deleting); + } MethodVFTableLocation ML = - CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD); + CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD); + // The vbases might be ordered differently in the final overrider object // and the complete object, so the "this" argument may sometimes point to // memory that has no particular type (e.g. past the complete object). diff --git a/contrib/llvm-project/clang/lib/CodeGen/TargetInfo.cpp b/contrib/llvm-project/clang/lib/CodeGen/TargetInfo.cpp index be1dbe8480c6..9e2d7a85d100 100644 --- a/contrib/llvm-project/clang/lib/CodeGen/TargetInfo.cpp +++ b/contrib/llvm-project/clang/lib/CodeGen/TargetInfo.cpp @@ -2381,9 +2381,7 @@ class X86_64ABIInfo : public ABIInfo { return false; const llvm::Triple &Triple = getTarget().getTriple(); - if (Triple.isOSDarwin() || Triple.isPS()) - return false; - if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10) + if (Triple.isOSDarwin() || Triple.isPS() || Triple.isOSFreeBSD()) return false; return true; } @@ -7418,18 +7416,28 @@ public: }; class SystemZTargetCodeGenInfo : public TargetCodeGenInfo { + ASTContext &Ctx; + + const SystemZABIInfo &getABIInfo() const { + return static_cast<const SystemZABIInfo&>(TargetCodeGenInfo::getABIInfo()); + } + // These are used for speeding up the search for a visible vector ABI. mutable bool HasVisibleVecABIFlag = false; mutable std::set<const Type *> SeenTypes; - // Returns true (the first time) if Ty is or found to make use of a vector - // type (e.g. as a function argument). - bool isVectorTypeBased(const Type *Ty) const; + // Returns true (the first time) if Ty is, or is found to include, a vector + // type that exposes the vector ABI. This is any vector >=16 bytes which + // with vector support are aligned to only 8 bytes. When IsParam is true, + // the type belongs to a value as passed between functions. If it is a + // vector <=16 bytes it will be passed in a vector register (if supported). + bool isVectorTypeBased(const Type *Ty, bool IsParam) const; public: SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector, bool SoftFloatABI) : TargetCodeGenInfo( - std::make_unique<SystemZABIInfo>(CGT, HasVector, SoftFloatABI)) { + std::make_unique<SystemZABIInfo>(CGT, HasVector, SoftFloatABI)), + Ctx(CGT.getContext()) { SwiftInfo = std::make_unique<SwiftABIInfo>(CGT, /*SwiftErrorInRegister=*/false); } @@ -7439,9 +7447,9 @@ public: // indicating a visible vector ABI is added. Eventually this will result in // a GNU attribute indicating the vector ABI of the module. Ty is the type // of a variable or function parameter that is globally visible. - void handleExternallyVisibleObjABI(const Type *Ty, - CodeGen::CodeGenModule &M) const { - if (!HasVisibleVecABIFlag && isVectorTypeBased(Ty)) { + void handleExternallyVisibleObjABI(const Type *Ty, CodeGen::CodeGenModule &M, + bool IsParam) const { + if (!HasVisibleVecABIFlag && isVectorTypeBased(Ty, IsParam)) { M.getModule().addModuleFlag(llvm::Module::Warning, "s390x-visible-vector-ABI", 1); HasVisibleVecABIFlag = true; @@ -7457,11 +7465,13 @@ public: // variable or function. if (const auto *VD = dyn_cast<VarDecl>(D)) { if (VD->isExternallyVisible()) - handleExternallyVisibleObjABI(VD->getType().getTypePtr(), M); + handleExternallyVisibleObjABI(VD->getType().getTypePtr(), M, + /*IsParam*/false); } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { if (FD->isExternallyVisible()) - handleExternallyVisibleObjABI(FD->getType().getTypePtr(), M); + handleExternallyVisibleObjABI(FD->getType().getTypePtr(), M, + /*IsParam*/false); } } @@ -7571,17 +7581,18 @@ QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const { // If this is a C++ record, check the bases first. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) - for (const auto &I : CXXRD->bases()) { - QualType Base = I.getType(); + if (CXXRD->hasDefinition()) + for (const auto &I : CXXRD->bases()) { + QualType Base = I.getType(); - // Empty bases don't affect things either way. - if (isEmptyRecord(getContext(), Base, true)) - continue; + // Empty bases don't affect things either way. + if (isEmptyRecord(getContext(), Base, true)) + continue; - if (!Found.isNull()) - return Ty; - Found = GetSingleElementType(Base); - } + if (!Found.isNull()) + return Ty; + Found = GetSingleElementType(Base); + } // Check the fields. for (const auto *FD : RD->fields()) { @@ -7635,7 +7646,8 @@ Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, bool IsVector = false; CharUnits UnpaddedSize; CharUnits DirectAlign; - SZCGI.handleExternallyVisibleObjABI(Ty.getTypePtr(), CGT.getCGM()); + SZCGI.handleExternallyVisibleObjABI(Ty.getTypePtr(), CGT.getCGM(), + /*IsParam*/true); if (IsIndirect) { DirectTy = llvm::PointerType::getUnqual(DirectTy); UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8); @@ -7843,35 +7855,57 @@ void SystemZABIInfo::computeInfo(CGFunctionInfo &FI) const { // Check if a vararg vector argument is passed, in which case the // vector ABI becomes visible as the va_list could be passed on to // other functions. - SZCGI.handleExternallyVisibleObjABI(I.type.getTypePtr(), CGT.getCGM()); + SZCGI.handleExternallyVisibleObjABI(I.type.getTypePtr(), CGT.getCGM(), + /*IsParam*/true); } } -bool SystemZTargetCodeGenInfo::isVectorTypeBased(const Type *Ty) const { - while (Ty->isPointerType() || Ty->isArrayType()) - Ty = Ty->getPointeeOrArrayElementType(); +bool SystemZTargetCodeGenInfo::isVectorTypeBased(const Type *Ty, + bool IsParam) const { if (!SeenTypes.insert(Ty).second) return false; - if (Ty->isVectorType()) - return true; + + if (IsParam) { + // A narrow (<16 bytes) vector will as a parameter also expose the ABI as + // it will be passed in a vector register. A wide (>16 bytes) vector will + // be passed via "hidden" pointer where any extra alignment is not + // required (per GCC). + const Type *SingleEltTy = + getABIInfo().GetSingleElementType(QualType(Ty, 0)).getTypePtr(); + bool SingleVecEltStruct = SingleEltTy != Ty && SingleEltTy->isVectorType() && + Ctx.getTypeSize(SingleEltTy) == Ctx.getTypeSize(Ty); + if (Ty->isVectorType() || SingleVecEltStruct) + return Ctx.getTypeSize(Ty) / 8 <= 16; + } + + // Assume pointers are dereferenced. + while (Ty->isPointerType() || Ty->isArrayType()) + Ty = Ty->getPointeeOrArrayElementType(); + + // Vectors >= 16 bytes expose the ABI through alignment requirements. + if (Ty->isVectorType() && Ctx.getTypeSize(Ty) / 8 >= 16) + return true; + if (const auto *RecordTy = Ty->getAs<RecordType>()) { const RecordDecl *RD = RecordTy->getDecl(); if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) if (CXXRD->hasDefinition()) for (const auto &I : CXXRD->bases()) - if (isVectorTypeBased(I.getType().getTypePtr())) + if (isVectorTypeBased(I.getType().getTypePtr(), /*IsParam*/false)) return true; for (const auto *FD : RD->fields()) - if (isVectorTypeBased(FD->getType().getTypePtr())) + if (isVectorTypeBased(FD->getType().getTypePtr(), /*IsParam*/false)) return true; } + if (const auto *FT = Ty->getAs<FunctionType>()) - if (isVectorTypeBased(FT->getReturnType().getTypePtr())) + if (isVectorTypeBased(FT->getReturnType().getTypePtr(), /*IsParam*/true)) return true; if (const FunctionProtoType *Proto = Ty->getAs<FunctionProtoType>()) for (auto ParamType : Proto->getParamTypes()) - if (isVectorTypeBased(ParamType.getTypePtr())) + if (isVectorTypeBased(ParamType.getTypePtr(), /*IsParam*/true)) return true; + return false; } diff --git a/contrib/llvm-project/clang/lib/Driver/Driver.cpp b/contrib/llvm-project/clang/lib/Driver/Driver.cpp index 661d9977fbc5..a268f2fa8fc5 100644 --- a/contrib/llvm-project/clang/lib/Driver/Driver.cpp +++ b/contrib/llvm-project/clang/lib/Driver/Driver.cpp @@ -1873,14 +1873,12 @@ int Driver::ExecuteCompilation( C.CleanupFileMap(C.getFailureResultFiles(), JA, true); } -#if LLVM_ON_UNIX - // llvm/lib/Support/Unix/Signals.inc will exit with a special return code + // llvm/lib/Support/*/Signals.inc will exit with a special return code // for SIGPIPE. Do not print diagnostics for this case. if (CommandRes == EX_IOERR) { Res = CommandRes; continue; } -#endif // Print extra information about abnormal failures, if possible. // diff --git a/contrib/llvm-project/clang/lib/Driver/SanitizerArgs.cpp b/contrib/llvm-project/clang/lib/Driver/SanitizerArgs.cpp index 52bee6a755ff..068a34a54a92 100644 --- a/contrib/llvm-project/clang/lib/Driver/SanitizerArgs.cpp +++ b/contrib/llvm-project/clang/lib/Driver/SanitizerArgs.cpp @@ -19,6 +19,7 @@ #include "llvm/Support/SpecialCaseList.h" #include "llvm/Support/TargetParser.h" #include "llvm/Support/VirtualFileSystem.h" +#include "llvm/TargetParser/RISCVTargetParser.h" #include "llvm/Transforms/Instrumentation/AddressSanitizerOptions.h" #include <memory> @@ -545,7 +546,8 @@ SanitizerArgs::SanitizerArgs(const ToolChain &TC, if ((Kinds & SanitizerKind::ShadowCallStack) && ((TC.getTriple().isAArch64() && !llvm::AArch64::isX18ReservedByDefault(TC.getTriple())) || - TC.getTriple().isRISCV()) && + (TC.getTriple().isRISCV() && + !llvm::RISCV::isX18ReservedByDefault(TC.getTriple()))) && !Args.hasArg(options::OPT_ffixed_x18) && DiagnoseErrors) { D.Diag(diag::err_drv_argument_only_allowed_with) << lastArgumentForMask(D, Args, Kinds & SanitizerKind::ShadowCallStack) diff --git a/contrib/llvm-project/clang/lib/Driver/ToolChains/Arch/PPC.cpp b/contrib/llvm-project/clang/lib/Driver/ToolChains/Arch/PPC.cpp index 6ec736bc701b..e3c025fb2468 100644 --- a/contrib/llvm-project/clang/lib/Driver/ToolChains/Arch/PPC.cpp +++ b/contrib/llvm-project/clang/lib/Driver/ToolChains/Arch/PPC.cpp @@ -34,53 +34,60 @@ static std::string getPPCGenericTargetCPU(const llvm::Triple &T) { return "ppc"; } -/// getPPCTargetCPU - Get the (LLVM) name of the PowerPC cpu we are targeting. -std::string ppc::getPPCTargetCPU(const ArgList &Args, const llvm::Triple &T) { - if (Arg *A = Args.getLastArg(clang::driver::options::OPT_mcpu_EQ)) { - StringRef CPUName = A->getValue(); - - // Clang/LLVM does not actually support code generation - // for the 405 CPU. However, there are uses of this CPU ID - // in projects that previously used GCC and rely on Clang - // accepting it. Clang has always ignored it and passed the - // generic CPU ID to the back end. - if (CPUName == "generic" || CPUName == "405") +static std::string normalizeCPUName(StringRef CPUName, const llvm::Triple &T) { + // Clang/LLVM does not actually support code generation + // for the 405 CPU. However, there are uses of this CPU ID + // in projects that previously used GCC and rely on Clang + // accepting it. Clang has always ignored it and passed the + // generic CPU ID to the back end. + if (CPUName == "generic" || CPUName == "405") + return getPPCGenericTargetCPU(T); + + if (CPUName == "native") { + std::string CPU = std::string(llvm::sys::getHostCPUName()); + if (!CPU.empty() && CPU != "generic") + return CPU; + else return getPPCGenericTargetCPU(T); + } - if (CPUName == "native") { - std::string CPU = std::string(llvm::sys::getHostCPUName()); - if (!CPU.empty() && CPU != "generic") - return CPU; - else - return getPPCGenericTargetCPU(T); - } + return llvm::StringSwitch<const char *>(CPUName) + .Case("common", "generic") + .Case("440fp", "440") + .Case("630", "pwr3") + .Case("G3", "g3") + .Case("G4", "g4") + .Case("G4+", "g4+") + .Case("8548", "e500") + .Case("G5", "g5") + .Case("power3", "pwr3") + .Case("power4", "pwr4") + .Case("power5", "pwr5") + .Case("power5x", "pwr5x") + .Case("power6", "pwr6") + .Case("power6x", "pwr6x") + .Case("power7", "pwr7") + .Case("power8", "pwr8") + .Case("power9", "pwr9") + .Case("power10", "pwr10") + .Case("future", "future") + .Case("powerpc", "ppc") + .Case("powerpc64", "ppc64") + .Case("powerpc64le", "ppc64le") + .Default(CPUName.data()); +} - return llvm::StringSwitch<const char *>(CPUName) - .Case("common", "generic") - .Case("440fp", "440") - .Case("630", "pwr3") - .Case("G3", "g3") - .Case("G4", "g4") - .Case("G4+", "g4+") - .Case("8548", "e500") - .Case("G5", "g5") - .Case("power3", "pwr3") - .Case("power4", "pwr4") - .Case("power5", "pwr5") - .Case("power5x", "pwr5x") - .Case("power6", "pwr6") - .Case("power6x", "pwr6x") - .Case("power7", "pwr7") - .Case("power8", "pwr8") - .Case("power9", "pwr9") - .Case("power10", "pwr10") - .Case("future", "future") - .Case("powerpc", "ppc") - .Case("powerpc64", "ppc64") - .Case("powerpc64le", "ppc64le") - .Default(CPUName.data()); - } +/// Get the (LLVM) name of the PowerPC cpu we are tuning for. +std::string ppc::getPPCTuneCPU(const ArgList &Args, const llvm::Triple &T) { + if (Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) + return normalizeCPUName(A->getValue(), T); + return getPPCGenericTargetCPU(T); +} +/// Get the (LLVM) name of the PowerPC cpu we are targeting. +std::string ppc::getPPCTargetCPU(const ArgList &Args, const llvm::Triple &T) { + if (Arg *A = Args.getLastArg(clang::driver::options::OPT_mcpu_EQ)) + return normalizeCPUName(A->getValue(), T); return getPPCGenericTargetCPU(T); } diff --git a/contrib/llvm-project/clang/lib/Driver/ToolChains/Arch/PPC.h b/contrib/llvm-project/clang/lib/Driver/ToolChains/Arch/PPC.h index cd2b47d392b6..97ac45083852 100644 --- a/contrib/llvm-project/clang/lib/Driver/ToolChains/Arch/PPC.h +++ b/contrib/llvm-project/clang/lib/Driver/ToolChains/Arch/PPC.h @@ -37,6 +37,8 @@ FloatABI getPPCFloatABI(const Driver &D, const llvm::opt::ArgList &Args); std::string getPPCTargetCPU(const llvm::opt::ArgList &Args, const llvm::Triple &T); +std::string getPPCTuneCPU(const llvm::opt::ArgList &Args, + const llvm::Triple &T); const char *getPPCAsmModeForCPU(StringRef Name); ReadGOTPtrMode getPPCReadGOTPtrMode(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args); diff --git a/contrib/llvm-project/clang/lib/Driver/ToolChains/Clang.cpp b/contrib/llvm-project/clang/lib/Driver/ToolChains/Clang.cpp index 3d40e19c83a5..ec6860113b7e 100644 --- a/contrib/llvm-project/clang/lib/Driver/ToolChains/Clang.cpp +++ b/contrib/llvm-project/clang/lib/Driver/ToolChains/Clang.cpp @@ -1989,22 +1989,19 @@ void Clang::AddMIPSTargetArgs(const ArgList &Args, void Clang::AddPPCTargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const { + const llvm::Triple &T = getToolChain().getTriple(); if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) { CmdArgs.push_back("-tune-cpu"); - if (strcmp(A->getValue(), "native") == 0) - CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName())); - else - CmdArgs.push_back(A->getValue()); + std::string CPU = ppc::getPPCTuneCPU(Args, T); + CmdArgs.push_back(Args.MakeArgString(CPU)); } // Select the ABI to use. const char *ABIName = nullptr; - const llvm::Triple &T = getToolChain().getTriple(); if (T.isOSBinFormatELF()) { switch (getToolChain().getArch()) { case llvm::Triple::ppc64: { - if ((T.isOSFreeBSD() && T.getOSMajorVersion() >= 13) || - T.isOSOpenBSD() || T.isMusl()) + if (T.isPPC64ELFv2ABI()) ABIName = "elfv2"; else ABIName = "elfv1"; diff --git a/contrib/llvm-project/clang/lib/Driver/ToolChains/Cuda.cpp b/contrib/llvm-project/clang/lib/Driver/ToolChains/Cuda.cpp index 484c8c070264..aa125bb308e8 100644 --- a/contrib/llvm-project/clang/lib/Driver/ToolChains/Cuda.cpp +++ b/contrib/llvm-project/clang/lib/Driver/ToolChains/Cuda.cpp @@ -443,24 +443,19 @@ void NVPTX::Assembler::ConstructJob(Compilation &C, const JobAction &JA, CmdArgs.push_back("--gpu-name"); CmdArgs.push_back(Args.MakeArgString(CudaArchToString(gpu_arch))); CmdArgs.push_back("--output-file"); - const char *OutputFileName = Args.MakeArgString(TC.getInputFilename(Output)); + std::string OutputFileName = TC.getInputFilename(Output); // If we are invoking `nvlink` internally we need to output a `.cubin` file. - // Checking if the output is a temporary is the cleanest way to determine - // this. Putting this logic in `getInputFilename` isn't an option because it - // relies on the compilation. // FIXME: This should hopefully be removed if NVIDIA updates their tooling. - if (Output.isFilename() && - llvm::find(C.getTempFiles(), Output.getFilename()) != - C.getTempFiles().end()) { + if (!C.getInputArgs().getLastArg(options::OPT_c)) { SmallString<256> Filename(Output.getFilename()); llvm::sys::path::replace_extension(Filename, "cubin"); - OutputFileName = Args.MakeArgString(Filename); + OutputFileName = Filename.str(); } if (Output.isFilename() && OutputFileName != Output.getFilename()) - C.addTempFile(OutputFileName); + C.addTempFile(Args.MakeArgString(OutputFileName)); - CmdArgs.push_back(OutputFileName); + CmdArgs.push_back(Args.MakeArgString(OutputFileName)); for (const auto &II : Inputs) CmdArgs.push_back(Args.MakeArgString(II.getFilename())); diff --git a/contrib/llvm-project/clang/lib/Driver/ToolChains/FreeBSD.cpp b/contrib/llvm-project/clang/lib/Driver/ToolChains/FreeBSD.cpp index 64935227b07e..2230295ccd74 100644 --- a/contrib/llvm-project/clang/lib/Driver/ToolChains/FreeBSD.cpp +++ b/contrib/llvm-project/clang/lib/Driver/ToolChains/FreeBSD.cpp @@ -85,16 +85,7 @@ void freebsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA, else CmdArgs.push_back("-mfpu=softvfp"); - switch (getToolChain().getTriple().getEnvironment()) { - case llvm::Triple::GNUEABIHF: - case llvm::Triple::GNUEABI: - case llvm::Triple::EABI: - CmdArgs.push_back("-meabi=5"); - break; - - default: - CmdArgs.push_back("-matpcs"); - } + CmdArgs.push_back("-meabi=5"); break; } case llvm::Triple::sparc: @@ -176,10 +167,8 @@ void freebsd::Linker::ConstructJob(Compilation &C, const JobAction &JA, CmdArgs.push_back("/libexec/ld-elf.so.1"); } const llvm::Triple &T = ToolChain.getTriple(); - if (T.getOSMajorVersion() >= 9) { - if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc || T.isX86()) - CmdArgs.push_back("--hash-style=both"); - } + if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc || T.isX86()) + CmdArgs.push_back("--hash-style=both"); CmdArgs.push_back("--enable-new-dtags"); } @@ -396,17 +385,11 @@ FreeBSD::FreeBSD(const Driver &D, const llvm::Triple &Triple, getFilePaths().push_back(concat(getDriver().SysRoot, "/usr/lib")); } -ToolChain::CXXStdlibType FreeBSD::GetDefaultCXXStdlibType() const { - unsigned Major = getTriple().getOSMajorVersion(); - if (Major >= 10 || Major == 0) - return ToolChain::CST_Libcxx; - return ToolChain::CST_Libstdcxx; -} - unsigned FreeBSD::GetDefaultDwarfVersion() const { - if (getTriple().getOSMajorVersion() < 12) - return 2; - return 4; + unsigned Major = getTriple().getOSMajorVersion(); + if (Major >= 12 || Major == 0) + return 4; + return 2; } void FreeBSD::AddClangSystemIncludeArgs( @@ -449,30 +432,14 @@ void FreeBSD::addLibCxxIncludePaths(const llvm::opt::ArgList &DriverArgs, concat(getDriver().SysRoot, "/usr/include/c++/v1")); } -void FreeBSD::addLibStdCxxIncludePaths( - const llvm::opt::ArgList &DriverArgs, - llvm::opt::ArgStringList &CC1Args) const { - addLibStdCXXIncludePaths(concat(getDriver().SysRoot, "/usr/include/c++/4.2"), - "", "", DriverArgs, CC1Args); -} - void FreeBSD::AddCXXStdlibLibArgs(const ArgList &Args, ArgStringList &CmdArgs) const { - CXXStdlibType Type = GetCXXStdlibType(Args); unsigned Major = getTriple().getOSMajorVersion(); bool Profiling = Args.hasArg(options::OPT_pg) && Major != 0 && Major < 14; - switch (Type) { - case ToolChain::CST_Libcxx: - CmdArgs.push_back(Profiling ? "-lc++_p" : "-lc++"); - if (Args.hasArg(options::OPT_fexperimental_library)) - CmdArgs.push_back("-lc++experimental"); - break; - - case ToolChain::CST_Libstdcxx: - CmdArgs.push_back(Profiling ? "-lstdc++_p" : "-lstdc++"); - break; - } + CmdArgs.push_back(Profiling ? "-lc++_p" : "-lc++"); + if (Args.hasArg(options::OPT_fexperimental_library)) + CmdArgs.push_back("-lc++experimental"); } void FreeBSD::AddCudaIncludeArgs(const ArgList &DriverArgs, @@ -491,21 +458,6 @@ Tool *FreeBSD::buildAssembler() const { Tool *FreeBSD::buildLinker() const { return new tools::freebsd::Linker(*this); } -llvm::ExceptionHandling FreeBSD::GetExceptionModel(const ArgList &Args) const { - // FreeBSD uses SjLj exceptions on ARM oabi. - switch (getTriple().getEnvironment()) { - case llvm::Triple::GNUEABIHF: - case llvm::Triple::GNUEABI: - case llvm::Triple::EABI: - return llvm::ExceptionHandling::None; - default: - if (getTriple().getArch() == llvm::Triple::arm || - getTriple().getArch() == llvm::Triple::thumb) - return llvm::ExceptionHandling::SjLj; - return llvm::ExceptionHandling::None; - } -} - bool FreeBSD::HasNativeLLVMSupport() const { return true; } ToolChain::UnwindTableLevel @@ -550,8 +502,9 @@ SanitizerMask FreeBSD::getSupportedSanitizers() const { void FreeBSD::addClangTargetOptions(const ArgList &DriverArgs, ArgStringList &CC1Args, Action::OffloadKind) const { + unsigned Major = getTriple().getOSMajorVersion(); if (!DriverArgs.hasFlag(options::OPT_fuse_init_array, options::OPT_fno_use_init_array, - getTriple().getOSMajorVersion() >= 12)) + (Major >= 12 || Major == 0))) CC1Args.push_back("-fno-use-init-array"); } diff --git a/contrib/llvm-project/clang/lib/Driver/ToolChains/FreeBSD.h b/contrib/llvm-project/clang/lib/Driver/ToolChains/FreeBSD.h index 18832dad9884..cec67d84a2ce 100644 --- a/contrib/llvm-project/clang/lib/Driver/ToolChains/FreeBSD.h +++ b/contrib/llvm-project/clang/lib/Driver/ToolChains/FreeBSD.h @@ -61,12 +61,16 @@ public: void AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override; - CXXStdlibType GetDefaultCXXStdlibType() const override; + + RuntimeLibType GetDefaultRuntimeLibType() const override { + return ToolChain::RLT_CompilerRT; + } + CXXStdlibType GetDefaultCXXStdlibType() const override { + return ToolChain::CST_Libcxx; + } + void addLibCxxIncludePaths(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override; - void - addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs, - llvm::opt::ArgStringList &CC1Args) const override; void AddCXXStdlibLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const override; void AddCudaIncludeArgs(const llvm::opt::ArgList &DriverArgs, @@ -74,8 +78,6 @@ public: void AddHIPIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override; - llvm::ExceptionHandling - GetExceptionModel(const llvm::opt::ArgList &Args) const override; UnwindTableLevel getDefaultUnwindTableLevel(const llvm::opt::ArgList &Args) const override; bool isPIEDefault(const llvm::opt::ArgList &Args) const override; diff --git a/contrib/llvm-project/clang/lib/Driver/ToolChains/Fuchsia.cpp b/contrib/llvm-project/clang/lib/Driver/ToolChains/Fuchsia.cpp index 9bdc3a791779..ea6d7d697770 100644 --- a/contrib/llvm-project/clang/lib/Driver/ToolChains/Fuchsia.cpp +++ b/contrib/llvm-project/clang/lib/Driver/ToolChains/Fuchsia.cpp @@ -447,13 +447,13 @@ SanitizerMask Fuchsia::getDefaultSanitizers() const { SanitizerMask Res; switch (getTriple().getArch()) { case llvm::Triple::aarch64: + case llvm::Triple::riscv64: Res |= SanitizerKind::ShadowCallStack; break; case llvm::Triple::x86_64: Res |= SanitizerKind::SafeStack; break; default: - // TODO: Enable SafeStack on RISC-V once tested. break; } return Res; diff --git a/contrib/llvm-project/clang/lib/Driver/ToolChains/MinGW.cpp b/contrib/llvm-project/clang/lib/Driver/ToolChains/MinGW.cpp index 908484fcc0b8..bac486bab885 100644 --- a/contrib/llvm-project/clang/lib/Driver/ToolChains/MinGW.cpp +++ b/contrib/llvm-project/clang/lib/Driver/ToolChains/MinGW.cpp @@ -200,6 +200,16 @@ void tools::MinGW::Linker::ConstructJob(Compilation &C, const JobAction &JA, Args.AddAllArgs(CmdArgs, options::OPT_u_Group); Args.AddLastArg(CmdArgs, options::OPT_Z_Flag); + // Add asan_dynamic as the first import lib before other libs. This allows + // asan to be initialized as early as possible to increase its instrumentation + // coverage to include other user DLLs which has not been built with asan. + if (Sanitize.needsAsanRt() && !Args.hasArg(options::OPT_nostdlib) && + !Args.hasArg(options::OPT_nodefaultlibs)) { + // MinGW always links against a shared MSVCRT. + CmdArgs.push_back( + TC.getCompilerRTArgString(Args, "asan_dynamic", ToolChain::FT_Shared)); + } + if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) { if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_mdll)) { CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("dllcrt2.o"))); diff --git a/contrib/llvm-project/clang/lib/Format/Format.cpp b/contrib/llvm-project/clang/lib/Format/Format.cpp index f37c3f983635..0d3fde90ab38 100644 --- a/contrib/llvm-project/clang/lib/Format/Format.cpp +++ b/contrib/llvm-project/clang/lib/Format/Format.cpp @@ -348,8 +348,11 @@ struct ScalarEnumerationTraits<FormatStyle::IndentExternBlockStyle> { template <> struct MappingTraits<FormatStyle::IntegerLiteralSeparatorStyle> { static void mapping(IO &IO, FormatStyle::IntegerLiteralSeparatorStyle &Base) { IO.mapOptional("Binary", Base.Binary); + IO.mapOptional("BinaryMinDigits", Base.BinaryMinDigits); IO.mapOptional("Decimal", Base.Decimal); + IO.mapOptional("DecimalMinDigits", Base.DecimalMinDigits); IO.mapOptional("Hex", Base.Hex); + IO.mapOptional("HexMinDigits", Base.HexMinDigits); } }; @@ -1392,7 +1395,10 @@ FormatStyle getLLVMStyle(FormatStyle::LanguageKind Language) { LLVMStyle.InsertBraces = false; LLVMStyle.InsertNewlineAtEOF = false; LLVMStyle.InsertTrailingCommas = FormatStyle::TCS_None; - LLVMStyle.IntegerLiteralSeparator = {/*Binary=*/0, /*Decimal=*/0, /*Hex=*/0}; + LLVMStyle.IntegerLiteralSeparator = { + /*Binary=*/0, /*BinaryMinDigits=*/0, + /*Decimal=*/0, /*DecimalMinDigits=*/0, + /*Hex=*/0, /*HexMinDigits=*/0}; LLVMStyle.JavaScriptQuotes = FormatStyle::JSQS_Leave; LLVMStyle.JavaScriptWrapImports = true; LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true; diff --git a/contrib/llvm-project/clang/lib/Format/IntegerLiteralSeparatorFixer.cpp b/contrib/llvm-project/clang/lib/Format/IntegerLiteralSeparatorFixer.cpp index ef07ab06760b..44034e44adec 100644 --- a/contrib/llvm-project/clang/lib/Format/IntegerLiteralSeparatorFixer.cpp +++ b/contrib/llvm-project/clang/lib/Format/IntegerLiteralSeparatorFixer.cpp @@ -69,6 +69,12 @@ IntegerLiteralSeparatorFixer::process(const Environment &Env, if (SkipBinary && SkipDecimal && SkipHex) return {}; + const auto BinaryMinDigits = + std::max((int)Option.BinaryMinDigits, Binary + 1); + const auto DecimalMinDigits = + std::max((int)Option.DecimalMinDigits, Decimal + 1); + const auto HexMinDigits = std::max((int)Option.HexMinDigits, Hex + 1); + const auto &SourceMgr = Env.getSourceManager(); AffectedRangeManager AffectedRangeMgr(SourceMgr, Env.getCharRanges()); @@ -106,17 +112,18 @@ IntegerLiteralSeparatorFixer::process(const Environment &Env, (IsBase16 && SkipHex) || B == Base::Other) { continue; } + if (Style.isCpp()) { + if (const auto Pos = Text.find_first_of("_i"); Pos != StringRef::npos) { + Text = Text.substr(0, Pos); + Length = Pos; + } + } if ((IsBase10 && Text.find_last_of(".eEfFdDmM") != StringRef::npos) || (IsBase16 && Text.find_last_of(".pP") != StringRef::npos)) { continue; } - if (((IsBase2 && Binary < 0) || (IsBase10 && Decimal < 0) || - (IsBase16 && Hex < 0)) && - Text.find(Separator) == StringRef::npos) { - continue; - } const auto Start = Text[0] == '0' ? 2 : 0; - auto End = Text.find_first_of("uUlLzZn"); + auto End = Text.find_first_of("uUlLzZn", Start); if (End == StringRef::npos) End = Length; if (Start > 0 || End < Length) { @@ -124,16 +131,30 @@ IntegerLiteralSeparatorFixer::process(const Environment &Env, Text = Text.substr(Start, Length); } auto DigitsPerGroup = Decimal; - if (IsBase2) + auto MinDigits = DecimalMinDigits; + if (IsBase2) { DigitsPerGroup = Binary; - else if (IsBase16) + MinDigits = BinaryMinDigits; + } else if (IsBase16) { DigitsPerGroup = Hex; - if (DigitsPerGroup > 0 && checkSeparator(Text, DigitsPerGroup)) + MinDigits = HexMinDigits; + } + const auto SeparatorCount = Text.count(Separator); + const int DigitCount = Length - SeparatorCount; + const bool RemoveSeparator = DigitsPerGroup < 0 || DigitCount < MinDigits; + if (RemoveSeparator && SeparatorCount == 0) continue; + if (!RemoveSeparator && SeparatorCount > 0 && + checkSeparator(Text, DigitsPerGroup)) { + continue; + } + const auto &Formatted = + format(Text, DigitsPerGroup, DigitCount, RemoveSeparator); + assert(Formatted != Text); if (Start > 0) Location = Location.getLocWithOffset(Start); - cantFail(Result.add(tooling::Replacement(SourceMgr, Location, Length, - format(Text, DigitsPerGroup)))); + cantFail(Result.add( + tooling::Replacement(SourceMgr, Location, Length, Formatted))); } return {Result, 0}; @@ -150,9 +171,9 @@ bool IntegerLiteralSeparatorFixer::checkSeparator( return false; I = 0; } else { - ++I; if (I == DigitsPerGroup) return false; + ++I; } } @@ -160,23 +181,20 @@ bool IntegerLiteralSeparatorFixer::checkSeparator( } std::string IntegerLiteralSeparatorFixer::format(const StringRef IntegerLiteral, - int DigitsPerGroup) const { + int DigitsPerGroup, + int DigitCount, + bool RemoveSeparator) const { assert(DigitsPerGroup != 0); std::string Formatted; - if (DigitsPerGroup < 0) { + if (RemoveSeparator) { for (auto C : IntegerLiteral) if (C != Separator) Formatted.push_back(C); return Formatted; } - int DigitCount = 0; - for (auto C : IntegerLiteral) - if (C != Separator) - ++DigitCount; - int Remainder = DigitCount % DigitsPerGroup; int I = 0; diff --git a/contrib/llvm-project/clang/lib/Format/IntegerLiteralSeparatorFixer.h b/contrib/llvm-project/clang/lib/Format/IntegerLiteralSeparatorFixer.h index 156bf5c14fca..2c158e4473bf 100644 --- a/contrib/llvm-project/clang/lib/Format/IntegerLiteralSeparatorFixer.h +++ b/contrib/llvm-project/clang/lib/Format/IntegerLiteralSeparatorFixer.h @@ -27,7 +27,8 @@ public: private: bool checkSeparator(const StringRef IntegerLiteral, int DigitsPerGroup) const; - std::string format(const StringRef IntegerLiteral, int DigitsPerGroup) const; + std::string format(const StringRef IntegerLiteral, int DigitsPerGroup, + int DigitCount, bool RemoveSeparator) const; char Separator; }; diff --git a/contrib/llvm-project/clang/lib/Format/QualifierAlignmentFixer.cpp b/contrib/llvm-project/clang/lib/Format/QualifierAlignmentFixer.cpp index cef8b36ff758..609b412380f8 100644 --- a/contrib/llvm-project/clang/lib/Format/QualifierAlignmentFixer.cpp +++ b/contrib/llvm-project/clang/lib/Format/QualifierAlignmentFixer.cpp @@ -280,8 +280,11 @@ const FormatToken *LeftRightQualifierAlignmentFixer::analyzeRight( // The case `const Foo &&` -> `Foo const &&` // The case `const std::Foo &&` -> `std::Foo const &&` // The case `const std::Foo<T> &&` -> `std::Foo<T> const &&` - while (Next && Next->isOneOf(tok::identifier, tok::coloncolon)) + // However, `const Bar::*` remains the same. + while (Next && Next->isOneOf(tok::identifier, tok::coloncolon) && + !Next->startsSequence(tok::coloncolon, tok::star)) { Next = Next->Next; + } if (Next && Next->is(TT_TemplateOpener)) { Next = Next->MatchingParen; // Move to the end of any template class members e.g. diff --git a/contrib/llvm-project/clang/lib/Format/TokenAnnotator.cpp b/contrib/llvm-project/clang/lib/Format/TokenAnnotator.cpp index 49c30ca78deb..ca651eaa9440 100644 --- a/contrib/llvm-project/clang/lib/Format/TokenAnnotator.cpp +++ b/contrib/llvm-project/clang/lib/Format/TokenAnnotator.cpp @@ -3833,6 +3833,9 @@ bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line, return true; if (Style.isCpp()) { + // Space between UDL and dot: auto b = 4s .count(); + if (Right.is(tok::period) && Left.is(tok::numeric_constant)) + return true; // Space between import <iostream>. // or import .....; if (Left.is(Keywords.kw_import) && Right.isOneOf(tok::less, tok::ellipsis)) diff --git a/contrib/llvm-project/clang/lib/Format/UnwrappedLineParser.cpp b/contrib/llvm-project/clang/lib/Format/UnwrappedLineParser.cpp index 3e58b6f90559..7a49b189b481 100644 --- a/contrib/llvm-project/clang/lib/Format/UnwrappedLineParser.cpp +++ b/contrib/llvm-project/clang/lib/Format/UnwrappedLineParser.cpp @@ -2739,16 +2739,17 @@ void UnwrappedLineParser::handleAttributes() { // Handle AttributeMacro, e.g. `if (x) UNLIKELY`. if (FormatTok->is(TT_AttributeMacro)) nextToken(); - handleCppAttributes(); + if (FormatTok->is(tok::l_square)) + handleCppAttributes(); } bool UnwrappedLineParser::handleCppAttributes() { // Handle [[likely]] / [[unlikely]] attributes. - if (FormatTok->is(tok::l_square) && tryToParseSimpleAttribute()) { - parseSquare(); - return true; - } - return false; + assert(FormatTok->is(tok::l_square)); + if (!tryToParseSimpleAttribute()) + return false; + parseSquare(); + return true; } /// Returns whether \c Tok begins a block. @@ -3855,7 +3856,7 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) { // An [[attribute]] can be before the identifier. while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash, tok::kw___attribute, tok::kw___declspec, - tok::kw_alignas, tok::l_square, tok::r_square) || + tok::kw_alignas, tok::l_square) || ((Style.Language == FormatStyle::LK_Java || Style.isJavaScript()) && FormatTok->isOneOf(tok::period, tok::comma))) { if (Style.isJavaScript() && @@ -3869,21 +3870,15 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) { continue; } } + if (FormatTok->is(tok::l_square) && handleCppAttributes()) + continue; bool IsNonMacroIdentifier = FormatTok->is(tok::identifier) && FormatTok->TokenText != FormatTok->TokenText.upper(); nextToken(); - // We can have macros or attributes in between 'class' and the class name. - if (!IsNonMacroIdentifier) { - if (FormatTok->is(tok::l_paren)) { - parseParens(); - } else if (FormatTok->is(TT_AttributeSquare)) { - parseSquare(); - // Consume the closing TT_AttributeSquare. - if (FormatTok->Next && FormatTok->is(TT_AttributeSquare)) - nextToken(); - } - } + // We can have macros in between 'class' and the class name. + if (!IsNonMacroIdentifier && FormatTok->is(tok::l_paren)) + parseParens(); } // Note that parsing away template declarations here leads to incorrectly diff --git a/contrib/llvm-project/clang/lib/Frontend/CompilerInstance.cpp b/contrib/llvm-project/clang/lib/Frontend/CompilerInstance.cpp index ecc1c4cf51c1..ac9f8f8ed51c 100644 --- a/contrib/llvm-project/clang/lib/Frontend/CompilerInstance.cpp +++ b/contrib/llvm-project/clang/lib/Frontend/CompilerInstance.cpp @@ -1983,14 +1983,7 @@ CompilerInstance::loadModule(SourceLocation ImportLoc, Module = PP->getHeaderSearchInfo().lookupModule( ModuleName, ImportLoc, /*AllowSearch*/ true, /*AllowExtraModuleMapSearch*/ !IsInclusionDirective); - /// FIXME: perhaps we should (a) look for a module using the module name - // to file map (PrebuiltModuleFiles) and (b) diagnose if still not found? - //if (Module == nullptr) { - // getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found) - // << ModuleName; - // DisableGeneratingGlobalModuleIndex = true; - // return ModuleLoadResult(); - //} + MM.cacheModuleLoad(*Path[0].first, Module); } else { ModuleLoadResult Result = findOrCompileModuleAndReadAST( diff --git a/contrib/llvm-project/clang/lib/Headers/immintrin.h b/contrib/llvm-project/clang/lib/Headers/immintrin.h index 6967b46fdb24..0d2e8be6e486 100644 --- a/contrib/llvm-project/clang/lib/Headers/immintrin.h +++ b/contrib/llvm-project/clang/lib/Headers/immintrin.h @@ -524,7 +524,7 @@ _storebe_i64(void * __P, long long __D) { #include <invpcidintrin.h> #endif #if !(defined(_MSC_VER) || defined(__SCE__)) || __has_feature(modules) || \ - defined(__AMXFP16__) + defined(__AMX_FP16__) #include <amxfp16intrin.h> #endif @@ -534,7 +534,7 @@ _storebe_i64(void * __P, long long __D) { #endif #if !(defined(_MSC_VER) || defined(__SCE__)) || __has_feature(modules) || \ - defined(__AMXTILE__) || defined(__AMXINT8__) || defined(__AMXBF16__) + defined(__AMX_TILE__) || defined(__AMX_INT8__) || defined(__AMX_BF16__) #include <amxintrin.h> #endif diff --git a/contrib/llvm-project/clang/lib/Headers/smmintrin.h b/contrib/llvm-project/clang/lib/Headers/smmintrin.h index 2111c24f31a6..16d8855a1c0b 100644 --- a/contrib/llvm-project/clang/lib/Headers/smmintrin.h +++ b/contrib/llvm-project/clang/lib/Headers/smmintrin.h @@ -1145,7 +1145,7 @@ static __inline__ int __DEFAULT_FN_ATTRS _mm_testnzc_si128(__m128i __M, /// A 128-bit integer vector containing the bits to be tested. /// \returns TRUE if the bits specified in the operand are all set to 1; FALSE /// otherwise. -#define _mm_test_all_ones(V) _mm_testc_si128((V), _mm_cmpeq_epi32((V), (V))) +#define _mm_test_all_ones(V) _mm_testc_si128((V), _mm_set1_epi32(-1)) /// Tests whether the specified bits in a 128-bit integer vector are /// neither all zeros nor all ones. diff --git a/contrib/llvm-project/clang/lib/Lex/PPMacroExpansion.cpp b/contrib/llvm-project/clang/lib/Lex/PPMacroExpansion.cpp index bbc271e5611e..76d0d53ed31d 100644 --- a/contrib/llvm-project/clang/lib/Lex/PPMacroExpansion.cpp +++ b/contrib/llvm-project/clang/lib/Lex/PPMacroExpansion.cpp @@ -1637,35 +1637,14 @@ void Preprocessor::ExpandBuiltinMacro(Token &Tok) { Tok.setKind(tok::string_literal); } else if (II == Ident__FLT_EVAL_METHOD__) { // __FLT_EVAL_METHOD__ is set to the default value. - if (getTUFPEvalMethod() == - LangOptions::FPEvalMethodKind::FEM_Indeterminable) { - // This is possible if `AllowFPReassoc` or `AllowReciprocal` is enabled. - // These modes can be triggered via the command line option `-ffast-math` - // or via a `pragam float_control`. - // __FLT_EVAL_METHOD__ expands to -1. - // The `minus` operator is the next token we read from the stream. - auto Toks = std::make_unique<Token[]>(1); - OS << "-"; - Tok.setKind(tok::minus); - // Push the token `1` to the stream. - Token NumberToken; - NumberToken.startToken(); - NumberToken.setKind(tok::numeric_constant); - NumberToken.setLiteralData("1"); - NumberToken.setLength(1); - Toks[0] = NumberToken; - EnterTokenStream(std::move(Toks), 1, /*DisableMacroExpansion*/ false, - /*IsReinject*/ false); - } else { - OS << getTUFPEvalMethod(); - // __FLT_EVAL_METHOD__ expands to a simple numeric value. - Tok.setKind(tok::numeric_constant); - if (getLastFPEvalPragmaLocation().isValid()) { - // The program is ill-formed. The value of __FLT_EVAL_METHOD__ is - // altered by the pragma. - Diag(Tok, diag::err_illegal_use_of_flt_eval_macro); - Diag(getLastFPEvalPragmaLocation(), diag::note_pragma_entered_here); - } + OS << getTUFPEvalMethod(); + // __FLT_EVAL_METHOD__ expands to a simple numeric value. + Tok.setKind(tok::numeric_constant); + if (getLastFPEvalPragmaLocation().isValid()) { + // The program is ill-formed. The value of __FLT_EVAL_METHOD__ is altered + // by the pragma. + Diag(Tok, diag::err_illegal_use_of_flt_eval_macro); + Diag(getLastFPEvalPragmaLocation(), diag::note_pragma_entered_here); } } else if (II == Ident__COUNTER__) { // __COUNTER__ expands to a simple numeric value. diff --git a/contrib/llvm-project/clang/lib/Lex/Preprocessor.cpp b/contrib/llvm-project/clang/lib/Lex/Preprocessor.cpp index fe9adb5685e3..0d411abf8f1c 100644 --- a/contrib/llvm-project/clang/lib/Lex/Preprocessor.cpp +++ b/contrib/llvm-project/clang/lib/Lex/Preprocessor.cpp @@ -207,11 +207,6 @@ void Preprocessor::Initialize(const TargetInfo &Target, else // Set initial value of __FLT_EVAL_METHOD__ from the command line. setCurrentFPEvalMethod(SourceLocation(), getLangOpts().getFPEvalMethod()); - // When `-ffast-math` option is enabled, it triggers several driver math - // options to be enabled. Among those, only one the following two modes - // affect the eval-method: reciprocal or reassociate. - if (getLangOpts().AllowFPReassoc || getLangOpts().AllowRecip) - setCurrentFPEvalMethod(SourceLocation(), LangOptions::FEM_Indeterminable); } void Preprocessor::InitializeForModelFile() { @@ -873,6 +868,7 @@ bool Preprocessor::HandleIdentifier(Token &Identifier) { CurLexerKind != CLK_CachingLexer) { ModuleImportLoc = Identifier.getLocation(); NamedModuleImportPath.clear(); + IsAtImport = true; ModuleImportExpectsIdentifier = true; CurLexerKind = CLK_LexAfterModuleImport; } @@ -940,6 +936,7 @@ void Preprocessor::Lex(Token &Result) { case tok::semi: TrackGMFState.handleSemi(); StdCXXImportSeqState.handleSemi(); + ModuleDeclState.handleSemi(); break; case tok::header_name: case tok::annot_header_unit: @@ -948,6 +945,13 @@ void Preprocessor::Lex(Token &Result) { case tok::kw_export: TrackGMFState.handleExport(); StdCXXImportSeqState.handleExport(); + ModuleDeclState.handleExport(); + break; + case tok::colon: + ModuleDeclState.handleColon(); + break; + case tok::period: + ModuleDeclState.handlePeriod(); break; case tok::identifier: if (Result.getIdentifierInfo()->isModulesImport()) { @@ -956,18 +960,25 @@ void Preprocessor::Lex(Token &Result) { if (StdCXXImportSeqState.afterImportSeq()) { ModuleImportLoc = Result.getLocation(); NamedModuleImportPath.clear(); + IsAtImport = false; ModuleImportExpectsIdentifier = true; CurLexerKind = CLK_LexAfterModuleImport; } break; } else if (Result.getIdentifierInfo() == getIdentifierInfo("module")) { TrackGMFState.handleModule(StdCXXImportSeqState.afterTopLevelSeq()); + ModuleDeclState.handleModule(); break; + } else { + ModuleDeclState.handleIdentifier(Result.getIdentifierInfo()); + if (ModuleDeclState.isModuleCandidate()) + break; } [[fallthrough]]; default: TrackGMFState.handleMisc(); StdCXXImportSeqState.handleMisc(); + ModuleDeclState.handleMisc(); break; } } @@ -1151,6 +1162,15 @@ bool Preprocessor::LexAfterModuleImport(Token &Result) { if (NamedModuleImportPath.empty() && getLangOpts().CPlusPlusModules) { if (LexHeaderName(Result)) return true; + + if (Result.is(tok::colon) && ModuleDeclState.isNamedModule()) { + std::string Name = ModuleDeclState.getPrimaryName().str(); + Name += ":"; + NamedModuleImportPath.push_back( + {getIdentifierInfo(Name), Result.getLocation()}); + CurLexerKind = CLK_LexAfterModuleImport; + return true; + } } else { Lex(Result); } @@ -1164,9 +1184,10 @@ bool Preprocessor::LexAfterModuleImport(Token &Result) { /*DisableMacroExpansion*/ true, /*IsReinject*/ false); }; + bool ImportingHeader = Result.is(tok::header_name); // Check for a header-name. SmallVector<Token, 32> Suffix; - if (Result.is(tok::header_name)) { + if (ImportingHeader) { // Enter the header-name token into the token stream; a Lex action cannot // both return a token and cache tokens (doing so would corrupt the token // cache if the call to Lex comes from CachingLex / PeekAhead). @@ -1244,8 +1265,8 @@ bool Preprocessor::LexAfterModuleImport(Token &Result) { if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) { // We expected to see an identifier here, and we did; continue handling // identifiers. - NamedModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(), - Result.getLocation())); + NamedModuleImportPath.push_back( + std::make_pair(Result.getIdentifierInfo(), Result.getLocation())); ModuleImportExpectsIdentifier = false; CurLexerKind = CLK_LexAfterModuleImport; return true; @@ -1285,7 +1306,8 @@ bool Preprocessor::LexAfterModuleImport(Token &Result) { std::string FlatModuleName; if (getLangOpts().ModulesTS || getLangOpts().CPlusPlusModules) { for (auto &Piece : NamedModuleImportPath) { - if (!FlatModuleName.empty()) + // If the FlatModuleName ends with colon, it implies it is a partition. + if (!FlatModuleName.empty() && FlatModuleName.back() != ':') FlatModuleName += "."; FlatModuleName += Piece.first->getName(); } @@ -1296,7 +1318,8 @@ bool Preprocessor::LexAfterModuleImport(Token &Result) { } Module *Imported = nullptr; - if (getLangOpts().Modules) { + // We don't/shouldn't load the standard c++20 modules when preprocessing. + if (getLangOpts().Modules && !isInImportingCXXNamedModules()) { Imported = TheModuleLoader.loadModule(ModuleImportLoc, NamedModuleImportPath, Module::Hidden, @@ -1304,6 +1327,7 @@ bool Preprocessor::LexAfterModuleImport(Token &Result) { if (Imported) makeModuleVisible(Imported, SemiLoc); } + if (Callbacks) Callbacks->moduleImport(ModuleImportLoc, NamedModuleImportPath, Imported); diff --git a/contrib/llvm-project/clang/lib/Lex/TokenLexer.cpp b/contrib/llvm-project/clang/lib/Lex/TokenLexer.cpp index c6968b9f417e..ebe7dd66c118 100644 --- a/contrib/llvm-project/clang/lib/Lex/TokenLexer.cpp +++ b/contrib/llvm-project/clang/lib/Lex/TokenLexer.cpp @@ -1020,8 +1020,16 @@ static void updateConsecutiveMacroArgTokens(SourceManager &SM, SourceLocation Limit = SM.getComposedLoc(BeginFID, SM.getFileIDSize(BeginFID)); Partition = All.take_while([&](const Token &T) { - return T.getLocation() >= BeginLoc && T.getLocation() < Limit && - NearLast(T.getLocation()); + // NOTE: the Limit is included! The lexer recovery only ever inserts a + // single token past the end of the FileID, specifically the ) when a + // macro-arg containing a comma should be guarded by parentheses. + // + // It is safe to include the Limit here because SourceManager allocates + // FileSize + 1 for each SLocEntry. + // + // See https://github.com/llvm/llvm-project/issues/60722. + return T.getLocation() >= BeginLoc && T.getLocation() <= Limit + && NearLast(T.getLocation()); }); } assert(!Partition.empty()); diff --git a/contrib/llvm-project/clang/lib/Parse/ParseDecl.cpp b/contrib/llvm-project/clang/lib/Parse/ParseDecl.cpp index c7fd1156928c..e6812ac72c88 100644 --- a/contrib/llvm-project/clang/lib/Parse/ParseDecl.cpp +++ b/contrib/llvm-project/clang/lib/Parse/ParseDecl.cpp @@ -4965,7 +4965,6 @@ void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS, bool IsDependent = false; const char *PrevSpec = nullptr; unsigned DiagID; - UsingShadowDecl* FoundUsing = nullptr; Decl *TagDecl = Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK, StartLoc, SS, Name, NameLoc, attrs, AS, DS.getModulePrivateSpecLoc(), @@ -4974,7 +4973,7 @@ void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS, BaseType, DSC == DeclSpecContext::DSC_type_specifier, DSC == DeclSpecContext::DSC_template_param || DSC == DeclSpecContext::DSC_template_type_arg, - OffsetOfState, FoundUsing, &SkipBody).get(); + OffsetOfState, &SkipBody).get(); if (SkipBody.ShouldSkip) { assert(TUK == Sema::TUK_Definition && "can only skip a definition"); @@ -4984,8 +4983,8 @@ void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS, T.skipToEnd(); if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc, - NameLoc.isValid() ? NameLoc : StartLoc, PrevSpec, - DiagID, FoundUsing ? FoundUsing : TagDecl, Owned, + NameLoc.isValid() ? NameLoc : StartLoc, + PrevSpec, DiagID, TagDecl, Owned, Actions.getASTContext().getPrintingPolicy())) Diag(StartLoc, DiagID) << PrevSpec; return; @@ -5039,8 +5038,8 @@ void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS, } if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc, - NameLoc.isValid() ? NameLoc : StartLoc, PrevSpec, - DiagID, FoundUsing ? FoundUsing : TagDecl, Owned, + NameLoc.isValid() ? NameLoc : StartLoc, + PrevSpec, DiagID, TagDecl, Owned, Actions.getASTContext().getPrintingPolicy())) Diag(StartLoc, DiagID) << PrevSpec; } diff --git a/contrib/llvm-project/clang/lib/Parse/ParseDeclCXX.cpp b/contrib/llvm-project/clang/lib/Parse/ParseDeclCXX.cpp index b26ec00cfedf..227c1df2bddd 100644 --- a/contrib/llvm-project/clang/lib/Parse/ParseDeclCXX.cpp +++ b/contrib/llvm-project/clang/lib/Parse/ParseDeclCXX.cpp @@ -1934,7 +1934,6 @@ void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind, // Create the tag portion of the class or class template. DeclResult TagOrTempResult = true; // invalid TypeResult TypeResult = true; // invalid - UsingShadowDecl *FoundUsing = nullptr; bool Owned = false; Sema::SkipBodyInfo SkipBody; @@ -2075,7 +2074,7 @@ void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind, DSC == DeclSpecContext::DSC_type_specifier, DSC == DeclSpecContext::DSC_template_param || DSC == DeclSpecContext::DSC_template_type_arg, - OffsetOfState, FoundUsing, &SkipBody); + OffsetOfState, &SkipBody); // If ActOnTag said the type was dependent, try again with the // less common call. @@ -2134,7 +2133,7 @@ void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind, } else if (!TagOrTempResult.isInvalid()) { Result = DS.SetTypeSpecType( TagType, StartLoc, NameLoc.isValid() ? NameLoc : StartLoc, PrevSpec, - DiagID, FoundUsing ? FoundUsing : TagOrTempResult.get(), Owned, Policy); + DiagID, TagOrTempResult.get(), Owned, Policy); } else { DS.SetTypeSpecError(); return; diff --git a/contrib/llvm-project/clang/lib/Parse/ParseExpr.cpp b/contrib/llvm-project/clang/lib/Parse/ParseExpr.cpp index 392ed29467a9..66d937ac5742 100644 --- a/contrib/llvm-project/clang/lib/Parse/ParseExpr.cpp +++ b/contrib/llvm-project/clang/lib/Parse/ParseExpr.cpp @@ -2629,12 +2629,6 @@ ExprResult Parser::ParseBuiltinPrimaryExpression() { Comps.back().U.IdentInfo = Tok.getIdentifierInfo(); Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken(); - enum class Kind { MemberAccess, ArraySubscript }; - auto DiagExt = [&](SourceLocation Loc, Kind K) { - Diag(Loc, diag::ext_offsetof_member_designator) - << (K == Kind::ArraySubscript) << (OOK == Sema::OOK_Macro); - }; - // FIXME: This loop leaks the index expressions on error. while (true) { if (Tok.is(tok::period)) { @@ -2648,7 +2642,6 @@ ExprResult Parser::ParseBuiltinPrimaryExpression() { SkipUntil(tok::r_paren, StopAtSemi); return ExprError(); } - DiagExt(Comps.back().LocStart, Kind::MemberAccess); Comps.back().U.IdentInfo = Tok.getIdentifierInfo(); Comps.back().LocEnd = ConsumeToken(); } else if (Tok.is(tok::l_square)) { @@ -2666,7 +2659,6 @@ ExprResult Parser::ParseBuiltinPrimaryExpression() { SkipUntil(tok::r_paren, StopAtSemi); return Res; } - DiagExt(Comps.back().LocStart, Kind::ArraySubscript); Comps.back().U.E = Res.get(); ST.consumeClose(); diff --git a/contrib/llvm-project/clang/lib/Sema/SemaAttr.cpp b/contrib/llvm-project/clang/lib/Sema/SemaAttr.cpp index 42f582724564..3ea97f6aa8f2 100644 --- a/contrib/llvm-project/clang/lib/Sema/SemaAttr.cpp +++ b/contrib/llvm-project/clang/lib/Sema/SemaAttr.cpp @@ -565,13 +565,6 @@ void Sema::ActOnPragmaFloatControl(SourceLocation Loc, case PFC_Precise: NewFPFeatures.setFPPreciseEnabled(true); FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures); - if (PP.getCurrentFPEvalMethod() == - LangOptions::FPEvalMethodKind::FEM_Indeterminable && - PP.getLastFPEvalPragmaLocation().isValid()) - // A preceding `pragma float_control(precise,off)` has changed - // the value of the evaluation method. - // Set it back to its old value. - PP.setCurrentFPEvalMethod(SourceLocation(), PP.getLastFPEvalMethod()); break; case PFC_NoPrecise: if (CurFPFeatures.getExceptionMode() == LangOptions::FPE_Strict) @@ -581,10 +574,6 @@ void Sema::ActOnPragmaFloatControl(SourceLocation Loc, else NewFPFeatures.setFPPreciseEnabled(false); FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures); - PP.setLastFPEvalMethod(PP.getCurrentFPEvalMethod()); - // `AllowFPReassoc` or `AllowReciprocal` option is enabled. - PP.setCurrentFPEvalMethod( - Loc, LangOptions::FPEvalMethodKind::FEM_Indeterminable); break; case PFC_Except: if (!isPreciseFPEnabled()) @@ -608,12 +597,6 @@ void Sema::ActOnPragmaFloatControl(SourceLocation Loc, } FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures); NewFPFeatures = FpPragmaStack.CurrentValue; - if (CurFPFeatures.getAllowFPReassociate() || - CurFPFeatures.getAllowReciprocal()) - // Since we are popping the pragma, we don't want to be passing - // a location here. - PP.setCurrentFPEvalMethod(SourceLocation(), - CurFPFeatures.getFPEvalMethod()); break; } CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts()); diff --git a/contrib/llvm-project/clang/lib/Sema/SemaConcept.cpp b/contrib/llvm-project/clang/lib/Sema/SemaConcept.cpp index 4d4b2482d046..a92bbde113fc 100755 --- a/contrib/llvm-project/clang/lib/Sema/SemaConcept.cpp +++ b/contrib/llvm-project/clang/lib/Sema/SemaConcept.cpp @@ -150,11 +150,19 @@ bool Sema::CheckConstraintExpression(const Expr *ConstraintExpression, namespace { struct SatisfactionStackRAII { Sema &SemaRef; - SatisfactionStackRAII(Sema &SemaRef, llvm::FoldingSetNodeID FSNID) + bool Inserted = false; + SatisfactionStackRAII(Sema &SemaRef, const NamedDecl *ND, + llvm::FoldingSetNodeID FSNID) : SemaRef(SemaRef) { - SemaRef.PushSatisfactionStackEntry(FSNID); + if (ND) { + SemaRef.PushSatisfactionStackEntry(ND, FSNID); + Inserted = true; + } + } + ~SatisfactionStackRAII() { + if (Inserted) + SemaRef.PopSatisfactionStackEntry(); } - ~SatisfactionStackRAII() { SemaRef.PopSatisfactionStackEntry(); } }; } // namespace @@ -273,7 +281,8 @@ calculateConstraintSatisfaction(Sema &S, const Expr *ConstraintExpr, } static bool -DiagRecursiveConstraintEval(Sema &S, llvm::FoldingSetNodeID &ID, const Expr *E, +DiagRecursiveConstraintEval(Sema &S, llvm::FoldingSetNodeID &ID, + const NamedDecl *Templ, const Expr *E, const MultiLevelTemplateArgumentList &MLTAL) { E->Profile(ID, S.Context, /*Canonical=*/true); for (const auto &List : MLTAL) @@ -286,7 +295,7 @@ DiagRecursiveConstraintEval(Sema &S, llvm::FoldingSetNodeID &ID, const Expr *E, // expression, or when trying to determine the constexpr-ness of special // members. Otherwise we could just use the // Sema::InstantiatingTemplate::isAlreadyBeingInstantiated function. - if (S.SatisfactionStackContains(ID)) { + if (S.SatisfactionStackContains(Templ, ID)) { S.Diag(E->getExprLoc(), diag::err_constraint_depends_on_self) << const_cast<Expr *>(E) << E->getSourceRange(); return true; @@ -317,13 +326,14 @@ static ExprResult calculateConstraintSatisfaction( return ExprError(); llvm::FoldingSetNodeID ID; - if (DiagRecursiveConstraintEval(S, ID, AtomicExpr, MLTAL)) { + if (Template && + DiagRecursiveConstraintEval(S, ID, Template, AtomicExpr, MLTAL)) { Satisfaction.IsSatisfied = false; Satisfaction.ContainsErrors = true; return ExprEmpty(); } - SatisfactionStackRAII StackRAII(S, ID); + SatisfactionStackRAII StackRAII(S, Template, ID); // We do not want error diagnostics escaping here. Sema::SFINAETrap Trap(S); @@ -1132,8 +1142,7 @@ substituteParameterMappings(Sema &S, NormalizedConstraint &N, Sema::InstantiatingTemplate Inst( S, ArgsAsWritten->arguments().front().getSourceRange().getBegin(), Sema::InstantiatingTemplate::ParameterMappingSubstitution{}, Concept, - SourceRange(ArgsAsWritten->arguments()[0].getSourceRange().getBegin(), - ArgsAsWritten->arguments().back().getSourceRange().getEnd())); + ArgsAsWritten->arguments().front().getSourceRange()); if (S.SubstTemplateArguments(*Atomic.ParameterMapping, MLTAL, SubstArgs)) return true; diff --git a/contrib/llvm-project/clang/lib/Sema/SemaCoroutine.cpp b/contrib/llvm-project/clang/lib/Sema/SemaCoroutine.cpp index 79c08adb8fab..9678e30699c8 100644 --- a/contrib/llvm-project/clang/lib/Sema/SemaCoroutine.cpp +++ b/contrib/llvm-project/clang/lib/Sema/SemaCoroutine.cpp @@ -1562,7 +1562,7 @@ bool CoroutineStmtBuilder::makeNewAndDeleteExpr() { const auto *OpDeleteType = OpDeleteQualType.getTypePtr()->castAs<FunctionProtoType>(); if (OpDeleteType->getNumParams() > DeleteArgs.size() && - S.getASTContext().hasSameType( + S.getASTContext().hasSameUnqualifiedType( OpDeleteType->getParamType(DeleteArgs.size()), FrameSize->getType())) DeleteArgs.push_back(FrameSize); @@ -1579,7 +1579,7 @@ bool CoroutineStmtBuilder::makeNewAndDeleteExpr() { // So we are not forced to pass alignment to the deallocation function. if (S.getLangOpts().CoroAlignedAllocation && OpDeleteType->getNumParams() > DeleteArgs.size() && - S.getASTContext().hasSameType( + S.getASTContext().hasSameUnqualifiedType( OpDeleteType->getParamType(DeleteArgs.size()), FrameAlignment->getType())) DeleteArgs.push_back(FrameAlignment); diff --git a/contrib/llvm-project/clang/lib/Sema/SemaDecl.cpp b/contrib/llvm-project/clang/lib/Sema/SemaDecl.cpp index e2b921bfe78f..051fad04219f 100644 --- a/contrib/llvm-project/clang/lib/Sema/SemaDecl.cpp +++ b/contrib/llvm-project/clang/lib/Sema/SemaDecl.cpp @@ -13088,9 +13088,10 @@ void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { // C++ [module.import/6] external definitions are not permitted in header // units. if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() && - VDecl->isThisDeclarationADefinition() && + !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() && VDecl->getFormalLinkage() == Linkage::ExternalLinkage && - !VDecl->isInline()) { + !VDecl->isInline() && !VDecl->isTemplated() && + !isa<VarTemplateSpecializationDecl>(VDecl)) { Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit); VDecl->setInvalidDecl(); } @@ -15259,9 +15260,10 @@ Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, // FIXME: Consider an alternate location for the test where the inlined() // state is complete. if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() && + !FD->isInvalidDecl() && !FD->isInlined() && + BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default && FD->getFormalLinkage() == Linkage::ExternalLinkage && - !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete && - BodyKind != FnBodyKind::Default && !FD->isInlined()) { + !FD->isTemplated() && !FD->isTemplateInstantiation()) { assert(FD->isThisDeclarationADefinition()); Diag(FD->getLocation(), diag::err_extern_def_in_header_unit); FD->setInvalidDecl(); @@ -16616,8 +16618,7 @@ Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, bool IsTemplateParamOrArg, - OffsetOfKind OOK, UsingShadowDecl *&FoundUsingShadow, - SkipBodyInfo *SkipBody) { + OffsetOfKind OOK, SkipBodyInfo *SkipBody) { // If this is not a definition, it must have a name. IdentifierInfo *OrigName = Name; assert((Name != nullptr || TUK == TUK_Definition) && @@ -17052,7 +17053,6 @@ Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, // redefinition if either context is within the other. if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { auto *OldTag = dyn_cast<TagDecl>(PrevDecl); - FoundUsingShadow = Shadow; if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && !(OldTag && isAcceptableTagRedeclContext( @@ -18871,10 +18871,24 @@ void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, ProcessDeclAttributeList(S, Record, Attrs); // Check to see if a FieldDecl is a pointer to a function. - auto IsFunctionPointer = [&](const Decl *D) { + auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) { const FieldDecl *FD = dyn_cast<FieldDecl>(D); - if (!FD) + if (!FD) { + // Check whether this is a forward declaration that was inserted by + // Clang. This happens when a non-forward declared / defined type is + // used, e.g.: + // + // struct foo { + // struct bar *(*f)(); + // struct bar *(*g)(); + // }; + // + // "struct bar" shows up in the decl AST as a "RecordDecl" with an + // incomplete definition. + if (const auto *TD = dyn_cast<TagDecl>(D)) + return !TD->isCompleteDefinition(); return false; + } QualType FieldType = FD->getType().getDesugaredType(Context); if (isa<PointerType>(FieldType)) { QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType(); @@ -18888,7 +18902,7 @@ void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, if (!getLangOpts().CPlusPlus && (Record->hasAttr<RandomizeLayoutAttr>() || (!Record->hasAttr<NoRandomizeLayoutAttr>() && - llvm::all_of(Record->decls(), IsFunctionPointer))) && + llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl))) && !Record->isUnion() && !getLangOpts().RandstructSeed.empty() && !Record->isRandomized()) { SmallVector<Decl *, 32> NewDeclOrdering; diff --git a/contrib/llvm-project/clang/lib/Sema/SemaDeclCXX.cpp b/contrib/llvm-project/clang/lib/Sema/SemaDeclCXX.cpp index 348092fc62e8..df83442a8cd1 100644 --- a/contrib/llvm-project/clang/lib/Sema/SemaDeclCXX.cpp +++ b/contrib/llvm-project/clang/lib/Sema/SemaDeclCXX.cpp @@ -16977,7 +16977,6 @@ DeclResult Sema::ActOnTemplatedFriendTag( if (SS.isEmpty()) { bool Owned = false; bool IsDependent = false; - UsingShadowDecl* FoundUsing = nullptr; return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, Attr, AS_public, /*ModulePrivateLoc=*/SourceLocation(), @@ -16986,7 +16985,7 @@ DeclResult Sema::ActOnTemplatedFriendTag( /*ScopedEnumUsesClassTag=*/false, /*UnderlyingType=*/TypeResult(), /*IsTypeSpecifier=*/false, - /*IsTemplateParamOrArg=*/false, /*OOK=*/OOK_Outside, FoundUsing); + /*IsTemplateParamOrArg=*/false, /*OOK=*/OOK_Outside); } NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); diff --git a/contrib/llvm-project/clang/lib/Sema/SemaExprCXX.cpp b/contrib/llvm-project/clang/lib/Sema/SemaExprCXX.cpp index e3eef9323b2f..abf5a72e7308 100644 --- a/contrib/llvm-project/clang/lib/Sema/SemaExprCXX.cpp +++ b/contrib/llvm-project/clang/lib/Sema/SemaExprCXX.cpp @@ -1483,13 +1483,14 @@ Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo, // Otherwise, if the type contains a placeholder type, it is replaced by the // type determined by placeholder type deduction. DeducedType *Deduced = Ty->getContainedDeducedType(); - if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) { + if (Deduced && !Deduced->isDeduced() && + isa<DeducedTemplateSpecializationType>(Deduced)) { Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity, Kind, Exprs); if (Ty.isNull()) return ExprError(); Entity = InitializedEntity::InitializeTemporary(TInfo, Ty); - } else if (Deduced) { + } else if (Deduced && !Deduced->isDeduced()) { MultiExprArg Inits = Exprs; if (ListInitialization) { auto *ILE = cast<InitListExpr>(Exprs[0]); @@ -2016,7 +2017,8 @@ ExprResult Sema::BuildCXXNew(SourceRange Range, bool UseGlobal, // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for. auto *Deduced = AllocType->getContainedDeducedType(); - if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) { + if (Deduced && !Deduced->isDeduced() && + isa<DeducedTemplateSpecializationType>(Deduced)) { if (ArraySize) return ExprError( Diag(*ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(), @@ -2030,7 +2032,7 @@ ExprResult Sema::BuildCXXNew(SourceRange Range, bool UseGlobal, AllocTypeInfo, Entity, Kind, Exprs); if (AllocType.isNull()) return ExprError(); - } else if (Deduced) { + } else if (Deduced && !Deduced->isDeduced()) { MultiExprArg Inits = Exprs; bool Braced = (initStyle == CXXNewExpr::ListInit); if (Braced) { diff --git a/contrib/llvm-project/clang/lib/Sema/SemaModule.cpp b/contrib/llvm-project/clang/lib/Sema/SemaModule.cpp index f52c0247f01c..194239ab0e10 100644 --- a/contrib/llvm-project/clang/lib/Sema/SemaModule.cpp +++ b/contrib/llvm-project/clang/lib/Sema/SemaModule.cpp @@ -337,20 +337,29 @@ Sema::ActOnModuleDecl(SourceLocation StartLoc, SourceLocation ModuleLoc, } case ModuleDeclKind::Implementation: { - std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc( - PP.getIdentifierInfo(ModuleName), Path[0].second); // C++20 A module-declaration that contains neither an export- // keyword nor a module-partition implicitly imports the primary // module interface unit of the module as if by a module-import- // declaration. + std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc( + PP.getIdentifierInfo(ModuleName), Path[0].second); + + // The module loader will assume we're trying to import the module that + // we're building if `LangOpts.CurrentModule` equals to 'ModuleName'. + // Change the value for `LangOpts.CurrentModule` temporarily to make the + // module loader work properly. + const_cast<LangOptions&>(getLangOpts()).CurrentModule = ""; Mod = getModuleLoader().loadModule(ModuleLoc, {ModuleNameLoc}, Module::AllVisible, /*IsInclusionDirective=*/false); + const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName; + if (!Mod) { Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName; // Create an empty module interface unit for error recovery. Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName); } + } break; case ModuleDeclKind::PartitionImplementation: diff --git a/contrib/llvm-project/clang/lib/Sema/SemaRISCVVectorLookup.cpp b/contrib/llvm-project/clang/lib/Sema/SemaRISCVVectorLookup.cpp index 7716dfb15458..fedc314f2965 100644 --- a/contrib/llvm-project/clang/lib/Sema/SemaRISCVVectorLookup.cpp +++ b/contrib/llvm-project/clang/lib/Sema/SemaRISCVVectorLookup.cpp @@ -192,7 +192,7 @@ void RISCVIntrinsicManagerImpl::InitIntrinsicList() { PolicyScheme MaskedPolicyScheme = static_cast<PolicyScheme>(Record.MaskedPolicyScheme); - const Policy DefaultPolicy(Record.HasTailPolicy, Record.HasMaskPolicy); + const Policy DefaultPolicy; llvm::SmallVector<PrototypeDescriptor> ProtoSeq = RVVIntrinsic::computeBuiltinTypes(BasicProtoSeq, /*IsMasked=*/false, @@ -208,8 +208,7 @@ void RISCVIntrinsicManagerImpl::InitIntrinsicList() { bool UnMaskedHasPolicy = UnMaskedPolicyScheme != PolicyScheme::SchemeNone; bool MaskedHasPolicy = MaskedPolicyScheme != PolicyScheme::SchemeNone; SmallVector<Policy> SupportedUnMaskedPolicies = - RVVIntrinsic::getSupportedUnMaskedPolicies(Record.HasTailPolicy, - Record.HasMaskPolicy); + RVVIntrinsic::getSupportedUnMaskedPolicies(); SmallVector<Policy> SupportedMaskedPolicies = RVVIntrinsic::getSupportedMaskedPolicies(Record.HasTailPolicy, Record.HasMaskPolicy); diff --git a/contrib/llvm-project/clang/lib/Sema/SemaTemplate.cpp b/contrib/llvm-project/clang/lib/Sema/SemaTemplate.cpp index 4b144c239fa4..890cea1dfb0e 100644 --- a/contrib/llvm-project/clang/lib/Sema/SemaTemplate.cpp +++ b/contrib/llvm-project/clang/lib/Sema/SemaTemplate.cpp @@ -2540,8 +2540,6 @@ private: TInfo->getType(), TInfo, LocEnd, Ctor); Guide->setImplicit(); Guide->setParams(Params); - if (Ctor && Ctor->getTrailingRequiresClause()) - Guide->setTrailingRequiresClause(Ctor->getTrailingRequiresClause()); for (auto *Param : Params) Param->setDeclContext(Guide); @@ -10181,14 +10179,11 @@ Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, bool Owned = false; bool IsDependent = false; - UsingShadowDecl* FoundUsing = nullptr; - Decl *TagD = - ActOnTag(S, TagSpec, Sema::TUK_Reference, KWLoc, SS, Name, NameLoc, Attr, - AS_none, /*ModulePrivateLoc=*/SourceLocation(), + Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference, KWLoc, SS, Name, + NameLoc, Attr, AS_none, /*ModulePrivateLoc=*/SourceLocation(), MultiTemplateParamsArg(), Owned, IsDependent, SourceLocation(), false, TypeResult(), /*IsTypeSpecifier*/ false, - /*IsTemplateParamOrArg*/ false, /*OOK=*/OOK_Outside, FoundUsing) - .get(); + /*IsTemplateParamOrArg*/ false, /*OOK=*/OOK_Outside).get(); assert(!IsDependent && "explicit instantiation of dependent name not yet handled"); if (!TagD) diff --git a/contrib/llvm-project/clang/lib/Sema/SemaTemplateDeduction.cpp b/contrib/llvm-project/clang/lib/Sema/SemaTemplateDeduction.cpp index 9e48a2a35a34..1fe2d3fac685 100644 --- a/contrib/llvm-project/clang/lib/Sema/SemaTemplateDeduction.cpp +++ b/contrib/llvm-project/clang/lib/Sema/SemaTemplateDeduction.cpp @@ -756,11 +756,8 @@ private: SmallVector<UnexpandedParameterPack, 2> Unexpanded; S.collectUnexpandedParameterPacks(Pattern, Unexpanded); for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) { - UnexpandedParameterPack U = Unexpanded[I]; - if (U.first.is<const SubstTemplateTypeParmPackType *>() || - U.first.is<const SubstNonTypeTemplateParmPackExpr *>()) - continue; - auto [Depth, Index] = getDepthAndIndex(U); + unsigned Depth, Index; + std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]); if (Depth == Info.getDeducedDepth()) AddPack(Index); } diff --git a/contrib/llvm-project/clang/lib/Sema/SemaTemplateVariadic.cpp b/contrib/llvm-project/clang/lib/Sema/SemaTemplateVariadic.cpp index 01a435668d88..86268b504cbb 100644 --- a/contrib/llvm-project/clang/lib/Sema/SemaTemplateVariadic.cpp +++ b/contrib/llvm-project/clang/lib/Sema/SemaTemplateVariadic.cpp @@ -89,23 +89,6 @@ namespace { return true; } - bool - VisitSubstTemplateTypeParmPackTypeLoc(SubstTemplateTypeParmPackTypeLoc TL) { - Unexpanded.push_back({TL.getTypePtr(), TL.getNameLoc()}); - return true; - } - - bool VisitSubstTemplateTypeParmPackType(SubstTemplateTypeParmPackType *T) { - Unexpanded.push_back({T, SourceLocation()}); - return true; - } - - bool - VisitSubstNonTypeTemplateParmPackExpr(SubstNonTypeTemplateParmPackExpr *E) { - Unexpanded.push_back({E, E->getParameterPackLocation()}); - return true; - } - /// Record occurrences of function and non-type template /// parameter packs in an expression. bool VisitDeclRefExpr(DeclRefExpr *E) { @@ -324,8 +307,7 @@ Sema::DiagnoseUnexpandedParameterPacks(SourceLocation Loc, auto *TTPD = dyn_cast<TemplateTypeParmDecl>(LocalPack); return TTPD && TTPD->getTypeForDecl() == TTPT; } - return declaresSameEntity(Pack.first.get<const NamedDecl *>(), - LocalPack); + return declaresSameEntity(Pack.first.get<NamedDecl *>(), LocalPack); }; if (llvm::any_of(LSI->LocalPacks, DeclaresThisPack)) LambdaParamPackReferences.push_back(Pack); @@ -377,7 +359,7 @@ Sema::DiagnoseUnexpandedParameterPacks(SourceLocation Loc, = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>()) Name = TTP->getIdentifier(); else - Name = Unexpanded[I].first.get<const NamedDecl *>()->getIdentifier(); + Name = Unexpanded[I].first.get<NamedDecl *>()->getIdentifier(); if (Name && NamesKnown.insert(Name).second) Names.push_back(Name); @@ -440,7 +422,7 @@ bool Sema::DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE) { llvm::SmallPtrSet<NamedDecl*, 8> ParmSet(Parms.begin(), Parms.end()); SmallVector<UnexpandedParameterPack, 2> UnexpandedParms; for (auto Parm : Unexpanded) - if (ParmSet.contains(Parm.first.dyn_cast<const NamedDecl *>())) + if (ParmSet.contains(Parm.first.dyn_cast<NamedDecl *>())) UnexpandedParms.push_back(Parm); if (UnexpandedParms.empty()) return false; @@ -692,95 +674,109 @@ bool Sema::CheckParameterPacksForExpansion( bool &RetainExpansion, std::optional<unsigned> &NumExpansions) { ShouldExpand = true; RetainExpansion = false; - std::pair<const IdentifierInfo *, SourceLocation> FirstPack; - std::optional<std::pair<unsigned, SourceLocation>> PartialExpansion; - std::optional<unsigned> CurNumExpansions; + std::pair<IdentifierInfo *, SourceLocation> FirstPack; + bool HaveFirstPack = false; + std::optional<unsigned> NumPartialExpansions; + SourceLocation PartiallySubstitutedPackLoc; - for (auto [P, Loc] : Unexpanded) { + for (UnexpandedParameterPack ParmPack : Unexpanded) { // Compute the depth and index for this parameter pack. - std::optional<std::pair<unsigned, unsigned>> Pos; + unsigned Depth = 0, Index = 0; + IdentifierInfo *Name; + bool IsVarDeclPack = false; + + if (const TemplateTypeParmType *TTP = + ParmPack.first.dyn_cast<const TemplateTypeParmType *>()) { + Depth = TTP->getDepth(); + Index = TTP->getIndex(); + Name = TTP->getIdentifier(); + } else { + NamedDecl *ND = ParmPack.first.get<NamedDecl *>(); + if (isa<VarDecl>(ND)) + IsVarDeclPack = true; + else + std::tie(Depth, Index) = getDepthAndIndex(ND); + + Name = ND->getIdentifier(); + } + + // Determine the size of this argument pack. unsigned NewPackSize; - const auto *ND = P.dyn_cast<const NamedDecl *>(); - if (ND && isa<VarDecl>(ND)) { - const auto *DAP = - CurrentInstantiationScope->findInstantiationOf(ND) - ->dyn_cast<LocalInstantiationScope::DeclArgumentPack *>(); - if (!DAP) { + if (IsVarDeclPack) { + // Figure out whether we're instantiating to an argument pack or not. + typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack; + + llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation = + CurrentInstantiationScope->findInstantiationOf( + ParmPack.first.get<NamedDecl *>()); + if (Instantiation->is<DeclArgumentPack *>()) { + // We could expand this function parameter pack. + NewPackSize = Instantiation->get<DeclArgumentPack *>()->size(); + } else { // We can't expand this function parameter pack, so we can't expand // the pack expansion. ShouldExpand = false; continue; } - NewPackSize = DAP->size(); - } else if (ND) { - Pos = getDepthAndIndex(ND); - } else if (const auto *TTP = P.dyn_cast<const TemplateTypeParmType *>()) { - Pos = {TTP->getDepth(), TTP->getIndex()}; - ND = TTP->getDecl(); - // FIXME: We either should have some fallback for canonical TTP, or - // never have canonical TTP here. - } else if (const auto *STP = - P.dyn_cast<const SubstTemplateTypeParmPackType *>()) { - NewPackSize = STP->getNumArgs(); - ND = STP->getReplacedParameter(); } else { - const auto *SEP = P.get<const SubstNonTypeTemplateParmPackExpr *>(); - NewPackSize = SEP->getArgumentPack().pack_size(); - ND = SEP->getParameterPack(); - } - - if (Pos) { // If we don't have a template argument at this depth/index, then we // cannot expand the pack expansion. Make a note of this, but we still // want to check any parameter packs we *do* have arguments for. - if (Pos->first >= TemplateArgs.getNumLevels() || - !TemplateArgs.hasTemplateArgument(Pos->first, Pos->second)) { + if (Depth >= TemplateArgs.getNumLevels() || + !TemplateArgs.hasTemplateArgument(Depth, Index)) { ShouldExpand = false; continue; } + // Determine the size of the argument pack. - NewPackSize = TemplateArgs(Pos->first, Pos->second).pack_size(); - // C++0x [temp.arg.explicit]p9: - // Template argument deduction can extend the sequence of template - // arguments corresponding to a template parameter pack, even when the - // sequence contains explicitly specified template arguments. - if (CurrentInstantiationScope) - if (const NamedDecl *PartialPack = - CurrentInstantiationScope->getPartiallySubstitutedPack(); - PartialPack && getDepthAndIndex(PartialPack) == *Pos) { + NewPackSize = TemplateArgs(Depth, Index).pack_size(); + } + + // C++0x [temp.arg.explicit]p9: + // Template argument deduction can extend the sequence of template + // arguments corresponding to a template parameter pack, even when the + // sequence contains explicitly specified template arguments. + if (!IsVarDeclPack && CurrentInstantiationScope) { + if (NamedDecl *PartialPack = + CurrentInstantiationScope->getPartiallySubstitutedPack()) { + unsigned PartialDepth, PartialIndex; + std::tie(PartialDepth, PartialIndex) = getDepthAndIndex(PartialPack); + if (PartialDepth == Depth && PartialIndex == Index) { RetainExpansion = true; // We don't actually know the new pack size yet. - PartialExpansion = {NewPackSize, Loc}; + NumPartialExpansions = NewPackSize; + PartiallySubstitutedPackLoc = ParmPack.second; continue; } + } } - // FIXME: Workaround for Canonical TTP. - const IdentifierInfo *Name = ND ? ND->getIdentifier() : nullptr; - if (!CurNumExpansions) { + if (!NumExpansions) { // The is the first pack we've seen for which we have an argument. // Record it. - CurNumExpansions = NewPackSize; - FirstPack = {Name, Loc}; - } else if (NewPackSize != *CurNumExpansions) { + NumExpansions = NewPackSize; + FirstPack.first = Name; + FirstPack.second = ParmPack.second; + HaveFirstPack = true; + continue; + } + + if (NewPackSize != *NumExpansions) { // C++0x [temp.variadic]p5: // All of the parameter packs expanded by a pack expansion shall have // the same number of arguments specified. - Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict) - << FirstPack.first << Name << *CurNumExpansions << NewPackSize - << SourceRange(FirstPack.second) << SourceRange(Loc); + if (HaveFirstPack) + Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict) + << FirstPack.first << Name << *NumExpansions << NewPackSize + << SourceRange(FirstPack.second) << SourceRange(ParmPack.second); + else + Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_multilevel) + << Name << *NumExpansions << NewPackSize + << SourceRange(ParmPack.second); return true; } } - if (NumExpansions && CurNumExpansions && - *NumExpansions != *CurNumExpansions) { - Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_multilevel) - << FirstPack.first << *CurNumExpansions << *NumExpansions - << SourceRange(FirstPack.second); - return true; - } - // If we're performing a partial expansion but we also have a full expansion, // expand to the number of common arguments. For example, given: // @@ -790,18 +786,17 @@ bool Sema::CheckParameterPacksForExpansion( // // ... a call to 'A<int, int>().f<int>' should expand the pack once and // retain an expansion. - if (PartialExpansion) { - if (CurNumExpansions && *CurNumExpansions < PartialExpansion->first) { + if (NumPartialExpansions) { + if (NumExpansions && *NumExpansions < *NumPartialExpansions) { NamedDecl *PartialPack = CurrentInstantiationScope->getPartiallySubstitutedPack(); Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_partial) - << PartialPack << PartialExpansion->first << *CurNumExpansions - << SourceRange(PartialExpansion->second); + << PartialPack << *NumPartialExpansions << *NumExpansions + << SourceRange(PartiallySubstitutedPackLoc); return true; } - NumExpansions = PartialExpansion->first; - } else { - NumExpansions = CurNumExpansions; + + NumExpansions = NumPartialExpansions; } return false; @@ -814,48 +809,47 @@ std::optional<unsigned> Sema::getNumArgumentsInExpansion( CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(Pattern); std::optional<unsigned> Result; - auto setResultSz = [&Result](unsigned Size) { - assert((!Result || *Result == Size) && "inconsistent pack sizes"); - Result = Size; - }; - auto setResultPos = [&](const std::pair<unsigned, unsigned> &Pos) -> bool { - unsigned Depth = Pos.first, Index = Pos.second; - if (Depth >= TemplateArgs.getNumLevels() || - !TemplateArgs.hasTemplateArgument(Depth, Index)) - // The pattern refers to an unknown template argument. We're not ready to - // expand this pack yet. - return true; - // Determine the size of the argument pack. - setResultSz(TemplateArgs(Depth, Index).pack_size()); - return false; - }; + for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) { + // Compute the depth and index for this parameter pack. + unsigned Depth; + unsigned Index; - for (auto [I, _] : Unexpanded) { - if (const auto *TTP = I.dyn_cast<const TemplateTypeParmType *>()) { - if (setResultPos({TTP->getDepth(), TTP->getIndex()})) - return std::nullopt; - } else if (const auto *STP = - I.dyn_cast<const SubstTemplateTypeParmPackType *>()) { - setResultSz(STP->getNumArgs()); - } else if (const auto *SEP = - I.dyn_cast<const SubstNonTypeTemplateParmPackExpr *>()) { - setResultSz(SEP->getArgumentPack().pack_size()); + if (const TemplateTypeParmType *TTP = + Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>()) { + Depth = TTP->getDepth(); + Index = TTP->getIndex(); } else { - const auto *ND = I.get<const NamedDecl *>(); - // Function parameter pack or init-capture pack. + NamedDecl *ND = Unexpanded[I].first.get<NamedDecl *>(); if (isa<VarDecl>(ND)) { - const auto *DAP = - CurrentInstantiationScope->findInstantiationOf(ND) - ->dyn_cast<LocalInstantiationScope::DeclArgumentPack *>(); - if (!DAP) + // Function parameter pack or init-capture pack. + typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack; + + llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation = + CurrentInstantiationScope->findInstantiationOf( + Unexpanded[I].first.get<NamedDecl *>()); + if (Instantiation->is<Decl *>()) // The pattern refers to an unexpanded pack. We're not ready to expand // this pack yet. return std::nullopt; - setResultSz(DAP->size()); - } else if (setResultPos(getDepthAndIndex(ND))) { - return std::nullopt; + + unsigned Size = Instantiation->get<DeclArgumentPack *>()->size(); + assert((!Result || *Result == Size) && "inconsistent pack sizes"); + Result = Size; + continue; } + + std::tie(Depth, Index) = getDepthAndIndex(ND); } + if (Depth >= TemplateArgs.getNumLevels() || + !TemplateArgs.hasTemplateArgument(Depth, Index)) + // The pattern refers to an unknown template argument. We're not ready to + // expand this pack yet. + return std::nullopt; + + // Determine the size of the argument pack. + unsigned Size = TemplateArgs(Depth, Index).pack_size(); + assert((!Result || *Result == Size) && "inconsistent pack sizes"); + Result = Size; } return Result; diff --git a/contrib/llvm-project/clang/lib/Sema/SemaType.cpp b/contrib/llvm-project/clang/lib/Sema/SemaType.cpp index 89d819a77dcb..8cb1ed28fe3e 100644 --- a/contrib/llvm-project/clang/lib/Sema/SemaType.cpp +++ b/contrib/llvm-project/clang/lib/Sema/SemaType.cpp @@ -1588,9 +1588,6 @@ static QualType ConvertDeclSpecToType(TypeProcessingState &state) { // TypeQuals handled by caller. Result = Context.getTypeDeclType(D); - if (const auto *Using = - dyn_cast_or_null<UsingShadowDecl>(DS.getRepAsFoundDecl())) - Result = Context.getUsingType(Using, Result); // In both C and C++, make an ElaboratedType. ElaboratedTypeKeyword Keyword @@ -6256,9 +6253,6 @@ namespace { void VisitTagTypeLoc(TagTypeLoc TL) { TL.setNameLoc(DS.getTypeSpecTypeNameLoc()); } - void VisitUsingTypeLoc(UsingTypeLoc TL) { - TL.setNameLoc(DS.getTypeSpecTypeNameLoc()); - } void VisitAtomicTypeLoc(AtomicTypeLoc TL) { // An AtomicTypeLoc can come from either an _Atomic(...) type specifier // or an _Atomic qualifier. diff --git a/contrib/llvm-project/clang/lib/Sema/TreeTransform.h b/contrib/llvm-project/clang/lib/Sema/TreeTransform.h index 6a05ecc5370f..48bb28b56cd3 100644 --- a/contrib/llvm-project/clang/lib/Sema/TreeTransform.h +++ b/contrib/llvm-project/clang/lib/Sema/TreeTransform.h @@ -4569,7 +4569,7 @@ bool TreeTransform<Derived>::TransformTemplateArgument( getSema(), Uneval ? Sema::ExpressionEvaluationContext::Unevaluated : Sema::ExpressionEvaluationContext::ConstantEvaluated, - /*LambdaContextDecl=*/nullptr, /*ExprContext=*/ + Sema::ReuseLambdaContextDecl, /*ExprContext=*/ Sema::ExpressionEvaluationContextRecord::EK_TemplateArgument); Expr *InputExpr = Input.getSourceExpression(); @@ -5897,7 +5897,6 @@ bool TreeTransform<Derived>::TransformFunctionTypeParams( = dyn_cast<PackExpansionType>(OldType)) { // We have a function parameter pack that may need to be expanded. QualType Pattern = Expansion->getPattern(); - NumExpansions = Expansion->getNumExpansions(); SmallVector<UnexpandedParameterPack, 2> Unexpanded; getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded); diff --git a/contrib/llvm-project/clang/lib/StaticAnalyzer/Checkers/ReturnPointerRangeChecker.cpp b/contrib/llvm-project/clang/lib/StaticAnalyzer/Checkers/ReturnPointerRangeChecker.cpp index b35ab1fe23ce..b85d0adb8eaf 100644 --- a/contrib/llvm-project/clang/lib/StaticAnalyzer/Checkers/ReturnPointerRangeChecker.cpp +++ b/contrib/llvm-project/clang/lib/StaticAnalyzer/Checkers/ReturnPointerRangeChecker.cpp @@ -41,6 +41,10 @@ void ReturnPointerRangeChecker::checkPreStmt(const ReturnStmt *RS, if (!RetE) return; + // Skip "body farmed" functions. + if (RetE->getSourceRange().isInvalid()) + return; + SVal V = C.getSVal(RetE); const MemRegion *R = V.getAsRegion(); diff --git a/contrib/llvm-project/clang/lib/StaticAnalyzer/Core/BugReporter.cpp b/contrib/llvm-project/clang/lib/StaticAnalyzer/Core/BugReporter.cpp index a7f149b87e79..c3bd4876faf2 100644 --- a/contrib/llvm-project/clang/lib/StaticAnalyzer/Core/BugReporter.cpp +++ b/contrib/llvm-project/clang/lib/StaticAnalyzer/Core/BugReporter.cpp @@ -766,7 +766,7 @@ PathDiagnosticPieceRef PathDiagnosticBuilder::generateDiagForSwitchOP( case Stmt::CaseStmtClass: { os << "Control jumps to 'case "; const auto *Case = cast<CaseStmt>(S); - const Expr *LHS = Case->getLHS()->IgnoreParenCasts(); + const Expr *LHS = Case->getLHS()->IgnoreParenImpCasts(); // Determine if it is an enum. bool GetRawInt = true; diff --git a/contrib/llvm-project/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp b/contrib/llvm-project/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp index 1017dff2b0f3..a275d36286d3 100644 --- a/contrib/llvm-project/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp +++ b/contrib/llvm-project/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp @@ -2678,7 +2678,18 @@ EquivalenceClass::simplify(SValBuilder &SVB, RangeSet::Factory &F, if (OldState == State) continue; - assert(find(State, MemberSym) == find(State, SimplifiedMemberSym)); + // Be aware that `SimplifiedMemberSym` might refer to an already dead + // symbol. In that case, the eqclass of that might not be the same as the + // eqclass of `MemberSym`. This is because the dead symbols are not + // preserved in the `ClassMap`, hence + // `find(State, SimplifiedMemberSym)` will result in a trivial eqclass + // compared to the eqclass of `MemberSym`. + // These eqclasses should be the same if `SimplifiedMemberSym` is alive. + // --> assert(find(State, MemberSym) == find(State, SimplifiedMemberSym)) + // + // Note that `MemberSym` must be alive here since that is from the + // `ClassMembers` where all the symbols are alive. + // Remove the old and more complex symbol. State = find(State, MemberSym).removeMember(State, MemberSym); diff --git a/contrib/llvm-project/clang/lib/StaticAnalyzer/Core/RegionStore.cpp b/contrib/llvm-project/clang/lib/StaticAnalyzer/Core/RegionStore.cpp index 46948c12617c..49855305cecc 100644 --- a/contrib/llvm-project/clang/lib/StaticAnalyzer/Core/RegionStore.cpp +++ b/contrib/llvm-project/clang/lib/StaticAnalyzer/Core/RegionStore.cpp @@ -1849,8 +1849,12 @@ std::optional<SVal> RegionStoreManager::getSValFromInitListExpr( // Go to the nested initializer list. ILE = IL; } - llvm_unreachable( - "Unhandled InitListExpr sub-expressions or invalid offsets."); + + assert(ILE); + + // FIXME: Unhandeled InitListExpr sub-expression, possibly constructing an + // enum? + return std::nullopt; } /// Returns an SVal, if possible, for the specified position in a string diff --git a/contrib/llvm-project/clang/lib/Support/RISCVVIntrinsicUtils.cpp b/contrib/llvm-project/clang/lib/Support/RISCVVIntrinsicUtils.cpp index 25084dd98e5c..86da7e86f831 100644 --- a/contrib/llvm-project/clang/lib/Support/RISCVVIntrinsicUtils.cpp +++ b/contrib/llvm-project/clang/lib/Support/RISCVVIntrinsicUtils.cpp @@ -966,40 +966,26 @@ llvm::SmallVector<PrototypeDescriptor> RVVIntrinsic::computeBuiltinTypes( return NewPrototype; } -llvm::SmallVector<Policy> -RVVIntrinsic::getSupportedUnMaskedPolicies(bool HasTailPolicy, - bool HasMaskPolicy) { - return { - Policy(Policy::PolicyType::Undisturbed, HasTailPolicy, - HasMaskPolicy), // TU - Policy(Policy::PolicyType::Agnostic, HasTailPolicy, HasMaskPolicy)}; // TA +llvm::SmallVector<Policy> RVVIntrinsic::getSupportedUnMaskedPolicies() { + return {Policy(Policy::PolicyType::Undisturbed)}; // TU } llvm::SmallVector<Policy> RVVIntrinsic::getSupportedMaskedPolicies(bool HasTailPolicy, bool HasMaskPolicy) { if (HasTailPolicy && HasMaskPolicy) - return { - Policy(Policy::PolicyType::Undisturbed, Policy::PolicyType::Agnostic, - HasTailPolicy, HasMaskPolicy), // TUMA - Policy(Policy::PolicyType::Agnostic, Policy::PolicyType::Agnostic, - HasTailPolicy, HasMaskPolicy), // TAMA - Policy(Policy::PolicyType::Undisturbed, Policy::PolicyType::Undisturbed, - HasTailPolicy, HasMaskPolicy), // TUMU - Policy(Policy::PolicyType::Agnostic, Policy::PolicyType::Undisturbed, - HasTailPolicy, HasMaskPolicy)}; // TAMU + return {Policy(Policy::PolicyType::Undisturbed, + Policy::PolicyType::Agnostic), // TUM + Policy(Policy::PolicyType::Undisturbed, + Policy::PolicyType::Undisturbed), // TUMU + Policy(Policy::PolicyType::Agnostic, + Policy::PolicyType::Undisturbed)}; // MU if (HasTailPolicy && !HasMaskPolicy) return {Policy(Policy::PolicyType::Undisturbed, - Policy::PolicyType::Agnostic, HasTailPolicy, - HasMaskPolicy), // TUM - Policy(Policy::PolicyType::Agnostic, Policy::PolicyType::Agnostic, - HasTailPolicy, HasMaskPolicy)}; // TAM + Policy::PolicyType::Agnostic)}; // TU if (!HasTailPolicy && HasMaskPolicy) - return {Policy(Policy::PolicyType::Agnostic, Policy::PolicyType::Agnostic, - HasTailPolicy, HasMaskPolicy), // MA - Policy(Policy::PolicyType::Agnostic, - Policy::PolicyType::Undisturbed, HasTailPolicy, - HasMaskPolicy)}; // MU + return {Policy(Policy::PolicyType::Agnostic, + Policy::PolicyType::Undisturbed)}; // MU llvm_unreachable("An RVV instruction should not be without both tail policy " "and mask policy"); } @@ -1016,46 +1002,34 @@ void RVVIntrinsic::updateNamesAndPolicy(bool IsMasked, bool HasPolicy, OverloadedName += suffix; }; - if (PolicyAttrs.isUnspecified()) { - PolicyAttrs.IsUnspecified = false; - if (IsMasked) { + // This follows the naming guideline under riscv-c-api-doc to add the + // `__riscv_` suffix for all RVV intrinsics. + Name = "__riscv_" + Name; + OverloadedName = "__riscv_" + OverloadedName; + + if (IsMasked) { + if (PolicyAttrs.isTUMUPolicy()) + appendPolicySuffix("_tumu"); + else if (PolicyAttrs.isTUMAPolicy()) + appendPolicySuffix("_tum"); + else if (PolicyAttrs.isTAMUPolicy()) + appendPolicySuffix("_mu"); + else if (PolicyAttrs.isTAMAPolicy()) { Name += "_m"; if (HasPolicy) BuiltinName += "_tama"; else BuiltinName += "_m"; - } else { + } else + llvm_unreachable("Unhandled policy condition"); + } else { + if (PolicyAttrs.isTUPolicy()) + appendPolicySuffix("_tu"); + else if (PolicyAttrs.isTAPolicy()) { if (HasPolicy) BuiltinName += "_ta"; - } - } else { - if (IsMasked) { - if (PolicyAttrs.isTUMAPolicy() && !PolicyAttrs.hasMaskPolicy()) - appendPolicySuffix("_tum"); - else if (PolicyAttrs.isTAMAPolicy() && !PolicyAttrs.hasMaskPolicy()) - appendPolicySuffix("_tam"); - else if (PolicyAttrs.isMUPolicy() && !PolicyAttrs.hasTailPolicy()) - appendPolicySuffix("_mu"); - else if (PolicyAttrs.isMAPolicy() && !PolicyAttrs.hasTailPolicy()) - appendPolicySuffix("_ma"); - else if (PolicyAttrs.isTUMUPolicy()) - appendPolicySuffix("_tumu"); - else if (PolicyAttrs.isTAMUPolicy()) - appendPolicySuffix("_tamu"); - else if (PolicyAttrs.isTUMAPolicy()) - appendPolicySuffix("_tuma"); - else if (PolicyAttrs.isTAMAPolicy()) - appendPolicySuffix("_tama"); - else - llvm_unreachable("Unhandled policy condition"); - } else { - if (PolicyAttrs.isTUPolicy()) - appendPolicySuffix("_tu"); - else if (PolicyAttrs.isTAPolicy()) - appendPolicySuffix("_ta"); - else - llvm_unreachable("Unhandled policy condition"); - } + } else + llvm_unreachable("Unhandled policy condition"); } } diff --git a/contrib/llvm-project/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp b/contrib/llvm-project/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp index 3fcef00a5780..ae1662237e87 100644 --- a/contrib/llvm-project/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp +++ b/contrib/llvm-project/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp @@ -40,67 +40,69 @@ DependencyScanningTool::DependencyScanningTool( llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS) : Worker(Service, std::move(FS)) {} -llvm::Expected<std::string> DependencyScanningTool::getDependencyFile( - const std::vector<std::string> &CommandLine, StringRef CWD, - std::optional<StringRef> ModuleName) { - /// Prints out all of the gathered dependencies into a string. - class MakeDependencyPrinterConsumer : public DependencyConsumer { - public: - void handleBuildCommand(Command) override {} +namespace { +/// Prints out all of the gathered dependencies into a string. +class MakeDependencyPrinterConsumer : public DependencyConsumer { +public: + void handleBuildCommand(Command) override {} + + void + handleDependencyOutputOpts(const DependencyOutputOptions &Opts) override { + this->Opts = std::make_unique<DependencyOutputOptions>(Opts); + } - void - handleDependencyOutputOpts(const DependencyOutputOptions &Opts) override { - this->Opts = std::make_unique<DependencyOutputOptions>(Opts); - } + void handleFileDependency(StringRef File) override { + Dependencies.push_back(std::string(File)); + } - void handleFileDependency(StringRef File) override { - Dependencies.push_back(std::string(File)); - } + void handlePrebuiltModuleDependency(PrebuiltModuleDep PMD) override { + // Same as `handleModuleDependency`. + } - void handlePrebuiltModuleDependency(PrebuiltModuleDep PMD) override { - // Same as `handleModuleDependency`. - } + void handleModuleDependency(ModuleDeps MD) override { + // These are ignored for the make format as it can't support the full + // set of deps, and handleFileDependency handles enough for implicitly + // built modules to work. + } - void handleModuleDependency(ModuleDeps MD) override { - // These are ignored for the make format as it can't support the full - // set of deps, and handleFileDependency handles enough for implicitly - // built modules to work. - } + void handleContextHash(std::string Hash) override {} - void handleContextHash(std::string Hash) override {} + std::string lookupModuleOutput(const ModuleID &ID, + ModuleOutputKind Kind) override { + llvm::report_fatal_error("unexpected call to lookupModuleOutput"); + } - std::string lookupModuleOutput(const ModuleID &ID, - ModuleOutputKind Kind) override { - llvm::report_fatal_error("unexpected call to lookupModuleOutput"); - } + void printDependencies(std::string &S) { + assert(Opts && "Handled dependency output options."); - void printDependencies(std::string &S) { - assert(Opts && "Handled dependency output options."); - - class DependencyPrinter : public DependencyFileGenerator { - public: - DependencyPrinter(DependencyOutputOptions &Opts, - ArrayRef<std::string> Dependencies) - : DependencyFileGenerator(Opts) { - for (const auto &Dep : Dependencies) - addDependency(Dep); - } - - void printDependencies(std::string &S) { - llvm::raw_string_ostream OS(S); - outputDependencyFile(OS); - } - }; - - DependencyPrinter Generator(*Opts, Dependencies); - Generator.printDependencies(S); - } + class DependencyPrinter : public DependencyFileGenerator { + public: + DependencyPrinter(DependencyOutputOptions &Opts, + ArrayRef<std::string> Dependencies) + : DependencyFileGenerator(Opts) { + for (const auto &Dep : Dependencies) + addDependency(Dep); + } - private: - std::unique_ptr<DependencyOutputOptions> Opts; - std::vector<std::string> Dependencies; - }; + void printDependencies(std::string &S) { + llvm::raw_string_ostream OS(S); + outputDependencyFile(OS); + } + }; + + DependencyPrinter Generator(*Opts, Dependencies); + Generator.printDependencies(S); + } + +protected: + std::unique_ptr<DependencyOutputOptions> Opts; + std::vector<std::string> Dependencies; +}; +} // anonymous namespace +llvm::Expected<std::string> DependencyScanningTool::getDependencyFile( + const std::vector<std::string> &CommandLine, StringRef CWD, + std::optional<StringRef> ModuleName) { MakeDependencyPrinterConsumer Consumer; auto Result = Worker.computeDependencies(CWD, CommandLine, Consumer, ModuleName); @@ -111,6 +113,50 @@ llvm::Expected<std::string> DependencyScanningTool::getDependencyFile( return Output; } +llvm::Expected<P1689Rule> DependencyScanningTool::getP1689ModuleDependencyFile( + const CompileCommand &Command, StringRef CWD, + std::string &MakeformatOutput, std::string &MakeformatOutputPath) { + class P1689ModuleDependencyPrinterConsumer + : public MakeDependencyPrinterConsumer { + public: + P1689ModuleDependencyPrinterConsumer(P1689Rule &Rule, + const CompileCommand &Command) + : Filename(Command.Filename), Rule(Rule) { + Rule.PrimaryOutput = Command.Output; + } + + void handleProvidedAndRequiredStdCXXModules( + std::optional<P1689ModuleInfo> Provided, + std::vector<P1689ModuleInfo> Requires) override { + Rule.Provides = Provided; + if (Rule.Provides) + Rule.Provides->SourcePath = Filename.str(); + Rule.Requires = Requires; + } + + StringRef getMakeFormatDependencyOutputPath() { + if (Opts->OutputFormat != DependencyOutputFormat::Make) + return {}; + return Opts->OutputFile; + } + + private: + StringRef Filename; + P1689Rule &Rule; + }; + + P1689Rule Rule; + P1689ModuleDependencyPrinterConsumer Consumer(Rule, Command); + auto Result = Worker.computeDependencies(CWD, Command.CommandLine, Consumer); + if (Result) + return std::move(Result); + + MakeformatOutputPath = Consumer.getMakeFormatDependencyOutputPath(); + if (!MakeformatOutputPath.empty()) + Consumer.printDependencies(MakeformatOutput); + return Rule; +} + llvm::Expected<FullDependenciesResult> DependencyScanningTool::getFullDependencies( const std::vector<std::string> &CommandLine, StringRef CWD, diff --git a/contrib/llvm-project/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp b/contrib/llvm-project/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp index b54b8de9157e..8eb0328d6322 100644 --- a/contrib/llvm-project/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp +++ b/contrib/llvm-project/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp @@ -247,10 +247,12 @@ public: std::make_shared<DependencyConsumerForwarder>( std::move(Opts), WorkingDirectory, Consumer)); break; + case ScanningOutputFormat::P1689: case ScanningOutputFormat::Full: MDC = std::make_shared<ModuleDepCollector>( std::move(Opts), ScanInstance, Consumer, OriginalInvocation, - OptimizeArgs, EagerLoadModules); + OptimizeArgs, EagerLoadModules, + Format == ScanningOutputFormat::P1689); ScanInstance.addDependencyCollector(MDC); break; } diff --git a/contrib/llvm-project/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp b/contrib/llvm-project/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp index cb1c66b8d63f..d1cbf79a843e 100644 --- a/contrib/llvm-project/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp +++ b/contrib/llvm-project/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp @@ -339,6 +339,14 @@ void ModuleDepCollectorPP::InclusionDirective( void ModuleDepCollectorPP::moduleImport(SourceLocation ImportLoc, ModuleIdPath Path, const Module *Imported) { + if (MDC.ScanInstance.getPreprocessor().isInImportingCXXNamedModules()) { + P1689ModuleInfo RequiredModule; + RequiredModule.ModuleName = Path[0].first->getName().str(); + RequiredModule.Type = P1689ModuleInfo::ModuleType::NamedCXXModule; + MDC.RequiredStdCXXModules.push_back(RequiredModule); + return; + } + handleImport(Imported); } @@ -361,6 +369,21 @@ void ModuleDepCollectorPP::EndOfMainFile() { .getFileEntryForID(MainFileID) ->getName()); + auto &PP = MDC.ScanInstance.getPreprocessor(); + if (PP.isInNamedModule()) { + P1689ModuleInfo ProvidedModule; + ProvidedModule.ModuleName = PP.getNamedModuleName(); + ProvidedModule.Type = P1689ModuleInfo::ModuleType::NamedCXXModule; + ProvidedModule.IsStdCXXModuleInterface = PP.isInNamedInterfaceUnit(); + // Don't put implementation (non partition) unit as Provide. + // Put the module as required instead. Since the implementation + // unit will import the primary module implicitly. + if (PP.isInImplementationUnit()) + MDC.RequiredStdCXXModules.push_back(ProvidedModule); + else + MDC.ProvidedStdCXXModule = ProvidedModule; + } + if (!MDC.ScanInstance.getPreprocessorOpts().ImplicitPCHInclude.empty()) MDC.addFileDep(MDC.ScanInstance.getPreprocessorOpts().ImplicitPCHInclude); @@ -374,6 +397,10 @@ void ModuleDepCollectorPP::EndOfMainFile() { MDC.Consumer.handleDependencyOutputOpts(*MDC.Opts); + if (MDC.IsStdModuleP1689Format) + MDC.Consumer.handleProvidedAndRequiredStdCXXModules( + MDC.ProvidedStdCXXModule, MDC.RequiredStdCXXModules); + for (auto &&I : MDC.ModularDeps) MDC.Consumer.handleModuleDependency(*I.second); @@ -548,10 +575,12 @@ void ModuleDepCollectorPP::addAffectingClangModule( ModuleDepCollector::ModuleDepCollector( std::unique_ptr<DependencyOutputOptions> Opts, CompilerInstance &ScanInstance, DependencyConsumer &C, - CompilerInvocation OriginalCI, bool OptimizeArgs, bool EagerLoadModules) + CompilerInvocation OriginalCI, bool OptimizeArgs, bool EagerLoadModules, + bool IsStdModuleP1689Format) : ScanInstance(ScanInstance), Consumer(C), Opts(std::move(Opts)), OriginalInvocation(std::move(OriginalCI)), OptimizeArgs(OptimizeArgs), - EagerLoadModules(EagerLoadModules) {} + EagerLoadModules(EagerLoadModules), + IsStdModuleP1689Format(IsStdModuleP1689Format) {} void ModuleDepCollector::attachToPreprocessor(Preprocessor &PP) { PP.addPPCallbacks(std::make_unique<ModuleDepCollectorPP>(*this)); |
