[clang] Revert changes in AddDefaultGCCPrefixes() for SystemZTriples. (PR #94729)
JonPsson1 wrote: I think other folks than myself also got a similar problem, so it's not just on my machine / setup. Should everybody set LLVM_DEFAULT_TARGET_TRIPLE with cmake instead of this patch? Sorry, not very familiar with this... Would it be ok to apply this for now? https://github.com/llvm/llvm-project/pull/94729 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [CodeGen] Simplify codegen for array initialization (PR #93956)
nikic wrote: ping https://github.com/llvm/llvm-project/pull/93956 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Driver] Add winsysroot alias to the GNU driver (PR #94731)
https://github.com/Andarwinux created https://github.com/llvm/llvm-project/pull/94731 fixes #91216 >From c1fd8cb831abc0312fb8f0fa0ec5f5348646ed01 Mon Sep 17 00:00:00 2001 From: Andarwinux <144242044+andarwi...@users.noreply.github.com> Date: Fri, 7 Jun 2024 07:07:40 + Subject: [PATCH] [Driver] Add winsysroot alias to the GNU driver fixes #91216 --- clang/include/clang/Driver/Options.td | 2 ++ 1 file changed, 2 insertions(+) diff --git a/clang/include/clang/Driver/Options.td b/clang/include/clang/Driver/Options.td index f04c220d6e1db..6c34c49b5e988 100644 --- a/clang/include/clang/Driver/Options.td +++ b/clang/include/clang/Driver/Options.td @@ -8569,6 +8569,8 @@ def : Separate<["-"], "Xmicrosoft-windows-sdk-root">, Alias<_SLASH_winsdkdir>; def : Separate<["-"], "Xmicrosoft-windows-sdk-version">, Alias<_SLASH_winsdkversion>; +def : Separate<["-"], "Xmicrosoft-windows-sys-root">, +Alias<_SLASH_winsysroot>; // Ignored: ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Driver] Add winsysroot alias to the GNU driver (PR #94731)
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/94731 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Driver] Add winsysroot alias to the GNU driver (PR #94731)
llvmbot wrote: @llvm/pr-subscribers-clang Author: None (Andarwinux) Changes fixes #91216 --- Full diff: https://github.com/llvm/llvm-project/pull/94731.diff 1 Files Affected: - (modified) clang/include/clang/Driver/Options.td (+2) ``diff diff --git a/clang/include/clang/Driver/Options.td b/clang/include/clang/Driver/Options.td index f04c220d6e1db..6c34c49b5e988 100644 --- a/clang/include/clang/Driver/Options.td +++ b/clang/include/clang/Driver/Options.td @@ -8569,6 +8569,8 @@ def : Separate<["-"], "Xmicrosoft-windows-sdk-root">, Alias<_SLASH_winsdkdir>; def : Separate<["-"], "Xmicrosoft-windows-sdk-version">, Alias<_SLASH_winsdkversion>; +def : Separate<["-"], "Xmicrosoft-windows-sys-root">, +Alias<_SLASH_winsysroot>; // Ignored: `` https://github.com/llvm/llvm-project/pull/94731 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Revert changes in AddDefaultGCCPrefixes() for SystemZTriples. (PR #94729)
MaskRay wrote: > I think other folks than myself also got a similar problem, so it's not just > on my machine / setup. > > Should everybody set LLVM_DEFAULT_TARGET_TRIPLE with cmake instead of this > patch? Sorry, not very familiar with this... > > Would it be ok to apply this for now? The inferred value is incorrect for many systems. For example, Probably all linux-musl users need to set LLVM_DEFAULT_TARGET_TRIPLE correctly, since the default guessed value isn't correct for them. ``` % grep -A1 s390x:Linux llvm/cmake/config.guess s390:Linux:*:* | s390x:Linux:*:*) echo ${UNAME_MACHINE}-ibm-linux ``` Since you have access to s390x, perhaps you can test a change to `llvm/cmake/config.guess` ``` if [ "$(grep -Ei 'debian|ubuntu' /etc/lsb-release)" ]; then echo ${UNAME_MACHINE}-unkown-linux-gnu else echo ${UNAME_MACHINE}-unkown-linux-gnu fi ``` https://github.com/llvm/llvm-project/pull/94729 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [MC,llvm-readobj,yaml2obj] Support CREL relocation format (PR #91280)
@@ -86,6 +86,8 @@ DYNAMIC_TAG(RELRSZ, 35) // Size of Relr relocation table. DYNAMIC_TAG(RELR, 36)// Address of relocation table (Relr entries). DYNAMIC_TAG(RELRENT, 37) // Size of a Relr relocation entry. +DYNAMIC_TAG(CREL, 38) // CREL relocation table + jh7370 wrote: > I understand the concern but this is just impossible given the essential > state of the generic ABI... I don't understand this comment. There's an active mailing list, where proposals are discussed and adopted, even if there's no fully published document, so a different proposal could easily come up whilst this is still under review. Perhaps it'll be implemented in GNU/Solaris/... initially with the same generic value. Whose meaning of the value should then win? In the worst case, maybe the generic ABI list ends up rejecting this crel proposal. The values aren't reserved for LLVM usage, so the next proposal to come along will use those same values and we then have a clash between what LLVM wants to use the value for (and there might be objects out there using that value, if this feature is adopted in an LLVM release), which would cause us all sorts of headaches in the future. https://github.com/llvm/llvm-project/pull/91280 ___ 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 crash with null check for Token at Loc (PR #94528)
https://github.com/kadircet edited https://github.com/llvm/llvm-project/pull/94528 ___ 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 crash with null check for Token at Loc (PR #94528)
@@ -447,7 +447,7 @@ class HighlightingsBuilder { if (!RLoc.isValid()) return; -const auto *RTok = TB.spelledTokenAt(RLoc); +const auto *RTok = TB.spelledTokenContaining(RLoc); kadircet wrote: so looks like this call site was actually expecting it to be null when provided with an offset into the token, but that's OK overall, as it's also trying to just slice the token. can you update the surroundings to reflect the new behavior so we don't leave old state documented for future travelers? something like: ``` // RLoc is either part of `>>` or a spelled token on its own `>`. // If it's the former, slice to have length of 1, if latter use the token as-is. assert(RTok); if (RTok->kind() == ...) ``` https://github.com/llvm/llvm-project/pull/94528 ___ 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 crash with null check for Token at Loc (PR #94528)
https://github.com/kadircet approved this pull request. https://github.com/llvm/llvm-project/pull/94528 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] c15b867 - [clang][Interp][NFC] Add GetPtrFieldPop opcode
Author: Timm Bäder Date: 2024-06-07T09:40:26+02:00 New Revision: c15b86731b78de88fadbc16ea1c2df2f60c991e9 URL: https://github.com/llvm/llvm-project/commit/c15b86731b78de88fadbc16ea1c2df2f60c991e9 DIFF: https://github.com/llvm/llvm-project/commit/c15b86731b78de88fadbc16ea1c2df2f60c991e9.diff LOG: [clang][Interp][NFC] Add GetPtrFieldPop opcode And change the previous GetPtrField to only peek() the base pointer. We can get rid of a whole bunch of DupPtr ops this way. Added: Modified: clang/lib/AST/Interp/ByteCodeExprGen.cpp clang/lib/AST/Interp/Interp.h clang/lib/AST/Interp/Opcodes.td Removed: diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp b/clang/lib/AST/Interp/ByteCodeExprGen.cpp index 9073175263645..1d0c36d0bf09f 100644 --- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp +++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp @@ -1104,14 +1104,9 @@ bool ByteCodeExprGen::visitInitList(ArrayRef Inits, if (!this->visit(Init)) return false; - if (FieldToInit->isBitField()) { -if (!this->emitInitBitField(T, FieldToInit, E)) - return false; - } else { -if (!this->emitInitField(T, FieldToInit->Offset, E)) - return false; - } - return this->emitPopPtr(E); + if (FieldToInit->isBitField()) +return this->emitInitBitField(T, FieldToInit, E); + return this->emitInitField(T, FieldToInit->Offset, E); }; auto initCompositeField = [=](const Record::Field *FieldToInit, @@ -1147,9 +1142,6 @@ bool ByteCodeExprGen::visitInitList(ArrayRef Inits, else FToInit = cast(E)->getInitializedFieldInUnion(); -if (!this->emitDupPtr(E)) - return false; - const Record::Field *FieldToInit = R->getField(FToInit); if (std::optional T = classify(Init)) { if (!initPrimitiveField(FieldToInit, Init, *T)) @@ -1169,8 +1161,6 @@ bool ByteCodeExprGen::visitInitList(ArrayRef Inits, while (InitIndex < R->getNumFields() && R->getField(InitIndex)->Decl->isUnnamedBitField()) ++InitIndex; - if (!this->emitDupPtr(E)) -return false; if (std::optional T = classify(Init)) { const Record::Field *FieldToInit = R->getField(InitIndex); @@ -1180,7 +1170,7 @@ bool ByteCodeExprGen::visitInitList(ArrayRef Inits, } else { // Initializer for a direct base class. if (const Record::Base *B = R->getBase(Init->getType())) { - if (!this->emitGetPtrBasePop(B->Offset, Init)) + if (!this->emitGetPtrBase(B->Offset, Init)) return false; if (!this->visitInitializer(Init)) @@ -1513,7 +1503,7 @@ bool ByteCodeExprGen::VisitMemberExpr(const MemberExpr *E) { // Leave a pointer to the field on the stack. if (F->Decl->getType()->isReferenceType()) return this->emitGetFieldPop(PT_Ptr, F->Offset, E) && maybeLoadValue(); -return this->emitGetPtrField(F->Offset, E) && maybeLoadValue(); +return this->emitGetPtrFieldPop(F->Offset, E) && maybeLoadValue(); } return false; @@ -2147,9 +2137,6 @@ bool ByteCodeExprGen::VisitLambdaExpr(const LambdaExpr *E) { if (!this->emitInitField(*T, F.Offset, E)) return false; } else { - if (!this->emitDupPtr(E)) -return false; - if (!this->emitGetPtrField(F.Offset, E)) return false; @@ -2846,9 +2833,6 @@ bool ByteCodeExprGen::visitZeroRecordInitializer(const Record *R, continue; } -// TODO: Add GetPtrFieldPop and get rid of this dup. -if (!this->emitDupPtr(E)) - return false; if (!this->emitGetPtrField(Field.Offset, E)) return false; @@ -3258,8 +3242,6 @@ bool ByteCodeExprGen::visitAPValueInitializer(const APValue &Val, PrimType ElemT = classifyPrim(ArrType->getElementType()); assert(ArrType); -if (!this->emitDupPtr(E)) - return false; if (!this->emitGetPtrField(RF->Offset, E)) return false; @@ -3273,8 +3255,6 @@ bool ByteCodeExprGen::visitAPValueInitializer(const APValue &Val, if (!this->emitPopPtr(E)) return false; } else if (F.isStruct() || F.isUnion()) { -if (!this->emitDupPtr(E)) - return false; if (!this->emitGetPtrField(RF->Offset, E)) return false; if (!this->visitAPValueInitializer(F, E)) @@ -4201,8 +4181,6 @@ bool ByteCodeExprGen::emitRecordDestruction(const Record *R) { for (const Record::Field &Field : llvm::reverse(R->fields())) { const Descriptor *D = Field.Desc; if (!D->isPrimitive() && !D->isPrimitiveArray()) { - if (!this->emitDupPtr(SourceInfo{})) -return false; if (!this->emitGetPtrField(Field.Offset, SourceInfo{})) return false; if (!this->emitDestruction(D)) diff --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/I
[clang] e622996 - [analyzer][NFC] Factor out NoOwnershipChangeVisitor (#94357)
Author: Kristóf Umann Date: 2024-06-07T09:49:16+02:00 New Revision: e622996eddfb2826d258b3a3760eed195f97aabe URL: https://github.com/llvm/llvm-project/commit/e622996eddfb2826d258b3a3760eed195f97aabe DIFF: https://github.com/llvm/llvm-project/commit/e622996eddfb2826d258b3a3760eed195f97aabe.diff LOG: [analyzer][NFC] Factor out NoOwnershipChangeVisitor (#94357) In preparation for adding essentially the same visitor to StreamChecker, this patch factors this visitor out to a common header. I'll be the first to admit that the interface of these classes are not terrific, but it rather tightly held back by its main technical debt, which is NoStoreFuncVisitor, the main descendant of NoStateChangeVisitor. Change-Id: I99d73ccd93a18dd145bbbc83afadbb432dd42b90 Added: clang/lib/StaticAnalyzer/Checkers/NoOwnershipChangeVisitor.cpp clang/lib/StaticAnalyzer/Checkers/NoOwnershipChangeVisitor.h Modified: clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp Removed: diff --git a/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt b/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt index cd5a3bdd02e4a..68e829cace495 100644 --- a/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt +++ b/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt @@ -78,6 +78,7 @@ add_clang_library(clangStaticAnalyzerCheckers NoReturnFunctionChecker.cpp NonNullParamChecker.cpp NonnullGlobalConstantsChecker.cpp + NoOwnershipChangeVisitor.cpp NullabilityChecker.cpp NumberObjectConversionChecker.cpp ObjCAtSyncChecker.cpp diff --git a/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp index 467cf8889b6d3..fe202c79ed620 100644 --- a/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp @@ -46,6 +46,7 @@ #include "AllocationState.h" #include "InterCheckerAPI.h" +#include "NoOwnershipChangeVisitor.h" #include "clang/AST/Attr.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclTemplate.h" @@ -79,13 +80,11 @@ #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SetOperations.h" -#include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/Casting.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" -#include #include #include #include @@ -414,7 +413,7 @@ class MallocChecker bool isFreeingCall(const CallEvent &Call) const; static bool isFreeingOwnershipAttrCall(const FunctionDecl *Func); - friend class NoOwnershipChangeVisitor; + friend class NoMemOwnershipChangeVisitor; CallDescriptionMap AllocatingMemFnMap{ {{CDM::CLibrary, {"alloca"}, 1}, &MallocChecker::checkAlloca}, @@ -765,61 +764,8 @@ class MallocChecker //===--===// namespace { -class NoOwnershipChangeVisitor final : public NoStateChangeFuncVisitor { - // The symbol whose (lack of) ownership change we are interested in. - SymbolRef Sym; - const MallocChecker &Checker; - using OwnerSet = llvm::SmallPtrSet; - - // Collect which entities point to the allocated memory, and could be - // responsible for deallocating it. - class OwnershipBindingsHandler : public StoreManager::BindingsHandler { -SymbolRef Sym; -OwnerSet &Owners; - - public: -OwnershipBindingsHandler(SymbolRef Sym, OwnerSet &Owners) -: Sym(Sym), Owners(Owners) {} - -bool HandleBinding(StoreManager &SMgr, Store Store, const MemRegion *Region, - SVal Val) override { - if (Val.getAsSymbol() == Sym) -Owners.insert(Region); - return true; -} - -LLVM_DUMP_METHOD void dump() const { dumpToStream(llvm::errs()); } -LLVM_DUMP_METHOD void dumpToStream(llvm::raw_ostream &out) const { - out << "Owners: {\n"; - for (const MemRegion *Owner : Owners) { -out << " "; -Owner->dumpToStream(out); -out << ",\n"; - } - out << "}\n"; -} - }; - +class NoMemOwnershipChangeVisitor final : public NoOwnershipChangeVisitor { protected: - OwnerSet getOwnersAtNode(const ExplodedNode *N) { -OwnerSet Ret; - -ProgramStateRef State = N->getState(); -OwnershipBindingsHandler Handler{Sym, Ret}; -State->getStateManager().getStoreManager().iterBindings(State->getStore(), -Handler); -return Ret; - } - - LLVM_DUMP_METHOD static std::string - getFunctionName(const ExplodedNode *CallEnterN) { -if (const CallExpr *CE = llvm::dyn_cast_or_null( -CallEnterN->getLocationAs()->getCallExpr())) - if (const FunctionDecl *FD = CE->getDirectCallee()) -return FD->getQualifiedNameAsString(); -
[clang] [analyzer][NFC] Factor out NoOwnershipChangeVisitor (PR #94357)
https://github.com/Szelethus closed https://github.com/llvm/llvm-project/pull/94357 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] Revert changes in AddDefaultGCCPrefixes() for SystemZTriples. (PR #94729)
https://github.com/JonPsson1 updated https://github.com/llvm/llvm-project/pull/94729 >From 9340b545ec2381937919dfd925940a191244234b Mon Sep 17 00:00:00 2001 From: Jonas Paulsson Date: Fri, 7 Jun 2024 08:24:16 +0200 Subject: [PATCH 1/3] Revert changes in AddDefaultGCCPrefixes() for SystemZTriples. --- clang/lib/Driver/ToolChains/Gnu.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/clang/lib/Driver/ToolChains/Gnu.cpp b/clang/lib/Driver/ToolChains/Gnu.cpp index b141e5f2adfab..85a8414372f21 100644 --- a/clang/lib/Driver/ToolChains/Gnu.cpp +++ b/clang/lib/Driver/ToolChains/Gnu.cpp @@ -2569,8 +2569,8 @@ void Generic_GCC::GCCInstallationDetector::AddDefaultGCCPrefixes( static const char *const SystemZLibDirs[] = {"/lib64", "/lib"}; static const char *const SystemZTriples[] = { - "s390x-unknown-linux-gnu", "s390x-ibm-linux-gnu", "s390x-suse-linux", - "s390x-redhat-linux"}; + "s390x-linux-gnu", "s390x-unknown-linux-gnu", "s390x-ibm-linux-gnu", + "s390x-suse-linux", "s390x-redhat-linux"}; using std::begin; using std::end; >From ed3b6e8dea0477b50b536034dfd94c78008a9f9a Mon Sep 17 00:00:00 2001 From: Jonas Paulsson Date: Fri, 7 Jun 2024 09:50:29 +0200 Subject: [PATCH 2/3] Revert "Revert changes in AddDefaultGCCPrefixes() for SystemZTriples." This reverts commit 9340b545ec2381937919dfd925940a191244234b. --- clang/lib/Driver/ToolChains/Gnu.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/clang/lib/Driver/ToolChains/Gnu.cpp b/clang/lib/Driver/ToolChains/Gnu.cpp index 85a8414372f21..b141e5f2adfab 100644 --- a/clang/lib/Driver/ToolChains/Gnu.cpp +++ b/clang/lib/Driver/ToolChains/Gnu.cpp @@ -2569,8 +2569,8 @@ void Generic_GCC::GCCInstallationDetector::AddDefaultGCCPrefixes( static const char *const SystemZLibDirs[] = {"/lib64", "/lib"}; static const char *const SystemZTriples[] = { - "s390x-linux-gnu", "s390x-unknown-linux-gnu", "s390x-ibm-linux-gnu", - "s390x-suse-linux", "s390x-redhat-linux"}; + "s390x-unknown-linux-gnu", "s390x-ibm-linux-gnu", "s390x-suse-linux", + "s390x-redhat-linux"}; using std::begin; using std::end; >From 2b24624210f8f5cab4808710bbb27293a5b9164f Mon Sep 17 00:00:00 2001 From: Jonas Paulsson Date: Fri, 7 Jun 2024 09:51:20 +0200 Subject: [PATCH 3/3] Fix in config.guess instead --- llvm/cmake/config.guess | 8 ++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/llvm/cmake/config.guess b/llvm/cmake/config.guess index f489623677694..2444ed7f5792b 100644 --- a/llvm/cmake/config.guess +++ b/llvm/cmake/config.guess @@ -4,7 +4,7 @@ # 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, # 2011 Free Software Foundation, Inc. -timestamp='2011-08-20' +timestamp='2024-06-07' # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by @@ -1028,7 +1028,11 @@ EOF echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; s390:Linux:*:* | s390x:Linux:*:*) - echo ${UNAME_MACHINE}-ibm-linux + if [ "$(grep -Ei 'debian|ubuntu' /etc/lsb-release)" ]; then + echo ${UNAME_MACHINE}-linux-gnu + else + echo ${UNAME_MACHINE}-ibm-linux + fi exit ;; sh64*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] Revert changes in AddDefaultGCCPrefixes() for SystemZTriples. (PR #94729)
JonPsson1 wrote: That seems to fix at least my Ubuntu build. https://github.com/llvm/llvm-project/pull/94729 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer][NFC] Factor out NoOwnershipChangeVisitor (PR #94357)
@@ -0,0 +1,116 @@ +//===--*- C++ -*--// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "NoOwnershipChangeVisitor.h" +#include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h" +#include "llvm/ADT/SetOperations.h" + +using namespace clang; +using namespace ento; +using OwnerSet = NoOwnershipChangeVisitor::OwnerSet; + +// Collect which entities point to the allocated memory, and could be +// responsible for deallocating it. +class OwnershipBindingsHandler : public StoreManager::BindingsHandler { balazske wrote: This class can be in an anonymous namespace? https://github.com/llvm/llvm-project/pull/94357 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [clang][CodeGen] `used` globals are fake (PR #93601)
@@ -8642,8 +8642,11 @@ The '``llvm.used``' Global Variable The ``@llvm.used`` global is an array which has :ref:`appending linkage `. This array contains a list of pointers to named global variables, functions and aliases which may optionally -have a pointer cast formed of bitcast or getelementptr. For example, a legal -use of it is: +have a pointer cast formed of bitcast or getelementptr. The address space of the +pointers is always unspecified, rather than the globals address space, since arsenm wrote: Do not say unspecified. Say it is the default address space. 0 is not an unspecified address space https://github.com/llvm/llvm-project/pull/93601 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Fix-it hint for `++this` -> `++*this` when deref is modifiable (PR #94159)
https://github.com/Rajveer100 edited https://github.com/llvm/llvm-project/pull/94159 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [flang] [llvm] [mlir] [Flang]Fix for changed code at the end of AllocaIP. (PR #92430)
https://github.com/nikic dismissed https://github.com/llvm/llvm-project/pull/92430 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer][NFC] Factor out NoOwnershipChangeVisitor (PR #94357)
@@ -0,0 +1,116 @@ +//===--*- C++ -*--// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "NoOwnershipChangeVisitor.h" +#include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h" +#include "llvm/ADT/SetOperations.h" + +using namespace clang; +using namespace ento; +using OwnerSet = NoOwnershipChangeVisitor::OwnerSet; + +// Collect which entities point to the allocated memory, and could be +// responsible for deallocating it. +class OwnershipBindingsHandler : public StoreManager::BindingsHandler { Szelethus wrote: Good catch, I'll fix that in a followup patch. https://github.com/llvm/llvm-project/pull/94357 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 1c0063b - [clang][Interp] Remove StoragKind limitation in Pointer assign operators
Author: Timm Bäder Date: 2024-06-07T10:32:16+02:00 New Revision: 1c0063b58a4fc23c94c7f5bf5a937bbdf9703cc0 URL: https://github.com/llvm/llvm-project/commit/1c0063b58a4fc23c94c7f5bf5a937bbdf9703cc0 DIFF: https://github.com/llvm/llvm-project/commit/1c0063b58a4fc23c94c7f5bf5a937bbdf9703cc0.diff LOG: [clang][Interp] Remove StoragKind limitation in Pointer assign operators It's not strictly needed and did cause some test failures. Added: Modified: clang/lib/AST/Interp/Pointer.cpp clang/test/AST/Interp/cxx20.cpp Removed: diff --git a/clang/lib/AST/Interp/Pointer.cpp b/clang/lib/AST/Interp/Pointer.cpp index a60b4d28b4387..e3d21f93f114e 100644 --- a/clang/lib/AST/Interp/Pointer.cpp +++ b/clang/lib/AST/Interp/Pointer.cpp @@ -64,26 +64,26 @@ Pointer::~Pointer() { } void Pointer::operator=(const Pointer &P) { - if (!this->isIntegralPointer() || !P.isBlockPointer()) -assert(P.StorageKind == StorageKind || (this->isZero() && P.isZero())); - + // If the current storage type is Block, we need to remove + // this pointer from the block. bool WasBlockPointer = isBlockPointer(); - StorageKind = P.StorageKind; if (StorageKind == Storage::Block) { Block *Old = PointeeStorage.BS.Pointee; -if (WasBlockPointer && PointeeStorage.BS.Pointee) +if (WasBlockPointer && Old) { PointeeStorage.BS.Pointee->removePointer(this); + Old->cleanup(); +} + } -Offset = P.Offset; + StorageKind = P.StorageKind; + Offset = P.Offset; + + if (P.isBlockPointer()) { PointeeStorage.BS = P.PointeeStorage.BS; if (PointeeStorage.BS.Pointee) PointeeStorage.BS.Pointee->addPointer(this); - -if (WasBlockPointer && Old) - Old->cleanup(); - - } else if (StorageKind == Storage::Int) { + } else if (P.isIntegralPointer()) { PointeeStorage.Int = P.PointeeStorage.Int; } else { assert(false && "Unhandled storage kind"); @@ -91,26 +91,26 @@ void Pointer::operator=(const Pointer &P) { } void Pointer::operator=(Pointer &&P) { - if (!this->isIntegralPointer() || !P.isBlockPointer()) -assert(P.StorageKind == StorageKind || (this->isZero() && P.isZero())); - + // If the current storage type is Block, we need to remove + // this pointer from the block. bool WasBlockPointer = isBlockPointer(); - StorageKind = P.StorageKind; if (StorageKind == Storage::Block) { Block *Old = PointeeStorage.BS.Pointee; -if (WasBlockPointer && PointeeStorage.BS.Pointee) +if (WasBlockPointer && Old) { PointeeStorage.BS.Pointee->removePointer(this); + Old->cleanup(); +} + } -Offset = P.Offset; + StorageKind = P.StorageKind; + Offset = P.Offset; + + if (P.isBlockPointer()) { PointeeStorage.BS = P.PointeeStorage.BS; if (PointeeStorage.BS.Pointee) PointeeStorage.BS.Pointee->addPointer(this); - -if (WasBlockPointer && Old) - Old->cleanup(); - - } else if (StorageKind == Storage::Int) { + } else if (P.isIntegralPointer()) { PointeeStorage.Int = P.PointeeStorage.Int; } else { assert(false && "Unhandled storage kind"); diff --git a/clang/test/AST/Interp/cxx20.cpp b/clang/test/AST/Interp/cxx20.cpp index 49ee040be392e..c750be866ca7c 100644 --- a/clang/test/AST/Interp/cxx20.cpp +++ b/clang/test/AST/Interp/cxx20.cpp @@ -782,3 +782,18 @@ namespace APValues { constexpr const A &v = get; constexpr const A &w = get; } + +namespace self_referencing { + struct S { +S* ptr = nullptr; +constexpr S(int i) : ptr(this) { + if (this == ptr && i) +ptr = nullptr; +} +constexpr ~S() {} + }; + + void test() { +S s(1); + } +} ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] Enforce SL.con.3: Add check to replace operator[] with at() (PR #90043)
PBHDK wrote: > > > I am adding @leunam99 and @PBHDK to the PR, who will contribute in the > > > next few weeks. > > > > > > Since we cannot push to this PR, we will be submitting a new PR with > > @sebwolf-de's + our work, correct, @EugeneZelenko, @PiotrZSL, @HerrCai0907? > > Could you please resolve conversations for fixed comments? Once we're clear on all our questions (see comments above), we'll submit a new PR that'll resolve all comments. The code is ready, but we don't want to submit the PR as long as we still have open questions. The problem is that we can't mark them as resolved on GitHub ourselves, and Sebastian is out-of-office right now. I don't know if you can assign us to this PR somehow, but if not, someone else would have to mark them as resolved. https://github.com/llvm/llvm-project/pull/90043 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Testing32 bit for https://github.com/llvm/llvm-project/pull/92083 (PR #94603)
DavidSpickett wrote: Sure I'll test it now. BTW if you see `Clang-Unit::ClangReplInterpreterTests/InterpreterTest/Value` failing on one of our bots, that's not due to your change. https://github.com/llvm/llvm-project/pull/94603 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] Revert changes in AddDefaultGCCPrefixes() for SystemZTriples. (PR #94729)
JonPsson1 wrote: (patch updated) https://github.com/llvm/llvm-project/pull/94729 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[compiler-rt] [libcxx] [libcxxabi] [libunwind] [libunwind][libcxx][libcxxabi][compiler-rt-builtins] Fix Exception Handling build for wasm (PR #79667)
https://github.com/trcrsired updated https://github.com/llvm/llvm-project/pull/79667 >From 4f1ce895254dd9505150c1f5f5cb77454b9aca68 Mon Sep 17 00:00:00 2001 From: cqwrteur <100043421+trcrsi...@users.noreply.github.com> Date: Sat, 1 Jun 2024 02:55:50 -0400 Subject: [PATCH] [libunwind][libcxx][libcxxabi] Fix Exception Handling build for wasm The wasm unwind build appears to be dysfunctional, likely because the author has only supplied a customized LLVM build on request, rather than a fully functional patch. This patch fixes the build Apply formatting patch proposed by github bot use "" to prevent CMAKE_SYSTEM_PROCESSOR not defined [libunwind] logAPI functions should also be built [libcxxabi] Fix function signatures for wasm wasm does not define the function signatures correctly for cxxabi Fix them Fix formatting issues for libcxxabi's wasm eh change Merge remote-tracking branch 'parent/main' into wasmlibunwindfix remove unwanted changes in unwind-wasm.c Make Unwind-wasm.c compile correctly without workaround in CMakeLists.txt using __wasm__ macro to guard against all wasm eh build fix UnwindLevel.c's formatting issue ISO C requires a translation unit to contain at least one declaration [-Werror,-Wempty-translation-unit] compiler-rt does not define CMP_RESULT correct on wasm64 Fixed Merge code --- compiler-rt/lib/builtins/fp_compare_impl.inc | 2 +- libcxx/include/__exception/exception_ptr.h | 21 +- libcxxabi/include/cxxabi.h | 179 ++--- libcxxabi/src/cxa_exception.cpp | 712 --- libcxxabi/src/cxa_exception.h| 7 +- libunwind/include/libunwind.h| 2 + libunwind/src/Unwind-wasm.c | 13 +- libunwind/src/UnwindRegistersRestore.S | 3 +- libunwind/src/UnwindRegistersSave.S | 3 + libunwind/src/assembly.h | 2 + libunwind/src/cet_unwind.h | 3 + libunwind/src/config.h | 15 +- libunwind/src/libunwind.cpp | 2 + libunwind/src/libunwind_ext.h| 2 + 14 files changed, 423 insertions(+), 543 deletions(-) diff --git a/compiler-rt/lib/builtins/fp_compare_impl.inc b/compiler-rt/lib/builtins/fp_compare_impl.inc index a9a4f6fbf5dfe..83bdea46a45da 100644 --- a/compiler-rt/lib/builtins/fp_compare_impl.inc +++ b/compiler-rt/lib/builtins/fp_compare_impl.inc @@ -12,7 +12,7 @@ // functions. We need to ensure that the return value is sign-extended in the // same way as GCC expects (since otherwise GCC-generated __builtin_isinf // returns true for finite 128-bit floating-point numbers). -#ifdef __aarch64__ +#if defined(__aarch64__) || defined(__wasm__) // AArch64 GCC overrides libgcc_cmp_return to use int instead of long. typedef int CMP_RESULT; #elif __SIZEOF_POINTER__ == 8 && __SIZEOF_LONG__ == 4 diff --git a/libcxx/include/__exception/exception_ptr.h b/libcxx/include/__exception/exception_ptr.h index 0a8337fa39de3..01f340a587ec3 100644 --- a/libcxx/include/__exception/exception_ptr.h +++ b/libcxx/include/__exception/exception_ptr.h @@ -29,22 +29,21 @@ namespace __cxxabiv1 { +#if defined(__wasm__) +typedef void* (*__libcpp_exception_destructor_func)(void*); +#elif defined(_WIN32) +typedef void(__thiscall* __libcpp_exception_destructor_func)(void*); +#else +typedef void (*__libcpp_exception_destructor_func)(void*); +#endif + extern "C" { _LIBCPP_OVERRIDABLE_FUNC_VIS void* __cxa_allocate_exception(size_t) throw(); _LIBCPP_OVERRIDABLE_FUNC_VIS void __cxa_free_exception(void*) throw(); struct __cxa_exception; -_LIBCPP_OVERRIDABLE_FUNC_VIS __cxa_exception* __cxa_init_primary_exception( -void*, -std::type_info*, -#if defined(_WIN32) -void(__thiscall*)(void*)) throw(); -#elif defined(__wasm__) -// In Wasm, a destructor returns its argument -void* (*)(void*)) throw(); -#else -void (*)(void*)) throw(); -#endif +_LIBCPP_OVERRIDABLE_FUNC_VIS __cxa_exception* +__cxa_init_primary_exception(void*, std::type_info*, __libcpp_exception_destructor_func) throw(); } } // namespace __cxxabiv1 diff --git a/libcxxabi/include/cxxabi.h b/libcxxabi/include/cxxabi.h index 0e3969084e04f..4162fd7ec2ba7 100644 --- a/libcxxabi/include/cxxabi.h +++ b/libcxxabi/include/cxxabi.h @@ -20,62 +20,51 @@ #include <__cxxabi_config.h> #define _LIBCPPABI_VERSION 15000 -#define _LIBCXXABI_NORETURN __attribute__((noreturn)) +#define _LIBCXXABI_NORETURN __attribute__((noreturn)) #define _LIBCXXABI_ALWAYS_COLD __attribute__((cold)) #ifdef __cplusplus namespace std { -#if defined(_WIN32) +# if defined(_WIN32) class _LIBCXXABI_TYPE_VIS type_info; // forward declaration -#else +# else class type_info; // forward declaration -#endif -} - +# endif +} // namespace std // runtime routines use C calling conventions, but are in __cxxabiv1 namespace namespace __cxxabiv1 { struct __cxa_exception; +# if defined(__wasm__) +typedef void*
[clang] [llvm] [ARM] Add support for Cortex-R52+ (PR #94633)
@@ -90,6 +90,8 @@ def ProcR7 : SubtargetFeature<"r7", "ARMProcFamily", "CortexR7", "Cortex-R7 ARM processors", []>; def ProcR52 : SubtargetFeature<"r52", "ARMProcFamily", "CortexR52", "Cortex-R52 ARM processors", []>; +def ProcR52plus : SubtargetFeature<"r52plus", "ARMProcFamily", "CortexR52plus", jthackray wrote: Thanks. I'll probably just keep it as-is (too many other concurrent tasks); upstreaming this now, since it was accidentally left downstream previously. https://github.com/llvm/llvm-project/pull/94633 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [APFloat] Add APFloat support for FP6 data types (PR #94735)
https://github.com/durga4github created https://github.com/llvm/llvm-project/pull/94735 This patch adds APFloat type support for two FP6 data types, E2M3 and E3M2. The definitions for the two formats are detailed in section 5.3.2 of the OCP specification, which can be accessed here: https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf >From 21432aeaeecc6ba06de252c460e5cb09abb68a29 Mon Sep 17 00:00:00 2001 From: Durgadoss R Date: Wed, 5 Jun 2024 19:22:31 +0530 Subject: [PATCH] [APFloat] Add APFloat support for FP6 data types This patch adds APFloat type support for two FP6 data types, E2M3 and E3M2. The definitions for the two formats are detailed in section 5.3.2 of the OCP specification, which can be accessed here: https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf Signed-off-by: Durgadoss R --- clang/lib/AST/MicrosoftMangle.cpp | 2 + llvm/include/llvm/ADT/APFloat.h| 14 + llvm/lib/Support/APFloat.cpp | 89 +- llvm/unittests/ADT/APFloatTest.cpp | 496 +++-- 4 files changed, 567 insertions(+), 34 deletions(-) diff --git a/clang/lib/AST/MicrosoftMangle.cpp b/clang/lib/AST/MicrosoftMangle.cpp index 36d611750ca48..72c79dab6bdcc 100644 --- a/clang/lib/AST/MicrosoftMangle.cpp +++ b/clang/lib/AST/MicrosoftMangle.cpp @@ -899,6 +899,8 @@ void MicrosoftCXXNameMangler::mangleFloat(llvm::APFloat Number) { case APFloat::S_Float8E4M3FNUZ: case APFloat::S_Float8E4M3B11FNUZ: case APFloat::S_FloatTF32: + case APFloat::S_Float6E3M2FN: + case APFloat::S_Float6E2M3FN: llvm_unreachable("Tried to mangle unexpected APFloat semantics"); } diff --git a/llvm/include/llvm/ADT/APFloat.h b/llvm/include/llvm/ADT/APFloat.h index 44a301ecc9928..149b7a165c9d4 100644 --- a/llvm/include/llvm/ADT/APFloat.h +++ b/llvm/include/llvm/ADT/APFloat.h @@ -189,6 +189,14 @@ struct APFloatBase { // improved range compared to half (16-bit) formats, at (potentially) // greater throughput than single precision (32-bit) formats. S_FloatTF32, +// 6-bit floating point number with bit layout S1E3M2. Unlike IEEE-754 +// types, there are no infinity or NaN values. The format is detailed in +// https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf +S_Float6E3M2FN, +// 6-bit floating point number with bit layout S1E2M3. Unlike IEEE-754 +// types, there are no infinity or NaN values. The format is detailed in +// https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf +S_Float6E2M3FN, S_x87DoubleExtended, S_MaxSemantics = S_x87DoubleExtended, @@ -209,6 +217,8 @@ struct APFloatBase { static const fltSemantics &Float8E4M3FNUZ() LLVM_READNONE; static const fltSemantics &Float8E4M3B11FNUZ() LLVM_READNONE; static const fltSemantics &FloatTF32() LLVM_READNONE; + static const fltSemantics &Float6E3M2FN() LLVM_READNONE; + static const fltSemantics &Float6E2M3FN() LLVM_READNONE; static const fltSemantics &x87DoubleExtended() LLVM_READNONE; /// A Pseudo fltsemantic used to construct APFloats that cannot conflict with @@ -627,6 +637,8 @@ class IEEEFloat final : public APFloatBase { APInt convertFloat8E4M3FNUZAPFloatToAPInt() const; APInt convertFloat8E4M3B11FNUZAPFloatToAPInt() const; APInt convertFloatTF32APFloatToAPInt() const; + APInt convertFloat6E3M2FNAPFloatToAPInt() const; + APInt convertFloat6E2M3FNAPFloatToAPInt() const; void initFromAPInt(const fltSemantics *Sem, const APInt &api); template void initFromIEEEAPInt(const APInt &api); void initFromHalfAPInt(const APInt &api); @@ -642,6 +654,8 @@ class IEEEFloat final : public APFloatBase { void initFromFloat8E4M3FNUZAPInt(const APInt &api); void initFromFloat8E4M3B11FNUZAPInt(const APInt &api); void initFromFloatTF32APInt(const APInt &api); + void initFromFloat6E3M2FNAPInt(const APInt &api); + void initFromFloat6E2M3FNAPInt(const APInt &api); void assign(const IEEEFloat &); void copySignificand(const IEEEFloat &); diff --git a/llvm/lib/Support/APFloat.cpp b/llvm/lib/Support/APFloat.cpp index 283fcc153b33a..b8ca56d96efe4 100644 --- a/llvm/lib/Support/APFloat.cpp +++ b/llvm/lib/Support/APFloat.cpp @@ -68,6 +68,10 @@ enum class fltNonfiniteBehavior { // `fltNanEncoding` enum. We treat all NaNs as quiet, as the available // encodings do not distinguish between signalling and quiet NaN. NanOnly, + + // This behavior is present in Float6E3M2FN and Float6E2M3FN types. + // There is no representation for Inf or NaN. + NoNanInf, }; // How NaN values are represented. This is curently only used in combination @@ -139,6 +143,10 @@ static constexpr fltSemantics semFloat8E4M3FNUZ = { static constexpr fltSemantics semFloat8E4M3B11FNUZ = { 4, -10, 4, 8, fltNonfiniteBehavior::NanOnly, fltNanEncoding::NegativeZero}; static constexpr fltSemantics semFloatTF32 = {127, -126, 11, 19}; +static co
[clang] [llvm] [APFloat] Add APFloat support for FP6 data types (PR #94735)
llvmbot wrote: @llvm/pr-subscribers-llvm-support Author: Durgadoss R (durga4github) Changes This patch adds APFloat type support for two FP6 data types, E2M3 and E3M2. The definitions for the two formats are detailed in section 5.3.2 of the OCP specification, which can be accessed here: https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf --- Patch is 34.42 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/94735.diff 4 Files Affected: - (modified) clang/lib/AST/MicrosoftMangle.cpp (+2) - (modified) llvm/include/llvm/ADT/APFloat.h (+14) - (modified) llvm/lib/Support/APFloat.cpp (+77-12) - (modified) llvm/unittests/ADT/APFloatTest.cpp (+474-22) ``diff diff --git a/clang/lib/AST/MicrosoftMangle.cpp b/clang/lib/AST/MicrosoftMangle.cpp index 36d611750ca48..72c79dab6bdcc 100644 --- a/clang/lib/AST/MicrosoftMangle.cpp +++ b/clang/lib/AST/MicrosoftMangle.cpp @@ -899,6 +899,8 @@ void MicrosoftCXXNameMangler::mangleFloat(llvm::APFloat Number) { case APFloat::S_Float8E4M3FNUZ: case APFloat::S_Float8E4M3B11FNUZ: case APFloat::S_FloatTF32: + case APFloat::S_Float6E3M2FN: + case APFloat::S_Float6E2M3FN: llvm_unreachable("Tried to mangle unexpected APFloat semantics"); } diff --git a/llvm/include/llvm/ADT/APFloat.h b/llvm/include/llvm/ADT/APFloat.h index 44a301ecc9928..149b7a165c9d4 100644 --- a/llvm/include/llvm/ADT/APFloat.h +++ b/llvm/include/llvm/ADT/APFloat.h @@ -189,6 +189,14 @@ struct APFloatBase { // improved range compared to half (16-bit) formats, at (potentially) // greater throughput than single precision (32-bit) formats. S_FloatTF32, +// 6-bit floating point number with bit layout S1E3M2. Unlike IEEE-754 +// types, there are no infinity or NaN values. The format is detailed in +// https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf +S_Float6E3M2FN, +// 6-bit floating point number with bit layout S1E2M3. Unlike IEEE-754 +// types, there are no infinity or NaN values. The format is detailed in +// https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf +S_Float6E2M3FN, S_x87DoubleExtended, S_MaxSemantics = S_x87DoubleExtended, @@ -209,6 +217,8 @@ struct APFloatBase { static const fltSemantics &Float8E4M3FNUZ() LLVM_READNONE; static const fltSemantics &Float8E4M3B11FNUZ() LLVM_READNONE; static const fltSemantics &FloatTF32() LLVM_READNONE; + static const fltSemantics &Float6E3M2FN() LLVM_READNONE; + static const fltSemantics &Float6E2M3FN() LLVM_READNONE; static const fltSemantics &x87DoubleExtended() LLVM_READNONE; /// A Pseudo fltsemantic used to construct APFloats that cannot conflict with @@ -627,6 +637,8 @@ class IEEEFloat final : public APFloatBase { APInt convertFloat8E4M3FNUZAPFloatToAPInt() const; APInt convertFloat8E4M3B11FNUZAPFloatToAPInt() const; APInt convertFloatTF32APFloatToAPInt() const; + APInt convertFloat6E3M2FNAPFloatToAPInt() const; + APInt convertFloat6E2M3FNAPFloatToAPInt() const; void initFromAPInt(const fltSemantics *Sem, const APInt &api); template void initFromIEEEAPInt(const APInt &api); void initFromHalfAPInt(const APInt &api); @@ -642,6 +654,8 @@ class IEEEFloat final : public APFloatBase { void initFromFloat8E4M3FNUZAPInt(const APInt &api); void initFromFloat8E4M3B11FNUZAPInt(const APInt &api); void initFromFloatTF32APInt(const APInt &api); + void initFromFloat6E3M2FNAPInt(const APInt &api); + void initFromFloat6E2M3FNAPInt(const APInt &api); void assign(const IEEEFloat &); void copySignificand(const IEEEFloat &); diff --git a/llvm/lib/Support/APFloat.cpp b/llvm/lib/Support/APFloat.cpp index 283fcc153b33a..b8ca56d96efe4 100644 --- a/llvm/lib/Support/APFloat.cpp +++ b/llvm/lib/Support/APFloat.cpp @@ -68,6 +68,10 @@ enum class fltNonfiniteBehavior { // `fltNanEncoding` enum. We treat all NaNs as quiet, as the available // encodings do not distinguish between signalling and quiet NaN. NanOnly, + + // This behavior is present in Float6E3M2FN and Float6E2M3FN types. + // There is no representation for Inf or NaN. + NoNanInf, }; // How NaN values are represented. This is curently only used in combination @@ -139,6 +143,10 @@ static constexpr fltSemantics semFloat8E4M3FNUZ = { static constexpr fltSemantics semFloat8E4M3B11FNUZ = { 4, -10, 4, 8, fltNonfiniteBehavior::NanOnly, fltNanEncoding::NegativeZero}; static constexpr fltSemantics semFloatTF32 = {127, -126, 11, 19}; +static constexpr fltSemantics semFloat6E3M2FN = { +4, -2, 3, 6, fltNonfiniteBehavior::NoNanInf}; +static constexpr fltSemantics semFloat6E2M3FN = { +2, 0, 4, 6, fltNonfiniteBehavior::NoNanInf}; static constexpr fltSemantics semX87DoubleExtended = {16383, -16382, 64, 80}; static constexpr fltSemantics semBogus = {0, 0, 0, 0}; @@ -206,6 +214,10 @@ const llvm::fltSemantics &APFloatB
[clang] [llvm] [APFloat] Add APFloat support for FP6 data types (PR #94735)
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 ac404632f991fc6e7dc75ef553a99676ba8002ce 21432aeaeecc6ba06de252c460e5cb09abb68a29 -- clang/lib/AST/MicrosoftMangle.cpp llvm/include/llvm/ADT/APFloat.h llvm/lib/Support/APFloat.cpp llvm/unittests/ADT/APFloatTest.cpp `` View the diff from clang-format here. ``diff diff --git a/llvm/lib/Support/APFloat.cpp b/llvm/lib/Support/APFloat.cpp index b8ca56d96e..04d54ee663 100644 --- a/llvm/lib/Support/APFloat.cpp +++ b/llvm/lib/Support/APFloat.cpp @@ -1531,7 +1531,7 @@ IEEEFloat::opStatus IEEEFloat::handleOverflow(roundingMode rounding_mode) { makeNaN(false, sign); else category = fcInfinity; - return (opStatus) (opOverflow | opInexact); + return (opStatus)(opOverflow | opInexact); } } diff --git a/llvm/unittests/ADT/APFloatTest.cpp b/llvm/unittests/ADT/APFloatTest.cpp index d80442b066..6b21afb52f 100644 --- a/llvm/unittests/ADT/APFloatTest.cpp +++ b/llvm/unittests/ADT/APFloatTest.cpp @@ -735,7 +735,6 @@ TEST(APFloatTest, IsSmallestNormalized) { EXPECT_FALSE(APFloat::getSNaN(Semantics).isSmallestNormalized()); } - EXPECT_FALSE(APFloat::getLargest(Semantics).isSmallestNormalized()); EXPECT_FALSE(APFloat::getLargest(Semantics, true).isSmallestNormalized()); @@ -1830,8 +1829,7 @@ TEST(APFloatTest, getLargest) { 30, APFloat::getLargest(APFloat::Float8E4M3B11FNUZ()).convertToDouble()); EXPECT_EQ(3.40116213421e+38f, APFloat::getLargest(APFloat::FloatTF32()).convertToFloat()); - EXPECT_EQ(28, -APFloat::getLargest(APFloat::Float6E3M2FN()).convertToDouble()); + EXPECT_EQ(28, APFloat::getLargest(APFloat::Float6E3M2FN()).convertToDouble()); EXPECT_EQ(7.5, APFloat::getLargest(APFloat::Float6E2M3FN()).convertToDouble()); } @@ -1906,7 +1904,6 @@ TEST(APFloatTest, getSmallest) { EXPECT_TRUE(test.isFiniteNonZero()); EXPECT_TRUE(test.isDenormal()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); - } TEST(APFloatTest, getSmallestNormalized) { @@ -2004,7 +2001,6 @@ TEST(APFloatTest, getSmallestNormalized) { EXPECT_FALSE(test.isDenormal()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); EXPECT_TRUE(test.isSmallestNormalized()); - } TEST(APFloatTest, getZero) { @@ -7025,8 +7021,7 @@ TEST(APFloatTest, Float6E3M2FNToDouble) { APFloat::getSmallestNormalized(APFloat::Float6E3M2FN(), true); EXPECT_EQ(-0x1p-2, NegSmallest.convertToDouble()); - APFloat SmallestDenorm = - APFloat::getSmallest(APFloat::Float6E3M2FN(), false); + APFloat SmallestDenorm = APFloat::getSmallest(APFloat::Float6E3M2FN(), false); EXPECT_TRUE(SmallestDenorm.isDenormal()); EXPECT_EQ(0x0.1p0, SmallestDenorm.convertToDouble()); } @@ -7047,8 +7042,7 @@ TEST(APFloatTest, Float6E2M3FNToDouble) { APFloat::getSmallestNormalized(APFloat::Float6E2M3FN(), true); EXPECT_EQ(-0x1p0, NegSmallest.convertToDouble()); - APFloat SmallestDenorm = - APFloat::getSmallest(APFloat::Float6E2M3FN(), false); + APFloat SmallestDenorm = APFloat::getSmallest(APFloat::Float6E2M3FN(), false); EXPECT_TRUE(SmallestDenorm.isDenormal()); EXPECT_EQ(0x0.2p0, SmallestDenorm.convertToDouble()); } @@ -7077,8 +7071,7 @@ TEST(APFloatTest, Float6E3M2FNToFloat) { APFloat::getSmallestNormalized(APFloat::Float6E3M2FN(), true); EXPECT_EQ(-0x1p-2, NegSmallest.convertToFloat()); - APFloat SmallestDenorm = - APFloat::getSmallest(APFloat::Float6E3M2FN(), false); + APFloat SmallestDenorm = APFloat::getSmallest(APFloat::Float6E3M2FN(), false); EXPECT_TRUE(SmallestDenorm.isDenormal()); EXPECT_EQ(0x0.1p0, SmallestDenorm.convertToFloat()); } @@ -7107,8 +7100,7 @@ TEST(APFloatTest, Float6E2M3FNToFloat) { APFloat::getSmallestNormalized(APFloat::Float6E2M3FN(), true); EXPECT_EQ(-0x1p0, NegSmallest.convertToFloat()); - APFloat SmallestDenorm = - APFloat::getSmallest(APFloat::Float6E2M3FN(), false); + APFloat SmallestDenorm = APFloat::getSmallest(APFloat::Float6E2M3FN(), false); EXPECT_TRUE(SmallestDenorm.isDenormal()); EXPECT_EQ(0x0.2p0, SmallestDenorm.convertToFloat()); } `` https://github.com/llvm/llvm-project/pull/94735 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Driver] Add winsysroot alias to the GNU driver (PR #94731)
github-actions[bot] wrote: ⚠️ We detected that you are using a GitHub private e-mail address to contribute to the repo. Please turn off [Keep my email addresses private](https://github.com/settings/emails) setting in your account. See [LLVM Discourse](https://discourse.llvm.org/t/hidden-emails-on-github-should-we-do-something-about-it) for more information. https://github.com/llvm/llvm-project/pull/94731 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Fix-it hint for `++this` -> `++*this` when deref is modifiable (PR #94159)
https://github.com/Rajveer100 updated https://github.com/llvm/llvm-project/pull/94159 >From e38b38773bcade3407dde112994de5a6c5f0d7e0 Mon Sep 17 00:00:00 2001 From: Rajveer Date: Sun, 2 Jun 2024 18:33:37 +0530 Subject: [PATCH] [clang] Fix-it hint for `++this` -> `++*this` when deref is modifiable Resolves #93066 --- .../clang/Basic/DiagnosticSemaKinds.td| 3 ++ clang/lib/Sema/SemaExpr.cpp | 30 -- clang/test/C/drs/dr1xx.c | 1 + clang/test/Sema/debug-93066.cpp | 31 +++ clang/test/Sema/exprs.c | 2 ++ clang/test/Sema/va_arg_x86_32.c | 1 + clang/test/SemaObjCXX/sel-address.mm | 1 + 7 files changed, 67 insertions(+), 2 deletions(-) create mode 100644 clang/test/Sema/debug-93066.cpp diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td index 270b0a1e01307..0ad0a80c21521 100644 --- a/clang/include/clang/Basic/DiagnosticSemaKinds.td +++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -8777,6 +8777,9 @@ def err_typecheck_incomplete_type_not_modifiable_lvalue : Error< def err_typecheck_lvalue_casts_not_supported : Error< "assignment to cast is illegal, lvalue casts are not supported">; +def note_typecheck_expression_not_modifiable_lvalue : Note< + "add '*' to dereference it">; + def err_typecheck_duplicate_vector_components_not_mlvalue : Error< "vector is not assignable (contains duplicate components)">; def err_block_decl_ref_not_modifiable_lvalue : Error< diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp index ff9c5ead36dcf..4c1dc9313947b 100644 --- a/clang/lib/Sema/SemaExpr.cpp +++ b/clang/lib/Sema/SemaExpr.cpp @@ -13367,6 +13367,20 @@ static void DiagnoseConstAssignment(Sema &S, const Expr *E, if (!DiagnosticEmitted) { S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstVariable << VD << VD->getType(); + ExprResult Deref; + Expr *TE = const_cast(E); + { +Sema::TentativeAnalysisScope Trap(S); +Deref = S.ActOnUnaryOp(S.getCurScope(), Loc, tok::star, TE); + } + if (Deref.isUsable() && + Deref.get()->isModifiableLvalue(S.Context, &Loc) == + Expr::MLV_Valid && + !E->getType()->isObjCObjectPointerType()) { +S.Diag(Loc, diag::note_typecheck_expression_not_modifiable_lvalue) +<< E->getSourceRange() +<< FixItHint::CreateInsertion(E->getBeginLoc(), "*"); + } DiagnosticEmitted = true; } S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) @@ -13587,10 +13601,22 @@ static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { SourceRange Assign; if (Loc != OrigLoc) Assign = SourceRange(OrigLoc, OrigLoc); - if (NeedType) + if (NeedType) { S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; - else + } else { +ExprResult Deref; +{ + Sema::TentativeAnalysisScope Trap(S); + Deref = S.ActOnUnaryOp(S.getCurScope(), Loc, tok::star, E); +} S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; +if (Deref.isUsable() && +Deref.get()->isModifiableLvalue(S.Context, &Loc) == Expr::MLV_Valid) { + S.Diag(Loc, diag::note_typecheck_expression_not_modifiable_lvalue) + << E->getSourceRange() << Assign + << FixItHint::CreateInsertion(E->getBeginLoc(), "*"); +} + } return true; } diff --git a/clang/test/C/drs/dr1xx.c b/clang/test/C/drs/dr1xx.c index 47538e44428c3..20e953b2c20ac 100644 --- a/clang/test/C/drs/dr1xx.c +++ b/clang/test/C/drs/dr1xx.c @@ -296,6 +296,7 @@ void dr126(void) { */ *object = 12; /* ok */ ++object; /* expected-error {{cannot assign to variable 'object' with const-qualified type 'const IP' (aka 'int *const')}} */ + /* expected-note@-1 {{add '*' to dereference it}} */ } /* WG14 DR128: yes diff --git a/clang/test/Sema/debug-93066.cpp b/clang/test/Sema/debug-93066.cpp new file mode 100644 index 0..8e9c382a63bbe --- /dev/null +++ b/clang/test/Sema/debug-93066.cpp @@ -0,0 +1,31 @@ +// RUN: %clang_cc1 -std=c++23 -fsyntax-only -verify %s + +struct S { + void f() { +++this; // expected-error {{expression is not assignable}} +// expected-note@-1 {{add '*' to dereference it}} + } + + void g() const { +++this; // expected-error {{expression is not assignable}} + } +}; + +void f(int* a, int* const b, const int* const c, __UINTPTR_TYPE__ d) { + (int*)d = 4; // expected-error {{assignment to cast is illegal, lvalue casts are not supported}} + // expected-note@-1 {{add '*' to dereference it}} + + ++a; + ++b; // expected-error {{cannot assign to variable 'b' with const-qualified type 'int *const'}} + // expected-note@-1 {{add '*' to dereference it}} + // expected
[clang] [clang] Fix-it hint for `++this` -> `++*this` when deref is modifiable (PR #94159)
@@ -10,6 +10,7 @@ void h() { SEL* ps = &s; @selector(dealloc) = s; // expected-error {{expression is not assignable}} + // expected-note@-1 {{add '*' to dereference it}} Rajveer100 wrote: One way I can think of is to do a AST visit and check for `ObjCSelectorExpr` in the child nodes of the `ValueDecl`. https://github.com/llvm/llvm-project/pull/94159 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [APFloat] Add APFloat support for FP6 data types (PR #94735)
https://github.com/durga4github updated https://github.com/llvm/llvm-project/pull/94735 >From ac137c57ee35e1662b40796637eb4b25aa773849 Mon Sep 17 00:00:00 2001 From: Durgadoss R Date: Wed, 5 Jun 2024 19:22:31 +0530 Subject: [PATCH] [APFloat] Add APFloat support for FP6 data types This patch adds APFloat type support for two FP6 data types, E2M3 and E3M2. The definitions for the two formats are detailed in section 5.3.2 of the OCP specification, which can be accessed here: https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf Signed-off-by: Durgadoss R --- clang/lib/AST/MicrosoftMangle.cpp | 2 + llvm/include/llvm/ADT/APFloat.h| 14 + llvm/lib/Support/APFloat.cpp | 89 +- llvm/unittests/ADT/APFloatTest.cpp | 488 +++-- 4 files changed, 559 insertions(+), 34 deletions(-) diff --git a/clang/lib/AST/MicrosoftMangle.cpp b/clang/lib/AST/MicrosoftMangle.cpp index 36d611750ca48..72c79dab6bdcc 100644 --- a/clang/lib/AST/MicrosoftMangle.cpp +++ b/clang/lib/AST/MicrosoftMangle.cpp @@ -899,6 +899,8 @@ void MicrosoftCXXNameMangler::mangleFloat(llvm::APFloat Number) { case APFloat::S_Float8E4M3FNUZ: case APFloat::S_Float8E4M3B11FNUZ: case APFloat::S_FloatTF32: + case APFloat::S_Float6E3M2FN: + case APFloat::S_Float6E2M3FN: llvm_unreachable("Tried to mangle unexpected APFloat semantics"); } diff --git a/llvm/include/llvm/ADT/APFloat.h b/llvm/include/llvm/ADT/APFloat.h index 44a301ecc9928..149b7a165c9d4 100644 --- a/llvm/include/llvm/ADT/APFloat.h +++ b/llvm/include/llvm/ADT/APFloat.h @@ -189,6 +189,14 @@ struct APFloatBase { // improved range compared to half (16-bit) formats, at (potentially) // greater throughput than single precision (32-bit) formats. S_FloatTF32, +// 6-bit floating point number with bit layout S1E3M2. Unlike IEEE-754 +// types, there are no infinity or NaN values. The format is detailed in +// https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf +S_Float6E3M2FN, +// 6-bit floating point number with bit layout S1E2M3. Unlike IEEE-754 +// types, there are no infinity or NaN values. The format is detailed in +// https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf +S_Float6E2M3FN, S_x87DoubleExtended, S_MaxSemantics = S_x87DoubleExtended, @@ -209,6 +217,8 @@ struct APFloatBase { static const fltSemantics &Float8E4M3FNUZ() LLVM_READNONE; static const fltSemantics &Float8E4M3B11FNUZ() LLVM_READNONE; static const fltSemantics &FloatTF32() LLVM_READNONE; + static const fltSemantics &Float6E3M2FN() LLVM_READNONE; + static const fltSemantics &Float6E2M3FN() LLVM_READNONE; static const fltSemantics &x87DoubleExtended() LLVM_READNONE; /// A Pseudo fltsemantic used to construct APFloats that cannot conflict with @@ -627,6 +637,8 @@ class IEEEFloat final : public APFloatBase { APInt convertFloat8E4M3FNUZAPFloatToAPInt() const; APInt convertFloat8E4M3B11FNUZAPFloatToAPInt() const; APInt convertFloatTF32APFloatToAPInt() const; + APInt convertFloat6E3M2FNAPFloatToAPInt() const; + APInt convertFloat6E2M3FNAPFloatToAPInt() const; void initFromAPInt(const fltSemantics *Sem, const APInt &api); template void initFromIEEEAPInt(const APInt &api); void initFromHalfAPInt(const APInt &api); @@ -642,6 +654,8 @@ class IEEEFloat final : public APFloatBase { void initFromFloat8E4M3FNUZAPInt(const APInt &api); void initFromFloat8E4M3B11FNUZAPInt(const APInt &api); void initFromFloatTF32APInt(const APInt &api); + void initFromFloat6E3M2FNAPInt(const APInt &api); + void initFromFloat6E2M3FNAPInt(const APInt &api); void assign(const IEEEFloat &); void copySignificand(const IEEEFloat &); diff --git a/llvm/lib/Support/APFloat.cpp b/llvm/lib/Support/APFloat.cpp index 283fcc153b33a..04d54ee66309c 100644 --- a/llvm/lib/Support/APFloat.cpp +++ b/llvm/lib/Support/APFloat.cpp @@ -68,6 +68,10 @@ enum class fltNonfiniteBehavior { // `fltNanEncoding` enum. We treat all NaNs as quiet, as the available // encodings do not distinguish between signalling and quiet NaN. NanOnly, + + // This behavior is present in Float6E3M2FN and Float6E2M3FN types. + // There is no representation for Inf or NaN. + NoNanInf, }; // How NaN values are represented. This is curently only used in combination @@ -139,6 +143,10 @@ static constexpr fltSemantics semFloat8E4M3FNUZ = { static constexpr fltSemantics semFloat8E4M3B11FNUZ = { 4, -10, 4, 8, fltNonfiniteBehavior::NanOnly, fltNanEncoding::NegativeZero}; static constexpr fltSemantics semFloatTF32 = {127, -126, 11, 19}; +static constexpr fltSemantics semFloat6E3M2FN = { +4, -2, 3, 6, fltNonfiniteBehavior::NoNanInf}; +static constexpr fltSemantics semFloat6E2M3FN = { +2, 0, 4, 6, fltNonfiniteBehavior::NoNanInf}; static constexpr fltSemantics semX87DoubleExtended = {16383, -16382, 64, 80}; static con
[clang] [clang-tools-extra] [clangd] Fix crash with null check for Token at Loc (PR #94528)
https://github.com/usx95 updated https://github.com/llvm/llvm-project/pull/94528 >From b13a663ae347649a3bcf9d6e381a5fbbfdc9ea4b Mon Sep 17 00:00:00 2001 From: Utkarsh Saxena Date: Wed, 5 Jun 2024 19:48:48 + Subject: [PATCH 1/6] [clangd] Fix crash with null check for Token at Loc --- clang-tools-extra/clangd/XRefs.cpp| 32 +++ .../clangd/unittests/XRefsTests.cpp | 14 +++- 2 files changed, 31 insertions(+), 15 deletions(-) diff --git a/clang-tools-extra/clangd/XRefs.cpp b/clang-tools-extra/clangd/XRefs.cpp index cd909266489a8..f52228e599591 100644 --- a/clang-tools-extra/clangd/XRefs.cpp +++ b/clang-tools-extra/clangd/XRefs.cpp @@ -1354,6 +1354,8 @@ maybeFindIncludeReferences(ParsedAST &AST, Position Pos, ReferencesResult::Reference Result; const auto *Token = AST.getTokens().spelledTokenAt(Loc); +if (!Token) + return; Result.Loc.range = Range{sourceLocToPosition(SM, Token->location()), sourceLocToPosition(SM, Token->endLocation())}; Result.Loc.uri = URIMainFile; @@ -2012,15 +2014,15 @@ static QualType typeForNode(const SelectionTree::Node *N) { return QualType(); } -// Given a type targeted by the cursor, return one or more types that are more interesting -// to target. -static void unwrapFindType( -QualType T, const HeuristicResolver* H, llvm::SmallVector& Out) { +// Given a type targeted by the cursor, return one or more types that are more +// interesting to target. +static void unwrapFindType(QualType T, const HeuristicResolver *H, + llvm::SmallVector &Out) { if (T.isNull()) return; // If there's a specific type alias, point at that rather than unwrapping. - if (const auto* TDT = T->getAs()) + if (const auto *TDT = T->getAs()) return Out.push_back(QualType(TDT, 0)); // Pointers etc => pointee type. @@ -2044,17 +2046,18 @@ static void unwrapFindType( // For smart pointer types, add the underlying type if (H) -if (const auto* PointeeType = H->getPointeeType(T.getNonReferenceType().getTypePtr())) { -unwrapFindType(QualType(PointeeType, 0), H, Out); -return Out.push_back(T); +if (const auto *PointeeType = +H->getPointeeType(T.getNonReferenceType().getTypePtr())) { + unwrapFindType(QualType(PointeeType, 0), H, Out); + return Out.push_back(T); } return Out.push_back(T); } // Convenience overload, to allow calling this without the out-parameter -static llvm::SmallVector unwrapFindType( -QualType T, const HeuristicResolver* H) { +static llvm::SmallVector unwrapFindType(QualType T, + const HeuristicResolver *H) { llvm::SmallVector Result; unwrapFindType(T, H, Result); return Result; @@ -2076,10 +2079,11 @@ std::vector findType(ParsedAST &AST, Position Pos, std::vector LocatedSymbols; // NOTE: unwrapFindType might return duplicates for something like -// unique_ptr>. Let's *not* remove them, because it gives you some -// information about the type you may have not known before -// (since unique_ptr> != unique_ptr). -for (const QualType& Type : unwrapFindType(typeForNode(N), AST.getHeuristicResolver())) +// unique_ptr>. Let's *not* remove them, because it gives you +// some information about the type you may have not known before (since +// unique_ptr> != unique_ptr). +for (const QualType &Type : + unwrapFindType(typeForNode(N), AST.getHeuristicResolver())) llvm::copy(locateSymbolForType(AST, Type, Index), std::back_inserter(LocatedSymbols)); diff --git a/clang-tools-extra/clangd/unittests/XRefsTests.cpp b/clang-tools-extra/clangd/unittests/XRefsTests.cpp index f53cbf01b7992..c4def624a2fcc 100644 --- a/clang-tools-extra/clangd/unittests/XRefsTests.cpp +++ b/clang-tools-extra/clangd/unittests/XRefsTests.cpp @@ -2358,7 +2358,14 @@ TEST(FindReferences, UsedSymbolsFromInclude) { R"cpp([[#in^clude ]] std::[[vector]] vec; - )cpp"}; + )cpp", + + R"cpp( +[[#include ^"operator_qoutes.h"]] +using ::operator_qoutes::[[operator]]"" _b; +auto x = 1_b; + )cpp", + }; for (const char *Test : Tests) { Annotations T(Test); auto TU = TestTU::withCode(T.code()); @@ -2375,6 +2382,11 @@ TEST(FindReferences, UsedSymbolsFromInclude) { class vector{}; } )cpp"); +TU.AdditionalFiles["operator_qoutes.h"] = guard(R"cpp( + namespace operator_qoutes { +bool operator"" _b(unsigned long long value); + } +)cpp"); TU.ExtraArgs.push_back("-isystem" + testPath("system")); auto AST = TU.build(); >From 3fe19589a332342abb069316224bdf9a6150c660 Mon Sep 17 00:00:00 2001 From: Utkarsh Saxena Date: Wed, 5 Jun 2024 19:59:44 + Subject: [PATCH 2/6] remove unintentional format --- clang-tools-extra/clangd/XR
[clang] [llvm] [APFloat] Add APFloat support for FP6 data types (PR #94735)
durga4github wrote: @ThomasRaoux , Could you please help review this change? https://github.com/llvm/llvm-project/pull/94735 ___ 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 crash with null check for Token at Loc (PR #94528)
@@ -447,7 +447,7 @@ class HighlightingsBuilder { if (!RLoc.isValid()) return; -const auto *RTok = TB.spelledTokenAt(RLoc); +const auto *RTok = TB.spelledTokenContaining(RLoc); usx95 wrote: Done. https://github.com/llvm/llvm-project/pull/94528 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] 5f1adf0 - [clangd] Fix crash with null check for Token at Loc (#94528)
Author: Utkarsh Saxena Date: 2024-06-07T11:08:25+02:00 New Revision: 5f1adf0433c6007f8be885b832c852da67e8524c URL: https://github.com/llvm/llvm-project/commit/5f1adf0433c6007f8be885b832c852da67e8524c DIFF: https://github.com/llvm/llvm-project/commit/5f1adf0433c6007f8be885b832c852da67e8524c.diff LOG: [clangd] Fix crash with null check for Token at Loc (#94528) Fixes https://github.com/llvm/llvm-project/issues/94599 Added: Modified: clang-tools-extra/clangd/FindSymbols.cpp clang-tools-extra/clangd/IncludeCleaner.cpp clang-tools-extra/clangd/SemanticHighlighting.cpp clang-tools-extra/clangd/XRefs.cpp clang-tools-extra/clangd/refactor/Rename.cpp clang-tools-extra/clangd/unittests/PreambleTests.cpp clang-tools-extra/clangd/unittests/XRefsTests.cpp clang/include/clang/Tooling/Syntax/Tokens.h clang/lib/Tooling/Syntax/Tokens.cpp clang/unittests/Tooling/Syntax/TokensTest.cpp Removed: diff --git a/clang-tools-extra/clangd/FindSymbols.cpp b/clang-tools-extra/clangd/FindSymbols.cpp index 5244a4e893769..55f16b7085a6f 100644 --- a/clang-tools-extra/clangd/FindSymbols.cpp +++ b/clang-tools-extra/clangd/FindSymbols.cpp @@ -454,7 +454,7 @@ class DocumentOutline { if (!MacroName.isValid() || !MacroName.isFileID()) continue; // All conditions satisfied, add the macro. - if (auto *Tok = AST.getTokens().spelledTokenAt(MacroName)) + if (auto *Tok = AST.getTokens().spelledTokenContaining(MacroName)) CurParent = &CurParent->inMacro( *Tok, SM, AST.getTokens().expansionStartingAt(Tok)); } diff --git a/clang-tools-extra/clangd/IncludeCleaner.cpp b/clang-tools-extra/clangd/IncludeCleaner.cpp index 01b47679790f1..dc5b7ec95db5f 100644 --- a/clang-tools-extra/clangd/IncludeCleaner.cpp +++ b/clang-tools-extra/clangd/IncludeCleaner.cpp @@ -303,7 +303,7 @@ collectMacroReferences(ParsedAST &AST) { for (const auto &[_, Refs] : AST.getMacros().MacroRefs) { for (const auto &Ref : Refs) { auto Loc = SM.getComposedLoc(SM.getMainFileID(), Ref.StartOffset); - const auto *Tok = AST.getTokens().spelledTokenAt(Loc); + const auto *Tok = AST.getTokens().spelledTokenContaining(Loc); if (!Tok) continue; auto Macro = locateMacroAt(*Tok, PP); diff --git a/clang-tools-extra/clangd/SemanticHighlighting.cpp b/clang-tools-extra/clangd/SemanticHighlighting.cpp index eb025f21f3616..a366f1331c2d3 100644 --- a/clang-tools-extra/clangd/SemanticHighlighting.cpp +++ b/clang-tools-extra/clangd/SemanticHighlighting.cpp @@ -447,11 +447,10 @@ class HighlightingsBuilder { if (!RLoc.isValid()) return; -const auto *RTok = TB.spelledTokenAt(RLoc); -// Handle `>>`. RLoc is always pointing at the right location, just change -// the end to be offset by 1. -// We'll either point at the beginning of `>>`, hence get a proper spelled -// or point in the middle of `>>` hence get no spelled tok. +const auto *RTok = TB.spelledTokenContaining(RLoc); +// Handle `>>`. RLoc is either part of `>>` or a spelled token on its own +// `>`. If it's the former, slice to have length of 1, if latter use the +// token as-is. if (!RTok || RTok->kind() == tok::greatergreater) { Position Begin = sourceLocToPosition(SourceMgr, RLoc); Position End = sourceLocToPosition(SourceMgr, RLoc.getLocWithOffset(1)); @@ -577,7 +576,7 @@ class HighlightingsBuilder { return std::nullopt; // We might have offsets in the main file that don't correspond to any // spelled tokens. -const auto *Tok = TB.spelledTokenAt(Loc); +const auto *Tok = TB.spelledTokenContaining(Loc); if (!Tok) return std::nullopt; return halfOpenToRange(SourceMgr, diff --git a/clang-tools-extra/clangd/XRefs.cpp b/clang-tools-extra/clangd/XRefs.cpp index cd909266489a8..f94cadeffaa29 100644 --- a/clang-tools-extra/clangd/XRefs.cpp +++ b/clang-tools-extra/clangd/XRefs.cpp @@ -844,7 +844,7 @@ std::vector getDocumentLinks(ParsedAST &AST) { if (Inc.Resolved.empty()) continue; auto HashLoc = SM.getComposedLoc(SM.getMainFileID(), Inc.HashOffset); -const auto *HashTok = AST.getTokens().spelledTokenAt(HashLoc); +const auto *HashTok = AST.getTokens().spelledTokenContaining(HashLoc); assert(HashTok && "got inclusion at wrong offset"); const auto *IncludeTok = std::next(HashTok); const auto *FileTok = std::next(IncludeTok); @@ -938,7 +938,7 @@ class ReferenceFinder : public index::IndexDataConsumer { CollectorOpts.CollectMainFileSymbols = true; for (SourceLocation L : Locs) { L = SM.getFileLoc(L); - if (const auto *Tok = TB.spelledTokenAt(L)) + if (const auto *Tok = TB.spelledTokenContaining(L)) References.push_back( {*Tok, Roles, SymbolCollector::getRefContainer(ASTNode.Parent, CollectorOpts
[clang] [clang-tools-extra] [clangd] Fix crash with null check for Token at Loc (PR #94528)
https://github.com/usx95 closed https://github.com/llvm/llvm-project/pull/94528 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang][Sema] qualifier should be transformed (PR #94725)
https://github.com/jcsxky updated https://github.com/llvm/llvm-project/pull/94725 >From 6a90ef0b3947a0de2d6453856c80d8f0fd393548 Mon Sep 17 00:00:00 2001 From: huqizhi Date: Fri, 7 Jun 2024 14:04:52 +0800 Subject: [PATCH] [Clang][Sema] qualifier should be transformed --- clang/lib/Sema/TreeTransform.h | 18 ++ .../SemaCXX/many-template-parameter-lists.cpp | 6 +++--- clang/test/SemaTemplate/PR91677.cpp| 14 ++ clang/test/SemaTemplate/instantiate-scope.cpp | 11 ++- .../test/SemaTemplate/typename-specifier-3.cpp | 7 --- 5 files changed, 45 insertions(+), 11 deletions(-) create mode 100644 clang/test/SemaTemplate/PR91677.cpp diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h index 3bfda09d5f80f..b4d31cbbf0c7c 100644 --- a/clang/lib/Sema/TreeTransform.h +++ b/clang/lib/Sema/TreeTransform.h @@ -4568,6 +4568,24 @@ TreeTransform::TransformTemplateName(CXXScopeSpec &SS, if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) { TemplateDecl *Template = QTN->getUnderlyingTemplate().getAsTemplateDecl(); assert(Template && "qualified template name must refer to a template"); +if (QTN->getQualifier()) { + CXXScopeSpec QualifierSS; + QualifierSS.MakeTrivial(getSema().getASTContext(), QTN->getQualifier(), + NameLoc); + NestedNameSpecifierLoc QualifierLoc = + QualifierSS.getWithLocInContext(getSema().getASTContext()); + NestedNameSpecifierLoc TransformedQualifierLoc = + getDerived().TransformNestedNameSpecifierLoc(QualifierLoc); + if (!TransformedQualifierLoc) +return Name; + if (!getDerived().AlwaysRebuild() && + QualifierLoc != TransformedQualifierLoc) { +SS.Adopt(TransformedQualifierLoc); +return getDerived().RebuildTemplateName( +SS, SourceLocation(), *Template->getIdentifier(), NameLoc, +ObjectType, FirstQualifierInScope, /*AllowInjectedClassName=*/true); + } +} TemplateDecl *TransTemplate = cast_or_null(getDerived().TransformDecl(NameLoc, diff --git a/clang/test/SemaCXX/many-template-parameter-lists.cpp b/clang/test/SemaCXX/many-template-parameter-lists.cpp index f98005c7e6fb5..b5d954986dd4f 100644 --- a/clang/test/SemaCXX/many-template-parameter-lists.cpp +++ b/clang/test/SemaCXX/many-template-parameter-lists.cpp @@ -5,7 +5,7 @@ template struct X { template - struct A { // expected-note {{not-yet-instantiated member is declared here}} + struct A { template struct B { template @@ -28,9 +28,9 @@ struct X { template template template - friend void A::template B::template C::template D::template E::operator+=(Z); // expected-warning {{not supported}} expected-error {{no member 'A' in 'X'; it has not yet been instantiated}} + friend void A::template B::template C::template D::template E::operator+=(Z); // expected-warning {{dependent nested name specifier 'A::B::C::D::template E::' for friend class declaration is not supported; turning off access control for 'X'}} }; void test() { - X::A::B::C::D::E() += 1.0; // expected-note {{in instantiation of template class 'X' requested here}} + X::A::B::C::D::E() += 1.0; } diff --git a/clang/test/SemaTemplate/PR91677.cpp b/clang/test/SemaTemplate/PR91677.cpp new file mode 100644 index 0..cc8db60a438ea --- /dev/null +++ b/clang/test/SemaTemplate/PR91677.cpp @@ -0,0 +1,14 @@ +// RUN: %clang_cc1 -verify -std=c++20 -fsyntax-only %s +// expected-no-diagnostics + +template struct t1 { + template + struct t2 {}; +}; + +template +t1::template t2 f1(); + +void f2() { + f1(); +} diff --git a/clang/test/SemaTemplate/instantiate-scope.cpp b/clang/test/SemaTemplate/instantiate-scope.cpp index 733105674b7a4..a8f02acd23fab 100644 --- a/clang/test/SemaTemplate/instantiate-scope.cpp +++ b/clang/test/SemaTemplate/instantiate-scope.cpp @@ -2,7 +2,8 @@ template struct X { void f(int); - void f(...); + void f(...); // expected-note {{member is declared here}} \ + expected-note {{member is declared here}} static int n; }; @@ -11,10 +12,10 @@ template using A = T; // These definitions are OK, X...> is equivalent to X // so this defines the member of the primary template. template -void X...>::f(int) {} // expected-error {{undeclared}} +void X...>::f(int) {} // expected-error {{use of undeclared identifier 'f'}} template -int X...>::n = 0; // expected-error {{undeclared}} +int X...>::n = 0; // expected-error {{use of undeclared identifier 'f'}} struct Y {}; void f(Y); @@ -25,6 +26,6 @@ void g() { // Error, substitution fails; this should not be treated as a SFINAE-able // condition, so we don't select X::f(...). - X().f(0); // expected-note {{instantiation of}} - X::n = 1; // expected-note {{instantiation of}} + X().f(0); // expected-note {{in instantiation of member function 'X::f'
[clang] [Clang][Sema] qualifier should be transformed (PR #94725)
https://github.com/jcsxky updated https://github.com/llvm/llvm-project/pull/94725 >From 57576620fc412015bd19a34e12be61f4b81eb655 Mon Sep 17 00:00:00 2001 From: huqizhi Date: Fri, 7 Jun 2024 14:04:52 +0800 Subject: [PATCH] [Clang][Sema] qualifier should be transformed --- clang/lib/Sema/TreeTransform.h | 18 ++ .../SemaCXX/many-template-parameter-lists.cpp | 6 +++--- clang/test/SemaTemplate/PR91677.cpp| 14 ++ clang/test/SemaTemplate/instantiate-scope.cpp | 8 .../test/SemaTemplate/typename-specifier-3.cpp | 7 --- 5 files changed, 43 insertions(+), 10 deletions(-) create mode 100644 clang/test/SemaTemplate/PR91677.cpp diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h index 3bfda09d5f80f..b4d31cbbf0c7c 100644 --- a/clang/lib/Sema/TreeTransform.h +++ b/clang/lib/Sema/TreeTransform.h @@ -4568,6 +4568,24 @@ TreeTransform::TransformTemplateName(CXXScopeSpec &SS, if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) { TemplateDecl *Template = QTN->getUnderlyingTemplate().getAsTemplateDecl(); assert(Template && "qualified template name must refer to a template"); +if (QTN->getQualifier()) { + CXXScopeSpec QualifierSS; + QualifierSS.MakeTrivial(getSema().getASTContext(), QTN->getQualifier(), + NameLoc); + NestedNameSpecifierLoc QualifierLoc = + QualifierSS.getWithLocInContext(getSema().getASTContext()); + NestedNameSpecifierLoc TransformedQualifierLoc = + getDerived().TransformNestedNameSpecifierLoc(QualifierLoc); + if (!TransformedQualifierLoc) +return Name; + if (!getDerived().AlwaysRebuild() && + QualifierLoc != TransformedQualifierLoc) { +SS.Adopt(TransformedQualifierLoc); +return getDerived().RebuildTemplateName( +SS, SourceLocation(), *Template->getIdentifier(), NameLoc, +ObjectType, FirstQualifierInScope, /*AllowInjectedClassName=*/true); + } +} TemplateDecl *TransTemplate = cast_or_null(getDerived().TransformDecl(NameLoc, diff --git a/clang/test/SemaCXX/many-template-parameter-lists.cpp b/clang/test/SemaCXX/many-template-parameter-lists.cpp index f98005c7e6fb5..b5d954986dd4f 100644 --- a/clang/test/SemaCXX/many-template-parameter-lists.cpp +++ b/clang/test/SemaCXX/many-template-parameter-lists.cpp @@ -5,7 +5,7 @@ template struct X { template - struct A { // expected-note {{not-yet-instantiated member is declared here}} + struct A { template struct B { template @@ -28,9 +28,9 @@ struct X { template template template - friend void A::template B::template C::template D::template E::operator+=(Z); // expected-warning {{not supported}} expected-error {{no member 'A' in 'X'; it has not yet been instantiated}} + friend void A::template B::template C::template D::template E::operator+=(Z); // expected-warning {{dependent nested name specifier 'A::B::C::D::template E::' for friend class declaration is not supported; turning off access control for 'X'}} }; void test() { - X::A::B::C::D::E() += 1.0; // expected-note {{in instantiation of template class 'X' requested here}} + X::A::B::C::D::E() += 1.0; } diff --git a/clang/test/SemaTemplate/PR91677.cpp b/clang/test/SemaTemplate/PR91677.cpp new file mode 100644 index 0..cc8db60a438ea --- /dev/null +++ b/clang/test/SemaTemplate/PR91677.cpp @@ -0,0 +1,14 @@ +// RUN: %clang_cc1 -verify -std=c++20 -fsyntax-only %s +// expected-no-diagnostics + +template struct t1 { + template + struct t2 {}; +}; + +template +t1::template t2 f1(); + +void f2() { + f1(); +} diff --git a/clang/test/SemaTemplate/instantiate-scope.cpp b/clang/test/SemaTemplate/instantiate-scope.cpp index 733105674b7a4..3a1708a695ceb 100644 --- a/clang/test/SemaTemplate/instantiate-scope.cpp +++ b/clang/test/SemaTemplate/instantiate-scope.cpp @@ -11,10 +11,10 @@ template using A = T; // These definitions are OK, X...> is equivalent to X // so this defines the member of the primary template. template -void X...>::f(int) {} // expected-error {{undeclared}} +void X...>::f(int) {} // expected-error {{use of undeclared identifier 'f'}} template -int X...>::n = 0; // expected-error {{undeclared}} +int X...>::n = 0; // expected-error {{use of undeclared identifier 'f'}} struct Y {}; void f(Y); @@ -25,6 +25,6 @@ void g() { // Error, substitution fails; this should not be treated as a SFINAE-able // condition, so we don't select X::f(...). - X().f(0); // expected-note {{instantiation of}} - X::n = 1; // expected-note {{instantiation of}} + X().f(0); // expected-note {{in instantiation of member function 'X::f' requested here}} + X::n = 1; // expected-note {{in instantiation of static data member 'X::n' requested here}} } diff --git a/clang/test/SemaTemplate/typename-specifier-3.cpp b/clang/test/SemaTemplate/typename-specifi
[clang] [clang][driver] Enable '-flto' on bare-metal (PR #94738)
https://github.com/walkerkd created https://github.com/llvm/llvm-project/pull/94738 Pass the linker LTO options enabled by the clang '-flto' command line options when targeting bare-metal. >From 8150a6529be5a3be65e49d5440c576d856d404d5 Mon Sep 17 00:00:00 2001 From: Keith Walker Date: Thu, 6 Jun 2024 15:14:49 +0100 Subject: [PATCH] [clang][driver] Enable '-flto' on bare-metal Pass the linker LTO options enabled by the clang '-flto' command line options when targeting bare-metal. --- clang/lib/Driver/ToolChains/BareMetal.cpp | 15 +++ clang/test/Driver/baremetal-ld.c | 6 ++ 2 files changed, 21 insertions(+) create mode 100644 clang/test/Driver/baremetal-ld.c diff --git a/clang/lib/Driver/ToolChains/BareMetal.cpp b/clang/lib/Driver/ToolChains/BareMetal.cpp index 221c481579240..d1bd7821414ec 100644 --- a/clang/lib/Driver/ToolChains/BareMetal.cpp +++ b/clang/lib/Driver/ToolChains/BareMetal.cpp @@ -429,6 +429,7 @@ void baremetal::Linker::ConstructJob(Compilation &C, const JobAction &JA, ArgStringList CmdArgs; auto &TC = static_cast(getToolChain()); + const Driver &D = getToolChain().getDriver(); const llvm::Triple::ArchType Arch = TC.getArch(); const llvm::Triple &Triple = getToolChain().getEffectiveTriple(); @@ -466,6 +467,20 @@ void baremetal::Linker::ConstructJob(Compilation &C, const JobAction &JA, TC.AddLinkRuntimeLib(Args, CmdArgs); } + + if (D.isUsingLTO()) { +assert(!Inputs.empty() && "Must have at least one input."); +// Find the first filename InputInfo object. +auto Input = llvm::find_if( +Inputs, [](const InputInfo &II) -> bool { return II.isFilename(); }); +if (Input == Inputs.end()) + // For a very rare case, all of the inputs to the linker are + // InputArg. If that happens, just use the first InputInfo. + Input = Inputs.begin(); + +addLTOOptions(TC, Args, CmdArgs, Output, *Input, + D.getLTOMode() == LTOK_Thin); + } if (TC.getTriple().isRISCV()) CmdArgs.push_back("-X"); diff --git a/clang/test/Driver/baremetal-ld.c b/clang/test/Driver/baremetal-ld.c new file mode 100644 index 0..ec61b42b6f487 --- /dev/null +++ b/clang/test/Driver/baremetal-ld.c @@ -0,0 +1,6 @@ +// RUN: %clang -### --target=armv7-unknown-none-eabi -mcpu=cortex-m4 --sysroot= -fuse-ld=ld %s 2>&1 | FileCheck --check-prefix=NOLTO %s +// NOLTO: {{".*ld.*"}} {{.*}} +// NOLTO-NOT: "-plugin-opt=mcpu" + +// RUN: %clang -### --target=armv7-unknown-none-eabi -mcpu=cortex-m4 --sysroot= -fuse-ld=ld -flto -O3 %s 2>&1 | FileCheck --check-prefix=LTO %s +// LTO: {{".*ld.*"}} {{.*}} "-plugin-opt=mcpu=cortex-m4" "-plugin-opt=O3" ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][driver] Enable '-flto' on bare-metal (PR #94738)
llvmbot wrote: @llvm/pr-subscribers-clang Author: None (walkerkd) Changes Pass the linker LTO options enabled by the clang '-flto' command line options when targeting bare-metal. --- Full diff: https://github.com/llvm/llvm-project/pull/94738.diff 2 Files Affected: - (modified) clang/lib/Driver/ToolChains/BareMetal.cpp (+15) - (added) clang/test/Driver/baremetal-ld.c (+6) ``diff diff --git a/clang/lib/Driver/ToolChains/BareMetal.cpp b/clang/lib/Driver/ToolChains/BareMetal.cpp index 221c481579240..d1bd7821414ec 100644 --- a/clang/lib/Driver/ToolChains/BareMetal.cpp +++ b/clang/lib/Driver/ToolChains/BareMetal.cpp @@ -429,6 +429,7 @@ void baremetal::Linker::ConstructJob(Compilation &C, const JobAction &JA, ArgStringList CmdArgs; auto &TC = static_cast(getToolChain()); + const Driver &D = getToolChain().getDriver(); const llvm::Triple::ArchType Arch = TC.getArch(); const llvm::Triple &Triple = getToolChain().getEffectiveTriple(); @@ -466,6 +467,20 @@ void baremetal::Linker::ConstructJob(Compilation &C, const JobAction &JA, TC.AddLinkRuntimeLib(Args, CmdArgs); } + + if (D.isUsingLTO()) { +assert(!Inputs.empty() && "Must have at least one input."); +// Find the first filename InputInfo object. +auto Input = llvm::find_if( +Inputs, [](const InputInfo &II) -> bool { return II.isFilename(); }); +if (Input == Inputs.end()) + // For a very rare case, all of the inputs to the linker are + // InputArg. If that happens, just use the first InputInfo. + Input = Inputs.begin(); + +addLTOOptions(TC, Args, CmdArgs, Output, *Input, + D.getLTOMode() == LTOK_Thin); + } if (TC.getTriple().isRISCV()) CmdArgs.push_back("-X"); diff --git a/clang/test/Driver/baremetal-ld.c b/clang/test/Driver/baremetal-ld.c new file mode 100644 index 0..ec61b42b6f487 --- /dev/null +++ b/clang/test/Driver/baremetal-ld.c @@ -0,0 +1,6 @@ +// RUN: %clang -### --target=armv7-unknown-none-eabi -mcpu=cortex-m4 --sysroot= -fuse-ld=ld %s 2>&1 | FileCheck --check-prefix=NOLTO %s +// NOLTO: {{".*ld.*"}} {{.*}} +// NOLTO-NOT: "-plugin-opt=mcpu" + +// RUN: %clang -### --target=armv7-unknown-none-eabi -mcpu=cortex-m4 --sysroot= -fuse-ld=ld -flto -O3 %s 2>&1 | FileCheck --check-prefix=LTO %s +// LTO: {{".*ld.*"}} {{.*}} "-plugin-opt=mcpu=cortex-m4" "-plugin-opt=O3" `` https://github.com/llvm/llvm-project/pull/94738 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][driver] Enable '-flto' on bare-metal (PR #94738)
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 ac404632f991fc6e7dc75ef553a99676ba8002ce 8150a6529be5a3be65e49d5440c576d856d404d5 -- clang/test/Driver/baremetal-ld.c clang/lib/Driver/ToolChains/BareMetal.cpp `` View the diff from clang-format here. ``diff diff --git a/clang/lib/Driver/ToolChains/BareMetal.cpp b/clang/lib/Driver/ToolChains/BareMetal.cpp index d1bd782141..dd365e62e0 100644 --- a/clang/lib/Driver/ToolChains/BareMetal.cpp +++ b/clang/lib/Driver/ToolChains/BareMetal.cpp @@ -467,7 +467,6 @@ void baremetal::Linker::ConstructJob(Compilation &C, const JobAction &JA, TC.AddLinkRuntimeLib(Args, CmdArgs); } - if (D.isUsingLTO()) { assert(!Inputs.empty() && "Must have at least one input."); // Find the first filename InputInfo object. `` https://github.com/llvm/llvm-project/pull/94738 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Support [[guarded_by(mutex)]] attribute inside C struct (PR #94216)
https://github.com/pdherbemont updated https://github.com/llvm/llvm-project/pull/94216 >From 55eb00bafdd19817a2c31af6178a301582f5523b Mon Sep 17 00:00:00 2001 From: Pierre d'Herbemont Date: Wed, 29 May 2024 11:11:03 +0200 Subject: [PATCH] Support [[guarded_by(mutex)]] and friends attributes inside C struct Today, it's only supported inside C++ classes or top level C/C++ declaration. I mostly copied and adapted over the code from the [[counted_by(value)]] lookup. I had to change ast-dump-color.cpp because of the way the expression marking now marks the mutex as "used" instead of "referenced". If I change the expression parsing to use `ExpressionEvaluationContext::Unevaluated` then I get the mutex as "referenced" but I lose the C++ check for "invalid use of non-static data member". Then I enabled the use of the experimental late parsing used by [[counted_by]] because that will enable the adoption of attributes without restructuring the data layout as requested by @rapidsna. --- clang/docs/ReleaseNotes.rst | 4 + clang/docs/ThreadSafetyAnalysis.rst | 6 - clang/include/clang/Basic/Attr.td | 8 +- clang/include/clang/Parse/Parser.h| 14 +++ clang/include/clang/Sema/Sema.h | 7 +- clang/lib/Parse/ParseDecl.cpp | 118 +- clang/lib/Sema/SemaExpr.cpp | 4 +- clang/test/AST/ast-dump-color.cpp | 4 +- clang/test/Sema/warn-thread-safety-analysis.c | 43 ++- .../SemaCXX/warn-thread-safety-parsing.cpp| 6 +- 10 files changed, 189 insertions(+), 25 deletions(-) diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index 99580c0d28a4f..c6bcf25d95dab 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -451,6 +451,10 @@ Attribute Changes in Clang size_t count; }; +- The ``guarded_by``, ``pt_guarded_by``, ``acquired_after``, ``acquired_before`` + attributes now support referencing struct members in C. The arguments are also + now late parsed when ``-fexperimental-late-parse-attributes`` is passed like + for ``counted_by``. Improvements to Clang's diagnostics --- diff --git a/clang/docs/ThreadSafetyAnalysis.rst b/clang/docs/ThreadSafetyAnalysis.rst index dcde0c706c704..6eefa306e3c89 100644 --- a/clang/docs/ThreadSafetyAnalysis.rst +++ b/clang/docs/ThreadSafetyAnalysis.rst @@ -764,12 +764,6 @@ doesn't know that munl.mu == mutex. The SCOPED_CAPABILITY attribute handles aliasing for MutexLocker, but does so only for that particular pattern. -ACQUIRED_BEFORE(...) and ACQUIRED_AFTER(...) are currently unimplemented. -- - -To be fixed in a future update. - - .. _mutexheader: mutex.h diff --git a/clang/include/clang/Basic/Attr.td b/clang/include/clang/Basic/Attr.td index c6f08860f203a..cb424965732b3 100644 --- a/clang/include/clang/Basic/Attr.td +++ b/clang/include/clang/Basic/Attr.td @@ -3633,7 +3633,7 @@ def NoThreadSafetyAnalysis : InheritableAttr { def GuardedBy : InheritableAttr { let Spellings = [GNU<"guarded_by">]; let Args = [ExprArgument<"Arg">]; - let LateParsed = LateAttrParseStandard; + let LateParsed = LateAttrParseExperimentalExt; let TemplateDependent = 1; let ParseArgumentsAsUnevaluated = 1; let InheritEvenIfAlreadyPresent = 1; @@ -3644,7 +3644,7 @@ def GuardedBy : InheritableAttr { def PtGuardedBy : InheritableAttr { let Spellings = [GNU<"pt_guarded_by">]; let Args = [ExprArgument<"Arg">]; - let LateParsed = LateAttrParseStandard; + let LateParsed = LateAttrParseExperimentalExt; let TemplateDependent = 1; let ParseArgumentsAsUnevaluated = 1; let InheritEvenIfAlreadyPresent = 1; @@ -3655,7 +3655,7 @@ def PtGuardedBy : InheritableAttr { def AcquiredAfter : InheritableAttr { let Spellings = [GNU<"acquired_after">]; let Args = [VariadicExprArgument<"Args">]; - let LateParsed = LateAttrParseStandard; + let LateParsed = LateAttrParseExperimentalExt; let TemplateDependent = 1; let ParseArgumentsAsUnevaluated = 1; let InheritEvenIfAlreadyPresent = 1; @@ -3666,7 +3666,7 @@ def AcquiredAfter : InheritableAttr { def AcquiredBefore : InheritableAttr { let Spellings = [GNU<"acquired_before">]; let Args = [VariadicExprArgument<"Args">]; - let LateParsed = LateAttrParseStandard; + let LateParsed = LateAttrParseExperimentalExt; let TemplateDependent = 1; let ParseArgumentsAsUnevaluated = 1; let InheritEvenIfAlreadyPresent = 1; diff --git a/clang/include/clang/Parse/Parser.h b/clang/include/clang/Parse/Parser.h index d054b8cf0d240..9e11078382756 100644 --- a/clang/include/clang/Parse/Parser.h +++ b/clang/include/clang/Parse/Parser.h @@ -3128,6 +3128,20 @@ class Parser : public CodeCompletionHandler { IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr
[clang] Support [[guarded_by(mutex)]] attribute inside C struct (PR #94216)
@@ -1,4 +1,4 @@ -// RUN: %clang_cc1 -fsyntax-only -verify -Wthread-safety -Wthread-safety-beta %s +// RUN: %clang_cc1 -fsyntax-only -verify -Wthread-safety -Wthread-safety-beta -fexperimental-late-parse-attributes %s pdherbemont wrote: done! https://github.com/llvm/llvm-project/pull/94216 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Support [[guarded_by(mutex)]] attribute inside C struct (PR #94216)
@@ -3330,6 +3340,112 @@ void Parser::DistributeCLateParsedAttrs(Decl *Dcl, } } +/// GuardedBy attributes (e.g., guarded_by): +/// AttrName '(' expression ')' +void Parser::ParseGuardedByAttribute( +IdentifierInfo &AttrName, SourceLocation AttrNameLoc, +ParsedAttributes &Attrs, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, +SourceLocation *EndLoc, ParsedAttr::Form Form) { + assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('"); + + BalancedDelimiterTracker Parens(*this, tok::l_paren); + Parens.consumeOpen(); + + if (Tok.is(tok::r_paren)) { +Diag(Tok.getLocation(), diag::err_argument_required_after_attribute); pdherbemont wrote: done! https://github.com/llvm/llvm-project/pull/94216 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Support [[guarded_by(mutex)]] attribute inside C struct (PR #94216)
@@ -29,6 +29,13 @@ struct LOCKABLE Mutex {}; struct Foo { struct Mutex *mu_; + int a_value GUARDED_BY(mu_); pdherbemont wrote: done! https://github.com/llvm/llvm-project/pull/94216 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Support [[guarded_by(mutex)]] attribute inside C struct (PR #94216)
@@ -3330,6 +3340,112 @@ void Parser::DistributeCLateParsedAttrs(Decl *Dcl, } } +/// GuardedBy attributes (e.g., guarded_by): +/// AttrName '(' expression ')' +void Parser::ParseGuardedByAttribute( +IdentifierInfo &AttrName, SourceLocation AttrNameLoc, +ParsedAttributes &Attrs, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, +SourceLocation *EndLoc, ParsedAttr::Form Form) { + assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('"); + + BalancedDelimiterTracker Parens(*this, tok::l_paren); + Parens.consumeOpen(); + + if (Tok.is(tok::r_paren)) { +Diag(Tok.getLocation(), diag::err_argument_required_after_attribute); +Parens.consumeClose(); +return; + } + + ArgsVector ArgExprs; + // Don't evaluate argument when the attribute is ignored. + using ExpressionKind = + Sema::ExpressionEvaluationContextRecord::ExpressionKind; + EnterExpressionEvaluationContext EC( + Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, nullptr, + ExpressionKind::EK_AttrArgument); + + ExprResult ArgExpr( + Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression())); + + if (ArgExpr.isInvalid()) { +Parens.skipToEnd(); +return; + } + + ArgExprs.push_back(ArgExpr.get()); + + auto RParens = Tok.getLocation(); + auto &AL = + *Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, RParens), ScopeName, +ScopeLoc, ArgExprs.data(), ArgExprs.size(), Form); + + if (EndLoc) +*EndLoc = RParens; + + if (!Tok.is(tok::r_paren)) { +Diag(Tok.getLocation(), diag::err_attribute_wrong_number_arguments) +<< AL << 1; +Parens.skipToEnd(); +return; + } + + Parens.consumeClose(); +} + +/// Acquired attributes (e.g., acquired_before, acquired_after): +/// AttrName '(' expression-list ')' +void Parser::ParseAcquiredAttribute( +IdentifierInfo &AttrName, SourceLocation AttrNameLoc, +ParsedAttributes &Attrs, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, +SourceLocation *EndLoc, ParsedAttr::Form Form) { + assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('"); + + BalancedDelimiterTracker Parens(*this, tok::l_paren); + Parens.consumeOpen(); + + if (Tok.is(tok::r_paren)) { +Diag(Tok.getLocation(), diag::err_argument_required_after_attribute); +Parens.consumeClose(); pdherbemont wrote: done! https://github.com/llvm/llvm-project/pull/94216 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Support [[guarded_by(mutex)]] attribute inside C struct (PR #94216)
@@ -3330,6 +3340,112 @@ void Parser::DistributeCLateParsedAttrs(Decl *Dcl, } } +/// GuardedBy attributes (e.g., guarded_by): +/// AttrName '(' expression ')' +void Parser::ParseGuardedByAttribute( +IdentifierInfo &AttrName, SourceLocation AttrNameLoc, +ParsedAttributes &Attrs, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, +SourceLocation *EndLoc, ParsedAttr::Form Form) { + assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('"); + + BalancedDelimiterTracker Parens(*this, tok::l_paren); + Parens.consumeOpen(); + + if (Tok.is(tok::r_paren)) { +Diag(Tok.getLocation(), diag::err_argument_required_after_attribute); +Parens.consumeClose(); +return; + } + + ArgsVector ArgExprs; + // Don't evaluate argument when the attribute is ignored. + using ExpressionKind = + Sema::ExpressionEvaluationContextRecord::ExpressionKind; + EnterExpressionEvaluationContext EC( + Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, nullptr, + ExpressionKind::EK_AttrArgument); + + ExprResult ArgExpr( + Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression())); + + if (ArgExpr.isInvalid()) { +Parens.skipToEnd(); pdherbemont wrote: done! https://github.com/llvm/llvm-project/pull/94216 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Support [[guarded_by(mutex)]] attribute inside C struct (PR #94216)
@@ -3330,6 +3340,112 @@ void Parser::DistributeCLateParsedAttrs(Decl *Dcl, } } +/// GuardedBy attributes (e.g., guarded_by): +/// AttrName '(' expression ')' +void Parser::ParseGuardedByAttribute( +IdentifierInfo &AttrName, SourceLocation AttrNameLoc, +ParsedAttributes &Attrs, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, +SourceLocation *EndLoc, ParsedAttr::Form Form) { + assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('"); + + BalancedDelimiterTracker Parens(*this, tok::l_paren); + Parens.consumeOpen(); + + if (Tok.is(tok::r_paren)) { +Diag(Tok.getLocation(), diag::err_argument_required_after_attribute); +Parens.consumeClose(); +return; + } + + ArgsVector ArgExprs; + // Don't evaluate argument when the attribute is ignored. + using ExpressionKind = + Sema::ExpressionEvaluationContextRecord::ExpressionKind; + EnterExpressionEvaluationContext EC( + Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, nullptr, + ExpressionKind::EK_AttrArgument); + + ExprResult ArgExpr( + Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression())); + + if (ArgExpr.isInvalid()) { +Parens.skipToEnd(); +return; + } + + ArgExprs.push_back(ArgExpr.get()); + + auto RParens = Tok.getLocation(); + auto &AL = + *Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, RParens), ScopeName, +ScopeLoc, ArgExprs.data(), ArgExprs.size(), Form); + + if (EndLoc) +*EndLoc = RParens; + + if (!Tok.is(tok::r_paren)) { +Diag(Tok.getLocation(), diag::err_attribute_wrong_number_arguments) +<< AL << 1; +Parens.skipToEnd(); +return; + } + + Parens.consumeClose(); +} + +/// Acquired attributes (e.g., acquired_before, acquired_after): +/// AttrName '(' expression-list ')' +void Parser::ParseAcquiredAttribute( +IdentifierInfo &AttrName, SourceLocation AttrNameLoc, +ParsedAttributes &Attrs, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, +SourceLocation *EndLoc, ParsedAttr::Form Form) { + assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('"); + + BalancedDelimiterTracker Parens(*this, tok::l_paren); + Parens.consumeOpen(); + + if (Tok.is(tok::r_paren)) { +Diag(Tok.getLocation(), diag::err_argument_required_after_attribute); +Parens.consumeClose(); +return; + } + + auto ArgStart = Tok.getLocation(); + + ArgsVector ArgExprs; + + do { + +// Don't evaluate argument when the attribute is ignored. +using ExpressionKind = +Sema::ExpressionEvaluationContextRecord::ExpressionKind; +EnterExpressionEvaluationContext EC( +Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, +nullptr, ExpressionKind::EK_AttrArgument); + +ExprResult ArgExpr( +Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression())); + +if (ArgExpr.isInvalid()) { + Parens.skipToEnd(); pdherbemont wrote: done! https://github.com/llvm/llvm-project/pull/94216 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Support [[guarded_by(mutex)]] attribute inside C struct (PR #94216)
pdherbemont wrote: > @pdherbemont thanks for working on this. It looks pretty good and its great > to see the late parsing support I added gaining new users. I just have some > nits about missing test cases. I should have added all the requested test cases. Not sure it's the way you wanted it, so let me know if you want any change! https://github.com/llvm/llvm-project/pull/94216 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][analyzer] Improved PointerSubChecker (PR #93676)
=?utf-8?q?Bal=C3=A1zs_K=C3=A9ri?= , =?utf-8?q?Bal=C3=A1zs_K=C3=A9ri?= , =?utf-8?q?Bal=C3=A1zs_K=C3=A9ri?= Message-ID: In-Reply-To: @@ -53,10 +62,10 @@ void f4(void) { int (*p)[m] = a; // p == &a[0] p += 1; // p == &a[1] - // FIXME: This warning is not needed + // FIXME: This is a known problem with -Wpointer-arith steakhal wrote: Please put the issue link here and to the other place. https://github.com/llvm/llvm-project/pull/93676 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][analyzer] Improved PointerSubChecker (PR #93676)
=?utf-8?q?Bal=C3=A1zs_K=C3=A9ri?= , =?utf-8?q?Bal=C3=A1zs_K=C3=A9ri?= , =?utf-8?q?Bal=C3=A1zs_K=C3=A9ri?= Message-ID: In-Reply-To: https://github.com/steakhal approved this pull request. LGTM, thanks. Minor nits. https://github.com/llvm/llvm-project/pull/93676 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][analyzer] Improved PointerSubChecker (PR #93676)
=?utf-8?q?Balázs_Kéri?= , =?utf-8?q?Balázs_Kéri?= , =?utf-8?q?Balázs_Kéri?= Message-ID: In-Reply-To: https://github.com/steakhal edited https://github.com/llvm/llvm-project/pull/93676 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][driver] Enable '-flto' on bare-metal (PR #94738)
https://github.com/walkerkd updated https://github.com/llvm/llvm-project/pull/94738 >From 8150a6529be5a3be65e49d5440c576d856d404d5 Mon Sep 17 00:00:00 2001 From: Keith Walker Date: Thu, 6 Jun 2024 15:14:49 +0100 Subject: [PATCH 1/2] [clang][driver] Enable '-flto' on bare-metal Pass the linker LTO options enabled by the clang '-flto' command line options when targeting bare-metal. --- clang/lib/Driver/ToolChains/BareMetal.cpp | 15 +++ clang/test/Driver/baremetal-ld.c | 6 ++ 2 files changed, 21 insertions(+) create mode 100644 clang/test/Driver/baremetal-ld.c diff --git a/clang/lib/Driver/ToolChains/BareMetal.cpp b/clang/lib/Driver/ToolChains/BareMetal.cpp index 221c481579240..d1bd7821414ec 100644 --- a/clang/lib/Driver/ToolChains/BareMetal.cpp +++ b/clang/lib/Driver/ToolChains/BareMetal.cpp @@ -429,6 +429,7 @@ void baremetal::Linker::ConstructJob(Compilation &C, const JobAction &JA, ArgStringList CmdArgs; auto &TC = static_cast(getToolChain()); + const Driver &D = getToolChain().getDriver(); const llvm::Triple::ArchType Arch = TC.getArch(); const llvm::Triple &Triple = getToolChain().getEffectiveTriple(); @@ -466,6 +467,20 @@ void baremetal::Linker::ConstructJob(Compilation &C, const JobAction &JA, TC.AddLinkRuntimeLib(Args, CmdArgs); } + + if (D.isUsingLTO()) { +assert(!Inputs.empty() && "Must have at least one input."); +// Find the first filename InputInfo object. +auto Input = llvm::find_if( +Inputs, [](const InputInfo &II) -> bool { return II.isFilename(); }); +if (Input == Inputs.end()) + // For a very rare case, all of the inputs to the linker are + // InputArg. If that happens, just use the first InputInfo. + Input = Inputs.begin(); + +addLTOOptions(TC, Args, CmdArgs, Output, *Input, + D.getLTOMode() == LTOK_Thin); + } if (TC.getTriple().isRISCV()) CmdArgs.push_back("-X"); diff --git a/clang/test/Driver/baremetal-ld.c b/clang/test/Driver/baremetal-ld.c new file mode 100644 index 0..ec61b42b6f487 --- /dev/null +++ b/clang/test/Driver/baremetal-ld.c @@ -0,0 +1,6 @@ +// RUN: %clang -### --target=armv7-unknown-none-eabi -mcpu=cortex-m4 --sysroot= -fuse-ld=ld %s 2>&1 | FileCheck --check-prefix=NOLTO %s +// NOLTO: {{".*ld.*"}} {{.*}} +// NOLTO-NOT: "-plugin-opt=mcpu" + +// RUN: %clang -### --target=armv7-unknown-none-eabi -mcpu=cortex-m4 --sysroot= -fuse-ld=ld -flto -O3 %s 2>&1 | FileCheck --check-prefix=LTO %s +// LTO: {{".*ld.*"}} {{.*}} "-plugin-opt=mcpu=cortex-m4" "-plugin-opt=O3" >From ad00328a73cd25c40e3c6d84a61e6db49ec22930 Mon Sep 17 00:00:00 2001 From: Keith Walker Date: Fri, 7 Jun 2024 10:25:08 +0100 Subject: [PATCH 2/2] [clang][driver] Remove blank line (NFC) --- clang/lib/Driver/ToolChains/BareMetal.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/clang/lib/Driver/ToolChains/BareMetal.cpp b/clang/lib/Driver/ToolChains/BareMetal.cpp index d1bd7821414ec..dd365e62e084e 100644 --- a/clang/lib/Driver/ToolChains/BareMetal.cpp +++ b/clang/lib/Driver/ToolChains/BareMetal.cpp @@ -467,7 +467,6 @@ void baremetal::Linker::ConstructJob(Compilation &C, const JobAction &JA, TC.AddLinkRuntimeLib(Args, CmdArgs); } - if (D.isUsingLTO()) { assert(!Inputs.empty() && "Must have at least one input."); // Find the first filename InputInfo object. ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [CMake][Release] Use the TXZ cpack generator for binaries (PR #90138)
https://github.com/tstellar closed https://github.com/llvm/llvm-project/pull/90138 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 5d6acf8 - [clang][Interp][NFC] Properly assign block pointer Pointee
Author: Timm Bäder Date: 2024-06-07T11:48:44+02:00 New Revision: 5d6acf8196a44225991ab2fb6dfc9cc72296b348 URL: https://github.com/llvm/llvm-project/commit/5d6acf8196a44225991ab2fb6dfc9cc72296b348 DIFF: https://github.com/llvm/llvm-project/commit/5d6acf8196a44225991ab2fb6dfc9cc72296b348.diff LOG: [clang][Interp][NFC] Properly assign block pointer Pointee Added: Modified: clang/lib/AST/Interp/Pointer.cpp Removed: diff --git a/clang/lib/AST/Interp/Pointer.cpp b/clang/lib/AST/Interp/Pointer.cpp index e3d21f93f114e..85857d4ee1c88 100644 --- a/clang/lib/AST/Interp/Pointer.cpp +++ b/clang/lib/AST/Interp/Pointer.cpp @@ -80,6 +80,7 @@ void Pointer::operator=(const Pointer &P) { if (P.isBlockPointer()) { PointeeStorage.BS = P.PointeeStorage.BS; +PointeeStorage.BS.Pointee = P.PointeeStorage.BS.Pointee; if (PointeeStorage.BS.Pointee) PointeeStorage.BS.Pointee->addPointer(this); @@ -107,6 +108,7 @@ void Pointer::operator=(Pointer &&P) { if (P.isBlockPointer()) { PointeeStorage.BS = P.PointeeStorage.BS; +PointeeStorage.BS.Pointee = P.PointeeStorage.BS.Pointee; if (PointeeStorage.BS.Pointee) PointeeStorage.BS.Pointee->addPointer(this); ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 3a31eae - [clang][Interp] Fix refers_to_enclosing_variable_or_capture DREs
Author: Timm Bäder Date: 2024-06-07T11:48:44+02:00 New Revision: 3a31eaeac8482fa5e242ee00cd4e77b203db539e URL: https://github.com/llvm/llvm-project/commit/3a31eaeac8482fa5e242ee00cd4e77b203db539e DIFF: https://github.com/llvm/llvm-project/commit/3a31eaeac8482fa5e242ee00cd4e77b203db539e.diff LOG: [clang][Interp] Fix refers_to_enclosing_variable_or_capture DREs They do not count into lambda captures, so visit them lazily. Added: Modified: clang/lib/AST/Interp/ByteCodeExprGen.cpp clang/test/AST/Interp/lambda.cpp Removed: diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp b/clang/lib/AST/Interp/ByteCodeExprGen.cpp index 1d0c36d0bf09f..8dc71b2527f3b 100644 --- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp +++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp @@ -3894,6 +3894,13 @@ bool ByteCodeExprGen::visitDeclRef(const ValueDecl *D, const Expr *E) { if (IsPtr) return this->emitGetThisFieldPtr(Offset, E); return this->emitGetPtrThisField(Offset, E); + } else if (const auto *DRE = dyn_cast(E); + DRE && DRE->refersToEnclosingVariableOrCapture() && + isa(D)) { +if (!this->visitVarDecl(cast(D))) + return false; +// Retry. +return this->visitDeclRef(D, E); } // Try to lazily visit (or emit dummy pointers for) declarations diff --git a/clang/test/AST/Interp/lambda.cpp b/clang/test/AST/Interp/lambda.cpp index 77e035ce25470..71e7077550b28 100644 --- a/clang/test/AST/Interp/lambda.cpp +++ b/clang/test/AST/Interp/lambda.cpp @@ -264,3 +264,6 @@ namespace CaptureDefaults { }; static_assert(f2() == 3, ""); } + +constexpr auto t4 = ([x=42]() consteval { return x; }()); +static_assert(t4 == 42, ""); ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 1a52392 - [ARM] r11 is reserved when using -mframe-chain=aapcs (#86951)
Author: Oliver Stannard Date: 2024-06-07T10:58:10+01:00 New Revision: 1a5239251ead73ee57f4e2f7fc93433ac7cf18b1 URL: https://github.com/llvm/llvm-project/commit/1a5239251ead73ee57f4e2f7fc93433ac7cf18b1 DIFF: https://github.com/llvm/llvm-project/commit/1a5239251ead73ee57f4e2f7fc93433ac7cf18b1.diff LOG: [ARM] r11 is reserved when using -mframe-chain=aapcs (#86951) When using the -mframe-chain=aapcs or -mframe-chain=aapcs-leaf options, we cannot use r11 as an allocatable register, even if -fomit-frame-pointer is also used. This is so that r11 will always point to a valid frame record, even if we don't create one in every function. Added: Modified: clang/include/clang/Basic/CodeGenOptions.def clang/include/clang/Basic/CodeGenOptions.h clang/include/clang/Driver/Options.td clang/lib/CodeGen/CGCall.cpp clang/lib/CodeGen/CodeGenModule.cpp clang/lib/Driver/ToolChains/Arch/ARM.cpp clang/lib/Driver/ToolChains/Clang.cpp clang/lib/Driver/ToolChains/CommonArgs.cpp llvm/docs/LangRef.rst llvm/include/llvm/Support/CodeGen.h llvm/include/llvm/Target/TargetOptions.h llvm/lib/CodeGen/CommandFlags.cpp llvm/lib/CodeGen/TargetOptionsImpl.cpp llvm/lib/IR/Function.cpp llvm/lib/IR/Verifier.cpp llvm/lib/Target/ARM/ARMBaseRegisterInfo.cpp llvm/lib/Target/ARM/ARMFeatures.td llvm/lib/Target/ARM/ARMFrameLowering.cpp llvm/lib/Target/ARM/ARMFrameLowering.h llvm/test/CodeGen/ARM/frame-chain-reserved-fp.ll llvm/test/CodeGen/ARM/frame-chain.ll llvm/test/CodeGen/Thumb/frame-access.ll llvm/test/CodeGen/Thumb/frame-chain-reserved-fp.ll llvm/test/CodeGen/Thumb/frame-chain.ll Removed: diff --git a/clang/include/clang/Basic/CodeGenOptions.def b/clang/include/clang/Basic/CodeGenOptions.def index 07b0ca1691a67..7ffc40a00504f 100644 --- a/clang/include/clang/Basic/CodeGenOptions.def +++ b/clang/include/clang/Basic/CodeGenOptions.def @@ -61,7 +61,7 @@ CODEGENOPT(SeparateNamedSections, 1, 0) ///< Set for -fseparate-named-sections. CODEGENOPT(EnableAIXExtendedAltivecABI, 1, 0) ///< Set for -mabi=vec-extabi. Enables the extended Altivec ABI on AIX. CODEGENOPT(XCOFFReadOnlyPointers, 1, 0) ///< Set for -mxcoff-roptr. CODEGENOPT(AllTocData, 1, 0) ///< AIX -mtocdata -ENUM_CODEGENOPT(FramePointer, FramePointerKind, 2, FramePointerKind::None) /// frame-pointer: all,non-leaf,none +ENUM_CODEGENOPT(FramePointer, FramePointerKind, 2, FramePointerKind::None) /// frame-pointer: all,non-leaf,reserved,none CODEGENOPT(ClearASTBeforeBackend , 1, 0) ///< Free the AST before running backend code generation. Only works with -disable-free. CODEGENOPT(DisableFree , 1, 0) ///< Don't free memory. diff --git a/clang/include/clang/Basic/CodeGenOptions.h b/clang/include/clang/Basic/CodeGenOptions.h index 9469a424045bb..00523a84d3895 100644 --- a/clang/include/clang/Basic/CodeGenOptions.h +++ b/clang/include/clang/Basic/CodeGenOptions.h @@ -127,15 +127,18 @@ class CodeGenOptions : public CodeGenOptionsBase { std::string BinutilsVersion; enum class FramePointerKind { -None,// Omit all frame pointers. -NonLeaf, // Keep non-leaf frame pointers. -All, // Keep all frame pointers. +None, // Omit all frame pointers. +Reserved, // Maintain valid frame pointer chain. +NonLeaf, // Keep non-leaf frame pointers. +All, // Keep all frame pointers. }; static StringRef getFramePointerKindName(FramePointerKind Kind) { switch (Kind) { case FramePointerKind::None: return "none"; +case FramePointerKind::Reserved: + return "reserved"; case FramePointerKind::NonLeaf: return "non-leaf"; case FramePointerKind::All: diff --git a/clang/include/clang/Driver/Options.td b/clang/include/clang/Driver/Options.td index f04c220d6e1db..d44faa55c456f 100644 --- a/clang/include/clang/Driver/Options.td +++ b/clang/include/clang/Driver/Options.td @@ -7724,8 +7724,8 @@ def pic_is_pie : Flag<["-"], "pic-is-pie">, MarshallingInfoFlag>; def mframe_pointer_EQ : Joined<["-"], "mframe-pointer=">, - HelpText<"Specify which frame pointers to retain.">, Values<"all,non-leaf,none">, - NormalizedValuesScope<"CodeGenOptions::FramePointerKind">, NormalizedValues<["All", "NonLeaf", "None"]>, + HelpText<"Specify which frame pointers to retain.">, Values<"all,non-leaf,reserved,none">, + NormalizedValuesScope<"CodeGenOptions::FramePointerKind">, NormalizedValues<["All", "NonLeaf", "Reserved", "None"]>, MarshallingInfoEnum, "None">; diff --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp index 97449a5e51e73..65d82285b907b 100644 --- a/clang/lib/CodeGen/CGCall.cpp +++ b/clang/lib/CodeGen/CGCall.cpp @@ -1917,6 +1917,7 @@ static void getTrivialDefaultFunctionAttributes( case CodeGenOptions::FramePointerKind::None: // This is the default behavior.
[clang] [llvm] [ARM] r11 is reserved when using -mframe-chain=aapcs (PR #86951)
https://github.com/ostannard closed https://github.com/llvm/llvm-project/pull/86951 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Testing32 bit for https://github.com/llvm/llvm-project/pull/92083 (PR #94603)
DavidSpickett wrote: Ok, this new version passes `check-llvm` and `check-clang` (ignoring the pre-existing failure), using the exact config from [clang-armv8-quick](https://lab.llvm.org/buildbot/#/builders/245). https://github.com/llvm/llvm-project/pull/94603 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 917afa8 - [ARM] Add support for Cortex-R52+ (#94633)
Author: Jonathan Thackray Date: 2024-06-07T11:03:32+01:00 New Revision: 917afa883258757575ac6448e83a9233d7877333 URL: https://github.com/llvm/llvm-project/commit/917afa883258757575ac6448e83a9233d7877333 DIFF: https://github.com/llvm/llvm-project/commit/917afa883258757575ac6448e83a9233d7877333.diff LOG: [ARM] Add support for Cortex-R52+ (#94633) Cortex-R52+ is an Armv8-R AArch32 CPU. Technical Reference Manual for Cortex-R52+: https://developer.arm.com/documentation/102199/latest/ Added: llvm/test/MC/ARM/invalid-armv8r.s Modified: clang/docs/ReleaseNotes.rst clang/test/Misc/target-invalid-cpu-note.c llvm/docs/ReleaseNotes.rst llvm/include/llvm/TargetParser/ARMTargetParser.def llvm/lib/Target/ARM/ARMProcessors.td llvm/lib/Target/ARM/ARMSubtarget.cpp llvm/lib/TargetParser/Host.cpp llvm/test/CodeGen/ARM/build-attributes.ll llvm/test/CodeGen/ARM/cortexr52-misched-basic.ll llvm/test/CodeGen/ARM/lsr-scale-addr-mode.ll llvm/test/CodeGen/ARM/misched-fp-basic.ll llvm/test/CodeGen/ARM/misched-int-basic-thumb2.mir llvm/test/CodeGen/ARM/misched-int-basic.mir llvm/test/CodeGen/ARM/proc-resource-sched.ll llvm/test/CodeGen/ARM/single-issue-r52.mir llvm/test/CodeGen/ARM/useaa.ll llvm/test/MC/ARM/dfb-neg.s llvm/test/MC/ARM/dfb.s llvm/test/MC/ARM/thumb-hints.s llvm/test/MC/Disassembler/ARM/dfb-thumb.txt llvm/unittests/TargetParser/TargetParserTest.cpp Removed: diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index b9c9070fcb22f..cf1ba02cbc4b2 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -907,6 +907,7 @@ Arm and AArch64 Support * Arm Cortex-A520AE (cortex-a520ae). * Arm Cortex-A720AE (cortex-a720ae). * Arm Cortex-R82AE (cortex-r82ae). +* Arm Cortex-R52+ (cortex-r52plus). * Arm Neoverse-N3 (neoverse-n3). * Arm Neoverse-V3 (neoverse-v3). * Arm Neoverse-V3AE (neoverse-v3ae). diff --git a/clang/test/Misc/target-invalid-cpu-note.c b/clang/test/Misc/target-invalid-cpu-note.c index cb5b6752850c6..2439025609b9f 100644 --- a/clang/test/Misc/target-invalid-cpu-note.c +++ b/clang/test/Misc/target-invalid-cpu-note.c @@ -1,7 +1,7 @@ // Use CHECK-NEXT instead of multiple CHECK-SAME to ensure we will fail if there is anything extra in the output. // RUN: not %clang_cc1 -triple armv5--- -target-cpu not-a-cpu -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix ARM // ARM: error: unknown target CPU 'not-a-cpu' -// ARM-NEXT: note: valid target CPU values are: arm8, arm810, strongarm, strongarm110, strongarm1100, strongarm1110, arm7tdmi, arm7tdmi-s, arm710t, arm720t, arm9, arm9tdmi, arm920, arm920t, arm922t, arm940t, ep9312, arm10tdmi, arm1020t, arm9e, arm946e-s, arm966e-s, arm968e-s, arm10e, arm1020e, arm1022e, arm926ej-s, arm1136j-s, arm1136jf-s, mpcore, mpcorenovfp, arm1176jz-s, arm1176jzf-s, arm1156t2-s, arm1156t2f-s, cortex-m0, cortex-m0plus, cortex-m1, sc000, cortex-a5, cortex-a7, cortex-a8, cortex-a9, cortex-a12, cortex-a15, cortex-a17, krait, cortex-r4, cortex-r4f, cortex-r5, cortex-r7, cortex-r8, cortex-r52, sc300, cortex-m3, cortex-m4, cortex-m7, cortex-m23, cortex-m33, cortex-m35p, cortex-m55, cortex-m85, cortex-m52, cortex-a32, cortex-a35, cortex-a53, cortex-a55, cortex-a57, cortex-a72, cortex-a73, cortex-a75, cortex-a76, cortex-a76ae, cortex-a77, cortex-a78, cortex-a78ae, cortex-a78c, cortex-a710, cortex-x1, cortex-x1c, neoverse-n1, neoverse-n2, neoverse-v1, cyclone, exynos-m3, exynos-m4, exynos-m5, kryo, iwmmxt, xscale, swift{{$}} +// ARM-NEXT: note: valid target CPU values are: arm8, arm810, strongarm, strongarm110, strongarm1100, strongarm1110, arm7tdmi, arm7tdmi-s, arm710t, arm720t, arm9, arm9tdmi, arm920, arm920t, arm922t, arm940t, ep9312, arm10tdmi, arm1020t, arm9e, arm946e-s, arm966e-s, arm968e-s, arm10e, arm1020e, arm1022e, arm926ej-s, arm1136j-s, arm1136jf-s, mpcore, mpcorenovfp, arm1176jz-s, arm1176jzf-s, arm1156t2-s, arm1156t2f-s, cortex-m0, cortex-m0plus, cortex-m1, sc000, cortex-a5, cortex-a7, cortex-a8, cortex-a9, cortex-a12, cortex-a15, cortex-a17, krait, cortex-r4, cortex-r4f, cortex-r5, cortex-r7, cortex-r8, cortex-r52, cortex-r52plus, sc300, cortex-m3, cortex-m4, cortex-m7, cortex-m23, cortex-m33, cortex-m35p, cortex-m55, cortex-m85, cortex-m52, cortex-a32, cortex-a35, cortex-a53, cortex-a55, cortex-a57, cortex-a72, cortex-a73, cortex-a75, cortex-a76, cortex-a76ae, cortex-a77, cortex-a78, cortex-a78ae, cortex-a78c, cortex-a710, cortex-x1, cortex-x1c, neoverse-n1, neoverse-n2, neoverse-v1, cyclone, exynos-m3, exynos-m4, exynos-m5, kryo, iwmmxt, xscale, swift{{$}} // RUN: not %clang_cc1 -triple arm64--- -target-cpu not-a-cpu -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix AARCH64 // AARCH64: error: unknown target CPU 'not-a-cpu' diff --git a/llvm/docs/ReleaseNotes.rst b/llvm/docs/ReleaseNotes.rs
[clang] [llvm] [ARM] Add support for Cortex-R52+ (PR #94633)
https://github.com/jthackray closed https://github.com/llvm/llvm-project/pull/94633 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] Enable LLDB tests in Linux pre-merge CI (PR #94208)
https://github.com/jthackray updated https://github.com/llvm/llvm-project/pull/94208 >From 5c757153a3f462d40663add6a9ae7caf42272913 Mon Sep 17 00:00:00 2001 From: Vlad Serebrennikov Date: Mon, 3 Jun 2024 13:33:36 +0300 Subject: [PATCH 1/8] Enable LLDB tests in pre-submit CI --- .ci/generate-buildkite-pipeline-premerge | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/.ci/generate-buildkite-pipeline-premerge b/.ci/generate-buildkite-pipeline-premerge index 033ab804b165e..a9972f235ff46 100755 --- a/.ci/generate-buildkite-pipeline-premerge +++ b/.ci/generate-buildkite-pipeline-premerge @@ -153,7 +153,6 @@ function exclude-linux() { for project in ${projects}; do case ${project} in cross-project-tests) ;; # tests failing -lldb);; # tests failing openmp) ;; # https://github.com/google/llvm-premerge-checks/issues/410 *) echo "${project}" @@ -170,7 +169,6 @@ function exclude-windows() { compiler-rt) ;; # tests taking too long openmp) ;; # TODO: having trouble with the Perl installation libc);; # no Windows support -lldb);; # tests failing bolt);; # tests are not supported yet *) echo "${project}" @@ -213,7 +211,7 @@ function check-targets() { echo "check-unwind" ;; lldb) - echo "check-all" # TODO: check-lldb may not include all the LLDB tests? + echo "check-lldb" # TODO: check-lldb may not include all the LLDB tests? ;; pstl) echo "check-all" >From 49e21f6b92623e280cfc49ac631b7481eb7a1229 Mon Sep 17 00:00:00 2001 From: Vlad Serebrennikov Date: Mon, 3 Jun 2024 13:34:18 +0300 Subject: [PATCH 2/8] Trigger Clang CI --- clang/examples/PrintFunctionNames/PrintFunctionNames.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clang/examples/PrintFunctionNames/PrintFunctionNames.cpp b/clang/examples/PrintFunctionNames/PrintFunctionNames.cpp index 6509a6440e12d..b2b785b87c25c 100644 --- a/clang/examples/PrintFunctionNames/PrintFunctionNames.cpp +++ b/clang/examples/PrintFunctionNames/PrintFunctionNames.cpp @@ -72,7 +72,7 @@ class PrintFunctionsConsumer : public ASTConsumer { *sema.LateParsedTemplateMap.find(FD)->second; sema.LateTemplateParser(sema.OpaqueParser, LPT); llvm::errs() << "late-parsed-decl: \"" << FD->getNameAsString() << "\"\n"; -} +} } }; >From c2d7679f76e971e5532c1cd91d99e7866f738960 Mon Sep 17 00:00:00 2001 From: Vlad Serebrennikov Date: Mon, 3 Jun 2024 15:48:05 +0300 Subject: [PATCH 3/8] Add `pip install pexpect` --- .ci/monolithic-linux.sh | 2 ++ .ci/monolithic-windows.sh | 2 ++ 2 files changed, 4 insertions(+) diff --git a/.ci/monolithic-linux.sh b/.ci/monolithic-linux.sh index 38d7128f241b6..95ac4218ef8fa 100755 --- a/.ci/monolithic-linux.sh +++ b/.ci/monolithic-linux.sh @@ -39,6 +39,8 @@ targets="${2}" echo "--- cmake" pip install -q -r "${MONOREPO_ROOT}"/mlir/python/requirements.txt +# Needed for several LLDB tests +pip install pexpect cmake -S "${MONOREPO_ROOT}"/llvm -B "${BUILD_DIR}" \ -D LLVM_ENABLE_PROJECTS="${projects}" \ -G Ninja \ diff --git a/.ci/monolithic-windows.sh b/.ci/monolithic-windows.sh index 91e719c52d436..e8807e3ba69bf 100755 --- a/.ci/monolithic-windows.sh +++ b/.ci/monolithic-windows.sh @@ -38,6 +38,8 @@ targets="${2}" echo "--- cmake" pip install -q -r "${MONOREPO_ROOT}"/mlir/python/requirements.txt +# Needed for several LLDB tests +pip install pexpect # The CMAKE_*_LINKER_FLAGS to disable the manifest come from research # on fixing a build reliability issue on the build server, please >From 496d2998a722a7bb57fc9a5a38f9ee5e52440c1d Mon Sep 17 00:00:00 2001 From: Vlad Serebrennikov Date: Mon, 3 Jun 2024 21:20:01 +0300 Subject: [PATCH 4/8] Switch to `requirements.txt` provided by LLDB now --- .ci/monolithic-linux.sh | 3 +-- .ci/monolithic-windows.sh | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/.ci/monolithic-linux.sh b/.ci/monolithic-linux.sh index 95ac4218ef8fa..b78dc59432b65 100755 --- a/.ci/monolithic-linux.sh +++ b/.ci/monolithic-linux.sh @@ -39,8 +39,7 @@ targets="${2}" echo "--- cmake" pip install -q -r "${MONOREPO_ROOT}"/mlir/python/requirements.txt -# Needed for several LLDB tests -pip install pexpect +pip install -q -r "${MONOREPO_ROOT}"/lldb/test/requirements.txt cmake -S "${MONOREPO_ROOT}"/llvm -B "${BUILD_DIR}" \ -D LLVM_ENABLE_PROJECTS="${projects}" \ -G Ninja \ diff --git a/.ci/monolithic-windows.sh b/.ci/monolithic-windows.sh index e8807e3ba69bf..af78447295012 100755 --- a/.ci/monolithic-windows.sh +++ b/.ci/monolithic-windows.sh @@ -38,8 +38,7 @@ targets="${2}" echo "--- cmake" pip install -q -r "${MONOREPO_ROOT}"/mlir/python/requirements.txt -# Needed for several LLDB tests -pip install pexpect +pip install -q -r "${MONOREPO_ROOT}"/lldb/test/requirements.txt # The CMA
[clang] [llvm] Enable LLDB tests in Linux pre-merge CI (PR #94208)
https://github.com/Endilll updated https://github.com/llvm/llvm-project/pull/94208 >From 5c757153a3f462d40663add6a9ae7caf42272913 Mon Sep 17 00:00:00 2001 From: Vlad Serebrennikov Date: Mon, 3 Jun 2024 13:33:36 +0300 Subject: [PATCH 1/8] Enable LLDB tests in pre-submit CI --- .ci/generate-buildkite-pipeline-premerge | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/.ci/generate-buildkite-pipeline-premerge b/.ci/generate-buildkite-pipeline-premerge index 033ab804b165e..a9972f235ff46 100755 --- a/.ci/generate-buildkite-pipeline-premerge +++ b/.ci/generate-buildkite-pipeline-premerge @@ -153,7 +153,6 @@ function exclude-linux() { for project in ${projects}; do case ${project} in cross-project-tests) ;; # tests failing -lldb);; # tests failing openmp) ;; # https://github.com/google/llvm-premerge-checks/issues/410 *) echo "${project}" @@ -170,7 +169,6 @@ function exclude-windows() { compiler-rt) ;; # tests taking too long openmp) ;; # TODO: having trouble with the Perl installation libc);; # no Windows support -lldb);; # tests failing bolt);; # tests are not supported yet *) echo "${project}" @@ -213,7 +211,7 @@ function check-targets() { echo "check-unwind" ;; lldb) - echo "check-all" # TODO: check-lldb may not include all the LLDB tests? + echo "check-lldb" # TODO: check-lldb may not include all the LLDB tests? ;; pstl) echo "check-all" >From 49e21f6b92623e280cfc49ac631b7481eb7a1229 Mon Sep 17 00:00:00 2001 From: Vlad Serebrennikov Date: Mon, 3 Jun 2024 13:34:18 +0300 Subject: [PATCH 2/8] Trigger Clang CI --- clang/examples/PrintFunctionNames/PrintFunctionNames.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clang/examples/PrintFunctionNames/PrintFunctionNames.cpp b/clang/examples/PrintFunctionNames/PrintFunctionNames.cpp index 6509a6440e12d..b2b785b87c25c 100644 --- a/clang/examples/PrintFunctionNames/PrintFunctionNames.cpp +++ b/clang/examples/PrintFunctionNames/PrintFunctionNames.cpp @@ -72,7 +72,7 @@ class PrintFunctionsConsumer : public ASTConsumer { *sema.LateParsedTemplateMap.find(FD)->second; sema.LateTemplateParser(sema.OpaqueParser, LPT); llvm::errs() << "late-parsed-decl: \"" << FD->getNameAsString() << "\"\n"; -} +} } }; >From c2d7679f76e971e5532c1cd91d99e7866f738960 Mon Sep 17 00:00:00 2001 From: Vlad Serebrennikov Date: Mon, 3 Jun 2024 15:48:05 +0300 Subject: [PATCH 3/8] Add `pip install pexpect` --- .ci/monolithic-linux.sh | 2 ++ .ci/monolithic-windows.sh | 2 ++ 2 files changed, 4 insertions(+) diff --git a/.ci/monolithic-linux.sh b/.ci/monolithic-linux.sh index 38d7128f241b6..95ac4218ef8fa 100755 --- a/.ci/monolithic-linux.sh +++ b/.ci/monolithic-linux.sh @@ -39,6 +39,8 @@ targets="${2}" echo "--- cmake" pip install -q -r "${MONOREPO_ROOT}"/mlir/python/requirements.txt +# Needed for several LLDB tests +pip install pexpect cmake -S "${MONOREPO_ROOT}"/llvm -B "${BUILD_DIR}" \ -D LLVM_ENABLE_PROJECTS="${projects}" \ -G Ninja \ diff --git a/.ci/monolithic-windows.sh b/.ci/monolithic-windows.sh index 91e719c52d436..e8807e3ba69bf 100755 --- a/.ci/monolithic-windows.sh +++ b/.ci/monolithic-windows.sh @@ -38,6 +38,8 @@ targets="${2}" echo "--- cmake" pip install -q -r "${MONOREPO_ROOT}"/mlir/python/requirements.txt +# Needed for several LLDB tests +pip install pexpect # The CMAKE_*_LINKER_FLAGS to disable the manifest come from research # on fixing a build reliability issue on the build server, please >From 496d2998a722a7bb57fc9a5a38f9ee5e52440c1d Mon Sep 17 00:00:00 2001 From: Vlad Serebrennikov Date: Mon, 3 Jun 2024 21:20:01 +0300 Subject: [PATCH 4/8] Switch to `requirements.txt` provided by LLDB now --- .ci/monolithic-linux.sh | 3 +-- .ci/monolithic-windows.sh | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/.ci/monolithic-linux.sh b/.ci/monolithic-linux.sh index 95ac4218ef8fa..b78dc59432b65 100755 --- a/.ci/monolithic-linux.sh +++ b/.ci/monolithic-linux.sh @@ -39,8 +39,7 @@ targets="${2}" echo "--- cmake" pip install -q -r "${MONOREPO_ROOT}"/mlir/python/requirements.txt -# Needed for several LLDB tests -pip install pexpect +pip install -q -r "${MONOREPO_ROOT}"/lldb/test/requirements.txt cmake -S "${MONOREPO_ROOT}"/llvm -B "${BUILD_DIR}" \ -D LLVM_ENABLE_PROJECTS="${projects}" \ -G Ninja \ diff --git a/.ci/monolithic-windows.sh b/.ci/monolithic-windows.sh index e8807e3ba69bf..af78447295012 100755 --- a/.ci/monolithic-windows.sh +++ b/.ci/monolithic-windows.sh @@ -38,8 +38,7 @@ targets="${2}" echo "--- cmake" pip install -q -r "${MONOREPO_ROOT}"/mlir/python/requirements.txt -# Needed for several LLDB tests -pip install pexpect +pip install -q -r "${MONOREPO_ROOT}"/lldb/test/requirements.txt # The CMAKE
[clang] [llvm] Enable LLDB tests in Linux pre-merge CI (PR #94208)
https://github.com/Endilll updated https://github.com/llvm/llvm-project/pull/94208 >From 5c757153a3f462d40663add6a9ae7caf42272913 Mon Sep 17 00:00:00 2001 From: Vlad Serebrennikov Date: Mon, 3 Jun 2024 13:33:36 +0300 Subject: [PATCH 1/9] Enable LLDB tests in pre-submit CI --- .ci/generate-buildkite-pipeline-premerge | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/.ci/generate-buildkite-pipeline-premerge b/.ci/generate-buildkite-pipeline-premerge index 033ab804b165e..a9972f235ff46 100755 --- a/.ci/generate-buildkite-pipeline-premerge +++ b/.ci/generate-buildkite-pipeline-premerge @@ -153,7 +153,6 @@ function exclude-linux() { for project in ${projects}; do case ${project} in cross-project-tests) ;; # tests failing -lldb);; # tests failing openmp) ;; # https://github.com/google/llvm-premerge-checks/issues/410 *) echo "${project}" @@ -170,7 +169,6 @@ function exclude-windows() { compiler-rt) ;; # tests taking too long openmp) ;; # TODO: having trouble with the Perl installation libc);; # no Windows support -lldb);; # tests failing bolt);; # tests are not supported yet *) echo "${project}" @@ -213,7 +211,7 @@ function check-targets() { echo "check-unwind" ;; lldb) - echo "check-all" # TODO: check-lldb may not include all the LLDB tests? + echo "check-lldb" # TODO: check-lldb may not include all the LLDB tests? ;; pstl) echo "check-all" >From 49e21f6b92623e280cfc49ac631b7481eb7a1229 Mon Sep 17 00:00:00 2001 From: Vlad Serebrennikov Date: Mon, 3 Jun 2024 13:34:18 +0300 Subject: [PATCH 2/9] Trigger Clang CI --- clang/examples/PrintFunctionNames/PrintFunctionNames.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clang/examples/PrintFunctionNames/PrintFunctionNames.cpp b/clang/examples/PrintFunctionNames/PrintFunctionNames.cpp index 6509a6440e12d..b2b785b87c25c 100644 --- a/clang/examples/PrintFunctionNames/PrintFunctionNames.cpp +++ b/clang/examples/PrintFunctionNames/PrintFunctionNames.cpp @@ -72,7 +72,7 @@ class PrintFunctionsConsumer : public ASTConsumer { *sema.LateParsedTemplateMap.find(FD)->second; sema.LateTemplateParser(sema.OpaqueParser, LPT); llvm::errs() << "late-parsed-decl: \"" << FD->getNameAsString() << "\"\n"; -} +} } }; >From c2d7679f76e971e5532c1cd91d99e7866f738960 Mon Sep 17 00:00:00 2001 From: Vlad Serebrennikov Date: Mon, 3 Jun 2024 15:48:05 +0300 Subject: [PATCH 3/9] Add `pip install pexpect` --- .ci/monolithic-linux.sh | 2 ++ .ci/monolithic-windows.sh | 2 ++ 2 files changed, 4 insertions(+) diff --git a/.ci/monolithic-linux.sh b/.ci/monolithic-linux.sh index 38d7128f241b6..95ac4218ef8fa 100755 --- a/.ci/monolithic-linux.sh +++ b/.ci/monolithic-linux.sh @@ -39,6 +39,8 @@ targets="${2}" echo "--- cmake" pip install -q -r "${MONOREPO_ROOT}"/mlir/python/requirements.txt +# Needed for several LLDB tests +pip install pexpect cmake -S "${MONOREPO_ROOT}"/llvm -B "${BUILD_DIR}" \ -D LLVM_ENABLE_PROJECTS="${projects}" \ -G Ninja \ diff --git a/.ci/monolithic-windows.sh b/.ci/monolithic-windows.sh index 91e719c52d436..e8807e3ba69bf 100755 --- a/.ci/monolithic-windows.sh +++ b/.ci/monolithic-windows.sh @@ -38,6 +38,8 @@ targets="${2}" echo "--- cmake" pip install -q -r "${MONOREPO_ROOT}"/mlir/python/requirements.txt +# Needed for several LLDB tests +pip install pexpect # The CMAKE_*_LINKER_FLAGS to disable the manifest come from research # on fixing a build reliability issue on the build server, please >From 496d2998a722a7bb57fc9a5a38f9ee5e52440c1d Mon Sep 17 00:00:00 2001 From: Vlad Serebrennikov Date: Mon, 3 Jun 2024 21:20:01 +0300 Subject: [PATCH 4/9] Switch to `requirements.txt` provided by LLDB now --- .ci/monolithic-linux.sh | 3 +-- .ci/monolithic-windows.sh | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/.ci/monolithic-linux.sh b/.ci/monolithic-linux.sh index 95ac4218ef8fa..b78dc59432b65 100755 --- a/.ci/monolithic-linux.sh +++ b/.ci/monolithic-linux.sh @@ -39,8 +39,7 @@ targets="${2}" echo "--- cmake" pip install -q -r "${MONOREPO_ROOT}"/mlir/python/requirements.txt -# Needed for several LLDB tests -pip install pexpect +pip install -q -r "${MONOREPO_ROOT}"/lldb/test/requirements.txt cmake -S "${MONOREPO_ROOT}"/llvm -B "${BUILD_DIR}" \ -D LLVM_ENABLE_PROJECTS="${projects}" \ -G Ninja \ diff --git a/.ci/monolithic-windows.sh b/.ci/monolithic-windows.sh index e8807e3ba69bf..af78447295012 100755 --- a/.ci/monolithic-windows.sh +++ b/.ci/monolithic-windows.sh @@ -38,8 +38,7 @@ targets="${2}" echo "--- cmake" pip install -q -r "${MONOREPO_ROOT}"/mlir/python/requirements.txt -# Needed for several LLDB tests -pip install pexpect +pip install -q -r "${MONOREPO_ROOT}"/lldb/test/requirements.txt # The CMAKE
[clang] [llvm] Enable LLDB tests in Linux pre-merge CI (PR #94208)
https://github.com/Endilll edited https://github.com/llvm/llvm-project/pull/94208 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] Enable LLDB tests in Linux pre-merge CI (PR #94208)
Endilll wrote: @AaronBallman @JDevlieghere @Michael137 @adrian-prantl @DavidSpickett @mizvekov I updated the PR to test LLDB on Clang changes. I hope we can start gathering approvals to get this PR moving. https://github.com/llvm/llvm-project/pull/94208 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Substitute for the type aliases inside of a CTAD guide (PR #94740)
https://github.com/zyn0217 created https://github.com/llvm/llvm-project/pull/94740 Similar to the approach of handling nested class templates when building a CTAD guide, we substitute the template parameters of a type alias declaration with the instantiating template arguments in order to ensure the guide eventually doesn't reference any outer template parameters. For example, ```cpp template struct Outer { using Alias = S; template struct Inner { Inner(Alias); }; }; ``` we used to retain the reference to T accidently because the TreeTransform does nothing on type alias Decls by default. Fixes https://github.com/llvm/llvm-project/issues/94614 >From 2f60e51f2017e4448047f64983b2f22cdb67e816 Mon Sep 17 00:00:00 2001 From: Younan Zhang Date: Fri, 7 Jun 2024 18:08:10 +0800 Subject: [PATCH] [Clang] Substitute for the type aliases inside of a CTAD guide --- clang/docs/ReleaseNotes.rst | 1 + clang/lib/Sema/SemaTemplate.cpp | 96 +-- .../SemaTemplate/nested-deduction-guides.cpp | 70 ++ 3 files changed, 160 insertions(+), 7 deletions(-) diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index 0c700d23257bf..3f6d040b0ddf1 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -823,6 +823,7 @@ Bug Fixes to C++ Support differering by their constraints when only one of these function was variadic. - Fix a crash when a variable is captured by a block nested inside a lambda. (Fixes #GH93625). - Fixed a type constraint substitution issue involving a generic lambda expression. (#GH93821) +- Fixed a CTAD substitution bug involving type aliases that reference outer template parameters. (#GH94614). Bug Fixes to AST Handling ^ diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp index 40a759ea330de..1e921dd26bd7d 100644 --- a/clang/lib/Sema/SemaTemplate.cpp +++ b/clang/lib/Sema/SemaTemplate.cpp @@ -2220,23 +2220,101 @@ namespace { class ExtractTypeForDeductionGuide : public TreeTransform { llvm::SmallVectorImpl &MaterializedTypedefs; + ClassTemplateDecl *NestedPattern; + const MultiLevelTemplateArgumentList *OuterInstantiationArgs; public: typedef TreeTransform Base; ExtractTypeForDeductionGuide( Sema &SemaRef, - llvm::SmallVectorImpl &MaterializedTypedefs) - : Base(SemaRef), MaterializedTypedefs(MaterializedTypedefs) {} + llvm::SmallVectorImpl &MaterializedTypedefs, + ClassTemplateDecl *NestedPattern, + const MultiLevelTemplateArgumentList *OuterInstantiationArgs) + : Base(SemaRef), MaterializedTypedefs(MaterializedTypedefs), +NestedPattern(NestedPattern), +OuterInstantiationArgs(OuterInstantiationArgs) {} TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); } + bool mightReferToOuterTemplateParameters(TypedefNameDecl *Typedef) { +if (!NestedPattern) + return false; + +static auto WalkUp = [](DeclContext *DC, DeclContext *TargetDC) { + if (DC == TargetDC) +return true; + while (!DC->isTranslationUnit()) { +if (DC->Equals(TargetDC)) + return true; +DC = DC->getParent(); + } + return false; +}; + +if (WalkUp(Typedef->getDeclContext(), NestedPattern->getTemplatedDecl())) + return true; +if (WalkUp(NestedPattern->getTemplatedDecl(), Typedef->getDeclContext())) + return true; +return false; + } + + QualType + RebuildTemplateSpecializationType(TemplateName Template, +SourceLocation TemplateNameLoc, +TemplateArgumentListInfo &TemplateArgs) { +if (!OuterInstantiationArgs || +!isa_and_present(Template.getAsTemplateDecl())) + return Base::RebuildTemplateSpecializationType(Template, TemplateNameLoc, + TemplateArgs); + +auto *TATD = cast(Template.getAsTemplateDecl()); +auto *Pattern = TATD; +while (Pattern->getInstantiatedFromMemberTemplate()) + Pattern = Pattern->getInstantiatedFromMemberTemplate(); +if (!mightReferToOuterTemplateParameters(Pattern->getTemplatedDecl())) + return Base::RebuildTemplateSpecializationType(Template, TemplateNameLoc, + TemplateArgs); + +Decl *NewD = SemaRef.SubstDecl( +TATD, SemaRef.getASTContext().getTranslationUnitDecl(), +*OuterInstantiationArgs); +if (!NewD) + return QualType(); + +auto *NewTATD = cast(NewD); +MaterializedTypedefs.push_back(NewTATD->getTemplatedDecl()); + +return Base::RebuildTemplateSpecializationType( +TemplateName(NewTATD), TemplateNameLoc, TemplateArgs); + } + QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) { ASTContext &Context = SemaRef.getASTContext(); TypedefNameDecl *OrigDecl = TL.getTypedefNameD
[clang] [Clang] Substitute for the type aliases inside of a CTAD guide (PR #94740)
https://github.com/zyn0217 edited https://github.com/llvm/llvm-project/pull/94740 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 54c5dbe - [clang][test] Skip interpreter value test on Arm 32 bit
Author: David Spickett Date: 2024-06-07T10:38:25Z New Revision: 54c5dbe7c3812461decbccb6ed122e41777e02bd URL: https://github.com/llvm/llvm-project/commit/54c5dbe7c3812461decbccb6ed122e41777e02bd DIFF: https://github.com/llvm/llvm-project/commit/54c5dbe7c3812461decbccb6ed122e41777e02bd.diff LOG: [clang][test] Skip interpreter value test on Arm 32 bit https://github.com/llvm/llvm-project/pull/89811 caused this test to fail, somehow. I think it may not be at fault, but actually be exposing some existing undefined behaviour, see https://github.com/llvm/llvm-project/issues/94741. Skipping this for now to get the bots green again. Added: Modified: clang/unittests/Interpreter/InterpreterTest.cpp Removed: diff --git a/clang/unittests/Interpreter/InterpreterTest.cpp b/clang/unittests/Interpreter/InterpreterTest.cpp index ab9b7a31094f7..72b34dae378e5 100644 --- a/clang/unittests/Interpreter/InterpreterTest.cpp +++ b/clang/unittests/Interpreter/InterpreterTest.cpp @@ -282,6 +282,9 @@ TEST_F(InterpreterTest, InstantiateTemplate) { EXPECT_EQ(42, fn(NewA.getPtr())); } +// This test exposes an ARM specific problem in the interpreter, see +// https://github.com/llvm/llvm-project/issues/94741. +#ifndef __arm__ TEST_F(InterpreterTest, Value) { std::unique_ptr Interp = createInterpreter(); @@ -379,5 +382,6 @@ TEST_F(InterpreterTest, Value) { EXPECT_EQ(V9.getKind(), Value::K_PtrOrObj); EXPECT_TRUE(V9.isManuallyAlloc()); } +#endif /* ifndef __arm__ */ } // end anonymous namespace ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 6fe5428 - [Flang] Handle the newly-added "Reserved" FramePointerKind for 1a5239251ead73ee57f4e2f7fc93433ac7cf18b1
Author: Haojian Wu Date: 2024-06-07T12:49:41+02:00 New Revision: 6fe5428ecbd18aa263417a244c0850b1271617c0 URL: https://github.com/llvm/llvm-project/commit/6fe5428ecbd18aa263417a244c0850b1271617c0 DIFF: https://github.com/llvm/llvm-project/commit/6fe5428ecbd18aa263417a244c0850b1271617c0.diff LOG: [Flang] Handle the newly-added "Reserved" FramePointerKind for 1a5239251ead73ee57f4e2f7fc93433ac7cf18b1 Added: Modified: clang/lib/Driver/ToolChains/Flang.cpp Removed: diff --git a/clang/lib/Driver/ToolChains/Flang.cpp b/clang/lib/Driver/ToolChains/Flang.cpp index 9609a1dc65c09..42b45dba2bd31 100644 --- a/clang/lib/Driver/ToolChains/Flang.cpp +++ b/clang/lib/Driver/ToolChains/Flang.cpp @@ -802,6 +802,9 @@ void Flang::ConstructJob(Compilation &C, const JobAction &JA, case CodeGenOptions::FramePointerKind::None: FPKeepKindStr = "-mframe-pointer=none"; break; + case CodeGenOptions::FramePointerKind::Reserved: +FPKeepKindStr = "-mframe-pointer=reserved"; +break; case CodeGenOptions::FramePointerKind::NonLeaf: FPKeepKindStr = "-mframe-pointer=non-leaf"; break; ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] Enforce SL.con.3: Add check to replace operator[] with at() (PR #90043)
PiotrZSL wrote: Check if you can commit to sebwolf-de:avoid-bounds-error-check https://github.com/llvm/llvm-project/pull/90043 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [clang][SPIR-V] Add support for AMDGCN flavoured SPIRV (PR #89796)
https://github.com/AlexVlx closed https://github.com/llvm/llvm-project/pull/89796 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Substitute for the type aliases inside of a CTAD guide (PR #94740)
https://github.com/zyn0217 updated https://github.com/llvm/llvm-project/pull/94740 >From 2f60e51f2017e4448047f64983b2f22cdb67e816 Mon Sep 17 00:00:00 2001 From: Younan Zhang Date: Fri, 7 Jun 2024 18:08:10 +0800 Subject: [PATCH 1/2] [Clang] Substitute for the type aliases inside of a CTAD guide --- clang/docs/ReleaseNotes.rst | 1 + clang/lib/Sema/SemaTemplate.cpp | 96 +-- .../SemaTemplate/nested-deduction-guides.cpp | 70 ++ 3 files changed, 160 insertions(+), 7 deletions(-) diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index 0c700d23257bf..3f6d040b0ddf1 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -823,6 +823,7 @@ Bug Fixes to C++ Support differering by their constraints when only one of these function was variadic. - Fix a crash when a variable is captured by a block nested inside a lambda. (Fixes #GH93625). - Fixed a type constraint substitution issue involving a generic lambda expression. (#GH93821) +- Fixed a CTAD substitution bug involving type aliases that reference outer template parameters. (#GH94614). Bug Fixes to AST Handling ^ diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp index 40a759ea330de..1e921dd26bd7d 100644 --- a/clang/lib/Sema/SemaTemplate.cpp +++ b/clang/lib/Sema/SemaTemplate.cpp @@ -2220,23 +2220,101 @@ namespace { class ExtractTypeForDeductionGuide : public TreeTransform { llvm::SmallVectorImpl &MaterializedTypedefs; + ClassTemplateDecl *NestedPattern; + const MultiLevelTemplateArgumentList *OuterInstantiationArgs; public: typedef TreeTransform Base; ExtractTypeForDeductionGuide( Sema &SemaRef, - llvm::SmallVectorImpl &MaterializedTypedefs) - : Base(SemaRef), MaterializedTypedefs(MaterializedTypedefs) {} + llvm::SmallVectorImpl &MaterializedTypedefs, + ClassTemplateDecl *NestedPattern, + const MultiLevelTemplateArgumentList *OuterInstantiationArgs) + : Base(SemaRef), MaterializedTypedefs(MaterializedTypedefs), +NestedPattern(NestedPattern), +OuterInstantiationArgs(OuterInstantiationArgs) {} TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); } + bool mightReferToOuterTemplateParameters(TypedefNameDecl *Typedef) { +if (!NestedPattern) + return false; + +static auto WalkUp = [](DeclContext *DC, DeclContext *TargetDC) { + if (DC == TargetDC) +return true; + while (!DC->isTranslationUnit()) { +if (DC->Equals(TargetDC)) + return true; +DC = DC->getParent(); + } + return false; +}; + +if (WalkUp(Typedef->getDeclContext(), NestedPattern->getTemplatedDecl())) + return true; +if (WalkUp(NestedPattern->getTemplatedDecl(), Typedef->getDeclContext())) + return true; +return false; + } + + QualType + RebuildTemplateSpecializationType(TemplateName Template, +SourceLocation TemplateNameLoc, +TemplateArgumentListInfo &TemplateArgs) { +if (!OuterInstantiationArgs || +!isa_and_present(Template.getAsTemplateDecl())) + return Base::RebuildTemplateSpecializationType(Template, TemplateNameLoc, + TemplateArgs); + +auto *TATD = cast(Template.getAsTemplateDecl()); +auto *Pattern = TATD; +while (Pattern->getInstantiatedFromMemberTemplate()) + Pattern = Pattern->getInstantiatedFromMemberTemplate(); +if (!mightReferToOuterTemplateParameters(Pattern->getTemplatedDecl())) + return Base::RebuildTemplateSpecializationType(Template, TemplateNameLoc, + TemplateArgs); + +Decl *NewD = SemaRef.SubstDecl( +TATD, SemaRef.getASTContext().getTranslationUnitDecl(), +*OuterInstantiationArgs); +if (!NewD) + return QualType(); + +auto *NewTATD = cast(NewD); +MaterializedTypedefs.push_back(NewTATD->getTemplatedDecl()); + +return Base::RebuildTemplateSpecializationType( +TemplateName(NewTATD), TemplateNameLoc, TemplateArgs); + } + QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) { ASTContext &Context = SemaRef.getASTContext(); TypedefNameDecl *OrigDecl = TL.getTypedefNameDecl(); TypedefNameDecl *Decl = OrigDecl; // Transform the underlying type of the typedef and clone the Decl only if // the typedef has a dependent context. -if (OrigDecl->getDeclContext()->isDependentContext()) { +bool InDependentContext = OrigDecl->getDeclContext()->isDependentContext(); + +// A typedef/alias Decl within the NestedPattern may reference the outer +// template parameters. They're substituted with corresponding instantiation +// arguments here and in RebuildTemplateSpecializationType() above. +// Otherwise, we would have a
[clang] [llvm] [clang][SPIR-V] Add support for AMDGCN flavoured SPIRV (PR #89796)
AlexVlx wrote: Thank you everyone for the reviews! https://github.com/llvm/llvm-project/pull/89796 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[libunwind] [libunwind] Tweak tests for musl support. (PR #85097)
al45tair wrote: I don't have merge rights here, so someone else will need to hit the Merge button. https://github.com/llvm/llvm-project/pull/85097 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] Add SonarCloud (PR #94745)
https://github.com/steakhal updated https://github.com/llvm/llvm-project/pull/94745 >From 099e93f425293daf376eccbe6fd771f297126588 Mon Sep 17 00:00:00 2001 From: Balazs Benics Date: Fri, 7 Jun 2024 12:55:07 +0200 Subject: [PATCH 1/2] Add initial SonarCloud config --- .github/workflows/clang-tests-sonar-cloud.yml | 38 + .../llvm-project-tests-sonar-cloud.yml| 146 ++ sonar-project.properties | 7 + 3 files changed, 191 insertions(+) create mode 100644 .github/workflows/clang-tests-sonar-cloud.yml create mode 100644 .github/workflows/llvm-project-tests-sonar-cloud.yml create mode 100644 sonar-project.properties diff --git a/.github/workflows/clang-tests-sonar-cloud.yml b/.github/workflows/clang-tests-sonar-cloud.yml new file mode 100644 index 0..2969687708629 --- /dev/null +++ b/.github/workflows/clang-tests-sonar-cloud.yml @@ -0,0 +1,38 @@ +name: Clang Tests with SonarScanner + +permissions: + contents: read + +on: + workflow_dispatch: + push: +branches: + - 'release/**' +paths: + - 'clang/**' + - '.github/workflows/clang-tests-sonar-cloud.yml' + - '.github/workflows/llvm-project-tests-sonar-cloud.yml' + - '!llvm/**' + pull_request: +branches: + - 'release/**' +paths: + - 'clang/**' + - '.github/workflows/clang-tests-sonar-cloud.yml' + - '.github/workflows/llvm-project-tests-sonar-cloud.yml' + - '!llvm/**' + +concurrency: + # Skip intermediate builds: always. + # Cancel intermediate builds: only if it is a pull request build. + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ startsWith(github.ref, 'refs/pull/') }} + +jobs: + check_clang: +if: github.repository_owner == 'llvm' +name: Test clang,lldb,libclc +uses: ./.github/workflows/llvm-project-tests-sonar-cloud.yml +with: + build_target: check-clang + projects: clang;lldb;libclc diff --git a/.github/workflows/llvm-project-tests-sonar-cloud.yml b/.github/workflows/llvm-project-tests-sonar-cloud.yml new file mode 100644 index 0..7c489effda92f --- /dev/null +++ b/.github/workflows/llvm-project-tests-sonar-cloud.yml @@ -0,0 +1,146 @@ +name: LLVM Project Tests and analyze with SonarScanner + +permissions: + contents: read + +on: + workflow_dispatch: +inputs: + build_target: +required: false + projects: +required: false + extra_cmake_args: +required: false + os_list: +required: false +default: '["ubuntu-latest"]' + python_version: +required: false +type: string +default: '3.11' + workflow_call: +inputs: + build_target: +required: false +type: string +default: "all" + + projects: +required: true +type: string + + extra_cmake_args: +required: false +type: string + + os_list: +required: false +type: string +# Use windows-2019 due to: +# https://developercommunity.visualstudio.com/t/Prev-Issue---with-__assume-isnan-/1597317 +default: '["ubuntu-latest"]' + + python_version: +required: false +type: string +default: '3.11' + +concurrency: + # Skip intermediate builds: always. + # Cancel intermediate builds: only if it is a pull request build. + # If the group name here is the same as the group name in the workflow that includes + # this one, then the action will try to wait on itself and get stuck. + group: llvm-project-${{ github.workflow }}-${{ inputs.projects }}${{ github.ref }} + cancel-in-progress: ${{ startsWith(github.ref, 'refs/pull/') }} + +jobs: + lit-tests: +name: Lit Tests +runs-on: ${{ matrix.os }} +container: + image: ${{(startsWith(matrix.os, 'ubuntu') && 'ghcr.io/llvm/ci-ubuntu-22.04:latest') || null}} + volumes: +- /mnt/:/mnt/ +strategy: + fail-fast: false + matrix: +os: ${{ fromJSON(inputs.os_list) }} +steps: + - name: Setup Windows +if: startsWith(matrix.os, 'windows') +uses: llvm/actions/setup-windows@main +with: + arch: amd64 + # On Windows, starting with win19/20220814.1, cmake choose the 32-bit + # python3.10.6 libraries instead of the 64-bit libraries when building + # lldb. Using this setup-python action to make 3.10 the default + # python fixes this. + - name: Setup Python +uses: actions/setup-python@v4 +with: + python-version: ${{ inputs.python_version }} + - name: Install Ninja +if: runner.os != 'Linux' +uses: llvm/actions/install-ninja@main + # actions/checkout deletes any existing files in the new git directory, + # so this needs to either run before ccache-action or it has to use + # clean: false. + - uses: actions/checkout@v4 +with: + fetch-depth: 250 + - name: Setup cca
[clang] [llvm] Add SonarCloud (PR #94745)
llvmbot wrote: @llvm/pr-subscribers-clang-static-analyzer-1 @llvm/pr-subscribers-clang Author: Balazs Benics (steakhal) Changes --- Full diff: https://github.com/llvm/llvm-project/pull/94745.diff 4 Files Affected: - (added) .github/workflows/clang-tests-sonar-cloud.yml (+38) - (added) .github/workflows/llvm-project-tests-sonar-cloud.yml (+146) - (modified) clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp (+1-1) - (added) sonar-project.properties (+7) ``diff diff --git a/.github/workflows/clang-tests-sonar-cloud.yml b/.github/workflows/clang-tests-sonar-cloud.yml new file mode 100644 index 0..2969687708629 --- /dev/null +++ b/.github/workflows/clang-tests-sonar-cloud.yml @@ -0,0 +1,38 @@ +name: Clang Tests with SonarScanner + +permissions: + contents: read + +on: + workflow_dispatch: + push: +branches: + - 'release/**' +paths: + - 'clang/**' + - '.github/workflows/clang-tests-sonar-cloud.yml' + - '.github/workflows/llvm-project-tests-sonar-cloud.yml' + - '!llvm/**' + pull_request: +branches: + - 'release/**' +paths: + - 'clang/**' + - '.github/workflows/clang-tests-sonar-cloud.yml' + - '.github/workflows/llvm-project-tests-sonar-cloud.yml' + - '!llvm/**' + +concurrency: + # Skip intermediate builds: always. + # Cancel intermediate builds: only if it is a pull request build. + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ startsWith(github.ref, 'refs/pull/') }} + +jobs: + check_clang: +if: github.repository_owner == 'llvm' +name: Test clang,lldb,libclc +uses: ./.github/workflows/llvm-project-tests-sonar-cloud.yml +with: + build_target: check-clang + projects: clang;lldb;libclc diff --git a/.github/workflows/llvm-project-tests-sonar-cloud.yml b/.github/workflows/llvm-project-tests-sonar-cloud.yml new file mode 100644 index 0..7c489effda92f --- /dev/null +++ b/.github/workflows/llvm-project-tests-sonar-cloud.yml @@ -0,0 +1,146 @@ +name: LLVM Project Tests and analyze with SonarScanner + +permissions: + contents: read + +on: + workflow_dispatch: +inputs: + build_target: +required: false + projects: +required: false + extra_cmake_args: +required: false + os_list: +required: false +default: '["ubuntu-latest"]' + python_version: +required: false +type: string +default: '3.11' + workflow_call: +inputs: + build_target: +required: false +type: string +default: "all" + + projects: +required: true +type: string + + extra_cmake_args: +required: false +type: string + + os_list: +required: false +type: string +# Use windows-2019 due to: +# https://developercommunity.visualstudio.com/t/Prev-Issue---with-__assume-isnan-/1597317 +default: '["ubuntu-latest"]' + + python_version: +required: false +type: string +default: '3.11' + +concurrency: + # Skip intermediate builds: always. + # Cancel intermediate builds: only if it is a pull request build. + # If the group name here is the same as the group name in the workflow that includes + # this one, then the action will try to wait on itself and get stuck. + group: llvm-project-${{ github.workflow }}-${{ inputs.projects }}${{ github.ref }} + cancel-in-progress: ${{ startsWith(github.ref, 'refs/pull/') }} + +jobs: + lit-tests: +name: Lit Tests +runs-on: ${{ matrix.os }} +container: + image: ${{(startsWith(matrix.os, 'ubuntu') && 'ghcr.io/llvm/ci-ubuntu-22.04:latest') || null}} + volumes: +- /mnt/:/mnt/ +strategy: + fail-fast: false + matrix: +os: ${{ fromJSON(inputs.os_list) }} +steps: + - name: Setup Windows +if: startsWith(matrix.os, 'windows') +uses: llvm/actions/setup-windows@main +with: + arch: amd64 + # On Windows, starting with win19/20220814.1, cmake choose the 32-bit + # python3.10.6 libraries instead of the 64-bit libraries when building + # lldb. Using this setup-python action to make 3.10 the default + # python fixes this. + - name: Setup Python +uses: actions/setup-python@v4 +with: + python-version: ${{ inputs.python_version }} + - name: Install Ninja +if: runner.os != 'Linux' +uses: llvm/actions/install-ninja@main + # actions/checkout deletes any existing files in the new git directory, + # so this needs to either run before ccache-action or it has to use + # clean: false. + - uses: actions/checkout@v4 +with: + fetch-depth: 250 + - name: Setup ccache +uses: hendrikmuhs/ccache-action@v1 +with: + # A full build of llvm, clang, lld, and lldb takes about 250MB + # of ccache space. There's not much re
[clang] [llvm] Add SonarCloud (PR #94745)
https://github.com/steakhal updated https://github.com/llvm/llvm-project/pull/94745 >From 099e93f425293daf376eccbe6fd771f297126588 Mon Sep 17 00:00:00 2001 From: Balazs Benics Date: Fri, 7 Jun 2024 12:55:07 +0200 Subject: [PATCH 1/3] Add initial SonarCloud config --- .github/workflows/clang-tests-sonar-cloud.yml | 38 + .../llvm-project-tests-sonar-cloud.yml| 146 ++ sonar-project.properties | 7 + 3 files changed, 191 insertions(+) create mode 100644 .github/workflows/clang-tests-sonar-cloud.yml create mode 100644 .github/workflows/llvm-project-tests-sonar-cloud.yml create mode 100644 sonar-project.properties diff --git a/.github/workflows/clang-tests-sonar-cloud.yml b/.github/workflows/clang-tests-sonar-cloud.yml new file mode 100644 index 0..2969687708629 --- /dev/null +++ b/.github/workflows/clang-tests-sonar-cloud.yml @@ -0,0 +1,38 @@ +name: Clang Tests with SonarScanner + +permissions: + contents: read + +on: + workflow_dispatch: + push: +branches: + - 'release/**' +paths: + - 'clang/**' + - '.github/workflows/clang-tests-sonar-cloud.yml' + - '.github/workflows/llvm-project-tests-sonar-cloud.yml' + - '!llvm/**' + pull_request: +branches: + - 'release/**' +paths: + - 'clang/**' + - '.github/workflows/clang-tests-sonar-cloud.yml' + - '.github/workflows/llvm-project-tests-sonar-cloud.yml' + - '!llvm/**' + +concurrency: + # Skip intermediate builds: always. + # Cancel intermediate builds: only if it is a pull request build. + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ startsWith(github.ref, 'refs/pull/') }} + +jobs: + check_clang: +if: github.repository_owner == 'llvm' +name: Test clang,lldb,libclc +uses: ./.github/workflows/llvm-project-tests-sonar-cloud.yml +with: + build_target: check-clang + projects: clang;lldb;libclc diff --git a/.github/workflows/llvm-project-tests-sonar-cloud.yml b/.github/workflows/llvm-project-tests-sonar-cloud.yml new file mode 100644 index 0..7c489effda92f --- /dev/null +++ b/.github/workflows/llvm-project-tests-sonar-cloud.yml @@ -0,0 +1,146 @@ +name: LLVM Project Tests and analyze with SonarScanner + +permissions: + contents: read + +on: + workflow_dispatch: +inputs: + build_target: +required: false + projects: +required: false + extra_cmake_args: +required: false + os_list: +required: false +default: '["ubuntu-latest"]' + python_version: +required: false +type: string +default: '3.11' + workflow_call: +inputs: + build_target: +required: false +type: string +default: "all" + + projects: +required: true +type: string + + extra_cmake_args: +required: false +type: string + + os_list: +required: false +type: string +# Use windows-2019 due to: +# https://developercommunity.visualstudio.com/t/Prev-Issue---with-__assume-isnan-/1597317 +default: '["ubuntu-latest"]' + + python_version: +required: false +type: string +default: '3.11' + +concurrency: + # Skip intermediate builds: always. + # Cancel intermediate builds: only if it is a pull request build. + # If the group name here is the same as the group name in the workflow that includes + # this one, then the action will try to wait on itself and get stuck. + group: llvm-project-${{ github.workflow }}-${{ inputs.projects }}${{ github.ref }} + cancel-in-progress: ${{ startsWith(github.ref, 'refs/pull/') }} + +jobs: + lit-tests: +name: Lit Tests +runs-on: ${{ matrix.os }} +container: + image: ${{(startsWith(matrix.os, 'ubuntu') && 'ghcr.io/llvm/ci-ubuntu-22.04:latest') || null}} + volumes: +- /mnt/:/mnt/ +strategy: + fail-fast: false + matrix: +os: ${{ fromJSON(inputs.os_list) }} +steps: + - name: Setup Windows +if: startsWith(matrix.os, 'windows') +uses: llvm/actions/setup-windows@main +with: + arch: amd64 + # On Windows, starting with win19/20220814.1, cmake choose the 32-bit + # python3.10.6 libraries instead of the 64-bit libraries when building + # lldb. Using this setup-python action to make 3.10 the default + # python fixes this. + - name: Setup Python +uses: actions/setup-python@v4 +with: + python-version: ${{ inputs.python_version }} + - name: Install Ninja +if: runner.os != 'Linux' +uses: llvm/actions/install-ninja@main + # actions/checkout deletes any existing files in the new git directory, + # so this needs to either run before ccache-action or it has to use + # clean: false. + - uses: actions/checkout@v4 +with: + fetch-depth: 250 + - name: Setup cca
[clang] [clang] Fix loss of `dllexport` for exported template specialization (PR #94664)
https://github.com/zmodem commented: Thanks! This basically looks good to me. It would be nice to keep `GetOrCreateLLVMGlobal` and `GetOrCreateLLVMFunction` in sync. Would it be possible to extract the "Handle dropped DLL attributes" logic into a small utility function that could be called from both? https://github.com/llvm/llvm-project/pull/94664 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 9ece3eb - [clang][Interp] Check ConstantExpr results for initialization
Author: Timm Bäder Date: 2024-06-07T13:29:23+02:00 New Revision: 9ece3eb1459309f9fbd18ce8ec8f771c238e8815 URL: https://github.com/llvm/llvm-project/commit/9ece3eb1459309f9fbd18ce8ec8f771c238e8815 DIFF: https://github.com/llvm/llvm-project/commit/9ece3eb1459309f9fbd18ce8ec8f771c238e8815.diff LOG: [clang][Interp] Check ConstantExpr results for initialization They need to be fully initialized, similar to global variables. Added: Modified: clang/lib/AST/Interp/EvalEmitter.cpp clang/lib/AST/Interp/EvaluationResult.cpp clang/test/AST/Interp/cxx20.cpp Removed: diff --git a/clang/lib/AST/Interp/EvalEmitter.cpp b/clang/lib/AST/Interp/EvalEmitter.cpp index 6d8aa3f20f01f..f6191d8ed6345 100644 --- a/clang/lib/AST/Interp/EvalEmitter.cpp +++ b/clang/lib/AST/Interp/EvalEmitter.cpp @@ -41,6 +41,7 @@ EvaluationResult EvalEmitter::interpretExpr(const Expr *E, bool ConvertResultToRValue) { S.setEvalLocation(E->getExprLoc()); this->ConvertResultToRValue = ConvertResultToRValue; + this->CheckFullyInitialized = isa(E); EvalResult.setSource(E); if (!this->visitExpr(E)) { @@ -175,6 +176,10 @@ bool EvalEmitter::emitRetVoid(const SourceInfo &Info) { bool EvalEmitter::emitRetValue(const SourceInfo &Info) { const auto &Ptr = S.Stk.pop(); + + if (CheckFullyInitialized && !EvalResult.checkFullyInitialized(S, Ptr)) +return false; + if (std::optional APV = Ptr.toRValue(S.getCtx())) { EvalResult.setValue(*APV); return true; diff --git a/clang/lib/AST/Interp/EvaluationResult.cpp b/clang/lib/AST/Interp/EvaluationResult.cpp index c04b0fc0a1121..29977232975fc 100644 --- a/clang/lib/AST/Interp/EvaluationResult.cpp +++ b/clang/lib/AST/Interp/EvaluationResult.cpp @@ -141,16 +141,14 @@ bool EvaluationResult::checkFullyInitialized(InterpState &S, const Pointer &Ptr) const { assert(Source); assert(empty()); - - // Our Source must be a VarDecl. - const Decl *SourceDecl = Source.dyn_cast(); - assert(SourceDecl); - const auto *VD = cast(SourceDecl); - assert(VD->getType()->isRecordType() || VD->getType()->isArrayType()); - SourceLocation InitLoc = VD->getAnyInitializer()->getExprLoc(); - assert(!Ptr.isZero()); + SourceLocation InitLoc; + if (const auto *D = Source.dyn_cast()) +InitLoc = cast(D)->getAnyInitializer()->getExprLoc(); + else if (const auto *E = Source.dyn_cast()) +InitLoc = E->getExprLoc(); + if (const Record *R = Ptr.getRecord()) return CheckFieldsInitialized(S, InitLoc, Ptr, R); const auto *CAT = diff --git a/clang/test/AST/Interp/cxx20.cpp b/clang/test/AST/Interp/cxx20.cpp index c750be866ca7c..434823644a7a3 100644 --- a/clang/test/AST/Interp/cxx20.cpp +++ b/clang/test/AST/Interp/cxx20.cpp @@ -797,3 +797,20 @@ namespace self_referencing { S s(1); } } + +namespace GH64949 { + struct f { +int g; // both-note {{subobject declared here}} +constexpr ~f() {} + }; + + class h { + public: +consteval h(char *) {} +f i; + }; + + void test() { h{nullptr}; } // both-error {{call to consteval function 'GH64949::h::h' is not a constant expression}} \ + // both-note {{subobject 'g' is not initialized}} \ + // both-warning {{expression result unused}} +} ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Fix loss of `dllexport` for exported template specialization (PR #94664)
nga888 wrote: > It would be nice to keep `GetOrCreateLLVMGlobal` and > `GetOrCreateLLVMFunction` in sync. Would it be possible to extract the > "Handle dropped DLL attributes" logic into a small utility function that > could be called from both? I did briefly think about this, but does this change really apply to `GetOrCreateLLVMGlobal`? Is there any test case to exercise it? Perhaps it would be better to leave `GetOrCreateLLVMGlobal` as is? https://github.com/llvm/llvm-project/pull/94664 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-repl] Lay the foundation of pretty printing for C. (PR #89811)
DavidSpickett wrote: > I will get you instructions on how to do that (will be tomorrow at this > point). https://github.com/llvm/llvm-project/issues/94741#issuecomment-2154656315 There is some underlying issue (https://github.com/llvm/llvm-project/issues/94741), so if you want to try and fix it, that's great, but it's also fine if you'd rather wait and see what I find on native hardware. https://github.com/llvm/llvm-project/pull/89811 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] b8cc85b - [clang][Interp] Limit lambda capture lazy visting to actual captures
Author: Timm Bäder Date: 2024-06-07T13:29:23+02:00 New Revision: b8cc85b318c0dd89e4dd69e3691ffcad5e401885 URL: https://github.com/llvm/llvm-project/commit/b8cc85b318c0dd89e4dd69e3691ffcad5e401885 DIFF: https://github.com/llvm/llvm-project/commit/b8cc85b318c0dd89e4dd69e3691ffcad5e401885.diff LOG: [clang][Interp] Limit lambda capture lazy visting to actual captures Check this by looking at the VarDecl. Added: Modified: clang/lib/AST/Interp/ByteCodeExprGen.cpp clang/test/AST/Interp/lambda.cpp Removed: diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp b/clang/lib/AST/Interp/ByteCodeExprGen.cpp index 8dc71b2527f3b..ff2b51e3fb6fa 100644 --- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp +++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp @@ -3895,12 +3895,13 @@ bool ByteCodeExprGen::visitDeclRef(const ValueDecl *D, const Expr *E) { return this->emitGetThisFieldPtr(Offset, E); return this->emitGetPtrThisField(Offset, E); } else if (const auto *DRE = dyn_cast(E); - DRE && DRE->refersToEnclosingVariableOrCapture() && - isa(D)) { -if (!this->visitVarDecl(cast(D))) - return false; -// Retry. -return this->visitDeclRef(D, E); + DRE && DRE->refersToEnclosingVariableOrCapture()) { +if (const auto *VD = dyn_cast(D); VD && VD->isInitCapture()) { + if (!this->visitVarDecl(cast(D))) +return false; + // Retry. + return this->visitDeclRef(D, E); +} } // Try to lazily visit (or emit dummy pointers for) declarations diff --git a/clang/test/AST/Interp/lambda.cpp b/clang/test/AST/Interp/lambda.cpp index 71e7077550b28..0eb12643b1b7f 100644 --- a/clang/test/AST/Interp/lambda.cpp +++ b/clang/test/AST/Interp/lambda.cpp @@ -267,3 +267,16 @@ namespace CaptureDefaults { constexpr auto t4 = ([x=42]() consteval { return x; }()); static_assert(t4 == 42, ""); + +namespace InvalidCapture { + + int &f(int *p); + char &f(...); + void g() { +int n = -1; // both-note {{declared here}} +[=] { + int arr[n]; // both-warning {{variable length arrays in C++ are a Clang extension}} \ + both-note {{read of non-const variable 'n' is not allowed in a constant expression}} +} (); + } +} ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 9eb8a13 - [clang][Interp][NFC] Fix a const-correctness warning
Author: Timm Bäder Date: 2024-06-07T13:29:23+02:00 New Revision: 9eb8a130c5d708dbabe824113add072436ae9997 URL: https://github.com/llvm/llvm-project/commit/9eb8a130c5d708dbabe824113add072436ae9997 DIFF: https://github.com/llvm/llvm-project/commit/9eb8a130c5d708dbabe824113add072436ae9997.diff LOG: [clang][Interp][NFC] Fix a const-correctness warning Added: Modified: clang/lib/AST/Interp/MemberPointer.h Removed: diff --git a/clang/lib/AST/Interp/MemberPointer.h b/clang/lib/AST/Interp/MemberPointer.h index 5c61f6a439574..f56dc530431e4 100644 --- a/clang/lib/AST/Interp/MemberPointer.h +++ b/clang/lib/AST/Interp/MemberPointer.h @@ -86,7 +86,7 @@ class MemberPointer final { bool hasBase() const { return !Base.isZero(); } void print(llvm::raw_ostream &OS) const { -OS << "MemberPtr(" << Base << " " << (void *)Dcl << " + " << PtrOffset +OS << "MemberPtr(" << Base << " " << (const void *)Dcl << " + " << PtrOffset << ")"; } ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [libcxx] [clang] Preserve Qualifiers and type sugar in TemplateNames (PR #93433)
kadircet wrote: so after this patch, clang seems to be crashing on: ```cpp template struct map {}; template class foo {}; template class MapType, typename Value> Value bar(MapType map); template class MapType, typename Value> Value bar(MapType> map); void aux() { map> input; bar(input); } ``` stack trace: ``` $ ./bin/clang -fsyntax-only -xc++ -std=c++20 -Wno-everything foo.cc clang: /usr/local/google/home/kadircet/repos/llvm/clang/lib/Sema/SemaTemplateDeduction.cpp:596: TemplateDeductionResult DeduceTemplateArguments(Sema &, TemplateParameterList *, TemplateName, TemplateName, TemplateDeductionInfo &, ArrayRef, SmallVectorImpl &): Assertion `DefaultArguments.size() <= As->size()' failed. PLEASE submit a bug report to https://github.com/llvm/llvm-project/issues/ and include the crash backtrace, preprocessed source, and associated run script. Stack dump: 0. Program arguments: ./bin/clang -fsyntax-only -xc++ -std=c++20 -Wno-everything myreduce.cc 1. myreduce.cc:12:12: current parser token ')' 2. myreduce.cc:10:12: parsing function body 'aux' 3. myreduce.cc:10:12: in compound statement ('{}') #0 0x561942c22558 llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) /usr/local/google/home/kadircet/repos/llvm/llvm/lib/Support/Unix/Signals.inc:723:13 #1 0x561942c2011e llvm::sys::RunSignalHandlers() /usr/local/google/home/kadircet/repos/llvm/llvm/lib/Support/Signals.cpp:106:18 #2 0x561942b8c686 HandleCrash /usr/local/google/home/kadircet/repos/llvm/llvm/lib/Support/CrashRecoveryContext.cpp:73:5 #3 0x561942b8c686 CrashRecoverySignalHandler(int) /usr/local/google/home/kadircet/repos/llvm/llvm/lib/Support/CrashRecoveryContext.cpp:390:51 #4 0x7fa5f6e5a510 (/lib/x86_64-linux-gnu/libc.so.6+0x3c510) #5 0x7fa5f6ea816c __pthread_kill_implementation ./nptl/pthread_kill.c:44:76 #6 0x7fa5f6e5a472 raise ./signal/../sysdeps/posix/raise.c:27:6 #7 0x7fa5f6e444b2 abort ./stdlib/abort.c:81:7 #8 0x7fa5f6e443d5 _nl_load_domain ./intl/loadmsgcat.c:1177:9 #9 0x7fa5f6e533a2 (/lib/x86_64-linux-gnu/libc.so.6+0x353a2) #10 0x561945cbacbc set_size /usr/local/google/home/kadircet/repos/llvm/llvm/include/llvm/ADT/SmallVector.h:102:5 #11 0x561945cbacbc resizeImpl /usr/local/google/home/kadircet/repos/llvm/llvm/include/llvm/ADT/SmallVector.h:647:11 #12 0x561945cbacbc resize /usr/local/google/home/kadircet/repos/llvm/llvm/include/llvm/ADT/SmallVector.h:651:30 #13 0x561945cbacbc SmallVector /usr/local/google/home/kadircet/repos/llvm/llvm/include/llvm/ADT/SmallVector.h:1220:11 #14 0x561945cbacbc DeduceTemplateArguments(clang::Sema&, clang::TemplateParameterList*, clang::TemplateName, clang::TemplateName, clang::sema::TemplateDeductionInfo&, llvm::ArrayRef, llvm::SmallVectorImpl&) /usr/local/google/home/kadircet/repos/llvm/clang/lib/Sema/SemaTemplateDeduction.cpp:597:37 #15 0x561945cbde14 DeduceTemplateSpecArguments(clang::Sema&, clang::TemplateParameterList*, clang::QualType, clang::QualType, clang::sema::TemplateDeductionInfo&, llvm::SmallVectorImpl&) /usr/local/google/home/kadircet/repos/llvm/clang/lib/Sema/SemaTemplateDeduction.cpp:717:13 #16 0x561945caf095 DeduceTemplateArgumentsByTypeMatch(clang::Sema&, clang::TemplateParameterList*, clang::QualType, clang::QualType, clang::sema::TemplateDeductionInfo&, llvm::SmallVectorImpl&, unsigned int, bool, bool) /usr/local/google/home/kadircet/repos/llvm/clang/lib/Sema/SemaTemplateDeduction.cpp:0:16 #17 0x561945cbd8e2 DeduceTemplateArguments(clang::Sema&, clang::TemplateParameterList*, clang::QualType const*, unsigned int, clang::QualType const*, unsigned int, clang::sema::TemplateDeductionInfo&, llvm::SmallVectorImpl&, unsigned int, bool) /usr/local/google/home/kadircet/repos/llvm/clang/lib/Sema/SemaTemplateDeduction.cpp:1223:44 #18 0x561945cb5910 isAtLeastAsSpecializedAs(clang::Sema&, clang::SourceLocation, clang::FunctionTemplateDecl const*, clang::FunctionTemplateDecl const*, clang::TemplatePartialOrderingContext, bool, llvm::SmallVector const&, llvm::SmallVector const&) /usr/local/google/home/kadircet/repos/llvm/clang/lib/Sema/SemaTemplateDeduction.cpp:0:0 #19 0x561945cb45df clang::Sema::getMoreSpecializedTemplate(clang::FunctionTemplateDecl*, clang::FunctionTemplateDecl*, clang::SourceLocation, clang::TemplatePartialOrderingContext, unsigned int, clang::QualType, clang::QualType, bool) /usr/local/google/home/kadircet/repos/llvm/clang/lib/Sema/SemaTemplateDeduction.cpp:0:18 #20 0x561945aef302 clang::isBetterOverloadCandidate(clang::Sema&, clang::OverloadCandidate const&, clang::OverloadCandidate const&, clang::SourceLocation, clang::OverloadCandidateSet::CandidateSetKind) /usr/local/google/home/kadircet/repos/llvm/clang/lib/Sema/SemaOverload.cpp:0:50 #21 0x561945ae0836 clang::OverloadCandidateSet::BestViableFunction(clang::Sema&, clang::SourceLocation, clang::OverloadCandidate*&) /usr/local/google/home/kadircet/repos/llvm/cla
[clang] [clang][AArch64] Add validation for Global Register Variable. (PR #94271)
https://github.com/kawashima-fj approved this pull request. Thanks for the fix. I left a minor suggestion. Some notes: - This commit make Clang emit `error: size of register '???' does not match variable size` error instead of `fatal error: error in backend: Invalid register name "???"`, regardless of the `-ffixed-???` option. - #76426 says "When `-ffixed-x15` is specified, it can be compiled.". When `-ffixed-x15` is specified, older revisions (including 18.1.x releases) compiles the program in #76426 without an error but the generated code is incorrect (the `foo` function is compiled into `mrs w0, NZCV; ret`!). Recent revisions emits `fatal error: error in backend: Invalid register name "x15".`. So make it a Clang error is appropriate. - GCC allows this variable-register size mismatch. Clang does not allow. - We don't need to use `starts_with_insensitive`. Register names are case-sensitive (same as GCC). https://github.com/llvm/llvm-project/pull/94271 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][AArch64] Add validation for Global Register Variable. (PR #94271)
@@ -0,0 +1,13 @@ +// Check that -ffixed register handled for globals. +// Regression test for #76426 +// RUN: %clang --target=aarch64-none-gnu -ffixed-x15 -### %s 2>&1 | FileCheck %s +// CHECK-NOT: fatal error: error in backend: Invalid register name "x15". kawashima-fj wrote: You modified Clang code but this error message is the one of the LLVM backend. Is it better to check the Clang-side message `error: size of register 'x15' does not match variable size`? https://github.com/llvm/llvm-project/pull/94271 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][AArch64] Add validation for Global Register Variable. (PR #94271)
https://github.com/kawashima-fj edited https://github.com/llvm/llvm-project/pull/94271 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Fix loss of `dllexport` for exported template specialization (PR #94664)
zmodem wrote: > > It would be nice to keep `GetOrCreateLLVMGlobal` and > > `GetOrCreateLLVMFunction` in sync. Would it be possible to extract the > > "Handle dropped DLL attributes" logic into a small utility function that > > could be called from both? > > I did briefly think about this, but does this change really apply to > `GetOrCreateLLVMGlobal`? Is there any test case to exercise it? Perhaps it > would be better to leave `GetOrCreateLLVMGlobal` as is? I think we should look at it the other way around: unless there's a reason that the functions should behave differently (and I'm not aware of any), it seems better for them to keep using the same logic. https://github.com/llvm/llvm-project/pull/94664 ___ 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 WarnOnSizeOfPointer mode to bugprone-sizeof-expression (PR #94356)
NagyDonat wrote: I re-ran the open source evaluation, and here is the clean diff that I promised (italicized notes are just copied from the old table): | Project | New Reports | Resolved Reports | Notes |-|-|--|--| | memcached | No reports | No reports | – | tmux | No reports | [23 resolved reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=tmux_2.6_old_sizeofexpressions_with_new_messages&newcheck=tmux_2.6_new_sizeofexpressions_rerun&diff-type=Resolved) | _reports seem to be FPs, including several ones that [use `qsort` in a clear and straightforward way](https://codechecker-demo.eastus.cloudapp.azure.com/Default/report-detail?run=tmux_2.6_old_sizeofexpressions&newcheck=tmux_2.6_new_sizeofexpressions&diff-type=Resolved&report-id=5493278&report-hash=e1dd82bffcf68169ff8fe7181ca44f16&report-filepath=%2Flocal%2Fpersistent_docker%2FCSA-measurements-driver-2894%2Fmeasurements_workspace%2Ftmux%2Fwindow-buffer.c)_ | curl | [3 new reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=curl_curl-7_66_0_old_sizeofexpressions_with_new_messages&newcheck=curl_curl-7_66_0_new_sizeofexpressions_rerun&diff-type=New) | [1 resolved reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=curl_curl-7_66_0_old_sizeofexpressions_with_new_messages&newcheck=curl_curl-7_66_0_new_sizeofexpressions_rerun&diff-type=Resolved) | _new reports are TPs (all reporting incorrect use of the same data structure), resolved one is FP_ | twin | No reports | No reports | – | vim | [1 new reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=vim_v8.2.1920_old_sizeofexpressions_with_new_messages&newcheck=vim_v8.2.1920_new_sizeofexpressions_rerun&diff-type=New) | No reports | _true positive_ | openssl | [23 new reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=openssl_openssl-3.0.0-alpha7_old_sizeofexpressions_with_new_messages_openssl_ffmpeg&newcheck=openssl_openssl-3.0.0-alpha7_new_sizeofexpressions_rerun_openssl_ffmpeg&diff-type=New) | [22 resolved reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=openssl_openssl-3.0.0-alpha7_old_sizeofexpressions_with_new_messages_openssl_ffmpeg&newcheck=openssl_openssl-3.0.0-alpha7_new_sizeofexpressions_rerun_openssl_ffmpeg&diff-type=Resolved) | resolved reports are FPs, new reports are mostly TPs or "works, but ugly and dodgy" code with a few FPs that look like `generic_function(&arg, sizeof(arg))` or `get_memory(length*sizeof(array[0]))` | sqlite | [11 new reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=sqlite_version-3.33.0_old_sizeofexpressions_with_new_messages&newcheck=sqlite_version-3.33.0_new_sizeofexpressions_rerun&diff-type=New) | No reports | _among the new results there are many FPs ([(1)](https://codechecker-demo.eastus.cloudapp.azure.com/Default/report-detail?run=sqlite_version-3.33.0_old_sizeofexpressions&newcheck=sqlite_version-3.33.0_new_sizeofexpressions&diff-type=New&report-id=5493379&report-hash=f411835e93b1711c2889d4bef2889db9&report-filepath=%2Flocal%2Fpersistent_docker%2FCSA-measurements-driver-2894%2Fmeasurements_workspace%2Fsqlite%2Fshell.c), [(2)](https://codechecker-demo.eastus.cloudapp.azure.com/Default/report-detail?run=sqlite_version-3.33.0_old_sizeofexpressions&newcheck=sqlite_version-3.33.0_new_sizeofexpressions&diff-type=New&report-id=5493385&report-hash=d9e3d0a984913130c821b7c18c2cc8d2&report-filepath=%2Flocal%2Fpersistent_docker%2FCSA-measurements-driver-2894%2Fmeasurements_workspace%2Fsqlite%2Fsqlite3.c)) that do things like `char **mem; realloc(mem, numElements*sizeof(mem[0]))`_ | ffmpeg | [22 new reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=ffmpeg_n4.3.1_old_sizeofexpressions_with_new_messages_openssl_ffmpeg&newcheck=ffmpeg_n4.3.1_new_sizeofexpressions_rerun_openssl_ffmpeg&diff-type=New) | [109 resolved reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=ffmpeg_n4.3.1_old_sizeofexpressions_with_new_messages_openssl_ffmpeg&newcheck=ffmpeg_n4.3.1_new_sizeofexpressions_rerun_openssl_ffmpeg&diff-type=Resolved) | postgres | No reports | [5 resolved reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=postgres_REL_13_0_old_sizeofexpressions_with_new_messages&newcheck=postgres_REL_13_0_new_sizeofexpressions_rerun&diff-type=Resolved) | _resolved reports are FPs_ | tinyxml2 | No reports | No reports | – | libwebm | No reports | No reports | – | xerces | [1 new reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=xerces_v3.2.3_old_sizeofexpressions_with_new_messages&newcheck=xerces_v3.2.3_new_sizeofexpressions_rerun&diff-type=New) | No reports | true positive, seems to be an ugly bug | bitcoin | [1 new reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=bitcoin_v0.20
[clang] Testing32 bit for https://github.com/llvm/llvm-project/pull/92083 (PR #94603)
ChuanqiXu9 wrote: Thank you very much! https://github.com/llvm/llvm-project/pull/94603 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer] Refine invalidation caused by `fread` (PR #93408)
@@ -0,0 +1,443 @@ +// RUN: %clang_analyze_cc1 -verify %s \ +// RUN: -triple x86_64-linux-gnu \ +// RUN: -analyzer-checker=core,unix.Stream,alpha.security.taint \ +// RUN: -analyzer-checker=debug.ExprInspection + +#include "Inputs/system-header-simulator-for-simple-stream.h" + +#define EOF (-1) + +void clang_analyzer_dump(int); +void clang_analyzer_isTainted(int); +void clang_analyzer_warnIfReached(void); + +// A stream is only tracked by StreamChecker if it results from a call to "fopen". +// Otherwise, there is no specific modelling of "fread". +void untracked_stream(FILE *fp) { + char c; + if (1 == fread(&c, 1, 1, fp)) { +char p = c; // Unknown value but not garbage and not modeled by checker. + } else { +char p = c; // Possibly indeterminate value but not modeled by checker. + } +} + +void fgetc_props_taint(void) { + FILE *fp = fopen("/home/test", "rb+"); + if (fp) { +int c = fgetc(fp); // c is tainted. +if (c != EOF) { + clang_analyzer_isTainted(c); // expected-warning{{YES}} +} +fclose(fp); + } +} + +void fread_props_taint(void) { + FILE *fp = fopen("/home/test", "rb+"); + if (fp) { +char buffer[10]; +int c = fread(buffer, 1, 10, fp); // c is tainted. +if (c != 10) { + // If the read failed, then the number of bytes successfully read should be tainted. + clang_analyzer_isTainted(c); // expected-warning{{YES}} +} +fclose(fp); + } +} + +void read_one_byte1(void) { + FILE *fp = fopen("/home/test", "rb+"); + if (fp) { +char c; +if (1 == fread(&c, 1, 1, fp)) { + char p = c; // Unknown value but not garbage. + clang_analyzer_isTainted(p); // expected-warning{{YES}} +} else { + char p = c; // Possibly indeterminate value but not modeled by checker. + clang_analyzer_isTainted(p); // expected-warning{{YES}} +} +fclose(fp); + } +} + +void read_one_byte2(char *buffer) { + FILE *fp = fopen("/home/test", "rb+"); + if (fp) { +if (1 == fread(buffer, 1, 1, fp)) { + char p = buffer[0]; // Unknown value but not garbage. + clang_analyzer_isTainted(p); // expected-warning{{YES}} +} else { + char p = buffer[0]; // Possibly indeterminate value but not modeled by checker. + clang_analyzer_isTainted(p); // expected-warning{{YES}} +} +fclose(fp); + } +} + +void read_one_byte3(char *buffer) { + buffer[1] = 10; + FILE *fp = fopen("/home/test", "rb+"); + if (fp) { +// buffer[1] is not mutated by fread and remains not tainted. +fread(buffer, 1, 1, fp); +char p = buffer[1]; +clang_analyzer_isTainted(p); // expected-warning{{NO}} +clang_analyzer_dump(buffer[1]); // expected-warning{{10 S32b}} +fclose(fp); + } +} + +void read_many_bytes(char *buffer) { + FILE *fp = fopen("/home/test", "rb+"); + if (fp) { +if (42 == fread(buffer, 1, 42, fp)) { + char p = buffer[0]; // Unknown value but not garbage. + clang_analyzer_isTainted(p); // expected-warning{{YES}} +} else { + char p = buffer[0]; // Possibly indeterminate value but not modeled. + clang_analyzer_isTainted(p); // expected-warning{{YES}} +} +fclose(fp); + } +} + +void random_access_read1(int index) { + FILE *fp = fopen("/home/test", "rb+"); + if (fp) { +long c[4]; +int success = 2 == fread(c + 1, sizeof(long), 2, fp); + +switch (index) { +case 0: + // c[0] is not mutated by fread. + if (success) { +char p = c[0]; // expected-warning {{Assigned value is garbage or undefined}} We kept the first byte intact. + } else { +char p = c[0]; // expected-warning {{Assigned value is garbage or undefined}} We kept the first byte intact. + } + break; + +case 1: + if (success) { +// Unknown value but not garbage. +clang_analyzer_isTainted(c[1]); // expected-warning {{YES}} +clang_analyzer_dump(c[1]); // expected-warning {{conj_}} + } else { +// Possibly indeterminate value but not modeled. +clang_analyzer_isTainted(c[1]); // expected-warning {{YES}} +clang_analyzer_dump(c[1]); // expected-warning {{conj_}} + } + break; + +case 2: + if (success) { +long p = c[2]; // Unknown value but not garbage. +// FIXME: Taint analysis only marks the first byte of a memory region. See getPointeeOf in GenericTaintChecker.cpp. +clang_analyzer_isTainted(c[2]); // expected-warning {{NO}} +clang_analyzer_dump(c[2]); // expected-warning {{conj_}} + } else { +// Possibly indeterminate value but not modeled. +clang_analyzer_isTainted(c[2]); // expected-warning {{NO}} // FIXME: See above. +clang_analyzer_dump(c[2]); // expected-warning {{conj_}} + } + break; + +case 3: + // c[3] is not mutated by fread. + if (success) { +long p = c[3]; // expected-warning {{Assigned value is garbage or undefined}} + } else { +long p = c[3]; // exp
[clang] 5a0181f - [serialization] no transitive decl change (#92083)
Author: Chuanqi Xu Date: 2024-06-07T20:21:55+08:00 New Revision: 5a0181f568e56e37df80d0f74eca4775776fa8cd URL: https://github.com/llvm/llvm-project/commit/5a0181f568e56e37df80d0f74eca4775776fa8cd DIFF: https://github.com/llvm/llvm-project/commit/5a0181f568e56e37df80d0f74eca4775776fa8cd.diff LOG: [serialization] no transitive decl change (#92083) Following of https://github.com/llvm/llvm-project/pull/86912 The motivation of the patch series is that, for a module interface unit `X`, when the dependent modules of `X` changes, if the changes is not relevant with `X`, we hope the BMI of `X` won't change. For the specific patch, we hope if the changes was about irrelevant declaration changes, we hope the BMI of `X` won't change. **However**, I found the patch itself is not very useful in practice, since the adding or removing declarations, will change the state of identifiers and types in most cases. That said, for the most simple example, ``` // partA.cppm export module m:partA; // partA.v1.cppm export module m:partA; export void a() {} // partB.cppm export module m:partB; export void b() {} // m.cppm export module m; export import :partA; export import :partB; // onlyUseB; export module onlyUseB; import m; export inline void onluUseB() { b(); } ``` the BMI of `onlyUseB` will change after we change the implementation of `partA.cppm` to `partA.v1.cppm`. Since `partA.v1.cppm` introduces new identifiers and types (the function prototype). So in this patch, we have to write the tests as: ``` // partA.cppm export module m:partA; export int getA() { ... } export int getA2(int) { ... } // partA.v1.cppm export module m:partA; export int getA() { ... } export int getA(int) { ... } export int getA2(int) { ... } // partB.cppm export module m:partB; export void b() {} // m.cppm export module m; export import :partA; export import :partB; // onlyUseB; export module onlyUseB; import m; export inline void onluUseB() { b(); } ``` so that the new introduced declaration `int getA(int)` doesn't introduce new identifiers and types, then the BMI of `onlyUseB` can keep unchanged. While it looks not so great, the patch should be the base of the patch to erase the transitive change for identifiers and types since I don't know how can we introduce new types and identifiers without introducing new declarations. Given how tightly the relationship between declarations, types and identifiers, I think we can only reach the ideal state after we made the series for all of the three entties. The design of the patch is similar to https://github.com/llvm/llvm-project/pull/86912, which extends the 32-bit DeclID to 64-bit and use the higher bits to store the module file index and the lower bits to store the Local Decl ID. A slight difference is that we only use 48 bits to store the new DeclID since we try to use the higher 16 bits to store the module ID in the prefix of Decl class. Previously, we use 32 bits to store the module ID and 32 bits to store the DeclID. I don't want to allocate additional space so I tried to make the additional space the same as 64 bits. An potential interesting thing here is about the relationship between the module ID and the module file index. I feel we can get the module file index by the module ID. But I didn't prove it or implement it. Since I want to make the patch itself as small as possible. We can make it in the future if we want. Another change in the patch is the new concept Decl Index, which means the index of the very big array `DeclsLoaded` in ASTReader. Previously, the index of a loaded declaration is simply the Decl ID minus PREDEFINED_DECL_NUMs. So there are some places they got used ambiguously. But this patch tried to split these two concepts. As https://github.com/llvm/llvm-project/pull/86912 did, the change will increase the on-disk PCM file sizes. As the declaration ID may be the most IDs in the PCM file, this can have the biggest impact on the size. In my experiments, this change will bring 6.6% increase of the on-disk PCM size. No compile-time performance regression observed. Given the benefits in the motivation example, I think the cost is worthwhile. Added: clang/test/Modules/no-transitive-decls-change.cppm Modified: clang/include/clang/AST/ASTUnresolvedSet.h clang/include/clang/AST/DeclAccessPair.h clang/include/clang/AST/DeclBase.h clang/include/clang/AST/DeclID.h clang/include/clang/AST/UnresolvedSet.h clang/include/clang/Serialization/ASTBitCodes.h clang/include/clang/Serialization/ASTReader.h clang/include/clang/Serialization/ModuleFile.h clang/include/clang/Serialization/ModuleManager.h clang/lib/AST/DeclBase.cpp clang/lib/AST/DeclCXX.cpp clang/lib/Serialization/ASTReader.cpp clang/lib/Serialization/ASTReaderDecl.cpp clang/lib/Serialization/ASTWriter.cpp clang/lib/Serialization/ModuleFile.cpp Removed: ###
[clang] [serialization] no transitive decl change (PR #92083)
ChuanqiXu9 wrote: Thanks for testing. I've resent https://github.com/llvm/llvm-project/commit/5a0181f568e56e37df80d0f74eca4775776fa8cd. https://github.com/llvm/llvm-project/pull/92083 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer] Refine invalidation caused by `fread` (PR #93408)
@@ -0,0 +1,443 @@ +// RUN: %clang_analyze_cc1 -verify %s \ +// RUN: -triple x86_64-linux-gnu \ +// RUN: -analyzer-checker=core,unix.Stream,alpha.security.taint \ +// RUN: -analyzer-checker=debug.ExprInspection + +#include "Inputs/system-header-simulator-for-simple-stream.h" + +#define EOF (-1) + +void clang_analyzer_dump(int); +void clang_analyzer_isTainted(int); +void clang_analyzer_warnIfReached(void); + +// A stream is only tracked by StreamChecker if it results from a call to "fopen". +// Otherwise, there is no specific modelling of "fread". +void untracked_stream(FILE *fp) { + char c; + if (1 == fread(&c, 1, 1, fp)) { +char p = c; // Unknown value but not garbage and not modeled by checker. + } else { +char p = c; // Possibly indeterminate value but not modeled by checker. + } +} + +void fgetc_props_taint(void) { + FILE *fp = fopen("/home/test", "rb+"); + if (fp) { +int c = fgetc(fp); // c is tainted. +if (c != EOF) { + clang_analyzer_isTainted(c); // expected-warning{{YES}} +} +fclose(fp); + } +} + +void fread_props_taint(void) { + FILE *fp = fopen("/home/test", "rb+"); + if (fp) { +char buffer[10]; +int c = fread(buffer, 1, 10, fp); // c is tainted. +if (c != 10) { + // If the read failed, then the number of bytes successfully read should be tainted. + clang_analyzer_isTainted(c); // expected-warning{{YES}} +} +fclose(fp); + } +} + +void read_one_byte1(void) { + FILE *fp = fopen("/home/test", "rb+"); + if (fp) { +char c; +if (1 == fread(&c, 1, 1, fp)) { + char p = c; // Unknown value but not garbage. + clang_analyzer_isTainted(p); // expected-warning{{YES}} +} else { + char p = c; // Possibly indeterminate value but not modeled by checker. + clang_analyzer_isTainted(p); // expected-warning{{YES}} +} +fclose(fp); + } +} + +void read_one_byte2(char *buffer) { + FILE *fp = fopen("/home/test", "rb+"); + if (fp) { +if (1 == fread(buffer, 1, 1, fp)) { + char p = buffer[0]; // Unknown value but not garbage. + clang_analyzer_isTainted(p); // expected-warning{{YES}} +} else { + char p = buffer[0]; // Possibly indeterminate value but not modeled by checker. + clang_analyzer_isTainted(p); // expected-warning{{YES}} +} +fclose(fp); + } +} + +void read_one_byte3(char *buffer) { + buffer[1] = 10; + FILE *fp = fopen("/home/test", "rb+"); + if (fp) { +// buffer[1] is not mutated by fread and remains not tainted. +fread(buffer, 1, 1, fp); +char p = buffer[1]; +clang_analyzer_isTainted(p); // expected-warning{{NO}} +clang_analyzer_dump(buffer[1]); // expected-warning{{10 S32b}} +fclose(fp); + } +} + +void read_many_bytes(char *buffer) { + FILE *fp = fopen("/home/test", "rb+"); + if (fp) { +if (42 == fread(buffer, 1, 42, fp)) { + char p = buffer[0]; // Unknown value but not garbage. + clang_analyzer_isTainted(p); // expected-warning{{YES}} +} else { + char p = buffer[0]; // Possibly indeterminate value but not modeled. + clang_analyzer_isTainted(p); // expected-warning{{YES}} +} +fclose(fp); + } +} + +void random_access_read1(int index) { + FILE *fp = fopen("/home/test", "rb+"); + if (fp) { +long c[4]; +int success = 2 == fread(c + 1, sizeof(long), 2, fp); + +switch (index) { +case 0: + // c[0] is not mutated by fread. + if (success) { +char p = c[0]; // expected-warning {{Assigned value is garbage or undefined}} We kept the first byte intact. + } else { +char p = c[0]; // expected-warning {{Assigned value is garbage or undefined}} We kept the first byte intact. + } + break; + +case 1: + if (success) { +// Unknown value but not garbage. +clang_analyzer_isTainted(c[1]); // expected-warning {{YES}} +clang_analyzer_dump(c[1]); // expected-warning {{conj_}} + } else { +// Possibly indeterminate value but not modeled. +clang_analyzer_isTainted(c[1]); // expected-warning {{YES}} +clang_analyzer_dump(c[1]); // expected-warning {{conj_}} + } + break; + +case 2: + if (success) { +long p = c[2]; // Unknown value but not garbage. +// FIXME: Taint analysis only marks the first byte of a memory region. See getPointeeOf in GenericTaintChecker.cpp. +clang_analyzer_isTainted(c[2]); // expected-warning {{NO}} +clang_analyzer_dump(c[2]); // expected-warning {{conj_}} + } else { +// Possibly indeterminate value but not modeled. +clang_analyzer_isTainted(c[2]); // expected-warning {{NO}} // FIXME: See above. +clang_analyzer_dump(c[2]); // expected-warning {{conj_}} + } + break; + +case 3: + // c[3] is not mutated by fread. + if (success) { +long p = c[3]; // expected-warning {{Assigned value is garbage or undefined}} + } else { +long p = c[3]; // exp
[clang] [analyzer] Refine invalidation caused by `fread` (PR #93408)
@@ -0,0 +1,443 @@ +// RUN: %clang_analyze_cc1 -verify %s \ +// RUN: -triple x86_64-linux-gnu \ +// RUN: -analyzer-checker=core,unix.Stream,alpha.security.taint \ +// RUN: -analyzer-checker=debug.ExprInspection + +#include "Inputs/system-header-simulator-for-simple-stream.h" + +#define EOF (-1) + +void clang_analyzer_dump(int); +void clang_analyzer_isTainted(int); +void clang_analyzer_warnIfReached(void); + +// A stream is only tracked by StreamChecker if it results from a call to "fopen". +// Otherwise, there is no specific modelling of "fread". +void untracked_stream(FILE *fp) { + char c; + if (1 == fread(&c, 1, 1, fp)) { +char p = c; // Unknown value but not garbage and not modeled by checker. + } else { +char p = c; // Possibly indeterminate value but not modeled by checker. + } +} + +void fgetc_props_taint(void) { + FILE *fp = fopen("/home/test", "rb+"); + if (fp) { +int c = fgetc(fp); // c is tainted. +if (c != EOF) { + clang_analyzer_isTainted(c); // expected-warning{{YES}} +} +fclose(fp); + } +} + +void fread_props_taint(void) { + FILE *fp = fopen("/home/test", "rb+"); + if (fp) { +char buffer[10]; +int c = fread(buffer, 1, 10, fp); // c is tainted. +if (c != 10) { + // If the read failed, then the number of bytes successfully read should be tainted. + clang_analyzer_isTainted(c); // expected-warning{{YES}} +} +fclose(fp); + } +} + +void read_one_byte1(void) { + FILE *fp = fopen("/home/test", "rb+"); + if (fp) { +char c; +if (1 == fread(&c, 1, 1, fp)) { + char p = c; // Unknown value but not garbage. + clang_analyzer_isTainted(p); // expected-warning{{YES}} +} else { + char p = c; // Possibly indeterminate value but not modeled by checker. + clang_analyzer_isTainted(p); // expected-warning{{YES}} +} +fclose(fp); + } +} + +void read_one_byte2(char *buffer) { + FILE *fp = fopen("/home/test", "rb+"); + if (fp) { +if (1 == fread(buffer, 1, 1, fp)) { + char p = buffer[0]; // Unknown value but not garbage. + clang_analyzer_isTainted(p); // expected-warning{{YES}} +} else { + char p = buffer[0]; // Possibly indeterminate value but not modeled by checker. + clang_analyzer_isTainted(p); // expected-warning{{YES}} +} +fclose(fp); + } +} + +void read_one_byte3(char *buffer) { + buffer[1] = 10; + FILE *fp = fopen("/home/test", "rb+"); + if (fp) { +// buffer[1] is not mutated by fread and remains not tainted. +fread(buffer, 1, 1, fp); +char p = buffer[1]; +clang_analyzer_isTainted(p); // expected-warning{{NO}} +clang_analyzer_dump(buffer[1]); // expected-warning{{10 S32b}} +fclose(fp); + } +} + +void read_many_bytes(char *buffer) { + FILE *fp = fopen("/home/test", "rb+"); + if (fp) { +if (42 == fread(buffer, 1, 42, fp)) { + char p = buffer[0]; // Unknown value but not garbage. + clang_analyzer_isTainted(p); // expected-warning{{YES}} +} else { + char p = buffer[0]; // Possibly indeterminate value but not modeled. + clang_analyzer_isTainted(p); // expected-warning{{YES}} +} +fclose(fp); + } +} + +void random_access_read1(int index) { + FILE *fp = fopen("/home/test", "rb+"); + if (fp) { +long c[4]; +int success = 2 == fread(c + 1, sizeof(long), 2, fp); + +switch (index) { +case 0: + // c[0] is not mutated by fread. + if (success) { +char p = c[0]; // expected-warning {{Assigned value is garbage or undefined}} We kept the first byte intact. + } else { +char p = c[0]; // expected-warning {{Assigned value is garbage or undefined}} We kept the first byte intact. + } + break; + +case 1: + if (success) { +// Unknown value but not garbage. +clang_analyzer_isTainted(c[1]); // expected-warning {{YES}} +clang_analyzer_dump(c[1]); // expected-warning {{conj_}} + } else { +// Possibly indeterminate value but not modeled. +clang_analyzer_isTainted(c[1]); // expected-warning {{YES}} +clang_analyzer_dump(c[1]); // expected-warning {{conj_}} + } + break; + +case 2: + if (success) { +long p = c[2]; // Unknown value but not garbage. +// FIXME: Taint analysis only marks the first byte of a memory region. See getPointeeOf in GenericTaintChecker.cpp. +clang_analyzer_isTainted(c[2]); // expected-warning {{NO}} +clang_analyzer_dump(c[2]); // expected-warning {{conj_}} + } else { +// Possibly indeterminate value but not modeled. +clang_analyzer_isTainted(c[2]); // expected-warning {{NO}} // FIXME: See above. +clang_analyzer_dump(c[2]); // expected-warning {{conj_}} + } + break; + +case 3: + // c[3] is not mutated by fread. + if (success) { +long p = c[3]; // expected-warning {{Assigned value is garbage or undefined}} + } else { +long p = c[3]; // exp
[clang] [analyzer] Refine invalidation caused by `fread` (PR #93408)
https://github.com/steakhal updated https://github.com/llvm/llvm-project/pull/93408 >From f9e841ddaa865d529c806b2d115d5ddbc7109243 Mon Sep 17 00:00:00 2001 From: Balazs Benics Date: Sun, 26 May 2024 11:40:01 +0200 Subject: [PATCH 01/16] [analyzer] Refine invalidation caused by `fread` This change enables more accurate modeling of the write effects of `fread`. In particular, instead of invalidating the whole buffer, in a best-effort basis, we would try to invalidate the actually accesses elements of the buffer. This preserves the previous value of the buffer of the unaffected slots. As a result, diagnose more uninitialized buffer uses for example. Currently, this refined invalidation only triggers for `fread` if and only if the `count` parameter and the buffer pointer's index component are concrete or perfectly-constrained symbols. Additionally, if the `fread` would read more than 64 elements, the whole buffer is invalidated as before. This is to have safeguards against performance issues. Refer to the comments of the assertions in the following example to see the changes in the diagnostics: ```c++ void demo() { FILE *fp = fopen("/home/test", "rb+"); if (!fp) return; int buffer[10]; // uninitialized int read_items = fread(buffer+1, sizeof(int), 5, fp); if (5 == read_items) { int v1 = buffer[1]; // Unknown value but not garbage. clang_analyzer_isTainted(v1); // expected-warning {{YES}} <-- Would be "NO" without this patch. clang_analyzer_dump(v1); // expected-warning {{conj_}} <-- Not a "derived" symbol, so it's directly invalidated now. int v0 = buffer[0]; // expected-warning {{Assigned value is garbage or undefined}} <-- Had no report here before. (void)(v1 + v0); } else { // If 'fread' had an error. int v0 = buffer[0]; // expected-warning {{Assigned value is garbage or undefined}} <-- Had no report here before. (void)v0; } fclose(fp); } ``` [CPP-3247](https://sonarsource.atlassian.net/browse/CPP-3247) Patch by Marco Borgeaud (marco-antognini-sonarsource) --- .../StaticAnalyzer/Checkers/StreamChecker.cpp | 88 - clang/test/Analysis/fread.cpp | 328 ++ 2 files changed, 405 insertions(+), 11 deletions(-) create mode 100644 clang/test/Analysis/fread.cpp diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp index d4e020f7a72a0..7b42c4f72b322 100644 --- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp @@ -717,18 +717,71 @@ const ExplodedNode *StreamChecker::getAcquisitionSite(const ExplodedNode *N, return nullptr; } +/// Invalidate only the requested elements instead of the whole buffer. +/// This is basically a refinement of the more generic 'escapeArgs' or +/// the plain old 'invalidateRegions'. +/// This only works if the \p StartIndex and \p Count are concrete or +/// perfectly-constrained. +static ProgramStateRef +escapeByStartIndexAndCount(ProgramStateRef State, CheckerContext &C, + const CallEvent &Call, const MemRegion *Buffer, + QualType ElemType, SVal StartIndex, SVal Count) { + if (!llvm::isa_and_nonnull(Buffer)) +return State; + + auto UnboxAsInt = [&C, &State](SVal V) -> std::optional { +auto &SVB = C.getSValBuilder(); +if (const llvm::APSInt *Int = SVB.getKnownValue(State, V)) + return Int->tryExtValue(); +return std::nullopt; + }; + + auto StartIndexVal = UnboxAsInt(StartIndex); + auto CountVal = UnboxAsInt(Count); + + // FIXME: Maybe we could make this more generic, and expose this by the + // 'invalidateRegions' API. After doing so, it might make sense to make this + // limit configurable. + constexpr int MaxInvalidatedElementsLimit = 64; + if (!StartIndexVal || !CountVal || *CountVal > MaxInvalidatedElementsLimit) { +return State->invalidateRegions({loc::MemRegionVal{Buffer}}, +Call.getOriginExpr(), C.blockCount(), +C.getLocationContext(), +/*CausesPointerEscape=*/false); + } + + constexpr auto DoNotInvalidateSuperRegion = + RegionAndSymbolInvalidationTraits::InvalidationKinds:: + TK_DoNotInvalidateSuperRegion; + + auto &RegionManager = Buffer->getMemRegionManager(); + SmallVector EscapingVals; + EscapingVals.reserve(*CountVal); + + RegionAndSymbolInvalidationTraits ITraits; + for (auto Idx : llvm::seq(*StartIndexVal, *StartIndexVal + *CountVal)) { +NonLoc Index = C.getSValBuilder().makeArrayIndex(Idx); +const auto *Element = RegionManager.getElementRegion( +ElemType, Index, cast(Buffer), C.getASTContext()); +EscapingVals.push_back(loc::MemRegionVal(Element)); +ITraits.setTrait(Element, DoNotInvalidateSuperRegion); + } + return State->invalidateRegions(EscapingVals, Call.getOriginExpr(), +
[clang] [analyzer] Refine invalidation caused by `fread` (PR #93408)
https://github.com/steakhal updated https://github.com/llvm/llvm-project/pull/93408 >From f9e841ddaa865d529c806b2d115d5ddbc7109243 Mon Sep 17 00:00:00 2001 From: Balazs Benics Date: Sun, 26 May 2024 11:40:01 +0200 Subject: [PATCH 01/16] [analyzer] Refine invalidation caused by `fread` This change enables more accurate modeling of the write effects of `fread`. In particular, instead of invalidating the whole buffer, in a best-effort basis, we would try to invalidate the actually accesses elements of the buffer. This preserves the previous value of the buffer of the unaffected slots. As a result, diagnose more uninitialized buffer uses for example. Currently, this refined invalidation only triggers for `fread` if and only if the `count` parameter and the buffer pointer's index component are concrete or perfectly-constrained symbols. Additionally, if the `fread` would read more than 64 elements, the whole buffer is invalidated as before. This is to have safeguards against performance issues. Refer to the comments of the assertions in the following example to see the changes in the diagnostics: ```c++ void demo() { FILE *fp = fopen("/home/test", "rb+"); if (!fp) return; int buffer[10]; // uninitialized int read_items = fread(buffer+1, sizeof(int), 5, fp); if (5 == read_items) { int v1 = buffer[1]; // Unknown value but not garbage. clang_analyzer_isTainted(v1); // expected-warning {{YES}} <-- Would be "NO" without this patch. clang_analyzer_dump(v1); // expected-warning {{conj_}} <-- Not a "derived" symbol, so it's directly invalidated now. int v0 = buffer[0]; // expected-warning {{Assigned value is garbage or undefined}} <-- Had no report here before. (void)(v1 + v0); } else { // If 'fread' had an error. int v0 = buffer[0]; // expected-warning {{Assigned value is garbage or undefined}} <-- Had no report here before. (void)v0; } fclose(fp); } ``` [CPP-3247](https://sonarsource.atlassian.net/browse/CPP-3247) Patch by Marco Borgeaud (marco-antognini-sonarsource) --- .../StaticAnalyzer/Checkers/StreamChecker.cpp | 88 - clang/test/Analysis/fread.cpp | 328 ++ 2 files changed, 405 insertions(+), 11 deletions(-) create mode 100644 clang/test/Analysis/fread.cpp diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp index d4e020f7a72a0..7b42c4f72b322 100644 --- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp @@ -717,18 +717,71 @@ const ExplodedNode *StreamChecker::getAcquisitionSite(const ExplodedNode *N, return nullptr; } +/// Invalidate only the requested elements instead of the whole buffer. +/// This is basically a refinement of the more generic 'escapeArgs' or +/// the plain old 'invalidateRegions'. +/// This only works if the \p StartIndex and \p Count are concrete or +/// perfectly-constrained. +static ProgramStateRef +escapeByStartIndexAndCount(ProgramStateRef State, CheckerContext &C, + const CallEvent &Call, const MemRegion *Buffer, + QualType ElemType, SVal StartIndex, SVal Count) { + if (!llvm::isa_and_nonnull(Buffer)) +return State; + + auto UnboxAsInt = [&C, &State](SVal V) -> std::optional { +auto &SVB = C.getSValBuilder(); +if (const llvm::APSInt *Int = SVB.getKnownValue(State, V)) + return Int->tryExtValue(); +return std::nullopt; + }; + + auto StartIndexVal = UnboxAsInt(StartIndex); + auto CountVal = UnboxAsInt(Count); + + // FIXME: Maybe we could make this more generic, and expose this by the + // 'invalidateRegions' API. After doing so, it might make sense to make this + // limit configurable. + constexpr int MaxInvalidatedElementsLimit = 64; + if (!StartIndexVal || !CountVal || *CountVal > MaxInvalidatedElementsLimit) { +return State->invalidateRegions({loc::MemRegionVal{Buffer}}, +Call.getOriginExpr(), C.blockCount(), +C.getLocationContext(), +/*CausesPointerEscape=*/false); + } + + constexpr auto DoNotInvalidateSuperRegion = + RegionAndSymbolInvalidationTraits::InvalidationKinds:: + TK_DoNotInvalidateSuperRegion; + + auto &RegionManager = Buffer->getMemRegionManager(); + SmallVector EscapingVals; + EscapingVals.reserve(*CountVal); + + RegionAndSymbolInvalidationTraits ITraits; + for (auto Idx : llvm::seq(*StartIndexVal, *StartIndexVal + *CountVal)) { +NonLoc Index = C.getSValBuilder().makeArrayIndex(Idx); +const auto *Element = RegionManager.getElementRegion( +ElemType, Index, cast(Buffer), C.getASTContext()); +EscapingVals.push_back(loc::MemRegionVal(Element)); +ITraits.setTrait(Element, DoNotInvalidateSuperRegion); + } + return State->invalidateRegions(EscapingVals, Call.getOriginExpr(), +