[clang] [clang][AST] Handle dependent representation of call to function with explicit object parameter in CallExpr::getBeginLoc() (PR #126868)
zyn0217 wrote: > > While this may not be the most optimal solution, we can likely go with it > > as-is to put the fire out. > > Given [this > comment](https://github.com/llvm/llvm-project/pull/126868#discussion_r1953948099) > (i.e. that the behaviour with this patch is correct for the dependent case > as well), is there anything else not optimal about this solution? I was considering finding a better AST model, but it's more complex than the approach so this is good enough for now :P https://github.com/llvm/llvm-project/pull/126868 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][AST] Handle dependent representation of call to function with explicit object parameter in CallExpr::getBeginLoc() (PR #126868)
https://github.com/zyn0217 approved this pull request. https://github.com/llvm/llvm-project/pull/126868 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-scan-deps] Avoid repeated map lookups (NFC) (PR #127023)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Kazu Hirata (kazutakahirata) Changes --- Full diff: https://github.com/llvm/llvm-project/pull/127023.diff 1 Files Affected: - (modified) clang/tools/clang-scan-deps/ClangScanDeps.cpp (+1-2) ``diff diff --git a/clang/tools/clang-scan-deps/ClangScanDeps.cpp b/clang/tools/clang-scan-deps/ClangScanDeps.cpp index 4b39ae9c35c04..9cdb1eae56187 100644 --- a/clang/tools/clang-scan-deps/ClangScanDeps.cpp +++ b/clang/tools/clang-scan-deps/ClangScanDeps.cpp @@ -308,8 +308,7 @@ class ResourceDirectoryCache { return ""; StringRef Output = OutputBuf.get()->getBuffer().rtrim('\n'); -Cache[ClangBinaryPath] = Output.str(); -return Cache[ClangBinaryPath]; +return Cache[ClangBinaryPath] = Output.str(); } private: `` https://github.com/llvm/llvm-project/pull/127023 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-scan-deps] Avoid repeated map lookups (NFC) (PR #127023)
https://github.com/kazutakahirata created https://github.com/llvm/llvm-project/pull/127023 None >From a5fcb4155ee6d50c295aa7b38f174ee35d4f4540 Mon Sep 17 00:00:00 2001 From: Kazu Hirata Date: Wed, 12 Feb 2025 09:11:49 -0800 Subject: [PATCH] [clang-scan-deps] Avoid repeated map lookups (NFC) --- clang/tools/clang-scan-deps/ClangScanDeps.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/clang/tools/clang-scan-deps/ClangScanDeps.cpp b/clang/tools/clang-scan-deps/ClangScanDeps.cpp index 4b39ae9c35c04..9cdb1eae56187 100644 --- a/clang/tools/clang-scan-deps/ClangScanDeps.cpp +++ b/clang/tools/clang-scan-deps/ClangScanDeps.cpp @@ -308,8 +308,7 @@ class ResourceDirectoryCache { return ""; StringRef Output = OutputBuf.get()->getBuffer().rtrim('\n'); -Cache[ClangBinaryPath] = Output.str(); -return Cache[ClangBinaryPath]; +return Cache[ClangBinaryPath] = Output.str(); } private: ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [NFC] Avoid potential null deref by adding an assert. (PR #127017)
https://github.com/schittir updated https://github.com/llvm/llvm-project/pull/127017 >From 66a9f9938ead51155560c911537c00bad7c644df Mon Sep 17 00:00:00 2001 From: Sindhu Chittireddy Date: Wed, 12 Feb 2025 23:27:01 -0800 Subject: [PATCH 1/2] [NFC] Avoid potential null deref by adding an assert. --- clang/lib/StaticAnalyzer/Checkers/MacOSKeychainAPIChecker.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/clang/lib/StaticAnalyzer/Checkers/MacOSKeychainAPIChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/MacOSKeychainAPIChecker.cpp index 12bf12a0b2322..8955cb209c399 100644 --- a/clang/lib/StaticAnalyzer/Checkers/MacOSKeychainAPIChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/MacOSKeychainAPIChecker.cpp @@ -314,6 +314,7 @@ void MacOSKeychainAPIChecker::checkPreStmt(const CallExpr *CE, RegionArgIsBad = true; } + assert(ArgSM); // Is the argument to the call being tracked? const AllocationState *AS = State->get(ArgSM); if (!AS) >From 0149532e4e47e5f3f0b09efb1392659719591957 Mon Sep 17 00:00:00 2001 From: Sindhu Chittireddy Date: Thu, 13 Feb 2025 00:04:28 -0800 Subject: [PATCH 2/2] Avoid potential null deref of OASE --- clang/lib/CodeGen/CGOpenMPRuntime.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp b/clang/lib/CodeGen/CGOpenMPRuntime.cpp index b679d63874b3b..9f7db25a15bec 100644 --- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp +++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp @@ -7447,7 +7447,7 @@ class MappableExprsHandler { // Update info about the lowest and highest elements for this struct if (!PartialStruct.Base.isValid()) { PartialStruct.LowestElem = {FieldIndex, LowestElem}; -if (IsFinalArraySection) { +if (IsFinalArraySection && OASE) { Address HB = CGF.EmitArraySectionExpr(OASE, /*IsLowerBound=*/false) .getAddress(); @@ -7460,7 +7460,7 @@ class MappableExprsHandler { } else if (FieldIndex < PartialStruct.LowestElem.first) { PartialStruct.LowestElem = {FieldIndex, LowestElem}; } else if (FieldIndex > PartialStruct.HighestElem.first) { -if (IsFinalArraySection) { +if (IsFinalArraySection && OASE) { Address HB = CGF.EmitArraySectionExpr(OASE, /*IsLowerBound=*/false) .getAddress(); ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-scan-deps] Avoid repeated map lookups (NFC) (PR #127023)
https://github.com/nikic approved this pull request. https://github.com/llvm/llvm-project/pull/127023 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [NFC] Avoid potential null dereference. (PR #127017)
https://github.com/schittir edited https://github.com/llvm/llvm-project/pull/127017 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][Sema] Fix type of an statement expression ending with an atomic type (PR #119711)
@@ -0,0 +1,16 @@ +// RUN: %clang_cc1 -fsyntax-only -verify %s + +typedef _Atomic char atomic_char; + +typedef _Atomic char atomic_char; alejandro-alvarez-sonarsource wrote: It isn't, I have removed the duplicated line. https://github.com/llvm/llvm-project/pull/119711 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [NFC] Avoid potential null dereference. (PR #127017)
https://github.com/schittir edited https://github.com/llvm/llvm-project/pull/127017 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[libclc] [libclc] Stop installing CLC headers (PR #126908)
arsenm wrote: I suppose we could interpret the environment part of the triple to influence the target's reported set of extensions (plus consolidate all of these defines into the compiler). Do we even get consistent behavior when using -fdeclare-opencl-bulitins? I could believe we could just delete the header defines without any issue https://github.com/llvm/llvm-project/pull/126908 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 912b154 - Revert "[C++20][Modules][Serialization] Delay marking pending incompl… (#127136)
Author: Zixu Wang Date: 2025-02-13T16:12:22-08:00 New Revision: 912b154f3a3f8c3cebf5cc5731fd8b0749762da5 URL: https://github.com/llvm/llvm-project/commit/912b154f3a3f8c3cebf5cc5731fd8b0749762da5 DIFF: https://github.com/llvm/llvm-project/commit/912b154f3a3f8c3cebf5cc5731fd8b0749762da5.diff LOG: Revert "[C++20][Modules][Serialization] Delay marking pending incompl… (#127136) …ete decl chains until the end of `finishPendingActions`. (#121245)" This reverts commit a9e249f64e800fbb20a3b26c0cfb68c1a1aee5e1. Reverting this change because of issue #126973. Added: Modified: clang/lib/Serialization/ASTReader.cpp Removed: clang/test/Modules/pr121245.cpp diff --git a/clang/lib/Serialization/ASTReader.cpp b/clang/lib/Serialization/ASTReader.cpp index 3c64b67503195..4a40df6399f64 100644 --- a/clang/lib/Serialization/ASTReader.cpp +++ b/clang/lib/Serialization/ASTReader.cpp @@ -10188,12 +10188,12 @@ void ASTReader::visitTopLevelModuleMaps( } void ASTReader::finishPendingActions() { - while (!PendingIdentifierInfos.empty() || - !PendingDeducedFunctionTypes.empty() || - !PendingDeducedVarTypes.empty() || !PendingDeclChains.empty() || - !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() || - !PendingUpdateRecords.empty() || - !PendingObjCExtensionIvarRedeclarations.empty()) { + while ( + !PendingIdentifierInfos.empty() || !PendingDeducedFunctionTypes.empty() || + !PendingDeducedVarTypes.empty() || !PendingIncompleteDeclChains.empty() || + !PendingDeclChains.empty() || !PendingMacroIDs.empty() || + !PendingDeclContextInfos.empty() || !PendingUpdateRecords.empty() || + !PendingObjCExtensionIvarRedeclarations.empty()) { // If any identifiers with corresponding top-level declarations have // been loaded, load those declarations now. using TopLevelDeclsMap = @@ -10241,6 +10241,13 @@ void ASTReader::finishPendingActions() { } PendingDeducedVarTypes.clear(); +// For each decl chain that we wanted to complete while deserializing, mark +// it as "still needs to be completed". +for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) { + markIncompleteDeclChain(PendingIncompleteDeclChains[I]); +} +PendingIncompleteDeclChains.clear(); + // Load pending declaration chains. for (unsigned I = 0; I != PendingDeclChains.size(); ++I) loadPendingDeclChain(PendingDeclChains[I].first, @@ -10478,12 +10485,6 @@ void ASTReader::finishPendingActions() { for (auto *ND : PendingMergedDefinitionsToDeduplicate) getContext().deduplicateMergedDefinitonsFor(ND); PendingMergedDefinitionsToDeduplicate.clear(); - - // For each decl chain that we wanted to complete while deserializing, mark - // it as "still needs to be completed". - for (Decl *D : PendingIncompleteDeclChains) -markIncompleteDeclChain(D); - PendingIncompleteDeclChains.clear(); } void ASTReader::diagnoseOdrViolations() { diff --git a/clang/test/Modules/pr121245.cpp b/clang/test/Modules/pr121245.cpp deleted file mode 100644 index 0e276ad0e435d..0 --- a/clang/test/Modules/pr121245.cpp +++ /dev/null @@ -1,93 +0,0 @@ -// If this test fails, it should be investigated under Debug builds. -// Before the PR, this test was encountering an `llvm_unreachable()`. - -// RUN: rm -rf %t -// RUN: mkdir -p %t -// RUN: split-file %s %t -// RUN: cd %t - -// RUN: %clang_cc1 -std=c++20 -emit-header-unit -xc++-user-header %t/hu-01.h \ -// RUN: -fcxx-exceptions -o %t/hu-01.pcm - -// RUN: %clang_cc1 -std=c++20 -emit-header-unit -xc++-user-header %t/hu-02.h \ -// RUN: -Wno-experimental-header-units -fcxx-exceptions \ -// RUN: -fmodule-file=%t/hu-01.pcm -o %t/hu-02.pcm - -// RUN: %clang_cc1 -std=c++20 -emit-header-unit -xc++-user-header %t/hu-03.h \ -// RUN: -Wno-experimental-header-units -fcxx-exceptions \ -// RUN: -fmodule-file=%t/hu-01.pcm -o %t/hu-03.pcm - -// RUN: %clang_cc1 -std=c++20 -emit-header-unit -xc++-user-header %t/hu-04.h \ -// RUN: -Wno-experimental-header-units -fcxx-exceptions \ -// RUN: -fmodule-file=%t/hu-01.pcm -o %t/hu-04.pcm - -// RUN: %clang_cc1 -std=c++20 -emit-header-unit -xc++-user-header %t/hu-05.h \ -// RUN: -Wno-experimental-header-units -fcxx-exceptions \ -// RUN: -fmodule-file=%t/hu-03.pcm -fmodule-file=%t/hu-04.pcm \ -// RUN: -fmodule-file=%t/hu-01.pcm -o %t/hu-05.pcm - -// RUN: %clang_cc1 -std=c++20 -emit-obj %t/main.cpp \ -// RUN: -Wno-experimental-header-units -fcxx-exceptions \ -// RUN: -fmodule-file=%t/hu-02.pcm -fmodule-file=%t/hu-05.pcm \ -// RUN: -fmodule-file=%t/hu-04.pcm -fmodule-file=%t/hu-03.pcm \ -// RUN: -fmodule-file=%t/hu-01.pcm - -//--- hu-01.h -template -struct A { - A() {} - ~A() {} -}; - -template -struct EBO : T { - EBO() = default; -}; - -template -struct HT : EBO> {}; - -//--- hu-02.h -import "hu-01.h"; - -inline void f() { - HT(); -}
[clang] Revert "[C++20][Modules][Serialization] Delay marking pending incompl… (PR #127136)
https://github.com/zixu-w closed https://github.com/llvm/llvm-project/pull/127136 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [HLSL] Implement HLSL splatting (PR #118992)
https://github.com/spall updated https://github.com/llvm/llvm-project/pull/118992 >From e994824f3630ee8b224afceb6c14d980c9013112 Mon Sep 17 00:00:00 2001 From: Sarah Spall Date: Fri, 6 Dec 2024 05:14:17 + Subject: [PATCH 01/19] splat cast wip --- clang/include/clang/AST/OperationKinds.def | 3 ++ clang/include/clang/Sema/SemaHLSL.h| 1 + clang/lib/CodeGen/CGExprAgg.cpp| 42 ++ clang/lib/CodeGen/CGExprScalar.cpp | 16 + clang/lib/Sema/Sema.cpp| 1 + clang/lib/Sema/SemaCast.cpp| 9 - clang/lib/Sema/SemaHLSL.cpp| 26 ++ 7 files changed, 97 insertions(+), 1 deletion(-) diff --git a/clang/include/clang/AST/OperationKinds.def b/clang/include/clang/AST/OperationKinds.def index b3dc7c3d8dc77..333fc7e1b1882 100644 --- a/clang/include/clang/AST/OperationKinds.def +++ b/clang/include/clang/AST/OperationKinds.def @@ -370,6 +370,9 @@ CAST_OPERATION(HLSLArrayRValue) // Aggregate by Value cast (HLSL only). CAST_OPERATION(HLSLElementwiseCast) +// Splat cast for Aggregates (HLSL only). +CAST_OPERATION(HLSLSplatCast) + //===- Binary Operations -===// // Operators listed in order of precedence. // Note that additions to this should also update the StmtVisitor class, diff --git a/clang/include/clang/Sema/SemaHLSL.h b/clang/include/clang/Sema/SemaHLSL.h index 6e8ca2e4710de..7508b149b0d81 100644 --- a/clang/include/clang/Sema/SemaHLSL.h +++ b/clang/include/clang/Sema/SemaHLSL.h @@ -144,6 +144,7 @@ class SemaHLSL : public SemaBase { bool CanPerformScalarCast(QualType SrcTy, QualType DestTy); bool ContainsBitField(QualType BaseTy); bool CanPerformElementwiseCast(Expr *Src, QualType DestType); + bool CanPerformSplat(Expr *Src, QualType DestType); ExprResult ActOnOutParamExpr(ParmVarDecl *Param, Expr *Arg); QualType getInoutParameterType(QualType Ty); diff --git a/clang/lib/CodeGen/CGExprAgg.cpp b/clang/lib/CodeGen/CGExprAgg.cpp index c3f1cbed6b39f..f26189bc4907c 100644 --- a/clang/lib/CodeGen/CGExprAgg.cpp +++ b/clang/lib/CodeGen/CGExprAgg.cpp @@ -491,6 +491,33 @@ static bool isTrivialFiller(Expr *E) { return false; } +static void EmitHLSLSplatCast(CodeGenFunction &CGF, Address DestVal, + QualType DestTy, llvm::Value *SrcVal, + QualType SrcTy, SourceLocation Loc) { + // Flatten our destination + SmallVector DestTypes; // Flattened type + SmallVector IdxList; + SmallVector, 16> StoreGEPList; + // ^^ Flattened accesses to DestVal we want to store into + CGF.FlattenAccessAndType(DestVal, DestTy, IdxList, StoreGEPList, + DestTypes); + + if (const VectorType *VT = SrcTy->getAs()) { +assert(VT->getNumElements() == 1 && "Invalid HLSL splat cast."); + +SrcTy = VT->getElementType(); +SrcVal = CGF.Builder.CreateExtractElement(SrcVal, (uint64_t)0, + "vec.load"); + } + assert(SrcTy->isScalarType() && "Invalid HLSL splat cast."); + for(unsigned i = 0; i < StoreGEPList.size(); i ++) { +llvm::Value *Cast = CGF.EmitScalarConversion(SrcVal, SrcTy, +DestTypes[i], +Loc); +CGF.PerformStore(StoreGEPList[i], Cast); + } +} + // emit a flat cast where the RHS is a scalar, including vector static void EmitHLSLScalarFlatCast(CodeGenFunction &CGF, Address DestVal, QualType DestTy, llvm::Value *SrcVal, @@ -963,6 +990,21 @@ void AggExprEmitter::VisitCastExpr(CastExpr *E) { case CK_HLSLArrayRValue: Visit(E->getSubExpr()); break; + case CK_HLSLSplatCast: { +Expr *Src = E->getSubExpr(); +QualType SrcTy = Src->getType(); +RValue RV = CGF.EmitAnyExpr(Src); +QualType DestTy = E->getType(); +Address DestVal = Dest.getAddress(); +SourceLocation Loc = E->getExprLoc(); + +if (RV.isScalar()) { + llvm::Value *SrcVal = RV.getScalarVal(); + EmitHLSLSplatCast(CGF, DestVal, DestTy, SrcVal, SrcTy, Loc); + break; +} +llvm_unreachable("RHS of HLSL splat cast must be a scalar or vector."); + } case CK_HLSLElementwiseCast: { Expr *Src = E->getSubExpr(); QualType SrcTy = Src->getType(); diff --git a/clang/lib/CodeGen/CGExprScalar.cpp b/clang/lib/CodeGen/CGExprScalar.cpp index 80daed7e53951..7dc2682bae42f 100644 --- a/clang/lib/CodeGen/CGExprScalar.cpp +++ b/clang/lib/CodeGen/CGExprScalar.cpp @@ -2795,6 +2795,22 @@ Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) { llvm::Value *Zero = llvm::Constant::getNullValue(CGF.SizeTy); return Builder.CreateExtractElement(Vec, Zero, "cast.vtrunc"); } + case CK_HLSLSplatCast: { +assert(DestTy->isVectorType() && "Destination type must be a vector."); +auto *DestVecTy = DestTy->getAs(); +QualType SrcTy = E->getType(); +SourceLocat
[clang] [clang-format] Support BraceWrapping.AfterNamespace with AllowShortNamespacesOnASingleLine (PR #123010)
https://github.com/owenca updated https://github.com/llvm/llvm-project/pull/123010 >From 9d60d4980f1edbdd4cd4a9499f69e9d225717238 Mon Sep 17 00:00:00 2001 From: Galen Elias Date: Tue, 14 Jan 2025 20:44:10 -0800 Subject: [PATCH 1/6] Support BraceWrapping.AfterNamespace with AllowShortNamespacesOnASingleLine AllowShortNamespacesOnASingleLine assumes that there is no newline before the namespace brace, however, there is no actual reason this shouldn't be compatible with BraceWrapping.AfterNamespace = true. This is a little tricky in the implementation because UnwrappedLineFormatter works on lines, so being flexible about the offsets is awkard. Not sure if there is a better pattern for combining the 'AllowShort' options with the various configurations of BraceWrapping, but this seemed mostly reasonable. Really, it would almost be preferable to just pattern match on the direct token stream, rathern than the AnnotatedLines, but I'm not seeing a straightforward way to do that. --- clang/lib/Format/UnwrappedLineFormatter.cpp | 45 + clang/unittests/Format/FormatTest.cpp | 20 + 2 files changed, 49 insertions(+), 16 deletions(-) diff --git a/clang/lib/Format/UnwrappedLineFormatter.cpp b/clang/lib/Format/UnwrappedLineFormatter.cpp index cee84fb1191ab..787136a26b378 100644 --- a/clang/lib/Format/UnwrappedLineFormatter.cpp +++ b/clang/lib/Format/UnwrappedLineFormatter.cpp @@ -367,8 +367,12 @@ class LineJoiner { if (Style.AllowShortNamespacesOnASingleLine && TheLine->First->is(tok::kw_namespace) && -TheLine->Last->is(tok::l_brace)) { - const auto result = tryMergeNamespace(I, E, Limit); +((Style.BraceWrapping.AfterNamespace && + NextLine.First->is(tok::l_brace)) || + (!Style.BraceWrapping.AfterNamespace && + TheLine->Last->is(tok::l_brace { + const auto result = + tryMergeNamespace(I, E, Limit, Style.BraceWrapping.AfterNamespace); if (result > 0) return result; } @@ -628,28 +632,36 @@ class LineJoiner { unsigned tryMergeNamespace(ArrayRef::const_iterator I, ArrayRef::const_iterator E, - unsigned Limit) { + unsigned Limit, bool OpenBraceWrapped) { if (Limit == 0) return 0; -assert(I[1]); -const auto &L1 = *I[1]; +// The merging code is relative to the opening namespace brace, which could +// be either on the first or second line due to the brace wrapping rules. +const size_t OpeningBraceLineOffset = OpenBraceWrapped ? 1 : 0; +const auto BraceOpenLine = I + OpeningBraceLineOffset; + +if (std::distance(BraceOpenLine, E) <= 2) + return 0; + +if (BraceOpenLine[0]->Last->is(TT_LineComment)) + return 0; + +assert(BraceOpenLine[1]); +const auto &L1 = *BraceOpenLine[1]; if (L1.InPPDirective != (*I)->InPPDirective || (L1.InPPDirective && L1.First->HasUnescapedNewline)) { return 0; } -if (std::distance(I, E) <= 2) - return 0; - -assert(I[2]); -const auto &L2 = *I[2]; +assert(BraceOpenLine[2]); +const auto &L2 = *BraceOpenLine[2]; if (L2.Type == LT_Invalid) return 0; Limit = limitConsideringMacros(I + 1, E, Limit); -if (!nextTwoLinesFitInto(I, Limit)) +if (!nextNLinesFitInto(I, I + OpeningBraceLineOffset + 2, Limit)) return 0; // Check if it's a namespace inside a namespace, and call recursively if so. @@ -660,17 +672,18 @@ class LineJoiner { assert(Limit >= L1.Last->TotalLength + 3); const auto InnerLimit = Limit - L1.Last->TotalLength - 3; - const auto MergedLines = tryMergeNamespace(I + 1, E, InnerLimit); + const auto MergedLines = + tryMergeNamespace(BraceOpenLine + 1, E, InnerLimit, OpenBraceWrapped); if (MergedLines == 0) return 0; - const auto N = MergedLines + 2; + const auto N = MergedLines + 2 + OpeningBraceLineOffset; // Check if there is even a line after the inner result. if (std::distance(I, E) <= N) return 0; // Check that the line after the inner result starts with a closing brace // which we are permitted to merge into one line. if (I[N]->First->is(tok::r_brace) && !I[N]->First->MustBreakBefore && - I[MergedLines + 1]->Last->isNot(tok::comment) && + BraceOpenLine[MergedLines + 1]->Last->isNot(tok::comment) && nextNLinesFitInto(I, I + N + 1, Limit)) { return N; } @@ -688,8 +701,8 @@ class LineJoiner { if (L2.First->isNot(tok::r_brace) || L2.First->MustBreakBefore) return 0; -// If so, merge all three lines. -return 2; +// If so, merge all lines. +return 2 + OpeningBraceLineOffset; } unsigned diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp index 4d48bcacddead..bf008e61490f5 100644 --- a/clang/un
[clang] [Feature]: support for the BC library file into the compile dependencies (PR #119513)
https://github.com/zhouronghua updated https://github.com/llvm/llvm-project/pull/119513 >From 3357b98baa4437a915594745ab3d0a6c1bd048f3 Mon Sep 17 00:00:00 2001 From: "ronghua.zhou" Date: Fri, 14 Feb 2025 01:04:51 + Subject: [PATCH] [Feature]: support for the BC library file into the compile dependencies --- clang/lib/Driver/ToolChains/Clang.cpp | 78 - clang/lib/Frontend/CompilerInstance.cpp | 10 +++- 2 files changed, 83 insertions(+), 5 deletions(-) diff --git a/clang/lib/Driver/ToolChains/Clang.cpp b/clang/lib/Driver/ToolChains/Clang.cpp index 55ec3db0ee994..ad106c0097ae7 100644 --- a/clang/lib/Driver/ToolChains/Clang.cpp +++ b/clang/lib/Driver/ToolChains/Clang.cpp @@ -1041,6 +1041,8 @@ void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA, else ArgM = ArgMD; + // Determine the output location. + const char *DepFile = nullptr; if (ArgM) { if (!JA.isDeviceOffloading(Action::OFK_HIP)) { // Determine the output location. @@ -1056,8 +1058,44 @@ void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA, DepFile = getDependencyFileName(Args, Inputs); C.addFailureResultFile(DepFile, &JA); } - CmdArgs.push_back("-dependency-file"); - CmdArgs.push_back(DepFile); + // mv to triple select + // CmdArgs.push_back("-dependency-file"); + // CmdArgs.push_back(DepFile); + + if (getToolChain().getTriple().isNVPTX() || + getToolChain().getTriple().isAMDGCN()) { +// When we set(CMAKE_DEPFILE_FLAGS_${lang} "-MD -MT -MF +// .host") in cmake during heterogeneous compilation, +// we really gererate *.d.host (for host) and *.d (for GPU target), +// the content of *.d = *.d.host + builtin.bc (i.e. libdevice.10.bc or +// some +// files in --hip-device-lib) +// so when libdevice.10.bc or hip-device-lib is updated, the incremental +// build rule will be triggered. +if (DepFile) { + SmallString<128> NewDepFile(DepFile); + llvm::StringRef SubStr = ".host"; + size_t Pos = NewDepFile.find(SubStr); + CmdArgs.push_back("-dependency-file"); + // for tops target, trim .host in dep file + if (Pos != llvm::StringRef::npos) { +// erase substr +auto ndf = NewDepFile.substr(0, Pos); +CmdArgs.push_back(Args.MakeArgString(ndf)); + } else { +// if not set dep file with .host extend, remain depfile not touched +CmdArgs.push_back(Args.MakeArgString(DepFile)); + } +} + } + // Host side remain depfile not touched + else { +// for host compile, we generate orginal dep file +if (DepFile) { + CmdArgs.push_back("-dependency-file"); + CmdArgs.push_back(DepFile); +} + } } bool HasTarget = false; @@ -1149,6 +1187,41 @@ void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA, CmdArgs.push_back("__clang_openmp_device_functions.h"); } + if (getToolChain().getTriple().isNVPTX() || + getToolChain().getTriple().isAMDGCN()) { +// When we set(CMAKE_DEPFILE_FLAGS_${lang} "-MD -MT -MF +// .host") in cmake during heterogeneous compilation, +// we really gererate *.d.host (for host) and *.d (for GPU target), +// the content of *.d = *.d.host + builtin.bc (i.e. libdevice.10.bc or some +// files in --hip-device-lib) +// so when libdevice.10.bc or hip-device-lib is updated, the incremental +// build rule will be triggered. +if (DepFile) { + SmallString<128> NewDepFile(DepFile); + llvm::StringRef SubStr = ".host"; + size_t Pos = NewDepFile.find(SubStr); + CmdArgs.push_back("-dependency-file"); + // for tops target, trim .host in dep file + if (Pos != llvm::StringRef::npos) { +// erase substr +auto ndf = NewDepFile.substr(0, Pos); +CmdArgs.push_back(Args.MakeArgString(ndf)); + } else { +// if not set dep file with .host extend, remain depfile not touched +CmdArgs.push_back(Args.MakeArgString(DepFile)); + } +} + } + // Host side remain depfile not touched + else { +// for host compile, we generate orginal dep file +if (DepFile) { + CmdArgs.push_back("-dependency-file"); + CmdArgs.push_back(DepFile); +} +GenerateHostCompilationDeviceArchMacro(Args, CmdArgs); + } + if (Args.hasArg(options::OPT_foffload_via_llvm)) { // Add llvm_wrappers/* to our system include path. This lets us wrap // standard library headers and other headers. @@ -1159,7 +1232,6 @@ void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA, CmdArgs.push_back("__llvm_offload_device.h"); else CmdArgs.push_back("__llvm_offload_host.h"); - } // Add -i* options, and automatically translate to // -include-pch/-include-pth for transp
[clang] [llvm] [AArch64] Add aliases for processors apple-a18/s6..10. (PR #127152)
https://github.com/ahmedbougacha created https://github.com/llvm/llvm-project/pull/127152 apple-a18 is an alias of apple-m4. apple-s6/s7/s8 are aliases of apple-a13. apple-s9/s10 are aliases of apple-a16. As with some other aliases today, this reflects identical ISA feature support, but not necessarily identical microarchitectures and performance characteristics. >From 46d4b1b52bd7a41ef263a3bebe5d2a6a3c4e5cdc Mon Sep 17 00:00:00 2001 From: Ahmed Bougacha Date: Thu, 2 Jan 2025 14:40:37 -0800 Subject: [PATCH] [AArch64] Add aliases for processors apple-a18/s6..10. apple-a18 is an alias of apple-m4. apple-s6/s7/s8 are aliases of apple-a13. apple-s9/s10 are aliases of apple-a16. As with other aliases, this reflects identical ISA feature support, but not necessarily identical microarchitectures and performance characteristics. --- clang/test/Driver/print-supported-cpus-aarch64.c | 6 ++ clang/test/Misc/target-invalid-cpu-note/aarch64.c | 6 ++ llvm/lib/Target/AArch64/AArch64Processors.td | 6 ++ llvm/unittests/TargetParser/TargetParserTest.cpp | 14 -- 4 files changed, 30 insertions(+), 2 deletions(-) diff --git a/clang/test/Driver/print-supported-cpus-aarch64.c b/clang/test/Driver/print-supported-cpus-aarch64.c index 3c1dcebf7c6c8..3a0ccaf015428 100644 --- a/clang/test/Driver/print-supported-cpus-aarch64.c +++ b/clang/test/Driver/print-supported-cpus-aarch64.c @@ -14,6 +14,7 @@ // CHECK: apple-a15 // CHECK: apple-a16 // CHECK: apple-a17 +// CHECK: apple-a18 // CHECK: apple-a7 // CHECK: apple-a8 // CHECK: apple-a9 @@ -21,7 +22,12 @@ // CHECK: apple-m2 // CHECK: apple-m3 // CHECK: apple-m4 +// CHECK: apple-s10 // CHECK: apple-s4 // CHECK: apple-s5 +// CHECK: apple-s6 +// CHECK: apple-s7 +// CHECK: apple-s8 +// CHECK: apple-s9 // CHECK: Use -mcpu or -mtune to specify the target's processor. diff --git a/clang/test/Misc/target-invalid-cpu-note/aarch64.c b/clang/test/Misc/target-invalid-cpu-note/aarch64.c index e6ff09557fe07..98a2ca0447bcf 100644 --- a/clang/test/Misc/target-invalid-cpu-note/aarch64.c +++ b/clang/test/Misc/target-invalid-cpu-note/aarch64.c @@ -19,6 +19,7 @@ // CHECK-SAME: {{^}}, apple-a15 // CHECK-SAME: {{^}}, apple-a16 // CHECK-SAME: {{^}}, apple-a17 +// CHECK-SAME: {{^}}, apple-a18 // CHECK-SAME: {{^}}, apple-a7 // CHECK-SAME: {{^}}, apple-a8 // CHECK-SAME: {{^}}, apple-a9 @@ -26,8 +27,13 @@ // CHECK-SAME: {{^}}, apple-m2 // CHECK-SAME: {{^}}, apple-m3 // CHECK-SAME: {{^}}, apple-m4 +// CHECK-SAME: {{^}}, apple-s10 // CHECK-SAME: {{^}}, apple-s4 // CHECK-SAME: {{^}}, apple-s5 +// CHECK-SAME: {{^}}, apple-s6 +// CHECK-SAME: {{^}}, apple-s7 +// CHECK-SAME: {{^}}, apple-s8 +// CHECK-SAME: {{^}}, apple-s9 // CHECK-SAME: {{^}}, carmel // CHECK-SAME: {{^}}, cobalt-100 // CHECK-SAME: {{^}}, cortex-a34 diff --git a/llvm/lib/Target/AArch64/AArch64Processors.td b/llvm/lib/Target/AArch64/AArch64Processors.td index d1d4986d12550..b977b6aaaf619 100644 --- a/llvm/lib/Target/AArch64/AArch64Processors.td +++ b/llvm/lib/Target/AArch64/AArch64Processors.td @@ -1224,6 +1224,9 @@ def : ProcessorAlias<"apple-s5", "apple-a12">; def : ProcessorModel<"apple-a13", CycloneModel, ProcessorFeatures.AppleA13, [TuneAppleA13]>; +def : ProcessorAlias<"apple-s6", "apple-a13">; +def : ProcessorAlias<"apple-s7", "apple-a13">; +def : ProcessorAlias<"apple-s8", "apple-a13">; def : ProcessorModel<"apple-a14", CycloneModel, ProcessorFeatures.AppleA14, [TuneAppleA14]>; @@ -1236,12 +1239,15 @@ def : ProcessorAlias<"apple-m2", "apple-a15">; def : ProcessorModel<"apple-a16", CycloneModel, ProcessorFeatures.AppleA16, [TuneAppleA16]>; def : ProcessorAlias<"apple-m3", "apple-a16">; +def : ProcessorAlias<"apple-s9", "apple-a16">; +def : ProcessorAlias<"apple-s10", "apple-a16">; def : ProcessorModel<"apple-a17", CycloneModel, ProcessorFeatures.AppleA17, [TuneAppleA17]>; def : ProcessorModel<"apple-m4", CycloneModel, ProcessorFeatures.AppleM4, [TuneAppleM4]>; +def : ProcessorAlias<"apple-a18", "apple-m4">; // Alias for the latest Apple processor model supported by LLVM. def : ProcessorAlias<"apple-latest", "apple-m4">; diff --git a/llvm/unittests/TargetParser/TargetParserTest.cpp b/llvm/unittests/TargetParser/TargetParserTest.cpp index 7fee62721e6e0..93ac7381b02ef 100644 --- a/llvm/unittests/TargetParser/TargetParserTest.cpp +++ b/llvm/unittests/TargetParser/TargetParserTest.cpp @@ -1130,14 +1130,20 @@ INSTANTIATE_TEST_SUITE_P( AArch64CPUTestParams("apple-s4", "armv8.3-a"), AArch64CPUTestParams("apple-s5", "armv8.3-a"), AArch64CPUTestParams("apple-a13", "armv8.4-a"), + AArch64CPUTestParams("apple-s6", "armv8.4-a"), + AArch64CPUTestParams("apple-s7", "armv8.4-a"), + AArch64CPUTestParams("apple-s8", "armv8.4-a"),
[clang] [llvm] [AArch64] Add aliases for processors apple-a18/s6..10. (PR #127152)
llvmbot wrote: @llvm/pr-subscribers-clang-driver @llvm/pr-subscribers-clang Author: Ahmed Bougacha (ahmedbougacha) Changes apple-a18 is an alias of apple-m4. apple-s6/s7/s8 are aliases of apple-a13. apple-s9/s10 are aliases of apple-a16. As with some other aliases today, this reflects identical ISA feature support, but not necessarily identical microarchitectures and performance characteristics. --- Full diff: https://github.com/llvm/llvm-project/pull/127152.diff 4 Files Affected: - (modified) clang/test/Driver/print-supported-cpus-aarch64.c (+6) - (modified) clang/test/Misc/target-invalid-cpu-note/aarch64.c (+6) - (modified) llvm/lib/Target/AArch64/AArch64Processors.td (+6) - (modified) llvm/unittests/TargetParser/TargetParserTest.cpp (+12-2) ``diff diff --git a/clang/test/Driver/print-supported-cpus-aarch64.c b/clang/test/Driver/print-supported-cpus-aarch64.c index 3c1dcebf7c6c8..3a0ccaf015428 100644 --- a/clang/test/Driver/print-supported-cpus-aarch64.c +++ b/clang/test/Driver/print-supported-cpus-aarch64.c @@ -14,6 +14,7 @@ // CHECK: apple-a15 // CHECK: apple-a16 // CHECK: apple-a17 +// CHECK: apple-a18 // CHECK: apple-a7 // CHECK: apple-a8 // CHECK: apple-a9 @@ -21,7 +22,12 @@ // CHECK: apple-m2 // CHECK: apple-m3 // CHECK: apple-m4 +// CHECK: apple-s10 // CHECK: apple-s4 // CHECK: apple-s5 +// CHECK: apple-s6 +// CHECK: apple-s7 +// CHECK: apple-s8 +// CHECK: apple-s9 // CHECK: Use -mcpu or -mtune to specify the target's processor. diff --git a/clang/test/Misc/target-invalid-cpu-note/aarch64.c b/clang/test/Misc/target-invalid-cpu-note/aarch64.c index e6ff09557fe07..98a2ca0447bcf 100644 --- a/clang/test/Misc/target-invalid-cpu-note/aarch64.c +++ b/clang/test/Misc/target-invalid-cpu-note/aarch64.c @@ -19,6 +19,7 @@ // CHECK-SAME: {{^}}, apple-a15 // CHECK-SAME: {{^}}, apple-a16 // CHECK-SAME: {{^}}, apple-a17 +// CHECK-SAME: {{^}}, apple-a18 // CHECK-SAME: {{^}}, apple-a7 // CHECK-SAME: {{^}}, apple-a8 // CHECK-SAME: {{^}}, apple-a9 @@ -26,8 +27,13 @@ // CHECK-SAME: {{^}}, apple-m2 // CHECK-SAME: {{^}}, apple-m3 // CHECK-SAME: {{^}}, apple-m4 +// CHECK-SAME: {{^}}, apple-s10 // CHECK-SAME: {{^}}, apple-s4 // CHECK-SAME: {{^}}, apple-s5 +// CHECK-SAME: {{^}}, apple-s6 +// CHECK-SAME: {{^}}, apple-s7 +// CHECK-SAME: {{^}}, apple-s8 +// CHECK-SAME: {{^}}, apple-s9 // CHECK-SAME: {{^}}, carmel // CHECK-SAME: {{^}}, cobalt-100 // CHECK-SAME: {{^}}, cortex-a34 diff --git a/llvm/lib/Target/AArch64/AArch64Processors.td b/llvm/lib/Target/AArch64/AArch64Processors.td index d1d4986d12550..b977b6aaaf619 100644 --- a/llvm/lib/Target/AArch64/AArch64Processors.td +++ b/llvm/lib/Target/AArch64/AArch64Processors.td @@ -1224,6 +1224,9 @@ def : ProcessorAlias<"apple-s5", "apple-a12">; def : ProcessorModel<"apple-a13", CycloneModel, ProcessorFeatures.AppleA13, [TuneAppleA13]>; +def : ProcessorAlias<"apple-s6", "apple-a13">; +def : ProcessorAlias<"apple-s7", "apple-a13">; +def : ProcessorAlias<"apple-s8", "apple-a13">; def : ProcessorModel<"apple-a14", CycloneModel, ProcessorFeatures.AppleA14, [TuneAppleA14]>; @@ -1236,12 +1239,15 @@ def : ProcessorAlias<"apple-m2", "apple-a15">; def : ProcessorModel<"apple-a16", CycloneModel, ProcessorFeatures.AppleA16, [TuneAppleA16]>; def : ProcessorAlias<"apple-m3", "apple-a16">; +def : ProcessorAlias<"apple-s9", "apple-a16">; +def : ProcessorAlias<"apple-s10", "apple-a16">; def : ProcessorModel<"apple-a17", CycloneModel, ProcessorFeatures.AppleA17, [TuneAppleA17]>; def : ProcessorModel<"apple-m4", CycloneModel, ProcessorFeatures.AppleM4, [TuneAppleM4]>; +def : ProcessorAlias<"apple-a18", "apple-m4">; // Alias for the latest Apple processor model supported by LLVM. def : ProcessorAlias<"apple-latest", "apple-m4">; diff --git a/llvm/unittests/TargetParser/TargetParserTest.cpp b/llvm/unittests/TargetParser/TargetParserTest.cpp index 7fee62721e6e0..93ac7381b02ef 100644 --- a/llvm/unittests/TargetParser/TargetParserTest.cpp +++ b/llvm/unittests/TargetParser/TargetParserTest.cpp @@ -1130,14 +1130,20 @@ INSTANTIATE_TEST_SUITE_P( AArch64CPUTestParams("apple-s4", "armv8.3-a"), AArch64CPUTestParams("apple-s5", "armv8.3-a"), AArch64CPUTestParams("apple-a13", "armv8.4-a"), + AArch64CPUTestParams("apple-s6", "armv8.4-a"), + AArch64CPUTestParams("apple-s7", "armv8.4-a"), + AArch64CPUTestParams("apple-s8", "armv8.4-a"), AArch64CPUTestParams("apple-a14", "armv8.4-a"), AArch64CPUTestParams("apple-m1", "armv8.4-a"), AArch64CPUTestParams("apple-a15", "armv8.6-a"), AArch64CPUTestParams("apple-m2", "armv8.6-a"), AArch64CPUTestParams("apple-a16", "armv8.6-a"),
[clang] [llvm] [AArch64] Add aliases for processors apple-a18/s6..10. (PR #127152)
llvmbot wrote: @llvm/pr-subscribers-backend-aarch64 Author: Ahmed Bougacha (ahmedbougacha) Changes apple-a18 is an alias of apple-m4. apple-s6/s7/s8 are aliases of apple-a13. apple-s9/s10 are aliases of apple-a16. As with some other aliases today, this reflects identical ISA feature support, but not necessarily identical microarchitectures and performance characteristics. --- Full diff: https://github.com/llvm/llvm-project/pull/127152.diff 4 Files Affected: - (modified) clang/test/Driver/print-supported-cpus-aarch64.c (+6) - (modified) clang/test/Misc/target-invalid-cpu-note/aarch64.c (+6) - (modified) llvm/lib/Target/AArch64/AArch64Processors.td (+6) - (modified) llvm/unittests/TargetParser/TargetParserTest.cpp (+12-2) ``diff diff --git a/clang/test/Driver/print-supported-cpus-aarch64.c b/clang/test/Driver/print-supported-cpus-aarch64.c index 3c1dcebf7c6c8..3a0ccaf015428 100644 --- a/clang/test/Driver/print-supported-cpus-aarch64.c +++ b/clang/test/Driver/print-supported-cpus-aarch64.c @@ -14,6 +14,7 @@ // CHECK: apple-a15 // CHECK: apple-a16 // CHECK: apple-a17 +// CHECK: apple-a18 // CHECK: apple-a7 // CHECK: apple-a8 // CHECK: apple-a9 @@ -21,7 +22,12 @@ // CHECK: apple-m2 // CHECK: apple-m3 // CHECK: apple-m4 +// CHECK: apple-s10 // CHECK: apple-s4 // CHECK: apple-s5 +// CHECK: apple-s6 +// CHECK: apple-s7 +// CHECK: apple-s8 +// CHECK: apple-s9 // CHECK: Use -mcpu or -mtune to specify the target's processor. diff --git a/clang/test/Misc/target-invalid-cpu-note/aarch64.c b/clang/test/Misc/target-invalid-cpu-note/aarch64.c index e6ff09557fe07..98a2ca0447bcf 100644 --- a/clang/test/Misc/target-invalid-cpu-note/aarch64.c +++ b/clang/test/Misc/target-invalid-cpu-note/aarch64.c @@ -19,6 +19,7 @@ // CHECK-SAME: {{^}}, apple-a15 // CHECK-SAME: {{^}}, apple-a16 // CHECK-SAME: {{^}}, apple-a17 +// CHECK-SAME: {{^}}, apple-a18 // CHECK-SAME: {{^}}, apple-a7 // CHECK-SAME: {{^}}, apple-a8 // CHECK-SAME: {{^}}, apple-a9 @@ -26,8 +27,13 @@ // CHECK-SAME: {{^}}, apple-m2 // CHECK-SAME: {{^}}, apple-m3 // CHECK-SAME: {{^}}, apple-m4 +// CHECK-SAME: {{^}}, apple-s10 // CHECK-SAME: {{^}}, apple-s4 // CHECK-SAME: {{^}}, apple-s5 +// CHECK-SAME: {{^}}, apple-s6 +// CHECK-SAME: {{^}}, apple-s7 +// CHECK-SAME: {{^}}, apple-s8 +// CHECK-SAME: {{^}}, apple-s9 // CHECK-SAME: {{^}}, carmel // CHECK-SAME: {{^}}, cobalt-100 // CHECK-SAME: {{^}}, cortex-a34 diff --git a/llvm/lib/Target/AArch64/AArch64Processors.td b/llvm/lib/Target/AArch64/AArch64Processors.td index d1d4986d12550..b977b6aaaf619 100644 --- a/llvm/lib/Target/AArch64/AArch64Processors.td +++ b/llvm/lib/Target/AArch64/AArch64Processors.td @@ -1224,6 +1224,9 @@ def : ProcessorAlias<"apple-s5", "apple-a12">; def : ProcessorModel<"apple-a13", CycloneModel, ProcessorFeatures.AppleA13, [TuneAppleA13]>; +def : ProcessorAlias<"apple-s6", "apple-a13">; +def : ProcessorAlias<"apple-s7", "apple-a13">; +def : ProcessorAlias<"apple-s8", "apple-a13">; def : ProcessorModel<"apple-a14", CycloneModel, ProcessorFeatures.AppleA14, [TuneAppleA14]>; @@ -1236,12 +1239,15 @@ def : ProcessorAlias<"apple-m2", "apple-a15">; def : ProcessorModel<"apple-a16", CycloneModel, ProcessorFeatures.AppleA16, [TuneAppleA16]>; def : ProcessorAlias<"apple-m3", "apple-a16">; +def : ProcessorAlias<"apple-s9", "apple-a16">; +def : ProcessorAlias<"apple-s10", "apple-a16">; def : ProcessorModel<"apple-a17", CycloneModel, ProcessorFeatures.AppleA17, [TuneAppleA17]>; def : ProcessorModel<"apple-m4", CycloneModel, ProcessorFeatures.AppleM4, [TuneAppleM4]>; +def : ProcessorAlias<"apple-a18", "apple-m4">; // Alias for the latest Apple processor model supported by LLVM. def : ProcessorAlias<"apple-latest", "apple-m4">; diff --git a/llvm/unittests/TargetParser/TargetParserTest.cpp b/llvm/unittests/TargetParser/TargetParserTest.cpp index 7fee62721e6e0..93ac7381b02ef 100644 --- a/llvm/unittests/TargetParser/TargetParserTest.cpp +++ b/llvm/unittests/TargetParser/TargetParserTest.cpp @@ -1130,14 +1130,20 @@ INSTANTIATE_TEST_SUITE_P( AArch64CPUTestParams("apple-s4", "armv8.3-a"), AArch64CPUTestParams("apple-s5", "armv8.3-a"), AArch64CPUTestParams("apple-a13", "armv8.4-a"), + AArch64CPUTestParams("apple-s6", "armv8.4-a"), + AArch64CPUTestParams("apple-s7", "armv8.4-a"), + AArch64CPUTestParams("apple-s8", "armv8.4-a"), AArch64CPUTestParams("apple-a14", "armv8.4-a"), AArch64CPUTestParams("apple-m1", "armv8.4-a"), AArch64CPUTestParams("apple-a15", "armv8.6-a"), AArch64CPUTestParams("apple-m2", "armv8.6-a"), AArch64CPUTestParams("apple-a16", "armv8.6-a"), AArch64CPUTestPara
[clang] Revert "[C++20][Modules][Serialization] Delay marking pending incompl… (PR #127136)
llvm-ci wrote: LLVM Buildbot has detected a new failure on builder `sanitizer-x86_64-linux-bootstrap-asan` running on `sanitizer-buildbot2` while building `clang` at step 2 "annotate". Full details are available at: https://lab.llvm.org/buildbot/#/builders/52/builds/5987 Here is the relevant piece of the build log for the reference ``` Step 2 (annotate) failure: 'python ../sanitizer_buildbot/sanitizers/zorg/buildbot/builders/sanitizers/buildbot_selector.py' (failure) ... llvm-lit: /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506: note: using lld-link: /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/lld-link llvm-lit: /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506: note: using ld64.lld: /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/ld64.lld llvm-lit: /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506: note: using wasm-ld: /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/wasm-ld llvm-lit: /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506: note: using ld.lld: /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/ld.lld llvm-lit: /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506: note: using lld-link: /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/lld-link llvm-lit: /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506: note: using ld64.lld: /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/ld64.lld llvm-lit: /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506: note: using wasm-ld: /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/wasm-ld llvm-lit: /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/llvm/utils/lit/lit/main.py:72: note: The test suite configuration requested an individual test timeout of 0 seconds but a timeout of 900 seconds was requested on the command line. Forcing timeout to be 900 seconds. -- Testing: 89040 tests, 88 workers -- Testing: 0.. 10 FAIL: Clang :: Interpreter/inline-virtual.cpp (12711 of 89040) TEST 'Clang :: Interpreter/inline-virtual.cpp' FAILED Exit Code: 1 Command Output (stderr): -- RUN: at line 6: cat /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/clang/test/Interpreter/inline-virtual.cpp | /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/clang-repl -Xcc -fno-rtti -Xcc -fno-sized-deallocation | /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/FileCheck /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/clang/test/Interpreter/inline-virtual.cpp + /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/clang-repl -Xcc -fno-rtti -Xcc -fno-sized-deallocation + cat /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/clang/test/Interpreter/inline-virtual.cpp + /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/FileCheck /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/clang/test/Interpreter/inline-virtual.cpp JIT session error: In graph incr_module_23-jitted-objectbuffer, section .text.startup: relocation target "_ZN1AD2Ev" at address 0x799d12e2f040 is out of range of Delta32 fixup at 0x759d1250f02d ( @ 0x759d1250f010 + 0x1d) error: Failed to materialize symbols: { (main, { a2, __orc_init_func.incr_module_23, $.incr_module_23.__inits.0 }) } error: Failed to materialize symbols: { (main, { __orc_init_func.incr_module_23 }) } /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/clang/test/Interpreter/inline-virtual.cpp:26:11: error: CHECK: expected string not found in input // CHECK: ~A(2) ^ :1:262: note: scanning from here clang-repl> clang-repl> clang-repl> clang-repl> clang-repl> clang-repl> clang-repl... clang-repl> clang-repl... clang-repl> clang-repl> clang-repl> clang-repl> clang-repl> clang-repl> clang-repl> clang-repl> clang-repl> clang-repl> clang-repl> clang-repl> ~A(1) ^ Input file: Check file: /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/clang/test/Interpreter/inline-virtual.cpp -dump-input=help explains the following input dump. Input was: << 1: clang-repl> clang-repl> clang-repl> clang-repl> clang-repl> clang-repl> clang-repl... clang-repl> clang-repl... clang-repl> cl
[clang] [llvm] [ThinLTO] Support dead RTTI data elimination under -fno-split-lto-unit (PR #126336)
@@ -911,6 +916,63 @@ static void setLiveRoot(ModuleSummaryIndex &Index, StringRef Name) { Summary->setLive(true); } +// Return true if the User U is reachable from a non-vtable user +// through the use-def chain. +static bool hasNonVTableUsers(const User *U, CXXABI *ABI) { + LLVM_DEBUG(dbgs() << "Check if " << *U << "has vtable users\n"); + if (isa(U)) { +// If the type info is used in dynamic_cast or exception handling, +// its user must be the instruction. +return true; + } + + // The virtual table type is either a struct of arrays. For example: + // @vtable = constant { [3 x ptr] } { [3 x ptr] [ ptr null, ptr @rtti, ptr @vf] } + // + // In this case, the user of @rtti is an anonymous ConstantArray. + // Therefore, if the user of the type information is anonymous, + // we need to perform a depth-first search (DFS) to locate its named users. + // + // And we also need to iterate its users if the current user is the type + // info global variable itself. + StringRef Name = U->getName(); + if (Name.empty() || ABI->isTypeInfo(Name)) { +for (const User *It : U->users()) + if (hasNonVTableUsers(It, ABI)) +return true; +return false; + } + + if (!ABI->isVTable(Name)) +return true; + + return false; +} + +static void analyzeRTTIVars(ModuleSummaryIndex &Index, const Module &M) { + Triple TT(M.getTargetTriple()); + + std::unique_ptr ABI = CXXABI::Create(TT); + if (!ABI) +return; + + for (const GlobalVariable &GV : M.globals()) { +if (!ABI->isTypeInfo(GV.getName())) + continue; + +if (hasNonVTableUsers(&GV, ABI.get())) { + std::string TypeName = + ABI->getTypeNameFromTypeInfo(GV.getName()); luxufan wrote: If I use a hardcoded approach in this patch, there will be multiple places where this kind of hardcoding is needed, which, in my opinion, would make the code less maintainable and harder to read. What do you think? https://github.com/llvm/llvm-project/pull/126336 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 083f099 - [clang-format] Support BraceWrapping.AfterNamespace with AllowShortNamespacesOnASingleLine (#123010)
Author: Galen Elias Date: 2025-02-13T20:14:39-08:00 New Revision: 083f099a345f02390d00a8196d4ffa36ae71c82f URL: https://github.com/llvm/llvm-project/commit/083f099a345f02390d00a8196d4ffa36ae71c82f DIFF: https://github.com/llvm/llvm-project/commit/083f099a345f02390d00a8196d4ffa36ae71c82f.diff LOG: [clang-format] Support BraceWrapping.AfterNamespace with AllowShortNamespacesOnASingleLine (#123010) AllowShortNamespacesOnASingleLine assumes that there is no newline before the namespace brace, however, there is no actual reason this shouldn't be compatible with BraceWrapping.AfterNamespace = true. This is a little tricky in the implementation because UnwrappedLineFormatter works on lines, so being flexible about the offsets is awkward. Not sure if there is a better pattern for combining the 'AllowShort' options with the various configurations of BraceWrapping, but this seemed mostly reasonable. Really, it would almost be preferable to just pattern match on the direct token stream, rather than the AnnotatedLines, but I'm not seeing a straightforward way to do that. - Co-authored-by: Owen Pan Added: Modified: clang/lib/Format/UnwrappedLineFormatter.cpp clang/unittests/Format/FormatTest.cpp Removed: diff --git a/clang/lib/Format/UnwrappedLineFormatter.cpp b/clang/lib/Format/UnwrappedLineFormatter.cpp index a5b30c85974c7..dd667a9944515 100644 --- a/clang/lib/Format/UnwrappedLineFormatter.cpp +++ b/clang/lib/Format/UnwrappedLineFormatter.cpp @@ -366,8 +366,7 @@ class LineJoiner { // instead of TheLine->First. if (Style.AllowShortNamespacesOnASingleLine && -TheLine->First->is(tok::kw_namespace) && -TheLine->Last->is(tok::l_brace)) { +TheLine->First->is(tok::kw_namespace)) { const auto result = tryMergeNamespace(I, E, Limit); if (result > 0) return result; @@ -633,24 +632,37 @@ class LineJoiner { if (Limit == 0) return 0; -assert(I[1]); -const auto &L1 = *I[1]; +// The merging code is relative to the opening namespace brace, which could +// be either on the first or second line due to the brace wrapping rules. +const bool OpenBraceWrapped = Style.BraceWrapping.AfterNamespace; +const auto *BraceOpenLine = I + OpenBraceWrapped; + +assert(*BraceOpenLine); +if (BraceOpenLine[0]->Last->isNot(TT_NamespaceLBrace)) + return 0; + +if (std::distance(BraceOpenLine, E) <= 2) + return 0; + +if (BraceOpenLine[0]->Last->is(tok::comment)) + return 0; + +assert(BraceOpenLine[1]); +const auto &L1 = *BraceOpenLine[1]; if (L1.InPPDirective != (*I)->InPPDirective || (L1.InPPDirective && L1.First->HasUnescapedNewline)) { return 0; } -if (std::distance(I, E) <= 2) - return 0; - -assert(I[2]); -const auto &L2 = *I[2]; +assert(BraceOpenLine[2]); +const auto &L2 = *BraceOpenLine[2]; if (L2.Type == LT_Invalid) return 0; Limit = limitConsideringMacros(I + 1, E, Limit); -if (!nextTwoLinesFitInto(I, Limit)) +const auto LinesToBeMerged = OpenBraceWrapped + 2; +if (!nextNLinesFitInto(I, I + LinesToBeMerged, Limit)) return 0; // Check if it's a namespace inside a namespace, and call recursively if so. @@ -661,17 +673,19 @@ class LineJoiner { assert(Limit >= L1.Last->TotalLength + 3); const auto InnerLimit = Limit - L1.Last->TotalLength - 3; - const auto MergedLines = tryMergeNamespace(I + 1, E, InnerLimit); + const auto MergedLines = + tryMergeNamespace(BraceOpenLine + 1, E, InnerLimit); if (MergedLines == 0) return 0; - const auto N = MergedLines + 2; + const auto N = MergedLines + LinesToBeMerged; // Check if there is even a line after the inner result. if (std::distance(I, E) <= N) return 0; // Check that the line after the inner result starts with a closing brace // which we are permitted to merge into one line. - if (I[N]->First->is(tok::r_brace) && !I[N]->First->MustBreakBefore && - I[MergedLines + 1]->Last->isNot(tok::comment) && + if (I[N]->First->is(TT_NamespaceRBrace) && + !I[N]->First->MustBreakBefore && + BraceOpenLine[MergedLines + 1]->Last->isNot(tok::comment) && nextNLinesFitInto(I, I + N + 1, Limit)) { return N; } @@ -686,11 +700,11 @@ class LineJoiner { return 0; // Last, check that the third line starts with a closing brace. -if (L2.First->isNot(tok::r_brace) || L2.First->MustBreakBefore) +if (L2.First->isNot(TT_NamespaceRBrace) || L2.First->MustBreakBefore) return 0; -// If so, merge all three lines. -return 2; +// If so, merge all lines. +return LinesToBeMerged; } unsigned diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTe
[clang] [clang-format] Support BraceWrapping.AfterNamespace with AllowShortNamespacesOnASingleLine (PR #123010)
https://github.com/owenca closed https://github.com/llvm/llvm-project/pull/123010 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [llvm:ir] Add support for constant data exceeding 4GiB (PR #126481)
https://github.com/pzzp updated https://github.com/llvm/llvm-project/pull/126481 >From a1d2d3538d44a0740dc24ed81e9d4bf6e7ed0524 Mon Sep 17 00:00:00 2001 From: zhoupeng12 Date: Mon, 30 Oct 2023 18:13:07 +0800 Subject: [PATCH] [llvm:ir] Add support for constant data exceeding 4GiB --- clang/lib/CodeGen/CGExprConstant.cpp | 8 llvm/include/llvm/IR/Constants.h | 8 llvm/lib/Bitcode/Writer/BitcodeWriter.cpp| 8 llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp | 6 +++--- llvm/lib/IR/Constants.cpp| 13 ++--- llvm/lib/Target/TargetLoweringObjectFile.cpp | 4 ++-- llvm/lib/Target/X86/X86MCInstLower.cpp | 2 +- 7 files changed, 24 insertions(+), 25 deletions(-) diff --git a/clang/lib/CodeGen/CGExprConstant.cpp b/clang/lib/CodeGen/CGExprConstant.cpp index ef11798869d3b..b0ff6fae65f16 100644 --- a/clang/lib/CodeGen/CGExprConstant.cpp +++ b/clang/lib/CodeGen/CGExprConstant.cpp @@ -364,14 +364,14 @@ bool ConstantAggregateBuilder::split(size_t Index, CharUnits Hint) { // FIXME: If possible, split into two ConstantDataSequentials at Hint. CharUnits ElemSize = getSize(CDS->getElementType()); replace(Elems, Index, Index + 1, -llvm::map_range(llvm::seq(0u, CDS->getNumElements()), -[&](unsigned Elem) { +llvm::map_range(llvm::seq(uint64_t(0u), CDS->getNumElements()), +[&](uint64_t Elem) { return CDS->getElementAsConstant(Elem); })); replace(Offsets, Index, Index + 1, llvm::map_range( -llvm::seq(0u, CDS->getNumElements()), -[&](unsigned Elem) { return Offset + Elem * ElemSize; })); +llvm::seq(uint64_t(0u), CDS->getNumElements()), +[&](uint64_t Elem) { return Offset + Elem * ElemSize; })); return true; } diff --git a/llvm/include/llvm/IR/Constants.h b/llvm/include/llvm/IR/Constants.h index 15b90589b7e2b..769ac821d1bd3 100644 --- a/llvm/include/llvm/IR/Constants.h +++ b/llvm/include/llvm/IR/Constants.h @@ -617,7 +617,7 @@ class ConstantDataSequential : public ConstantData { /// If this is a sequential container of integers (of any size), return the /// specified element in the low bits of a uint64_t. - uint64_t getElementAsInteger(unsigned i) const; + uint64_t getElementAsInteger(uint64_t i) const; /// If this is a sequential container of integers (of any size), return the /// specified element as an APInt. @@ -625,7 +625,7 @@ class ConstantDataSequential : public ConstantData { /// If this is a sequential container of floating point type, return the /// specified element as an APFloat. - APFloat getElementAsAPFloat(unsigned i) const; + APFloat getElementAsAPFloat(uint64_t i) const; /// If this is an sequential container of floats, return the specified element /// as a float. @@ -644,7 +644,7 @@ class ConstantDataSequential : public ConstantData { Type *getElementType() const; /// Return the number of elements in the array or vector. - unsigned getNumElements() const; + uint64_t getNumElements() const; /// Return the size (in bytes) of each element in the array/vector. /// The size of the elements is known to be a multiple of one byte. @@ -684,7 +684,7 @@ class ConstantDataSequential : public ConstantData { } private: - const char *getElementPointer(unsigned Elt) const; + const char *getElementPointer(uint64_t Elt) const; }; //===--===// diff --git a/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp b/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp index 7ca63c2c7251d..c95bfc5cf2415 100644 --- a/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp +++ b/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp @@ -2773,7 +2773,7 @@ void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal, cast(C)->isString()) { const ConstantDataSequential *Str = cast(C); // Emit constant strings specially. - unsigned NumElts = Str->getNumElements(); + uint64_t NumElts = Str->getNumElements(); // If this is a null-terminated string, use the denser CSTRING encoding. if (Str->isCString()) { Code = bitc::CST_CODE_CSTRING; @@ -2784,7 +2784,7 @@ void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal, } bool isCStr7 = Code == bitc::CST_CODE_CSTRING; bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING; - for (unsigned i = 0; i != NumElts; ++i) { + for (uint64_t i = 0; i != NumElts; ++i) { unsigned char V = Str->getElementAsInteger(i); Record.push_back(V); isCStr7 &= (V & 128) == 0; @@ -2801,10 +2801,10 @@ void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal, Code = bitc::CST_CODE_DATA; Type *EltTy = CDS->getElementType();
[clang] Fix amdgpu-arch for dll name on Windows (PR #101350)
@@ -31,16 +44,118 @@ typedef hipError_t (*hipGetDeviceCount_t)(int *); typedef hipError_t (*hipDeviceGet_t)(int *, int); typedef hipError_t (*hipGetDeviceProperties_t)(hipDeviceProp_t *, int); -int printGPUsByHIP() { +extern cl::opt Verbose; + #ifdef _WIN32 - constexpr const char *DynamicHIPPath = "amdhip64.dll"; +static std::vector getSearchPaths() { yxsamliu wrote: We need to find files matching the pattern "amdhip64_*.dll". Unfortunately SearchPathW does not support that. https://github.com/llvm/llvm-project/pull/101350 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [C++20][Modules][Serialization] Delay marking pending incomplete decl chains until the end of `finishPendingActions`. (PR #121245)
ChuanqiXu9 wrote: @zixu-w @mpark given the original patch get backported to the release branch and the patch get reverted, I think we should revert the patch in the release branch too. https://github.com/llvm/llvm-project/pull/121245 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clangd] [C++20] [Modules] Add scanning cache (PR #125988)
https://github.com/ChuanqiXu9 updated https://github.com/llvm/llvm-project/pull/125988 >From 42eb3826ed79de5aabb7f0197cfda2ad62d9735d Mon Sep 17 00:00:00 2001 From: Chuanqi Xu Date: Tue, 11 Feb 2025 11:21:34 +0800 Subject: [PATCH 1/2] [clangd] [C++20] [Modules] Introduce cache for scanning modules --- clang-tools-extra/clangd/ModulesBuilder.cpp | 115 +++--- clang-tools-extra/clangd/ProjectModules.h | 6 +- .../clangd/ScanningProjectModules.cpp | 15 ++- 3 files changed, 112 insertions(+), 24 deletions(-) diff --git a/clang-tools-extra/clangd/ModulesBuilder.cpp b/clang-tools-extra/clangd/ModulesBuilder.cpp index bee31fe51555e..121a4cec4c8c2 100644 --- a/clang-tools-extra/clangd/ModulesBuilder.cpp +++ b/clang-tools-extra/clangd/ModulesBuilder.cpp @@ -360,7 +360,8 @@ void ModuleFileCache::remove(StringRef ModuleName) { /// Collect the directly and indirectly required module names for \param /// ModuleName in topological order. The \param ModuleName is guaranteed to /// be the last element in \param ModuleNames. -llvm::SmallVector getAllRequiredModules(ProjectModules &MDB, +llvm::SmallVector getAllRequiredModules(PathRef RequiredSource, + ProjectModules &MDB, StringRef ModuleName) { llvm::SmallVector ModuleNames; llvm::StringSet<> ModuleNamesSet; @@ -368,8 +369,8 @@ llvm::SmallVector getAllRequiredModules(ProjectModules &MDB, auto VisitDeps = [&](StringRef ModuleName, auto Visitor) -> void { ModuleNamesSet.insert(ModuleName); -for (StringRef RequiredModuleName : - MDB.getRequiredModules(MDB.getSourceForModuleName(ModuleName))) +for (StringRef RequiredModuleName : MDB.getRequiredModules( + MDB.getSourceForModuleName(ModuleName, RequiredSource))) if (ModuleNamesSet.insert(RequiredModuleName).second) Visitor(RequiredModuleName, Visitor); @@ -380,30 +381,114 @@ llvm::SmallVector getAllRequiredModules(ProjectModules &MDB, return ModuleNames; } +class CachingProjectModules : public ProjectModules { +public: + CachingProjectModules(const GlobalCompilationDatabase &CDB) : CDB(CDB) {} + + std::vector getRequiredModules(PathRef File) override { +std::unique_ptr MDB = CDB.getProjectModules(File); +if (!MDB) { + elog("Failed to get Project Modules information for {0}", File); + return {}; +} +return MDB->getRequiredModules(File); + } + + std::string getModuleNameForSource(PathRef File) override { +std::unique_ptr MDB = CDB.getProjectModules(File); +if (!MDB) { + elog("Failed to get Project Modules information for {0}", File); + return {}; +} +return MDB->getModuleNameForSource(File); + } + + void setCommandMangler(CommandMangler M) override { +// GlobalCompilationDatabase::getProjectModules() will set mangler +// for the underlying ProjectModules. + } + + std::string getSourceForModuleName(llvm::StringRef ModuleName, + PathRef RequiredSrcFile) override { +std::string CachedResult; +{ + std::lock_guard Lock(CacheMutex); + auto Iter = ModuleNameToSourceCache.find(ModuleName); + if (Iter != ModuleNameToSourceCache.end()) +CachedResult = Iter->second; +} + +std::unique_ptr MDB = +CDB.getProjectModules(RequiredSrcFile); +if (!MDB) { + elog("Failed to get Project Modules information for {0}", + RequiredSrcFile); + return {}; +} + +// Verify Cached Result by seeing if the source declaring the same module +// as we query. +if (!CachedResult.empty()) { + std::string ModuleNameOfCachedSource = + MDB->getModuleNameForSource(CachedResult); + if (ModuleNameOfCachedSource == ModuleName) +return CachedResult; + else { +// Cached Result is invalid. Clear it. + +std::lock_guard Lock(CacheMutex); +ModuleNameToSourceCache.erase(ModuleName); + } +} + +auto Result = MDB->getSourceForModuleName(ModuleName, RequiredSrcFile); + +{ + std::lock_guard Lock(CacheMutex); + ModuleNameToSourceCache.insert({ModuleName, Result}); +} + +return Result; + } + +private: + const GlobalCompilationDatabase &CDB; + + std::mutex CacheMutex; + llvm::StringMap ModuleNameToSourceCache; +}; + } // namespace class ModulesBuilder::ModulesBuilderImpl { public: - ModulesBuilderImpl(const GlobalCompilationDatabase &CDB) : Cache(CDB) {} + ModulesBuilderImpl(const GlobalCompilationDatabase &CDB) + : CachedProjectModules(CDB), Cache(CDB) {} + + CachingProjectModules &getCachedProjectModules() { +return CachedProjectModules; + } const GlobalCompilationDatabase &getCDB() const { return Cache.getCDB(); } llvm::Error - getOrBuildModuleFile(StringRef ModuleName, const ThreadsafeFS &TFS, - ProjectModules &MDB, + getOrBuildModuleFile(PathRe
[clang] Fix amdgpu-arch for dll name on Windows (PR #101350)
@@ -31,16 +44,118 @@ typedef hipError_t (*hipGetDeviceCount_t)(int *); typedef hipError_t (*hipDeviceGet_t)(int *, int); typedef hipError_t (*hipGetDeviceProperties_t)(hipDeviceProp_t *, int); -int printGPUsByHIP() { +extern cl::opt Verbose; + #ifdef _WIN32 - constexpr const char *DynamicHIPPath = "amdhip64.dll"; +static std::vector getSearchPaths() { + std::vector Paths; + + // Get the directory of the current executable + if (auto MainExe = sys::fs::getMainExecutable(nullptr, nullptr); + !MainExe.empty()) +Paths.push_back(sys::path::parent_path(MainExe).str()); + + // Get the system directory + wchar_t SystemDirectory[MAX_PATH]; + if (GetSystemDirectoryW(SystemDirectory, MAX_PATH) > 0) { +std::string Utf8SystemDir; +if (convertUTF16ToUTF8String( +ArrayRef(reinterpret_cast(SystemDirectory), +wcslen(SystemDirectory)), +Utf8SystemDir)) + Paths.push_back(Utf8SystemDir); + } + + // Get the Windows directory + wchar_t WindowsDirectory[MAX_PATH]; + if (GetWindowsDirectoryW(WindowsDirectory, MAX_PATH) > 0) { +std::string Utf8WindowsDir; +if (convertUTF16ToUTF8String( +ArrayRef(reinterpret_cast(WindowsDirectory), +wcslen(WindowsDirectory)), +Utf8WindowsDir)) + Paths.push_back(Utf8WindowsDir); + } + + // Get the current working directory + SmallVector CWD; + if (sys::fs::current_path(CWD)) +Paths.push_back(std::string(CWD.begin(), CWD.end())); + + // Get the PATH environment variable + if (auto PathEnv = sys::Process::GetEnv("PATH")) { +SmallVector PathList; +StringRef(*PathEnv).split(PathList, sys::EnvPathSeparator); +for (auto &Path : PathList) + Paths.push_back(Path.str()); + } + + return Paths; +} + +// Custom comparison function for dll name +static bool compareVersions(const std::string &a, const std::string &b) { + // Extract version numbers + int versionA = std::stoi(a.substr(a.find_last_of('_') + 1)); + int versionB = std::stoi(b.substr(b.find_last_of('_') + 1)); + return versionA > versionB; +} + +#endif + +// On Windows, prefer amdhip64_n.dll where n is ROCm major version and greater +// value of n takes precedence. If amdhip64_n.dll is not found, fall back to +// amdhip64.dll. The reason is that a normal driver installation only has +// amdhip64_n.dll but we do not know what n is since this progrm may be used +// with a future version of HIP runtime. +// +// On Linux, always use default libamdhip64.so. +static std::pair findNewestHIPDLL() { +#ifdef _WIN32 + StringRef HipDLLPrefix = "amdhip64_"; + StringRef HipDLLSuffix = ".dll"; + + std::vector SearchPaths = getSearchPaths(); + std::vector DLLNames; + + for (const auto &Dir : SearchPaths) { +std::error_code EC; +for (sys::fs::directory_iterator DirIt(Dir, EC), DirEnd; + DirIt != DirEnd && !EC; DirIt.increment(EC)) { + StringRef Filename = sys::path::filename(DirIt->path()); + if (Filename.starts_with(HipDLLPrefix) && + Filename.ends_with(HipDLLSuffix)) +DLLNames.push_back(sys::path::convert_to_slash(DirIt->path())); +} +if (!DLLNames.empty()) + break; + } + + if (DLLNames.empty()) +return {"amdhip64.dll", true}; + + std::sort(DLLNames.begin(), DLLNames.end(), compareVersions); + return {DLLNames[0], false}; #else - constexpr const char *DynamicHIPPath = "libamdhip64.so"; + // On Linux, fallback to default shared object + return {"libamdhip64.so", true}; #endif +} + +int printGPUsByHIP() { + auto [DynamicHIPPath, IsFallback] = findNewestHIPDLL(); + + if (Verbose) { +if (IsFallback) + outs() << "Using default HIP runtime: " << DynamicHIPPath << "\n"; +else + outs() << "Found HIP runtime: " << DynamicHIPPath << "\n"; yxsamliu wrote: will fix https://github.com/llvm/llvm-project/pull/101350 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clangd] [C++20] [Modules] Add scanning cache (PR #125988)
@@ -380,30 +381,114 @@ llvm::SmallVector getAllRequiredModules(ProjectModules &MDB, return ModuleNames; } +class CachingProjectModules : public ProjectModules { +public: + CachingProjectModules(const GlobalCompilationDatabase &CDB) : CDB(CDB) {} + + std::vector getRequiredModules(PathRef File) override { +std::unique_ptr MDB = CDB.getProjectModules(File); +if (!MDB) { + elog("Failed to get Project Modules information for {0}", File); + return {}; +} +return MDB->getRequiredModules(File); + } + + std::string getModuleNameForSource(PathRef File) override { +std::unique_ptr MDB = CDB.getProjectModules(File); +if (!MDB) { + elog("Failed to get Project Modules information for {0}", File); + return {}; +} +return MDB->getModuleNameForSource(File); + } + + void setCommandMangler(CommandMangler M) override { +// GlobalCompilationDatabase::getProjectModules() will set mangler +// for the underlying ProjectModules. + } ChuanqiXu9 wrote: Done https://github.com/llvm/llvm-project/pull/125988 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clangd] [C++20] [Modules] Add scanning cache (PR #125988)
@@ -449,21 +534,17 @@ llvm::Error ModulesBuilder::ModulesBuilderImpl::getOrBuildModuleFile( std::unique_ptr ModulesBuilder::buildPrerequisiteModulesFor(PathRef File, const ThreadsafeFS &TFS) { - std::unique_ptr MDB = Impl->getCDB().getProjectModules(File); - if (!MDB) { -elog("Failed to get Project Modules information for {0}", File); -return std::make_unique(); - } + ProjectModules &MDB = Impl->getCachedProjectModules(); ChuanqiXu9 wrote: Done https://github.com/llvm/llvm-project/pull/125988 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Fix amdgpu-arch for dll name on Windows (PR #101350)
@@ -31,16 +44,118 @@ typedef hipError_t (*hipGetDeviceCount_t)(int *); typedef hipError_t (*hipDeviceGet_t)(int *, int); typedef hipError_t (*hipGetDeviceProperties_t)(hipDeviceProp_t *, int); -int printGPUsByHIP() { +extern cl::opt Verbose; + #ifdef _WIN32 - constexpr const char *DynamicHIPPath = "amdhip64.dll"; +static std::vector getSearchPaths() { + std::vector Paths; + + // Get the directory of the current executable + if (auto MainExe = sys::fs::getMainExecutable(nullptr, nullptr); + !MainExe.empty()) +Paths.push_back(sys::path::parent_path(MainExe).str()); + + // Get the system directory + wchar_t SystemDirectory[MAX_PATH]; + if (GetSystemDirectoryW(SystemDirectory, MAX_PATH) > 0) { +std::string Utf8SystemDir; +if (convertUTF16ToUTF8String( +ArrayRef(reinterpret_cast(SystemDirectory), +wcslen(SystemDirectory)), +Utf8SystemDir)) + Paths.push_back(Utf8SystemDir); + } + + // Get the Windows directory + wchar_t WindowsDirectory[MAX_PATH]; + if (GetWindowsDirectoryW(WindowsDirectory, MAX_PATH) > 0) { +std::string Utf8WindowsDir; +if (convertUTF16ToUTF8String( +ArrayRef(reinterpret_cast(WindowsDirectory), +wcslen(WindowsDirectory)), +Utf8WindowsDir)) + Paths.push_back(Utf8WindowsDir); + } + + // Get the current working directory + SmallVector CWD; + if (sys::fs::current_path(CWD)) +Paths.push_back(std::string(CWD.begin(), CWD.end())); + + // Get the PATH environment variable + if (auto PathEnv = sys::Process::GetEnv("PATH")) { +SmallVector PathList; +StringRef(*PathEnv).split(PathList, sys::EnvPathSeparator); +for (auto &Path : PathList) + Paths.push_back(Path.str()); + } + + return Paths; +} + +// Custom comparison function for dll name +static bool compareVersions(const std::string &a, const std::string &b) { + // Extract version numbers + int versionA = std::stoi(a.substr(a.find_last_of('_') + 1)); + int versionB = std::stoi(b.substr(b.find_last_of('_') + 1)); + return versionA > versionB; +} + +#endif + +// On Windows, prefer amdhip64_n.dll where n is ROCm major version and greater +// value of n takes precedence. If amdhip64_n.dll is not found, fall back to +// amdhip64.dll. The reason is that a normal driver installation only has +// amdhip64_n.dll but we do not know what n is since this progrm may be used yxsamliu wrote: will fix https://github.com/llvm/llvm-project/pull/101350 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Fix amdgpu-arch for dll name on Windows (PR #101350)
@@ -31,16 +44,118 @@ typedef hipError_t (*hipGetDeviceCount_t)(int *); typedef hipError_t (*hipDeviceGet_t)(int *, int); typedef hipError_t (*hipGetDeviceProperties_t)(hipDeviceProp_t *, int); -int printGPUsByHIP() { +extern cl::opt Verbose; + #ifdef _WIN32 - constexpr const char *DynamicHIPPath = "amdhip64.dll"; +static std::vector getSearchPaths() { + std::vector Paths; + + // Get the directory of the current executable + if (auto MainExe = sys::fs::getMainExecutable(nullptr, nullptr); + !MainExe.empty()) +Paths.push_back(sys::path::parent_path(MainExe).str()); + + // Get the system directory + wchar_t SystemDirectory[MAX_PATH]; + if (GetSystemDirectoryW(SystemDirectory, MAX_PATH) > 0) { +std::string Utf8SystemDir; +if (convertUTF16ToUTF8String( +ArrayRef(reinterpret_cast(SystemDirectory), +wcslen(SystemDirectory)), +Utf8SystemDir)) + Paths.push_back(Utf8SystemDir); + } + + // Get the Windows directory + wchar_t WindowsDirectory[MAX_PATH]; + if (GetWindowsDirectoryW(WindowsDirectory, MAX_PATH) > 0) { +std::string Utf8WindowsDir; +if (convertUTF16ToUTF8String( +ArrayRef(reinterpret_cast(WindowsDirectory), +wcslen(WindowsDirectory)), +Utf8WindowsDir)) + Paths.push_back(Utf8WindowsDir); + } + + // Get the current working directory + SmallVector CWD; + if (sys::fs::current_path(CWD)) +Paths.push_back(std::string(CWD.begin(), CWD.end())); + + // Get the PATH environment variable + if (auto PathEnv = sys::Process::GetEnv("PATH")) { yxsamliu wrote: will fix https://github.com/llvm/llvm-project/pull/101350 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Fix amdgpu-arch for dll name on Windows (PR #101350)
https://github.com/yxsamliu updated https://github.com/llvm/llvm-project/pull/101350 >From 649aba6ed5caee1632901238ed932e2c50214df7 Mon Sep 17 00:00:00 2001 From: "Yaxun (Sam) Liu" Date: Wed, 31 Jul 2024 09:23:05 -0400 Subject: [PATCH] Fix amdgpu-arch for dll name on Windows Recently HIP runtime changed dll name to amdhip64_n.dll on Windows, where n is ROCm major version number. Fix amdgpu-arch to search for amdhip64_n.dll on Windows. --- clang/tools/amdgpu-arch/AMDGPUArch.cpp | 3 + clang/tools/amdgpu-arch/AMDGPUArchByHIP.cpp | 123 +++- 2 files changed, 122 insertions(+), 4 deletions(-) diff --git a/clang/tools/amdgpu-arch/AMDGPUArch.cpp b/clang/tools/amdgpu-arch/AMDGPUArch.cpp index 6c10cbc5c46a8..86f3e31f47bbc 100644 --- a/clang/tools/amdgpu-arch/AMDGPUArch.cpp +++ b/clang/tools/amdgpu-arch/AMDGPUArch.cpp @@ -21,6 +21,9 @@ static cl::opt Help("h", cl::desc("Alias for -help"), cl::Hidden); // Mark all our options with this category. static cl::OptionCategory AMDGPUArchCategory("amdgpu-arch options"); +cl::opt Verbose("verbose", cl::desc("Enable verbose output"), + cl::init(false), cl::cat(AMDGPUArchCategory)); + static void PrintVersion(raw_ostream &OS) { OS << clang::getClangToolFullVersion("amdgpu-arch") << '\n'; } diff --git a/clang/tools/amdgpu-arch/AMDGPUArchByHIP.cpp b/clang/tools/amdgpu-arch/AMDGPUArchByHIP.cpp index 7338872dbf32f..49a993b9d8257 100644 --- a/clang/tools/amdgpu-arch/AMDGPUArchByHIP.cpp +++ b/clang/tools/amdgpu-arch/AMDGPUArchByHIP.cpp @@ -11,9 +11,22 @@ // //===--===// +#include "llvm/Support/CommandLine.h" +#include "llvm/Support/ConvertUTF.h" #include "llvm/Support/DynamicLibrary.h" #include "llvm/Support/Error.h" +#include "llvm/Support/FileSystem.h" +#include "llvm/Support/Path.h" +#include "llvm/Support/Process.h" +#include "llvm/Support/Program.h" #include "llvm/Support/raw_ostream.h" +#include +#include +#include + +#ifdef _WIN32 +#include +#endif using namespace llvm; @@ -31,16 +44,118 @@ typedef hipError_t (*hipGetDeviceCount_t)(int *); typedef hipError_t (*hipDeviceGet_t)(int *, int); typedef hipError_t (*hipGetDeviceProperties_t)(hipDeviceProp_t *, int); -int printGPUsByHIP() { +extern cl::opt Verbose; + #ifdef _WIN32 - constexpr const char *DynamicHIPPath = "amdhip64.dll"; +static std::vector getSearchPaths() { + std::vector Paths; + + // Get the directory of the current executable + if (auto MainExe = sys::fs::getMainExecutable(nullptr, nullptr); + !MainExe.empty()) +Paths.push_back(sys::path::parent_path(MainExe).str()); + + // Get the system directory + wchar_t SystemDirectory[MAX_PATH]; + if (GetSystemDirectoryW(SystemDirectory, MAX_PATH) > 0) { +std::string Utf8SystemDir; +if (convertUTF16ToUTF8String( +ArrayRef(reinterpret_cast(SystemDirectory), +wcslen(SystemDirectory)), +Utf8SystemDir)) + Paths.push_back(Utf8SystemDir); + } + + // Get the Windows directory + wchar_t WindowsDirectory[MAX_PATH]; + if (GetWindowsDirectoryW(WindowsDirectory, MAX_PATH) > 0) { +std::string Utf8WindowsDir; +if (convertUTF16ToUTF8String( +ArrayRef(reinterpret_cast(WindowsDirectory), +wcslen(WindowsDirectory)), +Utf8WindowsDir)) + Paths.push_back(Utf8WindowsDir); + } + + // Get the current working directory + SmallVector CWD; + if (sys::fs::current_path(CWD)) +Paths.push_back(std::string(CWD.begin(), CWD.end())); + + // Get the PATH environment variable + if (std::optional PathEnv = sys::Process::GetEnv("PATH")) { +SmallVector PathList; +StringRef(*PathEnv).split(PathList, sys::EnvPathSeparator); +for (auto &Path : PathList) + Paths.push_back(Path.str()); + } + + return Paths; +} + +// Custom comparison function for dll name +static bool compareVersions(const std::string &a, const std::string &b) { + // Extract version numbers + int versionA = std::stoi(a.substr(a.find_last_of('_') + 1)); + int versionB = std::stoi(b.substr(b.find_last_of('_') + 1)); + return versionA > versionB; +} + +#endif + +// On Windows, prefer amdhip64_n.dll where n is ROCm major version and greater +// value of n takes precedence. If amdhip64_n.dll is not found, fall back to +// amdhip64.dll. The reason is that a normal driver installation only has +// amdhip64_n.dll but we do not know what n is since this program may be used +// with a future version of HIP runtime. +// +// On Linux, always use default libamdhip64.so. +static std::pair findNewestHIPDLL() { +#ifdef _WIN32 + StringRef HipDLLPrefix = "amdhip64_"; + StringRef HipDLLSuffix = ".dll"; + + std::vector SearchPaths = getSearchPaths(); + std::vector DLLNames; + + for (const auto &Dir : SearchPaths) { +std::error_code EC; +for (sys::fs::directory_iterator DirIt(Dir, EC), DirEnd; + DirIt != DirEnd && !EC;
[clang-tools-extra] [clangd] [C++20] [Modules] Add scanning cache (PR #125988)
@@ -380,30 +381,114 @@ llvm::SmallVector getAllRequiredModules(ProjectModules &MDB, return ModuleNames; } +class CachingProjectModules : public ProjectModules { +public: + CachingProjectModules(const GlobalCompilationDatabase &CDB) : CDB(CDB) {} + + std::vector getRequiredModules(PathRef File) override { +std::unique_ptr MDB = CDB.getProjectModules(File); +if (!MDB) { + elog("Failed to get Project Modules information for {0}", File); + return {}; +} +return MDB->getRequiredModules(File); + } + + std::string getModuleNameForSource(PathRef File) override { +std::unique_ptr MDB = CDB.getProjectModules(File); +if (!MDB) { + elog("Failed to get Project Modules information for {0}", File); + return {}; +} +return MDB->getModuleNameForSource(File); + } + + void setCommandMangler(CommandMangler M) override { +// GlobalCompilationDatabase::getProjectModules() will set mangler +// for the underlying ProjectModules. + } + + std::string getSourceForModuleName(llvm::StringRef ModuleName, + PathRef RequiredSrcFile) override { +std::string CachedResult; +{ + std::lock_guard Lock(CacheMutex); + auto Iter = ModuleNameToSourceCache.find(ModuleName); + if (Iter != ModuleNameToSourceCache.end()) +CachedResult = Iter->second; +} + +std::unique_ptr MDB = +CDB.getProjectModules(RequiredSrcFile); +if (!MDB) { + elog("Failed to get Project Modules information for {0}", + RequiredSrcFile); + return {}; +} + +// Verify Cached Result by seeing if the source declaring the same module +// as we query. +if (!CachedResult.empty()) { + std::string ModuleNameOfCachedSource = + MDB->getModuleNameForSource(CachedResult); + if (ModuleNameOfCachedSource == ModuleName) +return CachedResult; + else { +// Cached Result is invalid. Clear it. + +std::lock_guard Lock(CacheMutex); +ModuleNameToSourceCache.erase(ModuleName); + } +} + +auto Result = MDB->getSourceForModuleName(ModuleName, RequiredSrcFile); ChuanqiXu9 wrote: Thanks for pointing this out. After thinking it again, I feel it might be easier to only store a module-name-to-source cache in the ModulesBuilder (Instead of the CachingProjectModules). And then we will construct the CachingProjectModules in `ModulesBuilder::ModulesBuilderImpl::getOrBuildModuleFile` with the cache and the ProjectModules from CDB. So we won't have the concern now. The lifetime of CachingProjectModules is the same with the previous approach. https://github.com/llvm/llvm-project/pull/125988 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Support BraceWrapping.AfterNamespace with AllowShortNamespacesOnASingleLine (PR #123010)
@@ -628,28 +632,36 @@ class LineJoiner { unsigned tryMergeNamespace(ArrayRef::const_iterator I, ArrayRef::const_iterator E, - unsigned Limit) { + unsigned Limit, bool OpenBraceWrapped) { if (Limit == 0) return 0; -assert(I[1]); -const auto &L1 = *I[1]; +// The merging code is relative to the opening namespace brace, which could +// be either on the first or second line due to the brace wrapping rules. +const auto OpeningBraceLineOffset = OpenBraceWrapped ? 1 : 0; +const auto BraceOpenLine = I + OpeningBraceLineOffset; owenca wrote: Addressed in 1415aaecb73205547e5a00af93d83ab2a1bcbeec. https://github.com/llvm/llvm-project/pull/123010 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [RISCV] Add a generic OOO CPU (PR #120712)
https://github.com/topperc approved this pull request. LGTM https://github.com/llvm/llvm-project/pull/120712 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Fix invalid fixit from modernize-use-ranges for nullptr used with std::unique_ptr (PR #127162)
https://github.com/Andrewyuan34 updated https://github.com/llvm/llvm-project/pull/127162 >From 05c61b85937025bf936ca2a64b38d66e18f4fcbc Mon Sep 17 00:00:00 2001 From: Andrewyuan34 Date: Thu, 13 Feb 2025 22:35:36 -0500 Subject: [PATCH 1/2] [clang-tidy] Fix invalid fixit from modernize-use-ranges for nullptr used with std::unique_ptr --- .../clang-tidy/modernize/UseRangesCheck.cpp | 1 + .../checkers/modernize/use-ranges.cpp | 25 --- 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/clang-tools-extra/clang-tidy/modernize/UseRangesCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseRangesCheck.cpp index 604204e762c78..03b4321ceae99 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseRangesCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseRangesCheck.cpp @@ -165,6 +165,7 @@ utils::UseRangesCheck::ReplacerMap UseRangesCheck::getReplacerMap() const { Buff.assign({"::std::", Name}); Result.try_emplace(Buff, Replacer); } +// auto Diag = diag(""); } if (getLangOpts().CPlusPlus23) Result.try_emplace( diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-ranges.cpp b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-ranges.cpp index b022efebfdf4d..57ca038f64511 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-ranges.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-ranges.cpp @@ -1,14 +1,24 @@ -// RUN: %check_clang_tidy -std=c++20 %s modernize-use-ranges %t -- -- -I %S/Inputs/use-ranges/ -// RUN: %check_clang_tidy -std=c++23 %s modernize-use-ranges %t -check-suffixes=,CPP23 -- -I %S/Inputs/use-ranges/ +// RUN: %check_clang_tidy -std=c++20 %s modernize-use-ranges %t -- -- -I %S/Inputs/ +// RUN: %check_clang_tidy -std=c++23 %s modernize-use-ranges %t -check-suffixes=,CPP23 -- -I %S/Inputs/ +// Example: ./check_clang_tidy.py -std=c++20 checkers/modernize/use-ranges.cpp modernize-use-ranges temp.txt -- -- -I ~/llvm-project/clang-tools-extra/test/clang-tidy/checkers/modernize/Inputs/ // CHECK-FIXES: #include // CHECK-FIXES-CPP23: #include // CHECK-FIXES: #include -#include "fake_std.h" +#include "use-ranges/fake_std.h" +#include "smart-ptr/unique_ptr.h" void Positives() { std::vector I, J; + + // Expect to have no check messages + std::find(I.begin(), I.end(), nullptr); + + std::find(I.begin(), I.end(), std::unique_ptr()); + // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm + // CHECK-FIXES: std::ranges::find(I, std::unique_ptr()); + std::find(I.begin(), I.end(), 0); // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm // CHECK-FIXES: std::ranges::find(I, 0); @@ -76,6 +86,14 @@ void Positives() { void Reverse(){ std::vector I, J; + + // Expect to have no check messages + std::find(I.rbegin(), I.rend(), nullptr); + + std::find(I.rbegin(), I.rend(), std::unique_ptr()); + // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm + // CHECK-FIXES: std::ranges::find(std::ranges::reverse_view(I), std::unique_ptr()); + std::find(I.rbegin(), I.rend(), 0); // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm // CHECK-FIXES: std::ranges::find(std::ranges::reverse_view(I), 0); @@ -112,3 +130,4 @@ void Negatives() { // Pathological, but probably shouldn't diagnose this std::rotate(I.begin(), I.end(), I.end() + 0); } + >From a1dfd7d82118d9e809544e73addd4887760cf066 Mon Sep 17 00:00:00 2001 From: Andrewyuan34 Date: Thu, 13 Feb 2025 23:28:49 -0500 Subject: [PATCH 2/2] asdas --- .../clang-tidy/modernize/UseRangesCheck.cpp| 1 - clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp | 10 ++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/clang-tools-extra/clang-tidy/modernize/UseRangesCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseRangesCheck.cpp index 03b4321ceae99..604204e762c78 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseRangesCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseRangesCheck.cpp @@ -165,7 +165,6 @@ utils::UseRangesCheck::ReplacerMap UseRangesCheck::getReplacerMap() const { Buff.assign({"::std::", Name}); Result.try_emplace(Buff, Replacer); } -// auto Diag = diag(""); } if (getLangOpts().CPlusPlus23) Result.try_emplace( diff --git a/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp b/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp index aba4d17ccd035..4c5db488dce7f 100644 --- a/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp +++ b/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp @@ -215,6 +215,16 @@ void UseRangesCheck::check(const MatchFinder::MatchResult &Result) { const auto *Call = Result.Nodes.getNodeAs(Buffer); if (!Call) continue; +if (Function->getName() == "find") { + unsigned ValueArgIndex = 2; + if (Call->get
[clang-tools-extra] [clang-tidy] Fix invalid fixit from modernize-use-ranges for nullptr used with std::unique_ptr (PR #127162)
https://github.com/Andrewyuan34 updated https://github.com/llvm/llvm-project/pull/127162 >From 7b73f5dfc81d972028382e622888ec71e02b4da2 Mon Sep 17 00:00:00 2001 From: Andrewyuan34 Date: Thu, 13 Feb 2025 22:35:36 -0500 Subject: [PATCH] [clang-tidy] Fix invalid fixit from modernize-use-ranges for nullptr used with std::unique_ptr --- .../clang-tidy/utils/UseRangesCheck.cpp | 10 .../checkers/modernize/use-ranges.cpp | 25 --- 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp b/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp index aba4d17ccd035..4c5db488dce7f 100644 --- a/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp +++ b/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp @@ -215,6 +215,16 @@ void UseRangesCheck::check(const MatchFinder::MatchResult &Result) { const auto *Call = Result.Nodes.getNodeAs(Buffer); if (!Call) continue; +if (Function->getName() == "find") { + unsigned ValueArgIndex = 2; + if (Call->getNumArgs() <= ValueArgIndex) +continue; + const Expr *ValueExpr = + Call->getArg(ValueArgIndex)->IgnoreParenImpCasts(); + if (isa(ValueExpr)) { +return; + } +} auto Diag = createDiag(*Call); if (auto ReplaceName = Replacer->getReplaceName(*Function)) Diag << FixItHint::CreateReplacement(Call->getCallee()->getSourceRange(), diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-ranges.cpp b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-ranges.cpp index b022efebfdf4d..57ca038f64511 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-ranges.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-ranges.cpp @@ -1,14 +1,24 @@ -// RUN: %check_clang_tidy -std=c++20 %s modernize-use-ranges %t -- -- -I %S/Inputs/use-ranges/ -// RUN: %check_clang_tidy -std=c++23 %s modernize-use-ranges %t -check-suffixes=,CPP23 -- -I %S/Inputs/use-ranges/ +// RUN: %check_clang_tidy -std=c++20 %s modernize-use-ranges %t -- -- -I %S/Inputs/ +// RUN: %check_clang_tidy -std=c++23 %s modernize-use-ranges %t -check-suffixes=,CPP23 -- -I %S/Inputs/ +// Example: ./check_clang_tidy.py -std=c++20 checkers/modernize/use-ranges.cpp modernize-use-ranges temp.txt -- -- -I ~/llvm-project/clang-tools-extra/test/clang-tidy/checkers/modernize/Inputs/ // CHECK-FIXES: #include // CHECK-FIXES-CPP23: #include // CHECK-FIXES: #include -#include "fake_std.h" +#include "use-ranges/fake_std.h" +#include "smart-ptr/unique_ptr.h" void Positives() { std::vector I, J; + + // Expect to have no check messages + std::find(I.begin(), I.end(), nullptr); + + std::find(I.begin(), I.end(), std::unique_ptr()); + // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm + // CHECK-FIXES: std::ranges::find(I, std::unique_ptr()); + std::find(I.begin(), I.end(), 0); // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm // CHECK-FIXES: std::ranges::find(I, 0); @@ -76,6 +86,14 @@ void Positives() { void Reverse(){ std::vector I, J; + + // Expect to have no check messages + std::find(I.rbegin(), I.rend(), nullptr); + + std::find(I.rbegin(), I.rend(), std::unique_ptr()); + // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm + // CHECK-FIXES: std::ranges::find(std::ranges::reverse_view(I), std::unique_ptr()); + std::find(I.rbegin(), I.rend(), 0); // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm // CHECK-FIXES: std::ranges::find(std::ranges::reverse_view(I), 0); @@ -112,3 +130,4 @@ void Negatives() { // Pathological, but probably shouldn't diagnose this std::rotate(I.begin(), I.end(), I.end() + 0); } + ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][docs] Fix DR staus for P2280R4 (PR #127166)
https://github.com/frederick-vs-ja created https://github.com/llvm/llvm-project/pull/127166 P2280R4 is officially a defect report. Although Clang 20 only implementated it for C++23 and later, and #95474 accidently removed the DR status in `cxx_status.html`. I think we should mention that it is a DR but not backported yet. >From a2fc3d0550ab22e1a4273dc2debfda23df7cad6f Mon Sep 17 00:00:00 2001 From: "A. Jiang" Date: Fri, 14 Feb 2025 14:03:23 +0800 Subject: [PATCH] [clang][docs] Fix DR staus for P2280R4 P2280R4 is officially a defect report. Although Clang 20 only implementated it for C++23 and later. I think we should mention that it is a DR but not backported yet. --- clang/www/cxx_status.html | 10 -- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/clang/www/cxx_status.html b/clang/www/cxx_status.html index 0fc3b1d314698..70490b2e4331f 100755 --- a/clang/www/cxx_status.html +++ b/clang/www/cxx_status.html @@ -439,8 +439,8 @@ C++23 implementation status Using unknown pointers and references in constant expressions - https://wg21.link/P2280R4";>P2280R4 - Clang 20 + https://wg21.link/P2280R4";>P2280R4 (DR) + Clang 20 (12) static operator() @@ -510,6 +510,12 @@ C++23 implementation status Yes + + +(12): In Clang 20, this change is not yet retroactively +applied to pre-C++23 modes. + + ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-reorder-fields] Avoid repeated hash lookups (NFC) (PR #127165)
https://github.com/kazutakahirata created https://github.com/llvm/llvm-project/pull/127165 None >From 13dc860f8c35928fa251825f80adba87600c2b07 Mon Sep 17 00:00:00 2001 From: Kazu Hirata Date: Thu, 13 Feb 2025 09:45:09 -0800 Subject: [PATCH] [clang-reorder-fields] Avoid repeated hash lookups (NFC) --- .../clang-reorder-fields/ReorderFieldsAction.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/clang-tools-extra/clang-reorder-fields/ReorderFieldsAction.cpp b/clang-tools-extra/clang-reorder-fields/ReorderFieldsAction.cpp index aeb7fe90f2175..ea0207619fb2b 100644 --- a/clang-tools-extra/clang-reorder-fields/ReorderFieldsAction.cpp +++ b/clang-tools-extra/clang-reorder-fields/ReorderFieldsAction.cpp @@ -70,11 +70,12 @@ getNewFieldsOrder(const RecordDecl *Definition, } SmallVector NewFieldsOrder; for (const auto &Name : DesiredFieldsOrder) { -if (!NameToIndex.count(Name)) { +auto It = NameToIndex.find(Name); +if (It == NameToIndex.end()) { llvm::errs() << "Field " << Name << " not found in definition.\n"; return {}; } -NewFieldsOrder.push_back(NameToIndex[Name]); +NewFieldsOrder.push_back(It->second); } assert(NewFieldsOrder.size() == NameToIndex.size()); return NewFieldsOrder; ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-reorder-fields] Avoid repeated hash lookups (NFC) (PR #127165)
llvmbot wrote: @llvm/pr-subscribers-clang-tools-extra Author: Kazu Hirata (kazutakahirata) Changes --- Full diff: https://github.com/llvm/llvm-project/pull/127165.diff 1 Files Affected: - (modified) clang-tools-extra/clang-reorder-fields/ReorderFieldsAction.cpp (+3-2) ``diff diff --git a/clang-tools-extra/clang-reorder-fields/ReorderFieldsAction.cpp b/clang-tools-extra/clang-reorder-fields/ReorderFieldsAction.cpp index aeb7fe90f2175..ea0207619fb2b 100644 --- a/clang-tools-extra/clang-reorder-fields/ReorderFieldsAction.cpp +++ b/clang-tools-extra/clang-reorder-fields/ReorderFieldsAction.cpp @@ -70,11 +70,12 @@ getNewFieldsOrder(const RecordDecl *Definition, } SmallVector NewFieldsOrder; for (const auto &Name : DesiredFieldsOrder) { -if (!NameToIndex.count(Name)) { +auto It = NameToIndex.find(Name); +if (It == NameToIndex.end()) { llvm::errs() << "Field " << Name << " not found in definition.\n"; return {}; } -NewFieldsOrder.push_back(NameToIndex[Name]); +NewFieldsOrder.push_back(It->second); } assert(NewFieldsOrder.size() == NameToIndex.size()); return NewFieldsOrder; `` https://github.com/llvm/llvm-project/pull/127165 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][docs] Fix DR staus for P2280R4 (PR #127166)
llvmbot wrote: @llvm/pr-subscribers-clang Author: A. Jiang (frederick-vs-ja) Changes P2280R4 is officially a defect report. Although Clang 20 only implementated it for C++23 and later, and #95474 accidently removed the DR status in `cxx_status.html`. I think we should mention that it is a DR but not backported yet. --- Full diff: https://github.com/llvm/llvm-project/pull/127166.diff 1 Files Affected: - (modified) clang/www/cxx_status.html (+8-2) ``diff diff --git a/clang/www/cxx_status.html b/clang/www/cxx_status.html index 0fc3b1d314698..70490b2e4331f 100755 --- a/clang/www/cxx_status.html +++ b/clang/www/cxx_status.html @@ -439,8 +439,8 @@ C++23 implementation status Using unknown pointers and references in constant expressions - https://wg21.link/P2280R4";>P2280R4 - Clang 20 + https://wg21.link/P2280R4";>P2280R4 (DR) + Clang 20 (12) static operator() @@ -510,6 +510,12 @@ C++23 implementation status Yes + + +(12): In Clang 20, this change is not yet retroactively +applied to pre-C++23 modes. + + `` https://github.com/llvm/llvm-project/pull/127166 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer] Update the undefined assignment checker diagnostics to not use the term 'garbage' (PR #126596)
haoNoQ wrote: Yes, right, this is more of a side effect of how we do things, not quite the intended behavior. In particular, if you write something out of bounds first, we will no longer report it as an uninitialized read, even though it's still an out-of-bounds read: https://godbolt.org/z/PYaYa1Yos So either way we've obtained a proof that it wasn't "initialized" through any legal means, and we've even considered some illegal means! (Initializations through formally-unrelated objects don't work this way. For example, if you have stack variables `int x[5]` and `int y`, and `y` happens to share the same address as `x[9]` in the final binary, then the code `y = 7; x[9]++;` would still produce an uninitialized read warning in the static analyzer. But if `x` and `y` are fields in the same struct, we'll be able to see whether the offset is shared between them and we'll throw away the warning.) So I'm still mildly in favor of simply saying "uninitialized". It may or may not be someone else's actively used memory but that's beyond the programmer's control and they know it (hopefully). It would be somewhat dishonest to give the user an impression that this checker has considered the object's bounds before emitting a warning. Both the checker and the engine itself effectively ignore allocation bounds for all intents and purposes. https://github.com/llvm/llvm-project/pull/126596 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Avoid repeated map lookups (NFC) (PR #127167)
llvmbot wrote: @llvm/pr-subscribers-clang-tidy Author: Kazu Hirata (kazutakahirata) Changes --- Full diff: https://github.com/llvm/llvm-project/pull/127167.diff 1 Files Affected: - (modified) clang-tools-extra/clang-tidy/readability/NonConstParameterCheck.cpp (+4-5) ``diff diff --git a/clang-tools-extra/clang-tidy/readability/NonConstParameterCheck.cpp b/clang-tools-extra/clang-tidy/readability/NonConstParameterCheck.cpp index 43b69a24bdb16..07071a1f6d2fe 100644 --- a/clang-tools-extra/clang-tidy/readability/NonConstParameterCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/NonConstParameterCheck.cpp @@ -119,13 +119,12 @@ void NonConstParameterCheck::addParm(const ParmVarDecl *Parm) { T->getPointeeType()->isFloatingType())) return; - if (Parameters.find(Parm) != Parameters.end()) + auto [It, Inserted] = Parameters.try_emplace(Parm); + if (!Inserted) return; - ParmInfo PI; - PI.IsReferenced = false; - PI.CanBeConst = true; - Parameters[Parm] = PI; + It->second.IsReferenced = false; + It->second.CanBeConst = true; } void NonConstParameterCheck::setReferenced(const DeclRefExpr *Ref) { `` https://github.com/llvm/llvm-project/pull/127167 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Avoid repeated map lookups (NFC) (PR #127167)
llvmbot wrote: @llvm/pr-subscribers-clang-tools-extra Author: Kazu Hirata (kazutakahirata) Changes --- Full diff: https://github.com/llvm/llvm-project/pull/127167.diff 1 Files Affected: - (modified) clang-tools-extra/clang-tidy/readability/NonConstParameterCheck.cpp (+4-5) ``diff diff --git a/clang-tools-extra/clang-tidy/readability/NonConstParameterCheck.cpp b/clang-tools-extra/clang-tidy/readability/NonConstParameterCheck.cpp index 43b69a24bdb16..07071a1f6d2fe 100644 --- a/clang-tools-extra/clang-tidy/readability/NonConstParameterCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/NonConstParameterCheck.cpp @@ -119,13 +119,12 @@ void NonConstParameterCheck::addParm(const ParmVarDecl *Parm) { T->getPointeeType()->isFloatingType())) return; - if (Parameters.find(Parm) != Parameters.end()) + auto [It, Inserted] = Parameters.try_emplace(Parm); + if (!Inserted) return; - ParmInfo PI; - PI.IsReferenced = false; - PI.CanBeConst = true; - Parameters[Parm] = PI; + It->second.IsReferenced = false; + It->second.CanBeConst = true; } void NonConstParameterCheck::setReferenced(const DeclRefExpr *Ref) { `` https://github.com/llvm/llvm-project/pull/127167 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][analysis] Fix flaky clang/test/Analysis/live-stmts.cpp test (PR #126913)
metaflow wrote: For what it worth this change made it persistently failing in my setup. https://github.com/llvm/llvm-project/pull/126913 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Avoid repeated map lookups (NFC) (PR #127167)
https://github.com/kazutakahirata created https://github.com/llvm/llvm-project/pull/127167 None >From 9ffb3c1c6664e5f78fce8d51ddc93a722e42a54b Mon Sep 17 00:00:00 2001 From: Kazu Hirata Date: Thu, 13 Feb 2025 09:47:28 -0800 Subject: [PATCH] [clang-tidy] Avoid repeated map lookups (NFC) --- .../clang-tidy/readability/NonConstParameterCheck.cpp| 9 - 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/clang-tools-extra/clang-tidy/readability/NonConstParameterCheck.cpp b/clang-tools-extra/clang-tidy/readability/NonConstParameterCheck.cpp index 43b69a24bdb16..07071a1f6d2fe 100644 --- a/clang-tools-extra/clang-tidy/readability/NonConstParameterCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/NonConstParameterCheck.cpp @@ -119,13 +119,12 @@ void NonConstParameterCheck::addParm(const ParmVarDecl *Parm) { T->getPointeeType()->isFloatingType())) return; - if (Parameters.find(Parm) != Parameters.end()) + auto [It, Inserted] = Parameters.try_emplace(Parm); + if (!Inserted) return; - ParmInfo PI; - PI.IsReferenced = false; - PI.CanBeConst = true; - Parameters[Parm] = PI; + It->second.IsReferenced = false; + It->second.CanBeConst = true; } void NonConstParameterCheck::setReferenced(const DeclRefExpr *Ref) { ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][analysis] Fix flaky clang/test/Analysis/live-stmts.cpp test (PR #126913)
steakhal wrote: > For what it worth this change made it persistently failing in my setup. I'm not sure I follow you. The test is disabled on all platforms unconditionally on main. Since e823f14eab4762bdf8483d02e2684f24ec4f100b https://github.com/llvm/llvm-project/pull/126913 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Fix invalid fixit from modernize-use-ranges for nullptr used with std::unique_ptr (PR #127162)
https://github.com/Andrewyuan34 updated https://github.com/llvm/llvm-project/pull/127162 >From 7b73f5dfc81d972028382e622888ec71e02b4da2 Mon Sep 17 00:00:00 2001 From: Andrewyuan34 Date: Thu, 13 Feb 2025 22:35:36 -0500 Subject: [PATCH 1/2] [clang-tidy] Fix invalid fixit from modernize-use-ranges for nullptr used with std::unique_ptr --- .../clang-tidy/utils/UseRangesCheck.cpp | 10 .../checkers/modernize/use-ranges.cpp | 25 --- 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp b/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp index aba4d17ccd035..4c5db488dce7f 100644 --- a/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp +++ b/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp @@ -215,6 +215,16 @@ void UseRangesCheck::check(const MatchFinder::MatchResult &Result) { const auto *Call = Result.Nodes.getNodeAs(Buffer); if (!Call) continue; +if (Function->getName() == "find") { + unsigned ValueArgIndex = 2; + if (Call->getNumArgs() <= ValueArgIndex) +continue; + const Expr *ValueExpr = + Call->getArg(ValueArgIndex)->IgnoreParenImpCasts(); + if (isa(ValueExpr)) { +return; + } +} auto Diag = createDiag(*Call); if (auto ReplaceName = Replacer->getReplaceName(*Function)) Diag << FixItHint::CreateReplacement(Call->getCallee()->getSourceRange(), diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-ranges.cpp b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-ranges.cpp index b022efebfdf4d..57ca038f64511 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-ranges.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-ranges.cpp @@ -1,14 +1,24 @@ -// RUN: %check_clang_tidy -std=c++20 %s modernize-use-ranges %t -- -- -I %S/Inputs/use-ranges/ -// RUN: %check_clang_tidy -std=c++23 %s modernize-use-ranges %t -check-suffixes=,CPP23 -- -I %S/Inputs/use-ranges/ +// RUN: %check_clang_tidy -std=c++20 %s modernize-use-ranges %t -- -- -I %S/Inputs/ +// RUN: %check_clang_tidy -std=c++23 %s modernize-use-ranges %t -check-suffixes=,CPP23 -- -I %S/Inputs/ +// Example: ./check_clang_tidy.py -std=c++20 checkers/modernize/use-ranges.cpp modernize-use-ranges temp.txt -- -- -I ~/llvm-project/clang-tools-extra/test/clang-tidy/checkers/modernize/Inputs/ // CHECK-FIXES: #include // CHECK-FIXES-CPP23: #include // CHECK-FIXES: #include -#include "fake_std.h" +#include "use-ranges/fake_std.h" +#include "smart-ptr/unique_ptr.h" void Positives() { std::vector I, J; + + // Expect to have no check messages + std::find(I.begin(), I.end(), nullptr); + + std::find(I.begin(), I.end(), std::unique_ptr()); + // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm + // CHECK-FIXES: std::ranges::find(I, std::unique_ptr()); + std::find(I.begin(), I.end(), 0); // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm // CHECK-FIXES: std::ranges::find(I, 0); @@ -76,6 +86,14 @@ void Positives() { void Reverse(){ std::vector I, J; + + // Expect to have no check messages + std::find(I.rbegin(), I.rend(), nullptr); + + std::find(I.rbegin(), I.rend(), std::unique_ptr()); + // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm + // CHECK-FIXES: std::ranges::find(std::ranges::reverse_view(I), std::unique_ptr()); + std::find(I.rbegin(), I.rend(), 0); // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm // CHECK-FIXES: std::ranges::find(std::ranges::reverse_view(I), 0); @@ -112,3 +130,4 @@ void Negatives() { // Pathological, but probably shouldn't diagnose this std::rotate(I.begin(), I.end(), I.end() + 0); } + >From ae08073e5b318fbdad17a2441a96f42ff622d8ea Mon Sep 17 00:00:00 2001 From: Andrewyuan34 Date: Fri, 14 Feb 2025 01:15:46 -0500 Subject: [PATCH 2/2] Based on PR reviews, improve code quality by making sure const correctness and modifying code format Co-authored-by: Piotr Zegar --- clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp b/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp index 4c5db488dce7f..bb5f12aa28c49 100644 --- a/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp +++ b/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp @@ -216,7 +216,7 @@ void UseRangesCheck::check(const MatchFinder::MatchResult &Result) { if (!Call) continue; if (Function->getName() == "find") { - unsigned ValueArgIndex = 2; + const unsigned ValueArgIndex = 2; if (Call->getNumArgs() <= ValueArgIndex) continue; const Expr *ValueExpr = ___ cfe-commits mailing list cfe-commits@lists.llvm.org https
[clang] [analyzer] Update the undefined assignment checker diagnostics to not use the term 'garbage' (PR #126596)
haoNoQ wrote: So when it comes to the ArrayBoundChecker, the checker that checks that every access is within bounds, I think that its underlying "model" should be enabled by default, so that to proactively terminate execution paths on which uninitialized accesses happen. It should probably even be considered part of `core` (i.e. we don't support turning it off under any circumstances). And if this means losing some of those uninitialized read warnings by default, that's probably for the best. Because, well, they work and behave the same way as other ArrayBoundChecker warnings. It is likely that these "uninitialized" read warnings are desired _if and only if_ ArrayBoundChecker warnings are desired. https://github.com/llvm/llvm-project/pull/126596 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Fix invalid fixit from modernize-use-ranges for nullptr used with std::unique_ptr (PR #127162)
https://github.com/Andrewyuan34 updated https://github.com/llvm/llvm-project/pull/127162 >From 7b73f5dfc81d972028382e622888ec71e02b4da2 Mon Sep 17 00:00:00 2001 From: Andrewyuan34 Date: Thu, 13 Feb 2025 22:35:36 -0500 Subject: [PATCH 1/3] [clang-tidy] Fix invalid fixit from modernize-use-ranges for nullptr used with std::unique_ptr --- .../clang-tidy/utils/UseRangesCheck.cpp | 10 .../checkers/modernize/use-ranges.cpp | 25 --- 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp b/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp index aba4d17ccd035..4c5db488dce7f 100644 --- a/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp +++ b/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp @@ -215,6 +215,16 @@ void UseRangesCheck::check(const MatchFinder::MatchResult &Result) { const auto *Call = Result.Nodes.getNodeAs(Buffer); if (!Call) continue; +if (Function->getName() == "find") { + unsigned ValueArgIndex = 2; + if (Call->getNumArgs() <= ValueArgIndex) +continue; + const Expr *ValueExpr = + Call->getArg(ValueArgIndex)->IgnoreParenImpCasts(); + if (isa(ValueExpr)) { +return; + } +} auto Diag = createDiag(*Call); if (auto ReplaceName = Replacer->getReplaceName(*Function)) Diag << FixItHint::CreateReplacement(Call->getCallee()->getSourceRange(), diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-ranges.cpp b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-ranges.cpp index b022efebfdf4d..57ca038f64511 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-ranges.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-ranges.cpp @@ -1,14 +1,24 @@ -// RUN: %check_clang_tidy -std=c++20 %s modernize-use-ranges %t -- -- -I %S/Inputs/use-ranges/ -// RUN: %check_clang_tidy -std=c++23 %s modernize-use-ranges %t -check-suffixes=,CPP23 -- -I %S/Inputs/use-ranges/ +// RUN: %check_clang_tidy -std=c++20 %s modernize-use-ranges %t -- -- -I %S/Inputs/ +// RUN: %check_clang_tidy -std=c++23 %s modernize-use-ranges %t -check-suffixes=,CPP23 -- -I %S/Inputs/ +// Example: ./check_clang_tidy.py -std=c++20 checkers/modernize/use-ranges.cpp modernize-use-ranges temp.txt -- -- -I ~/llvm-project/clang-tools-extra/test/clang-tidy/checkers/modernize/Inputs/ // CHECK-FIXES: #include // CHECK-FIXES-CPP23: #include // CHECK-FIXES: #include -#include "fake_std.h" +#include "use-ranges/fake_std.h" +#include "smart-ptr/unique_ptr.h" void Positives() { std::vector I, J; + + // Expect to have no check messages + std::find(I.begin(), I.end(), nullptr); + + std::find(I.begin(), I.end(), std::unique_ptr()); + // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm + // CHECK-FIXES: std::ranges::find(I, std::unique_ptr()); + std::find(I.begin(), I.end(), 0); // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm // CHECK-FIXES: std::ranges::find(I, 0); @@ -76,6 +86,14 @@ void Positives() { void Reverse(){ std::vector I, J; + + // Expect to have no check messages + std::find(I.rbegin(), I.rend(), nullptr); + + std::find(I.rbegin(), I.rend(), std::unique_ptr()); + // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm + // CHECK-FIXES: std::ranges::find(std::ranges::reverse_view(I), std::unique_ptr()); + std::find(I.rbegin(), I.rend(), 0); // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm // CHECK-FIXES: std::ranges::find(std::ranges::reverse_view(I), 0); @@ -112,3 +130,4 @@ void Negatives() { // Pathological, but probably shouldn't diagnose this std::rotate(I.begin(), I.end(), I.end() + 0); } + >From ae08073e5b318fbdad17a2441a96f42ff622d8ea Mon Sep 17 00:00:00 2001 From: Andrewyuan34 Date: Fri, 14 Feb 2025 01:15:46 -0500 Subject: [PATCH 2/3] Based on PR reviews, improve code quality by making sure const correctness and modifying code format Co-authored-by: Piotr Zegar --- clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp b/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp index 4c5db488dce7f..bb5f12aa28c49 100644 --- a/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp +++ b/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp @@ -216,7 +216,7 @@ void UseRangesCheck::check(const MatchFinder::MatchResult &Result) { if (!Call) continue; if (Function->getName() == "find") { - unsigned ValueArgIndex = 2; + const unsigned ValueArgIndex = 2; if (Call->getNumArgs() <= ValueArgIndex) continue; const Expr *ValueExpr = >From 58e8d1e67723de507e6c1bb8ed0bcac36993ac24 Mon Sep 17 00:00:00 2001 From: Andrewyuan34 Date: Fri, 14
[clang] [llvm] [ThinLTO] Support dead RTTI data elimination under -fno-split-lto-unit (PR #126336)
@@ -573,14 +574,29 @@ static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals, convertToDeclaration(GV); } + Triple TT(Mod.getTargetTriple()); + std::unique_ptr ABI = CXXABI::Create(TT); + // Now that all dead bodies have been dropped, delete the actual objects // themselves when possible. for (GlobalValue *GV : DeadGVs) { GV->removeDeadConstantUsers(); -// Might reference something defined in native object (i.e. dropped a -// non-prevailing IR def, but we need to keep the declaration). -if (GV->use_empty()) + +// The RTTI data consists of both type information and the type name string. +// Although they are considered dead, there are still users that reference them. +// For example, the type information might be used by a vtable, and the type name +// string might be used by the type info. +// Therefore, we need to replace these uses to null pointer before erasing them. +if (ABI && (ABI->isTypeInfo(GV->getName()) || +ABI->isTypeName(GV->getName( { + GV->replaceAllUsesWith( luxufan wrote: Although the RTTI GlobalVariable has been inferred as dead, the vtable still references it. Without this change, the RTTI GlobalVariable cannot be eliminated. https://github.com/llvm/llvm-project/pull/126336 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [ThinLTO] Support dead RTTI data elimination under -fno-split-lto-unit (PR #126336)
https://github.com/luxufan updated https://github.com/llvm/llvm-project/pull/126336 >From 83b532a3382a07e472558b8813d43a6f51801423 Mon Sep 17 00:00:00 2001 From: luxufan Date: Thu, 23 Jan 2025 09:28:15 +0800 Subject: [PATCH 01/12] [ThinLTO] Support dead RTTI data elimination under -fno-split-lto-unit This commit enhances the ThinLTO pipeline to support the elimination of unused Run-Time Type Information (RTTI) data when the `-fno-split-lto-unit` flag is used. Previously, dead RTTI data was not effectively removed, leading to larger binary sizes. --- clang/lib/CodeGen/ItaniumCXXABI.cpp | 1 + clang/test/CodeGenCXX/typeid-type-test.cpp| 32 + .../include/llvm/Analysis/TypeMetadataUtils.h | 2 + llvm/include/llvm/AsmParser/LLParser.h| 1 + llvm/include/llvm/AsmParser/LLToken.h | 1 + llvm/include/llvm/Bitcode/LLVMBitCodes.h | 1 + llvm/include/llvm/IR/ModuleSummaryIndex.h | 22 +++ llvm/include/llvm/LTO/LTO.h | 12 +++- llvm/include/llvm/Support/LibCXXABI.h | 49 ++ .../llvm/Transforms/IPO/DeadRTTIElimination.h | 21 ++ llvm/lib/Analysis/ModuleSummaryAnalysis.cpp | 66 ++- llvm/lib/Analysis/TypeMetadataUtils.cpp | 61 + llvm/lib/AsmParser/LLLexer.cpp| 1 + llvm/lib/AsmParser/LLParser.cpp | 30 + llvm/lib/Bitcode/Reader/BitcodeReader.cpp | 13 llvm/lib/Bitcode/Writer/BitcodeWriter.cpp | 15 + llvm/lib/IR/AsmWriter.cpp | 12 llvm/lib/LTO/LTO.cpp | 34 +++--- llvm/lib/LTO/LTOBackend.cpp | 16 - llvm/lib/Support/CMakeLists.txt | 1 + llvm/lib/Support/LibCXXABI.cpp| 25 +++ llvm/lib/Transforms/IPO/CMakeLists.txt| 1 + .../Transforms/IPO/DeadRTTIElimination.cpp| 46 + llvm/test/Assembler/thinlto-rtti-summary.ll | 20 ++ llvm/test/ThinLTO/X86/rtti-clean.ll | 34 ++ llvm/test/ThinLTO/X86/rtti-dont-clean.ll | 46 + 26 files changed, 547 insertions(+), 16 deletions(-) create mode 100644 clang/test/CodeGenCXX/typeid-type-test.cpp create mode 100644 llvm/include/llvm/Support/LibCXXABI.h create mode 100644 llvm/include/llvm/Transforms/IPO/DeadRTTIElimination.h create mode 100644 llvm/lib/Support/LibCXXABI.cpp create mode 100644 llvm/lib/Transforms/IPO/DeadRTTIElimination.cpp create mode 100644 llvm/test/Assembler/thinlto-rtti-summary.ll create mode 100644 llvm/test/ThinLTO/X86/rtti-clean.ll create mode 100644 llvm/test/ThinLTO/X86/rtti-dont-clean.ll diff --git a/clang/lib/CodeGen/ItaniumCXXABI.cpp b/clang/lib/CodeGen/ItaniumCXXABI.cpp index 7c463f51f63dc..090eb4c16ce0b 100644 --- a/clang/lib/CodeGen/ItaniumCXXABI.cpp +++ b/clang/lib/CodeGen/ItaniumCXXABI.cpp @@ -1592,6 +1592,7 @@ llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF, cast(SrcRecordTy->castAs()->getDecl()); llvm::Value *Value = CGF.GetVTablePtr(ThisPtr, CGM.GlobalsInt8PtrTy, ClassDecl); + CGF.EmitTypeMetadataCodeForVCall(ClassDecl, Value, SourceLocation()); if (CGM.getItaniumVTableContext().isRelativeLayout()) { // Load the type info. diff --git a/clang/test/CodeGenCXX/typeid-type-test.cpp b/clang/test/CodeGenCXX/typeid-type-test.cpp new file mode 100644 index 0..9408d87495c60 --- /dev/null +++ b/clang/test/CodeGenCXX/typeid-type-test.cpp @@ -0,0 +1,32 @@ +// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --version 5 +// RUN: %clang_cc1 -I%S -triple x86_64-unknown-linux -flto -fwhole-program-vtables -fvisibility=hidden -emit-llvm -o - %s | FileCheck %s + +#include + +namespace Test1 { +struct A { virtual void f(); }; + +// CHECK-LABEL: define hidden noundef nonnull align 8 dereferenceable(16) ptr @_ZN5Test19gettypeidEPNS_1AE( +// CHECK-SAME: ptr noundef [[A:%.*]]) #[[ATTR0:[0-9]+]] { +// CHECK-NEXT: [[ENTRY:.*:]] +// CHECK-NEXT:[[A_ADDR:%.*]] = alloca ptr, align 8 +// CHECK-NEXT:store ptr [[A]], ptr [[A_ADDR]], align 8 +// CHECK-NEXT:[[TMP0:%.*]] = load ptr, ptr [[A_ADDR]], align 8 +// CHECK-NEXT:[[TMP1:%.*]] = icmp eq ptr [[TMP0]], null +// CHECK-NEXT:br i1 [[TMP1]], label %[[TYPEID_BAD_TYPEID:.*]], label %[[TYPEID_END:.*]] +// CHECK: [[TYPEID_BAD_TYPEID]]: +// CHECK-NEXT:call void @__cxa_bad_typeid() #[[ATTR3:[0-9]+]] +// CHECK-NEXT:unreachable +// CHECK: [[TYPEID_END]]: +// CHECK-NEXT:[[VTABLE:%.*]] = load ptr, ptr [[TMP0]], align 8 +// CHECK-NEXT:[[TMP2:%.*]] = call i1 @llvm.type.test(ptr [[VTABLE]], metadata !"_ZTSN5Test11AE") +// CHECK-NEXT:call void @llvm.assume(i1 [[TMP2]]) +// CHECK-NEXT:[[TMP3:%.*]] = getelementptr inbounds ptr, ptr [[VTABLE]], i64 -1 +// CHECK-NEXT:[[TMP4:%.*]] = load ptr, ptr [[TMP3]], align 8 +// CHECK-NEXT:ret ptr [[TMP4]] +// +const std::type_info &gettype
[clang] [clang][cmake] Sanitize CLANG_BOLT values (PR #126768)
serge-sans-paille wrote: Thanks (and hi o/) https://github.com/llvm/llvm-project/pull/126768 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 29b7295 - [clang][cmake] Sanitize CLANG_BOLT values (#126768)
Author: serge-sans-paille Date: 2025-02-14T06:20:30Z New Revision: 29b7295d3a67ae236e99312efefb7c04753434ef URL: https://github.com/llvm/llvm-project/commit/29b7295d3a67ae236e99312efefb7c04753434ef DIFF: https://github.com/llvm/llvm-project/commit/29b7295d3a67ae236e99312efefb7c04753434ef.diff LOG: [clang][cmake] Sanitize CLANG_BOLT values (#126768) This avoids failing later in the build process. Added: Modified: clang/tools/driver/CMakeLists.txt Removed: diff --git a/clang/tools/driver/CMakeLists.txt b/clang/tools/driver/CMakeLists.txt index ad336fcc45b60..5d7962769014a 100644 --- a/clang/tools/driver/CMakeLists.txt +++ b/clang/tools/driver/CMakeLists.txt @@ -23,10 +23,14 @@ if(CLANG_PLUGIN_SUPPORT) set(support_plugins SUPPORT_PLUGINS) endif() +set(CLANG_BOLT_ALLOWLIST INSTRUMENT PERF LBR) set(CLANG_BOLT OFF CACHE STRING "Apply BOLT optimization to Clang. \ - May be specified as Instrument or Perf or LBR to use a particular profiling \ +May be specified as one of ${CLANG_BOLT_ALLOWLIST} to use a particular profiling \ mechanism.") string(TOUPPER "${CLANG_BOLT}" CLANG_BOLT) +if (CLANG_BOLT AND NOT CLANG_BOLT IN_LIST CLANG_BOLT_ALLOWLIST) +message(FATAL_ERROR "Specified CLANG_BOLT value '${CLANG_BOLT}' is not one of ${CLANG_BOLT_ALLOWLIST}.") +endif() if (CLANG_BOLT AND NOT LLVM_BUILD_INSTRUMENTED) set(CLANG_BOLT_DEPS clear-bolt-fdata llvm-bolt llvm-readobj) ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][cmake] Sanitize CLANG_BOLT values (PR #126768)
https://github.com/serge-sans-paille closed https://github.com/llvm/llvm-project/pull/126768 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Fix invalid fixit from modernize-use-ranges for nullptr used with std::unique_ptr (PR #127162)
https://github.com/Andrewyuan34 edited https://github.com/llvm/llvm-project/pull/127162 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 8a0914c - [clang][NFC] Avoid potential null dereferences (#127017)
Author: schittir Date: 2025-02-13T21:14:36-08:00 New Revision: 8a0914c24530c98c5ff65bce3710552ce3ebf7d7 URL: https://github.com/llvm/llvm-project/commit/8a0914c24530c98c5ff65bce3710552ce3ebf7d7 DIFF: https://github.com/llvm/llvm-project/commit/8a0914c24530c98c5ff65bce3710552ce3ebf7d7.diff LOG: [clang][NFC] Avoid potential null dereferences (#127017) Add null checking. Added: Modified: clang/lib/CodeGen/CGOpenMPRuntime.cpp clang/lib/StaticAnalyzer/Checkers/MacOSKeychainAPIChecker.cpp Removed: diff --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp b/clang/lib/CodeGen/CGOpenMPRuntime.cpp index b679d63874b3b..9f7db25a15bec 100644 --- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp +++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp @@ -7447,7 +7447,7 @@ class MappableExprsHandler { // Update info about the lowest and highest elements for this struct if (!PartialStruct.Base.isValid()) { PartialStruct.LowestElem = {FieldIndex, LowestElem}; -if (IsFinalArraySection) { +if (IsFinalArraySection && OASE) { Address HB = CGF.EmitArraySectionExpr(OASE, /*IsLowerBound=*/false) .getAddress(); @@ -7460,7 +7460,7 @@ class MappableExprsHandler { } else if (FieldIndex < PartialStruct.LowestElem.first) { PartialStruct.LowestElem = {FieldIndex, LowestElem}; } else if (FieldIndex > PartialStruct.HighestElem.first) { -if (IsFinalArraySection) { +if (IsFinalArraySection && OASE) { Address HB = CGF.EmitArraySectionExpr(OASE, /*IsLowerBound=*/false) .getAddress(); diff --git a/clang/lib/StaticAnalyzer/Checkers/MacOSKeychainAPIChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/MacOSKeychainAPIChecker.cpp index 12bf12a0b2322..8955cb209c399 100644 --- a/clang/lib/StaticAnalyzer/Checkers/MacOSKeychainAPIChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/MacOSKeychainAPIChecker.cpp @@ -314,6 +314,7 @@ void MacOSKeychainAPIChecker::checkPreStmt(const CallExpr *CE, RegionArgIsBad = true; } + assert(ArgSM); // Is the argument to the call being tracked? const AllocationState *AS = State->get(ArgSM); if (!AS) ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][NFC] Avoid potential null dereferences (PR #127017)
https://github.com/schittir closed https://github.com/llvm/llvm-project/pull/127017 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [ThinLTO] Support dead RTTI data elimination under -fno-split-lto-unit (PR #126336)
@@ -1920,6 +1924,18 @@ Error LTO::runThinLTO(AddStreamFn AddStream, FileCache Cache, ThinLTO.CombinedIndex, WholeProgramVisibilityEnabledInLTO, DynamicExportSymbols, VisibleToRegularObjSymbols); + Triple TT(getTargetTriple()); + DeadRTTIElimIndex(ThinLTO.CombinedIndex, TT).run(); + + if (!ThinLTO.CombinedIndex.withGlobalValueDeadStripping()) +computeDeadSymbolsWithConstProp(ThinLTO.CombinedIndex, GUIDPreservedSymbols, +IsPrevailing, Conf.OptLevel > 0); + + + if (Conf.CombinedIndexHook && luxufan wrote: Without this change, some existing test cases would fail. This is because the patch alters the position of the dead symbol analysis (moving it after DeadRTTIElimIndex). So this change makes the dumped index file still include information about dead symbols. https://github.com/llvm/llvm-project/pull/126336 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [ThinLTO] Support dead RTTI data elimination under -fno-split-lto-unit (PR #126336)
@@ -1920,6 +1924,18 @@ Error LTO::runThinLTO(AddStreamFn AddStream, FileCache Cache, ThinLTO.CombinedIndex, WholeProgramVisibilityEnabledInLTO, DynamicExportSymbols, VisibleToRegularObjSymbols); + Triple TT(getTargetTriple()); + DeadRTTIElimIndex(ThinLTO.CombinedIndex, TT).run(); + + if (!ThinLTO.CombinedIndex.withGlobalValueDeadStripping()) +computeDeadSymbolsWithConstProp(ThinLTO.CombinedIndex, GUIDPreservedSymbols, +IsPrevailing, Conf.OptLevel > 0); luxufan wrote: Yes, we can, but it would require refactoring the computeDeadSymbolsWithConstProp function. Because the signature of these two isPrevailing functions are different https://github.com/llvm/llvm-project/pull/126336 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clangd] Store full decl/def range with symbol locations (PR #118102)
HighCommander4 wrote: Sorry I haven't had a chance to look at this so far; I haven't quite gotten to a place where I'm keeping up with review requests. I will try to make time for it over the coming weeks, but I've also added our other clangd maintainers as reviewers, in case they have some time for it sooner. I would particularly appreciate any guidance from @kadircet on the high-level considerations (e.g. thoughts on the tradeoff of increased memory usage vs. the additional functionality we get for it). https://github.com/llvm/llvm-project/pull/118102 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Feature]: support for the BC library file into the compile dependencies (PR #119513)
https://github.com/zhouronghua updated https://github.com/llvm/llvm-project/pull/119513 >From c767342682f67da542f1d6ad7d2146885e50f69b Mon Sep 17 00:00:00 2001 From: "ronghua.zhou" Date: Tue, 10 Dec 2024 06:32:24 + Subject: [PATCH 1/2] [Feature](INF-2526) infra: support for the BC library file into the compile dependencies Change-Id: I0f1887f972653a48a4ea0a26768e5b729664c427 --- clang/lib/Driver/ToolChains/Clang.cpp | 45 ++--- clang/lib/Frontend/CompilerInstance.cpp | 10 -- 2 files changed, 48 insertions(+), 7 deletions(-) diff --git a/clang/lib/Driver/ToolChains/Clang.cpp b/clang/lib/Driver/ToolChains/Clang.cpp index d3206c3e8e25e..9a0d8f8938ba3 100644 --- a/clang/lib/Driver/ToolChains/Clang.cpp +++ b/clang/lib/Driver/ToolChains/Clang.cpp @@ -996,9 +996,9 @@ void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA, else ArgM = ArgMD; + // Determine the output location. + const char *DepFile = nullptr; if (ArgM) { -// Determine the output location. -const char *DepFile; if (Arg *MF = Args.getLastArg(options::OPT_MF)) { DepFile = MF->getValue(); C.addFailureResultFile(DepFile, &JA); @@ -1010,8 +1010,9 @@ void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA, DepFile = getDependencyFileName(Args, Inputs); C.addFailureResultFile(DepFile, &JA); } -CmdArgs.push_back("-dependency-file"); -CmdArgs.push_back(DepFile); +// mv to dtu select +// CmdArgs.push_back("-dependency-file"); +// CmdArgs.push_back(DepFile); bool HasTarget = false; for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) { @@ -1100,6 +1101,41 @@ void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA, CmdArgs.push_back("__clang_openmp_device_functions.h"); } + if (getToolChain().getTriple().isNVPTX() || + getToolChain().getTriple().isAMDGCN()) { +// When we set(CMAKE_DEPFILE_FLAGS_${lang} "-MD -MT -MF +// .host") in cmake during heterogeneous compilation, +// we really gererate *.d.host (for host) and *.d (for GPU target), +// the content of *.d = *.d.host + builtin.bc (i.e. libdevice.10.bc or some +// files in --hip-device-lib) +// so when libdevice.10.bc or hip-device-lib is updated, the incremental +// build rule will be triggered. +if (DepFile) { + SmallString<128> NewDepFile(DepFile); + llvm::StringRef SubStr = ".host"; + size_t Pos = NewDepFile.find(SubStr); + CmdArgs.push_back("-dependency-file"); + // for tops target, trim .host in dep file + if (Pos != llvm::StringRef::npos) { +// erase substr +auto ndf = NewDepFile.substr(0, Pos); +CmdArgs.push_back(Args.MakeArgString(ndf)); + } else { +// if not set dep file with .host extend, remain depfile not touched +CmdArgs.push_back(Args.MakeArgString(DepFile)); + } +} + } + // Host side remain depfile not touched + else { +// for host compile, we generate orginal dep file +if (DepFile) { + CmdArgs.push_back("-dependency-file"); + CmdArgs.push_back(DepFile); +} +GenerateHostCompilationDeviceArchMacro(Args, CmdArgs); + } + if (Args.hasArg(options::OPT_foffload_via_llvm)) { // Add llvm_wrappers/* to our system include path. This lets us wrap // standard library headers and other headers. @@ -1110,7 +1146,6 @@ void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA, CmdArgs.push_back("__llvm_offload_device.h"); else CmdArgs.push_back("__llvm_offload_host.h"); - } // Add -i* options, and automatically translate to // -include-pch/-include-pth for transparent PCH support. It's diff --git a/clang/lib/Frontend/CompilerInstance.cpp b/clang/lib/Frontend/CompilerInstance.cpp index fbfc305ca06a0..14779b0161a70 100644 --- a/clang/lib/Frontend/CompilerInstance.cpp +++ b/clang/lib/Frontend/CompilerInstance.cpp @@ -494,8 +494,14 @@ void CompilerInstance::createPreprocessor(TranslationUnitKind TUKind) { // Handle generating dependencies, if requested. const DependencyOutputOptions &DepOpts = getDependencyOutputOpts(); - if (!DepOpts.OutputFile.empty()) -addDependencyCollector(std::make_shared(DepOpts)); + if (!DepOpts.OutputFile.empty()) { +auto DFG = std::make_shared(DepOpts); +for (auto F : getCodeGenOpts().LinkBitcodeFiles) { + DFG->maybeAddDependency(F.Filename, false, false, false, false); +} +addDependencyCollector(DFG); + } + if (!DepOpts.DOTOutputFile.empty()) AttachDependencyGraphGen(*PP, DepOpts.DOTOutputFile, getHeaderSearchOpts().Sysroot); >From ada7f2139890dc9484212ca77fa07309b4903d89 Mon Sep 17 00:00:00 2001 From: "ronghua.zhou" Date: Tue, 10 Dec 2024 06:32:24 + Subject: [PATCH 2/2] [Feature]: support for the BC library file into the compile dependencies --- clang/lib/Driver/ToolChains/Clang.cpp
[clang] [Feature]: support for the BC library file into the compile dependencies (PR #119513)
https://github.com/zhouronghua updated https://github.com/llvm/llvm-project/pull/119513 >From 1c761f6c70feee9d777205936f1a1133ca3bb031 Mon Sep 17 00:00:00 2001 From: "ronghua.zhou" Date: Fri, 14 Feb 2025 01:04:51 + Subject: [PATCH] [Feature]: support for the BC library file into the compile dependencies --- clang/lib/Driver/ToolChains/Clang.cpp | 80 +++-- clang/lib/Frontend/CompilerInstance.cpp | 10 +++- 2 files changed, 83 insertions(+), 7 deletions(-) diff --git a/clang/lib/Driver/ToolChains/Clang.cpp b/clang/lib/Driver/ToolChains/Clang.cpp index d3206c3e8e25e..3e3caa80260f1 100644 --- a/clang/lib/Driver/ToolChains/Clang.cpp +++ b/clang/lib/Driver/ToolChains/Clang.cpp @@ -996,9 +996,9 @@ void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA, else ArgM = ArgMD; + // Determine the output location. + const char *DepFile = nullptr; if (ArgM) { -// Determine the output location. -const char *DepFile; if (Arg *MF = Args.getLastArg(options::OPT_MF)) { DepFile = MF->getValue(); C.addFailureResultFile(DepFile, &JA); @@ -1010,8 +1010,44 @@ void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA, DepFile = getDependencyFileName(Args, Inputs); C.addFailureResultFile(DepFile, &JA); } -CmdArgs.push_back("-dependency-file"); -CmdArgs.push_back(DepFile); +// mv to triple select +// CmdArgs.push_back("-dependency-file"); +// CmdArgs.push_back(DepFile); + +if (getToolChain().getTriple().isNVPTX() || +getToolChain().getTriple().isAMDGCN()) { + // When we set(CMAKE_DEPFILE_FLAGS_${lang} "-MD -MT -MF + // .host") in cmake during heterogeneous compilation, + // we really gererate *.d.host (for host) and *.d (for GPU target), + // the content of *.d = *.d.host + builtin.bc (i.e. libdevice.10.bc or + // some + // files in --hip-device-lib) + // so when libdevice.10.bc or hip-device-lib is updated, the incremental + // build rule will be triggered. + if (DepFile) { +SmallString<128> NewDepFile(DepFile); +llvm::StringRef SubStr = ".host"; +size_t Pos = NewDepFile.find(SubStr); +CmdArgs.push_back("-dependency-file"); +// for tops target, trim .host in dep file +if (Pos != llvm::StringRef::npos) { + // erase substr + auto ndf = NewDepFile.substr(0, Pos); + CmdArgs.push_back(Args.MakeArgString(ndf)); +} else { + // if not set dep file with .host extend, remain depfile not touched + CmdArgs.push_back(Args.MakeArgString(DepFile)); +} + } +} +// Host side remain depfile not touched +else { + // for host compile, we generate orginal dep file + if (DepFile) { +CmdArgs.push_back("-dependency-file"); +CmdArgs.push_back(DepFile); + } +} bool HasTarget = false; for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) { @@ -1100,6 +1136,41 @@ void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA, CmdArgs.push_back("__clang_openmp_device_functions.h"); } + if (getToolChain().getTriple().isNVPTX() || + getToolChain().getTriple().isAMDGCN()) { +// When we set(CMAKE_DEPFILE_FLAGS_${lang} "-MD -MT -MF +// .host") in cmake during heterogeneous compilation, +// we really gererate *.d.host (for host) and *.d (for GPU target), +// the content of *.d = *.d.host + builtin.bc (i.e. libdevice.10.bc or some +// files in --hip-device-lib) +// so when libdevice.10.bc or hip-device-lib is updated, the incremental +// build rule will be triggered. +if (DepFile) { + SmallString<128> NewDepFile(DepFile); + llvm::StringRef SubStr = ".host"; + size_t Pos = NewDepFile.find(SubStr); + CmdArgs.push_back("-dependency-file"); + // for tops target, trim .host in dep file + if (Pos != llvm::StringRef::npos) { +// erase substr +auto ndf = NewDepFile.substr(0, Pos); +CmdArgs.push_back(Args.MakeArgString(ndf)); + } else { +// if not set dep file with .host extend, remain depfile not touched +CmdArgs.push_back(Args.MakeArgString(DepFile)); + } +} + } + // Host side remain depfile not touched + else { +// for host compile, we generate orginal dep file +if (DepFile) { + CmdArgs.push_back("-dependency-file"); + CmdArgs.push_back(DepFile); +} +GenerateHostCompilationDeviceArchMacro(Args, CmdArgs); + } + if (Args.hasArg(options::OPT_foffload_via_llvm)) { // Add llvm_wrappers/* to our system include path. This lets us wrap // standard library headers and other headers. @@ -1110,7 +1181,6 @@ void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA, CmdArgs.push_back("__llvm_offload_device.h"); else CmdArgs.push_back("__llvm_offload_host.h"); - } // Add
[clang] [llvm] [ThinLTO] Support dead RTTI data elimination under -fno-split-lto-unit (PR #126336)
@@ -911,6 +916,63 @@ static void setLiveRoot(ModuleSummaryIndex &Index, StringRef Name) { Summary->setLive(true); } +// Return true if the User U is reachable from a non-vtable user +// through the use-def chain. +static bool hasNonVTableUsers(const User *U, CXXABI *ABI) { + LLVM_DEBUG(dbgs() << "Check if " << *U << "has vtable users\n"); + if (isa(U)) { +// If the type info is used in dynamic_cast or exception handling, +// its user must be the instruction. +return true; + } + + // The virtual table type is either a struct of arrays. For example: + // @vtable = constant { [3 x ptr] } { [3 x ptr] [ ptr null, ptr @rtti, ptr @vf] } + // + // In this case, the user of @rtti is an anonymous ConstantArray. + // Therefore, if the user of the type information is anonymous, + // we need to perform a depth-first search (DFS) to locate its named users. + // + // And we also need to iterate its users if the current user is the type + // info global variable itself. + StringRef Name = U->getName(); + if (Name.empty() || ABI->isTypeInfo(Name)) { +for (const User *It : U->users()) + if (hasNonVTableUsers(It, ABI)) +return true; +return false; + } + + if (!ABI->isVTable(Name)) +return true; + + return false; +} + +static void analyzeRTTIVars(ModuleSummaryIndex &Index, const Module &M) { + Triple TT(M.getTargetTriple()); + + std::unique_ptr ABI = CXXABI::Create(TT); + if (!ABI) +return; + + for (const GlobalVariable &GV : M.globals()) { +if (!ABI->isTypeInfo(GV.getName())) + continue; + +if (hasNonVTableUsers(&GV, ABI.get())) { + std::string TypeName = + ABI->getTypeNameFromTypeInfo(GV.getName()); + const GlobalVariable *TypeNameGV = M.getNamedGlobal(TypeName); + if (TypeNameGV) +Index.addTypeIdAccessed(TypeNameGV->getName()); + else +Index.addTypeIdAccessed(Index.saveString(TypeName)); + break; +} mingmingl-llvm wrote: The stats in https://github.com/llvm/llvm-project/pull/126336#pullrequestreview-2616544519 are got after removing this break in the locally-built compiler. https://github.com/llvm/llvm-project/pull/126336 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][cmake] Sanitize CLANG_BOLT values (PR #126768)
https://github.com/tstellar approved this pull request. https://github.com/llvm/llvm-project/pull/126768 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Fix a bug in annotating ObjCMethodSpecifier (PR #127159)
https://github.com/owenca created https://github.com/llvm/llvm-project/pull/127159 Fixes #58202. >From 957c2112b68a578baf45bbc2fe4bb657c6ea499e Mon Sep 17 00:00:00 2001 From: Owen Pan Date: Thu, 13 Feb 2025 18:57:38 -0800 Subject: [PATCH] [clang-format] Fix a bug in annotating ObjCMethodSpecifier Fixes #58202. --- clang/lib/Format/TokenAnnotator.cpp | 2 +- clang/unittests/Format/FormatTestObjC.cpp | 7 +++ clang/unittests/Format/TokenAnnotatorTest.cpp | 7 +++ 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp index b3540f39e6f69..069fd40e2834c 100644 --- a/clang/lib/Format/TokenAnnotator.cpp +++ b/clang/lib/Format/TokenAnnotator.cpp @@ -1313,7 +1313,7 @@ class AnnotatingParser { switch (bool IsIf = false; Tok->Tok.getKind()) { case tok::plus: case tok::minus: - if (!Tok->Previous && Line.MustBeDeclaration) + if (!Tok->getPreviousNonComment() && Line.MustBeDeclaration) Tok->setType(TT_ObjCMethodSpecifier); break; case tok::colon: diff --git a/clang/unittests/Format/FormatTestObjC.cpp b/clang/unittests/Format/FormatTestObjC.cpp index 9b6f0c396d4db..f7f73db62045c 100644 --- a/clang/unittests/Format/FormatTestObjC.cpp +++ b/clang/unittests/Format/FormatTestObjC.cpp @@ -567,6 +567,13 @@ TEST_F(FormatTestObjC, FormatObjCMethodDeclarations) { "error:(NSError **)theError {\n" "}"); verifyFormat("+ (instancetype)new;"); + + verifyFormat("/*\n" + " */\n" + "- (void)foo;", + "/*\n" + " */- (void)foo;"); + Style.ColumnLimit = 60; verifyFormat("- (instancetype)initXx:(id)x\n" " y:(id)y\n" diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp b/clang/unittests/Format/TokenAnnotatorTest.cpp index 5ab0867490122..7b489b1764cb2 100644 --- a/clang/unittests/Format/TokenAnnotatorTest.cpp +++ b/clang/unittests/Format/TokenAnnotatorTest.cpp @@ -1849,6 +1849,13 @@ TEST_F(TokenAnnotatorTest, UnderstandsObjCMethodExpr) { EXPECT_TOKEN(Tokens[15], tok::greater, TT_BinaryOperator); } +TEST_F(TokenAnnotatorTest, UnderstandsObjCMethodDecl) { + auto Tokens = annotate("/**/ - (void)foo;"); + ASSERT_EQ(Tokens.size(), 8u) << Tokens; + EXPECT_TOKEN(Tokens[1], tok::minus, TT_ObjCMethodSpecifier); + EXPECT_TOKEN(Tokens[5], tok::identifier, TT_SelectorName); +} + TEST_F(TokenAnnotatorTest, UnderstandsLambdas) { auto Tokens = annotate("[]() constexpr {}"); ASSERT_EQ(Tokens.size(), 8u) << Tokens; ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Fix a bug in annotating ObjCMethodSpecifier (PR #127159)
llvmbot wrote: @llvm/pr-subscribers-clang-format Author: Owen Pan (owenca) Changes Fixes #58202. --- Full diff: https://github.com/llvm/llvm-project/pull/127159.diff 3 Files Affected: - (modified) clang/lib/Format/TokenAnnotator.cpp (+1-1) - (modified) clang/unittests/Format/FormatTestObjC.cpp (+7) - (modified) clang/unittests/Format/TokenAnnotatorTest.cpp (+7) ``diff diff --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp index b3540f39e6f69..069fd40e2834c 100644 --- a/clang/lib/Format/TokenAnnotator.cpp +++ b/clang/lib/Format/TokenAnnotator.cpp @@ -1313,7 +1313,7 @@ class AnnotatingParser { switch (bool IsIf = false; Tok->Tok.getKind()) { case tok::plus: case tok::minus: - if (!Tok->Previous && Line.MustBeDeclaration) + if (!Tok->getPreviousNonComment() && Line.MustBeDeclaration) Tok->setType(TT_ObjCMethodSpecifier); break; case tok::colon: diff --git a/clang/unittests/Format/FormatTestObjC.cpp b/clang/unittests/Format/FormatTestObjC.cpp index 9b6f0c396d4db..f7f73db62045c 100644 --- a/clang/unittests/Format/FormatTestObjC.cpp +++ b/clang/unittests/Format/FormatTestObjC.cpp @@ -567,6 +567,13 @@ TEST_F(FormatTestObjC, FormatObjCMethodDeclarations) { "error:(NSError **)theError {\n" "}"); verifyFormat("+ (instancetype)new;"); + + verifyFormat("/*\n" + " */\n" + "- (void)foo;", + "/*\n" + " */- (void)foo;"); + Style.ColumnLimit = 60; verifyFormat("- (instancetype)initXx:(id)x\n" " y:(id)y\n" diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp b/clang/unittests/Format/TokenAnnotatorTest.cpp index 5ab0867490122..7b489b1764cb2 100644 --- a/clang/unittests/Format/TokenAnnotatorTest.cpp +++ b/clang/unittests/Format/TokenAnnotatorTest.cpp @@ -1849,6 +1849,13 @@ TEST_F(TokenAnnotatorTest, UnderstandsObjCMethodExpr) { EXPECT_TOKEN(Tokens[15], tok::greater, TT_BinaryOperator); } +TEST_F(TokenAnnotatorTest, UnderstandsObjCMethodDecl) { + auto Tokens = annotate("/**/ - (void)foo;"); + ASSERT_EQ(Tokens.size(), 8u) << Tokens; + EXPECT_TOKEN(Tokens[1], tok::minus, TT_ObjCMethodSpecifier); + EXPECT_TOKEN(Tokens[5], tok::identifier, TT_SelectorName); +} + TEST_F(TokenAnnotatorTest, UnderstandsLambdas) { auto Tokens = annotate("[]() constexpr {}"); ASSERT_EQ(Tokens.size(), 8u) << Tokens; `` https://github.com/llvm/llvm-project/pull/127159 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clangd] [C++20] [Modules] Add scanning cache (PR #125988)
https://github.com/ChuanqiXu9 updated https://github.com/llvm/llvm-project/pull/125988 >From 42eb3826ed79de5aabb7f0197cfda2ad62d9735d Mon Sep 17 00:00:00 2001 From: Chuanqi Xu Date: Tue, 11 Feb 2025 11:21:34 +0800 Subject: [PATCH 1/3] [clangd] [C++20] [Modules] Introduce cache for scanning modules --- clang-tools-extra/clangd/ModulesBuilder.cpp | 115 +++--- clang-tools-extra/clangd/ProjectModules.h | 6 +- .../clangd/ScanningProjectModules.cpp | 15 ++- 3 files changed, 112 insertions(+), 24 deletions(-) diff --git a/clang-tools-extra/clangd/ModulesBuilder.cpp b/clang-tools-extra/clangd/ModulesBuilder.cpp index bee31fe51555e..121a4cec4c8c2 100644 --- a/clang-tools-extra/clangd/ModulesBuilder.cpp +++ b/clang-tools-extra/clangd/ModulesBuilder.cpp @@ -360,7 +360,8 @@ void ModuleFileCache::remove(StringRef ModuleName) { /// Collect the directly and indirectly required module names for \param /// ModuleName in topological order. The \param ModuleName is guaranteed to /// be the last element in \param ModuleNames. -llvm::SmallVector getAllRequiredModules(ProjectModules &MDB, +llvm::SmallVector getAllRequiredModules(PathRef RequiredSource, + ProjectModules &MDB, StringRef ModuleName) { llvm::SmallVector ModuleNames; llvm::StringSet<> ModuleNamesSet; @@ -368,8 +369,8 @@ llvm::SmallVector getAllRequiredModules(ProjectModules &MDB, auto VisitDeps = [&](StringRef ModuleName, auto Visitor) -> void { ModuleNamesSet.insert(ModuleName); -for (StringRef RequiredModuleName : - MDB.getRequiredModules(MDB.getSourceForModuleName(ModuleName))) +for (StringRef RequiredModuleName : MDB.getRequiredModules( + MDB.getSourceForModuleName(ModuleName, RequiredSource))) if (ModuleNamesSet.insert(RequiredModuleName).second) Visitor(RequiredModuleName, Visitor); @@ -380,30 +381,114 @@ llvm::SmallVector getAllRequiredModules(ProjectModules &MDB, return ModuleNames; } +class CachingProjectModules : public ProjectModules { +public: + CachingProjectModules(const GlobalCompilationDatabase &CDB) : CDB(CDB) {} + + std::vector getRequiredModules(PathRef File) override { +std::unique_ptr MDB = CDB.getProjectModules(File); +if (!MDB) { + elog("Failed to get Project Modules information for {0}", File); + return {}; +} +return MDB->getRequiredModules(File); + } + + std::string getModuleNameForSource(PathRef File) override { +std::unique_ptr MDB = CDB.getProjectModules(File); +if (!MDB) { + elog("Failed to get Project Modules information for {0}", File); + return {}; +} +return MDB->getModuleNameForSource(File); + } + + void setCommandMangler(CommandMangler M) override { +// GlobalCompilationDatabase::getProjectModules() will set mangler +// for the underlying ProjectModules. + } + + std::string getSourceForModuleName(llvm::StringRef ModuleName, + PathRef RequiredSrcFile) override { +std::string CachedResult; +{ + std::lock_guard Lock(CacheMutex); + auto Iter = ModuleNameToSourceCache.find(ModuleName); + if (Iter != ModuleNameToSourceCache.end()) +CachedResult = Iter->second; +} + +std::unique_ptr MDB = +CDB.getProjectModules(RequiredSrcFile); +if (!MDB) { + elog("Failed to get Project Modules information for {0}", + RequiredSrcFile); + return {}; +} + +// Verify Cached Result by seeing if the source declaring the same module +// as we query. +if (!CachedResult.empty()) { + std::string ModuleNameOfCachedSource = + MDB->getModuleNameForSource(CachedResult); + if (ModuleNameOfCachedSource == ModuleName) +return CachedResult; + else { +// Cached Result is invalid. Clear it. + +std::lock_guard Lock(CacheMutex); +ModuleNameToSourceCache.erase(ModuleName); + } +} + +auto Result = MDB->getSourceForModuleName(ModuleName, RequiredSrcFile); + +{ + std::lock_guard Lock(CacheMutex); + ModuleNameToSourceCache.insert({ModuleName, Result}); +} + +return Result; + } + +private: + const GlobalCompilationDatabase &CDB; + + std::mutex CacheMutex; + llvm::StringMap ModuleNameToSourceCache; +}; + } // namespace class ModulesBuilder::ModulesBuilderImpl { public: - ModulesBuilderImpl(const GlobalCompilationDatabase &CDB) : Cache(CDB) {} + ModulesBuilderImpl(const GlobalCompilationDatabase &CDB) + : CachedProjectModules(CDB), Cache(CDB) {} + + CachingProjectModules &getCachedProjectModules() { +return CachedProjectModules; + } const GlobalCompilationDatabase &getCDB() const { return Cache.getCDB(); } llvm::Error - getOrBuildModuleFile(StringRef ModuleName, const ThreadsafeFS &TFS, - ProjectModules &MDB, + getOrBuildModuleFile(PathRe
[clang-tools-extra] [clangd] [C++20] [Modules] Add scanning cache (PR #125988)
ChuanqiXu9 wrote: Update: I asked the Scanner to not run again after global scanned. I felt this was an simple over sight. It doesn't make sense to ask a scanner to scan globally multiple times. https://github.com/llvm/llvm-project/pull/125988 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 4ac68ba - [clang-repl] fix error recovery while parsing completely fails (#127087)
Author: Vipul Cariappa Date: 2025-02-14T08:34:18+01:00 New Revision: 4ac68ba07d6df5d604af22c242c077ea120b9893 URL: https://github.com/llvm/llvm-project/commit/4ac68ba07d6df5d604af22c242c077ea120b9893 DIFF: https://github.com/llvm/llvm-project/commit/4ac68ba07d6df5d604af22c242c077ea120b9893.diff LOG: [clang-repl] fix error recovery while parsing completely fails (#127087) Fixes the following crash in clang-repl ```c++ clang-repl> try { throw 1; } catch { 0; } In file included from <<< inputs >>>:1: input_line_1:1:23: error: expected '(' 1 | try { throw 1; } catch { 0; } | ^ | ( clang-repl: /home/vipul-cariappa/Documents/Workspace/cpp-py/llvms/llvm-project-a/clang/lib/AST/DeclBase.cpp:1757: void clang::DeclContext::addHiddenDecl(clang::Decl*): Assertion `D->getLexicalDeclContext() == this && "Decl inserted into wrong lexical context"' failed. #0 0x59b28459e6da llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) /home/vipul-cariappa/Documents/Workspace/cpp-py/llvms/llvm-project-a/llvm/lib/Support/Unix/Signals.inc:804:22 #1 0x59b28459eaed PrintStackTraceSignalHandler(void*) /home/vipul-cariappa/Documents/Workspace/cpp-py/llvms/llvm-project-a/llvm/lib/Support/Unix/Signals.inc:880:1 #2 0x59b28459bf7f llvm::sys::RunSignalHandlers() /home/vipul-cariappa/Documents/Workspace/cpp-py/llvms/llvm-project-a/llvm/lib/Support/Signals.cpp:105:20 #3 0x59b28459df8e SignalHandler(int, siginfo_t*, void*) /home/vipul-cariappa/Documents/Workspace/cpp-py/llvms/llvm-project-a/llvm/lib/Support/Unix/Signals.inc:418:13 #4 0x77cdf444ea50 (/usr/lib/libc.so.6+0x42a50) #5 0x77cdf44aee3b pthread_kill (/usr/lib/libc.so.6+0xa2e3b) #6 0x77cdf444e928 raise (/usr/lib/libc.so.6+0x42928) #7 0x77cdf443156c abort (/usr/lib/libc.so.6+0x2556c) #8 0x77cdf44314d2 __assert_perror_fail (/usr/lib/libc.so.6+0x254d2) #9 0x77cdfc56 (/usr/lib/libc.so.6+0x38c56) #10 0x59b28495bfc4 clang::DeclContext::addHiddenDecl(clang::Decl*) /home/vipul-cariappa/Documents/Workspace/cpp-py/llvms/llvm-project-a/clang/lib/AST/DeclBase.cpp:1759:3 #11 0x59b28495c0f5 clang::DeclContext::addDecl(clang::Decl*) /home/vipul-cariappa/Documents/Workspace/cpp-py/llvms/llvm-project-a/clang/lib/AST/DeclBase.cpp:1785:37 #12 0x59b28773cc2a clang::Sema::ActOnStartTopLevelStmtDecl(clang::Scope*) /home/vipul-cariappa/Documents/Workspace/cpp-py/llvms/llvm-project-a/clang/lib/Sema/SemaDecl.cpp:20302:18 #13 0x59b286f1efdf clang::Parser::ParseTopLevelStmtDecl() /home/vipul-cariappa/Documents/Workspace/cpp-py/llvms/llvm-project-a/clang/lib/Parse/ParseDecl.cpp:6024:62 #14 0x59b286ef18ee clang::Parser::ParseExternalDeclaration(clang::ParsedAttributes&, clang::ParsedAttributes&, clang::ParsingDeclSpec*) /home/vipul-cariappa/Documents/Workspace/cpp-py/llvms/llvm-project-a/clang/lib/Parse/Parser.cpp:1065:35 #15 0x59b286ef0702 clang::Parser::ParseTopLevelDecl(clang::OpaquePtr&, clang::Sema::ModuleImportState&) /home/vipul-cariappa/Documents/Workspace/cpp-py/llvms/llvm-project-a/clang/lib/Parse/Parser.cpp:758:36 #16 0x59b28562dff2 clang::IncrementalParser::ParseOrWrapTopLevelDecl() /home/vipul-cariappa/Documents/Workspace/cpp-py/llvms/llvm-project-a/clang/lib/Interpreter/IncrementalParser.cpp:66:36 #17 0x59b28562e5b7 clang::IncrementalParser::Parse(llvm::StringRef) /home/vipul-cariappa/Documents/Workspace/cpp-py/llvms/llvm-project-a/clang/lib/Interpreter/IncrementalParser.cpp:132:8 #18 0x59b28561832b clang::Interpreter::Parse(llvm::StringRef) /home/vipul-cariappa/Documents/Workspace/cpp-py/llvms/llvm-project-a/clang/lib/Interpreter/Interpreter.cpp:570:8 #19 0x59b285618cbd clang::Interpreter::ParseAndExecute(llvm::StringRef, clang::Value*) /home/vipul-cariappa/Documents/Workspace/cpp-py/llvms/llvm-project-a/clang/lib/Interpreter/Interpreter.cpp:649:8 #20 0x59b2836f9343 main /home/vipul-cariappa/Documents/Workspace/cpp-py/llvms/llvm-project-a/clang/tools/clang-repl/ClangRepl.cpp:255:59 #21 0x77cdf443388e (/usr/lib/libc.so.6+0x2788e) #22 0x77cdf443394a __libc_start_main (/usr/lib/libc.so.6+0x2794a) #23 0x59b2836f7965 _start (./bin/clang-repl+0x73b8965) fish: Job 1, './bin/clang-repl' terminated by signal SIGABRT (Abort) ``` With this change: ```c++ clang-repl> try { throw 1; } catch { 0; } In file included from <<< inputs >>>:1: input_line_1:1:23: error: expected '(' 1 | try { throw 1; } catch { 0; } | ^ | ( error: Parsing failed. clang-repl> 1; clang-repl> %quit ``` Added: Modified: clang/lib/Parse/ParseDecl.cpp clang/unittests/Interpreter/InterpreterTest.cpp Removed: diff --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp index 75b5e11f8327c..7ae136af47391 100644 --- a/clang/lib/Parse/ParseDecl.cpp +++ b/clang/lib/Parse/Pars
[clang] [clang-repl] fix error recovery while parsing completely fails (PR #127087)
https://github.com/vgvassilev closed https://github.com/llvm/llvm-project/pull/127087 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] add new check: modernize-use-scoped-lock (PR #126434)
https://github.com/vbvictor updated https://github.com/llvm/llvm-project/pull/126434 >From 92588a7eb3f87e74887e94f88d3402ec25c6ee53 Mon Sep 17 00:00:00 2001 From: Victor Baranov Date: Sun, 9 Feb 2025 22:34:26 +0300 Subject: [PATCH 1/7] [clang-tidy] add modernize-use-scoped-lock check --- .../clang-tidy/modernize/CMakeLists.txt | 1 + .../modernize/ModernizeTidyModule.cpp | 3 + .../modernize/UseScopedLockCheck.cpp | 234 ++ .../clang-tidy/modernize/UseScopedLockCheck.h | 50 +++ clang-tools-extra/docs/ReleaseNotes.rst | 6 + .../docs/clang-tidy/checks/list.rst | 1 + .../checks/modernize/use-scoped-lock.rst | 81 + .../use-scoped-lock-only-warn-on-multiple.cpp | 122 .../checkers/modernize/use-scoped-lock.cpp| 290 ++ 9 files changed, 788 insertions(+) create mode 100644 clang-tools-extra/clang-tidy/modernize/UseScopedLockCheck.cpp create mode 100644 clang-tools-extra/clang-tidy/modernize/UseScopedLockCheck.h create mode 100644 clang-tools-extra/docs/clang-tidy/checks/modernize/use-scoped-lock.rst create mode 100644 clang-tools-extra/test/clang-tidy/checkers/modernize/use-scoped-lock-only-warn-on-multiple.cpp create mode 100644 clang-tools-extra/test/clang-tidy/checkers/modernize/use-scoped-lock.cpp diff --git a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt index bab1167fb15ff..619a27b2f9bb6 100644 --- a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt +++ b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt @@ -42,6 +42,7 @@ add_clang_library(clangTidyModernizeModule STATIC UseNullptrCheck.cpp UseOverrideCheck.cpp UseRangesCheck.cpp + UseScopedLockCheck.cpp UseStartsEndsWithCheck.cpp UseStdFormatCheck.cpp UseStdNumbersCheck.cpp diff --git a/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp b/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp index fc46c72982fdc..b2d4ddd667502 100644 --- a/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp +++ b/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp @@ -43,6 +43,7 @@ #include "UseNullptrCheck.h" #include "UseOverrideCheck.h" #include "UseRangesCheck.h" +#include "UseScopedLockCheck.h" #include "UseStartsEndsWithCheck.h" #include "UseStdFormatCheck.h" #include "UseStdNumbersCheck.h" @@ -80,6 +81,8 @@ class ModernizeModule : public ClangTidyModule { CheckFactories.registerCheck( "modernize-use-integer-sign-comparison"); CheckFactories.registerCheck("modernize-use-ranges"); +CheckFactories.registerCheck( +"modernize-use-scoped-lock"); CheckFactories.registerCheck( "modernize-use-starts-ends-with"); CheckFactories.registerCheck("modernize-use-std-format"); diff --git a/clang-tools-extra/clang-tidy/modernize/UseScopedLockCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseScopedLockCheck.cpp new file mode 100644 index 0..af2fea5ad310e --- /dev/null +++ b/clang-tools-extra/clang-tidy/modernize/UseScopedLockCheck.cpp @@ -0,0 +1,234 @@ +//===--- UseScopedLockCheck.cpp - clang-tidy --===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "UseScopedLockCheck.h" +#include "clang/AST/ASTContext.h" +#include "clang/AST/Decl.h" +#include "clang/AST/Stmt.h" +#include "clang/AST/Type.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/ASTMatchers/ASTMatchers.h" +#include "clang/Basic/SourceLocation.h" +#include "clang/Lex/Lexer.h" +#include "llvm/ADT/Twine.h" +#include +#include + +using namespace clang::ast_matchers; + +namespace clang::tidy::modernize { + +namespace { + +bool isLockGuard(const QualType &Type) { + if (const auto *RecordTy = Type->getAs()) { +if (const auto *RecordDecl = RecordTy->getDecl()) { + return RecordDecl->getQualifiedNameAsString() == "std::lock_guard"; +} + } + + if (const auto *TemplateSpecType = + Type->getAs()) { +if (const auto *TemplateDecl = +TemplateSpecType->getTemplateName().getAsTemplateDecl()) { + return TemplateDecl->getQualifiedNameAsString() == "std::lock_guard"; +} + } + + return false; +} + +std::vector getLockGuardsFromDecl(const DeclStmt *DS) { + std::vector LockGuards; + + for (const auto *Decl : DS->decls()) { +if (const auto *VD = dyn_cast(Decl)) { + const QualType Type = VD->getType().getCanonicalType(); + if (isLockGuard(Type)) { +LockGuards.push_back(VD); + } +} + } + + return LockGuards; +} + +// Scans through the statements in a block and groups consecutive +// 'std::lock_guard' variable declarations together. +std::v
[clang] [clang-tools-extra] [flang] [libc] [llvm] [mlir] [clang-tidy] Fix invalid fixit from modernize-use-ranges for nullptr used with std::unique_ptr (PR #127162)
https://github.com/Andrewyuan34 updated https://github.com/llvm/llvm-project/pull/127162 >From 2026e73fe1b0ff2939d1ea4335028440b78f309e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Valentin=20Clement=20=28=E3=83=90=E3=83=AC=E3=83=B3?= =?UTF-8?q?=E3=82=BF=E3=82=A4=E3=83=B3=20=E3=82=AF=E3=83=AC=E3=83=A1?= =?UTF-8?q?=E3=83=B3=29?= Date: Thu, 13 Feb 2025 18:59:24 -0800 Subject: [PATCH 01/10] [flang][cuda] Lower clock64 to nvvm intrinsic (#127155) --- flang/include/flang/Optimizer/Builder/IntrinsicCall.h | 1 + flang/lib/Optimizer/Builder/IntrinsicCall.cpp | 11 +++ flang/module/cudadevice.f90 | 5 + flang/test/Lower/CUDA/cuda-device-proc.cuf| 5 + 4 files changed, 22 insertions(+) diff --git a/flang/include/flang/Optimizer/Builder/IntrinsicCall.h b/flang/include/flang/Optimizer/Builder/IntrinsicCall.h index 47e8a77fa6aec..65732ce7f3224 100644 --- a/flang/include/flang/Optimizer/Builder/IntrinsicCall.h +++ b/flang/include/flang/Optimizer/Builder/IntrinsicCall.h @@ -231,6 +231,7 @@ struct IntrinsicLibrary { void genCFProcPointer(llvm::ArrayRef); fir::ExtendedValue genCFunLoc(mlir::Type, llvm::ArrayRef); fir::ExtendedValue genCLoc(mlir::Type, llvm::ArrayRef); + mlir::Value genClock64(mlir::Type, llvm::ArrayRef); template fir::ExtendedValue genCPtrCompare(mlir::Type, llvm::ArrayRef); diff --git a/flang/lib/Optimizer/Builder/IntrinsicCall.cpp b/flang/lib/Optimizer/Builder/IntrinsicCall.cpp index 3dc8d217ef38e..93744fa58ebc0 100644 --- a/flang/lib/Optimizer/Builder/IntrinsicCall.cpp +++ b/flang/lib/Optimizer/Builder/IntrinsicCall.cpp @@ -209,6 +209,7 @@ static constexpr IntrinsicHandler handlers[]{ &I::genChdir, {{{"name", asAddr}, {"status", asAddr, handleDynamicOptional}}}, /*isElemental=*/false}, +{"clock64", &I::genClock64, {}, /*isElemental=*/false}, {"cmplx", &I::genCmplx, {{{"x", asValue}, {"y", asValue, handleDynamicOptional, @@ -3228,6 +3229,16 @@ IntrinsicLibrary::genChdir(std::optional resultType, return {}; } +// CLOCK64 +mlir::Value IntrinsicLibrary::genClock64(mlir::Type resultType, + llvm::ArrayRef args) { + constexpr llvm::StringLiteral funcName = "llvm.nvvm.read.ptx.sreg.clock64"; + mlir::MLIRContext *context = builder.getContext(); + mlir::FunctionType ftype = mlir::FunctionType::get(context, {}, {resultType}); + auto funcOp = builder.createFunction(loc, funcName, ftype); + return builder.create(loc, funcOp, args).getResult(0); +} + // CMPLX mlir::Value IntrinsicLibrary::genCmplx(mlir::Type resultType, llvm::ArrayRef args) { diff --git a/flang/module/cudadevice.f90 b/flang/module/cudadevice.f90 index 45b9f2c838638..ed126a1253908 100644 --- a/flang/module/cudadevice.f90 +++ b/flang/module/cudadevice.f90 @@ -628,5 +628,10 @@ attributes(device) pure integer function atomicdeci(address, val) end interface public :: atomicdec + interface +attributes(device) integer(8) function clock64() +end function + end interface + public :: clock64 end module diff --git a/flang/test/Lower/CUDA/cuda-device-proc.cuf b/flang/test/Lower/CUDA/cuda-device-proc.cuf index 17a6a1d965640..6a5524102c0ea 100644 --- a/flang/test/Lower/CUDA/cuda-device-proc.cuf +++ b/flang/test/Lower/CUDA/cuda-device-proc.cuf @@ -9,6 +9,7 @@ attributes(global) subroutine devsub() real(8) :: ad integer(4) :: ai integer(8) :: al + integer(8) :: time call syncthreads() call syncwarp(1) @@ -43,6 +44,8 @@ attributes(global) subroutine devsub() ai = atomicor(ai, 1_4) ai = atomicinc(ai, 1_4) ai = atomicdec(ai, 1_4) + + time = clock64() end ! CHECK-LABEL: func.func @_QPdevsub() attributes {cuf.proc_attr = #cuf.cuda_proc} @@ -79,6 +82,8 @@ end ! CHECK: %{{.*}} = llvm.atomicrmw uinc_wrap %{{.*}}, %{{.*}} seq_cst : !llvm.ptr, i32 ! CHECK: %{{.*}} = llvm.atomicrmw udec_wrap %{{.*}}, %{{.*}} seq_cst : !llvm.ptr, i32 +! CHECK: fir.call @llvm.nvvm.read.ptx.sreg.clock64() + subroutine host1() integer, device :: a(32) integer, device :: ret >From 3e9c19bfa6f408137310171fd57c59f8da940ee1 Mon Sep 17 00:00:00 2001 From: Roland McGrath Date: Thu, 13 Feb 2025 20:05:24 -0800 Subject: [PATCH 02/10] [libc] Make test macros suppress the -Wdangling-else warnings (#127149) Use the trick from gtest to allow `ASSERT_...` and `EXPECT_...` macros to be used in braceless `if` without producing warnings about the nested `if`-`else` that results. --- libc/test/UnitTest/LibcTest.h | 9 + 1 file changed, 9 insertions(+) diff --git a/libc/test/UnitTest/LibcTest.h b/libc/test/UnitTest/LibcTest.h index b4e3819ea958d..fbeafd0bacb75 100644 --- a/libc/test/UnitTest/LibcTest.h +++ b/libc/test/UnitTest/LibcTest.h @@ -400,6 +400,14 @@ CString libc_make_test_file_path_func(const char *file_name); SuiteClass##_##TestName SuiteClass##_##TestName#
[clang] [clang-repl] fix error recovery while parsing completely fails (PR #127087)
https://github.com/vgvassilev approved this pull request. Lgtm! Thank you, @Vipul-Cariappa! https://github.com/llvm/llvm-project/pull/127087 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [lld] [llvm] Integrated Distributed ThinLTO (DTLTO): Initial support (PR #126654)
bd1976bris wrote: > If I were to convert [this > example](https://gist.github.com/MaskRay/24f4e2eed208b9d8b0a3752575a665d4#distributed-thinlto) > to its functional equivalent in DTLTO, would it be: > > ``` > clang -fuse-ld=lld -O2 -flto=thin -fthinlto-distributor=distributor_process > a.c b.c c.c > ``` In essence, yes. I was able to get the example to link using DTLTO (via the simple: [local.py](https://github.com/bd1976bris/llvm-project/blob/main/llvm/utils/dtlto/local.py)) with the following: > clang -flto=thin -fuse-ld=lld a.c b.c c.c elf0.c elf1.c > -fthinlto-distributor=$(which python3) -Xdist > $LLVMSRC/llvm/utils/dtlto/local.py This isn't a faithful port of the example because that uses --start-lib, --end-lib to make a virtual archive from `b.o` and `c.o` but I don't think that detail matters. > Is that correct? Yes. A dump of the JSON generated can be seen [here](https://gist.github.com/bd1976bris/625a077aec170aace5ca8685c992f161). https://github.com/llvm/llvm-project/pull/126654 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [RISCV] Add a generic OOO CPU (PR #120712)
@@ -0,0 +1,503 @@ +//===-- RISCVSchedGenericOOO.td - Generic O3 Processor -*- tablegen -*-===// topperc wrote: O3 -> "out of order" or "OOO"? "O3" looks too much like -O3 https://github.com/llvm/llvm-project/pull/120712 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [RISCV] Add a generic OOO CPU (PR #120712)
@@ -0,0 +1,503 @@ +//===-- RISCVSchedGenericOOO.td - Generic O3 Processor -*- tablegen -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +//===--===// +// We assume that: +// * 6-issue out-of-order CPU with 192 ROB entries. +// * Units: +// * IXU (Integer ALU Unit): 4 units, only one can execute mul/div. +// * FXU (Floating-point Unit): 2 units. +// * LSU (Load/Store Unit): 2 units. +// * VXU (Vector Unit): 1 unit. topperc wrote: Remove vector references until vector is supported? https://github.com/llvm/llvm-project/pull/120712 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [RISCV] Add a generic OOO CPU (PR #120712)
@@ -0,0 +1,503 @@ +//===-- RISCVSchedGenericOOO.td - Generic O3 Processor -*- tablegen -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +//===--===// +// We assume that: +// * 6-issue out-of-order CPU with 192 ROB entries. +// * Units: +// * IXU (Integer ALU Unit): 4 units, only one can execute mul/div. +// * FXU (Floating-point Unit): 2 units. +// * LSU (Load/Store Unit): 2 units. +// * VXU (Vector Unit): 1 unit. +// * Latency: +// * Integer instructions: 1 cycle. +// * Multiplication instructions: 4 cycles. +// * Division instructions: 13-21 cycles. +// * Floating-point instructions: 2-6 cycles. +// * Floating-point fdiv/fsqrt instructions: 9-21 cycles. +// * Vector instructions: 2-6 cycles. +// * Load/Store: +// * IXU: 4 cycles. +// * FXU: 4 cycles. +// * VXU: 6 cycles. +// * Integer/floating-point/vector div/rem/sqrt/... are non-pipelined. +//===--===// + +def GenericOOOModel : SchedMachineModel { + int IssueWidth = 6; + int MicroOpBufferSize = 192; + int LoadLatency = 4; + int MispredictPenalty = 8; + let CompleteModel = 0; +} + +let SchedModel = GenericOOOModel in { +//===--===// +// Resource groups +//===--===// +def GenericOOOBranch : ProcResource<1>; +def GenericOOOMulDiv : ProcResource<1>; +def GenericOOOInt : ProcResource<2>; +def GenericOOOALU +: ProcResGroup<[GenericOOOBranch, GenericOOOMulDiv, GenericOOOInt]>; +def GenericOOOLSU : ProcResource<2>; +def GenericOOOFMulDiv : ProcResource<1>; +def GenericOOOFloat : ProcResource<1>; +def GenericOOOFPU : ProcResGroup<[GenericOOOFMulDiv, GenericOOOFloat]>; +// TODO: Add vector scheduling. +// def GenericOOOVXU : ProcResource<1>; + +//===--===// +// Branches +//===--===// +def : WriteRes; +def : WriteRes; +def : WriteRes; + +//===--===// +// Integer arithmetic and logic +//===--===// +def : WriteRes; +def : WriteRes; +def : WriteRes; +def : WriteRes; +def : WriteRes; +def : WriteRes; + +//===--===// +// Integer multiplication +//===--===// +let Latency = 4 in { + def : WriteRes; + def : WriteRes; +} + +//===--===// +// Integer division +//===--===// +def : WriteRes { + let Latency = 13; + let ReleaseAtCycles = [13]; +} +def : WriteRes { + let Latency = 21; + let ReleaseAtCycles = [21]; +} +def : WriteRes { + let Latency = 13; + let ReleaseAtCycles = [13]; +} +def : WriteRes { + let Latency = 21; + let ReleaseAtCycles = [21]; +} + +//===--===// +// Integer memory +//===--===// +// Load +let Latency = 4 in { + def : WriteRes; + def : WriteRes; + def : WriteRes; + def : WriteRes; +} + +// Store +def : WriteRes; +def : WriteRes; +def : WriteRes; +def : WriteRes; + +//===--===// +// Atomic +//===--===// +let Latency = 4 in { + def : WriteRes; + def : WriteRes; +} + +let Latency = 5 in { + def : WriteRes; + def : WriteRes; +} + +def : WriteRes; +def : WriteRes; + +//===--===// +// Floating-point +//===--===// +// Floating-point load +let Latency = 4 in { + def : WriteRes; + def : WriteRes; +} + +// Floating-point store +def : WriteRes; +def : WriteRes; + +// Arithmetic and logic +let Latency = 2 in { + def : WriteRes; + def : WriteRes; +} + +def : WriteRes; +def : WriteRes; +def : WriteRes; +def : WriteRes; + +// Compare +let Latency = 2 in { + def : WriteRes; + def : WriteRes; +} + +// Multiplication +let Latency = 4 in { + def : WriteRes; + def : WriteRes; +} + +// FMA +let Latency = 6 in { + def : WriteRes; + def : WriteRes; +} + +// Division +let Latency = 13, ReleaseAtCycles = [13] in { + def : WriteRes; +
[clang] [llvm] [ThinLTO] Support dead RTTI data elimination under -fno-split-lto-unit (PR #126336)
@@ -911,6 +916,61 @@ static void setLiveRoot(ModuleSummaryIndex &Index, StringRef Name) { Summary->setLive(true); } +static bool hasNonVTableUsers(const User *U, CXXABI *ABI) { + LLVM_DEBUG(dbgs() << "Check if " << *U << "has vtable users\n"); + if (isa(U)) { +// If the type info is used in dynamic_cast or exception handling, +// its user must be the instruction. +return true; + } + + // The virtual table type is either a struct of arrays. For example: + // @vtable = constant { [3 x ptr] } { [3 x ptr] [ ptr null, ptr @rtti, ptr @vf] } + // + // In this case, the user of @rtti is an anonymous ConstantArray. + // Therefore, if the user of the type information is anonymous, + // we need to perform a depth-first search (DFS) to locate its named users. + // + // And we also need to iterate its users if the current user is the type + // info global variable itself. + StringRef Name = U->getName(); + if (Name.empty() || ABI->isTypeInfo(Name)) { +for (const User *It : U->users()) + if (hasNonVTableUsers(It, ABI)) +return true; +return false; + } + + if (!ABI->isVTable(Name)) +return true; luxufan wrote: Yes, I can replace it by checking for the presence of type metadata here. https://github.com/llvm/llvm-project/pull/126336 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Add 'instantiated_from' for enums to the output of TextNodeDumper (PR #124409)
https://github.com/thebrandre updated https://github.com/llvm/llvm-project/pull/124409 From be69a60b46838afdf44855477cfc85b5b268a624 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Brand?= Date: Wed, 22 Jan 2025 19:23:06 +0100 Subject: [PATCH 1/5] [clang] Add 'instantiated_from' for enums to the output of TextNodeDumper This enhances consistency with CXXRecordDecl and FunctionDecl, which also provide this information --- clang/lib/AST/TextNodeDumper.cpp | 5 + 1 file changed, 5 insertions(+) diff --git a/clang/lib/AST/TextNodeDumper.cpp b/clang/lib/AST/TextNodeDumper.cpp index 08efcda46b8f9..26493caa5d06a 100644 --- a/clang/lib/AST/TextNodeDumper.cpp +++ b/clang/lib/AST/TextNodeDumper.cpp @@ -2189,6 +2189,11 @@ void TextNodeDumper::VisitEnumDecl(const EnumDecl *D) { OS << " __module_private__"; if (D->isFixed()) dumpType(D->getIntegerType()); + + if (const auto *Instance = D->getInstantiatedFromMemberEnum()) { +OS << " instantiated_from"; +dumpPointer(Instance); + } } void TextNodeDumper::VisitRecordDecl(const RecordDecl *D) { From 3e1449a3bc7fb8308a54376f3da5f2cde38444e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Brand?= Date: Thu, 30 Jan 2025 19:20:07 +0100 Subject: [PATCH 2/5] [clang] Refine test for instantiated_from of CXXMethodDecl --- clang/test/AST/ast-dump-decl.cpp | 12 ++-- 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/clang/test/AST/ast-dump-decl.cpp b/clang/test/AST/ast-dump-decl.cpp index e84241cee922f..55e455ed7b2b2 100644 --- a/clang/test/AST/ast-dump-decl.cpp +++ b/clang/test/AST/ast-dump-decl.cpp @@ -328,9 +328,9 @@ namespace testClassTemplateDecl { // CHECK-NEXT: | | `-Destructor irrelevant non_trivial user_declared{{$}} // CHECK-NEXT: | |-CXXRecordDecl 0x{{.+}} col:30 implicit referenced class TestClassTemplate{{$}} // CHECK-NEXT: | |-AccessSpecDecl 0x{{.+}} col:3 public{{$}} -// CHECK-NEXT: | |-CXXConstructorDecl 0x{{.+}} col:5 TestClassTemplate 'void ()'{{$}} -// CHECK-NEXT: | |-CXXDestructorDecl 0x{{.+}} col:5 ~TestClassTemplate 'void ()' not_selected{{$}} -// CHECK-NEXT: | |-CXXMethodDecl 0x{{.+}} col:9 j 'int ()'{{$}} +// CHECK-NEXT: | |-CXXConstructorDecl 0x[[#%x,TEMPLATE_CONSTRUCTOR_DECL:]] col:5 TestClassTemplate 'void ()'{{$}} +// CHECK-NEXT: | |-CXXDestructorDecl 0x[[#%x,TEMPLATE_DESTRUCTOR_DECL:]] col:5 ~TestClassTemplate 'void ()' not_selected{{$}} +// CHECK-NEXT: | |-CXXMethodDecl 0x[[#%x,TEMPLATE_METHOD_DECL:]] col:9 j 'int ()'{{$}} // CHECK-NEXT: | `-FieldDecl 0x{{.+}} col:9 i 'int'{{$}} // CHECK-NEXT: |-ClassTemplateSpecializationDecl 0x{{.+}} line:[[@LINE-56]]:30 class TestClassTemplate definition implicit_instantiation{{$}} // CHECK-NEXT: | |-DefinitionData standard_layout has_user_declared_ctor can_const_default_init{{$}} @@ -345,9 +345,9 @@ namespace testClassTemplateDecl { // CHECK-NEXT: | | `-CXXRecord 0x{{.+}} 'A'{{$}} // CHECK-NEXT: | |-CXXRecordDecl 0x{{.+}} col:30 implicit class TestClassTemplate{{$}} // CHECK-NEXT: | |-AccessSpecDecl 0x{{.+}} col:3 public{{$}} -// CHECK-NEXT: | |-CXXConstructorDecl 0x{{.+}} col:5 used TestClassTemplate 'void ()' implicit_instantiation instantiated_from {{0x[^ ]+}}{{$}} -// CHECK-NEXT: | |-CXXDestructorDecl 0x{{.+}} col:5 used ~TestClassTemplate 'void () noexcept' implicit_instantiation instantiated_from {{0x[^ ]+}}{{$}} -// CHECK-NEXT: | |-CXXMethodDecl 0x{{.+}} col:9 j 'int ()' implicit_instantiation instantiated_from {{0x[^ ]+}}{{$}} +// CHECK-NEXT: | |-CXXConstructorDecl 0x{{.+}} col:5 used TestClassTemplate 'void ()' implicit_instantiation instantiated_from 0x[[#TEMPLATE_CONSTRUCTOR_DECL]]{{$}} +// CHECK-NEXT: | |-CXXDestructorDecl 0x{{.+}} col:5 used ~TestClassTemplate 'void () noexcept' implicit_instantiation instantiated_from 0x[[#TEMPLATE_DESTRUCTOR_DECL]]{{$}} +// CHECK-NEXT: | |-CXXMethodDecl 0x{{.+}} col:9 j 'int ()' implicit_instantiation instantiated_from 0x[[#TEMPLATE_METHOD_DECL]]{{$}} // CHECK-NEXT: | |-FieldDecl 0x{{.+}} col:9 i 'int'{{$}} // CHECK-NEXT: | `-CXXConstructorDecl 0x{{.+}} col:30 implicit constexpr TestClassTemplate 'void (const TestClassTemplate &)' inline default trivial noexcept-unevaluated 0x{{.+}}{{$}} // CHECK-NEXT: | `-ParmVarDecl 0x{{.+}} col:30 'const TestClassTemplate &'{{$}} From 85d536fdabf56c35f9703b3ea162238d1385bfe9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Brand?= Date: Thu, 30 Jan 2025 19:20:29 +0100 Subject: [PATCH 3/5] [clang] Add tests for instantiated_from of EnumDecl --- clang/test/AST/ast-dump-decl.cpp | 161 +++ 1 file changed, 161 insertions(+) diff --git a/clang/test/AST/ast-dump-decl.cpp b/clang/test/AST/ast-dump-decl.cpp index 55e455ed7b2b2..374ba43b1988b 100644 --- a/clang/test/AST/ast-dump-decl.cpp +++ b/clang/test/AST/ast-dump-decl.cpp @@ -15,7 +15,9 @@ class testEnumDecl { enum TestEnumDeclFixed : int; }; // CHECK: EnumDecl{{.*}} class TestEnu
[clang] [Clang] Remove the PackExpansion restrictions for rewrite substitution (PR #126206)
https://github.com/zyn0217 updated https://github.com/llvm/llvm-project/pull/126206 >From 2ce86d8842b7b37141d4a415830880b9d1d30260 Mon Sep 17 00:00:00 2001 From: Younan Zhang Date: Fri, 7 Feb 2025 17:15:05 +0800 Subject: [PATCH 1/2] [Clang] Remove the PackExpansion restrictions for rewrite substitution When substituting for rewrite purposes, as in rebuilding constraints for a synthesized deduction guide, it assumed that packs were in PackExpansion* form, such that the instantiator could extract a pattern. For type aliases CTAD, while rebuilding their associated constraints, this might not be the case because we'll call TransformTemplateArgument() for the alias template arguments, where there might be e.g. a non-pack expansion type into a pack expansion, so the assumption wouldn't hold. This patch fixes that by making it treat the non-pack expansions as direct patterns when rewriting. --- clang/lib/Sema/SemaTemplate.cpp| 2 +- clang/lib/Sema/SemaTemplateInstantiate.cpp | 20 ++ clang/test/AST/ast-dump-ctad-alias.cpp | 46 ++ 3 files changed, 60 insertions(+), 8 deletions(-) diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp index 35ece88c603dd..1891613c48fa6 100644 --- a/clang/lib/Sema/SemaTemplate.cpp +++ b/clang/lib/Sema/SemaTemplate.cpp @@ -4905,7 +4905,7 @@ bool Sema::CheckTemplateTypeArgument( [[fallthrough]]; } default: { -// We allow instantiateing a template with template argument packs when +// We allow instantiating a template with template argument packs when // building deduction guides. if (Arg.getKind() == TemplateArgument::Pack && CodeSynthesisContexts.back().Kind == diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp b/clang/lib/Sema/SemaTemplateInstantiate.cpp index 12e98a33d0785..4922d0893bb3d 100644 --- a/clang/lib/Sema/SemaTemplateInstantiate.cpp +++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp @@ -1627,7 +1627,7 @@ namespace { TemplateArgumentLoc Input = SemaRef.getTrivialTemplateArgumentLoc( pack, QualType(), SourceLocation{}); TemplateArgumentLoc Output; - if (SemaRef.SubstTemplateArgument(Input, TemplateArgs, Output)) + if (TransformTemplateArgument(Input, Output, Uneval)) return true; // fails TArgs.push_back(Output.getArgument()); } @@ -2041,9 +2041,11 @@ TemplateName TemplateInstantiator::TransformTemplateName( // We're rewriting the template parameter as a reference to another // template parameter. if (Arg.getKind() == TemplateArgument::Pack) { - assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() && + assert(Arg.pack_size() == 1 && "unexpected pack arguments in template rewrite"); - Arg = Arg.pack_begin()->getPackExpansionPattern(); + Arg = *Arg.pack_begin(); + if (Arg.isPackExpansion()) +Arg = Arg.getPackExpansionPattern(); } assert(Arg.getKind() == TemplateArgument::Template && "unexpected nontype template argument kind in template rewrite"); @@ -2126,9 +2128,11 @@ TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E, // We're rewriting the template parameter as a reference to another // template parameter. if (Arg.getKind() == TemplateArgument::Pack) { - assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() && + assert(Arg.pack_size() == 1 && "unexpected pack arguments in template rewrite"); - Arg = Arg.pack_begin()->getPackExpansionPattern(); + Arg = *Arg.pack_begin(); + if (Arg.isPackExpansion()) +Arg = Arg.getPackExpansionPattern(); } assert(Arg.getKind() == TemplateArgument::Expression && "unexpected nontype template argument kind in template rewrite"); @@ -2592,9 +2596,11 @@ TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB, // We're rewriting the template parameter as a reference to another // template parameter. if (Arg.getKind() == TemplateArgument::Pack) { -assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() && +assert(Arg.pack_size() == 1 && "unexpected pack arguments in template rewrite"); -Arg = Arg.pack_begin()->getPackExpansionPattern(); +Arg = *Arg.pack_begin(); +if (Arg.isPackExpansion()) + Arg = Arg.getPackExpansionPattern(); } assert(Arg.getKind() == TemplateArgument::Type && "unexpected nontype template argument kind in template rewrite"); diff --git a/clang/test/AST/ast-dump-ctad-alias.cpp b/clang/test/AST/ast-dump-ctad-alias.cpp index b1631f7822ce0..f39a4cee518ce 100644 --- a/clang/test/AST/ast-dump-ctad-alias.cpp +++ b/clang/test/AST/ast-dump-ctad-alias.cpp @@ -156,3 +156,49 @@ ATemplatedClass2 test2(list); // CHECK-NEXT: |-TypeT
[clang-tools-extra] [clang-tidy] Fix invalid fixit from modernize-use-ranges for nullptr used with std::unique_ptr (PR #127162)
https://github.com/Andrewyuan34 updated https://github.com/llvm/llvm-project/pull/127162 >From 7b73f5dfc81d972028382e622888ec71e02b4da2 Mon Sep 17 00:00:00 2001 From: Andrewyuan34 Date: Thu, 13 Feb 2025 22:35:36 -0500 Subject: [PATCH 1/3] [clang-tidy] Fix invalid fixit from modernize-use-ranges for nullptr used with std::unique_ptr --- .../clang-tidy/utils/UseRangesCheck.cpp | 10 .../checkers/modernize/use-ranges.cpp | 25 --- 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp b/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp index aba4d17ccd035..4c5db488dce7f 100644 --- a/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp +++ b/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp @@ -215,6 +215,16 @@ void UseRangesCheck::check(const MatchFinder::MatchResult &Result) { const auto *Call = Result.Nodes.getNodeAs(Buffer); if (!Call) continue; +if (Function->getName() == "find") { + unsigned ValueArgIndex = 2; + if (Call->getNumArgs() <= ValueArgIndex) +continue; + const Expr *ValueExpr = + Call->getArg(ValueArgIndex)->IgnoreParenImpCasts(); + if (isa(ValueExpr)) { +return; + } +} auto Diag = createDiag(*Call); if (auto ReplaceName = Replacer->getReplaceName(*Function)) Diag << FixItHint::CreateReplacement(Call->getCallee()->getSourceRange(), diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-ranges.cpp b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-ranges.cpp index b022efebfdf4d..57ca038f64511 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-ranges.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-ranges.cpp @@ -1,14 +1,24 @@ -// RUN: %check_clang_tidy -std=c++20 %s modernize-use-ranges %t -- -- -I %S/Inputs/use-ranges/ -// RUN: %check_clang_tidy -std=c++23 %s modernize-use-ranges %t -check-suffixes=,CPP23 -- -I %S/Inputs/use-ranges/ +// RUN: %check_clang_tidy -std=c++20 %s modernize-use-ranges %t -- -- -I %S/Inputs/ +// RUN: %check_clang_tidy -std=c++23 %s modernize-use-ranges %t -check-suffixes=,CPP23 -- -I %S/Inputs/ +// Example: ./check_clang_tidy.py -std=c++20 checkers/modernize/use-ranges.cpp modernize-use-ranges temp.txt -- -- -I ~/llvm-project/clang-tools-extra/test/clang-tidy/checkers/modernize/Inputs/ // CHECK-FIXES: #include // CHECK-FIXES-CPP23: #include // CHECK-FIXES: #include -#include "fake_std.h" +#include "use-ranges/fake_std.h" +#include "smart-ptr/unique_ptr.h" void Positives() { std::vector I, J; + + // Expect to have no check messages + std::find(I.begin(), I.end(), nullptr); + + std::find(I.begin(), I.end(), std::unique_ptr()); + // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm + // CHECK-FIXES: std::ranges::find(I, std::unique_ptr()); + std::find(I.begin(), I.end(), 0); // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm // CHECK-FIXES: std::ranges::find(I, 0); @@ -76,6 +86,14 @@ void Positives() { void Reverse(){ std::vector I, J; + + // Expect to have no check messages + std::find(I.rbegin(), I.rend(), nullptr); + + std::find(I.rbegin(), I.rend(), std::unique_ptr()); + // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm + // CHECK-FIXES: std::ranges::find(std::ranges::reverse_view(I), std::unique_ptr()); + std::find(I.rbegin(), I.rend(), 0); // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm // CHECK-FIXES: std::ranges::find(std::ranges::reverse_view(I), 0); @@ -112,3 +130,4 @@ void Negatives() { // Pathological, but probably shouldn't diagnose this std::rotate(I.begin(), I.end(), I.end() + 0); } + >From ae08073e5b318fbdad17a2441a96f42ff622d8ea Mon Sep 17 00:00:00 2001 From: Andrewyuan34 Date: Fri, 14 Feb 2025 01:15:46 -0500 Subject: [PATCH 2/3] Based on PR reviews, improve code quality by making sure const correctness and modifying code format Co-authored-by: Piotr Zegar --- clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp b/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp index 4c5db488dce7f..bb5f12aa28c49 100644 --- a/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp +++ b/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp @@ -216,7 +216,7 @@ void UseRangesCheck::check(const MatchFinder::MatchResult &Result) { if (!Call) continue; if (Function->getName() == "find") { - unsigned ValueArgIndex = 2; + const unsigned ValueArgIndex = 2; if (Call->getNumArgs() <= ValueArgIndex) continue; const Expr *ValueExpr = >From 58e8d1e67723de507e6c1bb8ed0bcac36993ac24 Mon Sep 17 00:00:00 2001 From: Andrewyuan34 Date: Fri, 14
[clang-tools-extra] [clang-tidy] Fix invalid fixit from modernize-use-ranges for nullptr used with std::unique_ptr (PR #127162)
https://github.com/Andrewyuan34 updated https://github.com/llvm/llvm-project/pull/127162 >From 7b73f5dfc81d972028382e622888ec71e02b4da2 Mon Sep 17 00:00:00 2001 From: Andrewyuan34 Date: Thu, 13 Feb 2025 22:35:36 -0500 Subject: [PATCH 1/4] [clang-tidy] Fix invalid fixit from modernize-use-ranges for nullptr used with std::unique_ptr --- .../clang-tidy/utils/UseRangesCheck.cpp | 10 .../checkers/modernize/use-ranges.cpp | 25 --- 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp b/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp index aba4d17ccd035..4c5db488dce7f 100644 --- a/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp +++ b/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp @@ -215,6 +215,16 @@ void UseRangesCheck::check(const MatchFinder::MatchResult &Result) { const auto *Call = Result.Nodes.getNodeAs(Buffer); if (!Call) continue; +if (Function->getName() == "find") { + unsigned ValueArgIndex = 2; + if (Call->getNumArgs() <= ValueArgIndex) +continue; + const Expr *ValueExpr = + Call->getArg(ValueArgIndex)->IgnoreParenImpCasts(); + if (isa(ValueExpr)) { +return; + } +} auto Diag = createDiag(*Call); if (auto ReplaceName = Replacer->getReplaceName(*Function)) Diag << FixItHint::CreateReplacement(Call->getCallee()->getSourceRange(), diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-ranges.cpp b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-ranges.cpp index b022efebfdf4d..57ca038f64511 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-ranges.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-ranges.cpp @@ -1,14 +1,24 @@ -// RUN: %check_clang_tidy -std=c++20 %s modernize-use-ranges %t -- -- -I %S/Inputs/use-ranges/ -// RUN: %check_clang_tidy -std=c++23 %s modernize-use-ranges %t -check-suffixes=,CPP23 -- -I %S/Inputs/use-ranges/ +// RUN: %check_clang_tidy -std=c++20 %s modernize-use-ranges %t -- -- -I %S/Inputs/ +// RUN: %check_clang_tidy -std=c++23 %s modernize-use-ranges %t -check-suffixes=,CPP23 -- -I %S/Inputs/ +// Example: ./check_clang_tidy.py -std=c++20 checkers/modernize/use-ranges.cpp modernize-use-ranges temp.txt -- -- -I ~/llvm-project/clang-tools-extra/test/clang-tidy/checkers/modernize/Inputs/ // CHECK-FIXES: #include // CHECK-FIXES-CPP23: #include // CHECK-FIXES: #include -#include "fake_std.h" +#include "use-ranges/fake_std.h" +#include "smart-ptr/unique_ptr.h" void Positives() { std::vector I, J; + + // Expect to have no check messages + std::find(I.begin(), I.end(), nullptr); + + std::find(I.begin(), I.end(), std::unique_ptr()); + // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm + // CHECK-FIXES: std::ranges::find(I, std::unique_ptr()); + std::find(I.begin(), I.end(), 0); // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm // CHECK-FIXES: std::ranges::find(I, 0); @@ -76,6 +86,14 @@ void Positives() { void Reverse(){ std::vector I, J; + + // Expect to have no check messages + std::find(I.rbegin(), I.rend(), nullptr); + + std::find(I.rbegin(), I.rend(), std::unique_ptr()); + // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm + // CHECK-FIXES: std::ranges::find(std::ranges::reverse_view(I), std::unique_ptr()); + std::find(I.rbegin(), I.rend(), 0); // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm // CHECK-FIXES: std::ranges::find(std::ranges::reverse_view(I), 0); @@ -112,3 +130,4 @@ void Negatives() { // Pathological, but probably shouldn't diagnose this std::rotate(I.begin(), I.end(), I.end() + 0); } + >From ae08073e5b318fbdad17a2441a96f42ff622d8ea Mon Sep 17 00:00:00 2001 From: Andrewyuan34 Date: Fri, 14 Feb 2025 01:15:46 -0500 Subject: [PATCH 2/4] Based on PR reviews, improve code quality by making sure const correctness and modifying code format Co-authored-by: Piotr Zegar --- clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp b/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp index 4c5db488dce7f..bb5f12aa28c49 100644 --- a/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp +++ b/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp @@ -216,7 +216,7 @@ void UseRangesCheck::check(const MatchFinder::MatchResult &Result) { if (!Call) continue; if (Function->getName() == "find") { - unsigned ValueArgIndex = 2; + const unsigned ValueArgIndex = 2; if (Call->getNumArgs() <= ValueArgIndex) continue; const Expr *ValueExpr = >From 58e8d1e67723de507e6c1bb8ed0bcac36993ac24 Mon Sep 17 00:00:00 2001 From: Andrewyuan34 Date: Fri, 14
[clang] [clang] Add 'instantiated_from' for enums to the output of TextNodeDumper (PR #124409)
thebrandre wrote: @Sirraide I just rebased the branch on main and ran the unit tests locally in case you'd like to merge it now. https://github.com/llvm/llvm-project/pull/124409 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][Sema] Fix type of an statement expression ending with an atomic type (PR #119711)
https://github.com/alejandro-alvarez-sonarsource updated https://github.com/llvm/llvm-project/pull/119711 From d398fa13c2fa141954c79ca68a59c6ac506b393f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20=C3=81lvarez=20Ayll=C3=B3n?= Date: Wed, 11 Dec 2024 15:43:58 +0100 Subject: [PATCH 1/7] Add regression test --- clang/test/Sema/gh106576.c | 16 1 file changed, 16 insertions(+) create mode 100644 clang/test/Sema/gh106576.c diff --git a/clang/test/Sema/gh106576.c b/clang/test/Sema/gh106576.c new file mode 100644 index 0..792977dea1413 --- /dev/null +++ b/clang/test/Sema/gh106576.c @@ -0,0 +1,16 @@ +// RUN: %clang_cc1 -fsyntax-only -verify %s + +typedef _Atomic char atomic_char; + +typedef _Atomic char atomic_char; + +atomic_char counter; + +char load_plus_one(void) { + return ({counter;}) + 1; // no crash +} + +char type_of_stmt_expr(void) { + typeof(({counter;})) y = ""; // expected-error-re {{incompatible pointer to integer conversion initializing 'typeof (({{{.*}}}))' (aka 'char') with an expression of type 'char[1]'}} + return y; +} From 296aa35fe32449067c69d2b40031af0dd6822a07 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20=C3=81lvarez=20Ayll=C3=B3n?= Date: Thu, 12 Dec 2024 15:08:56 +0100 Subject: [PATCH 2/7] Tentative fix --- clang/lib/Sema/SemaExpr.cpp | 13 +++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp index 20bf6f7f6f28f..165447efb345c 100644 --- a/clang/lib/Sema/SemaExpr.cpp +++ b/clang/lib/Sema/SemaExpr.cpp @@ -15861,10 +15861,19 @@ ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) return Cast->getSubExpr(); + auto Ty = E->getType().getUnqualifiedType(); + + // If the type is an atomic, the statement type is the underlying type. + if (const AtomicType *AT = Ty->getAs()) { +Ty = AT->getValueType().getUnqualifiedType(); +return ImplicitCastExpr::Create(Context, Ty, CK_AtomicToNonAtomic, E, +/*base path*/ nullptr, VK_PRValue, +FPOptionsOverride()); + } + // FIXME: Provide a better location for the initialization. return PerformCopyInitialization( - InitializedEntity::InitializeStmtExprResult( - E->getBeginLoc(), E->getType().getUnqualifiedType()), + InitializedEntity::InitializeStmtExprResult(E->getBeginLoc(), Ty), SourceLocation(), E); } From d13e1090c641314aae8eef50f1b0fb5c0ec67e39 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20=C3=81lvarez=20Ayll=C3=B3n?= Date: Thu, 12 Dec 2024 15:30:07 +0100 Subject: [PATCH 3/7] Use PerformImplicitConversion --- clang/lib/Sema/SemaExpr.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp index 165447efb345c..45ae97807c203 100644 --- a/clang/lib/Sema/SemaExpr.cpp +++ b/clang/lib/Sema/SemaExpr.cpp @@ -15866,9 +15866,7 @@ ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { // If the type is an atomic, the statement type is the underlying type. if (const AtomicType *AT = Ty->getAs()) { Ty = AT->getValueType().getUnqualifiedType(); -return ImplicitCastExpr::Create(Context, Ty, CK_AtomicToNonAtomic, E, -/*base path*/ nullptr, VK_PRValue, -FPOptionsOverride()); +return PerformImplicitConversion(E, Ty, AssignmentAction::Casting); } // FIXME: Provide a better location for the initialization. From 02d8385cc0f824ff0436a7b0a42d16555e5ee0c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20=C3=81lvarez=20Ayll=C3=B3n?= Date: Wed, 18 Dec 2024 09:19:51 +0100 Subject: [PATCH 4/7] Add release note --- clang/docs/ReleaseNotes.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index 408b2800f9e79..24420d9dd49d5 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -853,6 +853,7 @@ Bug Fixes to AST Handling - Clang now uses the location of the begin of the member expression for ``CallExpr`` involving deduced ``this``. (#GH116928) - Fixed printout of AST that uses pack indexing expression. (#GH116486) +- Fixed type deduction of an statement expression (a GCC extension) ending with an atomic type. (#GH106576) Miscellaneous Bug Fixes ^^^ From 2cfef9885cdf023b038cce86519f65a4e9c60bfa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20=C3=81lvarez=20Ayll=C3=B3n?= Date: Wed, 12 Feb 2025 11:22:03 +0100 Subject: [PATCH 5/7] Fix by using getAtomicUnqualifiedType --- clang/lib/Sema/SemaExpr.cpp | 11 ++- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp index 28ee5b07152ff..263cc181ad8de 100644 --- a/clang/lib/Sema/SemaExpr.cpp +++ b/clang/lib/Sema/SemaExpr.cpp @@ -1591
[clang-tools-extra] Added options to readability-implicit-bool-conversion (PR #120087)
chapuni wrote: @kaddkaka IIRC the issue was "char is unsigned". It could be reproducible with adding default target as failing targets above. https://github.com/llvm/llvm-project/pull/120087 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Remove the PackExpansion restrictions for rewrite substitution (PR #126206)
@@ -2041,9 +2041,11 @@ TemplateName TemplateInstantiator::TransformTemplateName( // We're rewriting the template parameter as a reference to another // template parameter. if (Arg.getKind() == TemplateArgument::Pack) { - assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() && hokein wrote: nit: this code is duplicated 3 times, I think we can pull out a common function for it. https://github.com/llvm/llvm-project/pull/126206 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Remove the PackExpansion restrictions for rewrite substitution (PR #126206)
https://github.com/hokein edited https://github.com/llvm/llvm-project/pull/126206 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Remove the PackExpansion restrictions for rewrite substitution (PR #126206)
https://github.com/hokein approved this pull request. Thanks! Please add a release note. https://github.com/llvm/llvm-project/pull/126206 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][analyzer] fix false positive of BlockInCriticalSectionChecker (PR #127049)
flovent wrote: i did something not right about git, so i closed before PR #126752 @Xazax-hun @whisperity please take another look i changed the variable name releated to marco `O_NONBLOCK`; make the first letter uppercase for local variable. add new lines to testcase file. and update the way i checks for NON_BLOCK descriptor, using set to store `open`'s return value https://github.com/llvm/llvm-project/pull/127049 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [Clang] [OpenMP] Add support for '#pragma omp stripe'. (PR #126927)
https://github.com/zahiraam closed https://github.com/llvm/llvm-project/pull/126927 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][analyzer] fix false positive of BlockInCriticalSectionChecker (PR #127049)
llvmbot wrote: @llvm/pr-subscribers-clang-static-analyzer-1 Author: None (flovent) Changes this PR close #124474 when calling `read` and `recv` function for a non-block file descriptor or a invalid file descriptor(`-1`), it will not cause block inside a critical section. this commit checks for non-block file descriptor assigned by `open` function with `O_NONBLOCK` flag. --- Full diff: https://github.com/llvm/llvm-project/pull/127049.diff 2 Files Affected: - (modified) clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp (+66-1) - (added) clang/test/Analysis/issue-124474.cpp (+49) ``diff diff --git a/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp index 7460781799d08..db784f2cc77b2 100644 --- a/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp @@ -145,7 +145,8 @@ using MutexDescriptor = std::variant; -class BlockInCriticalSectionChecker : public Checker { +class BlockInCriticalSectionChecker +: public Checker { private: const std::array MutexDescriptors{ // NOTE: There are standard library implementations where some methods @@ -179,6 +180,8 @@ class BlockInCriticalSectionChecker : public Checker { {CDM::CLibrary, {"read"}}, {CDM::CLibrary, {"recv"}}}; + const CallDescription OpenFunction{CDM::CLibrary, {"open"}, 2}; + const BugType BlockInCritSectionBugType{ this, "Call to blocking function in critical section", "Blocking Error"}; @@ -197,6 +200,8 @@ class BlockInCriticalSectionChecker : public Checker { void handleUnlock(const MutexDescriptor &Mutex, const CallEvent &Call, CheckerContext &C) const; + void handleOpen(const CallEvent &Call, CheckerContext &C) const; + [[nodiscard]] bool isBlockingInCritSection(const CallEvent &Call, CheckerContext &C) const; @@ -205,11 +210,14 @@ class BlockInCriticalSectionChecker : public Checker { /// Process lock. /// Process blocking functions (sleep, getc, fgets, read, recv) void checkPostCall(const CallEvent &Call, CheckerContext &C) const; + + void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const; }; } // end anonymous namespace REGISTER_LIST_WITH_PROGRAMSTATE(ActiveCritSections, CritSectionMarker) +REGISTER_SET_WITH_PROGRAMSTATE(NonBlockFileDescriptor, SymbolRef) // Iterator traits for ImmutableList data structure // that enable the use of STL algorithms. @@ -306,6 +314,25 @@ void BlockInCriticalSectionChecker::handleUnlock( C.addTransition(State); } +void BlockInCriticalSectionChecker::handleOpen(const CallEvent &Call, + CheckerContext &C) const { + const auto *Flag = Call.getArgExpr(1); + static std::optional ValueOfONonBlockVFlag = + tryExpandAsInteger("O_NONBLOCK", C.getBugReporter().getPreprocessor()); + if (!ValueOfONonBlockVFlag) +return; + + SVal FlagSV = C.getState()->getSVal(Flag, C.getLocationContext()); + const llvm::APSInt *FlagV = FlagSV.getAsInteger(); + if (!FlagV) +return; + + if ((*FlagV & ValueOfONonBlockVFlag.value()) != 0) +if (SymbolRef SR = Call.getReturnValue().getAsSymbol()) { + C.addTransition(C.getState()->add(SR)); +} +} + bool BlockInCriticalSectionChecker::isBlockingInCritSection( const CallEvent &Call, CheckerContext &C) const { return BlockingFunctions.contains(Call) && @@ -315,6 +342,27 @@ bool BlockInCriticalSectionChecker::isBlockingInCritSection( void BlockInCriticalSectionChecker::checkPostCall(const CallEvent &Call, CheckerContext &C) const { if (isBlockingInCritSection(Call, C)) { +// for 'read' and 'recv' call, check whether it's file descriptor(first +// argument) is +// created by 'open' API with O_NONBLOCK flag or is equal to -1, they will +// not cause block in these situations, don't report +StringRef FuncName = Call.getCalleeIdentifier()->getName(); +if (FuncName == "read" || FuncName == "recv") { + const auto *Arg = Call.getArgExpr(0); + if (!Arg) +return; + + SVal SV = C.getSVal(Arg); + if (const auto *IntValue = SV.getAsInteger()) { +if (*IntValue == -1) + return; + } + + SymbolRef SR = C.getSVal(Arg).getAsSymbol(); + if (SR && C.getState()->contains(SR)) { +return; + } +} reportBlockInCritSection(Call, C); } else if (std::optional LockDesc = checkDescriptorMatch(Call, C, /*IsLock=*/true)) { @@ -322,9 +370,26 @@ void BlockInCriticalSectionChecker::checkPostCall(const CallEvent &Call, } else if (std::optional UnlockDesc = checkDescriptorMatch(Call, C, /*IsL
[clang] [clang][analyzer] fix false positive of BlockInCriticalSectionChecker (PR #127049)
https://github.com/flovent created https://github.com/llvm/llvm-project/pull/127049 this PR close #124474 when calling `read` and `recv` function for a non-block file descriptor or a invalid file descriptor(`-1`), it will not cause block inside a critical section. this commit checks for non-block file descriptor assigned by `open` function with `O_NONBLOCK` flag. >From c916dadbaf6021eda606d76784115698a9800571 Mon Sep 17 00:00:00 2001 From: flovent Date: Thu, 13 Feb 2025 20:17:20 +0800 Subject: [PATCH] [clang][analyzer] fix false positive of BlockInCriticalSectionChecker --- .../BlockInCriticalSectionChecker.cpp | 67 ++- clang/test/Analysis/issue-124474.cpp | 49 ++ 2 files changed, 115 insertions(+), 1 deletion(-) create mode 100644 clang/test/Analysis/issue-124474.cpp diff --git a/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp index 7460781799d08..db784f2cc77b2 100644 --- a/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp @@ -145,7 +145,8 @@ using MutexDescriptor = std::variant; -class BlockInCriticalSectionChecker : public Checker { +class BlockInCriticalSectionChecker +: public Checker { private: const std::array MutexDescriptors{ // NOTE: There are standard library implementations where some methods @@ -179,6 +180,8 @@ class BlockInCriticalSectionChecker : public Checker { {CDM::CLibrary, {"read"}}, {CDM::CLibrary, {"recv"}}}; + const CallDescription OpenFunction{CDM::CLibrary, {"open"}, 2}; + const BugType BlockInCritSectionBugType{ this, "Call to blocking function in critical section", "Blocking Error"}; @@ -197,6 +200,8 @@ class BlockInCriticalSectionChecker : public Checker { void handleUnlock(const MutexDescriptor &Mutex, const CallEvent &Call, CheckerContext &C) const; + void handleOpen(const CallEvent &Call, CheckerContext &C) const; + [[nodiscard]] bool isBlockingInCritSection(const CallEvent &Call, CheckerContext &C) const; @@ -205,11 +210,14 @@ class BlockInCriticalSectionChecker : public Checker { /// Process lock. /// Process blocking functions (sleep, getc, fgets, read, recv) void checkPostCall(const CallEvent &Call, CheckerContext &C) const; + + void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const; }; } // end anonymous namespace REGISTER_LIST_WITH_PROGRAMSTATE(ActiveCritSections, CritSectionMarker) +REGISTER_SET_WITH_PROGRAMSTATE(NonBlockFileDescriptor, SymbolRef) // Iterator traits for ImmutableList data structure // that enable the use of STL algorithms. @@ -306,6 +314,25 @@ void BlockInCriticalSectionChecker::handleUnlock( C.addTransition(State); } +void BlockInCriticalSectionChecker::handleOpen(const CallEvent &Call, + CheckerContext &C) const { + const auto *Flag = Call.getArgExpr(1); + static std::optional ValueOfONonBlockVFlag = + tryExpandAsInteger("O_NONBLOCK", C.getBugReporter().getPreprocessor()); + if (!ValueOfONonBlockVFlag) +return; + + SVal FlagSV = C.getState()->getSVal(Flag, C.getLocationContext()); + const llvm::APSInt *FlagV = FlagSV.getAsInteger(); + if (!FlagV) +return; + + if ((*FlagV & ValueOfONonBlockVFlag.value()) != 0) +if (SymbolRef SR = Call.getReturnValue().getAsSymbol()) { + C.addTransition(C.getState()->add(SR)); +} +} + bool BlockInCriticalSectionChecker::isBlockingInCritSection( const CallEvent &Call, CheckerContext &C) const { return BlockingFunctions.contains(Call) && @@ -315,6 +342,27 @@ bool BlockInCriticalSectionChecker::isBlockingInCritSection( void BlockInCriticalSectionChecker::checkPostCall(const CallEvent &Call, CheckerContext &C) const { if (isBlockingInCritSection(Call, C)) { +// for 'read' and 'recv' call, check whether it's file descriptor(first +// argument) is +// created by 'open' API with O_NONBLOCK flag or is equal to -1, they will +// not cause block in these situations, don't report +StringRef FuncName = Call.getCalleeIdentifier()->getName(); +if (FuncName == "read" || FuncName == "recv") { + const auto *Arg = Call.getArgExpr(0); + if (!Arg) +return; + + SVal SV = C.getSVal(Arg); + if (const auto *IntValue = SV.getAsInteger()) { +if (*IntValue == -1) + return; + } + + SymbolRef SR = C.getSVal(Arg).getAsSymbol(); + if (SR && C.getState()->contains(SR)) { +return; + } +} reportBlockInCritSection(Call, C); } else if (std::optional LockDesc = checkDescriptorMatch(Call, C, /*IsLock
[clang] [flang] [flang][OpenMP] Upstream first part of `do concurrent` mapping (PR #126026)
@@ -352,16 +352,38 @@ bool CodeGenAction::beginSourceFileAction() { // Add OpenMP-related passes // WARNING: These passes must be run immediately after the lowering to ensure // that the FIR is correct with respect to OpenMP operations/attributes. - if (ci.getInvocation().getFrontendOpts().features.IsEnabled( - Fortran::common::LanguageFeature::OpenMP)) { -bool isDevice = false; + bool isOpenMPEnabled = + ci.getInvocation().getFrontendOpts().features.IsEnabled( + Fortran::common::LanguageFeature::OpenMP); + + fir::OpenMPFIRPassPipelineOpts opts; + + using DoConcurrentMappingKind = + Fortran::frontend::CodeGenOptions::DoConcurrentMappingKind; + opts.doConcurrentMappingKind = + ci.getInvocation().getCodeGenOpts().getDoConcurrentMapping(); + + if (opts.doConcurrentMappingKind != DoConcurrentMappingKind::DCMK_None && + !isOpenMPEnabled) { +unsigned diagID = ci.getDiagnostics().getCustomDiagID( +clang::DiagnosticsEngine::Warning, +"lowering `do concurrent` loops to OpenMP is only supported if " +"OpenMP is enabled. Enable OpenMP using `-fopenmp`. `do concurrent` " +"loops will be serialized."); kiranchandramohan wrote: Nit: It will be great if the warning can be in a single line or in lines separated by full stops. This will aid better searching for this warning. https://github.com/llvm/llvm-project/pull/126026 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [flang] [flang][OpenMP] Upstream first part of `do concurrent` mapping (PR #126026)
@@ -157,6 +157,34 @@ static bool parseDebugArgs(Fortran::frontend::CodeGenOptions &opts, return true; } +static bool parseDoConcurrentMapping(Fortran::frontend::CodeGenOptions &opts, kiranchandramohan wrote: The return value seems unused. https://github.com/llvm/llvm-project/pull/126026 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [flang] [flang][OpenMP] Upstream first part of `do concurrent` mapping (PR #126026)
https://github.com/kiranchandramohan edited https://github.com/llvm/llvm-project/pull/126026 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [flang] [flang][OpenMP] Upstream first part of `do concurrent` mapping (PR #126026)
https://github.com/kiranchandramohan approved this pull request. LG. Please wait for @skatrak https://github.com/llvm/llvm-project/pull/126026 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][analyzer] fix false positive of BlockInCriticalSectionChecker (PR #127049)
https://github.com/flovent updated https://github.com/llvm/llvm-project/pull/127049 >From c916dadbaf6021eda606d76784115698a9800571 Mon Sep 17 00:00:00 2001 From: flovent Date: Thu, 13 Feb 2025 20:17:20 +0800 Subject: [PATCH 1/2] [clang][analyzer] fix false positive of BlockInCriticalSectionChecker --- .../BlockInCriticalSectionChecker.cpp | 67 ++- clang/test/Analysis/issue-124474.cpp | 49 ++ 2 files changed, 115 insertions(+), 1 deletion(-) create mode 100644 clang/test/Analysis/issue-124474.cpp diff --git a/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp index 7460781799d08..db784f2cc77b2 100644 --- a/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp @@ -145,7 +145,8 @@ using MutexDescriptor = std::variant; -class BlockInCriticalSectionChecker : public Checker { +class BlockInCriticalSectionChecker +: public Checker { private: const std::array MutexDescriptors{ // NOTE: There are standard library implementations where some methods @@ -179,6 +180,8 @@ class BlockInCriticalSectionChecker : public Checker { {CDM::CLibrary, {"read"}}, {CDM::CLibrary, {"recv"}}}; + const CallDescription OpenFunction{CDM::CLibrary, {"open"}, 2}; + const BugType BlockInCritSectionBugType{ this, "Call to blocking function in critical section", "Blocking Error"}; @@ -197,6 +200,8 @@ class BlockInCriticalSectionChecker : public Checker { void handleUnlock(const MutexDescriptor &Mutex, const CallEvent &Call, CheckerContext &C) const; + void handleOpen(const CallEvent &Call, CheckerContext &C) const; + [[nodiscard]] bool isBlockingInCritSection(const CallEvent &Call, CheckerContext &C) const; @@ -205,11 +210,14 @@ class BlockInCriticalSectionChecker : public Checker { /// Process lock. /// Process blocking functions (sleep, getc, fgets, read, recv) void checkPostCall(const CallEvent &Call, CheckerContext &C) const; + + void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const; }; } // end anonymous namespace REGISTER_LIST_WITH_PROGRAMSTATE(ActiveCritSections, CritSectionMarker) +REGISTER_SET_WITH_PROGRAMSTATE(NonBlockFileDescriptor, SymbolRef) // Iterator traits for ImmutableList data structure // that enable the use of STL algorithms. @@ -306,6 +314,25 @@ void BlockInCriticalSectionChecker::handleUnlock( C.addTransition(State); } +void BlockInCriticalSectionChecker::handleOpen(const CallEvent &Call, + CheckerContext &C) const { + const auto *Flag = Call.getArgExpr(1); + static std::optional ValueOfONonBlockVFlag = + tryExpandAsInteger("O_NONBLOCK", C.getBugReporter().getPreprocessor()); + if (!ValueOfONonBlockVFlag) +return; + + SVal FlagSV = C.getState()->getSVal(Flag, C.getLocationContext()); + const llvm::APSInt *FlagV = FlagSV.getAsInteger(); + if (!FlagV) +return; + + if ((*FlagV & ValueOfONonBlockVFlag.value()) != 0) +if (SymbolRef SR = Call.getReturnValue().getAsSymbol()) { + C.addTransition(C.getState()->add(SR)); +} +} + bool BlockInCriticalSectionChecker::isBlockingInCritSection( const CallEvent &Call, CheckerContext &C) const { return BlockingFunctions.contains(Call) && @@ -315,6 +342,27 @@ bool BlockInCriticalSectionChecker::isBlockingInCritSection( void BlockInCriticalSectionChecker::checkPostCall(const CallEvent &Call, CheckerContext &C) const { if (isBlockingInCritSection(Call, C)) { +// for 'read' and 'recv' call, check whether it's file descriptor(first +// argument) is +// created by 'open' API with O_NONBLOCK flag or is equal to -1, they will +// not cause block in these situations, don't report +StringRef FuncName = Call.getCalleeIdentifier()->getName(); +if (FuncName == "read" || FuncName == "recv") { + const auto *Arg = Call.getArgExpr(0); + if (!Arg) +return; + + SVal SV = C.getSVal(Arg); + if (const auto *IntValue = SV.getAsInteger()) { +if (*IntValue == -1) + return; + } + + SymbolRef SR = C.getSVal(Arg).getAsSymbol(); + if (SR && C.getState()->contains(SR)) { +return; + } +} reportBlockInCritSection(Call, C); } else if (std::optional LockDesc = checkDescriptorMatch(Call, C, /*IsLock=*/true)) { @@ -322,9 +370,26 @@ void BlockInCriticalSectionChecker::checkPostCall(const CallEvent &Call, } else if (std::optional UnlockDesc = checkDescriptorMatch(Call, C, /*IsLock=*/false)) { handleUnlock(*UnlockDesc, Call, C); + } else if (OpenFunctio
[clang-tools-extra] [clangd] [C++20] [Modules] Add scanning cache (PR #125988)
https://github.com/kadircet edited https://github.com/llvm/llvm-project/pull/125988 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clangd] [C++20] [Modules] Add scanning cache (PR #125988)
@@ -449,21 +534,17 @@ llvm::Error ModulesBuilder::ModulesBuilderImpl::getOrBuildModuleFile( std::unique_ptr ModulesBuilder::buildPrerequisiteModulesFor(PathRef File, const ThreadsafeFS &TFS) { - std::unique_ptr MDB = Impl->getCDB().getProjectModules(File); - if (!MDB) { -elog("Failed to get Project Modules information for {0}", File); -return std::make_unique(); - } + ProjectModules &MDB = Impl->getCachedProjectModules(); kadircet wrote: nit: prefer the derived type, `CachingProjectModules&` also in the other interfaces. this should make both the code more explicit, but also enable us to add custom methods to `CachingProjectModules` and use them in the future easily. https://github.com/llvm/llvm-project/pull/125988 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits