[clang] [clang-format][NFC] Add getNextNonComment() to FormatTokenSource (PR #87868)
https://github.com/owenca updated https://github.com/llvm/llvm-project/pull/87868 >From 5c614fec2b54c146841a9ef3089dee1a63f72543 Mon Sep 17 00:00:00 2001 From: Owen Pan Date: Fri, 5 Apr 2024 22:45:47 -0700 Subject: [PATCH 1/2] [clang-format][NFC] Add getNextNonComment() to FormatTokenSource --- clang/lib/Format/FormatTokenSource.h | 9 + clang/lib/Format/UnwrappedLineParser.cpp | 11 ++- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/clang/lib/Format/FormatTokenSource.h b/clang/lib/Format/FormatTokenSource.h index cce19f527a9236..1b7d2820e2c3b8 100644 --- a/clang/lib/Format/FormatTokenSource.h +++ b/clang/lib/Format/FormatTokenSource.h @@ -72,6 +72,15 @@ class FormatTokenSource { // getNextToken() -> a1 // getNextToken() -> a2 virtual FormatToken *insertTokens(ArrayRef Tokens) = 0; + + FormatToken *getNextNonComment() { +FormatToken *Tok; +do { + Tok = getNextToken(); + assert(Tok); +} while (Tok->is(tok::comment)); +return Tok; + } }; class IndexedTokenSource : public FormatTokenSource { diff --git a/clang/lib/Format/UnwrappedLineParser.cpp b/clang/lib/Format/UnwrappedLineParser.cpp index 57d8dbcf3b4c77..33be39f2f77b0b 100644 --- a/clang/lib/Format/UnwrappedLineParser.cpp +++ b/clang/lib/Format/UnwrappedLineParser.cpp @@ -427,11 +427,7 @@ bool UnwrappedLineParser::parseLevel(const FormatToken *OpeningBrace, break; case tok::kw_default: { unsigned StoredPosition = Tokens->getPosition(); - FormatToken *Next; - do { -Next = Tokens->getNextToken(); -assert(Next); - } while (Next->is(tok::comment)); + auto *Next = Tokens->getNextNonComment(); FormatTok = Tokens->setPosition(StoredPosition); if (Next->isNot(tok::colon)) { // default not followed by ':' is not a case label; treat it like @@ -497,10 +493,7 @@ void UnwrappedLineParser::calculateBraceTypes(bool ExpectClassBody) { assert(Tok->is(tok::l_brace)); do { -FormatToken *NextTok; -do { - NextTok = Tokens->getNextToken(); -} while (NextTok->is(tok::comment)); +auto *NextTok = Tokens->getNextNonComment(); if (!Line->InMacroBody && !Style.isTableGen()) { // Skip PPDirective lines and comments. >From a7675f4a362ffc52a19c49bdc8016335d36127b6 Mon Sep 17 00:00:00 2001 From: Owen Pan Date: Sat, 6 Apr 2024 01:38:10 -0700 Subject: [PATCH 2/2] Update FormatTokenSource.h Add `[[nodiscard]]`. --- clang/lib/Format/FormatTokenSource.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clang/lib/Format/FormatTokenSource.h b/clang/lib/Format/FormatTokenSource.h index 1b7d2820e2c3b8..2b93f302d36034 100644 --- a/clang/lib/Format/FormatTokenSource.h +++ b/clang/lib/Format/FormatTokenSource.h @@ -73,7 +73,7 @@ class FormatTokenSource { // getNextToken() -> a2 virtual FormatToken *insertTokens(ArrayRef Tokens) = 0; - FormatToken *getNextNonComment() { + [[nodiscard]] FormatToken *getNextNonComment() { FormatToken *Tok; do { Tok = getNextToken(); ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 684f27d - [clang-format][NFC] Use `is` instead of `getType() ==`
Author: Owen Pan Date: 2024-04-06T01:51:45-07:00 New Revision: 684f27d37a6f1faf546a71bcb784b48c7fc8b7e0 URL: https://github.com/llvm/llvm-project/commit/684f27d37a6f1faf546a71bcb784b48c7fc8b7e0 DIFF: https://github.com/llvm/llvm-project/commit/684f27d37a6f1faf546a71bcb784b48c7fc8b7e0.diff LOG: [clang-format][NFC] Use `is` instead of `getType() ==` Added: Modified: clang/lib/Format/FormatTokenLexer.cpp clang/lib/Format/TokenAnnotator.cpp clang/lib/Format/UnwrappedLineParser.cpp clang/lib/Format/WhitespaceManager.cpp Removed: diff --git a/clang/lib/Format/FormatTokenLexer.cpp b/clang/lib/Format/FormatTokenLexer.cpp index 036f7e6a4efc1e..f430d3764babeb 100644 --- a/clang/lib/Format/FormatTokenLexer.cpp +++ b/clang/lib/Format/FormatTokenLexer.cpp @@ -404,7 +404,7 @@ bool FormatTokenLexer::tryMergeNullishCoalescingEqual() { return false; auto &NullishCoalescing = *(Tokens.end() - 2); auto &Equal = *(Tokens.end() - 1); - if (NullishCoalescing->getType() != TT_NullCoalescingOperator || + if (NullishCoalescing->isNot(TT_NullCoalescingOperator) || Equal->isNot(tok::equal)) { return false; } diff --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp index 3e9988d5094554..9abd4282103b7b 100644 --- a/clang/lib/Format/TokenAnnotator.cpp +++ b/clang/lib/Format/TokenAnnotator.cpp @@ -825,8 +825,7 @@ class AnnotatingParser { Parent->overwriteFixedType(TT_BinaryOperator); } // An arrow after an ObjC method expression is not a lambda arrow. -if (CurrentToken->getType() == TT_ObjCMethodExpr && -CurrentToken->Next && +if (CurrentToken->is(TT_ObjCMethodExpr) && CurrentToken->Next && CurrentToken->Next->is(TT_TrailingReturnArrow)) { CurrentToken->Next->overwriteFixedType(TT_Unknown); } @@ -1563,7 +1562,7 @@ class AnnotatingParser { case tok::l_brace: if (Style.Language == FormatStyle::LK_TextProto) { FormatToken *Previous = Tok->getPreviousNonComment(); -if (Previous && Previous->getType() != TT_DictLiteral) +if (Previous && Previous->isNot(TT_DictLiteral)) Previous->setType(TT_SelectorName); } Scopes.push_back(getScopeType(*Tok)); @@ -1583,7 +1582,7 @@ class AnnotatingParser { Tok->Previous->isOneOf(TT_SelectorName, TT_DictLiteral))) { Tok->setType(TT_DictLiteral); FormatToken *Previous = Tok->getPreviousNonComment(); - if (Previous && Previous->getType() != TT_DictLiteral) + if (Previous && Previous->isNot(TT_DictLiteral)) Previous->setType(TT_SelectorName); } if (Style.isTableGen()) @@ -4754,8 +4753,7 @@ bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line, // Objective-C dictionary literal -> no space before closing brace. return false; } - if (Right.getType() == TT_TrailingAnnotation && - Right.isOneOf(tok::amp, tok::ampamp) && + if (Right.is(TT_TrailingAnnotation) && Right.isOneOf(tok::amp, tok::ampamp) && Left.isOneOf(tok::kw_const, tok::kw_volatile) && (!Right.Next || Right.Next->is(tok::semi))) { // Match const and volatile ref-qualifiers without any additional diff --git a/clang/lib/Format/UnwrappedLineParser.cpp b/clang/lib/Format/UnwrappedLineParser.cpp index 57d8dbcf3b4c77..6df7cc1c39551d 100644 --- a/clang/lib/Format/UnwrappedLineParser.cpp +++ b/clang/lib/Format/UnwrappedLineParser.cpp @@ -366,9 +366,9 @@ bool UnwrappedLineParser::parseLevel(const FormatToken *OpeningBrace, continue; } tok::TokenKind Kind = FormatTok->Tok.getKind(); -if (FormatTok->getType() == TT_MacroBlockBegin) +if (FormatTok->is(TT_MacroBlockBegin)) Kind = tok::l_brace; -else if (FormatTok->getType() == TT_MacroBlockEnd) +else if (FormatTok->is(TT_MacroBlockEnd)) Kind = tok::r_brace; auto ParseDefault = [this, OpeningBrace, IfKind, &IfLBrace, &HasDoWhile, @@ -4709,14 +4709,13 @@ void UnwrappedLineParser::readToken(int LevelDifference) { do { FormatTok = Tokens->getNextToken(); assert(FormatTok); -while (FormatTok->getType() == TT_ConflictStart || - FormatTok->getType() == TT_ConflictEnd || - FormatTok->getType() == TT_ConflictAlternative) { - if (FormatTok->getType() == TT_ConflictStart) +while (FormatTok->isOneOf(TT_ConflictStart, TT_ConflictEnd, + TT_ConflictAlternative)) { + if (FormatTok->is(TT_ConflictStart)) conditionalCompilationStart(/*Unreachable=*/false); - else if (FormatTok->getType() == TT_ConflictAlternative) + else if (FormatTok->is(TT_ConflictAlternative)) conditionalCompilationAlternative(); - else if (FormatTok->getType() == TT_ConflictEnd) + else if (FormatTok->is(TT_ConflictEnd))
[clang] [clang-tools-extra] [clangd] Fix: exclude insertions at end of CursorPlaceholder in formatting (PR #87746)
https://github.com/roife updated https://github.com/llvm/llvm-project/pull/87746 >From 03fe6bec808cb968c35f1bad7432ea6155ed0115 Mon Sep 17 00:00:00 2001 From: roife Date: Thu, 4 Apr 2024 14:54:08 +0800 Subject: [PATCH] [clangd] Fix: exclude insertions at the end of CursorPlaceholder in formatting This commit introduces a new param 'includeInsAtPos' for 'getShiftedCodePosition', which is defaulted to be true. If 'includeInsAtPos' is true, the insertion at the 'Position' will be counted in. Otherwise, the insertion will not be counted in. Changes made: - Added new param 'includeInsAtPos' to 'getShiftedCodePosition'. - Set 'includeInsAtPos' to be false when calculate the end position of 'CursorPlaceholder' in 'formatIncremental' of clangd. Fixes #71983 --- clang-tools-extra/clangd/Format.cpp | 2 +- .../clangd/unittests/FormatTests.cpp | 19 +++ .../include/clang/Tooling/Core/Replacement.h | 7 --- clang/lib/Tooling/Core/Replacement.cpp| 7 +-- 4 files changed, 29 insertions(+), 6 deletions(-) diff --git a/clang-tools-extra/clangd/Format.cpp b/clang-tools-extra/clangd/Format.cpp index 272a34d4ed7972..901a709e2e3934 100644 --- a/clang-tools-extra/clangd/Format.cpp +++ b/clang-tools-extra/clangd/Format.cpp @@ -341,7 +341,7 @@ formatIncremental(llvm::StringRef OriginalCode, unsigned OriginalCursor, unsigned FormattedCursorStart = FormattingChanges.getShiftedCodePosition(Cursor), FormattedCursorEnd = FormattingChanges.getShiftedCodePosition( - Cursor + Incremental.CursorPlaceholder.size()); + Cursor + Incremental.CursorPlaceholder.size(), false); tooling::Replacements RemoveCursorPlaceholder( tooling::Replacement(Filename, FormattedCursorStart, FormattedCursorEnd - FormattedCursorStart, "")); diff --git a/clang-tools-extra/clangd/unittests/FormatTests.cpp b/clang-tools-extra/clangd/unittests/FormatTests.cpp index f7384a1bc63c99..22c19fefc61aad 100644 --- a/clang-tools-extra/clangd/unittests/FormatTests.cpp +++ b/clang-tools-extra/clangd/unittests/FormatTests.cpp @@ -315,6 +315,25 @@ vector x = {1, 2, 3}^ )cpp"); } +TEST(FormatIncremental, InsertBraces) { + format::FormatStyle Style = +format::getGoogleStyle(format::FormatStyle::LK_Cpp); + Style.InsertBraces = true; + expectAfterNewline(R"cpp( +int main() { + while (true) +^ +} +)cpp", + R"cpp( +int main() { + while (true) { + + }^ +} +)cpp", + Style); +} } // namespace } // namespace clangd } // namespace clang diff --git a/clang/include/clang/Tooling/Core/Replacement.h b/clang/include/clang/Tooling/Core/Replacement.h index f9452111e147f1..69fe5186dfb0a5 100644 --- a/clang/include/clang/Tooling/Core/Replacement.h +++ b/clang/include/clang/Tooling/Core/Replacement.h @@ -268,9 +268,10 @@ class Replacements { std::vector getAffectedRanges() const; // Returns the new offset in the code after replacements being applied. - // Note that if there is an insertion at Offset in the current replacements, - // \p Offset will be shifted to Offset + Length in inserted text. - unsigned getShiftedCodePosition(unsigned Position) const; + // If \p includeInsAtPos is true and there is an insertion at Offset in the + // current replacements, \p Offset will be shifted to Offset + Length in + // inserted text. Otherwise, the insertion at Offset will not be counted in. + unsigned getShiftedCodePosition(unsigned Position, bool includeInsAtPos = true) const; unsigned size() const { return Replaces.size(); } diff --git a/clang/lib/Tooling/Core/Replacement.cpp b/clang/lib/Tooling/Core/Replacement.cpp index 269f17a6db4cfc..95a3b62f47c708 100644 --- a/clang/lib/Tooling/Core/Replacement.cpp +++ b/clang/lib/Tooling/Core/Replacement.cpp @@ -544,10 +544,13 @@ std::vector Replacements::getAffectedRanges() const { return combineAndSortRanges(ChangedRanges); } -unsigned Replacements::getShiftedCodePosition(unsigned Position) const { +unsigned Replacements::getShiftedCodePosition(unsigned Position, + bool includeInsAtPos) const { unsigned Offset = 0; for (const auto &R : Replaces) { -if (R.getOffset() + R.getLength() <= Position) { +unsigned End = R.getOffset() + R.getLength(); +if (End <= Position +&& (includeInsAtPos || (End < Position || R.getLength() > 0))) { Offset += R.getReplacementText().size() - R.getLength(); continue; } ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[libclc] [libclc] Fix a couple of issues preventing in-tree builds (PR #87505)
mgorny wrote: This change broke standalone build against LLVM dylib — it now insists on linking to non-existing static libraries: ``` FAILED: prepare_builtins : && /usr/lib/ccache/bin/x86_64-pc-linux-gnu-g++ -march=znver2 --param=l1-cache-size=32 --param=l1-cache-line-size=64 -O2 -pipe -frecord-gcc-switches -Wl,-O1 -Wl,--as-needed -Wl,--defsym=__gentoo_check_ldflags__=0 -Wl,-rpath-link, -Wl,--gc-sections CMakeFiles/prepare_builtins.dir/utils/prepare-builtins.cpp.o -o prepare_builtins -Wl,-rpath,"\$ORIGIN/../lib64:/usr/lib/llvm/17/lib64" -lLLVMBitReader -lLLVMBitWriter -lLLVMCore -lLLVMIRReader /usr/lib/llvm/17/lib64/libLLVMSupport.a -lrt -ldl -lm /usr/lib64/libz3.so /usr/lib64/libz.so /usr/lib64/libzstd.so /usr/lib64/libtinfo.so /usr/lib/llvm/17/lib64/libLLVMDemangle.a && : /usr/lib/gcc/x86_64-pc-linux-gnu/13/../../../../x86_64-pc-linux-gnu/bin/ld: cannot find -lLLVMBitReader: No such file or directory /usr/lib/gcc/x86_64-pc-linux-gnu/13/../../../../x86_64-pc-linux-gnu/bin/ld: cannot find -lLLVMBitWriter: No such file or directory /usr/lib/gcc/x86_64-pc-linux-gnu/13/../../../../x86_64-pc-linux-gnu/bin/ld: cannot find -lLLVMCore: No such file or directory /usr/lib/gcc/x86_64-pc-linux-gnu/13/../../../../x86_64-pc-linux-gnu/bin/ld: cannot find -lLLVMIRReader: No such file or directory collect2: error: ld returned 1 exit status ``` Given that it apparently doesn't fix in-tree builds fully, please revert and let's figure out how to do it properly without breaking its primary use case. https://github.com/llvm/llvm-project/pull/87505 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][StaticAnalyzer] Adding getentropy to CStringChecker. (PR #83675)
https://github.com/devnexen updated https://github.com/llvm/llvm-project/pull/83675 >From 39a9b19e266275624e472bd3fbd5fdab542a5c31 Mon Sep 17 00:00:00 2001 From: David Carlier Date: Sat, 2 Mar 2024 14:56:15 + Subject: [PATCH] [clang][StaticAnalyzer] Adding getentropy to CStringChecker. since it went way beyond just openbsd, adding basic check for possible misusage. --- .../Checkers/CStringChecker.cpp | 49 ++ clang/test/Analysis/bstring.c | 67 +++ 2 files changed, 116 insertions(+) diff --git a/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp index 63844563de44f1..25b7e131d84619 100644 --- a/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp @@ -186,6 +186,8 @@ class CStringChecker : public Checker< eval::Call, &CStringChecker::evalSprintf}, {{CDM::CLibraryMaybeHardened, {"snprintf"}, std::nullopt, 3}, &CStringChecker::evalSnprintf}, + {{CDM::CLibraryMaybeHardened, {"getentropy"}, 2}, + &CStringChecker::evalGetentropy}, }; // These require a bit of special handling. @@ -240,6 +242,7 @@ class CStringChecker : public Checker< eval::Call, void evalSnprintf(CheckerContext &C, const CallEvent &Call) const; void evalSprintfCommon(CheckerContext &C, const CallEvent &Call, bool IsBounded) const; + void evalGetentropy(CheckerContext &C, const CallEvent &Call) const; // Utility methods std::pair @@ -2535,6 +2538,52 @@ void CStringChecker::evalSprintfCommon(CheckerContext &C, const CallEvent &Call, C.addTransition(State); } +void CStringChecker::evalGetentropy(CheckerContext &C, const CallEvent &Call) const { + DestinationArgExpr Buffer = {{Call.getArgExpr(0), 0}}; + SizeArgExpr Size = {{Call.getArgExpr(1), 1}}; + ProgramStateRef State = C.getState(); + SValBuilder &SVB = C.getSValBuilder(); + + std::optional SizeVal = C.getSVal(Size.Expression).getAs(); + if (!SizeVal) +return; + + std::optional MaxLength = SVB.makeIntVal(256, C.getASTContext().IntTy).getAs(); + QualType SizeTy = Size.Expression->getType(); + + SVal Buff = C.getSVal(Buffer.Expression); + auto [StateZeroSize, StateNonZeroSize] = + assumeZero(C, State, *SizeVal, SizeTy); + + if (StateZeroSize && !StateNonZeroSize) { +State = invalidateDestinationBufferBySize(C, State, Buffer.Expression, Buff, *SizeVal, SizeTy); +C.addTransition(State); +return; + } + + State = checkNonNull(C, StateNonZeroSize, Buffer, Buff); + if (!State) +return; + + State = CheckBufferAccess(C, State, Buffer, Size, AccessKind::write); + if (!State) +return; + + QualType cmpTy = C.getSValBuilder().getConditionType(); + auto [sizeAboveLimit, sizeNotAboveLimit] = State->assume( +SVB + .evalBinOpNN(State, BO_GT, *SizeVal, *MaxLength, cmpTy) + .castAs()); + if (sizeAboveLimit && !sizeNotAboveLimit) { +emitOutOfBoundsBug(C, sizeAboveLimit, Buffer.Expression, "must be smaller than or equal to 256"); + } else { +State = invalidateDestinationBufferBySize(C, sizeNotAboveLimit, Buffer.Expression, +Buff, +*SizeVal, SizeTy); +C.addTransition(State); + } +} + //===--===// // The driver method, and other Checker callbacks. //===--===// diff --git a/clang/test/Analysis/bstring.c b/clang/test/Analysis/bstring.c index f015e0b5d9fb7b..1c4810b499b0a9 100644 --- a/clang/test/Analysis/bstring.c +++ b/clang/test/Analysis/bstring.c @@ -529,3 +529,70 @@ void nocrash_on_locint_offset(void *addr, void* from, struct S s) { size_t iAdd = (size_t) addr; memcpy(((void *) &(s.f)), from, iAdd); } + +//===--===// +// getentropy() +//===--===// + +int getentropy(void *d, size_t n); + +int getentropy0(void) { + char buf[16] = {0}; + + int r = getentropy(buf, sizeof(buf)); // no-warning + return r; +} + +int getentropy1(void) { + char buf[257] = {0}; + + int r = getentropy(buf, 256); // no-warning + return r; +} + +int getentropy2(void) { + char buf[1024] = {0}; + + int r = getentropy(buf, sizeof(buf)); // expected-warning{{must be smaller than or equal to 256}} + return r; +} + +int getentropy3(void) { + char buf[256] = {0}; + + int r = getentropy(buf, 0); // no-warning + return r; +} + +int getentropy4(size_t arg) { + char buf[256] = {0}; + + int r = getentropy(buf, arg); // no-warning + return r; +} + +int do_something(size_t arg) { + char buf[256] = {0}; + int r = getentropy(buf, arg); // no-warning + return r; +} + +int getentropy5(size_t arg) { + char buf[257] = {0}
[clang] [compiler-rt] Fix "[clang][UBSan] Add implicit conversion check for bitfields" (PR #87761)
Zonotora wrote: @vitalybuka all green? https://github.com/llvm/llvm-project/pull/87761 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Add CodeGen tests for CWG 6xx issues (PR #87876)
https://github.com/Endilll created https://github.com/llvm/llvm-project/pull/87876 This patch covers [CWG605](https://cplusplus.github.io/CWG/issues/605.html) "Linkage of explicit specializations", [CWG650](https://cplusplus.github.io/CWG/issues/650.html) "Order of destruction for temporaries bound to the returned value of a function", [CWG653](https://cplusplus.github.io/CWG/issues/653.html) "Copy assignment of unions", [CWG658](https://cplusplus.github.io/CWG/issues/658.html) "Defining `reinterpret_cast` for pointer types", [CWG661](https://cplusplus.github.io/CWG/issues/661.html) "Semantics of arithmetic comparisons", [CWG672](https://cplusplus.github.io/CWG/issues/672.html) "Sequencing of initialization in _new-expression_s". [CWG624](https://cplusplus.github.io/CWG/issues/624.html) "Overflow in calculating size of allocation" and [CWG668](https://cplusplus.github.io/CWG/issues/668.html) "Throwing an exception from the destructor of a local static object" are marked as requiring libc++abi tests. >From fd186c00525753fc1bf1cc61cc11841a53373a8c Mon Sep 17 00:00:00 2001 From: Vlad Serebrennikov Date: Sat, 6 Apr 2024 14:05:24 +0300 Subject: [PATCH] [clang] Add CodeGen tests for CWG 6xx issues This patch covers [CWG605](https://cplusplus.github.io/CWG/issues/605.html) "Linkage of explicit specializations", [CWG650](https://cplusplus.github.io/CWG/issues/650.html) "Order of destruction for temporaries bound to the returned value of a function", [CWG653](https://cplusplus.github.io/CWG/issues/653.html) "Copy assignment of unions", [CWG658](https://cplusplus.github.io/CWG/issues/658.html) "Defining `reinterpret_cast` for pointer types", [CWG661](https://cplusplus.github.io/CWG/issues/661.html) "Semantics of arithmetic comparisons", [CWG672](https://cplusplus.github.io/CWG/issues/672.html) "Sequencing of initialization in _new-expression_s". [CWG624](https://cplusplus.github.io/CWG/issues/624.html) "Overflow in calculating size of allocation" and [CWG668](https://cplusplus.github.io/CWG/issues/668.html) "Throwing an exception from the destructor of a local static object" are marked as requiring libc++abi tests. --- clang/test/CXX/drs/dr605.cpp | 23 + clang/test/CXX/drs/dr650.cpp | 40 clang/test/CXX/drs/dr653.cpp | 25 ++ clang/test/CXX/drs/dr658.cpp | 25 ++ clang/test/CXX/drs/dr661.cpp | 29 ++ clang/test/CXX/drs/dr672.cpp | 32 + clang/test/CXX/drs/dr6xx.cpp | 16 +++ clang/www/cxx_dr_status.html | 12 +-- 8 files changed, 188 insertions(+), 14 deletions(-) create mode 100644 clang/test/CXX/drs/dr605.cpp create mode 100644 clang/test/CXX/drs/dr650.cpp create mode 100644 clang/test/CXX/drs/dr653.cpp create mode 100644 clang/test/CXX/drs/dr658.cpp create mode 100644 clang/test/CXX/drs/dr661.cpp create mode 100644 clang/test/CXX/drs/dr672.cpp diff --git a/clang/test/CXX/drs/dr605.cpp b/clang/test/CXX/drs/dr605.cpp new file mode 100644 index 00..6c212d8dabc06c --- /dev/null +++ b/clang/test/CXX/drs/dr605.cpp @@ -0,0 +1,23 @@ +// RUN: %clang_cc1 -std=c++98 %s -triple x86_64-linux-gnu -emit-llvm -o - -fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt -n | FileCheck %s --check-prefixes CHECK +// RUN: %clang_cc1 -std=c++11 %s -triple x86_64-linux-gnu -emit-llvm -o - -fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt -n | FileCheck %s --check-prefixes CHECK +// RUN: %clang_cc1 -std=c++14 %s -triple x86_64-linux-gnu -emit-llvm -o - -fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt -n | FileCheck %s --check-prefixes CHECK +// RUN: %clang_cc1 -std=c++17 %s -triple x86_64-linux-gnu -emit-llvm -o - -fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt -n | FileCheck %s --check-prefixes CHECK +// RUN: %clang_cc1 -std=c++20 %s -triple x86_64-linux-gnu -emit-llvm -o - -fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt -n | FileCheck %s --check-prefixes CHECK +// RUN: %clang_cc1 -std=c++23 %s -triple x86_64-linux-gnu -emit-llvm -o - -fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt -n | FileCheck %s --check-prefixes CHECK +// RUN: %clang_cc1 -std=c++2c %s -triple x86_64-linux-gnu -emit-llvm -o - -fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt -n | FileCheck %s --check-prefixes CHECK + +namespace dr605 { // dr605: 2.7 + +template +static T f(T t) {} + +template <> +int f(int t) {} + +void g(int a) { + f(a); +} + +} // namespace dr605 + +// CHECK: define internal {{.*}} i32 @int dr605::f(int) diff --git a/clang/test/CXX/drs/dr650.cpp b/clang/test/CXX/drs/dr650.cpp new file mode 100644 index 00..715b4fdf04a7f0 --- /dev/null +++ b/clang/test/CXX/drs/dr650.cpp @@ -0,0 +1,40 @@ +// RUN: %clang_cc1 -std=c++98 %s -triple x86_64-linux-gnu -emit-llvm -o - -fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt
[clang] [clang] Add CodeGen tests for CWG 6xx issues (PR #87876)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Vlad Serebrennikov (Endilll) Changes This patch covers [CWG605](https://cplusplus.github.io/CWG/issues/605.html) "Linkage of explicit specializations", [CWG650](https://cplusplus.github.io/CWG/issues/650.html) "Order of destruction for temporaries bound to the returned value of a function", [CWG653](https://cplusplus.github.io/CWG/issues/653.html) "Copy assignment of unions", [CWG658](https://cplusplus.github.io/CWG/issues/658.html) "Defining `reinterpret_cast` for pointer types", [CWG661](https://cplusplus.github.io/CWG/issues/661.html) "Semantics of arithmetic comparisons", [CWG672](https://cplusplus.github.io/CWG/issues/672.html) "Sequencing of initialization in _new-expression_s". [CWG624](https://cplusplus.github.io/CWG/issues/624.html) "Overflow in calculating size of allocation" and [CWG668](https://cplusplus.github.io/CWG/issues/668.html) "Throwing an exception from the destructor of a local static object" are marked as requiring libc++abi tests. --- Full diff: https://github.com/llvm/llvm-project/pull/87876.diff 8 Files Affected: - (added) clang/test/CXX/drs/dr605.cpp (+23) - (added) clang/test/CXX/drs/dr650.cpp (+40) - (added) clang/test/CXX/drs/dr653.cpp (+25) - (added) clang/test/CXX/drs/dr658.cpp (+25) - (added) clang/test/CXX/drs/dr661.cpp (+29) - (added) clang/test/CXX/drs/dr672.cpp (+32) - (modified) clang/test/CXX/drs/dr6xx.cpp (+8-8) - (modified) clang/www/cxx_dr_status.html (+6-6) ``diff diff --git a/clang/test/CXX/drs/dr605.cpp b/clang/test/CXX/drs/dr605.cpp new file mode 100644 index 00..6c212d8dabc06c --- /dev/null +++ b/clang/test/CXX/drs/dr605.cpp @@ -0,0 +1,23 @@ +// RUN: %clang_cc1 -std=c++98 %s -triple x86_64-linux-gnu -emit-llvm -o - -fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt -n | FileCheck %s --check-prefixes CHECK +// RUN: %clang_cc1 -std=c++11 %s -triple x86_64-linux-gnu -emit-llvm -o - -fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt -n | FileCheck %s --check-prefixes CHECK +// RUN: %clang_cc1 -std=c++14 %s -triple x86_64-linux-gnu -emit-llvm -o - -fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt -n | FileCheck %s --check-prefixes CHECK +// RUN: %clang_cc1 -std=c++17 %s -triple x86_64-linux-gnu -emit-llvm -o - -fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt -n | FileCheck %s --check-prefixes CHECK +// RUN: %clang_cc1 -std=c++20 %s -triple x86_64-linux-gnu -emit-llvm -o - -fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt -n | FileCheck %s --check-prefixes CHECK +// RUN: %clang_cc1 -std=c++23 %s -triple x86_64-linux-gnu -emit-llvm -o - -fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt -n | FileCheck %s --check-prefixes CHECK +// RUN: %clang_cc1 -std=c++2c %s -triple x86_64-linux-gnu -emit-llvm -o - -fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt -n | FileCheck %s --check-prefixes CHECK + +namespace dr605 { // dr605: 2.7 + +template +static T f(T t) {} + +template <> +int f(int t) {} + +void g(int a) { + f(a); +} + +} // namespace dr605 + +// CHECK: define internal {{.*}} i32 @int dr605::f(int) diff --git a/clang/test/CXX/drs/dr650.cpp b/clang/test/CXX/drs/dr650.cpp new file mode 100644 index 00..715b4fdf04a7f0 --- /dev/null +++ b/clang/test/CXX/drs/dr650.cpp @@ -0,0 +1,40 @@ +// RUN: %clang_cc1 -std=c++98 %s -triple x86_64-linux-gnu -emit-llvm -o - -fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt -n | FileCheck %s --check-prefixes CHECK +// RUN: %clang_cc1 -std=c++11 %s -triple x86_64-linux-gnu -emit-llvm -o - -fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt -n | FileCheck %s --check-prefixes CHECK +// RUN: %clang_cc1 -std=c++14 %s -triple x86_64-linux-gnu -emit-llvm -o - -fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt -n | FileCheck %s --check-prefixes CHECK +// RUN: %clang_cc1 -std=c++17 %s -triple x86_64-linux-gnu -emit-llvm -o - -fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt -n | FileCheck %s --check-prefixes CHECK +// RUN: %clang_cc1 -std=c++20 %s -triple x86_64-linux-gnu -emit-llvm -o - -fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt -n | FileCheck %s --check-prefixes CHECK +// RUN: %clang_cc1 -std=c++23 %s -triple x86_64-linux-gnu -emit-llvm -o - -fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt -n | FileCheck %s --check-prefixes CHECK +// RUN: %clang_cc1 -std=c++2c %s -triple x86_64-linux-gnu -emit-llvm -o - -fexceptions -fcxx-exceptions -pedantic-errors | llvm-cxxfilt -n | FileCheck %s --check-prefixes CHECK + +#if __cplusplus == 199711L +#define NOTHROW throw() +#else +#define NOTHROW noexcept(true) +#endif + +namespace dr650 { // dr650: 2.8 + +struct Q { + ~Q() NOTHROW; +}; + +struct R { + ~R() NOTHROW; +}; + +struct S { + ~S() NOTHROW; +}; + +const S& f() { + Q q; + return (R(), S()); +} + +} // namespace dr650 + +// CHECK-LABEL: define {{.*}}
[clang] [clang][NFC] Introduce `SemaBase` (PR #87634)
https://github.com/Endilll closed https://github.com/llvm/llvm-project/pull/87634 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] d288444 - [clang][NFC] Introduce `SemaBase` (#87634)
Author: Vlad Serebrennikov Date: 2024-04-06T15:10:48+04:00 New Revision: d288472e92a8282f4d215a27128ac83a26b9 URL: https://github.com/llvm/llvm-project/commit/d288472e92a8282f4d215a27128ac83a26b9 DIFF: https://github.com/llvm/llvm-project/commit/d288472e92a8282f4d215a27128ac83a26b9.diff LOG: [clang][NFC] Introduce `SemaBase` (#87634) This is a follow-up to #84184. Multiple reviewers there pointed out to me that we should have a common base class for `Sema` and `SemaOpenACC` to avoid code duplication for common helpers like `getLangOpts()`. On top of that, `Diag()` function was requested for `SemaOpenACC`. This patch delivers both. The intent is to keep `SemaBase` as small as possible, as things there are globally available across `Sema` and its parts without any additional effort from usage side. Overused, this can undermine the whole endeavor of splitting `Sema` apart. Apart of shuffling code around, this patch introduces a helper private function `SemaDiagnosticBuilder::getDeviceDeferredDiags()`, the sole purpose of which is to encapsulate member access into (incomplete) `Sema` for function templates defined in the header, where `Sema` can't be complete. Added: clang/include/clang/Sema/SemaBase.h clang/lib/Sema/SemaBase.cpp Modified: clang/include/clang/Sema/Sema.h clang/include/clang/Sema/SemaOpenACC.h clang/lib/Sema/CMakeLists.txt clang/lib/Sema/Sema.cpp clang/lib/Sema/SemaOpenACC.cpp Removed: diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h index f52816e12efe47..f49bc724c96c89 100644 --- a/clang/include/clang/Sema/Sema.h +++ b/clang/include/clang/Sema/Sema.h @@ -55,6 +55,7 @@ #include "clang/Sema/ObjCMethodList.h" #include "clang/Sema/Ownership.h" #include "clang/Sema/Scope.h" +#include "clang/Sema/SemaBase.h" #include "clang/Sema/SemaConcept.h" #include "clang/Sema/TypoCorrection.h" #include "clang/Sema/Weak.h" @@ -422,7 +423,7 @@ enum class TemplateDeductionResult { /// Sema - This implements semantic analysis and AST building for C. /// \nosubgrouping -class Sema final { +class Sema final : public SemaBase { // Table of Contents // - // 1. Semantic Analysis (Sema.cpp) @@ -512,195 +513,6 @@ class Sema final { /// void addExternalSource(ExternalSemaSource *E); - /// Helper class that creates diagnostics with optional - /// template instantiation stacks. - /// - /// This class provides a wrapper around the basic DiagnosticBuilder - /// class that emits diagnostics. ImmediateDiagBuilder is - /// responsible for emitting the diagnostic (as DiagnosticBuilder - /// does) and, if the diagnostic comes from inside a template - /// instantiation, printing the template instantiation stack as - /// well. - class ImmediateDiagBuilder : public DiagnosticBuilder { -Sema &SemaRef; -unsigned DiagID; - - public: -ImmediateDiagBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID) -: DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {} -ImmediateDiagBuilder(DiagnosticBuilder &&DB, Sema &SemaRef, unsigned DiagID) -: DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {} - -// This is a cunning lie. DiagnosticBuilder actually performs move -// construction in its copy constructor (but due to varied uses, it's not -// possible to conveniently express this as actual move construction). So -// the default copy ctor here is fine, because the base class disables the -// source anyway, so the user-defined ~ImmediateDiagBuilder is a safe no-op -// in that case anwyay. -ImmediateDiagBuilder(const ImmediateDiagBuilder &) = default; - -~ImmediateDiagBuilder() { - // If we aren't active, there is nothing to do. - if (!isActive()) -return; - - // Otherwise, we need to emit the diagnostic. First clear the diagnostic - // builder itself so it won't emit the diagnostic in its own destructor. - // - // This seems wasteful, in that as written the DiagnosticBuilder dtor will - // do its own needless checks to see if the diagnostic needs to be - // emitted. However, because we take care to ensure that the builder - // objects never escape, a sufficiently smart compiler will be able to - // eliminate that code. - Clear(); - - // Dispatch to Sema to emit the diagnostic. - SemaRef.EmitCurrentDiagnostic(DiagID); -} - -/// Teach operator<< to produce an object of the correct type. -template -friend const ImmediateDiagBuilder & -operator<<(const ImmediateDiagBuilder &Diag, const T &Value) { - const DiagnosticBuilder &BaseDiag = Diag; - BaseDiag << Value; - return Diag; -} - -// It is necessary to limit this to rvalue reference to avoid calling this -// function with a bitfield lvalue argument since non-const reference to
[clang] [clang] Reject incomplete types in `__is_layout_compatible()` (PR #87869)
https://github.com/cor3ntin approved this pull request. https://github.com/llvm/llvm-project/pull/87869 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-tools-extra] [clangd] Fix: exclude insertions at end of CursorPlaceholder in formatting (PR #87746)
roife wrote: I'm not sure why the test is showing as failed since all tests of clangd have passed; I didn't find any failed tests in the log. https://github.com/llvm/llvm-project/pull/87746 ___ 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 fix-its to `avoid-return-with-void-value` check (PR #81420)
https://github.com/SimplyDanny updated https://github.com/llvm/llvm-project/pull/81420 From 4b7d4a46d03c903c6834dfce5b6f379122fdb806 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Danny=20M=C3=B6sch?= Date: Sun, 11 Feb 2024 17:04:12 +0100 Subject: [PATCH 1/5] [clang-tidy] Add fix-its to `avoid-return-with-void-value` check --- .../AvoidReturnWithVoidValueCheck.cpp | 41 +++ clang-tools-extra/docs/ReleaseNotes.rst | 4 ++ .../avoid-return-with-void-value.cpp | 14 ++- 3 files changed, 49 insertions(+), 10 deletions(-) diff --git a/clang-tools-extra/clang-tidy/readability/AvoidReturnWithVoidValueCheck.cpp b/clang-tools-extra/clang-tidy/readability/AvoidReturnWithVoidValueCheck.cpp index e3400f614fa564..1202eeebd06674 100644 --- a/clang-tools-extra/clang-tidy/readability/AvoidReturnWithVoidValueCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/AvoidReturnWithVoidValueCheck.cpp @@ -10,16 +10,18 @@ #include "clang/AST/Stmt.h" #include "clang/ASTMatchers/ASTMatchFinder.h" #include "clang/ASTMatchers/ASTMatchers.h" +#include "clang/Basic/Diagnostic.h" +#include "clang/Lex/Lexer.h" using namespace clang::ast_matchers; namespace clang::tidy::readability { -static constexpr auto IgnoreMacrosName = "IgnoreMacros"; -static constexpr auto IgnoreMacrosDefault = true; +static constexpr char IgnoreMacrosName[] = "IgnoreMacros"; +static const bool IgnoreMacrosDefault = true; -static constexpr auto StrictModeName = "StrictMode"; -static constexpr auto StrictModeDefault = true; +static constexpr char StrictModeName[] = "StrictMode"; +static const bool StrictModeDefault = true; AvoidReturnWithVoidValueCheck::AvoidReturnWithVoidValueCheck( StringRef Name, ClangTidyContext *Context) @@ -40,12 +42,35 @@ void AvoidReturnWithVoidValueCheck::registerMatchers(MatchFinder *Finder) { void AvoidReturnWithVoidValueCheck::check( const MatchFinder::MatchResult &Result) { const auto *VoidReturn = Result.Nodes.getNodeAs("void_return"); - if (IgnoreMacros && VoidReturn->getBeginLoc().isMacroID()) + if (IgnoreMacros && VoidReturn->getBeginLoc().isMacroID()) { return; - if (!StrictMode && !Result.Nodes.getNodeAs("compound_parent")) + } + const auto *SurroundingBlock = + Result.Nodes.getNodeAs("compound_parent"); + if (!StrictMode && !SurroundingBlock) { return; - diag(VoidReturn->getBeginLoc(), "return statement within a void function " - "should not have a specified return value"); + } + DiagnosticBuilder Diag = diag(VoidReturn->getBeginLoc(), +"return statement within a void function " +"should not have a specified return value"); + std::optional SemicolonPos = + Lexer::findNextToken(VoidReturn->getRetValue()->getEndLoc(), + *Result.SourceManager, getLangOpts()); + if (!SemicolonPos) { +return; + } + const StringRef ReturnExpr = + Lexer::getSourceText(CharSourceRange::getTokenRange( + VoidReturn->getRetValue()->getSourceRange()), + *Result.SourceManager, getLangOpts()); + std::string Replacement = (ReturnExpr + "; return;").str(); + if (!SurroundingBlock) { +Replacement = "{" + Replacement + "}"; + } + Diag << FixItHint::CreateReplacement( + CharSourceRange::getTokenRange(VoidReturn->getBeginLoc(), + SemicolonPos->getEndLoc()), + Replacement); } void AvoidReturnWithVoidValueCheck::storeOptions( diff --git a/clang-tools-extra/docs/ReleaseNotes.rst b/clang-tools-extra/docs/ReleaseNotes.rst index 34bad7e624630c..2babb1406b9776 100644 --- a/clang-tools-extra/docs/ReleaseNotes.rst +++ b/clang-tools-extra/docs/ReleaseNotes.rst @@ -255,6 +255,10 @@ Changes in existing checks analyzed, se the check now handles the common patterns `const auto e = (*vector_ptr)[i]` and `const auto e = vector_ptr->at(i);`. +- Improved :doc:`readability-avoid-return-with-void-value + ` check by adding + fix-its. + - Improved :doc:`readability-duplicate-include ` check by excluding include directives that form the filename using macro. diff --git a/clang-tools-extra/test/clang-tidy/checkers/readability/avoid-return-with-void-value.cpp b/clang-tools-extra/test/clang-tidy/checkers/readability/avoid-return-with-void-value.cpp index f00407c99ce570..0d269ceee82bc9 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/readability/avoid-return-with-void-value.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/readability/avoid-return-with-void-value.cpp @@ -12,14 +12,18 @@ void f2() { return f1(); // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: return statement within a void function should not have a specified return value [readability-avoid-return-with-void-value] // CHECK-MESSAGES-LENIENT: :[[@LINE-2]]:5: warning: return statement within a void function should not have a speci
[clang] [clang-tools-extra] [clangd] Fix: exclude insertions at end of CursorPlaceholder in formatting (PR #87746)
github-actions[bot] wrote: :warning: C/C++ code formatter, clang-format found issues in your code. :warning: You can test this locally with the following command: ``bash git-clang-format --diff d4cd65ecf2546e509f43363f96364c976f49b9da 03fe6bec808cb968c35f1bad7432ea6155ed0115 -- clang-tools-extra/clangd/Format.cpp clang-tools-extra/clangd/unittests/FormatTests.cpp clang/include/clang/Tooling/Core/Replacement.h clang/lib/Tooling/Core/Replacement.cpp `` View the diff from clang-format here. ``diff diff --git a/clang-tools-extra/clangd/unittests/FormatTests.cpp b/clang-tools-extra/clangd/unittests/FormatTests.cpp index 22c19fefc6..72e662a070 100644 --- a/clang-tools-extra/clangd/unittests/FormatTests.cpp +++ b/clang-tools-extra/clangd/unittests/FormatTests.cpp @@ -317,7 +317,7 @@ vector x = {1, 2, 3}^ TEST(FormatIncremental, InsertBraces) { format::FormatStyle Style = -format::getGoogleStyle(format::FormatStyle::LK_Cpp); + format::getGoogleStyle(format::FormatStyle::LK_Cpp); Style.InsertBraces = true; expectAfterNewline(R"cpp( int main() { diff --git a/clang/include/clang/Tooling/Core/Replacement.h b/clang/include/clang/Tooling/Core/Replacement.h index 69fe5186df..d2b79e4ab0 100644 --- a/clang/include/clang/Tooling/Core/Replacement.h +++ b/clang/include/clang/Tooling/Core/Replacement.h @@ -271,7 +271,8 @@ public: // If \p includeInsAtPos is true and there is an insertion at Offset in the // current replacements, \p Offset will be shifted to Offset + Length in // inserted text. Otherwise, the insertion at Offset will not be counted in. - unsigned getShiftedCodePosition(unsigned Position, bool includeInsAtPos = true) const; + unsigned getShiftedCodePosition(unsigned Position, + bool includeInsAtPos = true) const; unsigned size() const { return Replaces.size(); } diff --git a/clang/lib/Tooling/Core/Replacement.cpp b/clang/lib/Tooling/Core/Replacement.cpp index 95a3b62f47..07d3e4e587 100644 --- a/clang/lib/Tooling/Core/Replacement.cpp +++ b/clang/lib/Tooling/Core/Replacement.cpp @@ -549,8 +549,8 @@ unsigned Replacements::getShiftedCodePosition(unsigned Position, unsigned Offset = 0; for (const auto &R : Replaces) { unsigned End = R.getOffset() + R.getLength(); -if (End <= Position -&& (includeInsAtPos || (End < Position || R.getLength() > 0))) { +if (End <= Position && +(includeInsAtPos || (End < Position || R.getLength() > 0))) { Offset += R.getReplacementText().size() - R.getLength(); continue; } `` https://github.com/llvm/llvm-project/pull/87746 ___ 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 fix-its to `avoid-return-with-void-value` check (PR #81420)
SimplyDanny wrote: @PiotrZSL: Friendly ping. https://github.com/llvm/llvm-project/pull/81420 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-tools-extra] [clangd] Fix: exclude insertions at end of CursorPlaceholder in formatting (PR #87746)
zyn0217 wrote: AFAIK the Windows CI has been rather fragile recently, and I think you could probably ignore it. https://github.com/llvm/llvm-project/pull/87746 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 1803d67 - [Driver] Add missing include of std::set.
Author: Florian Hahn Date: 2024-04-06T14:56:35+01:00 New Revision: 1803d675004bb512051d2df7e1ae3ea95692fc67 URL: https://github.com/llvm/llvm-project/commit/1803d675004bb512051d2df7e1ae3ea95692fc67 DIFF: https://github.com/llvm/llvm-project/commit/1803d675004bb512051d2df7e1ae3ea95692fc67.diff LOG: [Driver] Add missing include of std::set. 4ddd4ed7fe15a added a use of std::set without including it. With some recent libc++, std::set isn't included transitively causing build failures. Add explicit include. Added: Modified: clang/lib/Driver/ToolChains/AIX.cpp Removed: diff --git a/clang/lib/Driver/ToolChains/AIX.cpp b/clang/lib/Driver/ToolChains/AIX.cpp index 7a62b0f9aec419..3f10888596a29a 100644 --- a/clang/lib/Driver/ToolChains/AIX.cpp +++ b/clang/lib/Driver/ToolChains/AIX.cpp @@ -17,6 +17,8 @@ #include "llvm/ProfileData/InstrProf.h" #include "llvm/Support/Path.h" +#include + using AIX = clang::driver::toolchains::AIX; using namespace clang::driver; using namespace clang::driver::tools; ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][Sema] Track trivial-relocatability as a type trait (PR #84621)
dangelog wrote: I perfectly understand that Clang wants to implement the semantics that are being adopted by standard C++, so it wants to reserve `__is_trivially_relocatable` to match those semantics. The amount of comments in this PR is however a strong signal that standard C++ is going directly against widely established practices. Qt won't need P2786 but P1144, because it uses trivial relocation not only ① for vector reallocation (that is: move *construction* + destruction via trivial relocation) but also ② for vector erase/insert (that is: move *assignment* (+destruction) via trivial relocation). It would not make sense for a type with a user-declared assignment operator to be considered TR for Qt. Upstream C++ seems to be fine with just providing ① (via P2786), but that leaves a huge number of optimizations on the plate: vector insert, erase, swaps and swap-based algorithms, etc.; which is a total shame. I perfectly understand that some types (like the aforementioned "reference wrappers", pmr::string, etc.) only allow ① semantics. If upstream cares about them so much and doesn't want to lose the opportunity of optimizing vector reallocation for them, why haven't they landed _two_ type traits? A generic "is trivial relocatable" (that captures construction and assignment) and a more specific one (that only captures construction; a subset of the first). It would make perfect sense to me to capture different semantics via different traits. Not only that, but P2786 has squatted the "trivial relocatable" name for the trait, which really belongs to the _more general_ trait. Oh well, sorry for the rant :-) > I don't think this accurate, If a library requires additional constraint, > they can add them (in addition to checking the type trait), But this isn't useful at all; every library has already invented its own constraints and type traits. The point of having a language-based solution is that the "is TR" property gets automatically propagated when you compose types. No library solution can achieve that, especially lacking reflection. > I don't think we should put efforts into supporting a P1144-based approach. Do you mean that you would reject a proposal that adds Clang-specific trait (with another name) that implements P1144's semantics? https://github.com/llvm/llvm-project/pull/84621 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-tools-extra] [clangd] Fix: exclude insertions at end of CursorPlaceholder in formatting (PR #87746)
https://github.com/roife updated https://github.com/llvm/llvm-project/pull/87746 >From b89d456b4ef5ae2311e448b939639c59b9c1aa23 Mon Sep 17 00:00:00 2001 From: roife Date: Thu, 4 Apr 2024 14:54:08 +0800 Subject: [PATCH] [clangd] Fix: exclude insertions at the end of placeholder This commit introduces a new param 'includeInsAtPos' for 'getShiftedCodePosition', which is defaulted to be true. If 'includeInsAtPos' is true, the insertion at the 'Position' will be counted in. Otherwise, the insertion will not be counted in. Changes made: - Added new param 'includeInsAtPos' to 'getShiftedCodePosition'. - Set 'includeInsAtPos' to be false when calculate the end position of 'CursorPlaceholder' in 'formatIncremental' of clangd. Fixes #71983 --- clang-tools-extra/clangd/Format.cpp | 2 +- .../clangd/unittests/FormatTests.cpp | 19 +++ .../include/clang/Tooling/Core/Replacement.h | 8 +--- clang/lib/Tooling/Core/Replacement.cpp| 7 +-- 4 files changed, 30 insertions(+), 6 deletions(-) diff --git a/clang-tools-extra/clangd/Format.cpp b/clang-tools-extra/clangd/Format.cpp index 272a34d4ed7972..901a709e2e3934 100644 --- a/clang-tools-extra/clangd/Format.cpp +++ b/clang-tools-extra/clangd/Format.cpp @@ -341,7 +341,7 @@ formatIncremental(llvm::StringRef OriginalCode, unsigned OriginalCursor, unsigned FormattedCursorStart = FormattingChanges.getShiftedCodePosition(Cursor), FormattedCursorEnd = FormattingChanges.getShiftedCodePosition( - Cursor + Incremental.CursorPlaceholder.size()); + Cursor + Incremental.CursorPlaceholder.size(), false); tooling::Replacements RemoveCursorPlaceholder( tooling::Replacement(Filename, FormattedCursorStart, FormattedCursorEnd - FormattedCursorStart, "")); diff --git a/clang-tools-extra/clangd/unittests/FormatTests.cpp b/clang-tools-extra/clangd/unittests/FormatTests.cpp index f7384a1bc63c99..72e662a07062d3 100644 --- a/clang-tools-extra/clangd/unittests/FormatTests.cpp +++ b/clang-tools-extra/clangd/unittests/FormatTests.cpp @@ -315,6 +315,25 @@ vector x = {1, 2, 3}^ )cpp"); } +TEST(FormatIncremental, InsertBraces) { + format::FormatStyle Style = + format::getGoogleStyle(format::FormatStyle::LK_Cpp); + Style.InsertBraces = true; + expectAfterNewline(R"cpp( +int main() { + while (true) +^ +} +)cpp", + R"cpp( +int main() { + while (true) { + + }^ +} +)cpp", + Style); +} } // namespace } // namespace clangd } // namespace clang diff --git a/clang/include/clang/Tooling/Core/Replacement.h b/clang/include/clang/Tooling/Core/Replacement.h index f9452111e147f1..d2b79e4ab07ae7 100644 --- a/clang/include/clang/Tooling/Core/Replacement.h +++ b/clang/include/clang/Tooling/Core/Replacement.h @@ -268,9 +268,11 @@ class Replacements { std::vector getAffectedRanges() const; // Returns the new offset in the code after replacements being applied. - // Note that if there is an insertion at Offset in the current replacements, - // \p Offset will be shifted to Offset + Length in inserted text. - unsigned getShiftedCodePosition(unsigned Position) const; + // If \p includeInsAtPos is true and there is an insertion at Offset in the + // current replacements, \p Offset will be shifted to Offset + Length in + // inserted text. Otherwise, the insertion at Offset will not be counted in. + unsigned getShiftedCodePosition(unsigned Position, + bool includeInsAtPos = true) const; unsigned size() const { return Replaces.size(); } diff --git a/clang/lib/Tooling/Core/Replacement.cpp b/clang/lib/Tooling/Core/Replacement.cpp index 269f17a6db4cfc..07d3e4e58718cb 100644 --- a/clang/lib/Tooling/Core/Replacement.cpp +++ b/clang/lib/Tooling/Core/Replacement.cpp @@ -544,10 +544,13 @@ std::vector Replacements::getAffectedRanges() const { return combineAndSortRanges(ChangedRanges); } -unsigned Replacements::getShiftedCodePosition(unsigned Position) const { +unsigned Replacements::getShiftedCodePosition(unsigned Position, + bool includeInsAtPos) const { unsigned Offset = 0; for (const auto &R : Replaces) { -if (R.getOffset() + R.getLength() <= Position) { +unsigned End = R.getOffset() + R.getLength(); +if (End <= Position && +(includeInsAtPos || (End < Position || R.getLength() > 0))) { Offset += R.getReplacementText().size() - R.getLength(); continue; } ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Ignore non-forwarded arguments if they are unnamed (PR #87832)
@@ -182,6 +182,10 @@ Changes in existing checks giving false positives for deleted functions and fix false negative when some parameters are forwarded, but other aren't. +- Improved :doc:`cppcoreguidelines-missing-std-forward EugeneZelenko wrote: Should be merged with previous entry. https://github.com/llvm/llvm-project/pull/87832 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Ignore non-forwarded arguments if they are unnamed (PR #87832)
https://github.com/SimplyDanny updated https://github.com/llvm/llvm-project/pull/87832 From b8662eb6681d86ac475f30a70740b6b83eda1de3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Danny=20M=C3=B6sch?= Date: Fri, 5 Apr 2024 23:41:50 +0200 Subject: [PATCH 1/2] [clang-tidy] Ignore non-forwarded arguments if they are unnamed --- .../cppcoreguidelines/MissingStdForwardCheck.cpp | 15 +-- clang-tools-extra/docs/ReleaseNotes.rst | 4 .../cppcoreguidelines/missing-std-forward.cpp | 3 +++ 3 files changed, 16 insertions(+), 6 deletions(-) diff --git a/clang-tools-extra/clang-tidy/cppcoreguidelines/MissingStdForwardCheck.cpp b/clang-tools-extra/clang-tidy/cppcoreguidelines/MissingStdForwardCheck.cpp index 87fd8adf997082..6817bcb24c8112 100644 --- a/clang-tools-extra/clang-tidy/cppcoreguidelines/MissingStdForwardCheck.cpp +++ b/clang-tools-extra/clang-tidy/cppcoreguidelines/MissingStdForwardCheck.cpp @@ -79,6 +79,8 @@ AST_MATCHER_P(LambdaExpr, hasCaptureDefaultKind, LambdaCaptureDefault, Kind) { return Node.getCaptureDefault() == Kind; } +AST_MATCHER(ParmVarDecl, hasAnyName) { return !Node.getName().empty(); } + } // namespace void MissingStdForwardCheck::registerMatchers(MatchFinder *Finder) { @@ -125,12 +127,13 @@ void MissingStdForwardCheck::registerMatchers(MatchFinder *Finder) { hasAncestor(expr(hasUnevaluatedContext()); Finder->addMatcher( - parmVarDecl(parmVarDecl().bind("param"), isTemplateTypeParameter(), - hasAncestor(functionDecl().bind("func")), - hasAncestor(functionDecl( - isDefinition(), equalsBoundNode("func"), ToParam, - unless(anyOf(isDeleted(), hasDescendant(std::move( -ForwardCallMatcher))), + parmVarDecl( + parmVarDecl().bind("param"), hasAnyName(), isTemplateTypeParameter(), + hasAncestor(functionDecl().bind("func")), + hasAncestor(functionDecl( + isDefinition(), equalsBoundNode("func"), ToParam, + unless(anyOf(isDeleted(), + hasDescendant(std::move(ForwardCallMatcher))), this); } diff --git a/clang-tools-extra/docs/ReleaseNotes.rst b/clang-tools-extra/docs/ReleaseNotes.rst index 456e09204fa2f9..f79d3b9f362063 100644 --- a/clang-tools-extra/docs/ReleaseNotes.rst +++ b/clang-tools-extra/docs/ReleaseNotes.rst @@ -182,6 +182,10 @@ Changes in existing checks giving false positives for deleted functions and fix false negative when some parameters are forwarded, but other aren't. +- Improved :doc:`cppcoreguidelines-missing-std-forward + ` check by ignoring + parameters without a name (unused arguments). + - Improved :doc:`cppcoreguidelines-owning-memory ` check to properly handle return type in lambdas and in nested functions. diff --git a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/missing-std-forward.cpp b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/missing-std-forward.cpp index 9a50eabf619bd5..c435a0e023ba0b 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/missing-std-forward.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/missing-std-forward.cpp @@ -198,3 +198,6 @@ struct S { }; } // namespace deleted_functions + +template +void unused_argument(F&&) {} From fd2e64dc4c70a53336e35b83d54e51f706f5fa52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Danny=20M=C3=B6sch?= Date: Sat, 6 Apr 2024 16:51:36 +0200 Subject: [PATCH 2/2] Merge entries in release notes --- clang-tools-extra/docs/ReleaseNotes.rst | 9 +++-- 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/clang-tools-extra/docs/ReleaseNotes.rst b/clang-tools-extra/docs/ReleaseNotes.rst index f79d3b9f362063..a6e248b0872123 100644 --- a/clang-tools-extra/docs/ReleaseNotes.rst +++ b/clang-tools-extra/docs/ReleaseNotes.rst @@ -179,12 +179,9 @@ Changes in existing checks - Improved :doc:`cppcoreguidelines-missing-std-forward ` check by no longer - giving false positives for deleted functions and fix false negative when some - parameters are forwarded, but other aren't. - -- Improved :doc:`cppcoreguidelines-missing-std-forward - ` check by ignoring - parameters without a name (unused arguments). + giving false positives for deleted functions, by fixing false negatives when only + a few parameters are forwarded and by ignoring parameters without a name (unused + arguments). - Improved :doc:`cppcoreguidelines-owning-memory ` check to properly handle ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Fix/interp init list unnamed bitfields (PR #87799)
@@ -0,0 +1,114 @@ +// UNSUPPORTED: asserts +// REQUIRES: asserts +// ^ this attempts to say "don't actually run this test", because it's broken sethp wrote: Yeah, the test was meant to validate the "iterating the init expressions in the init list in-order will work for C records", but it doesn't get that far: in trying to do so, I uncovered a different bug. What do you usually do, when that happens? Stop and dig out the bug? Or do you have some way you're deferring/keeping track of those kinds of things? https://github.com/llvm/llvm-project/pull/87799 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Fix/interp init list unnamed bitfields (PR #87799)
@@ -0,0 +1,114 @@ +// UNSUPPORTED: asserts +// REQUIRES: asserts +// ^ this attempts to say "don't actually run this test", because it's broken +// +// The point of this test is to demonstrate something that ExprConstant accepts, +// but Interp rejects. I had hoped to express that as the same file with two sethp wrote: 😅 sorry, I got that from the abbreviation in the commit messages. What do you call it, when you need to distinguish it from the recursive-descent implementation? https://github.com/llvm/llvm-project/pull/87799 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Fix/interp init list unnamed bitfields (PR #87799)
@@ -884,8 +884,36 @@ bool ByteCodeExprGen::visitInitList(ArrayRef Inits, if (!this->emitDupPtr(E)) return false; +// guard relatively expensive base check behind an almost-always-false sethp wrote: Maybe half so? It's an attempt to avoid a performance regression that I think I would've otherwise introduced by making this change. https://github.com/llvm/llvm-project/pull/87799 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Extend lifetime of temporaries in mem-default-init for P2718R0 (PR #86960)
https://github.com/yronglin updated https://github.com/llvm/llvm-project/pull/86960 >From 55f6fe094d50759784fdf7ba2e80616bc7bf3f4b Mon Sep 17 00:00:00 2001 From: yronglin Date: Tue, 2 Apr 2024 23:47:33 +0800 Subject: [PATCH] [Clang] Extend lifetime of temporaries in mem-default-init for P2718R0 Signed-off-by: yronglin --- clang/include/clang/Sema/Sema.h | 47 clang/lib/CodeGen/CGExpr.cpp | 62 +- clang/lib/CodeGen/CGStmt.cpp | 18 +++ clang/lib/CodeGen/CodeGenFunction.h | 31 + clang/lib/Parse/ParseDecl.cpp | 4 - clang/lib/Sema/SemaExpr.cpp | 11 +- clang/lib/Sema/SemaExprCXX.cpp| 2 +- clang/lib/Sema/SemaInit.cpp | 36 +++--- .../lib/Sema/SemaTemplateInstantiateDecl.cpp | 1 - clang/lib/Sema/TreeTransform.h| 4 - clang/test/CXX/drs/dr16xx.cpp | 3 +- clang/test/CXX/drs/dr18xx.cpp | 7 +- clang/test/CXX/special/class.temporary/p6.cpp | 106 ++ clang/test/SemaCXX/constexpr-default-arg.cpp | 4 +- clang/test/SemaCXX/eval-crashes.cpp | 6 +- 15 files changed, 225 insertions(+), 117 deletions(-) diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h index f49bc724c96c89..0a07e850c74e47 100644 --- a/clang/include/clang/Sema/Sema.h +++ b/clang/include/clang/Sema/Sema.h @@ -5078,34 +5078,6 @@ class Sema final : public SemaBase { /// example, in a for-range initializer). bool InLifetimeExtendingContext = false; -/// Whether we are currently in a context in which all temporaries must be -/// materialized. -/// -/// [class.temporary]/p2: -/// The materialization of a temporary object is generally delayed as long -/// as possible in order to avoid creating unnecessary temporary objects. -/// -/// Temporary objects are materialized: -/// (2.1) when binding a reference to a prvalue ([dcl.init.ref], -/// [expr.type.conv], [expr.dynamic.cast], [expr.static.cast], -/// [expr.const.cast], [expr.cast]), -/// -/// (2.2) when performing member access on a class prvalue ([expr.ref], -/// [expr.mptr.oper]), -/// -/// (2.3) when performing an array-to-pointer conversion or subscripting -/// on an array prvalue ([conv.array], [expr.sub]), -/// -/// (2.4) when initializing an object of type -/// std::initializer_list from a braced-init-list -/// ([dcl.init.list]), -/// -/// (2.5) for certain unevaluated operands ([expr.typeid], [expr.sizeof]) -/// -/// (2.6) when a prvalue that has type other than cv void appears as a -/// discarded-value expression ([expr.context]). -bool InMaterializeTemporaryObjectContext = false; - // When evaluating immediate functions in the initializer of a default // argument or default member initializer, this is the declaration whose // default initializer is being evaluated and the location of the call @@ -6386,19 +6358,6 @@ class Sema final : public SemaBase { } } - /// keepInMaterializeTemporaryObjectContext - Pull down - /// InMaterializeTemporaryObjectContext flag from previous context. - void keepInMaterializeTemporaryObjectContext() { -if (ExprEvalContexts.size() > 2 && -ExprEvalContexts[ExprEvalContexts.size() - 2] -.InMaterializeTemporaryObjectContext) { - auto &LastRecord = ExprEvalContexts.back(); - auto &PrevRecord = ExprEvalContexts[ExprEvalContexts.size() - 2]; - LastRecord.InMaterializeTemporaryObjectContext = - PrevRecord.InMaterializeTemporaryObjectContext; -} - } - DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) { return getDefaultedFunctionKind(FD).asComparison(); } @@ -6542,12 +6501,6 @@ class Sema final : public SemaBase { /// used in initializer of the field. llvm::MapVector DeleteExprs; - bool isInMaterializeTemporaryObjectContext() const { -assert(!ExprEvalContexts.empty() && - "Must be in an expression evaluation context"); -return ExprEvalContexts.back().InMaterializeTemporaryObjectContext; - } - ParsedType getInheritingConstructorName(CXXScopeSpec &SS, SourceLocation NameLoc, IdentifierInfo &Name); diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp index 2480972f1432f7..27f616d497a2c5 100644 --- a/clang/lib/CodeGen/CGExpr.cpp +++ b/clang/lib/CodeGen/CGExpr.cpp @@ -274,9 +274,9 @@ void CodeGenFunction::EmitAnyExprToMem(const Expr *E, llvm_unreachable("bad evaluation kind"); } -static void -pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M, - const Expr *E, Address ReferenceTemporary) { +void CodeGenFunction::pushTemporaryCleanup(const MaterializeTemporary
[clang] [Clang] Extend lifetime of temporaries in mem-default-init for P2718R0 (PR #86960)
https://github.com/yronglin ready_for_review https://github.com/llvm/llvm-project/pull/86960 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Extend lifetime of temporaries in mem-default-init for P2718R0 (PR #86960)
llvmbot wrote: @llvm/pr-subscribers-clang-codegen Author: None (yronglin) Changes Fixes https://github.com/llvm/llvm-project/issues/85613. In https://github.com/llvm/llvm-project/pull/76361, we've not implement the lifetime extensions for the temporaries which in `CXXDefaultInitExpr`. As the confirmation in https://github.com/llvm/llvm-project/issues/85613, we should extend lifetime for that. There are two main modifications made to this PR: - Extend lifetime of temporaries in `CXXDefaultInitExpr`. This reuse `CXXDefaultInitExpr` rewrite machinery. - Before emitting the `__range` variable, we store the `__range` variable decl in `LexicalScope`. During emitting the `__range` variable, if we encounter a `MaterializedTemporaryExpr` whose lifetime is extended by the `__range` variable, we collect these temporaries and store into `LexicalScope::ForRangeInitTemps`. Once `__range` variable emitting finished, we will emitting the cleanups for the temporaries which we collected. TODO: The lit test not add yet, because I'm not sure it's the correct approach, but I've posted some cases in https://github.com/llvm/llvm-project/issues/85613. --- Patch is 27.12 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/86960.diff 15 Files Affected: - (modified) clang/include/clang/Sema/Sema.h (-47) - (modified) clang/lib/CodeGen/CGExpr.cpp (+33-29) - (modified) clang/lib/CodeGen/CGStmt.cpp (+18) - (modified) clang/lib/CodeGen/CodeGenFunction.h (+31) - (modified) clang/lib/Parse/ParseDecl.cpp (-4) - (modified) clang/lib/Sema/SemaExpr.cpp (+6-5) - (modified) clang/lib/Sema/SemaExprCXX.cpp (+1-1) - (modified) clang/lib/Sema/SemaInit.cpp (+23-13) - (modified) clang/lib/Sema/SemaTemplateInstantiateDecl.cpp (-1) - (modified) clang/lib/Sema/TreeTransform.h (-4) - (modified) clang/test/CXX/drs/dr16xx.cpp (+1-2) - (modified) clang/test/CXX/drs/dr18xx.cpp (+2-5) - (modified) clang/test/CXX/special/class.temporary/p6.cpp (+106) - (modified) clang/test/SemaCXX/constexpr-default-arg.cpp (+2-2) - (modified) clang/test/SemaCXX/eval-crashes.cpp (+2-4) ``diff diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h index f49bc724c96c89..0a07e850c74e47 100644 --- a/clang/include/clang/Sema/Sema.h +++ b/clang/include/clang/Sema/Sema.h @@ -5078,34 +5078,6 @@ class Sema final : public SemaBase { /// example, in a for-range initializer). bool InLifetimeExtendingContext = false; -/// Whether we are currently in a context in which all temporaries must be -/// materialized. -/// -/// [class.temporary]/p2: -/// The materialization of a temporary object is generally delayed as long -/// as possible in order to avoid creating unnecessary temporary objects. -/// -/// Temporary objects are materialized: -/// (2.1) when binding a reference to a prvalue ([dcl.init.ref], -/// [expr.type.conv], [expr.dynamic.cast], [expr.static.cast], -/// [expr.const.cast], [expr.cast]), -/// -/// (2.2) when performing member access on a class prvalue ([expr.ref], -/// [expr.mptr.oper]), -/// -/// (2.3) when performing an array-to-pointer conversion or subscripting -/// on an array prvalue ([conv.array], [expr.sub]), -/// -/// (2.4) when initializing an object of type -/// std::initializer_list from a braced-init-list -/// ([dcl.init.list]), -/// -/// (2.5) for certain unevaluated operands ([expr.typeid], [expr.sizeof]) -/// -/// (2.6) when a prvalue that has type other than cv void appears as a -/// discarded-value expression ([expr.context]). -bool InMaterializeTemporaryObjectContext = false; - // When evaluating immediate functions in the initializer of a default // argument or default member initializer, this is the declaration whose // default initializer is being evaluated and the location of the call @@ -6386,19 +6358,6 @@ class Sema final : public SemaBase { } } - /// keepInMaterializeTemporaryObjectContext - Pull down - /// InMaterializeTemporaryObjectContext flag from previous context. - void keepInMaterializeTemporaryObjectContext() { -if (ExprEvalContexts.size() > 2 && -ExprEvalContexts[ExprEvalContexts.size() - 2] -.InMaterializeTemporaryObjectContext) { - auto &LastRecord = ExprEvalContexts.back(); - auto &PrevRecord = ExprEvalContexts[ExprEvalContexts.size() - 2]; - LastRecord.InMaterializeTemporaryObjectContext = - PrevRecord.InMaterializeTemporaryObjectContext; -} - } - DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) { return getDefaultedFunctionKind(FD).asComparison(); } @@ -6542,12 +6501,6 @@ class Sema final : public SemaBase { /// used in initializer of the field. llvm::MapVector DeleteExprs; - bool isInMaterializeTemporaryObjectContext() const { -assert(!ExprEvalCont
[clang] [Clang] Extend lifetime of temporaries in mem-default-init for P2718R0 (PR #86960)
llvmbot wrote: @llvm/pr-subscribers-clang Author: None (yronglin) Changes Fixes https://github.com/llvm/llvm-project/issues/85613. In https://github.com/llvm/llvm-project/pull/76361, we've not implement the lifetime extensions for the temporaries which in `CXXDefaultInitExpr`. As the confirmation in https://github.com/llvm/llvm-project/issues/85613, we should extend lifetime for that. There are two main modifications made to this PR: - Extend lifetime of temporaries in `CXXDefaultInitExpr`. This reuse `CXXDefaultInitExpr` rewrite machinery. - Before emitting the `__range` variable, we store the `__range` variable decl in `LexicalScope`. During emitting the `__range` variable, if we encounter a `MaterializedTemporaryExpr` whose lifetime is extended by the `__range` variable, we collect these temporaries and store into `LexicalScope::ForRangeInitTemps`. Once `__range` variable emitting finished, we will emitting the cleanups for the temporaries which we collected. TODO: The lit test not add yet, because I'm not sure it's the correct approach, but I've posted some cases in https://github.com/llvm/llvm-project/issues/85613. --- Patch is 27.12 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/86960.diff 15 Files Affected: - (modified) clang/include/clang/Sema/Sema.h (-47) - (modified) clang/lib/CodeGen/CGExpr.cpp (+33-29) - (modified) clang/lib/CodeGen/CGStmt.cpp (+18) - (modified) clang/lib/CodeGen/CodeGenFunction.h (+31) - (modified) clang/lib/Parse/ParseDecl.cpp (-4) - (modified) clang/lib/Sema/SemaExpr.cpp (+6-5) - (modified) clang/lib/Sema/SemaExprCXX.cpp (+1-1) - (modified) clang/lib/Sema/SemaInit.cpp (+23-13) - (modified) clang/lib/Sema/SemaTemplateInstantiateDecl.cpp (-1) - (modified) clang/lib/Sema/TreeTransform.h (-4) - (modified) clang/test/CXX/drs/dr16xx.cpp (+1-2) - (modified) clang/test/CXX/drs/dr18xx.cpp (+2-5) - (modified) clang/test/CXX/special/class.temporary/p6.cpp (+106) - (modified) clang/test/SemaCXX/constexpr-default-arg.cpp (+2-2) - (modified) clang/test/SemaCXX/eval-crashes.cpp (+2-4) ``diff diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h index f49bc724c96c89..0a07e850c74e47 100644 --- a/clang/include/clang/Sema/Sema.h +++ b/clang/include/clang/Sema/Sema.h @@ -5078,34 +5078,6 @@ class Sema final : public SemaBase { /// example, in a for-range initializer). bool InLifetimeExtendingContext = false; -/// Whether we are currently in a context in which all temporaries must be -/// materialized. -/// -/// [class.temporary]/p2: -/// The materialization of a temporary object is generally delayed as long -/// as possible in order to avoid creating unnecessary temporary objects. -/// -/// Temporary objects are materialized: -/// (2.1) when binding a reference to a prvalue ([dcl.init.ref], -/// [expr.type.conv], [expr.dynamic.cast], [expr.static.cast], -/// [expr.const.cast], [expr.cast]), -/// -/// (2.2) when performing member access on a class prvalue ([expr.ref], -/// [expr.mptr.oper]), -/// -/// (2.3) when performing an array-to-pointer conversion or subscripting -/// on an array prvalue ([conv.array], [expr.sub]), -/// -/// (2.4) when initializing an object of type -/// std::initializer_list from a braced-init-list -/// ([dcl.init.list]), -/// -/// (2.5) for certain unevaluated operands ([expr.typeid], [expr.sizeof]) -/// -/// (2.6) when a prvalue that has type other than cv void appears as a -/// discarded-value expression ([expr.context]). -bool InMaterializeTemporaryObjectContext = false; - // When evaluating immediate functions in the initializer of a default // argument or default member initializer, this is the declaration whose // default initializer is being evaluated and the location of the call @@ -6386,19 +6358,6 @@ class Sema final : public SemaBase { } } - /// keepInMaterializeTemporaryObjectContext - Pull down - /// InMaterializeTemporaryObjectContext flag from previous context. - void keepInMaterializeTemporaryObjectContext() { -if (ExprEvalContexts.size() > 2 && -ExprEvalContexts[ExprEvalContexts.size() - 2] -.InMaterializeTemporaryObjectContext) { - auto &LastRecord = ExprEvalContexts.back(); - auto &PrevRecord = ExprEvalContexts[ExprEvalContexts.size() - 2]; - LastRecord.InMaterializeTemporaryObjectContext = - PrevRecord.InMaterializeTemporaryObjectContext; -} - } - DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) { return getDefaultedFunctionKind(FD).asComparison(); } @@ -6542,12 +6501,6 @@ class Sema final : public SemaBase { /// used in initializer of the field. llvm::MapVector DeleteExprs; - bool isInMaterializeTemporaryObjectContext() const { -assert(!ExprEvalContexts.emp
[clang] [Clang] Extend lifetime of temporaries in mem-default-init for P2718R0 (PR #86960)
https://github.com/yronglin updated https://github.com/llvm/llvm-project/pull/86960 >From e5f2bfb1652118be0112b8242263942063b75b89 Mon Sep 17 00:00:00 2001 From: yronglin Date: Tue, 2 Apr 2024 23:47:33 +0800 Subject: [PATCH] [Clang] Extend lifetime of temporaries in mem-default-init for P2718R0 Signed-off-by: yronglin --- clang/include/clang/Sema/Sema.h | 47 clang/lib/CodeGen/CGExpr.cpp | 62 +- clang/lib/CodeGen/CGStmt.cpp | 15 +++ clang/lib/CodeGen/CodeGenFunction.h | 31 + clang/lib/Parse/ParseDecl.cpp | 4 - clang/lib/Sema/SemaExpr.cpp | 11 +- clang/lib/Sema/SemaExprCXX.cpp| 2 +- clang/lib/Sema/SemaInit.cpp | 36 +++--- .../lib/Sema/SemaTemplateInstantiateDecl.cpp | 1 - clang/lib/Sema/TreeTransform.h| 4 - clang/test/CXX/drs/dr16xx.cpp | 3 +- clang/test/CXX/drs/dr18xx.cpp | 7 +- clang/test/CXX/special/class.temporary/p6.cpp | 106 ++ clang/test/SemaCXX/constexpr-default-arg.cpp | 4 +- clang/test/SemaCXX/eval-crashes.cpp | 6 +- 15 files changed, 222 insertions(+), 117 deletions(-) diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h index f49bc724c96c89..0a07e850c74e47 100644 --- a/clang/include/clang/Sema/Sema.h +++ b/clang/include/clang/Sema/Sema.h @@ -5078,34 +5078,6 @@ class Sema final : public SemaBase { /// example, in a for-range initializer). bool InLifetimeExtendingContext = false; -/// Whether we are currently in a context in which all temporaries must be -/// materialized. -/// -/// [class.temporary]/p2: -/// The materialization of a temporary object is generally delayed as long -/// as possible in order to avoid creating unnecessary temporary objects. -/// -/// Temporary objects are materialized: -/// (2.1) when binding a reference to a prvalue ([dcl.init.ref], -/// [expr.type.conv], [expr.dynamic.cast], [expr.static.cast], -/// [expr.const.cast], [expr.cast]), -/// -/// (2.2) when performing member access on a class prvalue ([expr.ref], -/// [expr.mptr.oper]), -/// -/// (2.3) when performing an array-to-pointer conversion or subscripting -/// on an array prvalue ([conv.array], [expr.sub]), -/// -/// (2.4) when initializing an object of type -/// std::initializer_list from a braced-init-list -/// ([dcl.init.list]), -/// -/// (2.5) for certain unevaluated operands ([expr.typeid], [expr.sizeof]) -/// -/// (2.6) when a prvalue that has type other than cv void appears as a -/// discarded-value expression ([expr.context]). -bool InMaterializeTemporaryObjectContext = false; - // When evaluating immediate functions in the initializer of a default // argument or default member initializer, this is the declaration whose // default initializer is being evaluated and the location of the call @@ -6386,19 +6358,6 @@ class Sema final : public SemaBase { } } - /// keepInMaterializeTemporaryObjectContext - Pull down - /// InMaterializeTemporaryObjectContext flag from previous context. - void keepInMaterializeTemporaryObjectContext() { -if (ExprEvalContexts.size() > 2 && -ExprEvalContexts[ExprEvalContexts.size() - 2] -.InMaterializeTemporaryObjectContext) { - auto &LastRecord = ExprEvalContexts.back(); - auto &PrevRecord = ExprEvalContexts[ExprEvalContexts.size() - 2]; - LastRecord.InMaterializeTemporaryObjectContext = - PrevRecord.InMaterializeTemporaryObjectContext; -} - } - DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) { return getDefaultedFunctionKind(FD).asComparison(); } @@ -6542,12 +6501,6 @@ class Sema final : public SemaBase { /// used in initializer of the field. llvm::MapVector DeleteExprs; - bool isInMaterializeTemporaryObjectContext() const { -assert(!ExprEvalContexts.empty() && - "Must be in an expression evaluation context"); -return ExprEvalContexts.back().InMaterializeTemporaryObjectContext; - } - ParsedType getInheritingConstructorName(CXXScopeSpec &SS, SourceLocation NameLoc, IdentifierInfo &Name); diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp index 2480972f1432f7..27f616d497a2c5 100644 --- a/clang/lib/CodeGen/CGExpr.cpp +++ b/clang/lib/CodeGen/CGExpr.cpp @@ -274,9 +274,9 @@ void CodeGenFunction::EmitAnyExprToMem(const Expr *E, llvm_unreachable("bad evaluation kind"); } -static void -pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M, - const Expr *E, Address ReferenceTemporary) { +void CodeGenFunction::pushTemporaryCleanup(const MaterializeTemporary
[clang] [Clang] Extend lifetime of temporaries in mem-default-init for P2718R0 (PR #86960)
https://github.com/yronglin edited https://github.com/llvm/llvm-project/pull/86960 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Extend lifetime of temporaries in mem-default-init for P2718R0 (PR #86960)
https://github.com/yronglin edited https://github.com/llvm/llvm-project/pull/86960 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Extend lifetime of temporaries in mem-default-init for P2718R0 (PR #86960)
@@ -1230,11 +1230,26 @@ CodeGenFunction::EmitCXXForRangeStmt(const CXXForRangeStmt &S, JumpDest LoopExit = getJumpDestInCurrentScope("for.end"); LexicalScope ForScope(*this, S.getSourceRange()); + const DeclStmt *RangeDS = cast(S.getRangeStmt()); + const VarDecl *RangeVar = cast(RangeDS->getSingleDecl()); + if (getLangOpts().CPlusPlus23) yronglin wrote: I think we need to continue to improve here. We can decide whether to extend the lifetime in Sema. For example: do not store temporaries into ExpressionEvaluationContext::ForRangeLifetimeExtendTemps when building for-range-init expressions. https://github.com/llvm/llvm-project/pull/86960 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Extend lifetime of temporaries in mem-default-init for P2718R0 (PR #86960)
@@ -1230,11 +1230,26 @@ CodeGenFunction::EmitCXXForRangeStmt(const CXXForRangeStmt &S, JumpDest LoopExit = getJumpDestInCurrentScope("for.end"); LexicalScope ForScope(*this, S.getSourceRange()); + const DeclStmt *RangeDS = cast(S.getRangeStmt()); + const VarDecl *RangeVar = cast(RangeDS->getSingleDecl()); + if (getLangOpts().CPlusPlus23) +ForScope.setForRangeVar(RangeVar); // Evaluate the first pieces before the loop. if (S.getInit()) EmitStmt(S.getInit()); EmitStmt(S.getRangeStmt()); + + // Emit cleanup for tempories in for-range-init expression. + if (getLangOpts().CPlusPlus23) { yronglin wrote: Same as above. https://github.com/llvm/llvm-project/pull/86960 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Extend lifetime of temporaries in mem-default-init for P2718R0 (PR #86960)
https://github.com/yronglin edited https://github.com/llvm/llvm-project/pull/86960 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Extend lifetime of temporaries in mem-default-init for P2718R0 (PR #86960)
https://github.com/yronglin edited https://github.com/llvm/llvm-project/pull/86960 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang][Sema] Skip checking anonymous enum in using enum declaration (PR #87144)
@@ -1537,6 +1537,10 @@ void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { cast(D)->isFunctionTemplateSpecialization()) return; + if (isa(D) && D->getDeclName().isEmpty()) { zygoloid wrote: Why do we push a `UsingEnumDecl` into the scope at all? Would it make sense for the caller to just add the declaration to the `DeclContext` instead of calling `PushOnScopeChains`? https://github.com/llvm/llvm-project/pull/87144 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Extend lifetime of temporaries in mem-default-init for P2718R0 (PR #86960)
https://github.com/Endilll commented: `Sema.h` changes look good. https://github.com/llvm/llvm-project/pull/86960 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Variant checker bindings (PR #87886)
https://github.com/spaits created https://github.com/llvm/llvm-project/pull/87886 None From b9d22d9ebc152ac0bccc7e196f8bbecc9302d833 Mon Sep 17 00:00:00 2001 From: Gabor Spaits Date: Sat, 13 Jan 2024 21:06:52 +0100 Subject: [PATCH 1/2] [analyzer] Implement modeling of std::swap and bind to SVal to std::get call --- .../Checkers/StdVariantChecker.cpp| 105 ++ .../Checkers/TaggedUnionModeling.h| 80 ++--- .../Checkers/UndefinedAssignmentChecker.cpp | 8 +- .../Inputs/system-header-simulator-cxx.h | 3 + clang/test/Analysis/std-variant-checker.cpp | 30 - 5 files changed, 185 insertions(+), 41 deletions(-) diff --git a/clang/lib/StaticAnalyzer/Checkers/StdVariantChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/StdVariantChecker.cpp index f7b7befe28ee7d..f86aea6032f205 100644 --- a/clang/lib/StaticAnalyzer/Checkers/StdVariantChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/StdVariantChecker.cpp @@ -6,6 +6,8 @@ // //===--===// +#include "clang/AST/CXXInheritance.h" +#include "clang/AST/Expr.h" #include "clang/AST/Type.h" #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h" #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" @@ -14,12 +16,16 @@ #include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h" #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h" #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h" #include "llvm/ADT/FoldingSet.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/Casting.h" +#include "llvm/Support/ErrorHandling.h" +#include "llvm/Support/raw_ostream.h" +#include #include -#include #include "TaggedUnionModeling.h" @@ -27,7 +33,7 @@ using namespace clang; using namespace ento; using namespace tagged_union_modeling; -REGISTER_MAP_WITH_PROGRAMSTATE(VariantHeldTypeMap, const MemRegion *, QualType) +REGISTER_MAP_WITH_PROGRAMSTATE(VariantHeldMap, const MemRegion *, SVal) namespace clang::ento::tagged_union_modeling { @@ -132,8 +138,11 @@ class StdVariantChecker : public Checker { CallDescription VariantConstructor{{"std", "variant", "variant"}}; CallDescription VariantAssignmentOperator{{"std", "variant", "operator="}}; CallDescription StdGet{{"std", "get"}, 1, 1}; + CallDescription StdSwap{{"std", "swap"}, 2}; + CallDescription StdEmplace{{"std", "variant", "emplace"}}; - BugType BadVariantType{this, "BadVariantType", "BadVariantType"}; + BugType BadVariantType{ + this, "The active type of std::variant differs from the accessed."}; public: ProgramStateRef checkRegionChanges(ProgramStateRef State, @@ -145,8 +154,8 @@ class StdVariantChecker : public Checker { if (!Call) return State; -return removeInformationStoredForDeadInstances( -*Call, State, Regions); +return removeInformationStoredForDeadInstances(*Call, State, + Regions); } bool evalCall(const CallEvent &Call, CheckerContext &C) const { @@ -158,6 +167,13 @@ class StdVariantChecker : public Checker { if (StdGet.matches(Call)) return handleStdGetCall(Call, C); +if (StdSwap.matches(Call)) + return handleStdSwapCall(Call, C); + +// TODO Implement the modeling of std::variants emplace method. +if (StdEmplace.matches(Call)) + return handleStdVariantEmplaceCall(Call, C); + // First check if a constructor call is happening. If it is a // constructor call, check if it is an std::variant constructor call. bool IsVariantConstructor = @@ -188,16 +204,15 @@ class StdVariantChecker : public Checker { return false; } - handleConstructorAndAssignment(Call, C, ThisSVal); - return true; + return handleConstructorAndAssignment(Call, C, ThisSVal); } return false; } private: - // The default constructed std::variant must be handled separately - // by default the std::variant is going to hold a default constructed instance - // of the first type of the possible types + // The default constructed std::variant must be handled separately. + // When an std::variant instance is default constructed it holds + // a value-initialized value of the first type alternative. void handleDefaultConstructor(const CXXConstructorCall *ConstructorCall, CheckerContext &C) const { SVal ThisSVal = ConstructorCall->getCXXThisVal(); @@ -206,23 +221,42 @@ class StdVariantChecker : public Checker { if (!ThisMemRegion) return; +// Get the first type alternative of the std::variant instance. +assert((ThisSVal.getType(C.getASTContext())->isPointerType() || +
[clang] [analyzer] Variant checker bindings (PR #87886)
https://github.com/spaits edited https://github.com/llvm/llvm-project/pull/87886 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer] Variant checker bindings (PR #87886)
https://github.com/spaits edited https://github.com/llvm/llvm-project/pull/87886 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer] Variant checker bindings (PR #87886)
github-actions[bot] wrote: :warning: C/C++ code formatter, clang-format found issues in your code. :warning: You can test this locally with the following command: ``bash git-clang-format --diff b5f2db940643af3837c77adde1dadb7208922211 b250e2db91515b33c427bfa1b9faf6f376010bf0 -- clang/lib/StaticAnalyzer/Checkers/StdVariantChecker.cpp clang/lib/StaticAnalyzer/Checkers/TaggedUnionModeling.h clang/lib/StaticAnalyzer/Checkers/UndefinedAssignmentChecker.cpp clang/lib/StaticAnalyzer/Core/ExprEngine.cpp clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp clang/test/Analysis/Inputs/system-header-simulator-cxx.h clang/test/Analysis/std-variant-checker.cpp `` View the diff from clang-format here. ``diff diff --git a/clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp b/clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp index 5bdbc0e755c..11b9fbd9656 100644 --- a/clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp +++ b/clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp @@ -45,15 +45,15 @@ static SVal conjureOffsetSymbolOnLocation( // Update the SVal bound to the Cast expression with the SVal // bound to the casted expression -static ProgramStateRef updateStateAfterSimpleCast(StmtNodeBuilder& Bldr, - ExplodedNode *Pred, - const CastExpr *CastE, - const Expr *CastedE) { +static ProgramStateRef updateStateAfterSimpleCast(StmtNodeBuilder &Bldr, + ExplodedNode *Pred, + const CastExpr *CastE, + const Expr *CastedE) { ProgramStateRef state = Pred->getState(); const LocationContext *LCtx = Pred->getLocationContext(); SVal V = state->getSVal(CastedE, LCtx); return state->BindExpr(CastE, LCtx, V); - //Bldr.generateNode(CastE, Pred, state); + // Bldr.generateNode(CastE, Pred, state); } void ExprEngine::VisitBinaryOperator(const BinaryOperator* B, `` https://github.com/llvm/llvm-project/pull/87886 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer] Variant checker bindings (PR #87886)
https://github.com/spaits edited https://github.com/llvm/llvm-project/pull/87886 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Extend lifetime of temporaries in mem-default-init for P2718R0 (PR #86960)
@@ -1230,11 +1230,26 @@ CodeGenFunction::EmitCXXForRangeStmt(const CXXForRangeStmt &S, JumpDest LoopExit = getJumpDestInCurrentScope("for.end"); LexicalScope ForScope(*this, S.getSourceRange()); + const DeclStmt *RangeDS = cast(S.getRangeStmt()); + const VarDecl *RangeVar = cast(RangeDS->getSingleDecl()); + if (getLangOpts().CPlusPlus23) efriedma-quic wrote: What makes temporaries in for-range statements different from other temporaries? The standard explicitly defines for-range in terms of a regular for-loop; it shouldn't require any special handling unless our AST is somehow deficient. https://github.com/llvm/llvm-project/pull/86960 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Extend lifetime of temporaries in mem-default-init for P2718R0 (PR #86960)
@@ -311,9 +311,9 @@ pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M, CleanupKind CleanupKind; if (Lifetime == Qualifiers::OCL_Strong) { const ValueDecl *VD = M->getExtendingDecl(); - bool Precise = - VD && isa(VD) && VD->hasAttr(); - CleanupKind = CGF.getARCCleanupKind(); + bool Precise = isa_and_nonnull(VD) && efriedma-quic wrote: Mixing together a bunch of cleanups with your actual changes makes things hard to read. https://github.com/llvm/llvm-project/pull/86960 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [OpenMP] Add amdgpu-num-work-groups attribute to OpenMP kernels (PR #87695)
arsenm wrote: Note this attribute doesn't actually do anything yet. @jwanggit86 are you working on implementing the propagation and optimizations with this? https://github.com/llvm/llvm-project/pull/87695 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][Sema] Track trivial-relocatability as a type trait (PR #84621)
cor3ntin wrote: > But this isn't useful at all; every library has already invented its own > constraints and type traits. The point of having a language-based solution is > that the "is TR" property gets automatically propagated when you compose > types. No library solution can achieve that, especially lacking reflection. I am not sure i understand, assignability is already a transitive property for defaults operators? so the scenario you are concerned about is triviality copyable types with a user defined assignment operators? This would for example not impact reference wrappers which are not assignable. The larger point is that there are 2 concerns here, one is whether it is safe to relocate a type at the language level, which this type trait is intended to provide, and one is how a library uses relocatability for optimization. A library may decide it doesn't want to relocate types that are not assignable for some operations (which btw doesn't need to apply recursively to subobjects) , and it can do so today. I would in fact imagine that the logic would be 1/checking for assignability in all cases 2/checking for relocatability for optimization. It would be useful to illustrate with code examples scenarios in which that wouldn't work. And again, https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2023/p2959r0.html goes into some of these questions and might be worth checking out. https://github.com/llvm/llvm-project/pull/84621 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][Sema] Track trivial-relocatability as a type trait (PR #84621)
cor3ntin wrote: > Do you mean that you would reject a proposal that adds Clang-specific trait > (with another name) that implements P1144's semantics? A proposal that explores trivial swapability for example, with the understanding it would be a subset of trivially relocatable types might be worth exploring as a separate feature. Hopefully this would go through careful design and RFC. https://github.com/llvm/llvm-project/pull/84621 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [mlir] fix vulnerabilities (PR #79697)
https://github.com/gitworkflows updated https://github.com/llvm/llvm-project/pull/79697 >From f7b4f61db6016a1a02d775efc1e921fac785e823 Mon Sep 17 00:00:00 2001 From: snyk-bot Date: Fri, 19 Jan 2024 07:12:22 + Subject: [PATCH 1/9] feat: upgrade vscode-languageclient from 8.0.2-next.5 to 9.0.1 Snyk has created this PR to upgrade vscode-languageclient from 8.0.2-next.5 to 9.0.1. See this package in npm: https://www.npmjs.com/package/vscode-languageclient See this project in Snyk: https://app.snyk.io/org/gitaction-log4j/project/a71a1b94-9555-4c53-b459-4ef6c4d3545e?utm_source=github&utm_medium=referral&page=upgrade-pr --- mlir/utils/vscode/package-lock.json | 117 +++- mlir/utils/vscode/package.json | 2 +- 2 files changed, 80 insertions(+), 39 deletions(-) diff --git a/mlir/utils/vscode/package-lock.json b/mlir/utils/vscode/package-lock.json index c93f6167c80a1e..7d573b63fcca1f 100644 --- a/mlir/utils/vscode/package-lock.json +++ b/mlir/utils/vscode/package-lock.json @@ -10,7 +10,7 @@ "dependencies": { "base64-js": "^1.5.1", "chokidar": "3.5.2", -"vscode-languageclient": "^8.0.2-next.5" +"vscode-languageclient": "^9.0.1" }, "devDependencies": { "@types/mocha": "^7.0.2", @@ -279,6 +279,7 @@ "version": "1.1.11", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz";, "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" @@ -509,7 +510,8 @@ "node_modules/concat-map": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz";, - "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=" + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", + "dev": true }, "node_modules/console-control-strings": { "version": "1.1.0", @@ -1198,6 +1200,7 @@ "version": "3.0.4", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz";, "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "dev": true, "dependencies": { "brace-expansion": "^1.1.7" }, @@ -1881,24 +1884,43 @@ "dev": true }, "node_modules/vscode-jsonrpc": { - "version": "8.0.2-next.1", - "resolved": "https://registry.npmjs.org/vscode-jsonrpc/-/vscode-jsonrpc-8.0.2-next.1.tgz";, - "integrity": "sha512-sbbvGSWja7NVBLHPGawtgezc8DHYJaP4qfr/AaJiyDapWcSFtHyPtm18+LnYMLTmB7bhOUW/lf5PeeuLpP6bKA==", + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/vscode-jsonrpc/-/vscode-jsonrpc-8.2.0.tgz";, + "integrity": "sha512-C+r0eKJUIfiDIfwJhria30+TYWPtuHJXHtI7J0YlOmKAo7ogxP20T0zxB7HZQIFhIyvoBPwWskjxrvAtfjyZfA==", "engines": { "node": ">=14.0.0" } }, "node_modules/vscode-languageclient": { - "version": "8.0.2-next.5", - "resolved": "https://registry.npmjs.org/vscode-languageclient/-/vscode-languageclient-8.0.2-next.5.tgz";, - "integrity": "sha512-g87RJLHz0XlRyk6DOTbAk4JHcj8CKggXy4JiFL7OlhETkcYzTOR8d+Qdb4GqZr37PDs1Cl21omtTNK5LyR/RQg==", + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/vscode-languageclient/-/vscode-languageclient-9.0.1.tgz";, + "integrity": "sha512-JZiimVdvimEuHh5olxhxkht09m3JzUGwggb5eRUkzzJhZ2KjCN0nh55VfiED9oez9DyF8/fz1g1iBV3h+0Z2EA==", "dependencies": { -"minimatch": "^3.0.4", -"semver": "^7.3.5", -"vscode-languageserver-protocol": "3.17.2-next.6" +"minimatch": "^5.1.0", +"semver": "^7.3.7", +"vscode-languageserver-protocol": "3.17.5" }, "engines": { -"vscode": "^1.67.0" +"vscode": "^1.82.0" + } +}, +"node_modules/vscode-languageclient/node_modules/brace-expansion": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz";, + "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", + "dependencies": { +"balanced-match": "^1.0.0" + } +}, +"node_modules/vscode-languageclient/node_modules/minimatch": { + "version": "5.1.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.6.tgz";, + "integrity": "sha512-lKwV/1brpG6mBUFHtb7NUmtABCb2WZZmm2wNiOA5hAb8VdCS4B3dtMWyvcoViccwAW/COERjXLt0zP1zXUN26g==", + "dependencies": { +"brace-expansion": "^2.0.1" + }, + "engines": { +"node": ">=10" } }, "node_modules/vscode-languageclient/node_modules/semver": { @@ -1916,18 +1938,18 @@ } }, "node_modules/vscode-languageserver-protocol": { - "version": "3.17.2-next.6", -
[clang-tools-extra] [clang-pseudo] Add a --print-terminal-tokens option (PR #87898)
https://github.com/jeremy-rifkin created https://github.com/llvm/llvm-project/pull/87898 This PR adds a `--print-terminal-tokens` option to clang-pseudo which prints tokens in a parse forest in addition to providing the token index: ``` › bin/clang-pseudo --source test.cpp --print-forest [ 0, end) translation-unit~simple-declaration := decl-specifier-seq init-declarator-list ; [ 0, 1) ├─decl-specifier-seq~simple-type-specifier := [ 0, 1) │ ├─simple-type-specifier~IDENTIFIER := tok[0] [ 0, 1) │ └─simple-type-specifier~IDENTIFIER := tok[0] [ 1, 3) ├─init-declarator-list~ptr-declarator := ptr-operator ptr-declarator [ 1, 2) │ ├─ptr-operator~* := tok[1] [ 2, 3) │ └─ptr-declarator~IDENTIFIER := tok[2] [ 3, end) └─; := tok[3] ``` ``` › bin/clang-pseudo --source test.cpp --print-forest --print-terminal-tokens [ 0, end) translation-unit~simple-declaration := decl-specifier-seq init-declarator-list ; [ 0, 1) ├─decl-specifier-seq~simple-type-specifier := [ 0, 1) │ ├─simple-type-specifier~IDENTIFIER := tok[0] (identifier 1:0 "T" flags=1) [ 0, 1) │ └─simple-type-specifier~IDENTIFIER := tok[0] (identifier 1:0 "T" flags=1) [ 1, 3) ├─init-declarator-list~ptr-declarator := ptr-operator ptr-declarator [ 1, 2) │ ├─ptr-operator~* := tok[1] (star 1:0 "*") [ 2, 3) │ └─ptr-declarator~IDENTIFIER := tok[2] (identifier 1:0 "y") [ 3, end) └─; := tok[3] (semi 1:0 ";") ``` >From 2ebb15e08b5e2d8a9fe6cfddbe0dd2a8942b2542 Mon Sep 17 00:00:00 2001 From: Jeremy <51220084+jeremy-rif...@users.noreply.github.com> Date: Sat, 6 Apr 2024 17:02:20 -0500 Subject: [PATCH] Add a --print-terminal-tokens option --- clang-tools-extra/pseudo/fuzzer/Fuzzer.cpp| 2 +- .../pseudo/include/clang-pseudo/Forest.h | 11 ++-- clang-tools-extra/pseudo/lib/Forest.cpp | 26 +-- clang-tools-extra/pseudo/tool/ClangPseudo.cpp | 12 +++-- 4 files changed, 38 insertions(+), 13 deletions(-) diff --git a/clang-tools-extra/pseudo/fuzzer/Fuzzer.cpp b/clang-tools-extra/pseudo/fuzzer/Fuzzer.cpp index 87b9d15480cc35..33b3da1ed6ea9f 100644 --- a/clang-tools-extra/pseudo/fuzzer/Fuzzer.cpp +++ b/clang-tools-extra/pseudo/fuzzer/Fuzzer.cpp @@ -46,7 +46,7 @@ class Fuzzer { glrParse(clang::pseudo::ParseParams{ParseableStream, Arena, GSS}, *Lang.G.findNonterminal("translation-unit"), Lang); if (Print) - llvm::outs() << Root.dumpRecursive(Lang.G); + llvm::outs() << Root.dumpRecursive(Lang.G, std::nullopt); } }; diff --git a/clang-tools-extra/pseudo/include/clang-pseudo/Forest.h b/clang-tools-extra/pseudo/include/clang-pseudo/Forest.h index e9edb40e02b64e..642c489b3fba41 100644 --- a/clang-tools-extra/pseudo/include/clang-pseudo/Forest.h +++ b/clang-tools-extra/pseudo/include/clang-pseudo/Forest.h @@ -26,6 +26,8 @@ #include "llvm/ADT/STLExtras.h" #include "llvm/Support/Allocator.h" #include +#include +#include namespace clang { namespace pseudo { @@ -112,8 +114,13 @@ class alignas(class ForestNode *) ForestNode { // Iteration over all nodes in the forest, including this. llvm::iterator_range descendants() const; - std::string dump(const Grammar &) const; - std::string dumpRecursive(const Grammar &, bool Abbreviated = false) const; + std::string + dump(const Grammar &, + std::optional>) const; + std::string + dumpRecursive(const Grammar &, +std::optional>, +bool Abbreviated = false) const; private: friend class ForestArena; diff --git a/clang-tools-extra/pseudo/lib/Forest.cpp b/clang-tools-extra/pseudo/lib/Forest.cpp index e8e60e5ec475a4..adce731d6c1e1c 100644 --- a/clang-tools-extra/pseudo/lib/Forest.cpp +++ b/clang-tools-extra/pseudo/lib/Forest.cpp @@ -45,13 +45,21 @@ ForestNode::descendants() const { return {RecursiveIterator(this), RecursiveIterator()}; } -std::string ForestNode::dump(const Grammar &G) const { +std::string ForestNode::dump( +const Grammar &G, +std::optional> Code) const { switch (kind()) { case Ambiguous: return llvm::formatv("{0} := ", G.symbolName(symbol())); case Terminal: -return llvm::formatv("{0} := tok[{1}]", G.symbolName(symbol()), - startTokenIndex()); +if (Code) { + return llvm::formatv("{0} := tok[{1}] ({2})", G.symbolName(symbol()), + startTokenIndex(), + Code->get().tokens()[startTokenIndex()]); +} else { + return llvm::formatv("{0} := tok[{1}]", G.symbolName(symbol()), + startTokenIndex()); +} case Sequence: return G.dumpRule(rule()); case Opaque: @@ -60,8 +68,10 @@ std::string ForestNode::dump(const Grammar &G) const { llvm_unreachable("Unhandled node kind!"); } -std::string ForestNode::dumpRecursive(const Grammar &G, - bool Abbreviated) const { +std::string ForestNode::dumpRecursive( +const Grammar &G, +std::optional> Code,
[clang-tools-extra] [clang-pseudo] Add a --print-terminal-tokens option (PR #87898)
github-actions[bot] wrote: Thank you for submitting a Pull Request (PR) to the LLVM Project! This PR will be automatically labeled and the relevant teams will be notified. If you wish to, you can add reviewers by using the "Reviewers" section on this page. If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using `@` followed by their GitHub username. If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers. If you have further questions, they may be answered by the [LLVM GitHub User Guide](https://llvm.org/docs/GitHub.html). You can also ask questions in a comment on this PR, on the [LLVM Discord](https://discord.com/invite/xS7Z362) or on the [forums](https://discourse.llvm.org/). https://github.com/llvm/llvm-project/pull/87898 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-pseudo] Add a --print-terminal-tokens option (PR #87898)
llvmbot wrote: @llvm/pr-subscribers-clang-tools-extra Author: Jeremy Rifkin (jeremy-rifkin) Changes This PR adds a `--print-terminal-tokens` option to clang-pseudo which prints tokens in a parse forest in addition to providing the token index: ``` › bin/clang-pseudo --source test.cpp --print-forest [ 0, end) translation-unit~simple-declaration := decl-specifier-seq init-declarator-list ; [ 0, 1) ├─decl-specifier-seq~simple-type-specifier :=[ 0, 1) │ ├─simple-type-specifier~IDENTIFIER := tok[0] [ 0, 1) │ └─simple-type-specifier~IDENTIFIER := tok[0] [ 1, 3) ├─init-declarator-list~ptr-declarator := ptr-operator ptr-declarator [ 1, 2) │ ├─ptr-operator~* := tok[1] [ 2, 3) │ └─ptr-declarator~IDENTIFIER := tok[2] [ 3, end) └─; := tok[3] ``` ``` › bin/clang-pseudo --source test.cpp --print-forest --print-terminal-tokens [ 0, end) translation-unit~simple-declaration := decl-specifier-seq init-declarator-list ; [ 0, 1) ├─decl-specifier-seq~simple-type-specifier := [ 0, 1) │ ├─simple-type-specifier~IDENTIFIER := tok[0] (identifier 1:0 "T" flags=1) [ 0, 1) │ └─simple-type-specifier~IDENTIFIER := tok[0] (identifier 1:0 "T" flags=1) [ 1, 3) ├─init-declarator-list~ptr-declarator := ptr-operator ptr-declarator [ 1, 2) │ ├─ptr-operator~* := tok[1] (star 1:0 "*") [ 2, 3) │ └─ptr-declarator~IDENTIFIER := tok[2] (identifier 1:0 "y") [ 3, end) └─; := tok[3] (semi 1:0 ";") ``` --- Full diff: https://github.com/llvm/llvm-project/pull/87898.diff 4 Files Affected: - (modified) clang-tools-extra/pseudo/fuzzer/Fuzzer.cpp (+1-1) - (modified) clang-tools-extra/pseudo/include/clang-pseudo/Forest.h (+9-2) - (modified) clang-tools-extra/pseudo/lib/Forest.cpp (+18-8) - (modified) clang-tools-extra/pseudo/tool/ClangPseudo.cpp (+10-2) ``diff diff --git a/clang-tools-extra/pseudo/fuzzer/Fuzzer.cpp b/clang-tools-extra/pseudo/fuzzer/Fuzzer.cpp index 87b9d15480cc35..33b3da1ed6ea9f 100644 --- a/clang-tools-extra/pseudo/fuzzer/Fuzzer.cpp +++ b/clang-tools-extra/pseudo/fuzzer/Fuzzer.cpp @@ -46,7 +46,7 @@ class Fuzzer { glrParse(clang::pseudo::ParseParams{ParseableStream, Arena, GSS}, *Lang.G.findNonterminal("translation-unit"), Lang); if (Print) - llvm::outs() << Root.dumpRecursive(Lang.G); + llvm::outs() << Root.dumpRecursive(Lang.G, std::nullopt); } }; diff --git a/clang-tools-extra/pseudo/include/clang-pseudo/Forest.h b/clang-tools-extra/pseudo/include/clang-pseudo/Forest.h index e9edb40e02b64e..642c489b3fba41 100644 --- a/clang-tools-extra/pseudo/include/clang-pseudo/Forest.h +++ b/clang-tools-extra/pseudo/include/clang-pseudo/Forest.h @@ -26,6 +26,8 @@ #include "llvm/ADT/STLExtras.h" #include "llvm/Support/Allocator.h" #include +#include +#include namespace clang { namespace pseudo { @@ -112,8 +114,13 @@ class alignas(class ForestNode *) ForestNode { // Iteration over all nodes in the forest, including this. llvm::iterator_range descendants() const; - std::string dump(const Grammar &) const; - std::string dumpRecursive(const Grammar &, bool Abbreviated = false) const; + std::string + dump(const Grammar &, + std::optional>) const; + std::string + dumpRecursive(const Grammar &, +std::optional>, +bool Abbreviated = false) const; private: friend class ForestArena; diff --git a/clang-tools-extra/pseudo/lib/Forest.cpp b/clang-tools-extra/pseudo/lib/Forest.cpp index e8e60e5ec475a4..adce731d6c1e1c 100644 --- a/clang-tools-extra/pseudo/lib/Forest.cpp +++ b/clang-tools-extra/pseudo/lib/Forest.cpp @@ -45,13 +45,21 @@ ForestNode::descendants() const { return {RecursiveIterator(this), RecursiveIterator()}; } -std::string ForestNode::dump(const Grammar &G) const { +std::string ForestNode::dump( +const Grammar &G, +std::optional> Code) const { switch (kind()) { case Ambiguous: return llvm::formatv("{0} := ", G.symbolName(symbol())); case Terminal: -return llvm::formatv("{0} := tok[{1}]", G.symbolName(symbol()), - startTokenIndex()); +if (Code) { + return llvm::formatv("{0} := tok[{1}] ({2})", G.symbolName(symbol()), + startTokenIndex(), + Code->get().tokens()[startTokenIndex()]); +} else { + return llvm::formatv("{0} := tok[{1}]", G.symbolName(symbol()), + startTokenIndex()); +} case Sequence: return G.dumpRule(rule()); case Opaque: @@ -60,8 +68,10 @@ std::string ForestNode::dump(const Grammar &G) const { llvm_unreachable("Unhandled node kind!"); } -std::string ForestNode::dumpRecursive(const Grammar &G, - bool Abbreviated) const { +std::string ForestNode::dumpRecursive( +const Grammar &G, +std::optional> Code, +bool Abbreviated) const { using llvm::formatv; Token::Index MaxToken = 0; // Count visits of nodes so we
[clang-tools-extra] [clang-pseudo] clang-format file (PR #87900)
https://github.com/jeremy-rifkin created https://github.com/llvm/llvm-project/pull/87900 This PR just clang-formats the `clang-tools-extra/pseudo` directory to make contribution easier. One issue I ran into is clang-format kept changing this region, despite the `clang-format off` directives, which I manually reverted: ``` //clang-format off #define NONTERMINAL(NAME, ID) \ };\ } \ namespace NAME { \ enum Rule : RuleID { //clang-format on ``` >From 7add6f47c280b5345f0ad15738a0e82a39f51cb8 Mon Sep 17 00:00:00 2001 From: Jeremy <51220084+jeremy-rif...@users.noreply.github.com> Date: Sat, 6 Apr 2024 17:39:48 -0500 Subject: [PATCH 1/2] clang-format clang-tools-extra/pseudo --- clang-tools-extra/pseudo/gen/Main.cpp | 4 +- .../pseudo/include/clang-pseudo/GLR.h | 4 +- .../pseudo/include/clang-pseudo/cxx/CXX.h | 2 +- .../include/clang-pseudo/grammar/LRGraph.h| 6 +- .../include/clang-pseudo/grammar/LRTable.h| 5 +- .../pseudo/lib/DirectiveTree.cpp | 8 +- clang-tools-extra/pseudo/lib/GLR.cpp | 19 +-- clang-tools-extra/pseudo/lib/cxx/CXX.cpp | 130 +- .../pseudo/lib/grammar/GrammarBNF.cpp | 8 +- clang-tools-extra/pseudo/tool/ClangPseudo.cpp | 9 +- .../pseudo/unittests/GLRTest.cpp | 38 +++-- 11 files changed, 116 insertions(+), 117 deletions(-) diff --git a/clang-tools-extra/pseudo/gen/Main.cpp b/clang-tools-extra/pseudo/gen/Main.cpp index 25cb26563837a6..779d5077f40ba7 100644 --- a/clang-tools-extra/pseudo/gen/Main.cpp +++ b/clang-tools-extra/pseudo/gen/Main.cpp @@ -74,7 +74,7 @@ std::string mangleSymbol(SymbolID SID, const Grammar &G) { #define TOK(X) llvm::StringRef(#X).upper(), #define KEYWORD(Keyword, Condition) llvm::StringRef(#Keyword).upper(), #include "clang/Basic/TokenKinds.def" - }; + }; if (isToken(SID)) return TokNames[symbolToToken(SID)]; std::string Name = G.symbolName(SID).str(); @@ -84,7 +84,7 @@ std::string mangleSymbol(SymbolID SID, const Grammar &G) { } // Mangles the RHS of a rule definition into a valid identifier. -// +// // These are unique only for a fixed LHS. // e.g. for the grammar rule `ptr-declarator := ptr-operator ptr-declarator`, // it is `ptr_operator__ptr_declarator`. diff --git a/clang-tools-extra/pseudo/include/clang-pseudo/GLR.h b/clang-tools-extra/pseudo/include/clang-pseudo/GLR.h index 0100f818d4ed78..84610b47360b9d 100644 --- a/clang-tools-extra/pseudo/include/clang-pseudo/GLR.h +++ b/clang-tools-extra/pseudo/include/clang-pseudo/GLR.h @@ -120,8 +120,8 @@ struct ParseParams { const TokenStream &Code; // Arena for data structure used by the GLR algorithm. - ForestArena &Forest; // Storage for the output forest. - GSS &GSStack; // Storage for parsing stacks. + ForestArena &Forest; // Storage for the output forest. + GSS &GSStack;// Storage for parsing stacks. }; // Parses the given token stream as the start symbol with the GLR algorithm, diff --git a/clang-tools-extra/pseudo/include/clang-pseudo/cxx/CXX.h b/clang-tools-extra/pseudo/include/clang-pseudo/cxx/CXX.h index 7bbb4d2c00201f..897727ab61ca7a 100644 --- a/clang-tools-extra/pseudo/include/clang-pseudo/cxx/CXX.h +++ b/clang-tools-extra/pseudo/include/clang-pseudo/cxx/CXX.h @@ -65,7 +65,7 @@ enum Rule : RuleID { #define RULE(LHS, RHS, ID) RHS = ID, #include "CXXSymbols.inc" }; -} +} // namespace dummy } // namespace rules } // namespace detail diff --git a/clang-tools-extra/pseudo/include/clang-pseudo/grammar/LRGraph.h b/clang-tools-extra/pseudo/include/clang-pseudo/grammar/LRGraph.h index dd9e87c2c172bf..4527f0e41c9452 100644 --- a/clang-tools-extra/pseudo/include/clang-pseudo/grammar/LRGraph.h +++ b/clang-tools-extra/pseudo/include/clang-pseudo/grammar/LRGraph.h @@ -143,9 +143,9 @@ class LRGraph { // stmt := { . stmt-seq [recover=braces] } // has a Recovery { Src = S, Strategy=braces, Result=stmt-seq }. struct Recovery { -StateID Src; // The state we are in when encountering the error. -ExtensionID Strategy; // Heuristic choosing the tokens to match. -SymbolID Result; // The symbol that is produced. +StateID Src; // The state we are in when encountering the error. +ExtensionID Strategy; // Heuristic choosing the tokens to match. +SymbolID Result; // The symbol that is produced. }; llvm::ArrayRef states() const { return States; } diff --git a/clang-tools-extra/pseudo/include/clang-pseudo/grammar/LRTable.h b/clang-tools-extra/pseudo/include/clang-pseudo/grammar/LRTable.h index 1706b6936c9ea2..26c3d1f6c8c829 100644 --- a/clang-tools-extra/pseudo/include/clang-pseudo/grammar/LRTable.h +++ b/clang-tools-extra/pseudo/include/clang-pseudo/grammar/LRTable.h @@ -76,14 +76,13 @@ class LRTable { // Expected to be called by LR parsers. // If the nonterminal is invalid here, returns std::nullopt.
[clang-tools-extra] [clang-pseudo] clang-format file (PR #87900)
github-actions[bot] wrote: Thank you for submitting a Pull Request (PR) to the LLVM Project! This PR will be automatically labeled and the relevant teams will be notified. If you wish to, you can add reviewers by using the "Reviewers" section on this page. If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using `@` followed by their GitHub username. If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers. If you have further questions, they may be answered by the [LLVM GitHub User Guide](https://llvm.org/docs/GitHub.html). You can also ask questions in a comment on this PR, on the [LLVM Discord](https://discord.com/invite/xS7Z362) or on the [forums](https://discourse.llvm.org/). https://github.com/llvm/llvm-project/pull/87900 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-pseudo] clang-format file (PR #87900)
llvmbot wrote: @llvm/pr-subscribers-clang-tools-extra Author: Jeremy Rifkin (jeremy-rifkin) Changes This PR just clang-formats the `clang-tools-extra/pseudo` directory to make contribution easier. One issue I ran into is clang-format kept changing this region, despite the `clang-format off` directives, which I manually reverted: ``` //clang-format off #define NONTERMINAL(NAME, ID) \ };\ } \ namespace NAME { \ enum Rule : RuleID { //clang-format on ``` --- Patch is 23.04 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/87900.diff 11 Files Affected: - (modified) clang-tools-extra/pseudo/gen/Main.cpp (+2-2) - (modified) clang-tools-extra/pseudo/include/clang-pseudo/GLR.h (+2-2) - (modified) clang-tools-extra/pseudo/include/clang-pseudo/cxx/CXX.h (+1-1) - (modified) clang-tools-extra/pseudo/include/clang-pseudo/grammar/LRGraph.h (+3-3) - (modified) clang-tools-extra/pseudo/include/clang-pseudo/grammar/LRTable.h (+2-3) - (modified) clang-tools-extra/pseudo/lib/DirectiveTree.cpp (+4-4) - (modified) clang-tools-extra/pseudo/lib/GLR.cpp (+11-8) - (modified) clang-tools-extra/pseudo/lib/cxx/CXX.cpp (+67-68) - (modified) clang-tools-extra/pseudo/lib/grammar/GrammarBNF.cpp (+4-4) - (modified) clang-tools-extra/pseudo/tool/ClangPseudo.cpp (+5-4) - (modified) clang-tools-extra/pseudo/unittests/GLRTest.cpp (+16-22) ``diff diff --git a/clang-tools-extra/pseudo/gen/Main.cpp b/clang-tools-extra/pseudo/gen/Main.cpp index 25cb26563837a6..779d5077f40ba7 100644 --- a/clang-tools-extra/pseudo/gen/Main.cpp +++ b/clang-tools-extra/pseudo/gen/Main.cpp @@ -74,7 +74,7 @@ std::string mangleSymbol(SymbolID SID, const Grammar &G) { #define TOK(X) llvm::StringRef(#X).upper(), #define KEYWORD(Keyword, Condition) llvm::StringRef(#Keyword).upper(), #include "clang/Basic/TokenKinds.def" - }; + }; if (isToken(SID)) return TokNames[symbolToToken(SID)]; std::string Name = G.symbolName(SID).str(); @@ -84,7 +84,7 @@ std::string mangleSymbol(SymbolID SID, const Grammar &G) { } // Mangles the RHS of a rule definition into a valid identifier. -// +// // These are unique only for a fixed LHS. // e.g. for the grammar rule `ptr-declarator := ptr-operator ptr-declarator`, // it is `ptr_operator__ptr_declarator`. diff --git a/clang-tools-extra/pseudo/include/clang-pseudo/GLR.h b/clang-tools-extra/pseudo/include/clang-pseudo/GLR.h index 0100f818d4ed78..84610b47360b9d 100644 --- a/clang-tools-extra/pseudo/include/clang-pseudo/GLR.h +++ b/clang-tools-extra/pseudo/include/clang-pseudo/GLR.h @@ -120,8 +120,8 @@ struct ParseParams { const TokenStream &Code; // Arena for data structure used by the GLR algorithm. - ForestArena &Forest; // Storage for the output forest. - GSS &GSStack; // Storage for parsing stacks. + ForestArena &Forest; // Storage for the output forest. + GSS &GSStack;// Storage for parsing stacks. }; // Parses the given token stream as the start symbol with the GLR algorithm, diff --git a/clang-tools-extra/pseudo/include/clang-pseudo/cxx/CXX.h b/clang-tools-extra/pseudo/include/clang-pseudo/cxx/CXX.h index 7bbb4d2c00201f..897727ab61ca7a 100644 --- a/clang-tools-extra/pseudo/include/clang-pseudo/cxx/CXX.h +++ b/clang-tools-extra/pseudo/include/clang-pseudo/cxx/CXX.h @@ -65,7 +65,7 @@ enum Rule : RuleID { #define RULE(LHS, RHS, ID) RHS = ID, #include "CXXSymbols.inc" }; -} +} // namespace dummy } // namespace rules } // namespace detail diff --git a/clang-tools-extra/pseudo/include/clang-pseudo/grammar/LRGraph.h b/clang-tools-extra/pseudo/include/clang-pseudo/grammar/LRGraph.h index dd9e87c2c172bf..4527f0e41c9452 100644 --- a/clang-tools-extra/pseudo/include/clang-pseudo/grammar/LRGraph.h +++ b/clang-tools-extra/pseudo/include/clang-pseudo/grammar/LRGraph.h @@ -143,9 +143,9 @@ class LRGraph { // stmt := { . stmt-seq [recover=braces] } // has a Recovery { Src = S, Strategy=braces, Result=stmt-seq }. struct Recovery { -StateID Src; // The state we are in when encountering the error. -ExtensionID Strategy; // Heuristic choosing the tokens to match. -SymbolID Result; // The symbol that is produced. +StateID Src; // The state we are in when encountering the error. +ExtensionID Strategy; // Heuristic choosing the tokens to match. +SymbolID Result; // The symbol that is produced. }; llvm::ArrayRef states() const { return States; } diff --git a/clang-tools-extra/pseudo/include/clang-pseudo/grammar/LRTable.h b/clang-tools-extra/pseudo/include/clang-pseudo/grammar/LRTable.h index 1706b6936c9ea2..26c3d1f6c8c829 100644 --- a/clang-tools-extra/pseudo/include/clang-pseudo/grammar/LRTable.h +++ b/clang-tools-extra/pseudo/include/clang-pseudo/grammar/LRTable.h @@ -76,14 +76,13 @@ class LRTable { // Expected to be called by LR parsers. // If the nonterminal is inv
[clang-tools-extra] [clang-pseudo] clang-format files (PR #87900)
https://github.com/jeremy-rifkin edited https://github.com/llvm/llvm-project/pull/87900 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-pseudo] Add a --print-terminal-tokens option (PR #87898)
https://github.com/jeremy-rifkin updated https://github.com/llvm/llvm-project/pull/87898 >From 2ebb15e08b5e2d8a9fe6cfddbe0dd2a8942b2542 Mon Sep 17 00:00:00 2001 From: Jeremy <51220084+jeremy-rif...@users.noreply.github.com> Date: Sat, 6 Apr 2024 17:02:20 -0500 Subject: [PATCH 1/2] Add a --print-terminal-tokens option --- clang-tools-extra/pseudo/fuzzer/Fuzzer.cpp| 2 +- .../pseudo/include/clang-pseudo/Forest.h | 11 ++-- clang-tools-extra/pseudo/lib/Forest.cpp | 26 +-- clang-tools-extra/pseudo/tool/ClangPseudo.cpp | 12 +++-- 4 files changed, 38 insertions(+), 13 deletions(-) diff --git a/clang-tools-extra/pseudo/fuzzer/Fuzzer.cpp b/clang-tools-extra/pseudo/fuzzer/Fuzzer.cpp index 87b9d15480cc35..33b3da1ed6ea9f 100644 --- a/clang-tools-extra/pseudo/fuzzer/Fuzzer.cpp +++ b/clang-tools-extra/pseudo/fuzzer/Fuzzer.cpp @@ -46,7 +46,7 @@ class Fuzzer { glrParse(clang::pseudo::ParseParams{ParseableStream, Arena, GSS}, *Lang.G.findNonterminal("translation-unit"), Lang); if (Print) - llvm::outs() << Root.dumpRecursive(Lang.G); + llvm::outs() << Root.dumpRecursive(Lang.G, std::nullopt); } }; diff --git a/clang-tools-extra/pseudo/include/clang-pseudo/Forest.h b/clang-tools-extra/pseudo/include/clang-pseudo/Forest.h index e9edb40e02b64e..642c489b3fba41 100644 --- a/clang-tools-extra/pseudo/include/clang-pseudo/Forest.h +++ b/clang-tools-extra/pseudo/include/clang-pseudo/Forest.h @@ -26,6 +26,8 @@ #include "llvm/ADT/STLExtras.h" #include "llvm/Support/Allocator.h" #include +#include +#include namespace clang { namespace pseudo { @@ -112,8 +114,13 @@ class alignas(class ForestNode *) ForestNode { // Iteration over all nodes in the forest, including this. llvm::iterator_range descendants() const; - std::string dump(const Grammar &) const; - std::string dumpRecursive(const Grammar &, bool Abbreviated = false) const; + std::string + dump(const Grammar &, + std::optional>) const; + std::string + dumpRecursive(const Grammar &, +std::optional>, +bool Abbreviated = false) const; private: friend class ForestArena; diff --git a/clang-tools-extra/pseudo/lib/Forest.cpp b/clang-tools-extra/pseudo/lib/Forest.cpp index e8e60e5ec475a4..adce731d6c1e1c 100644 --- a/clang-tools-extra/pseudo/lib/Forest.cpp +++ b/clang-tools-extra/pseudo/lib/Forest.cpp @@ -45,13 +45,21 @@ ForestNode::descendants() const { return {RecursiveIterator(this), RecursiveIterator()}; } -std::string ForestNode::dump(const Grammar &G) const { +std::string ForestNode::dump( +const Grammar &G, +std::optional> Code) const { switch (kind()) { case Ambiguous: return llvm::formatv("{0} := ", G.symbolName(symbol())); case Terminal: -return llvm::formatv("{0} := tok[{1}]", G.symbolName(symbol()), - startTokenIndex()); +if (Code) { + return llvm::formatv("{0} := tok[{1}] ({2})", G.symbolName(symbol()), + startTokenIndex(), + Code->get().tokens()[startTokenIndex()]); +} else { + return llvm::formatv("{0} := tok[{1}]", G.symbolName(symbol()), + startTokenIndex()); +} case Sequence: return G.dumpRule(rule()); case Opaque: @@ -60,8 +68,10 @@ std::string ForestNode::dump(const Grammar &G) const { llvm_unreachable("Unhandled node kind!"); } -std::string ForestNode::dumpRecursive(const Grammar &G, - bool Abbreviated) const { +std::string ForestNode::dumpRecursive( +const Grammar &G, +std::optional> Code, +bool Abbreviated) const { using llvm::formatv; Token::Index MaxToken = 0; // Count visits of nodes so we can mark those seen multiple times. @@ -95,7 +105,7 @@ std::string ForestNode::dumpRecursive(const Grammar &G, std::string Result; constexpr Token::Index KEnd = std::numeric_limits::max(); std::function, - LineDecoration &LineDec)> + LineDecoration LineDec)> Dump = [&](const ForestNode *P, Token::Index End, std::optional ElidedParent, LineDecoration LineDec) { bool SharedNode = VisitCounts.find(P)->getSecond() > 1; @@ -145,13 +155,13 @@ std::string ForestNode::dumpRecursive(const Grammar &G, // The first time, print as #1. Later, =#1. if (First) { -Result += formatv("{0} #{1}", P->dump(G), ID); +Result += formatv("{0} #{1}", P->dump(G, Code), ID); } else { Result += formatv("{0} =#{1}", G.symbolName(P->symbol()), ID); Children = {}; // Don't walk the children again. } } else { - Result.append(P->dump(G)); + Result.append(P->dump(G, Code)); } Result.push_back('\n'); diff --git a/clang-tools-extra/pseudo/tool/ClangPseudo.cpp b/clang-tools-extra/pseudo/tool/ClangPseud
[clang] [X86_64] fix arg pass error in struct. (PR #86902)
@@ -2100,8 +2100,12 @@ void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase, Class &Lo, postMerge(Size, Lo, Hi); return; } + + bool InMemory = Offset % getContext().getTypeAlign(i->getType()) || + (i->getType()->getAs() && CoTinker wrote: I think it's a really good idea. https://github.com/llvm/llvm-project/pull/86902 ___ 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 fix-its to `avoid-return-with-void-value` check (PR #81420)
Danny =?utf-8?q?M=C3=B6sch?= , Danny =?utf-8?q?M=C3=B6sch?= , Danny =?utf-8?q?M=C3=B6sch?= , Danny =?utf-8?q?M=C3=B6sch?= Message-ID: In-Reply-To: https://github.com/HerrCai0907 approved this pull request. https://github.com/llvm/llvm-project/pull/81420 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] d08a76d - Fix warnings discovered by #87348 [-Wunused-but-set-variable]
Author: NAKAMURA Takumi Date: 2024-04-07T11:02:08+09:00 New Revision: d08a76d1ac1ba6b376faa908ccbaaabc999dfbc5 URL: https://github.com/llvm/llvm-project/commit/d08a76d1ac1ba6b376faa908ccbaaabc999dfbc5 DIFF: https://github.com/llvm/llvm-project/commit/d08a76d1ac1ba6b376faa908ccbaaabc999dfbc5.diff LOG: Fix warnings discovered by #87348 [-Wunused-but-set-variable] Added: Modified: clang/lib/AST/Interp/ByteCodeExprGen.cpp clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp clang/lib/Sema/SemaOverload.cpp llvm/lib/Transforms/Utils/BasicBlockUtils.cpp Removed: diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp b/clang/lib/AST/Interp/ByteCodeExprGen.cpp index 46182809810bcf..50e86d94736476 100644 --- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp +++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp @@ -2511,6 +2511,7 @@ unsigned ByteCodeExprGen::allocateLocalPrimitive(DeclTy &&Src, dyn_cast_if_present(Src.dyn_cast())) { assert(!P.getGlobal(VD)); assert(!Locals.contains(VD)); +(void)VD; } // FIXME: There are cases where Src.is() is wrong, e.g. diff --git a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp index 70ac0764476f60..1bfa7ebcfd50c9 100644 --- a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp +++ b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp @@ -850,6 +850,7 @@ void Environment::setValue(const Expr &E, Value &Val) { if (auto *RecordVal = dyn_cast(&Val)) { assert(isOriginalRecordConstructor(CanonE) || &RecordVal->getLoc() == &getResultObjectLocation(CanonE)); +(void)RecordVal; } assert(CanonE.isPRValue()); diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp index 0c913bc700f4a1..3808af37ff54a8 100644 --- a/clang/lib/Sema/SemaOverload.cpp +++ b/clang/lib/Sema/SemaOverload.cpp @@ -6354,6 +6354,7 @@ Sema::EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value, // by this point. assert(CE->getResultStorageKind() != ConstantResultStorageKind::None && "ConstantExpr has no value associated with it"); +(void)CE; } else { E = ConstantExpr::Create(Context, Result.get(), Value); } diff --git a/llvm/lib/Transforms/Utils/BasicBlockUtils.cpp b/llvm/lib/Transforms/Utils/BasicBlockUtils.cpp index 915cd81661f027..5396038d8b92b7 100644 --- a/llvm/lib/Transforms/Utils/BasicBlockUtils.cpp +++ b/llvm/lib/Transforms/Utils/BasicBlockUtils.cpp @@ -784,7 +784,7 @@ BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, DominatorTree *DT, // If the successor only has a single pred, split the top of the successor // block. assert(SP == BB && "CFG broken"); -SP = nullptr; +(void)SP; return SplitBlock(Succ, &Succ->front(), DT, LI, MSSAU, BBName, /*Before=*/true); } ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [C++20] [Modules] Introduce -fexperimental-modules-reduced-bmi (PR #85050)
https://github.com/ChuanqiXu9 updated https://github.com/llvm/llvm-project/pull/85050 >From 8c51aa534a20655a6a86a84f1050efd850130afd Mon Sep 17 00:00:00 2001 From: Chuanqi Xu Date: Tue, 12 Mar 2024 17:26:49 +0800 Subject: [PATCH] [C++20] [Modules] Introduce -fgen-reduced-bmi --- clang/include/clang/CodeGen/CodeGenAction.h | 2 + clang/include/clang/Driver/Options.td | 6 +++ .../include/clang/Frontend/FrontendOptions.h | 11 clang/lib/CodeGen/CodeGenAction.cpp | 19 +++ clang/lib/Driver/Driver.cpp | 12 - clang/lib/Driver/ToolChains/Clang.cpp | 18 +++ clang/lib/Frontend/FrontendActions.cpp| 7 +++ .../test/Driver/module-fgen-reduced-bmi.cppm | 51 +++ clang/test/Modules/modules-reduced-bmi.cppm | 36 + 9 files changed, 161 insertions(+), 1 deletion(-) create mode 100644 clang/test/Driver/module-fgen-reduced-bmi.cppm create mode 100644 clang/test/Modules/modules-reduced-bmi.cppm diff --git a/clang/include/clang/CodeGen/CodeGenAction.h b/clang/include/clang/CodeGen/CodeGenAction.h index 7ad2988e589eb2..186dbb43f01ef7 100644 --- a/clang/include/clang/CodeGen/CodeGenAction.h +++ b/clang/include/clang/CodeGen/CodeGenAction.h @@ -57,6 +57,8 @@ class CodeGenAction : public ASTFrontendAction { bool loadLinkModules(CompilerInstance &CI); protected: + bool BeginSourceFileAction(CompilerInstance &CI) override; + /// Create a new code generation action. If the optional \p _VMContext /// parameter is supplied, the action uses it without taking ownership, /// otherwise it creates a fresh LLVM context and takes ownership. diff --git a/clang/include/clang/Driver/Options.td b/clang/include/clang/Driver/Options.td index 827d9d7c0c18e4..09feb1c775e2e8 100644 --- a/clang/include/clang/Driver/Options.td +++ b/clang/include/clang/Driver/Options.td @@ -3034,6 +3034,7 @@ defm prebuilt_implicit_modules : BoolFOption<"prebuilt-implicit-modules", def fmodule_output_EQ : Joined<["-"], "fmodule-output=">, Flags<[NoXarchOption]>, Visibility<[ClangOption, CC1Option]>, + MarshallingInfoString>, HelpText<"Save intermediate module file results when compiling a standard C++ module unit.">; def fmodule_output : Flag<["-"], "fmodule-output">, Flags<[NoXarchOption]>, Visibility<[ClangOption, CC1Option]>, @@ -3047,6 +3048,11 @@ defm skip_odr_check_in_gmf : BoolOption<"f", "skip-odr-check-in-gmf", "Perform ODR checks for decls in the global module fragment.">>, Group; +def modules_reduced_bmi : Flag<["-"], "fexperimental-modules-reduced-bmi">, + Group, Visibility<[ClangOption, CC1Option]>, + HelpText<"Generate the reduced BMI">, + MarshallingInfoFlag>; + def fmodules_prune_interval : Joined<["-"], "fmodules-prune-interval=">, Group, Visibility<[ClangOption, CC1Option]>, MetaVarName<"">, HelpText<"Specify the interval (in seconds) between attempts to prune the module cache">, diff --git a/clang/include/clang/Frontend/FrontendOptions.h b/clang/include/clang/Frontend/FrontendOptions.h index 5ee4d471670f48..5479d13aab 100644 --- a/clang/include/clang/Frontend/FrontendOptions.h +++ b/clang/include/clang/Frontend/FrontendOptions.h @@ -404,6 +404,10 @@ class FrontendOptions { LLVM_PREFERRED_TYPE(bool) unsigned EmitPrettySymbolGraphs : 1; + /// Whether to generate reduced BMI for C++20 named modules. + LLVM_PREFERRED_TYPE(bool) + unsigned GenReducedBMI : 1; + CodeCompleteOptions CodeCompleteOpts; /// Specifies the output format of the AST. @@ -568,6 +572,9 @@ class FrontendOptions { /// Path which stores the output files for -ftime-trace std::string TimeTracePath; + /// Output Path for module output file. + std::string ModuleOutputPath; + public: FrontendOptions() : DisableFree(false), RelocatablePCH(false), ShowHelp(false), @@ -580,9 +587,13 @@ class FrontendOptions { BuildingImplicitModuleUsesLock(true), ModulesEmbedAllFiles(false), IncludeTimestamps(true), UseTemporary(true), AllowPCMWithCompilerErrors(false), ModulesShareFileManager(true), +<<< HEAD EmitSymbolGraph(false), EmitExtensionSymbolGraphs(false), EmitSymbolGraphSymbolLabelsForTesting(false), EmitPrettySymbolGraphs(false), TimeTraceGranularity(500) {} +=== +GenReducedBMI(false), TimeTraceGranularity(500) {} +>>> 8baafcdac143 ([C++20] [Modules] Introduce -fgen-reduced-bmi) /// getInputKindForExtension - Return the appropriate input kind for a file /// extension. For example, "c" would return Language::C. diff --git a/clang/lib/CodeGen/CodeGenAction.cpp b/clang/lib/CodeGen/CodeGenAction.cpp index bb9aaba025fa59..cd0d011e8c72b0 100644 --- a/clang/lib/CodeGen/CodeGenAction.cpp +++ b/clang/lib/CodeGen/CodeGenAction.cpp @@ -25,8 +25,11 @@ #include "clang/CodeGen/ModuleBuilder.h" #include "clang/Driver/DriverDiagnostic.h" #include "clang/Frontend/CompilerInstance.h" +#include "clang/Frontend/
[clang] [C++20] [Modules] Introduce -fexperimental-modules-reduced-bmi (PR #85050)
ChuanqiXu9 wrote: Rebased with main. @dwblaikie may you have more comments? https://github.com/llvm/llvm-project/pull/85050 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [C++20] [Modules] Introduce -fexperimental-modules-reduced-bmi (PR #85050)
https://github.com/ChuanqiXu9 updated https://github.com/llvm/llvm-project/pull/85050 >From 7b0b9b52ac06a78a172e3628ab7fb3cdb3749d13 Mon Sep 17 00:00:00 2001 From: Chuanqi Xu Date: Tue, 12 Mar 2024 17:26:49 +0800 Subject: [PATCH] [C++20] [Modules] Introduce -fgen-reduced-bmi --- clang/include/clang/CodeGen/CodeGenAction.h | 2 + clang/include/clang/Driver/Options.td | 6 +++ .../include/clang/Frontend/FrontendOptions.h | 10 +++- clang/lib/CodeGen/CodeGenAction.cpp | 19 +++ clang/lib/Driver/Driver.cpp | 12 - clang/lib/Driver/ToolChains/Clang.cpp | 18 +++ clang/lib/Frontend/FrontendActions.cpp| 7 +++ .../test/Driver/module-fgen-reduced-bmi.cppm | 51 +++ clang/test/Modules/modules-reduced-bmi.cppm | 36 + 9 files changed, 159 insertions(+), 2 deletions(-) create mode 100644 clang/test/Driver/module-fgen-reduced-bmi.cppm create mode 100644 clang/test/Modules/modules-reduced-bmi.cppm diff --git a/clang/include/clang/CodeGen/CodeGenAction.h b/clang/include/clang/CodeGen/CodeGenAction.h index 7ad2988e589eb2..186dbb43f01ef7 100644 --- a/clang/include/clang/CodeGen/CodeGenAction.h +++ b/clang/include/clang/CodeGen/CodeGenAction.h @@ -57,6 +57,8 @@ class CodeGenAction : public ASTFrontendAction { bool loadLinkModules(CompilerInstance &CI); protected: + bool BeginSourceFileAction(CompilerInstance &CI) override; + /// Create a new code generation action. If the optional \p _VMContext /// parameter is supplied, the action uses it without taking ownership, /// otherwise it creates a fresh LLVM context and takes ownership. diff --git a/clang/include/clang/Driver/Options.td b/clang/include/clang/Driver/Options.td index 827d9d7c0c18e4..09feb1c775e2e8 100644 --- a/clang/include/clang/Driver/Options.td +++ b/clang/include/clang/Driver/Options.td @@ -3034,6 +3034,7 @@ defm prebuilt_implicit_modules : BoolFOption<"prebuilt-implicit-modules", def fmodule_output_EQ : Joined<["-"], "fmodule-output=">, Flags<[NoXarchOption]>, Visibility<[ClangOption, CC1Option]>, + MarshallingInfoString>, HelpText<"Save intermediate module file results when compiling a standard C++ module unit.">; def fmodule_output : Flag<["-"], "fmodule-output">, Flags<[NoXarchOption]>, Visibility<[ClangOption, CC1Option]>, @@ -3047,6 +3048,11 @@ defm skip_odr_check_in_gmf : BoolOption<"f", "skip-odr-check-in-gmf", "Perform ODR checks for decls in the global module fragment.">>, Group; +def modules_reduced_bmi : Flag<["-"], "fexperimental-modules-reduced-bmi">, + Group, Visibility<[ClangOption, CC1Option]>, + HelpText<"Generate the reduced BMI">, + MarshallingInfoFlag>; + def fmodules_prune_interval : Joined<["-"], "fmodules-prune-interval=">, Group, Visibility<[ClangOption, CC1Option]>, MetaVarName<"">, HelpText<"Specify the interval (in seconds) between attempts to prune the module cache">, diff --git a/clang/include/clang/Frontend/FrontendOptions.h b/clang/include/clang/Frontend/FrontendOptions.h index 5ee4d471670f48..a738c1f3757682 100644 --- a/clang/include/clang/Frontend/FrontendOptions.h +++ b/clang/include/clang/Frontend/FrontendOptions.h @@ -404,6 +404,10 @@ class FrontendOptions { LLVM_PREFERRED_TYPE(bool) unsigned EmitPrettySymbolGraphs : 1; + /// Whether to generate reduced BMI for C++20 named modules. + LLVM_PREFERRED_TYPE(bool) + unsigned GenReducedBMI : 1; + CodeCompleteOptions CodeCompleteOpts; /// Specifies the output format of the AST. @@ -568,6 +572,9 @@ class FrontendOptions { /// Path which stores the output files for -ftime-trace std::string TimeTracePath; + /// Output Path for module output file. + std::string ModuleOutputPath; + public: FrontendOptions() : DisableFree(false), RelocatablePCH(false), ShowHelp(false), @@ -582,7 +589,8 @@ class FrontendOptions { AllowPCMWithCompilerErrors(false), ModulesShareFileManager(true), EmitSymbolGraph(false), EmitExtensionSymbolGraphs(false), EmitSymbolGraphSymbolLabelsForTesting(false), -EmitPrettySymbolGraphs(false), TimeTraceGranularity(500) {} +EmitPrettySymbolGraphs(false), GenReducedBMI(false), +TimeTraceGranularity(500) {} /// getInputKindForExtension - Return the appropriate input kind for a file /// extension. For example, "c" would return Language::C. diff --git a/clang/lib/CodeGen/CodeGenAction.cpp b/clang/lib/CodeGen/CodeGenAction.cpp index bb9aaba025fa59..cd0d011e8c72b0 100644 --- a/clang/lib/CodeGen/CodeGenAction.cpp +++ b/clang/lib/CodeGen/CodeGenAction.cpp @@ -25,8 +25,11 @@ #include "clang/CodeGen/ModuleBuilder.h" #include "clang/Driver/DriverDiagnostic.h" #include "clang/Frontend/CompilerInstance.h" +#include "clang/Frontend/FrontendActions.h" #include "clang/Frontend/FrontendDiagnostic.h" +#include "clang/Frontend/MultiplexConsumer.h" #include "clang/Lex/Preprocessor.h" +#include "clang/Serialization/A
[clang] [Clang][Sema] Skip checking anonymous enum in using enum declaration (PR #87144)
@@ -1537,6 +1537,10 @@ void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { cast(D)->isFunctionTemplateSpecialization()) return; + if (isa(D) && D->getDeclName().isEmpty()) { jcsxky wrote: `Sema::ActOnUsingEnumDeclaration` invoke `PushOnScopeChains` when `D` is a `UsingEnumDecl` (anonymous or not) and do some extra works. Just add the declaration would skip checking even it's not anonymous. https://github.com/llvm/llvm-project/pull/87144 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Modules] No transitive source location change (PR #86912)
https://github.com/ChuanqiXu9 updated https://github.com/llvm/llvm-project/pull/86912 >From 8e07cbdd0f348484d532d7827e4b4a7888e70978 Mon Sep 17 00:00:00 2001 From: Chuanqi Xu Date: Mon, 18 Mar 2024 08:36:55 +0800 Subject: [PATCH] [Modules] No transitive source location change --- clang/include/clang/Basic/SourceLocation.h| 1 + .../include/clang/Serialization/ASTBitCodes.h | 56 ++-- clang/include/clang/Serialization/ASTReader.h | 54 +++- clang/include/clang/Serialization/ASTWriter.h | 4 + .../include/clang/Serialization/ModuleFile.h | 4 - .../Serialization/SourceLocationEncoding.h| 88 +-- clang/lib/Frontend/ASTUnit.cpp| 2 - clang/lib/Serialization/ASTReader.cpp | 84 +++--- clang/lib/Serialization/ASTReaderDecl.cpp | 2 +- clang/lib/Serialization/ASTWriter.cpp | 41 +++-- clang/lib/Serialization/ASTWriterDecl.cpp | 8 +- clang/lib/Serialization/ModuleFile.cpp| 1 - .../no-transitive-source-location-change.cppm | 69 +++ clang/test/Modules/pr61067.cppm | 25 -- .../SourceLocationEncodingTest.cpp| 12 +-- 15 files changed, 275 insertions(+), 176 deletions(-) create mode 100644 clang/test/Modules/no-transitive-source-location-change.cppm diff --git a/clang/include/clang/Basic/SourceLocation.h b/clang/include/clang/Basic/SourceLocation.h index 00b1e0fa855b7a..7a0f5ba8d1270b 100644 --- a/clang/include/clang/Basic/SourceLocation.h +++ b/clang/include/clang/Basic/SourceLocation.h @@ -90,6 +90,7 @@ class SourceLocation { friend class ASTWriter; friend class SourceManager; friend struct llvm::FoldingSetTrait; + friend class SourceLocationEncoding; public: using UIntTy = uint32_t; diff --git a/clang/include/clang/Serialization/ASTBitCodes.h b/clang/include/clang/Serialization/ASTBitCodes.h index f762116fea956c..f94b32d762effc 100644 --- a/clang/include/clang/Serialization/ASTBitCodes.h +++ b/clang/include/clang/Serialization/ASTBitCodes.h @@ -22,6 +22,7 @@ #include "clang/Basic/IdentifierTable.h" #include "clang/Basic/OperatorKinds.h" #include "clang/Basic/SourceLocation.h" +#include "clang/Serialization/SourceLocationEncoding.h" #include "llvm/ADT/DenseMapInfo.h" #include "llvm/Bitstream/BitCodes.h" #include @@ -175,45 +176,38 @@ const unsigned int NUM_PREDEF_SUBMODULE_IDS = 1; /// Source range/offset of a preprocessed entity. struct PPEntityOffset { + using RawLocEncoding = SourceLocationEncoding::RawLocEncoding; + /// Raw source location of beginning of range. - SourceLocation::UIntTy Begin; + RawLocEncoding Begin; /// Raw source location of end of range. - SourceLocation::UIntTy End; + RawLocEncoding End; /// Offset in the AST file relative to ModuleFile::MacroOffsetsBase. uint32_t BitOffset; - PPEntityOffset(SourceRange R, uint32_t BitOffset) - : Begin(R.getBegin().getRawEncoding()), End(R.getEnd().getRawEncoding()), -BitOffset(BitOffset) {} - - SourceLocation getBegin() const { -return SourceLocation::getFromRawEncoding(Begin); - } + PPEntityOffset(RawLocEncoding Begin, RawLocEncoding End, uint32_t BitOffset) + : Begin(Begin), End(End), BitOffset(BitOffset) {} - SourceLocation getEnd() const { -return SourceLocation::getFromRawEncoding(End); - } + RawLocEncoding getBegin() const { return Begin; } + RawLocEncoding getEnd() const { return End; } }; /// Source range of a skipped preprocessor region struct PPSkippedRange { + using RawLocEncoding = SourceLocationEncoding::RawLocEncoding; + /// Raw source location of beginning of range. - SourceLocation::UIntTy Begin; + RawLocEncoding Begin; /// Raw source location of end of range. - SourceLocation::UIntTy End; + RawLocEncoding End; - PPSkippedRange(SourceRange R) - : Begin(R.getBegin().getRawEncoding()), End(R.getEnd().getRawEncoding()) { - } + PPSkippedRange(RawLocEncoding Begin, RawLocEncoding End) + : Begin(Begin), End(End) {} - SourceLocation getBegin() const { -return SourceLocation::getFromRawEncoding(Begin); - } - SourceLocation getEnd() const { -return SourceLocation::getFromRawEncoding(End); - } + RawLocEncoding getBegin() const { return Begin; } + RawLocEncoding getEnd() const { return End; } }; /// Offset in the AST file. Use splitted 64-bit integer into low/high @@ -239,8 +233,10 @@ struct UnderalignedInt64 { /// Source location and bit offset of a declaration. struct DeclOffset { + using RawLocEncoding = SourceLocationEncoding::RawLocEncoding; + /// Raw source location. - SourceLocation::UIntTy Loc = 0; + RawLocEncoding RawLoc = 0; /// Offset relative to the start of the DECLTYPES_BLOCK block. Keep /// structure alignment 32-bit and avoid padding gap because undefined @@ -248,17 +244,15 @@ struct DeclOffset { UnderalignedInt64 BitOffset; DeclOffset() = default; - DeclOffset(SourceLocation Loc, uint64_t BitOffset, -
[clang] [Modules] No transitive source location change (PR #86912)
https://github.com/ChuanqiXu9 edited https://github.com/llvm/llvm-project/pull/86912 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Modules] No transitive source location change (PR #86912)
ChuanqiXu9 wrote: Rebase with main and enabling the sequence optimization when the module file index is 0. Now the size of the PCMs goes to 204M (originally it is 200M). It looks better. @jansvoboda11 @Bigcheese ping https://github.com/llvm/llvm-project/pull/86912 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-pseudo] Add a --print-terminal-tokens option (PR #87898)
https://github.com/jeremy-rifkin updated https://github.com/llvm/llvm-project/pull/87898 >From 2ebb15e08b5e2d8a9fe6cfddbe0dd2a8942b2542 Mon Sep 17 00:00:00 2001 From: Jeremy <51220084+jeremy-rif...@users.noreply.github.com> Date: Sat, 6 Apr 2024 17:02:20 -0500 Subject: [PATCH 1/3] Add a --print-terminal-tokens option --- clang-tools-extra/pseudo/fuzzer/Fuzzer.cpp| 2 +- .../pseudo/include/clang-pseudo/Forest.h | 11 ++-- clang-tools-extra/pseudo/lib/Forest.cpp | 26 +-- clang-tools-extra/pseudo/tool/ClangPseudo.cpp | 12 +++-- 4 files changed, 38 insertions(+), 13 deletions(-) diff --git a/clang-tools-extra/pseudo/fuzzer/Fuzzer.cpp b/clang-tools-extra/pseudo/fuzzer/Fuzzer.cpp index 87b9d15480cc35..33b3da1ed6ea9f 100644 --- a/clang-tools-extra/pseudo/fuzzer/Fuzzer.cpp +++ b/clang-tools-extra/pseudo/fuzzer/Fuzzer.cpp @@ -46,7 +46,7 @@ class Fuzzer { glrParse(clang::pseudo::ParseParams{ParseableStream, Arena, GSS}, *Lang.G.findNonterminal("translation-unit"), Lang); if (Print) - llvm::outs() << Root.dumpRecursive(Lang.G); + llvm::outs() << Root.dumpRecursive(Lang.G, std::nullopt); } }; diff --git a/clang-tools-extra/pseudo/include/clang-pseudo/Forest.h b/clang-tools-extra/pseudo/include/clang-pseudo/Forest.h index e9edb40e02b64e..642c489b3fba41 100644 --- a/clang-tools-extra/pseudo/include/clang-pseudo/Forest.h +++ b/clang-tools-extra/pseudo/include/clang-pseudo/Forest.h @@ -26,6 +26,8 @@ #include "llvm/ADT/STLExtras.h" #include "llvm/Support/Allocator.h" #include +#include +#include namespace clang { namespace pseudo { @@ -112,8 +114,13 @@ class alignas(class ForestNode *) ForestNode { // Iteration over all nodes in the forest, including this. llvm::iterator_range descendants() const; - std::string dump(const Grammar &) const; - std::string dumpRecursive(const Grammar &, bool Abbreviated = false) const; + std::string + dump(const Grammar &, + std::optional>) const; + std::string + dumpRecursive(const Grammar &, +std::optional>, +bool Abbreviated = false) const; private: friend class ForestArena; diff --git a/clang-tools-extra/pseudo/lib/Forest.cpp b/clang-tools-extra/pseudo/lib/Forest.cpp index e8e60e5ec475a4..adce731d6c1e1c 100644 --- a/clang-tools-extra/pseudo/lib/Forest.cpp +++ b/clang-tools-extra/pseudo/lib/Forest.cpp @@ -45,13 +45,21 @@ ForestNode::descendants() const { return {RecursiveIterator(this), RecursiveIterator()}; } -std::string ForestNode::dump(const Grammar &G) const { +std::string ForestNode::dump( +const Grammar &G, +std::optional> Code) const { switch (kind()) { case Ambiguous: return llvm::formatv("{0} := ", G.symbolName(symbol())); case Terminal: -return llvm::formatv("{0} := tok[{1}]", G.symbolName(symbol()), - startTokenIndex()); +if (Code) { + return llvm::formatv("{0} := tok[{1}] ({2})", G.symbolName(symbol()), + startTokenIndex(), + Code->get().tokens()[startTokenIndex()]); +} else { + return llvm::formatv("{0} := tok[{1}]", G.symbolName(symbol()), + startTokenIndex()); +} case Sequence: return G.dumpRule(rule()); case Opaque: @@ -60,8 +68,10 @@ std::string ForestNode::dump(const Grammar &G) const { llvm_unreachable("Unhandled node kind!"); } -std::string ForestNode::dumpRecursive(const Grammar &G, - bool Abbreviated) const { +std::string ForestNode::dumpRecursive( +const Grammar &G, +std::optional> Code, +bool Abbreviated) const { using llvm::formatv; Token::Index MaxToken = 0; // Count visits of nodes so we can mark those seen multiple times. @@ -95,7 +105,7 @@ std::string ForestNode::dumpRecursive(const Grammar &G, std::string Result; constexpr Token::Index KEnd = std::numeric_limits::max(); std::function, - LineDecoration &LineDec)> + LineDecoration LineDec)> Dump = [&](const ForestNode *P, Token::Index End, std::optional ElidedParent, LineDecoration LineDec) { bool SharedNode = VisitCounts.find(P)->getSecond() > 1; @@ -145,13 +155,13 @@ std::string ForestNode::dumpRecursive(const Grammar &G, // The first time, print as #1. Later, =#1. if (First) { -Result += formatv("{0} #{1}", P->dump(G), ID); +Result += formatv("{0} #{1}", P->dump(G, Code), ID); } else { Result += formatv("{0} =#{1}", G.symbolName(P->symbol()), ID); Children = {}; // Don't walk the children again. } } else { - Result.append(P->dump(G)); + Result.append(P->dump(G, Code)); } Result.push_back('\n'); diff --git a/clang-tools-extra/pseudo/tool/ClangPseudo.cpp b/clang-tools-extra/pseudo/tool/ClangPseud
[clang] [llvm] [clang][llvm] Remove "implicit-section-name" attribute (PR #87906)
https://github.com/aeubanks created https://github.com/llvm/llvm-project/pull/87906 D33412/D33413 introduced this to support a clang pragma to set section names for a symbol depending on if it would be placed in bss/data/rodata/text, which may not be known until the backend. However, for text we know that only functions will go there, so just directly set the section in clang instead of going through a completely separate attribute. >From 7a9df42b4c4f4f1b02dc3158d24800f3d4b68d8f Mon Sep 17 00:00:00 2001 From: Arthur Eubanks Date: Sun, 7 Apr 2024 05:29:36 + Subject: [PATCH] [clang][llvm] Remove "implicit-section-name" attribute D33412/D33413 introduced this to support a clang pragma to set section names for a symbol depending on if it would be placed in bss/data/rodata/text, which may not be known until the backend. However, for text we know that only functions will go there, so just directly set the section in clang instead of going through a completely separate attribute. --- clang/lib/CodeGen/CodeGenModule.cpp | 2 +- clang/test/CodeGen/clang-sections-attribute.c | 3 --- clang/test/CodeGenCXX/clang-sections.cpp | 18 ++--- llvm/lib/CodeGen/TargetInstrInfo.cpp | 3 +-- .../CodeGen/TargetLoweringObjectFileImpl.cpp | 11 +--- llvm/lib/Target/TargetLoweringObjectFile.cpp | 5 .../CodeGen/AArch64/clang-section-macho.ll| 22 --- llvm/test/CodeGen/ARM/clang-section.ll| 24 - .../Generic/machine-function-splitter.ll | 27 +++ .../basic-block-sections-pragma-sections.ll | 4 +-- 10 files changed, 15 insertions(+), 104 deletions(-) delete mode 100644 llvm/test/CodeGen/AArch64/clang-section-macho.ll diff --git a/clang/lib/CodeGen/CodeGenModule.cpp b/clang/lib/CodeGen/CodeGenModule.cpp index 00b3bfcaa0bc25..f4dbfe7a21f83c 100644 --- a/clang/lib/CodeGen/CodeGenModule.cpp +++ b/clang/lib/CodeGen/CodeGenModule.cpp @@ -2627,7 +2627,7 @@ void CodeGenModule::setNonAliasAttributes(GlobalDecl GD, addUsedGlobal(F); if (auto *SA = D->getAttr()) if (!D->getAttr()) - F->addFnAttr("implicit-section-name", SA->getName()); + F->setSection(SA->getName()); llvm::AttrBuilder Attrs(F->getContext()); if (GetCPUAndFeaturesAttributes(GD, Attrs)) { diff --git a/clang/test/CodeGen/clang-sections-attribute.c b/clang/test/CodeGen/clang-sections-attribute.c index 70ed24ed07a280..768bdd4d87649e 100644 --- a/clang/test/CodeGen/clang-sections-attribute.c +++ b/clang/test/CodeGen/clang-sections-attribute.c @@ -69,8 +69,5 @@ static int int_zvar; // CHECK: define internal void @int_fun() #0 section ".int_fun_attr" // CHECK: define internal void @int_fun2() #0 section ".int_fun2_attr" // -// Function attributes should not include implicit-section-name. -// CHECK-NOT: attributes #0 = {{.*}}implicit-section-name -// // No other attribute group should be present in the file. // CHECK-NOT: attributes #1 diff --git a/clang/test/CodeGenCXX/clang-sections.cpp b/clang/test/CodeGenCXX/clang-sections.cpp index a444f2d0cae59c..aa159e552b1b3c 100644 --- a/clang/test/CodeGenCXX/clang-sections.cpp +++ b/clang/test/CodeGenCXX/clang-sections.cpp @@ -81,24 +81,22 @@ int hoo(void) { //CHECK: @p ={{.*}} constant i32 7, align 4 //CHECK: @_ZL5fptrs = internal constant [2 x ptr] [ptr @foo, ptr @goo], align {{4|8}} #3 -//CHECK: define{{.*}} i32 @foo() #5 { -//CHECK: define{{.*}} i32 @goo() #6 { -//CHECK: declare i32 @zoo(ptr noundef, ptr noundef) #7 -//CHECK: define{{.*}} i32 @hoo() #8 { +//ELF: define{{.*}} i32 @foo(){{.*}} section "my_text.1" { +//ELF: define{{.*}} i32 @goo(){{.*}} section "my_text.2" { +//MACHO: define{{.*}} i32 @foo(){{.*}} section "__TEXT,__mytext1" { +//MACHO: define{{.*}} i32 @goo(){{.*}} section "__TEXT,__mytext2" { + +// ensure zoo/hoo don't have a section +//CHECK: declare i32 @zoo(ptr noundef, ptr noundef) #6{{$}} +//CHECK: define{{.*}} i32 @hoo() #5 { //ELF: attributes #0 = { "bss-section"="my_bss.1" "data-section"="my_data.1" "rodata-section"="my_rodata.1" } //ELF: attributes #1 = { "data-section"="my_data.1" "rodata-section"="my_rodata.1" } //ELF: attributes #2 = { "bss-section"="my_bss.2" "rodata-section"="my_rodata.1" } //ELF: attributes #3 = { "bss-section"="my_bss.2" "data-section"="my_data.2" "relro-section"="my_relro.2" "rodata-section"="my_rodata.2" } //ELF: attributes #4 = { "relro-section"="my_relro.2" } -//ELF: attributes #5 = { {{.*"implicit-section-name"="my_text.1".*}} } -//ELF: attributes #6 = { {{.*"implicit-section-name"="my_text.2".*}} } //MACHO: attributes #0 = { "bss-section"="__BSS,__mybss1" "data-section"="__DATA,__mydata1" "rodata-section"="__RODATA,__myrodata1" } //MACHO: attributes #1 = { "data-section"="__DATA,__mydata1" "rodata-section"="__RODATA,__myrodata1" } //MACHO: attributes #2 = { "bss-section"="__BSS,__mybss2" "rodata-section"="__RODATA,__myrodata1" } //MACHO: attributes #3 = { "bss-section"="
[clang] [llvm] [clang][llvm] Remove "implicit-section-name" attribute (PR #87906)
aeubanks wrote: this probably needs bitcode upgrade? https://github.com/llvm/llvm-project/pull/87906 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [clang][llvm] Remove "implicit-section-name" attribute (PR #87906)
llvmbot wrote: @llvm/pr-subscribers-backend-aarch64 @llvm/pr-subscribers-clang-codegen Author: Arthur Eubanks (aeubanks) Changes D33412/D33413 introduced this to support a clang pragma to set section names for a symbol depending on if it would be placed in bss/data/rodata/text, which may not be known until the backend. However, for text we know that only functions will go there, so just directly set the section in clang instead of going through a completely separate attribute. --- Full diff: https://github.com/llvm/llvm-project/pull/87906.diff 10 Files Affected: - (modified) clang/lib/CodeGen/CodeGenModule.cpp (+1-1) - (modified) clang/test/CodeGen/clang-sections-attribute.c (-3) - (modified) clang/test/CodeGenCXX/clang-sections.cpp (+8-10) - (modified) llvm/lib/CodeGen/TargetInstrInfo.cpp (+1-2) - (modified) llvm/lib/CodeGen/TargetLoweringObjectFileImpl.cpp (+1-10) - (modified) llvm/lib/Target/TargetLoweringObjectFile.cpp (-5) - (removed) llvm/test/CodeGen/AArch64/clang-section-macho.ll (-22) - (modified) llvm/test/CodeGen/ARM/clang-section.ll (-24) - (modified) llvm/test/CodeGen/Generic/machine-function-splitter.ll (+3-24) - (modified) llvm/test/CodeGen/X86/basic-block-sections-pragma-sections.ll (+1-3) ``diff diff --git a/clang/lib/CodeGen/CodeGenModule.cpp b/clang/lib/CodeGen/CodeGenModule.cpp index 00b3bfcaa0bc25..f4dbfe7a21f83c 100644 --- a/clang/lib/CodeGen/CodeGenModule.cpp +++ b/clang/lib/CodeGen/CodeGenModule.cpp @@ -2627,7 +2627,7 @@ void CodeGenModule::setNonAliasAttributes(GlobalDecl GD, addUsedGlobal(F); if (auto *SA = D->getAttr()) if (!D->getAttr()) - F->addFnAttr("implicit-section-name", SA->getName()); + F->setSection(SA->getName()); llvm::AttrBuilder Attrs(F->getContext()); if (GetCPUAndFeaturesAttributes(GD, Attrs)) { diff --git a/clang/test/CodeGen/clang-sections-attribute.c b/clang/test/CodeGen/clang-sections-attribute.c index 70ed24ed07a280..768bdd4d87649e 100644 --- a/clang/test/CodeGen/clang-sections-attribute.c +++ b/clang/test/CodeGen/clang-sections-attribute.c @@ -69,8 +69,5 @@ static int int_zvar; // CHECK: define internal void @int_fun() #0 section ".int_fun_attr" // CHECK: define internal void @int_fun2() #0 section ".int_fun2_attr" // -// Function attributes should not include implicit-section-name. -// CHECK-NOT: attributes #0 = {{.*}}implicit-section-name -// // No other attribute group should be present in the file. // CHECK-NOT: attributes #1 diff --git a/clang/test/CodeGenCXX/clang-sections.cpp b/clang/test/CodeGenCXX/clang-sections.cpp index a444f2d0cae59c..aa159e552b1b3c 100644 --- a/clang/test/CodeGenCXX/clang-sections.cpp +++ b/clang/test/CodeGenCXX/clang-sections.cpp @@ -81,24 +81,22 @@ int hoo(void) { //CHECK: @p ={{.*}} constant i32 7, align 4 //CHECK: @_ZL5fptrs = internal constant [2 x ptr] [ptr @foo, ptr @goo], align {{4|8}} #3 -//CHECK: define{{.*}} i32 @foo() #5 { -//CHECK: define{{.*}} i32 @goo() #6 { -//CHECK: declare i32 @zoo(ptr noundef, ptr noundef) #7 -//CHECK: define{{.*}} i32 @hoo() #8 { +//ELF: define{{.*}} i32 @foo(){{.*}} section "my_text.1" { +//ELF: define{{.*}} i32 @goo(){{.*}} section "my_text.2" { +//MACHO: define{{.*}} i32 @foo(){{.*}} section "__TEXT,__mytext1" { +//MACHO: define{{.*}} i32 @goo(){{.*}} section "__TEXT,__mytext2" { + +// ensure zoo/hoo don't have a section +//CHECK: declare i32 @zoo(ptr noundef, ptr noundef) #6{{$}} +//CHECK: define{{.*}} i32 @hoo() #5 { //ELF: attributes #0 = { "bss-section"="my_bss.1" "data-section"="my_data.1" "rodata-section"="my_rodata.1" } //ELF: attributes #1 = { "data-section"="my_data.1" "rodata-section"="my_rodata.1" } //ELF: attributes #2 = { "bss-section"="my_bss.2" "rodata-section"="my_rodata.1" } //ELF: attributes #3 = { "bss-section"="my_bss.2" "data-section"="my_data.2" "relro-section"="my_relro.2" "rodata-section"="my_rodata.2" } //ELF: attributes #4 = { "relro-section"="my_relro.2" } -//ELF: attributes #5 = { {{.*"implicit-section-name"="my_text.1".*}} } -//ELF: attributes #6 = { {{.*"implicit-section-name"="my_text.2".*}} } //MACHO: attributes #0 = { "bss-section"="__BSS,__mybss1" "data-section"="__DATA,__mydata1" "rodata-section"="__RODATA,__myrodata1" } //MACHO: attributes #1 = { "data-section"="__DATA,__mydata1" "rodata-section"="__RODATA,__myrodata1" } //MACHO: attributes #2 = { "bss-section"="__BSS,__mybss2" "rodata-section"="__RODATA,__myrodata1" } //MACHO: attributes #3 = { "bss-section"="__BSS,__mybss2" "data-section"="__DATA,__mydata2" "relro-section"="__RELRO,__myrelro2" "rodata-section"="__RODATA,__myrodata2" } //MACHO: attributes #4 = { "relro-section"="__RELRO,__myrelro2" } -//MACHO: attributes #5 = { {{.*"implicit-section-name"="__TEXT,__mytext1".*}} } -//MACHO: attributes #6 = { {{.*"implicit-section-name"="__TEXT,__mytext2".*}} } -//CHECK-NOT: attributes #7 = { {{.*"implicit-section-name".*}} } -//CHECK-NOT: attributes #8 = { {{.*"implicit-secti
[clang] [llvm] [clang][llvm] Remove "implicit-section-name" attribute (PR #87906)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Arthur Eubanks (aeubanks) Changes D33412/D33413 introduced this to support a clang pragma to set section names for a symbol depending on if it would be placed in bss/data/rodata/text, which may not be known until the backend. However, for text we know that only functions will go there, so just directly set the section in clang instead of going through a completely separate attribute. --- Full diff: https://github.com/llvm/llvm-project/pull/87906.diff 10 Files Affected: - (modified) clang/lib/CodeGen/CodeGenModule.cpp (+1-1) - (modified) clang/test/CodeGen/clang-sections-attribute.c (-3) - (modified) clang/test/CodeGenCXX/clang-sections.cpp (+8-10) - (modified) llvm/lib/CodeGen/TargetInstrInfo.cpp (+1-2) - (modified) llvm/lib/CodeGen/TargetLoweringObjectFileImpl.cpp (+1-10) - (modified) llvm/lib/Target/TargetLoweringObjectFile.cpp (-5) - (removed) llvm/test/CodeGen/AArch64/clang-section-macho.ll (-22) - (modified) llvm/test/CodeGen/ARM/clang-section.ll (-24) - (modified) llvm/test/CodeGen/Generic/machine-function-splitter.ll (+3-24) - (modified) llvm/test/CodeGen/X86/basic-block-sections-pragma-sections.ll (+1-3) ``diff diff --git a/clang/lib/CodeGen/CodeGenModule.cpp b/clang/lib/CodeGen/CodeGenModule.cpp index 00b3bfcaa0bc25..f4dbfe7a21f83c 100644 --- a/clang/lib/CodeGen/CodeGenModule.cpp +++ b/clang/lib/CodeGen/CodeGenModule.cpp @@ -2627,7 +2627,7 @@ void CodeGenModule::setNonAliasAttributes(GlobalDecl GD, addUsedGlobal(F); if (auto *SA = D->getAttr()) if (!D->getAttr()) - F->addFnAttr("implicit-section-name", SA->getName()); + F->setSection(SA->getName()); llvm::AttrBuilder Attrs(F->getContext()); if (GetCPUAndFeaturesAttributes(GD, Attrs)) { diff --git a/clang/test/CodeGen/clang-sections-attribute.c b/clang/test/CodeGen/clang-sections-attribute.c index 70ed24ed07a280..768bdd4d87649e 100644 --- a/clang/test/CodeGen/clang-sections-attribute.c +++ b/clang/test/CodeGen/clang-sections-attribute.c @@ -69,8 +69,5 @@ static int int_zvar; // CHECK: define internal void @int_fun() #0 section ".int_fun_attr" // CHECK: define internal void @int_fun2() #0 section ".int_fun2_attr" // -// Function attributes should not include implicit-section-name. -// CHECK-NOT: attributes #0 = {{.*}}implicit-section-name -// // No other attribute group should be present in the file. // CHECK-NOT: attributes #1 diff --git a/clang/test/CodeGenCXX/clang-sections.cpp b/clang/test/CodeGenCXX/clang-sections.cpp index a444f2d0cae59c..aa159e552b1b3c 100644 --- a/clang/test/CodeGenCXX/clang-sections.cpp +++ b/clang/test/CodeGenCXX/clang-sections.cpp @@ -81,24 +81,22 @@ int hoo(void) { //CHECK: @p ={{.*}} constant i32 7, align 4 //CHECK: @_ZL5fptrs = internal constant [2 x ptr] [ptr @foo, ptr @goo], align {{4|8}} #3 -//CHECK: define{{.*}} i32 @foo() #5 { -//CHECK: define{{.*}} i32 @goo() #6 { -//CHECK: declare i32 @zoo(ptr noundef, ptr noundef) #7 -//CHECK: define{{.*}} i32 @hoo() #8 { +//ELF: define{{.*}} i32 @foo(){{.*}} section "my_text.1" { +//ELF: define{{.*}} i32 @goo(){{.*}} section "my_text.2" { +//MACHO: define{{.*}} i32 @foo(){{.*}} section "__TEXT,__mytext1" { +//MACHO: define{{.*}} i32 @goo(){{.*}} section "__TEXT,__mytext2" { + +// ensure zoo/hoo don't have a section +//CHECK: declare i32 @zoo(ptr noundef, ptr noundef) #6{{$}} +//CHECK: define{{.*}} i32 @hoo() #5 { //ELF: attributes #0 = { "bss-section"="my_bss.1" "data-section"="my_data.1" "rodata-section"="my_rodata.1" } //ELF: attributes #1 = { "data-section"="my_data.1" "rodata-section"="my_rodata.1" } //ELF: attributes #2 = { "bss-section"="my_bss.2" "rodata-section"="my_rodata.1" } //ELF: attributes #3 = { "bss-section"="my_bss.2" "data-section"="my_data.2" "relro-section"="my_relro.2" "rodata-section"="my_rodata.2" } //ELF: attributes #4 = { "relro-section"="my_relro.2" } -//ELF: attributes #5 = { {{.*"implicit-section-name"="my_text.1".*}} } -//ELF: attributes #6 = { {{.*"implicit-section-name"="my_text.2".*}} } //MACHO: attributes #0 = { "bss-section"="__BSS,__mybss1" "data-section"="__DATA,__mydata1" "rodata-section"="__RODATA,__myrodata1" } //MACHO: attributes #1 = { "data-section"="__DATA,__mydata1" "rodata-section"="__RODATA,__myrodata1" } //MACHO: attributes #2 = { "bss-section"="__BSS,__mybss2" "rodata-section"="__RODATA,__myrodata1" } //MACHO: attributes #3 = { "bss-section"="__BSS,__mybss2" "data-section"="__DATA,__mydata2" "relro-section"="__RELRO,__myrelro2" "rodata-section"="__RODATA,__myrodata2" } //MACHO: attributes #4 = { "relro-section"="__RELRO,__myrelro2" } -//MACHO: attributes #5 = { {{.*"implicit-section-name"="__TEXT,__mytext1".*}} } -//MACHO: attributes #6 = { {{.*"implicit-section-name"="__TEXT,__mytext2".*}} } -//CHECK-NOT: attributes #7 = { {{.*"implicit-section-name".*}} } -//CHECK-NOT: attributes #8 = { {{.*"implicit-section-name".*}} } diff --git a/llvm/lib/CodeGen/
[clang] D41416: [modules] [pch] Do not deserialize all lazy template specializations when looking for one. (PR #83108)
https://github.com/ChuanqiXu9 updated https://github.com/llvm/llvm-project/pull/83108 >From 2a9dfdab30467bef5361cea743be0dc215011685 Mon Sep 17 00:00:00 2001 From: Vassil Vassilev Date: Sun, 7 Jan 2018 15:16:11 +0200 Subject: [PATCH 1/3] D41416: [modules] [pch] Do not deserialize all lazy template specializations when looking for one. --- clang/include/clang/AST/DeclTemplate.h| 36 - clang/lib/AST/DeclTemplate.cpp| 96 +-- clang/lib/AST/ODRHash.cpp | 15 clang/lib/Serialization/ASTReader.cpp | 25 -- clang/lib/Serialization/ASTReaderDecl.cpp | 36 ++--- clang/lib/Serialization/ASTWriter.cpp | 21 - clang/lib/Serialization/ASTWriterDecl.cpp | 74 ++--- 7 files changed, 242 insertions(+), 61 deletions(-) diff --git a/clang/include/clang/AST/DeclTemplate.h b/clang/include/clang/AST/DeclTemplate.h index e3b6a7efb1127a..4ed9b58d4ff609 100644 --- a/clang/include/clang/AST/DeclTemplate.h +++ b/clang/include/clang/AST/DeclTemplate.h @@ -256,6 +256,9 @@ class TemplateArgumentList final TemplateArgumentList(const TemplateArgumentList &) = delete; TemplateArgumentList &operator=(const TemplateArgumentList &) = delete; + /// Create hash for the given arguments. + static unsigned ComputeODRHash(ArrayRef Args); + /// Create a new template argument list that copies the given set of /// template arguments. static TemplateArgumentList *CreateCopy(ASTContext &Context, @@ -730,6 +733,26 @@ class RedeclarableTemplateDecl : public TemplateDecl, } void anchor() override; + struct LazySpecializationInfo { +uint32_t DeclID = ~0U; +unsigned ODRHash = ~0U; +bool IsPartial = false; +LazySpecializationInfo(uint32_t ID, unsigned Hash = ~0U, + bool Partial = false) + : DeclID(ID), ODRHash(Hash), IsPartial(Partial) { } +LazySpecializationInfo() { } +bool operator<(const LazySpecializationInfo &Other) const { + return DeclID < Other.DeclID; +} +bool operator==(const LazySpecializationInfo &Other) const { + assert((DeclID != Other.DeclID || ODRHash == Other.ODRHash) && + "Hashes differ!"); + assert((DeclID != Other.DeclID || IsPartial == Other.IsPartial) && + "Both must be the same kinds!"); + return DeclID == Other.DeclID; +} + }; + protected: template struct SpecEntryTraits { using DeclType = EntryType; @@ -770,7 +793,12 @@ class RedeclarableTemplateDecl : public TemplateDecl, return SpecIterator(isEnd ? Specs.end() : Specs.begin()); } - void loadLazySpecializationsImpl() const; + void loadLazySpecializationsImpl(bool OnlyPartial = false) const; + + void loadLazySpecializationsImpl(llvm::ArrayRef Args, + TemplateParameterList *TPL = nullptr) const; + + Decl *loadLazySpecializationImpl(LazySpecializationInfo &LazySpecInfo) const; template typename SpecEntryTraits::DeclType* @@ -797,7 +825,7 @@ class RedeclarableTemplateDecl : public TemplateDecl, /// /// The first value in the array is the number of specializations/partial /// specializations that follow. -uint32_t *LazySpecializations = nullptr; +LazySpecializationInfo *LazySpecializations = nullptr; /// The set of "injected" template arguments used within this /// template. @@ -2268,7 +2296,7 @@ class ClassTemplateDecl : public RedeclarableTemplateDecl { friend class TemplateDeclInstantiator; /// Load any lazily-loaded specializations from the external source. - void LoadLazySpecializations() const; + void LoadLazySpecializations(bool OnlyPartial = false) const; /// Get the underlying class declarations of the template. CXXRecordDecl *getTemplatedDecl() const { @@ -3039,7 +3067,7 @@ class VarTemplateDecl : public RedeclarableTemplateDecl { friend class ASTDeclWriter; /// Load any lazily-loaded specializations from the external source. - void LoadLazySpecializations() const; + void LoadLazySpecializations(bool OnlyPartial = false) const; /// Get the underlying variable declarations of the template. VarDecl *getTemplatedDecl() const { diff --git a/clang/lib/AST/DeclTemplate.cpp b/clang/lib/AST/DeclTemplate.cpp index 3c217d6a6a5ae3..1babe39ee2a7e5 100644 --- a/clang/lib/AST/DeclTemplate.cpp +++ b/clang/lib/AST/DeclTemplate.cpp @@ -20,6 +20,8 @@ #include "clang/AST/TemplateBase.h" #include "clang/AST/TemplateName.h" #include "clang/AST/Type.h" +#include "clang/AST/ODRHash.h" +#include "clang/AST/ExprCXX.h" #include "clang/AST/TypeLoc.h" #include "clang/Basic/Builtins.h" #include "clang/Basic/LLVM.h" @@ -331,16 +333,43 @@ RedeclarableTemplateDecl::CommonBase *RedeclarableTemplateDecl::getCommonPtr() c return Common; } -void RedeclarableTemplateDecl::loadLazySpecializationsImpl() const { +void RedeclarableTemplateDecl::loadLazySpecializationsImpl( + bool Onl