[PATCH] D153612: [clang][analyzer] Add and change NoteTags in StdLibraryFunctionsChecker.

2023-06-27 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added inline comments.



Comment at: 
clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp:1299
+// StdLibraryFunctionsChecker.
+ExplodedNode *Pred = const_cast(Node);
+if (!Case.getNote().empty()) {

donat.nagy wrote:
> Can you explain why is it safe to use `const_cast` here? (I don't see any 
> concrete issue, but the engine has lots of invariants / unwritten rules and I 
> fear that this might break one of them.)
The node `Pred` should be modified only later when a successor is added 
(`addTransition` has non-const parameter).



Comment at: 
clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp:1309
+[Node, Note](PathSensitiveBugReport &BR) -> std::string {
+  if (Node->succ_size() > 1)
+return Note.str();

donat.nagy wrote:
> It's surprising to see this check inside the lambda, as its result does not 
> depend on `BR`. My best guess is that it's performed here because the 
> successors of `Node` will appear between the execution of the surrounding 
> code and the execution of this lambda.
> 
> However, CheckerContext.h line 69-70 claims that "checkers should not retain 
> the node in their state since the nodes might get invalidated." which would 
> imply that the captured `Node` might be invalid when the lambda is called.
This check is to decide if multiple cases could be applied, the same as if we 
count how many times this place in the loop is executed (add a transition for a 
case, constraints could be applied). This check is problematic because other 
checkers can apply state splits before this checker is executed or after it, in 
this way `StreamChecker` interferes with this code (it has a state split for 
success/failure cases of same function, and here we see only that a single case 
is applied on one branch). This is why this check is only used in the 
`EvalCallAsPure` case (theoretically still another checker can make a state 
split in PostCall before this where the same constraint is applied, then the 
problem occurs again).

I made a solution that does not have this check but has 2 case loops instead, 
but the mentioned problem (which exists when `if (Summary.getInvalidationKd() 
== EvalCallAsPure)` is not used) did not go away. And it may not work to search 
backwards for the first node with the same statement, because maybe not the 
first one is where a state split is done.

I only think that if this lambda is called with the saved node, that node is 
not invalid because it is part of a bug report call sequence.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153612/new/

https://reviews.llvm.org/D153612

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153652: [Support] Don't set "all_exe" mode by default for file written by llvm::writeToOutput

2023-06-27 Thread James Henderson via Phabricator via cfe-commits
jhenderson added a comment.

The updated unit test is failing on Windows in the pre-merge checks. Please 
investigate and fix as appropriate.




Comment at: llvm/unittests/Support/raw_ostream_test.cpp:500
+  ASSERT_TRUE(!!Perms);
+  EXPECT_EQ(0, *Perms & llvm::sys::fs::all_exe);
+

Here and below, rather than just checking the all_exe bit, let's check the 
permissions are exactly what are expected (e.g. does it have the read/write 
perms?). 


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153652/new/

https://reviews.llvm.org/D153652

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153836: [RISCV] Bump vector crypto to v1.0.0-rc1

2023-06-27 Thread Brandon Wu via Phabricator via cfe-commits
4vtomat created this revision.
Herald added subscribers: jobnoorman, luke, VincentWu, vkmr, frasercrmck, 
jdoerfert, luismarques, apazos, sameer.abuasal, s.egerton, Jim, benna, psnobl, 
jocewei, PkmX, the_o, brucehoult, MartinMosbeck, rogfer01, edward-jones, 
zzheng, jrtc27, shiva0217, kito-cheng, niosHD, sabuasal, simoncook, johnrusso, 
rbar, asb, hiraditya, arichardson.
Herald added a project: All.
4vtomat requested review of this revision.
Herald added subscribers: llvm-commits, cfe-commits, wangpc, eopXD, MaskRay.
Herald added projects: clang, LLVM.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D153836

Files:
  clang/test/Preprocessor/riscv-target-features.c
  llvm/docs/RISCVUsage.rst
  llvm/lib/Support/RISCVISAInfo.cpp
  llvm/lib/Target/RISCV/RISCVInstrInfoZvk.td
  llvm/test/CodeGen/RISCV/attributes.ll
  llvm/test/MC/RISCV/attribute-arch.s

Index: llvm/test/MC/RISCV/attribute-arch.s
===
--- llvm/test/MC/RISCV/attribute-arch.s
+++ llvm/test/MC/RISCV/attribute-arch.s
@@ -111,50 +111,50 @@
 .attribute arch, "rv32izbc1p0"
 # CHECK: attribute  5, "rv32i2p1_zbc1p0"
 
-.attribute arch, "rv32i_zve64x_zvbb0p9"
-# CHECK: attribute  5, "rv32i2p1_zicsr2p0_zvbb0p9_zve32x1p0_zve64x1p0_zvl32b1p0_zvl64b1p0"
+.attribute arch, "rv32i_zve64x_zvbb1p0"
+# CHECK: attribute  5, "rv32i2p1_zicsr2p0_zvbb1p0_zve32x1p0_zve64x1p0_zvl32b1p0_zvl64b1p0"
 
-.attribute arch, "rv32i_zve64x_zvbc0p9"
-# CHECK: attribute  5, "rv32i2p1_zicsr2p0_zvbc0p9_zve32x1p0_zve64x1p0_zvl32b1p0_zvl64b1p0"
+.attribute arch, "rv32i_zve64x_zvbc1p0"
+# CHECK: attribute  5, "rv32i2p1_zicsr2p0_zvbc1p0_zve32x1p0_zve64x1p0_zvl32b1p0_zvl64b1p0"
 
-.attribute arch, "rv32i_zve32x_zvkg0p9"
-# CHECK: attribute  5, "rv32i2p1_zicsr2p0_zve32x1p0_zvkg0p9_zvl32b1p0"
+.attribute arch, "rv32i_zve32x_zvkg1p0"
+# CHECK: attribute  5, "rv32i2p1_zicsr2p0_zve32x1p0_zvkg1p0_zvl32b1p0"
 
-.attribute arch, "rv32i_zve64x_zvkn0p9"
-# CHECK: attribute  5, "rv32i2p1_zicsr2p0_zvbb0p9_zve32x1p0_zve64x1p0_zvkn0p9_zvkned0p9_zvknha0p9_zvknhb0p9_zvkt0p9_zvl32b1p0_zvl64b1p0"
+.attribute arch, "rv32i_zve64x_zvkn1p0"
+# CHECK: attribute  5, "rv32i2p1_zicsr2p0_zvbb1p0_zve32x1p0_zve64x1p0_zvkn1p0_zvkned1p0_zvknha1p0_zvknhb1p0_zvkt1p0_zvl32b1p0_zvl64b1p0"
 
-.attribute arch, "rv32i_zve64x_zvknc0p9"
-# CHECK: attribute  5, "rv32i2p1_zicsr2p0_zvbb0p9_zvbc0p9_zve32x1p0_zve64x1p0_zvkn0p9_zvknc0p9_zvkned0p9_zvknha0p9_zvknhb0p9_zvkt0p9_zvl32b1p0_zvl64b1p0"
+.attribute arch, "rv32i_zve64x_zvknc1p0"
+# CHECK: attribute  5, "rv32i2p1_zicsr2p0_zvbb1p0_zvbc1p0_zve32x1p0_zve64x1p0_zvkn1p0_zvknc1p0_zvkned1p0_zvknha1p0_zvknhb1p0_zvkt1p0_zvl32b1p0_zvl64b1p0"
 
-.attribute arch, "rv32i_zve64x_zvkng0p9"
-# CHECK: attribute  5, "rv32i2p1_zicsr2p0_zvbb0p9_zve32x1p0_zve64x1p0_zvkg0p9_zvkn0p9_zvkned0p9_zvkng0p9_zvknha0p9_zvknhb0p9_zvkt0p9_zvl32b1p0_zvl64b1p0"
+.attribute arch, "rv32i_zve64x_zvkng1p0"
+# CHECK: attribute  5, "rv32i2p1_zicsr2p0_zvbb1p0_zve32x1p0_zve64x1p0_zvkg1p0_zvkn1p0_zvkned1p0_zvkng1p0_zvknha1p0_zvknhb1p0_zvkt1p0_zvl32b1p0_zvl64b1p0"
 
-.attribute arch, "rv32i_zve32x_zvknha0p9"
-# CHECK: attribute  5, "rv32i2p1_zicsr2p0_zve32x1p0_zvknha0p9_zvl32b1p0"
+.attribute arch, "rv32i_zve32x_zvknha1p0"
+# CHECK: attribute  5, "rv32i2p1_zicsr2p0_zve32x1p0_zvknha1p0_zvl32b1p0"
 
-.attribute arch, "rv32i_zve64x_zvknhb0p9"
-# CHECK: attribute  5, "rv32i2p1_zicsr2p0_zve32x1p0_zve64x1p0_zvknha0p9_zvknhb0p9_zvl32b1p0_zvl64b1p0"
+.attribute arch, "rv32i_zve64x_zvknhb1p0"
+# CHECK: attribute  5, "rv32i2p1_zicsr2p0_zve32x1p0_zve64x1p0_zvknha1p0_zvknhb1p0_zvl32b1p0_zvl64b1p0"
 
-.attribute arch, "rv32i_zve32x_zvkned0p9"
-# CHECK: attribute  5, "rv32i2p1_zicsr2p0_zve32x1p0_zvkned0p9_zvl32b1p0"
+.attribute arch, "rv32i_zve32x_zvkned1p0"
+# CHECK: attribute  5, "rv32i2p1_zicsr2p0_zve32x1p0_zvkned1p0_zvl32b1p0"
 
-.attribute arch, "rv32i_zve64x_zvks0p9"
-# CHECK: attribute  5, "rv32i2p1_zicsr2p0_zvbb0p9_zve32x1p0_zve64x1p0_zvks0p9_zvksed0p9_zvksh0p9_zvkt0p9_zvl32b1p0_zvl64b1p0"
+.attribute arch, "rv32i_zve64x_zvks1p0"
+# CHECK: attribute  5, "rv32i2p1_zicsr2p0_zvbb1p0_zve32x1p0_zve64x1p0_zvks1p0_zvksed1p0_zvksh1p0_zvkt1p0_zvl32b1p0_zvl64b1p0"
 
-.attribute arch, "rv32i_zve64x_zvksc0p9"
-# CHECK: attribute  5, "rv32i2p1_zicsr2p0_zvbb0p9_zvbc0p9_zve32x1p0_zve64x1p0_zvks0p9_zvksc0p9_zvksed0p9_zvksh0p9_zvkt0p9_zvl32b1p0_zvl64b1p0"
+.attribute arch, "rv32i_zve64x_zvksc1p0"
+# CHECK: attribute  5, "rv32i2p1_zicsr2p0_zvbb1p0_zvbc1p0_zve32x1p0_zve64x1p0_zvks1p0_zvksc1p0_zvksed1p0_zvksh1p0_zvkt1p0_zvl32b1p0_zvl64b1p0"
 
-.attribute arch, "rv32i_zve64x_zvksg0p9"
-# CHECK: attribute  5, "rv32i2p1_zicsr2p0_zvbb0p9_zve32x1p0_zve64x1p0_zvkg0p9_zvks0p9_zvksed0p9_zvksg0p9_zvksh0p9_zvkt0p9_zvl32b1p0_zvl64b1p0"
+.attribute arch, "rv32i_zve64x_zvksg1p0"
+# CHECK: attribute  5, "rv32i2p1_zicsr2p0_zvbb1p0_zve32x1p0_zve64x1p0_zvkg1p0_zvks1p0_zvksed1p0_zvksg1p

[PATCH] D152686: [clangd] Enforce strict unused includes by default

2023-06-27 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added a comment.

In D152686#4449481 , @cjdb wrote:

> This patch seems to have broken clangd for a project of mine. Most of my 
> headers are now flagged as not being directly used even though they're the 
> root header for the symbol.

replied on https://github.com/clangd/clangd/issues/1683


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D152686/new/

https://reviews.llvm.org/D152686

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153833: [clang][dataflow] Use namespace qualifiers when defining functions.

2023-06-27 Thread Martin Böhme via Phabricator via cfe-commits
mboehme added a comment.

Pre-merge failures look unrelated.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153833/new/

https://reviews.llvm.org/D153833

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D151397: [3/3][RISCV][POC] Model vxrm in C intrinsics for RVV fixed-point instruction vaadd, vasub

2023-06-27 Thread Zixuan Wu via Phabricator via cfe-commits
zixuan-wu added inline comments.



Comment at: clang/include/clang/Basic/riscv_vector.td:1734
+  __RISCV_VXRM_RDN = 2,
+  __RISCV_VXRM_ROD = 3,
+};

I am wondering if we need a dynamic mode enum which representing using current 
vxrm value? 


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D151397/new/

https://reviews.llvm.org/D151397

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D152989: Pre-commit test for D151696.

2023-06-27 Thread Freddy, Ye via Phabricator via cfe-commits
FreddyYe updated this revision to Diff 534861.
FreddyYe added a comment.

Added more checks for resolver function.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D152989/new/

https://reviews.llvm.org/D152989

Files:
  clang/test/CodeGen/attr-cpuspecific-cpus.c
  clang/test/CodeGen/attr-cpuspecific.c

Index: clang/test/CodeGen/attr-cpuspecific.c
===
--- clang/test/CodeGen/attr-cpuspecific.c
+++ clang/test/CodeGen/attr-cpuspecific.c
@@ -43,12 +43,18 @@
 void SingleVersion(void);
 // LINUX: define weak_odr ptr @SingleVersion.resolver()
 // LINUX: call void @__cpu_indicator_init
+// LINUX: %[[FEAT_INIT:.+]] = load i32, ptr getelementptr inbounds ({ i32, i32, i32, [1 x i32] }, ptr @__cpu_model, i32 0, i32 3, i32 0), align 4
+// LINUX: %[[FEAT_JOIN:.+]] = and i32 %[[FEAT_INIT]], 1023
+// LINUX: %[[FEAT_CHECK:.+]] = icmp eq i32 %[[FEAT_JOIN]], 1023
 // LINUX: ret ptr @SingleVersion.S
 // LINUX: call void @llvm.trap
 // LINUX: unreachable
 
 // WINDOWS: define weak_odr dso_local void @SingleVersion() comdat
 // WINDOWS: call void @__cpu_indicator_init()
+// WINDOWS: %[[FEAT_INIT:.+]] = load i32, ptr getelementptr inbounds ({ i32, i32, i32, [1 x i32] }, ptr @__cpu_model, i32 0, i32 3, i32 0), align 4
+// WINDOWS: %[[FEAT_JOIN:.+]] = and i32 %[[FEAT_INIT]], 1023
+// WINDOWS: %[[FEAT_CHECK:.+]] = icmp eq i32 %[[FEAT_JOIN]], 1023
 // WINDOWS: call void @SingleVersion.S()
 // WINDOWS-NEXT: ret void
 // WINDOWS: call void @llvm.trap
@@ -67,6 +73,9 @@
 void TwoVersions(void);
 // LINUX: define weak_odr ptr @TwoVersions.resolver()
 // LINUX: call void @__cpu_indicator_init
+// LINUX: %[[FEAT_INIT:.+]] = load i32, ptr getelementptr inbounds ({ i32, i32, i32, [1 x i32] }, ptr @__cpu_model, i32 0, i32 3, i32 0), align 4
+// LINUX: %[[FEAT_JOIN:.+]] = and i32 %[[FEAT_INIT]], 58836991
+// LINUX: %[[FEAT_CHECK:.+]] = icmp eq i32 %[[FEAT_JOIN]], 58836991
 // LINUX: ret ptr @TwoVersions.Z
 // LINUX: ret ptr @TwoVersions.S
 // LINUX: call void @llvm.trap
@@ -74,6 +83,9 @@
 
 // WINDOWS: define weak_odr dso_local void @TwoVersions() comdat
 // WINDOWS: call void @__cpu_indicator_init()
+// WINDOWS: %[[FEAT_INIT:.+]] = load i32, ptr getelementptr inbounds ({ i32, i32, i32, [1 x i32] }, ptr @__cpu_model, i32 0, i32 3, i32 0), align 4
+// WINDOWS: %[[FEAT_JOIN:.+]] = and i32 %[[FEAT_INIT]], 58836991
+// WINDOWS: %[[FEAT_CHECK:.+]] = icmp eq i32 %[[FEAT_JOIN]], 58836991
 // WINDOWS: call void @TwoVersions.Z()
 // WINDOWS-NEXT: ret void
 // WINDOWS: call void @TwoVersions.S()
Index: clang/test/CodeGen/attr-cpuspecific-cpus.c
===
--- /dev/null
+++ clang/test/CodeGen/attr-cpuspecific-cpus.c
@@ -0,0 +1,240 @@
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -emit-llvm -o - %s
+// RUN: %clang_cc1 -triple x86_64-windows-pc -fms-compatibility -emit-llvm -o - %s
+
+#ifdef _WIN64
+#define ATTR(X) __declspec(X)
+#else
+#define ATTR(X) __attribute__((X))
+#endif // _MSC_VER
+
+ATTR(cpu_dispatch(generic, pentium))
+void Version1(void);
+ATTR(cpu_specific(generic))
+void Version1(void){}
+ATTR(cpu_specific(pentium))
+void Version1(void){}
+
+ATTR(cpu_dispatch(generic, pentium_pro))
+void Version2(void);
+ATTR(cpu_specific(generic))
+void Version2(void){}
+ATTR(cpu_specific(pentium_pro))
+void Version2(void){}
+
+ATTR(cpu_dispatch(generic, pentium_mmx))
+void Version3(void);
+ATTR(cpu_specific(generic))
+void Version3(void){}
+ATTR(cpu_specific(pentium_mmx))
+void Version3(void){}
+
+ATTR(cpu_dispatch(generic, pentium_ii))
+void Version4(void);
+ATTR(cpu_specific(generic))
+void Version4(void){}
+ATTR(cpu_specific(pentium_ii))
+void Version4(void){}
+
+ATTR(cpu_dispatch(generic, pentium_iii))
+void Version5(void);
+ATTR(cpu_specific(generic))
+void Version5(void){}
+ATTR(cpu_specific(pentium_iii))
+void Version5(void){}
+
+ATTR(cpu_dispatch(generic, pentium_iii_no_xmm_regs))
+void Version6(void);
+ATTR(cpu_specific(generic))
+void Version6(void){}
+ATTR(cpu_specific(pentium_iii_no_xmm_regs))
+void Version6(void){}
+
+ATTR(cpu_dispatch(generic, pentium_4))
+void Version7(void);
+ATTR(cpu_specific(generic))
+void Version7(void){}
+ATTR(cpu_specific(pentium_4))
+void Version7(void){}
+
+ATTR(cpu_dispatch(generic, pentium_m))
+void Version8(void);
+ATTR(cpu_specific(generic))
+void Version8(void){}
+ATTR(cpu_specific(pentium_m))
+void Version8(void){}
+
+ATTR(cpu_dispatch(generic, pentium_4_sse3))
+void Version9(void);
+ATTR(cpu_specific(generic))
+void Version9(void){}
+ATTR(cpu_specific(pentium_4_sse3))
+void Version9(void){}
+
+ATTR(cpu_dispatch(generic, core_2_duo_ssse3))
+void Version10(void);
+ATTR(cpu_specific(generic))
+void Version10(void){}
+ATTR(cpu_specific(core_2_duo_ssse3))
+void Version10(void){}
+
+ATTR(cpu_dispatch(generic, core_2_duo_sse4_1))
+void Version11(void);
+ATTR(cpu_specific(generic))
+void Version11(void){}
+ATTR(cpu_specific(core_2_duo_sse4_1))
+void Versi

[clang-tools-extra] 8aa88ee - [clangd] Fix the flaky FindTarget unittest after 1b66840

2023-06-27 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2023-06-27T09:48:41+02:00
New Revision: 8aa88ee5e01df0daf08a3768fbf23fe655ad81c0

URL: 
https://github.com/llvm/llvm-project/commit/8aa88ee5e01df0daf08a3768fbf23fe655ad81c0
DIFF: 
https://github.com/llvm/llvm-project/commit/8aa88ee5e01df0daf08a3768fbf23fe655ad81c0.diff

LOG: [clangd] Fix the flaky FindTarget unittest after 1b66840

after 1b66840, FindTarget will report multiple refs with the same
location, make the sort order of the refs deterministic in
FindTargetTests.

Added: 


Modified: 
clang-tools-extra/clangd/unittests/FindTargetTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/unittests/FindTargetTests.cpp 
b/clang-tools-extra/clangd/unittests/FindTargetTests.cpp
index 64ac524fc5187..19e80658de063 100644
--- a/clang-tools-extra/clangd/unittests/FindTargetTests.cpp
+++ b/clang-tools-extra/clangd/unittests/FindTargetTests.cpp
@@ -1241,7 +1241,7 @@ class FindExplicitReferencesTest : public ::testing::Test 
{
   AllRefs annotatedReferences(llvm::StringRef Code, ParsedAST &AST,
   std::vector Refs) {
 auto &SM = AST.getSourceManager();
-llvm::sort(Refs, [&](const ReferenceLoc &L, const ReferenceLoc &R) {
+llvm::stable_sort(Refs, [&](const ReferenceLoc &L, const ReferenceLoc &R) {
   return SM.isBeforeInTranslationUnit(L.NameLoc, R.NameLoc);
 });
 



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153314: [clang] Replace uses of CGBuilderTy::CreateElementBitCast (NFC)

2023-06-27 Thread Nikita Popov via Phabricator via cfe-commits
nikic added inline comments.



Comment at: clang/lib/CodeGen/Targets/AArch64.cpp:522-523
 auto *Load = CGF.Builder.CreateLoad(VAListAddr);
 Address Addr = Address(Load, CGF.Int8Ty, SlotSize);
-return CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
+return Addr.withElementType(CGF.ConvertTypeForMem(Ty));
   }




Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153314/new/

https://reviews.llvm.org/D153314

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153776: [clang][analyzer] Display notes in StdLibraryFunctionsChecker only if interesting

2023-06-27 Thread Balázs Kéri via Phabricator via cfe-commits
balazske updated this revision to Diff 534868.
balazske added a comment.

`markInteresting` must be used at arguments found to be invalid


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153776/new/

https://reviews.llvm.org/D153776

Files:
  clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
  clang/test/Analysis/errno-stdlibraryfunctions-notes.c
  clang/test/Analysis/std-c-library-functions-arg-constraints-note-tags.cpp
  clang/test/Analysis/std-c-library-functions-arg-constraints.c
  clang/test/Analysis/std-c-library-functions-path-notes.c
  clang/test/Analysis/stream-errno-note.c
  clang/test/Analysis/stream-note.c

Index: clang/test/Analysis/stream-note.c
===
--- clang/test/Analysis/stream-note.c
+++ clang/test/Analysis/stream-note.c
@@ -13,7 +13,6 @@
 // expected-note@-2 {{Taking false branch}}
 return;
   FILE *F2 = tmpfile();
-  // stdargs-note@-1 {{call is successful}}
   if (!F2) {
 // expected-note@-1 {{'F2' is non-null}}
 // expected-note@-2 {{Taking false branch}}
@@ -22,7 +21,6 @@
   }
   rewind(F2);
   fclose(F2);
-  // stdargs-note@-1 {{call fails}}
   rewind(F1);
 }
 // expected-warning@-1 {{Opened stream never closed. Potential resource leak}}
@@ -59,7 +57,6 @@
 void check_note_leak_2(int c) {
   FILE *F1 = fopen("foo1.c", "r"); // expected-note {{Stream opened here}}
   // stdargs-note@-1 {{call is successful}}
-  // stdargs-note@-2 {{call is successful}}
   if (!F1)
 // expected-note@-1 {{'F1' is non-null}}
 // expected-note@-2 {{Taking false branch}}
@@ -68,7 +65,6 @@
 return;
   FILE *F2 = fopen("foo2.c", "r"); // expected-note {{Stream opened here}}
   // stdargs-note@-1 {{call is successful}}
-  // stdargs-note@-2 {{call is successful}}
   if (!F2) {
 // expected-note@-1 {{'F2' is non-null}}
 // expected-note@-2 {{Taking false branch}}
@@ -107,7 +103,6 @@
   FILE *F;
   char Buf[10];
   F = fopen("foo1.c", "r");
-  // stdargs-note@-1 {{call is successful}}
   if (F == NULL) { // expected-note {{Taking false branch}} expected-note {{'F' is not equal to NULL}}
 return;
   }
@@ -127,7 +122,6 @@
   FILE *F;
   char Buf[10];
   F = fopen("foo1.c", "r");
-  // stdargs-note@-1 {{call is successful}}
   if (F == NULL) { // expected-note {{Taking false branch}} expected-note {{'F' is not equal to NULL}}
 return;
   }
@@ -151,7 +145,6 @@
   FILE *F;
   char Buf[10];
   F = fopen("foo1.c", "r");
-  // stdargs-note@-1 {{call is successful}}
   if (F == NULL) // expected-note {{Taking false branch}} expected-note {{'F' is not equal to NULL}}
 return;
   int RRet = fread(Buf, 1, 1, F); // expected-note {{Assuming stream reaches end-of-file here}}
Index: clang/test/Analysis/stream-errno-note.c
===
--- clang/test/Analysis/stream-errno-note.c
+++ clang/test/Analysis/stream-errno-note.c
@@ -11,7 +11,6 @@
 void check_fopen(void) {
   FILE *F = fopen("xxx", "r");
   // expected-note@-1{{'errno' may be undefined after successful call to 'fopen'}}
-  // expected-note@-2{{call is successful}}
   // expected-note@+2{{'F' is non-null}}
   // expected-note@+1{{Taking false branch}}
   if (!F)
@@ -24,7 +23,6 @@
 void check_tmpfile(void) {
   FILE *F = tmpfile();
   // expected-note@-1{{'errno' may be undefined after successful call to 'tmpfile'}}
-  // expected-note@-2{{call is successful}}
   // expected-note@+2{{'F' is non-null}}
   // expected-note@+1{{Taking false branch}}
   if (!F)
@@ -36,14 +34,12 @@
 
 void check_freopen(void) {
   FILE *F = tmpfile();
-  // expected-note@-1{{call is successful}}
   // expected-note@+2{{'F' is non-null}}
   // expected-note@+1{{Taking false branch}}
   if (!F)
 return;
   F = freopen("xxx", "w", F);
   // expected-note@-1{{'errno' may be undefined after successful call to 'freopen'}}
-  // expected-note@-2{{call is successful}}
   // expected-note@+2{{'F' is non-null}}
   // expected-note@+1{{Taking false branch}}
   if (!F)
@@ -55,14 +51,12 @@
 
 void check_fclose(void) {
   FILE *F = tmpfile();
-  // expected-note@-1{{call is successful}}
   // expected-note@+2{{'F' is non-null}}
   // expected-note@+1{{Taking false branch}}
   if (!F)
 return;
   (void)fclose(F);
   // expected-note@-1{{'errno' may be undefined after successful call to 'fclose'}}
-  // expected-note@-2{{call is successful}}
   if (errno) {} // expected-warning{{An undefined value may be read from 'errno'}}
   // expected-note@-1{{An undefined value may be read from 'errno'}}
 }
@@ -70,7 +64,6 @@
 void check_fread(void) {
   char Buf[10];
   FILE *F = tmpfile();
-  // expected-note@-1{{call is successful}}
   // expected-note@+2{{'F' is non-null}}
   // expected-note@+1{{Taking false branch}}
   if (!F)
@@ -85,7 +78,6 @@
 void check_fwrite(void) {
   char Buf[] = "0123456789";
   FILE *F = tmpfile();
-  // expected-note@-1{{call is successful}}
   // expected-

[PATCH] D153776: [clang][analyzer] Display notes in StdLibraryFunctionsChecker only if interesting

2023-06-27 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added a comment.

Here 

 are results for vim, still the fileno problem is not fixed. This run was made 
before the last update where `markInteresting` is added, then it should work.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153776/new/

https://reviews.llvm.org/D153776

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] dc6f5c9 - [Clang][Sema] Do not try to analyze dependent alignment during -Wcast-align

2023-06-27 Thread via cfe-commits

Author: serge-sans-paille
Date: 2023-06-27T10:29:09+02:00
New Revision: dc6f5c9b588adfe62449a898ebd06a5a09c05439

URL: 
https://github.com/llvm/llvm-project/commit/dc6f5c9b588adfe62449a898ebd06a5a09c05439
DIFF: 
https://github.com/llvm/llvm-project/commit/dc6f5c9b588adfe62449a898ebd06a5a09c05439.diff

LOG: [Clang][Sema] Do not try to analyze dependent alignment during -Wcast-align

Fix #63007

Differential Revision: https://reviews.llvm.org/D151753

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaChecking.cpp
clang/test/SemaCXX/warn-cast-align.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index c022e9ffb6604..bc6366b36fd4d 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -370,6 +370,7 @@ Improvements to Clang's diagnostics
 - Clang now diagnoses unexpected tokens after a
   ``#pragma clang|GCC diagnostic push|pop`` directive.
   (`#13920: `_)
+- Clang now does not try to analyze cast validity on variables with dependent 
alignment (`#63007: `_).
 
 Bug Fixes in This Version
 -

diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 6969cf147ffbd..ffda87ac87d7a 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -16351,8 +16351,12 @@ std::optional(cast(E)->getDecl())) {
   // FIXME: If VD is captured by copy or is an escaping __block variable,
   // use the alignment of VD's type.
-  if (!VD->getType()->isReferenceType())
+  if (!VD->getType()->isReferenceType()) {
+// Dependent alignment cannot be resolved -> bail out.
+if (VD->hasDependentAlignment())
+  break;
 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
+  }
   if (VD->hasInit())
 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
 }

diff  --git a/clang/test/SemaCXX/warn-cast-align.cpp 
b/clang/test/SemaCXX/warn-cast-align.cpp
index 1e84ba9cd67af..855fac4dffc25 100644
--- a/clang/test/SemaCXX/warn-cast-align.cpp
+++ b/clang/test/SemaCXX/warn-cast-align.cpp
@@ -44,6 +44,11 @@ void test1(void *P) {
   c = IntPtr(P);
 }
 
+template  void DependentAlign() {
+  alignas(A) int lut[]{};
+  (long *)lut; // expected-warning {{cast from 'int *' to 'long *'}}
+}
+
 struct __attribute__((aligned(16))) AlignedS {
   char m[16];
 };



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D151753: [Clang][Sema] Do not try to analyze dependent alignment during -Wcast-align

2023-06-27 Thread serge via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGdc6f5c9b588a: [Clang][Sema] Do not try to analyze dependent 
alignment during -Wcast-align (authored by serge-sans-paille).

Changed prior to commit:
  https://reviews.llvm.org/D151753?vs=528999&id=534869#toc

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D151753/new/

https://reviews.llvm.org/D151753

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Sema/SemaChecking.cpp
  clang/test/SemaCXX/warn-cast-align.cpp


Index: clang/test/SemaCXX/warn-cast-align.cpp
===
--- clang/test/SemaCXX/warn-cast-align.cpp
+++ clang/test/SemaCXX/warn-cast-align.cpp
@@ -44,6 +44,11 @@
   c = IntPtr(P);
 }
 
+template  void DependentAlign() {
+  alignas(A) int lut[]{};
+  (long *)lut; // expected-warning {{cast from 'int *' to 'long *'}}
+}
+
 struct __attribute__((aligned(16))) AlignedS {
   char m[16];
 };
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -16351,8 +16351,12 @@
 if (auto *VD = dyn_cast(cast(E)->getDecl())) {
   // FIXME: If VD is captured by copy or is an escaping __block variable,
   // use the alignment of VD's type.
-  if (!VD->getType()->isReferenceType())
+  if (!VD->getType()->isReferenceType()) {
+// Dependent alignment cannot be resolved -> bail out.
+if (VD->hasDependentAlignment())
+  break;
 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
+  }
   if (VD->hasInit())
 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
 }
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -370,6 +370,7 @@
 - Clang now diagnoses unexpected tokens after a
   ``#pragma clang|GCC diagnostic push|pop`` directive.
   (`#13920: `_)
+- Clang now does not try to analyze cast validity on variables with dependent 
alignment (`#63007: `_).
 
 Bug Fixes in This Version
 -


Index: clang/test/SemaCXX/warn-cast-align.cpp
===
--- clang/test/SemaCXX/warn-cast-align.cpp
+++ clang/test/SemaCXX/warn-cast-align.cpp
@@ -44,6 +44,11 @@
   c = IntPtr(P);
 }
 
+template  void DependentAlign() {
+  alignas(A) int lut[]{};
+  (long *)lut; // expected-warning {{cast from 'int *' to 'long *'}}
+}
+
 struct __attribute__((aligned(16))) AlignedS {
   char m[16];
 };
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -16351,8 +16351,12 @@
 if (auto *VD = dyn_cast(cast(E)->getDecl())) {
   // FIXME: If VD is captured by copy or is an escaping __block variable,
   // use the alignment of VD's type.
-  if (!VD->getType()->isReferenceType())
+  if (!VD->getType()->isReferenceType()) {
+// Dependent alignment cannot be resolved -> bail out.
+if (VD->hasDependentAlignment())
+  break;
 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
+  }
   if (VD->hasInit())
 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
 }
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -370,6 +370,7 @@
 - Clang now diagnoses unexpected tokens after a
   ``#pragma clang|GCC diagnostic push|pop`` directive.
   (`#13920: `_)
+- Clang now does not try to analyze cast validity on variables with dependent alignment (`#63007: `_).
 
 Bug Fixes in This Version
 -
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153776: [clang][analyzer] Display notes in StdLibraryFunctionsChecker only if interesting

2023-06-27 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added inline comments.



Comment at: 
clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp:1325
   if (!Pred)
-break;
+continue;
 }

steakhal wrote:
> Why do you continue here? Do you have a case for this?
This is only because the same loop has other failure places (if the state can 
not be applied) where `continue` is used already. The reason is that if one 
`addTransition` fails a next one may succeed. It is probably better to use 
`break` at all places. Even then what was already added to the state can not be 
removed, so it may be not wrong to add all states that can be added.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153776/new/

https://reviews.llvm.org/D153776

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153833: [clang][dataflow] Use namespace qualifiers when defining functions.

2023-06-27 Thread Martin Böhme via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG9a4097e9cd89: [clang][dataflow] Use namespace qualifiers 
when defining functions. (authored by mboehme).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153833/new/

https://reviews.llvm.org/D153833

Files:
  clang/lib/Analysis/FlowSensitive/RecordOps.cpp


Index: clang/lib/Analysis/FlowSensitive/RecordOps.cpp
===
--- clang/lib/Analysis/FlowSensitive/RecordOps.cpp
+++ clang/lib/Analysis/FlowSensitive/RecordOps.cpp
@@ -14,11 +14,9 @@
 
 #define DEBUG_TYPE "dataflow"
 
-namespace clang {
-namespace dataflow {
-
-void copyRecord(AggregateStorageLocation &Src, AggregateStorageLocation &Dst,
-Environment &Env) {
+void clang::dataflow::copyRecord(AggregateStorageLocation &Src,
+ AggregateStorageLocation &Dst,
+ Environment &Env) {
   LLVM_DEBUG({
 if (Dst.getType().getCanonicalType().getUnqualifiedType() !=
 Src.getType().getCanonicalType().getUnqualifiedType()) {
@@ -62,9 +60,10 @@
   }
 }
 
-bool recordsEqual(const AggregateStorageLocation &Loc1, const Environment 
&Env1,
-  const AggregateStorageLocation &Loc2,
-  const Environment &Env2) {
+bool clang::dataflow::recordsEqual(const AggregateStorageLocation &Loc1,
+   const Environment &Env1,
+   const AggregateStorageLocation &Loc2,
+   const Environment &Env2) {
   LLVM_DEBUG({
 if (Loc2.getType().getCanonicalType().getUnqualifiedType() !=
 Loc1.getType().getCanonicalType().getUnqualifiedType()) {
@@ -124,6 +123,3 @@
 
   return true;
 }
-
-} // namespace dataflow
-} // namespace clang


Index: clang/lib/Analysis/FlowSensitive/RecordOps.cpp
===
--- clang/lib/Analysis/FlowSensitive/RecordOps.cpp
+++ clang/lib/Analysis/FlowSensitive/RecordOps.cpp
@@ -14,11 +14,9 @@
 
 #define DEBUG_TYPE "dataflow"
 
-namespace clang {
-namespace dataflow {
-
-void copyRecord(AggregateStorageLocation &Src, AggregateStorageLocation &Dst,
-Environment &Env) {
+void clang::dataflow::copyRecord(AggregateStorageLocation &Src,
+ AggregateStorageLocation &Dst,
+ Environment &Env) {
   LLVM_DEBUG({
 if (Dst.getType().getCanonicalType().getUnqualifiedType() !=
 Src.getType().getCanonicalType().getUnqualifiedType()) {
@@ -62,9 +60,10 @@
   }
 }
 
-bool recordsEqual(const AggregateStorageLocation &Loc1, const Environment &Env1,
-  const AggregateStorageLocation &Loc2,
-  const Environment &Env2) {
+bool clang::dataflow::recordsEqual(const AggregateStorageLocation &Loc1,
+   const Environment &Env1,
+   const AggregateStorageLocation &Loc2,
+   const Environment &Env2) {
   LLVM_DEBUG({
 if (Loc2.getType().getCanonicalType().getUnqualifiedType() !=
 Loc1.getType().getCanonicalType().getUnqualifiedType()) {
@@ -124,6 +123,3 @@
 
   return true;
 }
-
-} // namespace dataflow
-} // namespace clang
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 9a4097e - [clang][dataflow] Use namespace qualifiers when defining functions.

2023-06-27 Thread Martin Braenne via cfe-commits

Author: Martin Braenne
Date: 2023-06-27T08:56:21Z
New Revision: 9a4097e9cd891e1445ba07ac6a21fe117fce

URL: 
https://github.com/llvm/llvm-project/commit/9a4097e9cd891e1445ba07ac6a21fe117fce
DIFF: 
https://github.com/llvm/llvm-project/commit/9a4097e9cd891e1445ba07ac6a21fe117fce.diff

LOG: [clang][dataflow] Use namespace qualifiers when defining functions.

See

https://llvm.org/docs/CodingStandards.html#use-namespace-qualifiers-to-implement-previously-declared-functions

Thank you to MaskRay for pointing this out on

https://reviews.llvm.org/D153006

Reviewed By: xazax.hun

Differential Revision: https://reviews.llvm.org/D153833

Added: 


Modified: 
clang/lib/Analysis/FlowSensitive/RecordOps.cpp

Removed: 




diff  --git a/clang/lib/Analysis/FlowSensitive/RecordOps.cpp 
b/clang/lib/Analysis/FlowSensitive/RecordOps.cpp
index d7145b0e2b312..eac9e3d4f93f2 100644
--- a/clang/lib/Analysis/FlowSensitive/RecordOps.cpp
+++ b/clang/lib/Analysis/FlowSensitive/RecordOps.cpp
@@ -14,11 +14,9 @@
 
 #define DEBUG_TYPE "dataflow"
 
-namespace clang {
-namespace dataflow {
-
-void copyRecord(AggregateStorageLocation &Src, AggregateStorageLocation &Dst,
-Environment &Env) {
+void clang::dataflow::copyRecord(AggregateStorageLocation &Src,
+ AggregateStorageLocation &Dst,
+ Environment &Env) {
   LLVM_DEBUG({
 if (Dst.getType().getCanonicalType().getUnqualifiedType() !=
 Src.getType().getCanonicalType().getUnqualifiedType()) {
@@ -62,9 +60,10 @@ void copyRecord(AggregateStorageLocation &Src, 
AggregateStorageLocation &Dst,
   }
 }
 
-bool recordsEqual(const AggregateStorageLocation &Loc1, const Environment 
&Env1,
-  const AggregateStorageLocation &Loc2,
-  const Environment &Env2) {
+bool clang::dataflow::recordsEqual(const AggregateStorageLocation &Loc1,
+   const Environment &Env1,
+   const AggregateStorageLocation &Loc2,
+   const Environment &Env2) {
   LLVM_DEBUG({
 if (Loc2.getType().getCanonicalType().getUnqualifiedType() !=
 Loc1.getType().getCanonicalType().getUnqualifiedType()) {
@@ -124,6 +123,3 @@ bool recordsEqual(const AggregateStorageLocation &Loc1, 
const Environment &Env1,
 
   return true;
 }
-
-} // namespace dataflow
-} // namespace clang



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153612: [clang][analyzer] Add and change NoteTags in StdLibraryFunctionsChecker.

2023-06-27 Thread Donát Nagy via Phabricator via cfe-commits
donat.nagy added inline comments.



Comment at: 
clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp:1299
+// StdLibraryFunctionsChecker.
+ExplodedNode *Pred = const_cast(Node);
+if (!Case.getNote().empty()) {

balazske wrote:
> donat.nagy wrote:
> > Can you explain why is it safe to use `const_cast` here? (I don't see any 
> > concrete issue, but the engine has lots of invariants / unwritten rules and 
> > I fear that this might break one of them.)
> The node `Pred` should be modified only later when a successor is added 
> (`addTransition` has non-const parameter).
I understood that you //need// a non-const `ExplodedNode *` because 
`addTransition` expects it; I want to understand why you are //allowed to// 
`const_cast` it (why doesn't this confuse the engine logic).

Equivalent question from the other direction: Why did the author of 
`CheckerContext::getPredecessor()` specify that its return value is a //const// 
pointer to `ExplodedNode`?

If we can conclude that `const_cast` is valid in this kind of situation, then 
I'd also consider simply removing the "const" from the return type of 
`getPredecessor`.



Comment at: 
clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp:1309
+[Node, Note](PathSensitiveBugReport &BR) -> std::string {
+  if (Node->succ_size() > 1)
+return Note.str();

balazske wrote:
> donat.nagy wrote:
> > It's surprising to see this check inside the lambda, as its result does not 
> > depend on `BR`. My best guess is that it's performed here because the 
> > successors of `Node` will appear between the execution of the surrounding 
> > code and the execution of this lambda.
> > 
> > However, CheckerContext.h line 69-70 claims that "checkers should not 
> > retain the node in their state since the nodes might get invalidated." 
> > which would imply that the captured `Node` might be invalid when the lambda 
> > is called.
> This check is to decide if multiple cases could be applied, the same as if we 
> count how many times this place in the loop is executed (add a transition for 
> a case, constraints could be applied). This check is problematic because 
> other checkers can apply state splits before this checker is executed or 
> after it, in this way `StreamChecker` interferes with this code (it has a 
> state split for success/failure cases of same function, and here we see only 
> that a single case is applied on one branch). This is why this check is only 
> used in the `EvalCallAsPure` case (theoretically still another checker can 
> make a state split in PostCall before this where the same constraint is 
> applied, then the problem occurs again).
> 
> I made a solution that does not have this check but has 2 case loops instead, 
> but the mentioned problem (which exists when `if (Summary.getInvalidationKd() 
> == EvalCallAsPure)` is not used) did not go away. And it may not work to 
> search backwards for the first node with the same statement, because maybe 
> not the first one is where a state split is done.
> 
> I only think that if this lambda is called with the saved node, that node is 
> not invalid because it is part of a bug report call sequence.
> This check is problematic because [...details...]

Thanks for the explanation, now I see why this roundabout solution is needed.

> I only think that if this lambda is called with the saved node, that node is 
> not invalid because it is part of a bug report call sequence.

This is a good point, I think we can keep this "check successors in the lambda" 
solution. Please add a comment like "This check is performed inside the lambda, 
after other checkers had a chance to add other successors. Dereferencing the 
saved node object is valid because it's part of a bug report call sequence." to 
record the the reasoning that we discussed.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153612/new/

https://reviews.llvm.org/D153612

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D121410: Have cpu-specific variants set 'tune-cpu' as an optimization hint

2023-06-27 Thread Freddy, Ye via Phabricator via cfe-commits
FreddyYe added inline comments.
Herald added a subscriber: StephenFan.



Comment at: clang/lib/CodeGen/CodeGenModule.cpp:2067
+  // favor this processor.
+  TuneCPU = SD->getCPUName(GD.getMultiVersionIndex())->getName();
+}

pengfei wrote:
> erichkeane wrote:
> > andrew.w.kaylor wrote:
> > > Unfortunately, I don't think it's this easy. The list of names used for 
> > > cpu_specific doesn't come from the same place as the list of names used 
> > > by "tune-cpu". For one thing, the cpu_specific names can't contain the 
> > > '-' character, so we have names like "skylake_avx512" in cpu_specific 
> > > that would need to be translated to "skylake-avx512" for "tune-cpu". I 
> > > believe the list of valid names for "tune-cpu" comes from here: 
> > > https://github.com/llvm/llvm-project/blob/26cd258420c774254cc48330b1f4d23d353baf05/llvm/lib/Support/X86TargetParser.cpp#L294
> > > 
> > > Also, some of the aliases supported by cpu_specific don't have any 
> > > corresponding "tune-cpu" name. You happen to have picked one of these for 
> > > the test. I believe "core_4th_gen_avx" should map to "haswell".
> > Hmm... this is unfortunate.  I wonder if we add some 'translation' type 
> > field to the X86TargetParser.def entries?  Any idea who the right one to 
> > populate said list would be?
> > I believe the list of valid names for "tune-cpu" comes from ...
> 
> I think it's here 
> https://github.com/llvm/llvm-project/blob/26cd258420c774254cc48330b1f4d23d353baf05/llvm/lib/Target/X86/X86.td#L1408
> 
> So back to Andy's problems, where we consume the cpu_specific names in 
> compiler previously, e.g., mapping to different targets? Or it is done by 
> external libraries like compiler-rt?
> 
> I think I have the same requirments that mapping `-` and `_` for "tune-cpu" 
> in https://github.com/llvm/llvm-project/issues/50125 where the preprocessor 
> defines use `_` as well.
> Unfortunately, I don't think it's this easy. The list of names used for 
> cpu_specific doesn't come from the same place as the list of names used by 
> "tune-cpu". For one thing, the cpu_specific names can't contain the '-' 
> character, so we have names like "skylake_avx512" in cpu_specific that would 
> need to be translated to "skylake-avx512" for "tune-cpu". I believe the list 
> of valid names for "tune-cpu" comes from here: 
> https://github.com/llvm/llvm-project/blob/26cd258420c774254cc48330b1f4d23d353baf05/llvm/lib/Support/X86TargetParser.cpp#L294
> 
> Also, some of the aliases supported by cpu_specific don't have any 
> corresponding "tune-cpu" name. You happen to have picked one of these for the 
> test. I believe "core_4th_gen_avx" should map to "haswell".

Happens to find this patch. I recently also change here back to the initial 
version of this patch at https://reviews.llvm.org/D151696.  To resolve the 
problem @andrew.w.kaylor mentioned here, I added these "unsupported" names in 
X86.td like Phoebe mentioned below. If you are interested, feel free to comment 
there.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D121410/new/

https://reviews.llvm.org/D121410

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153849: [clang][Diagnostics] Fix diagnostic line numbers

2023-06-27 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder created this revision.
tbaeder added reviewers: cjdb, aaron.ballman.
Herald added a project: All.
tbaeder requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

  The first line of the code snippet we print is potentially lower than
  the caret line, so handle that case.
  
  Fixes https://github.com/llvm/llvm-project/issues/63524


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D153849

Files:
  clang/lib/Frontend/TextDiagnostic.cpp
  clang/test/Misc/diag-style.cpp


Index: clang/test/Misc/diag-style.cpp
===
--- clang/test/Misc/diag-style.cpp
+++ clang/test/Misc/diag-style.cpp
@@ -10,3 +10,17 @@
 // CHECK-NEXT: {{^}}5 | {{$}}
 // CHECK-NEXT: {{^}}6 |   true, "");{{$}}
 // CHECK-NEXT: {{^}}  |   {{$}}
+
+
+/// #line pragmas are respected
+void printf(const char *a, ...) __attribute__((__format__(__printf__, 1, 2)));
+#line 10
+void f(int x) {
+  printf("%f",
+ x);
+}
+// CHECK: 12:10: warning: format specifies type
+// CHECK-NEXT: {{^}}   11 |
+// CHECK-NEXT: {{^}}  |
+// CHECK-NEXT: {{^}}  |
+// CHECK-NEXT: {{^}}   12 |
Index: clang/lib/Frontend/TextDiagnostic.cpp
===
--- clang/lib/Frontend/TextDiagnostic.cpp
+++ clang/lib/Frontend/TextDiagnostic.cpp
@@ -1160,16 +1160,20 @@
   // Find the set of lines to include.
   const unsigned MaxLines = DiagOpts->SnippetLineLimit;
   std::pair Lines = {CaretLineNo, CaretLineNo};
+  unsigned DisplayLineNo =
+  Ranges.empty() ? Loc.getPresumedLoc().getLine() : ~0u;
   for (const auto &I : Ranges) {
 if (auto OptionalRange = findLinesForRange(I, FID, SM))
   Lines = maybeAddRange(Lines, *OptionalRange, MaxLines);
+
+DisplayLineNo =
+std::min(DisplayLineNo, SM.getPresumedLineNumber(I.getBegin()));
   }
 
   // Our line numbers look like:
   // " [number] | "
   // Where [number] is MaxLineNoDisplayWidth columns
   // and the full thing is therefore MaxLineNoDisplayWidth + 4 columns.
-  unsigned DisplayLineNo = Loc.getPresumedLoc().getLine();
   unsigned MaxLineNoDisplayWidth =
   DiagOpts->ShowLineNumbers
   ? std::max(4u, getNumDisplayWidth(DisplayLineNo + MaxLines))


Index: clang/test/Misc/diag-style.cpp
===
--- clang/test/Misc/diag-style.cpp
+++ clang/test/Misc/diag-style.cpp
@@ -10,3 +10,17 @@
 // CHECK-NEXT: {{^}}5 | {{$}}
 // CHECK-NEXT: {{^}}6 |   true, "");{{$}}
 // CHECK-NEXT: {{^}}  |   {{$}}
+
+
+/// #line pragmas are respected
+void printf(const char *a, ...) __attribute__((__format__(__printf__, 1, 2)));
+#line 10
+void f(int x) {
+  printf("%f",
+ x);
+}
+// CHECK: 12:10: warning: format specifies type
+// CHECK-NEXT: {{^}}   11 |
+// CHECK-NEXT: {{^}}  |
+// CHECK-NEXT: {{^}}  |
+// CHECK-NEXT: {{^}}   12 |
Index: clang/lib/Frontend/TextDiagnostic.cpp
===
--- clang/lib/Frontend/TextDiagnostic.cpp
+++ clang/lib/Frontend/TextDiagnostic.cpp
@@ -1160,16 +1160,20 @@
   // Find the set of lines to include.
   const unsigned MaxLines = DiagOpts->SnippetLineLimit;
   std::pair Lines = {CaretLineNo, CaretLineNo};
+  unsigned DisplayLineNo =
+  Ranges.empty() ? Loc.getPresumedLoc().getLine() : ~0u;
   for (const auto &I : Ranges) {
 if (auto OptionalRange = findLinesForRange(I, FID, SM))
   Lines = maybeAddRange(Lines, *OptionalRange, MaxLines);
+
+DisplayLineNo =
+std::min(DisplayLineNo, SM.getPresumedLineNumber(I.getBegin()));
   }
 
   // Our line numbers look like:
   // " [number] | "
   // Where [number] is MaxLineNoDisplayWidth columns
   // and the full thing is therefore MaxLineNoDisplayWidth + 4 columns.
-  unsigned DisplayLineNo = Loc.getPresumedLoc().getLine();
   unsigned MaxLineNoDisplayWidth =
   DiagOpts->ShowLineNumbers
   ? std::max(4u, getNumDisplayWidth(DisplayLineNo + MaxLines))
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D151696: [x86] Remove CPU_SPECIFIC* MACROs and add getCPUDispatchMangling

2023-06-27 Thread Freddy, Ye via Phabricator via cfe-commits
FreddyYe added a comment.

In D151696#4448680 , @FreddyYe wrote:

> In D151696#4448573 , @erichkeane 
> wrote:
>
>> I think this is OK, I have a slight fear we're losing a bit of the 'tune' 
>> functionality, but it is not impossible that we've never really cared about 
>> that.  One concern I have is that the list was used for the resolver 
>> function, but I don't see any test changes for that?  Are we properly 
>> filtering out the features list somehow?
>
> Yes! Now there are no tests yet testing the resolver function influenced by 
> the feature list. I'll add another pre-commit test to show this.

Added checks in https://reviews.llvm.org/D152989. pls help review. About the 
"-tune-cpu", I think it's ok to use the same name as the one that users 
specified in _cpu_specific(), after I supported those missing names in X86.td 
so that optimizer can now recognize them.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D151696/new/

https://reviews.llvm.org/D151696

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] c319694 - [clang][Interp][NFC] Compare std::optional variables directly

2023-06-27 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-06-27T11:36:42+02:00
New Revision: c3196947312e530960fde1b8849a4a848a5095f3

URL: 
https://github.com/llvm/llvm-project/commit/c3196947312e530960fde1b8849a4a848a5095f3
DIFF: 
https://github.com/llvm/llvm-project/commit/c3196947312e530960fde1b8849a4a848a5095f3.diff

LOG: [clang][Interp][NFC] Compare std::optional variables directly

We can do that and we already checked that they aren't nullopt before.

Added: 


Modified: 
clang/lib/AST/Interp/ByteCodeExprGen.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 8558ba0ba1ee7..86200f9ad0831 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -230,7 +230,7 @@ bool ByteCodeExprGen::VisitBinaryOperator(const 
BinaryOperator *BO) {
 
   // Pointer arithmetic special case.
   if (BO->getOpcode() == BO_Add || BO->getOpcode() == BO_Sub) {
-if (*T == PT_Ptr || (*LT == PT_Ptr && *RT == PT_Ptr))
+if (T == PT_Ptr || (LT == PT_Ptr && RT == PT_Ptr))
   return this->VisitPointerArithBinOp(BO);
   }
 



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153798: [clang-format] Correctly annotate operator free function call

2023-06-27 Thread Yilong Guo via Phabricator via cfe-commits
Nuu accepted this revision.
Nuu added a comment.
This revision is now accepted and ready to land.

Thanks, LGTM!




Comment at: clang/lib/Format/TokenAnnotator.cpp:316
+  // line can't be a declaration.
   bool OperatorCalledAsMemberFunction =
+  (Prev->Previous &&

minor. Probably better to rename it to something like `IsOperatorCallSite`.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153798/new/

https://reviews.llvm.org/D153798

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D150758: [AIX] make integrated-as as default on AIX.

2023-06-27 Thread Esme Yi via Phabricator via cfe-commits
Esme updated this revision to Diff 534884.
Esme added a comment.

Rebase.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D150758/new/

https://reviews.llvm.org/D150758

Files:
  clang/lib/Driver/ToolChains/AIX.h
  clang/test/Driver/aix-as.c
  clang/test/Driver/aix-integrated-as.c


Index: clang/test/Driver/aix-integrated-as.c
===
--- /dev/null
+++ clang/test/Driver/aix-integrated-as.c
@@ -0,0 +1,15 @@
+// Test integrated-as is called by default on AIX.
+
+// Check powerpc-ibm-aix7.1.0.0, 32-bit.
+// RUN: %clang %s -### -c 2>&1 \
+// RUN: --target=powerpc-ibm-aix7.1.0.0 \
+// RUN:   | FileCheck --check-prefix=CHECK-IAS32 %s
+// CHECK-IAS32-NOT: "-a32"
+// CHECK-IAS32: "-cc1" "-triple" "powerpc-ibm-aix7.1.0.0" "-emit-obj"
+
+// Check powerpc64-ibm-aix7.1.0.0, 64-bit.
+// RUN: %clang %s -### -c 2>&1 \
+// RUN: --target=powerpc64-ibm-aix7.1.0.0 \
+// RUN:   | FileCheck --check-prefix=CHECK-IAS64 %s
+// CHECK-IAS64-NOT: "-a64"
+// CHECK-IAS64: "-cc1" "-triple" "powerpc64-ibm-aix7.1.0.0" "-emit-obj"
Index: clang/test/Driver/aix-as.c
===
--- clang/test/Driver/aix-as.c
+++ clang/test/Driver/aix-as.c
@@ -11,7 +11,7 @@
 // RUN:   | FileCheck --check-prefix=CHECK-AS32 %s
 
 // Check powerpc-ibm-aix7.1.0.0, 32-bit.
-// RUN: %clang %s -### -c 2>&1 \
+// RUN: %clang %s -### -c -fno-integrated-as 2>&1 \
 // RUN: --target=powerpc-ibm-aix7.1.0.0 \
 // RUN:   | FileCheck --check-prefixes=CHECK-AS32,CHECK-AS32-CC1 %s
 // CHECK-AS32-NOT: warning:
@@ -30,7 +30,7 @@
 // RUN:   | FileCheck --check-prefix=CHECK-AS64 %s
 
 // Check powerpc64-ibm-aix7.1.0.0, 64-bit.
-// RUN: %clang %s -### -c 2>&1 \
+// RUN: %clang %s -### -c -fno-integrated-as 2>&1 \
 // RUN: --target=powerpc64-ibm-aix7.1.0.0 \
 // RUN:   | FileCheck --check-prefixes=CHECK-AS64,CHECK-AS64-CC1 %s
 // CHECK-AS64-NOT: warning:
@@ -40,7 +40,7 @@
 // CHECK-AS64: "-many"
 
 // Check powerpc-ibm-aix7.1.0.0, 32-bit. -Xassembler  option. 
-// RUN: %clang %s -### -c 2>&1 \
+// RUN: %clang %s -### -c -fno-integrated-as 2>&1 \
 // RUN: -Xassembler -w \
 // RUN: --target=powerpc-ibm-aix7.1.0.0 \
 // RUN:   | FileCheck --check-prefix=CHECK-AS32-Xassembler %s
@@ -52,7 +52,7 @@
 // CHECK-AS32-Xassembler: "-w"
 
 // Check powerpc64-ibm-aix7.1.0.0, 64-bit. -Wa,, option.
-// RUN: %clang %s -### -c 2>&1 \
+// RUN: %clang %s -### -c -fno-integrated-as 2>&1 \
 // RUN: -Wa,-v,-w \
 // RUN: --target=powerpc64-ibm-aix7.1.0.0 \
 // RUN:   | FileCheck --check-prefix=CHECK-AS64-Wa %s
@@ -65,7 +65,7 @@
 // CHECK-AS64-Wa: "-w"
 
 // Check powerpc-ibm-aix7.1.0.0, 32-bit. Multiple input files.
-// RUN: %clang -### -c \
+// RUN: %clang -### -fno-integrated-as -c \
 // RUN: %S/Inputs/aix_ppc_tree/dummy0.s \
 // RUN: %S/Inputs/aix_ppc_tree/dummy1.s \
 // RUN: %S/Inputs/aix_ppc_tree/dummy2.s 2>&1 \
@@ -85,8 +85,8 @@
 // Check not passing no-integrated-as flag by default.
 // RUN: %clang %s -### -c 2>&1 --target=powerpc64-ibm-aix7.1.0.0 \
 // RUN:   | FileCheck --check-prefix=CHECK-IAS 
--implicit-check-not=-no-integrated-as %s
+// CHECK-IAS-NOT: "-a64"
 // CHECK-IAS: InstalledDir
-// CHECK-IAS: "-a64"
 
 // Check passing no-integrated-as flag if specified by user.
 // RUN: %clang %s -### -c 2>&1 --target=powerpc64-ibm-aix7.1.0.0 
-fno-integrated-as \
Index: clang/lib/Driver/ToolChains/AIX.h
===
--- clang/lib/Driver/ToolChains/AIX.h
+++ clang/lib/Driver/ToolChains/AIX.h
@@ -68,6 +68,7 @@
   }
   bool isPICDefaultForced() const override { return true; }
   bool HasNativeLLVMSupport() const override { return true; }
+  bool IsIntegratedAssemblerDefault() const override { return true; }
 
   void
   AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs,


Index: clang/test/Driver/aix-integrated-as.c
===
--- /dev/null
+++ clang/test/Driver/aix-integrated-as.c
@@ -0,0 +1,15 @@
+// Test integrated-as is called by default on AIX.
+
+// Check powerpc-ibm-aix7.1.0.0, 32-bit.
+// RUN: %clang %s -### -c 2>&1 \
+// RUN: --target=powerpc-ibm-aix7.1.0.0 \
+// RUN:   | FileCheck --check-prefix=CHECK-IAS32 %s
+// CHECK-IAS32-NOT: "-a32"
+// CHECK-IAS32: "-cc1" "-triple" "powerpc-ibm-aix7.1.0.0" "-emit-obj"
+
+// Check powerpc64-ibm-aix7.1.0.0, 64-bit.
+// RUN: %clang %s -### -c 2>&1 \
+// RUN: --target=powerpc64-ibm-aix7.1.0.0 \
+// RUN:   | FileCheck --check-prefix=CHECK-IAS64 %s
+// CHECK-IAS64-NOT: "-a64"
+// CHECK-IAS64: "-cc1" "-triple" "powerpc64-ibm-aix7.1.0.0" "-emit-obj"
Index: clang/test/Driver/aix-as.c
===
--- clang/test/Driver/aix-as.c
+++ clang/test/Driver/aix-as.c
@@ -11,7 +11,7 @@
 // RUN:   | FileCheck --check-prefix=CHECK-AS32 %

[PATCH] D153409: [clang][dataflow] Treat fields of anonymous records as being part of their parent.

2023-06-27 Thread Martin Böhme via Phabricator via cfe-commits
mboehme updated this revision to Diff 534891.
mboehme added a comment.

Undo all of the non-test changes. This patch now only introduces a test that
we can access fields of anonymous structs.

I realized based on gribozavr2's comment that we shouldn't be lumping all fields
of anonymous records into the parent record, as this goes against the grain of
the Clang AST and, for example, requires special-case code in `MemberExpr`.

Instead, I realized that everything essentially already works -- anonymous
records were already being correctly added as fields of their parent record.
The only thing that needs to be fixed is handling `IndirectFieldDecl` correctly
when transferring `CXXCtorInitializer`. This will come in a followup patch.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153409/new/

https://reviews.llvm.org/D153409

Files:
  clang/unittests/Analysis/FlowSensitive/TestingSupport.cpp
  clang/unittests/Analysis/FlowSensitive/TestingSupport.h
  clang/unittests/Analysis/FlowSensitive/TransferTest.cpp


Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -5434,4 +5434,38 @@
   });
 }
 
+// Check that fields of anonymous records are modeled.
+TEST(TransferTest, AnonymousStruct) {
+  std::string Code = R"(
+struct S {
+  struct {
+bool b;
+  };
+};
+void target() {
+  S s;
+  s.b = true;
+  // [[p]]
+}
+  )";
+  runDataflow(
+  Code,
+  [](const llvm::StringMap> &Results,
+ ASTContext &ASTCtx) {
+const Environment &Env = getEnvironmentAtAnnotation(Results, "p");
+const ValueDecl *SDecl = findValueDecl(ASTCtx, "s");
+const ValueDecl *BDecl = findValueDecl(ASTCtx, "b");
+const IndirectFieldDecl *IndirectField =
+findIndirectFieldDecl(ASTCtx, "b");
+
+auto *S =
+cast(Env.getStorageLocation(*SDecl));
+auto &AnonStruct = cast(
+S->getChild(*cast(IndirectField->chain().front(;
+
+auto *B = cast(Env.getValue(AnonStruct.getChild(*BDecl)));
+ASSERT_TRUE(Env.flowConditionImplies(*B));
+  });
+}
+
 } // namespace
Index: clang/unittests/Analysis/FlowSensitive/TestingSupport.h
===
--- clang/unittests/Analysis/FlowSensitive/TestingSupport.h
+++ clang/unittests/Analysis/FlowSensitive/TestingSupport.h
@@ -428,6 +428,14 @@
 ///   `Name` must be unique in `ASTCtx`.
 const ValueDecl *findValueDecl(ASTContext &ASTCtx, llvm::StringRef Name);
 
+/// Returns the `IndirectFieldDecl` for the given identifier.
+///
+/// Requirements:
+///
+///   `Name` must be unique in `ASTCtx`.
+const IndirectFieldDecl *findIndirectFieldDecl(ASTContext &ASTCtx,
+   llvm::StringRef Name);
+
 /// Returns the storage location (of type `LocT`) for the given identifier.
 /// `LocT` must be a subclass of `StorageLocation` and must be of the
 /// appropriate type.
Index: clang/unittests/Analysis/FlowSensitive/TestingSupport.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TestingSupport.cpp
+++ clang/unittests/Analysis/FlowSensitive/TestingSupport.cpp
@@ -154,9 +154,19 @@
 }
 
 const ValueDecl *test::findValueDecl(ASTContext &ASTCtx, llvm::StringRef Name) 
{
-  auto TargetNodes = match(valueDecl(hasName(Name)).bind("v"), ASTCtx);
+  auto TargetNodes = match(
+  valueDecl(unless(indirectFieldDecl()), hasName(Name)).bind("v"), ASTCtx);
   assert(TargetNodes.size() == 1 && "Name must be unique");
   auto *const Result = selectFirst("v", TargetNodes);
   assert(Result != nullptr);
   return Result;
 }
+
+const IndirectFieldDecl *test::findIndirectFieldDecl(ASTContext &ASTCtx,
+ llvm::StringRef Name) {
+  auto TargetNodes = match(indirectFieldDecl(hasName(Name)).bind("i"), ASTCtx);
+  assert(TargetNodes.size() == 1 && "Name must be unique");
+  const auto *Result = selectFirst("i", TargetNodes);
+  assert(Result != nullptr);
+  return Result;
+}


Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -5434,4 +5434,38 @@
   });
 }
 
+// Check that fields of anonymous records are modeled.
+TEST(TransferTest, AnonymousStruct) {
+  std::string Code = R"(
+struct S {
+  struct {
+bool b;
+  };
+};
+void target() {
+  S s;
+  s.b = true;
+  // [[p]]
+}
+  )";
+  runDataflow(
+  Code,
+  [](const llvm::StringMap> &Results,
+ ASTContext &ASTCtx) {
+const Environme

[PATCH] D153409: [clang][dataflow] Treat fields of anonymous records as being part of their parent.

2023-06-27 Thread Martin Böhme via Phabricator via cfe-commits
mboehme marked 2 inline comments as done.
mboehme added a comment.

PTAL




Comment at: clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp:305
+if (Field->isAnonymousStructOrUnion())
+  getFieldsFromClassHierarchy(Field->getType(), Fields);
+else

gribozavr2 wrote:
> Could we somehow take advantage of the IndirectFieldDecl instead of recursing 
> ourselves? Seems like that way we would be delegating to Clang the questions 
> of the name injection/lookup.
Thanks for pointing this out.

I realized I was really working against the grain of the Clang AST. I've 
changed this patch so that it merely adds a new test (to demonstrate that we 
are already representing fields of anonymous records correctly).

The thing that actually needs to be fixed is the handling of 
`CXXCtorInitializer`; I'll do this in a followup patch.



Comment at: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp:5427
+const ValueDecl *SDecl = findValueDecl(ASTCtx, "s");
+const ValueDecl *IDecl = findValueDecl(ASTCtx, "i");
+

gribozavr2 wrote:
> Could we make some stronger assertion to prove that the transfer function 
> works? It seems to me that getChild() by itself does not prove that.
> 
> For example, store and load the value and assert that it is the same.
Good point, done.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153409/new/

https://reviews.llvm.org/D153409

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153851: [clang][dataflow] Output debug info if `getChild()` doesn't find field.

2023-06-27 Thread Martin Böhme via Phabricator via cfe-commits
mboehme created this revision.
Herald added subscribers: martong, xazax.hun.
Herald added a reviewer: NoQ.
Herald added a project: All.
mboehme requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Depends On D153409 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D153851

Files:
  clang/include/clang/Analysis/FlowSensitive/StorageLocation.h


Index: clang/include/clang/Analysis/FlowSensitive/StorageLocation.h
===
--- clang/include/clang/Analysis/FlowSensitive/StorageLocation.h
+++ clang/include/clang/Analysis/FlowSensitive/StorageLocation.h
@@ -17,6 +17,9 @@
 #include "clang/AST/Decl.h"
 #include "clang/AST/Type.h"
 #include "llvm/ADT/DenseMap.h"
+#include "llvm/Support/Debug.h"
+
+#define DEBUG_TYPE "dataflow"
 
 namespace clang {
 namespace dataflow {
@@ -85,6 +88,17 @@
   /// Returns the child storage location for `D`.
   StorageLocation &getChild(const ValueDecl &D) const {
 auto It = Children.find(&D);
+LLVM_DEBUG({
+  if (It == Children.end()) {
+llvm::dbgs() << "Couldn't find child " << D.getNameAsString()
+ << " on StorageLocation " << this << " of type "
+ << getType() << "\n";
+llvm::dbgs() << "Existing children:\n";
+for ([[maybe_unused]] auto [Field, Loc] : Children) {
+  llvm::dbgs() << Field->getNameAsString() << "\n";
+}
+  }
+});
 assert(It != Children.end());
 return *It->second;
   }
@@ -100,4 +114,6 @@
 } // namespace dataflow
 } // namespace clang
 
+#undef DEBUG_TYPE
+
 #endif // LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_STORAGELOCATION_H


Index: clang/include/clang/Analysis/FlowSensitive/StorageLocation.h
===
--- clang/include/clang/Analysis/FlowSensitive/StorageLocation.h
+++ clang/include/clang/Analysis/FlowSensitive/StorageLocation.h
@@ -17,6 +17,9 @@
 #include "clang/AST/Decl.h"
 #include "clang/AST/Type.h"
 #include "llvm/ADT/DenseMap.h"
+#include "llvm/Support/Debug.h"
+
+#define DEBUG_TYPE "dataflow"
 
 namespace clang {
 namespace dataflow {
@@ -85,6 +88,17 @@
   /// Returns the child storage location for `D`.
   StorageLocation &getChild(const ValueDecl &D) const {
 auto It = Children.find(&D);
+LLVM_DEBUG({
+  if (It == Children.end()) {
+llvm::dbgs() << "Couldn't find child " << D.getNameAsString()
+ << " on StorageLocation " << this << " of type "
+ << getType() << "\n";
+llvm::dbgs() << "Existing children:\n";
+for ([[maybe_unused]] auto [Field, Loc] : Children) {
+  llvm::dbgs() << Field->getNameAsString() << "\n";
+}
+  }
+});
 assert(It != Children.end());
 return *It->second;
   }
@@ -100,4 +114,6 @@
 } // namespace dataflow
 } // namespace clang
 
+#undef DEBUG_TYPE
+
 #endif // LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_STORAGELOCATION_H
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153852: [clang][dataflow] Initialize fields of anonymous records correctly.

2023-06-27 Thread Martin Böhme via Phabricator via cfe-commits
mboehme created this revision.
Herald added subscribers: martong, xazax.hun.
Herald added a reviewer: NoQ.
Herald added a project: All.
mboehme requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Previously, the newly added test would crash.

Depends On D153851 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D153852

Files:
  clang/lib/Analysis/FlowSensitive/Transfer.cpp
  clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
  clang/unittests/Analysis/FlowSensitive/TransferTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -5468,4 +5468,35 @@
   });
 }
 
+TEST(TransferTest, AnonymousStructWithInitializer) {
+  std::string Code = R"(
+struct target {
+  target() {
+(void)b;
+// [[p]]
+  }
+  struct {
+bool b = true;
+  };
+};
+  )";
+  runDataflow(
+  Code,
+  [](const llvm::StringMap> &Results,
+ ASTContext &ASTCtx) {
+const Environment &Env = getEnvironmentAtAnnotation(Results, "p");
+const ValueDecl *BDecl = findValueDecl(ASTCtx, "b");
+const IndirectFieldDecl *IndirectField =
+findIndirectFieldDecl(ASTCtx, "b");
+
+auto *ThisLoc =
+cast(Env.getThisPointeeStorageLocation());
+auto &AnonStruct = cast(ThisLoc->getChild(
+*cast(IndirectField->chain().front(;
+
+auto *B = cast(Env.getValue(AnonStruct.getChild(*BDecl)));
+ASSERT_TRUE(Env.flowConditionImplies(*B));
+  });
+}
+
 } // namespace
Index: clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
===
--- clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
+++ clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
@@ -332,27 +332,41 @@
   assert(Init != nullptr);
 
   auto &Env = InputState.Env;
-  const auto &ThisLoc =
+  auto &ThisLoc =
   *cast(Env.getThisPointeeStorageLocation());
 
-  const FieldDecl *Member = Init->getMember();
-  if (Member == nullptr)
-// Not a field initializer.
+  if (!Init->isAnyMemberInitializer())
+// FIXME: Handle base initialization
 return;
 
   auto *InitStmt = Init->getInit();
   assert(InitStmt != nullptr);
 
+  const FieldDecl *Member = nullptr;
+  StorageLocation *MemberLoc = nullptr;
+  if (Init->isMemberInitializer()) {
+Member = Init->getMember();
+MemberLoc = &ThisLoc.getChild(*Member);
+  } else {
+IndirectFieldDecl *IndirectField = Init->getIndirectMember();
+assert(IndirectField != nullptr);
+MemberLoc = &ThisLoc;
+for (const auto *I : IndirectField->chain()) {
+  Member = cast(I);
+  MemberLoc = &cast(MemberLoc)->getChild(*Member);
+}
+  }
+  assert(Member != nullptr);
+  assert(MemberLoc != nullptr);
+
   if (Member->getType()->isReferenceType()) {
 auto *InitStmtLoc = Env.getStorageLocationStrict(*InitStmt);
 if (InitStmtLoc == nullptr)
   return;
 
-auto &MemberLoc = ThisLoc.getChild(*Member);
-Env.setValue(MemberLoc, Env.create(*InitStmtLoc));
+Env.setValue(*MemberLoc, Env.create(*InitStmtLoc));
   } else if (auto *InitStmtVal = Env.getValueStrict(*InitStmt)) {
-auto &MemberLoc = ThisLoc.getChild(*Member);
-Env.setValue(MemberLoc, *InitStmtVal);
+Env.setValue(*MemberLoc, *InitStmtVal);
   }
 }
 
Index: clang/lib/Analysis/FlowSensitive/Transfer.cpp
===
--- clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -153,7 +153,7 @@
 Env.setStorageLocationStrict(To, *Loc);
 }
 
-// Forwards the value or storage location of `From` to `To` in cases where
+// Propagates the value or storage location of `From` to `To` in cases where
 // `From` may be either a glvalue or a prvalue. `To` must be a glvalue iff
 // `From` is a glvalue.
 static void propagateValueOrStorageLocation(const Expr &From, const Expr &To,
@@ -572,18 +572,7 @@
   void VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *S) {
 const Expr *InitExpr = S->getExpr();
 assert(InitExpr != nullptr);
-
-Value *InitExprVal = Env.getValue(*InitExpr, SkipPast::None);
-if (InitExprVal == nullptr)
-  return;
-
-const FieldDecl *Field = S->getField();
-assert(Field != nullptr);
-
-auto &ThisLoc =
-*cast(Env.getThisPointeeStorageLocation());
-auto &FieldLoc = ThisLoc.getChild(*Field);
-Env.setValue(FieldLoc, *InitExprVal);
+propagateValueOrStorageLocation(*InitExpr, *S, Env);
   }
 
   void VisitCXXConstructExpr(const CXXConstructExpr *S) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.

[PATCH] D153852: [clang][dataflow] Initialize fields of anonymous records correctly.

2023-06-27 Thread Martin Böhme via Phabricator via cfe-commits
mboehme added inline comments.



Comment at: clang/lib/Analysis/FlowSensitive/Transfer.cpp:575
 assert(InitExpr != nullptr);
-
-Value *InitExprVal = Env.getValue(*InitExpr, SkipPast::None);
-if (InitExprVal == nullptr)
-  return;
-
-const FieldDecl *Field = S->getField();
-assert(Field != nullptr);
-
-auto &ThisLoc =
-*cast(Env.getThisPointeeStorageLocation());
-auto &FieldLoc = ThisLoc.getChild(*Field);
-Env.setValue(FieldLoc, *InitExprVal);
+propagateValueOrStorageLocation(*InitExpr, *S, Env);
   }

It turns out this was doing strictly too much work.

`CXXDefaultInitExpr` should only be producing the default value. The actual 
initialization should be left to `CXXCtorInitializer`.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153852/new/

https://reviews.llvm.org/D153852

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 173df3d - [clang][CFG][NFC] A few smaller cleanups

2023-06-27 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-06-27T11:38:41+02:00
New Revision: 173df3dd5f9a812b07f9866965f4e92a982a3fca

URL: 
https://github.com/llvm/llvm-project/commit/173df3dd5f9a812b07f9866965f4e92a982a3fca
DIFF: 
https://github.com/llvm/llvm-project/commit/173df3dd5f9a812b07f9866965f4e92a982a3fca.diff

LOG: [clang][CFG][NFC] A few smaller cleanups

Use dyn_cast_if_present instead of _or_null, use decomposition decls,
and a few other minor things.

Added: 


Modified: 
clang/lib/Analysis/CFG.cpp
clang/lib/Analysis/ThreadSafety.cpp

Removed: 




diff  --git a/clang/lib/Analysis/CFG.cpp b/clang/lib/Analysis/CFG.cpp
index 246bace4debcf..318b0af86ab70 100644
--- a/clang/lib/Analysis/CFG.cpp
+++ b/clang/lib/Analysis/CFG.cpp
@@ -1560,7 +1560,7 @@ std::unique_ptr CFGBuilder::buildCFG(const Decl *D, 
Stmt *Statement) {
  "AddImplicitDtors and AddLifetime cannot be used at the same time");
 
   if (BuildOpts.AddImplicitDtors)
-if (const CXXDestructorDecl *DD = dyn_cast_or_null(D))
+if (const CXXDestructorDecl *DD = 
dyn_cast_if_present(D))
   addImplicitDtorsForDestructor(DD);
 
   // Visit the statements and create the CFG.
@@ -1581,7 +1581,7 @@ std::unique_ptr CFGBuilder::buildCFG(const Decl *D, 
Stmt *Statement) {
   // fields. To handle this, make a CFG branch. We only need to add one such
   // branch per constructor, since the Standard states that all virtual bases
   // shall be initialized before non-virtual bases and direct data members.
-  if (const auto *CD = dyn_cast_or_null(D)) {
+  if (const auto *CD = dyn_cast_if_present(D)) {
 CFGBlock *VBaseSucc = nullptr;
 for (auto *I : llvm::reverse(CD->inits())) {
   if (BuildOpts.AddVirtualBaseBranches && !VBaseSucc &&
@@ -3010,7 +3010,7 @@ CFGBlock *CFGBuilder::VisitDeclSubExpr(DeclStmt *DS) {
 
   // If the initializer is an ArrayInitLoopExpr, we want to extract the
   // initializer, that's used for each element.
-  const auto *AILE = dyn_cast_or_null(Init);
+  const auto *AILE = dyn_cast_if_present(Init);
 
   findConstructionContexts(
   ConstructionContextLayer::create(cfg->getBumpVectorContext(), DS),
@@ -3591,7 +3591,7 @@ CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) {
 // Specially handle logical operators, which have a slightly
 // more optimal CFG representation.
 if (BinaryOperator *Cond =
-dyn_cast_or_null(C ? C->IgnoreParens() : nullptr))
+dyn_cast_if_present(C ? C->IgnoreParens() : 
nullptr))
   if (Cond->isLogicalOp()) {
 std::tie(EntryConditionBlock, ExitConditionBlock) =
   VisitLogicalOperator(Cond, F, BodyBlock, LoopSuccessor);
@@ -5383,7 +5383,7 @@ bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions 
&F,
 // If the 'To' has no label or is labeled but the label isn't a
 // CaseStmt then filter this edge.
 if (const SwitchStmt *S =
-dyn_cast_or_null(From->getTerminatorStmt())) {
+dyn_cast_if_present(From->getTerminatorStmt())) {
   if (S->isAllEnumCasesCovered()) {
 const Stmt *L = To->getLabel();
 if (!L || !isa(L))

diff  --git a/clang/lib/Analysis/ThreadSafety.cpp 
b/clang/lib/Analysis/ThreadSafety.cpp
index 087994e6ebd70..1dc35edded70b 100644
--- a/clang/lib/Analysis/ThreadSafety.cpp
+++ b/clang/lib/Analysis/ThreadSafety.cpp
@@ -608,7 +608,7 @@ void VarMapBuilder::VisitDeclStmt(const DeclStmt *S) {
   bool modifiedCtx = false;
   const DeclGroupRef DGrp = S->getDeclGroup();
   for (const auto *D : DGrp) {
-if (const auto *VD = dyn_cast_or_null(D)) {
+if (const auto *VD = dyn_cast_if_present(D)) {
   const Expr *E = VD->getInit();
 
   // Add local variables with trivial type to the variable map
@@ -1347,9 +1347,9 @@ void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet &Mtxs, 
AttrType *Attr,
Expr *BrE, bool Neg) {
   // Find out which branch has the lock
   bool branch = false;
-  if (const auto *BLE = dyn_cast_or_null(BrE))
+  if (const auto *BLE = dyn_cast_if_present(BrE))
 branch = BLE->getValue();
-  else if (const auto *ILE = dyn_cast_or_null(BrE))
+  else if (const auto *ILE = dyn_cast_if_present(BrE))
 branch = ILE->getValue().getBoolValue();
 
   int branchnum = branch ? 0 : 1;
@@ -1472,7 +1472,7 @@ void ThreadSafetyAnalyzer::getEdgeLockset(FactSet& Result,
   if (!Exp)
 return;
 
-  auto *FunDecl = dyn_cast_or_null(Exp->getCalleeDecl());
+  auto *FunDecl = dyn_cast_if_present(Exp->getCalleeDecl());
   if(!FunDecl || !FunDecl->hasAttrs())
 return;
 
@@ -1787,15 +1787,15 @@ void BuildLockset::handleCall(const Expr *Exp, const 
NamedDecl *D,
 assert(!Self);
 const auto *TagT = Exp->getType()->getAs();
 if (TagT && Exp->isPRValue()) {
-  std::pair Placeholder =
+  auto [ThisPtr, DiagType] =
   Analyzer->SxBuilder.createThisPlaceholder(Exp);
   [[maybe_unused]] auto inserted =
-  ConstructedObject

[PATCH] D153854: [clang][dataflow] Make `getThisPointeeStorageLocation()` return an `AggregateStorageLocation`.

2023-06-27 Thread Martin Böhme via Phabricator via cfe-commits
mboehme created this revision.
Herald added subscribers: martong, xazax.hun.
Herald added a reviewer: NoQ.
Herald added a project: All.
mboehme requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This avoids the need for casts at callsites.

Depends On D153852 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D153854

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
  clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
  clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
  clang/unittests/Analysis/FlowSensitive/TransferTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -1517,8 +1517,7 @@
 ASSERT_THAT(Results.keys(), UnorderedElementsAre("p"));
 const Environment &Env = getEnvironmentAtAnnotation(Results, "p");
 
-const auto *ThisLoc = dyn_cast(
-Env.getThisPointeeStorageLocation());
+const auto *ThisLoc = Env.getThisPointeeStorageLocation();
 ASSERT_THAT(ThisLoc, NotNull());
 
 const ValueDecl *BarDecl = findValueDecl(ASTCtx, "Bar");
@@ -1593,8 +1592,7 @@
 ASSERT_THAT(Results.keys(), UnorderedElementsAre("p"));
 const Environment &Env = getEnvironmentAtAnnotation(Results, "p");
 
-const auto *ThisLoc =
-cast(Env.getThisPointeeStorageLocation());
+const auto *ThisLoc = Env.getThisPointeeStorageLocation();
 
 const ValueDecl *BarDecl = findValueDecl(ASTCtx, "Bar");
 ASSERT_THAT(BarDecl, NotNull());
@@ -1664,8 +1662,7 @@
 ASSERT_THAT(Results.keys(), UnorderedElementsAre("p"));
 const Environment &Env = getEnvironmentAtAnnotation(Results, "p");
 
-const auto *ThisLoc = dyn_cast(
-Env.getThisPointeeStorageLocation());
+const auto *ThisLoc = Env.getThisPointeeStorageLocation();
 ASSERT_THAT(ThisLoc, NotNull());
 
 const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
@@ -1710,8 +1707,7 @@
 ASSERT_THAT(Results.keys(), UnorderedElementsAre("p1"));
 const Environment &Env = getEnvironmentAtAnnotation(Results, "p1");
 
-const auto *ThisLoc = dyn_cast(
-Env.getThisPointeeStorageLocation());
+const auto *ThisLoc = Env.getThisPointeeStorageLocation();
 ASSERT_THAT(ThisLoc, NotNull());
 
 const ValueDecl *BarDecl = findValueDecl(ASTCtx, "Bar");
@@ -1749,8 +1745,7 @@
 ASSERT_THAT(Results.keys(), UnorderedElementsAre("p2"));
 const Environment &Env = getEnvironmentAtAnnotation(Results, "p2");
 
-const auto *ThisLoc = dyn_cast(
-Env.getThisPointeeStorageLocation());
+const auto *ThisLoc = Env.getThisPointeeStorageLocation();
 ASSERT_THAT(ThisLoc, NotNull());
 
 const ValueDecl *BarDecl = findValueDecl(ASTCtx, "Bar");
@@ -1808,8 +1803,7 @@
 ASSERT_THAT(Results.keys(), UnorderedElementsAre("p"));
 const Environment &Env = getEnvironmentAtAnnotation(Results, "p");
 
-const auto *ThisLoc = dyn_cast(
-Env.getThisPointeeStorageLocation());
+const auto *ThisLoc = Env.getThisPointeeStorageLocation();
 ASSERT_THAT(ThisLoc, NotNull());
 
 const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
@@ -1842,8 +1836,7 @@
 ASSERT_THAT(Results.keys(), UnorderedElementsAre("p"));
 const Environment &Env = getEnvironmentAtAnnotation(Results, "p");
 
-const auto *ThisLoc = dyn_cast(
-Env.getThisPointeeStorageLocation());
+const auto *ThisLoc = Env.getThisPointeeStorageLocation();
 ASSERT_THAT(ThisLoc, NotNull());
 
 const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
@@ -1876,8 +1869,7 @@
 ASSERT_THAT(Results.keys(), UnorderedElementsAre("p"));
 const Environment &Env = getEnvironmentAtAnnotation(Results, "p");
 
-const auto *ThisLoc = dyn_cast(
-Env.getThisPointeeStorageLocation());
+const auto *ThisLoc = Env.getThisPointeeStorageLocation();
 ASSERT_THAT(ThisLoc, NotNull());
 
 const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
Index: clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
===
--- clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
+++ clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
@@ -332,8 +332,7 @@
   assert(Init != nullptr);
 
   auto &Env = InputState.Env;
-  auto &ThisLoc =
-  *cast(Env.getThisPointeeStorageLocation());
+  auto &ThisLoc = *Env.getThisPointeeStorageLocation();
 
   if (!Init->isAnyMemberInitializer())
 // FIXME: Handle base initialization
Index: clang/lib/A

[clang] 0243a76 - Revert "[clang][CFG][NFC] A few smaller cleanups"

2023-06-27 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-06-27T13:06:27+02:00
New Revision: 0243a76f53abbf0bfa69e0893a4a9c8b9d926284

URL: 
https://github.com/llvm/llvm-project/commit/0243a76f53abbf0bfa69e0893a4a9c8b9d926284
DIFF: 
https://github.com/llvm/llvm-project/commit/0243a76f53abbf0bfa69e0893a4a9c8b9d926284.diff

LOG: Revert "[clang][CFG][NFC] A few smaller cleanups"

This reverts commit 173df3dd5f9a812b07f9866965f4e92a982a3fca.

Looks like this wasn't as innocent as it seemed:
https://lab.llvm.org/buildbot#builders/38/builds/12982

Added: 


Modified: 
clang/lib/Analysis/CFG.cpp
clang/lib/Analysis/ThreadSafety.cpp

Removed: 




diff  --git a/clang/lib/Analysis/CFG.cpp b/clang/lib/Analysis/CFG.cpp
index 318b0af86ab70..246bace4debcf 100644
--- a/clang/lib/Analysis/CFG.cpp
+++ b/clang/lib/Analysis/CFG.cpp
@@ -1560,7 +1560,7 @@ std::unique_ptr CFGBuilder::buildCFG(const Decl *D, 
Stmt *Statement) {
  "AddImplicitDtors and AddLifetime cannot be used at the same time");
 
   if (BuildOpts.AddImplicitDtors)
-if (const CXXDestructorDecl *DD = 
dyn_cast_if_present(D))
+if (const CXXDestructorDecl *DD = dyn_cast_or_null(D))
   addImplicitDtorsForDestructor(DD);
 
   // Visit the statements and create the CFG.
@@ -1581,7 +1581,7 @@ std::unique_ptr CFGBuilder::buildCFG(const Decl *D, 
Stmt *Statement) {
   // fields. To handle this, make a CFG branch. We only need to add one such
   // branch per constructor, since the Standard states that all virtual bases
   // shall be initialized before non-virtual bases and direct data members.
-  if (const auto *CD = dyn_cast_if_present(D)) {
+  if (const auto *CD = dyn_cast_or_null(D)) {
 CFGBlock *VBaseSucc = nullptr;
 for (auto *I : llvm::reverse(CD->inits())) {
   if (BuildOpts.AddVirtualBaseBranches && !VBaseSucc &&
@@ -3010,7 +3010,7 @@ CFGBlock *CFGBuilder::VisitDeclSubExpr(DeclStmt *DS) {
 
   // If the initializer is an ArrayInitLoopExpr, we want to extract the
   // initializer, that's used for each element.
-  const auto *AILE = dyn_cast_if_present(Init);
+  const auto *AILE = dyn_cast_or_null(Init);
 
   findConstructionContexts(
   ConstructionContextLayer::create(cfg->getBumpVectorContext(), DS),
@@ -3591,7 +3591,7 @@ CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) {
 // Specially handle logical operators, which have a slightly
 // more optimal CFG representation.
 if (BinaryOperator *Cond =
-dyn_cast_if_present(C ? C->IgnoreParens() : 
nullptr))
+dyn_cast_or_null(C ? C->IgnoreParens() : nullptr))
   if (Cond->isLogicalOp()) {
 std::tie(EntryConditionBlock, ExitConditionBlock) =
   VisitLogicalOperator(Cond, F, BodyBlock, LoopSuccessor);
@@ -5383,7 +5383,7 @@ bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions 
&F,
 // If the 'To' has no label or is labeled but the label isn't a
 // CaseStmt then filter this edge.
 if (const SwitchStmt *S =
-dyn_cast_if_present(From->getTerminatorStmt())) {
+dyn_cast_or_null(From->getTerminatorStmt())) {
   if (S->isAllEnumCasesCovered()) {
 const Stmt *L = To->getLabel();
 if (!L || !isa(L))

diff  --git a/clang/lib/Analysis/ThreadSafety.cpp 
b/clang/lib/Analysis/ThreadSafety.cpp
index 1dc35edded70b..087994e6ebd70 100644
--- a/clang/lib/Analysis/ThreadSafety.cpp
+++ b/clang/lib/Analysis/ThreadSafety.cpp
@@ -608,7 +608,7 @@ void VarMapBuilder::VisitDeclStmt(const DeclStmt *S) {
   bool modifiedCtx = false;
   const DeclGroupRef DGrp = S->getDeclGroup();
   for (const auto *D : DGrp) {
-if (const auto *VD = dyn_cast_if_present(D)) {
+if (const auto *VD = dyn_cast_or_null(D)) {
   const Expr *E = VD->getInit();
 
   // Add local variables with trivial type to the variable map
@@ -1347,9 +1347,9 @@ void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet &Mtxs, 
AttrType *Attr,
Expr *BrE, bool Neg) {
   // Find out which branch has the lock
   bool branch = false;
-  if (const auto *BLE = dyn_cast_if_present(BrE))
+  if (const auto *BLE = dyn_cast_or_null(BrE))
 branch = BLE->getValue();
-  else if (const auto *ILE = dyn_cast_if_present(BrE))
+  else if (const auto *ILE = dyn_cast_or_null(BrE))
 branch = ILE->getValue().getBoolValue();
 
   int branchnum = branch ? 0 : 1;
@@ -1472,7 +1472,7 @@ void ThreadSafetyAnalyzer::getEdgeLockset(FactSet& Result,
   if (!Exp)
 return;
 
-  auto *FunDecl = dyn_cast_if_present(Exp->getCalleeDecl());
+  auto *FunDecl = dyn_cast_or_null(Exp->getCalleeDecl());
   if(!FunDecl || !FunDecl->hasAttrs())
 return;
 
@@ -1787,15 +1787,15 @@ void BuildLockset::handleCall(const Expr *Exp, const 
NamedDecl *D,
 assert(!Self);
 const auto *TagT = Exp->getType()->getAs();
 if (TagT && Exp->isPRValue()) {
-  auto [ThisPtr, DiagType] =
+  std::pair Placeholder =
   Analyzer->SxBuilder.createThisPlaceholde

[clang] 268032f - [clang] Add myself as code owner for the new constant interpreter

2023-06-27 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-06-27T13:39:03+02:00
New Revision: 268032f6f10d595bb723f6b4a21632a9f3b35be8

URL: 
https://github.com/llvm/llvm-project/commit/268032f6f10d595bb723f6b4a21632a9f3b35be8
DIFF: 
https://github.com/llvm/llvm-project/commit/268032f6f10d595bb723f6b4a21632a9f3b35be8.diff

LOG: [clang] Add myself as code owner for the new constant interpreter

As discussed in the RFC at
https://discourse.llvm.org/t/rfc-proposing-a-code-owner-for-the-experimental-constexpr-interpreter/71514

Added: 


Modified: 
clang/CodeOwners.rst

Removed: 




diff  --git a/clang/CodeOwners.rst b/clang/CodeOwners.rst
index b2183a72b0a7f..771f245a49eba 100644
--- a/clang/CodeOwners.rst
+++ b/clang/CodeOwners.rst
@@ -58,6 +58,12 @@ Analysis & CFG
 | sgatev\@google.com (email), sgatev (Phabricator), sgatev (GitHub)
 
 
+Experimental new constant interpreter
+~
+| Timm Bäder
+| tbae...@redhat.com (email), tbaeder (Phabricator), tbaederr (GitHub)
+
+
 Modules & serialization
 ~~~
 | Chuanqi Xu



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153241: [clang][Diagnostics] Provide source range to invalid casts in const expr

2023-06-27 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder added a comment.

Ping


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153241/new/

https://reviews.llvm.org/D153241

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153857: [clang] Fix new-expression with elaborated-type-specifier

2023-06-27 Thread Mariya Podchishchaeva via Phabricator via cfe-commits
Fznamznon created this revision.
Herald added a project: All.
Fznamznon requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Expressions like

  new struct A {};
  struct A* b = (1 == 1) ? new struct A : new struct A;
  ``
  Were parsed as definitions of `struct A` and failed, however as clarified by
  `CWG2141` new-expression cannot define a type, so both these examples
  should be considered as valid.
  The patch adds a "new" kind context for parsing declaration specifiers in
  addition to already existing declarator context in order to track that
  the parser is inside of a new expression.
  
  Fixes https://github.com/llvm/llvm-project/issues/34341


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D153857

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Parse/Parser.h
  clang/lib/Parse/ParseDecl.cpp
  clang/lib/Parse/ParseExprCXX.cpp
  clang/test/CXX/dcl.dcl/dcl.spec/dcl.type/p3-0x.cpp
  clang/test/CXX/drs/dr19xx.cpp
  clang/test/CXX/drs/dr6xx.cpp
  clang/test/Parser/cxx11-type-specifier.cpp

Index: clang/test/Parser/cxx11-type-specifier.cpp
===
--- clang/test/Parser/cxx11-type-specifier.cpp
+++ clang/test/Parser/cxx11-type-specifier.cpp
@@ -13,10 +13,10 @@
   } catch (constexpr int) { // expected-error{{type name does not allow constexpr}}
   }
 
-  // These parse as type definitions, not as type references with braced
-  // initializers. Sad but true...
-  (void) new struct S {}; // expected-error{{'S' cannot be defined in a type specifier}}
-  (void) new enum E { e }; // expected-error{{'E' cannot be defined in a type specifier}}
+  (void) new struct S {};
+  (void) new enum E { e };
+  struct S *a = (1 == 1) ? new struct S : new struct S;
+  struct A *b = (1 == 1) ? new struct A : new struct A; // expected-error 2{{allocation of incomplete type}} // expected-note 2{{forward}}
 }
 
 // And for trailing-type-specifier-seq
Index: clang/test/CXX/drs/dr6xx.cpp
===
--- clang/test/CXX/drs/dr6xx.cpp
+++ clang/test/CXX/drs/dr6xx.cpp
@@ -1078,9 +1078,10 @@
 (void)const_cast(0); // expected-error {{cannot be defined in a type specifier}}
 (void)sizeof(struct F*);
 (void)sizeof(struct F{}*); // expected-error {{cannot be defined in a type specifier}}
-(void)new struct G*;
-(void)new struct G{}*; // expected-error {{cannot be defined in a type specifier}}
+(void)new struct G*; // expected-note {{forward}}
+(void)new struct G{}*; // expected-error {{incomplete}}
 #if __cplusplus >= 201103L
+// expected-error@-2 {{expected expression}}
 (void)alignof(struct H*);
 (void)alignof(struct H{}*); // expected-error {{cannot be defined in a type specifier}}
 #endif
Index: clang/test/CXX/drs/dr19xx.cpp
===
--- clang/test/CXX/drs/dr19xx.cpp
+++ clang/test/CXX/drs/dr19xx.cpp
@@ -194,7 +194,7 @@
 enum E : int {1}; // expected-error {{expected identifier}} (not bit-field)
   };
   auto *p1 = new enum E : int; // expected-error {{only permitted as a standalone declaration}}
-  auto *p2 = new enum F : int {}; // expected-error {{cannot be defined in a type specifier}}
+  auto *p2 = new enum F : int {}; // expected-error {{only permitted as a standalone declaration}}
   auto *p3 = true ? new enum G : int {}; // expected-error {{forward reference}} expected-error {{incomplete}} expected-note {{declaration}}
   auto h() -> enum E : int {}; // expected-error {{only permitted as a standalone declaration}}
 
Index: clang/test/CXX/dcl.dcl/dcl.spec/dcl.type/p3-0x.cpp
===
--- clang/test/CXX/dcl.dcl/dcl.spec/dcl.type/p3-0x.cpp
+++ clang/test/CXX/dcl.dcl/dcl.spec/dcl.type/p3-0x.cpp
@@ -21,8 +21,8 @@
   for (struct S { S(int) {} } s : Undeclared); // expected-error{{types may not be defined in a for range declaration}}
// expected-error@-1{{use of undeclared identifier 'Undeclared'}}
 
-  new struct T {}; // expected-error {{'T' cannot be defined in a type specifier}}
-  new struct A {}; // expected-error {{'A' cannot be defined in a type specifier}}
+  new struct T {}; // expected-error {{allocation of incomplete type 'struct T'}} //expected-note{{forward declaration of 'T'}}
+  new struct A {};
 
   try {} catch (struct U {}) {} // expected-error {{'U' cannot be defined in a type specifier}}
 
Index: clang/lib/Parse/ParseExprCXX.cpp
===
--- clang/lib/Parse/ParseExprCXX.cpp
+++ clang/lib/Parse/ParseExprCXX.cpp
@@ -3231,7 +3231,7 @@
 // A new-type-id is a simplified type-id, where essentially the
 // direct-declarator is replaced by a direct-new-declarator.
 MaybeParseGNUAttributes(DeclaratorInfo);
-if (ParseCXXTypeSpecifierSeq(DS))
+if

[PATCH] D153314: [clang] Replace uses of CGBuilderTy::CreateElementBitCast (NFC)

2023-06-27 Thread Youngsuk Kim via Phabricator via cfe-commits
JOE1994 updated this revision to Diff 534913.
JOE1994 added a comment.

Apply suggested change from nikic
(sorry, I missed it out in the previous update)


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153314/new/

https://reviews.llvm.org/D153314

Files:
  clang/lib/CodeGen/CGAtomic.cpp
  clang/lib/CodeGen/CGCXXABI.cpp
  clang/lib/CodeGen/CGNonTrivialStruct.cpp
  clang/lib/CodeGen/MicrosoftCXXABI.cpp
  clang/lib/CodeGen/Targets/AArch64.cpp
  clang/lib/CodeGen/Targets/ARM.cpp
  clang/lib/CodeGen/Targets/Hexagon.cpp
  clang/lib/CodeGen/Targets/LoongArch.cpp
  clang/lib/CodeGen/Targets/PPC.cpp
  clang/lib/CodeGen/Targets/X86.cpp

Index: clang/lib/CodeGen/Targets/X86.cpp
===
--- clang/lib/CodeGen/Targets/X86.cpp
+++ clang/lib/CodeGen/Targets/X86.cpp
@@ -318,8 +318,7 @@
   ResultTruncRegTypes.push_back(CoerceTy);
 
   // Coerce the integer by bitcasting the return slot pointer.
-  ReturnSlot.setAddress(
-  CGF.Builder.CreateElementBitCast(ReturnSlot.getAddress(CGF), CoerceTy));
+  ReturnSlot.setAddress(ReturnSlot.getAddress(CGF).withElementType(CoerceTy));
   ResultRegDests.push_back(ReturnSlot);
 
   rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
@@ -3048,7 +3047,7 @@
 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
 llvm::StructType *ST = cast(AI.getCoerceToType());
 Address Tmp = CGF.CreateMemTemp(Ty);
-Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
+Tmp = Tmp.withElementType(ST);
 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
 llvm::Type *TyLo = ST->getElementType(0);
 llvm::Type *TyHi = ST->getElementType(1);
@@ -3076,11 +3075,10 @@
 CharUnits::fromQuantity(getDataLayout().getABITypeAlign(TyHi)));
 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
 
-RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
+RegAddr = Tmp.withElementType(LTy);
   } else if (neededInt) {
 RegAddr = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, gp_offset),
-  CGF.Int8Ty, CharUnits::fromQuantity(8));
-RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
+  LTy, CharUnits::fromQuantity(8));
 
 // Copy to a temporary if necessary to ensure the appropriate alignment.
 auto TInfo = getContext().getTypeInfoInChars(Ty);
@@ -3097,8 +3095,7 @@
 
   } else if (neededSSE == 1) {
 RegAddr = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, fp_offset),
-  CGF.Int8Ty, CharUnits::fromQuantity(16));
-RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
+  LTy, CharUnits::fromQuantity(16));
   } else {
 assert(neededSSE == 2 && "Invalid number of needed registers!");
 // SSE registers are spaced 16 bytes apart in the register save
@@ -3118,15 +3115,15 @@
  : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy);
 llvm::Value *V;
 Address Tmp = CGF.CreateMemTemp(Ty);
-Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
-V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
-RegAddrLo, ST->getStructElementType(0)));
+Tmp = Tmp.withElementType(ST);
+V = CGF.Builder.CreateLoad(
+RegAddrLo.withElementType(ST->getStructElementType(0)));
 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
-V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
-RegAddrHi, ST->getStructElementType(1)));
+V = CGF.Builder.CreateLoad(
+RegAddrHi.withElementType(ST->getStructElementType(1)));
 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
 
-RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
+RegAddr = Tmp.withElementType(LTy);
   }
 
   // AMD64-ABI 3.5.7p5: Step 5. Set:
Index: clang/lib/CodeGen/Targets/PPC.cpp
===
--- clang/lib/CodeGen/Targets/PPC.cpp
+++ clang/lib/CodeGen/Targets/PPC.cpp
@@ -31,8 +31,8 @@
   }
 
   llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
-  RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
-  ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
+  RealAddr = RealAddr.withElementType(EltTy);
+  ImagAddr = ImagAddr.withElementType(EltTy);
   llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
   llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
 
@@ -456,8 +456,7 @@
 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
 RegAddr = Address(
 Builder.CreateInBoundsGEP(CGF.Int8Ty, RegAddr.getPointer(), RegOffset),
-CGF.Int8Ty, RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
-RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
+DirectTy, RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
 
 // Increase the used-register count.
  

[PATCH] D153560: [Clang] Allow C++11 style initialisation of SVE types.

2023-06-27 Thread Paul Walker via Phabricator via cfe-commits
paulwalker-arm updated this revision to Diff 534914.
paulwalker-arm added a comment.

Rebased and updated to allow copy initialisation.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153560/new/

https://reviews.llvm.org/D153560

Files:
  clang/lib/CodeGen/CGExprScalar.cpp
  clang/test/CodeGenCXX/aarch64-sve-vector-init.cpp

Index: clang/test/CodeGenCXX/aarch64-sve-vector-init.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/aarch64-sve-vector-init.cpp
@@ -0,0 +1,881 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --version 2
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve -emit-llvm -o - %s | FileCheck %s
+
+// CHECK-LABEL: define dso_local void @_Z11test_localsv
+// CHECK-SAME: () #[[ATTR0:[0-9]+]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[S8:%.*]] = alloca , align 16
+// CHECK-NEXT:[[S16:%.*]] = alloca , align 16
+// CHECK-NEXT:[[S32:%.*]] = alloca , align 16
+// CHECK-NEXT:[[S64:%.*]] = alloca , align 16
+// CHECK-NEXT:[[U8:%.*]] = alloca , align 16
+// CHECK-NEXT:[[U16:%.*]] = alloca , align 16
+// CHECK-NEXT:[[U32:%.*]] = alloca , align 16
+// CHECK-NEXT:[[U64:%.*]] = alloca , align 16
+// CHECK-NEXT:[[F16:%.*]] = alloca , align 16
+// CHECK-NEXT:[[F32:%.*]] = alloca , align 16
+// CHECK-NEXT:[[F64:%.*]] = alloca , align 16
+// CHECK-NEXT:[[BF16:%.*]] = alloca , align 16
+// CHECK-NEXT:[[S8X2:%.*]] = alloca , align 16
+// CHECK-NEXT:[[S16X2:%.*]] = alloca , align 16
+// CHECK-NEXT:[[S32X2:%.*]] = alloca , align 16
+// CHECK-NEXT:[[X64X2:%.*]] = alloca , align 16
+// CHECK-NEXT:[[U8X2:%.*]] = alloca , align 16
+// CHECK-NEXT:[[U16X2:%.*]] = alloca , align 16
+// CHECK-NEXT:[[U32X2:%.*]] = alloca , align 16
+// CHECK-NEXT:[[U64X2:%.*]] = alloca , align 16
+// CHECK-NEXT:[[F16X2:%.*]] = alloca , align 16
+// CHECK-NEXT:[[F32X2:%.*]] = alloca , align 16
+// CHECK-NEXT:[[F64X2:%.*]] = alloca , align 16
+// CHECK-NEXT:[[BF16X2:%.*]] = alloca , align 16
+// CHECK-NEXT:[[S8X3:%.*]] = alloca , align 16
+// CHECK-NEXT:[[S16X3:%.*]] = alloca , align 16
+// CHECK-NEXT:[[S32X3:%.*]] = alloca , align 16
+// CHECK-NEXT:[[X64X3:%.*]] = alloca , align 16
+// CHECK-NEXT:[[U8X3:%.*]] = alloca , align 16
+// CHECK-NEXT:[[U16X3:%.*]] = alloca , align 16
+// CHECK-NEXT:[[U32X3:%.*]] = alloca , align 16
+// CHECK-NEXT:[[U64X3:%.*]] = alloca , align 16
+// CHECK-NEXT:[[F16X3:%.*]] = alloca , align 16
+// CHECK-NEXT:[[F32X3:%.*]] = alloca , align 16
+// CHECK-NEXT:[[F64X3:%.*]] = alloca , align 16
+// CHECK-NEXT:[[BF16X3:%.*]] = alloca , align 16
+// CHECK-NEXT:[[S8X4:%.*]] = alloca , align 16
+// CHECK-NEXT:[[S16X4:%.*]] = alloca , align 16
+// CHECK-NEXT:[[S32X4:%.*]] = alloca , align 16
+// CHECK-NEXT:[[X64X4:%.*]] = alloca , align 16
+// CHECK-NEXT:[[U8X4:%.*]] = alloca , align 16
+// CHECK-NEXT:[[U16X4:%.*]] = alloca , align 16
+// CHECK-NEXT:[[U32X4:%.*]] = alloca , align 16
+// CHECK-NEXT:[[U64X4:%.*]] = alloca , align 16
+// CHECK-NEXT:[[F16X4:%.*]] = alloca , align 16
+// CHECK-NEXT:[[F32X4:%.*]] = alloca , align 16
+// CHECK-NEXT:[[F64X4:%.*]] = alloca , align 16
+// CHECK-NEXT:[[BF16X4:%.*]] = alloca , align 16
+// CHECK-NEXT:[[B8:%.*]] = alloca , align 2
+// CHECK-NEXT:[[B8X2:%.*]] = alloca , align 2
+// CHECK-NEXT:[[B8X4:%.*]] = alloca , align 2
+// CHECK-NEXT:store  zeroinitializer, ptr [[S8]], align 16
+// CHECK-NEXT:store  zeroinitializer, ptr [[S16]], align 16
+// CHECK-NEXT:store  zeroinitializer, ptr [[S32]], align 16
+// CHECK-NEXT:store  zeroinitializer, ptr [[S64]], align 16
+// CHECK-NEXT:store  zeroinitializer, ptr [[U8]], align 16
+// CHECK-NEXT:store  zeroinitializer, ptr [[U16]], align 16
+// CHECK-NEXT:store  zeroinitializer, ptr [[U32]], align 16
+// CHECK-NEXT:store  zeroinitializer, ptr [[U64]], align 16
+// CHECK-NEXT:store  zeroinitializer, ptr [[F16]], align 16
+// CHECK-NEXT:store  zeroinitializer, ptr [[F32]], align 16
+// CHECK-NEXT:store  zeroinitializer, ptr [[F64]], align 16
+// CHECK-NEXT:store  zeroinitializer, ptr [[BF16]], align 16
+// CHECK-NEXT:store  zeroinitializer, ptr [[S8X2]], align 16
+// CHECK-NEXT:store  zeroinitializer, ptr [[S16X2]], align 16
+// CHECK-NEXT:store  zeroinitializer, ptr [[S32X2]], align 16
+// CHECK-NEXT:store  zeroinitializer, ptr [[X64X2]], align 16
+// CHECK-NEXT:store  zeroinitializer, ptr [[U8X2]], align 16
+// CHECK-NEXT:store  zeroinitializer, ptr [[U16X2]], align 16
+// CHECK-NEXT:store  zeroinitializer, ptr [[U32X2]], align 16
+// CHECK-NEXT:store  zeroinitializer, ptr [[U64X2]], align 16
+// CHECK-NEXT:store  zeroinitializer, ptr [[F16X2]], align 16
+// CHECK-NEXT:store  zeroinitial

[PATCH] D153652: [Support] Don't set "all_exe" mode by default for file written by llvm::writeToOutput

2023-06-27 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 534917.
hokein marked 2 inline comments as done.
hokein added a comment.

fix the test failures on windows


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153652/new/

https://reviews.llvm.org/D153652

Files:
  llvm/lib/Support/raw_ostream.cpp
  llvm/test/tools/llvm-dwarfutil/ELF/X86/mirror-permissions-unix.test
  llvm/unittests/Support/raw_ostream_test.cpp


Index: llvm/unittests/Support/raw_ostream_test.cpp
===
--- llvm/unittests/Support/raw_ostream_test.cpp
+++ llvm/unittests/Support/raw_ostream_test.cpp
@@ -495,6 +495,11 @@
   ASSERT_FALSE(sys::fs::createTemporaryFile("foo", "bar", FD, Path));
   FileRemover Cleanup(Path);
 
+#ifndef _WIN32
+  ErrorOr Perms = llvm::sys::fs::getPermissions(Path);
+  EXPECT_TRUE(Perms && !(*Perms & llvm::sys::fs::all_exe));
+#endif
+
   ASSERT_THAT_ERROR(writeToOutput(Path,
   [](raw_ostream &Out) -> Error {
 Out << "HelloWorld";
@@ -502,6 +507,12 @@
   }),
 Succeeded());
   checkFileData(Path, "HelloWorld");
+
+#ifndef _WIN32
+  // No exe bit set by the writeToOutput API.
+  Perms = llvm::sys::fs::getPermissions(Path);
+  EXPECT_TRUE(Perms && !(*Perms & llvm::sys::fs::all_exe));
+#endif
 }
 
 TEST(raw_ostreamTest, writeToNonexistingPath) {
Index: llvm/test/tools/llvm-dwarfutil/ELF/X86/mirror-permissions-unix.test
===
--- /dev/null
+++ llvm/test/tools/llvm-dwarfutil/ELF/X86/mirror-permissions-unix.test
@@ -0,0 +1,51 @@
+## The Unix version of this test must use umask(1) because
+## llvm-dwarfutil respects the umask in setting output permissions.
+## Setting the umask to 0 ensures deterministic permissions across
+## test environments.
+# UNSUPPORTED: system-windows
+# REQUIRES: shell
+
+# RUN: touch %t
+# RUN: chmod 0777 %t
+# RUN: ls -l %t | cut -f 1 -d ' ' > %t.0777
+# RUN: chmod 0666 %t
+# RUN: ls -l %t | cut -f 1 -d ' ' > %t.0666
+# RUN: chmod 0640 %t
+# RUN: ls -l %t | cut -f 1 -d ' ' > %t.0640
+
+## Set umask to be permissive of all permissions,
+## only test mirroring of permissions.
+# RUN: umask 0
+
+# RUN: yaml2obj %s -o %t
+
+# RUN: chmod 0777 %t
+# RUN: llvm-dwarfutil --no-garbage-collection %t %t1
+# RUN: ls -l %t1 | cut -f 1 -d ' ' > %t1.perms
+# RUN: cmp %t1.perms %t.0777
+# RUN: llvm-dwarfutil --garbage-collection --separate-debug-file %t %t2
+# RUN: ls -l %t2 | cut -f 1 -d ' ' > %t2.perms
+# RUN: cmp %t2.perms %t.0777
+
+# RUN: chmod 0666 %t
+# RUN: llvm-dwarfutil --no-garbage-collection %t %t1
+# RUN: ls -l %t1 | cut -f 1 -d ' ' > %t1.perms
+# RUN: cmp %t1.perms %t.0666
+# RUN: llvm-dwarfutil --garbage-collection --separate-debug-file %t %t2
+# RUN: ls -l %t2 | cut -f 1 -d ' ' > %t2.perms
+# RUN: cmp %t2.perms %t.0666
+
+# RUN: chmod 0640 %t
+# RUN: llvm-dwarfutil --no-garbage-collection %t %t1
+# RUN: ls -l %t1 | cut -f 1 -d ' ' > %t1.perms
+# RUN: cmp %t1.perms %t.0640
+# RUN: llvm-dwarfutil --garbage-collection --separate-debug-file %t %t2
+# RUN: ls -l %t2 | cut -f 1 -d ' ' > %t2.perms
+# RUN: cmp %t2.perms %t.0640
+
+--- !ELF
+FileHeader:
+  Class:   ELFCLASS64
+  Data:ELFDATA2LSB
+  Type:ET_EXEC
+  Machine: EM_X86_64
Index: llvm/lib/Support/raw_ostream.cpp
===
--- llvm/lib/Support/raw_ostream.cpp
+++ llvm/lib/Support/raw_ostream.cpp
@@ -1007,7 +1007,7 @@
 return Write(Out);
   }
 
-  unsigned Mode = sys::fs::all_read | sys::fs::all_write | sys::fs::all_exe;
+  unsigned Mode = sys::fs::all_read | sys::fs::all_write;
   Expected Temp =
   sys::fs::TempFile::create(OutputFileName + ".temp-stream-%%", Mode);
   if (!Temp)


Index: llvm/unittests/Support/raw_ostream_test.cpp
===
--- llvm/unittests/Support/raw_ostream_test.cpp
+++ llvm/unittests/Support/raw_ostream_test.cpp
@@ -495,6 +495,11 @@
   ASSERT_FALSE(sys::fs::createTemporaryFile("foo", "bar", FD, Path));
   FileRemover Cleanup(Path);
 
+#ifndef _WIN32
+  ErrorOr Perms = llvm::sys::fs::getPermissions(Path);
+  EXPECT_TRUE(Perms && !(*Perms & llvm::sys::fs::all_exe));
+#endif
+
   ASSERT_THAT_ERROR(writeToOutput(Path,
   [](raw_ostream &Out) -> Error {
 Out << "HelloWorld";
@@ -502,6 +507,12 @@
   }),
 Succeeded());
   checkFileData(Path, "HelloWorld");
+
+#ifndef _WIN32
+  // No exe bit set by the writeToOutput API.
+  Perms = llvm::sys::fs::getPermissions(Path);
+  EXPECT_TRUE(Perms && !(*Perms & llvm::sys::fs::all_exe));
+#endif
 }
 
 TEST(raw_ostreamTest, writeToNonexistingPath) {
Index: llvm/test/tools/llvm-dwarfutil/ELF/X86/mirror-permissions-unix.test
=

[PATCH] D153652: [Support] Don't set "all_exe" mode by default for file written by llvm::writeToOutput

2023-06-27 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

In D153652#4451292 , @jhenderson 
wrote:

> The updated unit test is failing on Windows in the pre-merge checks. Please 
> investigate and fix as appropriate.

Good catch, thanks. I have restricted the unittest to linux only, I think it 
should be fine -- the behavior on windows is a bit different, the exe bit is 
set even you only set `read|write` bits, the `unittests/Support/Path.cpp` 
verifies that behavior.




Comment at: llvm/unittests/Support/raw_ostream_test.cpp:499
+  ErrorOr Perms = llvm::sys::fs::getPermissions(Path);
+  ASSERT_TRUE(!!Perms);
+  EXPECT_EQ(0, *Perms & llvm::sys::fs::all_exe);

avl wrote:
> !!  looks a bit unclear. Probably check it in more explicit way?
> 
> EXPECT_TRUE(Perms && !(*Perms & llvm::sys::fs::all_exe)); 
sure, done.



Comment at: llvm/unittests/Support/raw_ostream_test.cpp:500
+  ASSERT_TRUE(!!Perms);
+  EXPECT_EQ(0, *Perms & llvm::sys::fs::all_exe);
+

jhenderson wrote:
> Here and below, rather than just checking the all_exe bit, let's check the 
> permissions are exactly what are expected (e.g. does it have the read/write 
> perms?). 
checking all existing bits is a bit tricky here (I tried it, then gave up):

- createTemporaryFile() creates a file with `owner_read | owner_write`
- writeToOutput() sets the written file to `all_read | all_write`

Both API don't provide a way to customize these bits, and they're internal 
details. We could test against them, but testing the implementation details 
seems subtle. And here we aim to verify the exe-bit not set by the 
`writeToOutput`, so I think just testing the exe-bit is not set should be 
enough. 


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153652/new/

https://reviews.llvm.org/D153652

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153369: [OpenMP] Always apply target declarations to canonical definitions

2023-06-27 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added a comment.

Did you try instead fix the OMPDeclareTargetDeclAttr::getActiveAttr() function 
to make it look through all the declarations and return the attribute from the 
first found instead of adding a new attribute?




Comment at: clang/lib/Sema/SemaOpenMP.cpp:22993-22999
+  if (auto *CD = dyn_cast(ND->getCanonicalDecl())) {
+if (!CD->hasAttr()) {
+  CD->addAttr(A);
+  if (ASTMutationListener *ML = Context.getASTMutationListener())
+ML->DeclarationMarkedOpenMPDeclareTarget(CD, A);
+}
+  }

Here it would be better to reconstruct the attribute and make it implicit 
attribute.



Comment at: clang/lib/Sema/SemaOpenMP.cpp:23105-23112
+// If this was not a canonical definition we need to update it as well.
+if (auto *CD = dyn_cast(D->getCanonicalDecl())) {
+  if (!CD->hasAttr()) {
+CD->addAttr(A);
+if (ASTMutationListener *ML = Context.getASTMutationListener())
+  ML->DeclarationMarkedOpenMPDeclareTarget(CD, A);
+  }

Here it would be better to reconstruct the attribute and make it implicit 
attribute


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153369/new/

https://reviews.llvm.org/D153369

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153701: [Clang] Implement P2718R0 "Lifetime extension in range-based for loops"

2023-06-27 Thread Yurong via Phabricator via cfe-commits
yronglin updated this revision to Diff 534920.
yronglin added a comment.

Poke CI


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153701/new/

https://reviews.llvm.org/D153701

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/AST/Decl.h
  clang/include/clang/Sema/Sema.h
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaExprCXX.cpp
  clang/lib/Sema/SemaStmt.cpp
  clang/test/CodeGenCXX/for-range-temporaries.cpp
  clang/www/cxx_status.html

Index: clang/www/cxx_status.html
===
--- clang/www/cxx_status.html
+++ clang/www/cxx_status.html
@@ -413,7 +413,7 @@
 
   Lifetime extension in range-based for loops
   https://wg21.link/P2718R0";>P2718R0
-  No
+  Clang 17
 
 
 
Index: clang/test/CodeGenCXX/for-range-temporaries.cpp
===
--- clang/test/CodeGenCXX/for-range-temporaries.cpp
+++ clang/test/CodeGenCXX/for-range-temporaries.cpp
@@ -1,9 +1,10 @@
-// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -std=c++11 -emit-llvm -o - -UDESUGAR %s | FileCheck %s
-// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -std=c++11 -emit-llvm -o - -DDESUGAR %s | FileCheck %s
-// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -std=c++11 -emit-llvm -o - -UDESUGAR -DTEMPLATE %s | FileCheck %s
-// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -std=c++11 -emit-llvm -o - -DDESUGAR -DTEMPLATE %s | FileCheck %s
-// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -std=c++11 -emit-llvm -o - -UDESUGAR -DTEMPLATE -DDEPENDENT %s | FileCheck %s
-// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -std=c++11 -emit-llvm -o - -DDESUGAR -DTEMPLATE -DDEPENDENT %s | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -std=c++11 -emit-llvm -o - -UDESUGAR %s | FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-NO-EXT-LIFETIME
+// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -std=c++11 -emit-llvm -o - -DDESUGAR %s | FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-NO-EXT-LIFETIME
+// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -std=c++11 -emit-llvm -o - -UDESUGAR -DTEMPLATE %s | FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-NO-EXT-LIFETIME
+// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -std=c++11 -emit-llvm -o - -DDESUGAR -DTEMPLATE %s | FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-NO-EXT-LIFETIME
+// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -std=c++11 -emit-llvm -o - -UDESUGAR -DTEMPLATE -DDEPENDENT %s | FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-NO-EXT-LIFETIME
+// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -std=c++11 -emit-llvm -o - -DDESUGAR -DTEMPLATE -DDEPENDENT %s | FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-NO-EXT-LIFETIME
+// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -std=c++20 -emit-llvm -o - -UDESUGAR %s | FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-EXT-LIFETIME
 
 struct A {
   A();
@@ -103,8 +104,8 @@
 // CHECK: call void @_ZN1BC1Ev(
 // CHECK: call void @_ZN1CC1ERK1B(
 // CHECK: call void @_ZN1DC1ERK1C(
-// CHECK: call void @_ZN1CD1Ev(
-// CHECK: call void @_ZN1BD1Ev(
+// CHECK-NO-EXT-LIFETIME: call void @_ZN1CD1Ev(
+// CHECK-NO-EXT-LIFETIME: call void @_ZN1BD1Ev(
 // CHECK: call void @_ZN1DC1ERKS_(
 // CHECK: call void @_Z5begin1D(
 // CHECK: call void @_ZN1DD1Ev(
@@ -122,6 +123,8 @@
 // CHECK: [[CLEANUP]]:
 // CHECK: call void @_ZN1ED1Ev(
 // CHECK: call void @_ZN1ED1Ev(
+// CHECK-EXT-LIFETIME: call void @_ZN1CD1Ev(
+// CHECK-EXT-LIFETIME: call void @_ZN1BD1Ev(
 // In for-range:
 // call void @_ZN1DD1Ev(
 // CHECK: br label %[[END:.*]]
@@ -142,5 +145,6 @@
 // CHECK: [[END]]:
 // In desugared version:
 // call void @_ZN1DD1Ev(
+// CHECK-EXT-LIFETIME: call void @_ZN1DD1Ev(
 // CHECK: call void @_ZN1AD1Ev(
 // CHECK: ret void
Index: clang/lib/Sema/SemaStmt.cpp
===
--- clang/lib/Sema/SemaStmt.cpp
+++ clang/lib/Sema/SemaStmt.cpp
@@ -2529,6 +2529,7 @@
   VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
Context.getAutoRRefDeductType(),
std::string("__range") + DepthStr);
+  RangeVar->setCXXForRangeInitializer(true);
   if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
 diag::err_for_range_deduction_failure)) {
 ActOnInitializerError(LoopVar);
Index: clang/lib/Sema/SemaExprCXX.cpp
===
--- clang/lib/Sema/SemaExprCXX.cpp
+++ clang/lib/Sema/SemaExprCXX.cpp
@@ -8807,7 +8807,8 @@
 
 ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
  bool DiscardedValue, bool IsConstexpr,
- bool IsTemplateArgument) {
+ bool IsTemplateArgument,
+ bool IsFo

[PATCH] D153241: [clang][Diagnostics] Provide source range to invalid casts in const expr

2023-06-27 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin accepted this revision.
cor3ntin added a comment.
This revision is now accepted and ready to land.

LGTM (modulo failed build / rebase)


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153241/new/

https://reviews.llvm.org/D153241

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153369: [OpenMP] Always apply target declarations to canonical definitions

2023-06-27 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 added a comment.

In D153369#4451993 , @ABataev wrote:

> Did you try instead fix the OMPDeclareTargetDeclAttr::getActiveAttr() 
> function to make it look through all the declarations and return the 
> attribute from the first found instead of adding a new attribute?

I originally tried that but found that once we've found a canonical 
declaration, nothing will really bind to the new non-canonical definition. So 
the only way to do it would be to scan the entire file with the source manager 
as far as I could tell. I could be wrong though, I'm not as familiar with Clang 
here.




Comment at: clang/lib/Sema/SemaOpenMP.cpp:23105-23112
+// If this was not a canonical definition we need to update it as well.
+if (auto *CD = dyn_cast(D->getCanonicalDecl())) {
+  if (!CD->hasAttr()) {
+CD->addAttr(A);
+if (ASTMutationListener *ML = Context.getASTMutationListener())
+  ML->DeclarationMarkedOpenMPDeclareTarget(CD, A);
+  }

ABataev wrote:
> Here it would be better to reconstruct the attribute and make it implicit 
> attribute
I thought it was already implcit since we use 
`OMPDeclareTargetDeclAttr::CreateImplicit` above, what would be different in 
the new version?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153369/new/

https://reviews.llvm.org/D153369

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153690: [clang][Sema] Remove dead diagnostic for loss of __unaligned qualifier

2023-06-27 Thread Takuya Shimizu via Phabricator via cfe-commits
hazohelet added a comment.

Ah looking at the code again, I noticed this change is not NFC. This suppresses 
inappropriate diagnostics (example added in summary).


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153690/new/

https://reviews.llvm.org/D153690

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153369: [OpenMP] Always apply target declarations to canonical definitions

2023-06-27 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added a comment.

In D153369#4452008 , @jhuber6 wrote:

> In D153369#4451993 , @ABataev wrote:
>
>> Did you try instead fix the OMPDeclareTargetDeclAttr::getActiveAttr() 
>> function to make it look through all the declarations and return the 
>> attribute from the first found instead of adding a new attribute?
>
> I originally tried that but found that once we've found a canonical 
> declaration, nothing will really bind to the new non-canonical definition. So 
> the only way to do it would be to scan the entire file with the source 
> manager as far as I could tell. I could be wrong though, I'm not as familiar 
> with Clang here.

Hmm, it should not be so. Did you try to get redecls()?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153369/new/

https://reviews.llvm.org/D153369

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153860: [clang-tidy] Fix modernize-use-std-print check when return value used

2023-06-27 Thread Mike Crowe via Phabricator via cfe-commits
mikecrowe created this revision.
mikecrowe added a reviewer: PiotrZSL.
Herald added subscribers: carlosgalvezp, xazax.hun.
Herald added a reviewer: njames93.
Herald added a project: All.
mikecrowe requested review of this revision.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

The initial implementation of the modernize-use-std-print check was
capable of converting calls to printf (etc.) which used the return value
to calls to std::print which has no return value, thus breaking the
code.

Use code inspired by the implementation of bugprone-unused-return-value
check to ignore cases where the return value is used. Add appropriate
lit test cases and documentation.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D153860

Files:
  clang-tools-extra/clang-tidy/modernize/UseStdPrintCheck.cpp
  clang-tools-extra/docs/clang-tidy/checks/modernize/use-std-print.rst
  clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print-absl.cpp
  clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print-custom.cpp
  clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print.cpp
@@ -44,6 +44,233 @@
   // CHECK-FIXES: std::println("Hello");
 }
 
+// std::print returns nothing, so any callers that use the return
+// value cannot be automatically translated.
+int printf_uses_return_value(int choice) {
+  const int i = printf("Return value assigned to variable %d\n", 42);
+
+  if (choice == 0)
+printf("if body %d\n", i);
+// CHECK-MESSAGES: [[@LINE-1]]:5: warning: use 'std::println' instead of 'printf' [modernize-use-std-print]
+// CHECK-FIXES: std::println("if body {}", i);
+  else if (choice == 1)
+printf("else if body %d\n", i);
+// CHECK-MESSAGES: [[@LINE-1]]:5: warning: use 'std::println' instead of 'printf' [modernize-use-std-print]
+// CHECK-FIXES: std::println("else if body {}", i);
+  else
+printf("else body %d\n", i);
+// CHECK-MESSAGES: [[@LINE-1]]:5: warning: use 'std::println' instead of 'printf' [modernize-use-std-print]
+// CHECK-FIXES: std::println("else body {}", i);
+
+  if (printf("Return value used as boolean in if statement"))
+if (printf("Return value used in expression if statement") == 44)
+  if (const int j = printf("Return value used in assignment in if statement"))
+if (const int k = printf("Return value used with initializer in if statement"); k == 44)
+  ;
+
+  int d = 0;
+  while (printf("%d", d) < 2)
+++d;
+
+  while (true)
+printf("while body %d\n", i);
+// CHECK-MESSAGES: [[@LINE-1]]:5: warning: use 'std::println' instead of 'printf' [modernize-use-std-print]
+// CHECK-FIXES: std::println("while body {}", i);
+
+  do
+printf("do body %d\n", i);
+// CHECK-MESSAGES: [[@LINE-1]]:5: warning: use 'std::println' instead of 'printf' [modernize-use-std-print]
+// CHECK-FIXES: std::println("do body {}", i);
+  while (true);
+
+  for (;;)
+printf("for body %d\n", i);
+// CHECK-MESSAGES: [[@LINE-1]]:5: warning: use 'std::println' instead of 'printf' [modernize-use-std-print]
+// CHECK-FIXES: std::println("for body {}", i);
+
+  for (printf("for init statement %d\n", i);;)
+// CHECK-MESSAGES: [[@LINE-1]]:8: warning: use 'std::println' instead of 'printf' [modernize-use-std-print]
+// CHECK-FIXES: std::println("for init statement {}", i);
+;;
+
+  for (int j = printf("for init statement %d\n", i);;)
+;;
+
+  for (; printf("for condition %d\n", i);)
+;;
+
+  for (;; printf("for expression %d\n", i))
+// CHECK-MESSAGES: [[@LINE-1]]:11: warning: use 'std::println' instead of 'printf' [modernize-use-std-print]
+// CHECK-FIXES: std::println("for expression {}", i)
+;;
+
+  for (auto C : "foo")
+printf("ranged-for body %d\n", i);
+// CHECK-MESSAGES: [[@LINE-1]]:5: warning: use 'std::println' instead of 'printf' [modernize-use-std-print]
+// CHECK-FIXES: std::println("ranged-for body {}", i);
+
+  switch (1) {
+  case 1:
+printf("switch case body %d\n", i);
+// CHECK-MESSAGES: [[@LINE-1]]:5: warning: use 'std::println' instead of 'printf' [modernize-use-std-print]
+// CHECK-FIXES: std::println("switch case body {}", i);
+break;
+  default:
+printf("switch default body %d\n", i);
+// CHECK-MESSAGES: [[@LINE-1]]:5: warning: use 'std::println' instead of 'printf' [modernize-use-std-print]
+// CHECK-FIXES: std::println("switch default body {}", i);
+break;
+  }
+
+  try {
+printf("try body %d\n", i);
+// CHECK-MESSAGES: [[@LINE-1]]:5: warning: use 'std::println' instead of 'printf' [modernize-use-std-print]
+// CHECK-FIXES: std::println("try body {}", i);
+  } catch (i

[PATCH] D151952: [clang] adds `__type_pack_index` so we can get a type's parameter pack index

2023-06-27 Thread Daniel Bertalan via Phabricator via cfe-commits
BertalanD added a subscriber: jwakely.
BertalanD added a comment.

I am considering making use of this feature in a real-world project. I have a 
few short observations after rebasing this diff and playing with it for a bit:

- It seems to me that `__has_builtin(__type_pack_index)`  currently evaluates 
to false. Please include a check for the feature detection working correctly in 
the test.

- Has there been any coordination with GCC folks on the name/semantics of this 
builtin?

  GCC trunk has recently gained support for `__type_pack_element`, and on the 
feature request for it (PR100157 ), @jwakely has 
already expressed interest in implementing the reverse of that, i.e. what this 
diff proposes. A slight incompatibility has managed to seep in: GCC does not 
allow the use of `__type_pack_element` in a position where its name would end 
up being manged; see the Folly bug report 
. While this is easy to work 
around (wrap it in a template), as a user, it would be inconvenient needing to 
add a GCC/Clang check alongside `__has_builtin` if the two compilers were to 
come up with incompatibly behaving implementations for this one.

- What would be the expected way of gracefully handing the queried type not 
being present in the list?

  Our `std::variant`-like type uses a `can_contain` constraint on its accessors 
to prevent asking for a type that's not in the type list. We currently achieve 
this by `index_of` returning `sizeof...(Ts)` as a sentinel value if no match 
was found. libc++'s __find_exactly_one_t 

 uses `(size_t)-1` for the same purpose.

  I'm targeting C++20, so `requires { __type_pack_index(T, InTypes...); }` 
seems to do just what I want, but `std::variant` is C++17 and `std::tuple` is 
even earlier than that. Of course, in earlier language modes you don't have to 
worry about it working in concepts, but e.g. libc++ `static_assert`s that the 
index is not the sentinel. Not sure about what libstdc++'s requirements would 
be.

  In any case, could you please test/document the expected way of recovering 
from the error?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D151952/new/

https://reviews.llvm.org/D151952

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 6101d72 - [RISCV] Relax rules for ordering s/z/x prefixed extensions in ISA naming strings

2023-06-27 Thread Alex Bradbury via cfe-commits

Author: Alex Bradbury
Date: 2023-06-27T13:32:11+01:00
New Revision: 6101d720cb499f5ad19293475b429828fa3dbd75

URL: 
https://github.com/llvm/llvm-project/commit/6101d720cb499f5ad19293475b429828fa3dbd75
DIFF: 
https://github.com/llvm/llvm-project/commit/6101d720cb499f5ad19293475b429828fa3dbd75.diff

LOG: [RISCV] Relax rules for ordering s/z/x prefixed extensions in ISA naming 
strings

This was discussed somewhat in D148315. As it stands, we require in
RISCVISAInfo::parseArchString (used for e.g. -march parsing in Clang)
that extensions are given in the order of z, then s, then x prefixed
extensions (after the standard single-letter extensions). However, we
recently (in D148315) moved to that order from z/x/s as the canonical
ordering was changed in the spec. In addition, recent GCC seems to
require z* extensions before s*.

My recollection of the history here is that we thought keeping -march as
close to the rules for ISA naming strings as possible would simplify
things, as there's an existing spec to point to. My feeling is that now
we've had incompatible changes, and an incompatibility with GCC there's
no real benefit to sticking to this restriction, and it risks making it
much more painful than it needs to be to copy a -march= string between
GCC and Clang.

This patch removes all ordering restrictions so you can freely mix x/s/z
extensions.

To be very explicit, this doesn't change our behaviour when emitting a
canonically ordered extension string (e.g. in build attributes). We of
course sort according to the canonical order (as we understand it) in
that case.

Differential Revision: https://reviews.llvm.org/D149246

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/test/Driver/riscv-arch.c
llvm/docs/RISCVUsage.rst
llvm/lib/Support/RISCVISAInfo.cpp
llvm/unittests/Support/RISCVISAInfoTest.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index bc6366b36fd4d..1ecf620f2a768 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -704,6 +704,9 @@ RISC-V Support
 - Added ``attribute(riscv_rvv_vector_bits(__riscv_v_fixed_vlen))`` to allow
   the size of a RVV (RISC-V Vector) scalable type to be specified. This allows
   RVV scalable vector types to be used in structs or in global variables.
+- The rules for ordering of extensions in ``-march`` strings were relaxed. A
+  canonical ordering is no longer enforced on ``z*``, ``s*``, and ``x*``
+  prefixed extensions.
 
 CUDA/HIP Language Changes
 ^

diff  --git a/clang/test/Driver/riscv-arch.c b/clang/test/Driver/riscv-arch.c
index 8929d88e92c23..4f618d52dce10 100644
--- a/clang/test/Driver/riscv-arch.c
+++ b/clang/test/Driver/riscv-arch.c
@@ -323,8 +323,7 @@
 // RUN: %clang --target=riscv32-unknown-elf -march=rv32ixdef_sabc -### %s \
 // RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=RV32-X-ORDER %s
 // RV32-X-ORDER: error: invalid arch name 'rv32ixdef_sabc',
-// RV32-X-ORDER: standard supervisor-level extension not given
-// RV32-X-ORDER: in canonical order 'sabc'
+// RV32-X-ORDER  unsupported non-standard user-level extension 'xdef'
 
 // RUN: %clang --target=riscv32-unknown-elf -march=rv32ixabc_xabc -### %s \
 // RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=RV32-XDUP %s

diff  --git a/llvm/docs/RISCVUsage.rst b/llvm/docs/RISCVUsage.rst
index 66c4aa61fe65b..f50ddf23d7d6a 100644
--- a/llvm/docs/RISCVUsage.rst
+++ b/llvm/docs/RISCVUsage.rst
@@ -40,6 +40,8 @@ The current known variances from the specification are:
   users migrate build systems so as not to rely on this.
 * Allowing CSRs to be named without gating on specific extensions.  This
   applies to all CSR names, not just those in zicsr, zicntr, and zihpm.
+* The ordering of ``z*``, ``s*``, and ``x*`` prefixed extension names is not
+  enforced in user-specified ISA naming strings (e.g. ``-march``).
 
 We are actively deciding not to support multiple specification revisions
 at this time. We acknowledge a likely future need, but actively defer the

diff  --git a/llvm/lib/Support/RISCVISAInfo.cpp 
b/llvm/lib/Support/RISCVISAInfo.cpp
index 58a98bc497a89..7b12abcdc801e 100644
--- a/llvm/lib/Support/RISCVISAInfo.cpp
+++ b/llvm/lib/Support/RISCVISAInfo.cpp
@@ -811,9 +811,9 @@ RISCVISAInfo::parseArchString(StringRef Arch, bool 
EnableExperimentalExtension,
   // Parse the ISA string containing non-standard user-level
   // extensions, standard supervisor-level extensions and
   // non-standard supervisor-level extensions.
-  // These extensions start with 'z', 's', 'x' prefixes, follow a
-  // canonical order, might have a version number (major, minor)
-  // and are separated by a single underscore '_'.
+  // These extensions start with 'z', 's', 'x' prefixes, might have a version
+  // number (major, minor) and are separated by a single underscore '_'. We do
+  // not enforce a canonical order for them.
 

[PATCH] D149246: [RISCV] Relax rules for ordering s/z/x prefixed extensions in ISA naming strings

2023-06-27 Thread Alex Bradbury via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG6101d720cb49: [RISCV] Relax rules for ordering s/z/x 
prefixed extensions in ISA naming strings (authored by asb).

Changed prior to commit:
  https://reviews.llvm.org/D149246?vs=517106&id=534930#toc

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D149246/new/

https://reviews.llvm.org/D149246

Files:
  clang/docs/ReleaseNotes.rst
  clang/test/Driver/riscv-arch.c
  llvm/docs/RISCVUsage.rst
  llvm/lib/Support/RISCVISAInfo.cpp
  llvm/unittests/Support/RISCVISAInfoTest.cpp

Index: llvm/unittests/Support/RISCVISAInfoTest.cpp
===
--- llvm/unittests/Support/RISCVISAInfoTest.cpp
+++ llvm/unittests/Support/RISCVISAInfoTest.cpp
@@ -192,7 +192,7 @@
   EXPECT_EQ(InfoRV64G.getFLen(), 64U);
 }
 
-TEST(ParseArchString, RequiresCanonicalOrderForExtensions) {
+TEST(ParseArchString, RequiresCanonicalOrderForSingleLetterExtensions) {
   EXPECT_EQ(
   toString(RISCVISAInfo::parseArchString("rv64idf", true).takeError()),
   "standard user-level extension not given in canonical order 'f'");
@@ -203,12 +203,10 @@
   toString(
   RISCVISAInfo::parseArchString("rv32i_zfinx_a", true).takeError()),
   "invalid extension prefix 'a'");
-  EXPECT_EQ(
-  toString(RISCVISAInfo::parseArchString("rv64i_svnapot_zicsr", true)
-   .takeError()),
-  "standard user-level extension not given in canonical order 'zicsr'");
+  // Canonical ordering not required for z*, s*, and x* extensions.
   EXPECT_THAT_EXPECTED(
-  RISCVISAInfo::parseArchString("rv64imafdc_zicsr_svnapot", true),
+  RISCVISAInfo::parseArchString(
+  "rv64imafdc_xsfvcp_zicsr_xtheadba_svnapot_zawrs", true),
   Succeeded());
 }
 
Index: llvm/lib/Support/RISCVISAInfo.cpp
===
--- llvm/lib/Support/RISCVISAInfo.cpp
+++ llvm/lib/Support/RISCVISAInfo.cpp
@@ -811,9 +811,9 @@
   // Parse the ISA string containing non-standard user-level
   // extensions, standard supervisor-level extensions and
   // non-standard supervisor-level extensions.
-  // These extensions start with 'z', 's', 'x' prefixes, follow a
-  // canonical order, might have a version number (major, minor)
-  // and are separated by a single underscore '_'.
+  // These extensions start with 'z', 's', 'x' prefixes, might have a version
+  // number (major, minor) and are separated by a single underscore '_'. We do
+  // not enforce a canonical order for them.
   // Set the hardware features for the extensions that are supported.
 
   // Multi-letter extensions are seperated by a single underscore
@@ -822,9 +822,6 @@
   OtherExts.split(Split, '_');
 
   SmallVector AllExts;
-  std::array Prefix{"z", "s", "x"};
-  auto I = Prefix.begin();
-  auto E = Prefix.end();
   if (Split.size() > 1 || Split[0] != "") {
 for (StringRef Ext : Split) {
   if (Ext.empty())
@@ -844,18 +841,6 @@
  "invalid extension prefix '" + Ext + "'");
   }
 
-  // Check ISA extensions are specified in the canonical order.
-  while (I != E && *I != Type)
-++I;
-
-  if (I == E) {
-if (IgnoreUnknown)
-  continue;
-return createStringError(errc::invalid_argument,
- "%s not given in canonical order '%s'",
- Desc.str().c_str(), Ext.str().c_str());
-  }
-
   if (!IgnoreUnknown && Name.size() == Type.size()) {
 return createStringError(errc::invalid_argument,
  "%s name missing after '%s'",
Index: llvm/docs/RISCVUsage.rst
===
--- llvm/docs/RISCVUsage.rst
+++ llvm/docs/RISCVUsage.rst
@@ -40,6 +40,8 @@
   users migrate build systems so as not to rely on this.
 * Allowing CSRs to be named without gating on specific extensions.  This
   applies to all CSR names, not just those in zicsr, zicntr, and zihpm.
+* The ordering of ``z*``, ``s*``, and ``x*`` prefixed extension names is not
+  enforced in user-specified ISA naming strings (e.g. ``-march``).
 
 We are actively deciding not to support multiple specification revisions
 at this time. We acknowledge a likely future need, but actively defer the
Index: clang/test/Driver/riscv-arch.c
===
--- clang/test/Driver/riscv-arch.c
+++ clang/test/Driver/riscv-arch.c
@@ -323,8 +323,7 @@
 // RUN: %clang --target=riscv32-unknown-elf -march=rv32ixdef_sabc -### %s \
 // RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=RV32-X-ORDER %s
 // RV32-X-ORDER: error: invalid arch name 'rv32ixdef_sabc',
-// RV32-X-ORDER: standard supervisor-level extension not given
-// RV32-X-ORDER: in canonical order 'sabc'
+// RV32-X-ORDER  unsuppor

[PATCH] D153314: [clang] Replace uses of CGBuilderTy::CreateElementBitCast (NFC)

2023-06-27 Thread Nikita Popov via Phabricator via cfe-commits
nikic accepted this revision.
nikic added a comment.
This revision is now accepted and ready to land.

LGTM


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153314/new/

https://reviews.llvm.org/D153314

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153092: [Clang][CodeGen]`vtable`, `typeinfo` et al. are globals

2023-06-27 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added a comment.

This could be a good chance to switch VT to constant address space instead of 
global address space. AFAIK if a target has global addr space they usually also 
has constant addr space since they usually support OpenCL or CUDA/HIP. Is there 
any reason we cannot introduce a CGM.ConstantGlobalsInt8PtrTy and use it for VT 
instead?


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153092/new/

https://reviews.llvm.org/D153092

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153556: [OPENMP52] Initial support for doacross clause.

2023-06-27 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: clang/lib/Parse/ParseOpenMP.cpp:4415-4439
+  } else if (Kind == OMPC_doacross) {
+// Handle dependence type for the doacross clause.
+ColonProtectionRAIIObject ColonRAII(*this);
+Data.ExtraModifier = getOpenMPSimpleClauseType(
+Kind, Tok.is(tok::identifier) ? PP.getSpelling(Tok) : "",
+getLangOpts());
+Data.ExtraModifierLoc = Tok.getLocation();

Can it be unified with depenbd clause parsing? (Maybe in a separate template 
function)



Comment at: clang/lib/Sema/SemaOpenMP.cpp:91
   llvm::SmallVector, 4>;
-  using DoacrossDependMapTy =
-  llvm::DenseMap;
+  using DoacrossDependMapTy = llvm::DenseMap;
   /// Kind of the declaration used in the uses_allocators clauses.

DoacrossClauseMapTy? Since it is intended to handle also doacross clauses.



Comment at: clang/lib/Sema/SemaOpenMP.cpp:11299-11344
   if (DC->getDependencyKind() == OMPC_DEPEND_source) {
 if (DependSourceClause) {
   Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
   << getOpenMPDirectiveName(OMPD_ordered)
   << getOpenMPClauseName(OMPC_depend) << 2;
   ErrorFound = true;
 } else {

Try to avoid copy-paste. Maybe introduce templated function?



Comment at: clang/lib/Sema/SemaOpenMP.cpp:11359-11371
+  } else if ((DependFound || DoacrossFound) && (TC || SC)) {
+SourceLocation Loc =
+DependFound ? DependFound->getBeginLoc() : 
DoacrossFound->getBeginLoc();
+Diag(Loc, diag::err_omp_depend_clause_thread_simd)
+<< getOpenMPClauseName(DependFound ? OMPC_depend : OMPC_doacross)
 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
 ErrorFound = true;

Same, try to avoid copy-paste



Comment at: clang/lib/Sema/SemaOpenMP.cpp:24002
+
+OMPClause *Sema::ActOnOpenMPDoacrossClause(
+OpenMPDoacrossClauseModifier DepType, SourceLocation DepLoc,

Same, if possible try to unify handling with the depend clause, if possible


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153556/new/

https://reviews.llvm.org/D153556

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D144634: [Clang][OpenMP] Support for Code Generation of loop bind clause

2023-06-27 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: clang/include/clang/Sema/Sema.h:11094
 
+  bool checkLastPrivateForMappedDirectives(ArrayRef Clauses);
+  bool mapLoopConstruct(llvm::SmallVector *ClausesWithoutBind,

const member function?
Add a comment



Comment at: clang/include/clang/Sema/Sema.h:11095
+  bool checkLastPrivateForMappedDirectives(ArrayRef Clauses);
+  bool mapLoopConstruct(llvm::SmallVector *ClausesWithoutBind,
+ArrayRef Clauses,

Add a comment



Comment at: clang/include/clang/Sema/Sema.h:11095
+  bool checkLastPrivateForMappedDirectives(ArrayRef Clauses);
+  bool mapLoopConstruct(llvm::SmallVector *ClausesWithoutBind,
+ArrayRef Clauses,

ABataev wrote:
> Add a comment
`SmallVectorImpl &` instead of pointer to fully specified 
`SmallVector`


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D144634/new/

https://reviews.llvm.org/D144634

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153652: [Support] Don't set "all_exe" mode by default for file written by llvm::writeToOutput

2023-06-27 Thread James Henderson via Phabricator via cfe-commits
jhenderson added inline comments.



Comment at: llvm/unittests/Support/raw_ostream_test.cpp:500
+  ASSERT_TRUE(!!Perms);
+  EXPECT_EQ(0, *Perms & llvm::sys::fs::all_exe);
+

hokein wrote:
> jhenderson wrote:
> > Here and below, rather than just checking the all_exe bit, let's check the 
> > permissions are exactly what are expected (e.g. does it have the read/write 
> > perms?). 
> checking all existing bits is a bit tricky here (I tried it, then gave up):
> 
> - createTemporaryFile() creates a file with `owner_read | owner_write`
> - writeToOutput() sets the written file to `all_read | all_write`
> 
> Both API don't provide a way to customize these bits, and they're internal 
> details. We could test against them, but testing the implementation details 
> seems subtle. And here we aim to verify the exe-bit not set by the 
> `writeToOutput`, so I think just testing the exe-bit is not set should be 
> enough. 
This argument doesn't make much sense to me. Why are the `all_read` and 
`all_write` bits implementation details that shouldn't be tested when the lack 
of `all_exe` is?

This test is for testing `writeToOutput`. Part of `writeToOutput`'s behaviour 
appears to be to create a file with the `all_read` and `all_write` bits set. 
Therefore, we should be testing that behaviour. As there was already one issue 
with the permission bits of the file this method creates, and you are directly 
modifiyng a test to add permissions testing, I think it's justified to request 
testing of the other bits.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153652/new/

https://reviews.llvm.org/D153652

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153296: [AST] Stop evaluate constant expression if the condition expression which in switch statement contains errors

2023-06-27 Thread Yurong via Phabricator via cfe-commits
yronglin added a comment.

Seems the diagnostic message `:5:9: note: constexpr evaluation hit 
maximum step limit; possible infinite loop?` was redundant, also gcc dose not 
emit this message.

https://godbolt.org/z/v55P88cdT


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153296/new/

https://reviews.llvm.org/D153296

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153417: New CharSetConverter wrapper class for ConverterEBCDIC

2023-06-27 Thread Abhina Sree via Phabricator via cfe-commits
abhina.sreeskantharajan added a comment.

> I don't think anyone is particularly against the concept of adding a charset 
> conversion API; most of the discussion is around the choice to implement the 
> API as a thin wrapper around POSIX iconv().  And that concern applies equally 
> no matter where the code is located in the source tree.

Sorry, I misremembered where it was. That discussion I mentioned was from the 
previous patch https://reviews.llvm.org/D88741, not my RFC.

@cor3ntin had the following concerns:

> If we do use iconv though, i would like us to have a better understanding of 
> use cases, The patch currently links iconv to all llvm libraries, which might 
> be overkill if the only project using it is Clang, and I wonder how that 
> affects packaging
> on linux distributions.




Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153417/new/

https://reviews.llvm.org/D153417

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153836: [RISCV] Bump vector crypto to v1.0.0-rc1

2023-06-27 Thread Alex Bradbury via Phabricator via cfe-commits
asb accepted this revision.
asb added a comment.
This revision is now accepted and ready to land.

Agreed that looking at 
https://github.com/riscv/riscv-crypto/compare/v20230531...v20230620 there are 
no changes that need to be reflected on the LLVM side beyond the version bump 
here. LGTM


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153836/new/

https://reviews.llvm.org/D153836

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D151952: [clang] adds `__type_pack_index` so we can get a type's parameter pack index

2023-06-27 Thread Jonathan Wakely via Phabricator via cfe-commits
jwakely added a comment.

In D151952#4396485 , @cjdb wrote:

> Since we're doing this, it may also be worth checking that `T1s...` are 
> unique in `T2s...`, which I'd intended to be a separate feature.

It seems like it would be more efficient to include the uniqueness check in the 
intrinsic, otherwise `std::get` and helpers like libstdc++'s 
`variant::__index_of` will still need some template metaprogramming to check 
for uniqueness. Even if there's a separate intrinsic for that, it seems more 
useful to just have one intrinsic that does both. If you have a use case for 
finding the index of the first T in a pack, maybe add an additional boolean 
that requests uniqueness and would cause `__type_pack_index` to fail if T is 
not unique.

As @BertalanD also said, it doesn't seem useful to be ill-formed if the type 
isn't in the pack. That makes it unusable for `std::get` and `std::variant`. 
Libstdc++'s `__find_uniq_type_in_pack` returns `sizeof...(Types)` 
if `T` isn't found (either this or `-1uz` seems fine, you can check the 
returned index is `< sizeof...(Types)` to tell if the type was found).




Comment at: clang/docs/LanguageExtensions.rst:1660
+T& get(tuple& ts) noexcept {
+  return std::get<__type_pack_index(T, Ts...)>(ts);
+}

If this intrinsic doesn't (yet?) check for uniqueness, then this `get` 
doesn't match `std::get`. It might be worth mentioning that here.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D151952/new/

https://reviews.llvm.org/D151952

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153092: [Clang][CodeGen]`vtable`, `typeinfo` et al. are globals

2023-06-27 Thread Alex Voicu via Phabricator via cfe-commits
AlexVlx added a comment.

In D153092#4452070 , @yaxunl wrote:

> This could be a good chance to switch VT to constant address space instead of 
> global address space. AFAIK if a target has global addr space they usually 
> also has constant addr space since they usually support OpenCL or CUDA/HIP. 
> Is there any reason we cannot introduce a CGM.ConstantGlobalsInt8PtrTy and 
> use it for VT instead?

I did give this some thought and the benefits are somewhat unclear to the point 
of being ultimately counterproductive. Note that these are already marked 
`constant`, which IIRC is / was going to be enough to get most of the benefits, 
at least on our back-end. Furthermore, the semantics of the constant address 
space are a bit weird in something like OpenCL e.g. `A pointer that points to 
the constant address space cannot be cast or implicitly converted to the 
generic address space.`. This would lead to weirdness when composing with CUDA 
/ HIP, where `constant` is treated as `device`, which is to say global. IIRC, 
you are also meant to use magical interfaces to write into `constant` from the 
host, which a loader wouldn't necessarily do. Overall, I think that the OCL 
formulation of `constant` is actually meant to allow for relatively strange 
things like loading things into ROM or having different pointer types (be it 
width or canonicity). TL;DR, I am concerned that a target could validly have 
the `constant` addr space be disjoint from generic/flat, with no viable way to 
even cast between the two. We could say “yes, but this is not that `constant`”, 
but then if OCL ever starts supporting dynamic polymorphism it would get 
confusing.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153092/new/

https://reviews.llvm.org/D153092

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153369: [OpenMP] Always apply target declarations to canonical definitions

2023-06-27 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 updated this revision to Diff 534950.
jhuber6 added a comment.

Updating to use `VD->redecls()`.

Thanks for pointing that out, couldn't find it when I looked initially.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153369/new/

https://reviews.llvm.org/D153369

Files:
  clang/lib/AST/AttrImpl.cpp
  clang/lib/Sema/SemaOpenMP.cpp
  clang/test/OpenMP/declare_target_codegen.cpp


Index: clang/test/OpenMP/declare_target_codegen.cpp
===
--- clang/test/OpenMP/declare_target_codegen.cpp
+++ clang/test/OpenMP/declare_target_codegen.cpp
@@ -27,11 +27,13 @@
 // CHECK-DAG: Bake
 // CHECK-NOT: @{{hhh|ggg|fff|eee}} =
 // CHECK-DAG: @flag = protected global i8 undef,
+// CHECK-DAG: @dx = {{protected | }}global i32 0,
+// CHECK-DAG: @dy = {{protected | }}global i32 0,
 // CHECK-DAG: @aaa = external global i32,
-// CHECK-DAG: @bbb ={{ protected | }}global i32 0,
+// CHECK-DAG: @bbb = {{protected | }}global i32 0,
 // CHECK-DAG: weak constant %struct.__tgt_offload_entry { ptr @bbb,
 // CHECK-DAG: @ccc = external global i32,
-// CHECK-DAG: @ddd ={{ protected | }}global i32 0,
+// CHECK-DAG: @ddd = {{protected | }}global i32 0,
 // CHECK-DAG: @hhh_decl_tgt_ref_ptr = weak global ptr null
 // CHECK-DAG: @ggg_decl_tgt_ref_ptr = weak global ptr null
 // CHECK-DAG: @fff_decl_tgt_ref_ptr = weak global ptr null
@@ -51,10 +53,21 @@
 // CHECK-DAG: define {{.*}}i32 @{{.*}}{{foo|bar|baz2|baz3|FA|f_method}}{{.*}}()
 // CHECK-DAG: define {{.*}}void @{{.*}}TemplateClass{{.*}}(ptr {{[^,]*}} 
%{{.*}})
 // CHECK-DAG: define {{.*}}i32 @{{.*}}TemplateClass{{.*}}f_method{{.*}}(ptr 
{{[^,]*}} %{{.*}})
-// CHECK-DAG: define {{.*}}void 
@__omp_offloading_{{.*}}_globals_l[[@LINE+78]]_ctor()
+// CHECK-DAG: define {{.*}}void 
@__omp_offloading_{{.*}}_globals_l[[@LINE+89]]_ctor()
 
 #ifndef HEADER
 #define HEADER
+
+int dx = 0;
+extern int dx;
+#pragma omp declare target to(dx)
+
+int dy = 0;
+#pragma omp begin declare target
+
+extern int dy;
+#pragma omp end declare target
+
 #pragma omp declare target
 bool flag [[clang::loader_uninitialized]];
 extern int bbb;
Index: clang/lib/Sema/SemaOpenMP.cpp
===
--- clang/lib/Sema/SemaOpenMP.cpp
+++ clang/lib/Sema/SemaOpenMP.cpp
@@ -22988,6 +22988,7 @@
   ND->addAttr(A);
   if (ASTMutationListener *ML = Context.getASTMutationListener())
 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
+
   checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc);
 }
 
Index: clang/lib/AST/AttrImpl.cpp
===
--- clang/lib/AST/AttrImpl.cpp
+++ clang/lib/AST/AttrImpl.cpp
@@ -151,14 +151,16 @@
 
 std::optional
 OMPDeclareTargetDeclAttr::getActiveAttr(const ValueDecl *VD) {
-  if (!VD->hasAttrs())
+  if (llvm::all_of(VD->redecls(), [](const Decl *D) { return !D->hasAttrs(); 
}))
 return std::nullopt;
   unsigned Level = 0;
   OMPDeclareTargetDeclAttr *FoundAttr = nullptr;
-  for (auto *Attr : VD->specific_attrs()) {
-if (Level <= Attr->getLevel()) {
-  Level = Attr->getLevel();
-  FoundAttr = Attr;
+  for (const Decl *D : VD->redecls()) {
+for (auto *Attr : D->specific_attrs()) {
+  if (Level <= Attr->getLevel()) {
+Level = Attr->getLevel();
+FoundAttr = Attr;
+  }
 }
   }
   if (FoundAttr)


Index: clang/test/OpenMP/declare_target_codegen.cpp
===
--- clang/test/OpenMP/declare_target_codegen.cpp
+++ clang/test/OpenMP/declare_target_codegen.cpp
@@ -27,11 +27,13 @@
 // CHECK-DAG: Bake
 // CHECK-NOT: @{{hhh|ggg|fff|eee}} =
 // CHECK-DAG: @flag = protected global i8 undef,
+// CHECK-DAG: @dx = {{protected | }}global i32 0,
+// CHECK-DAG: @dy = {{protected | }}global i32 0,
 // CHECK-DAG: @aaa = external global i32,
-// CHECK-DAG: @bbb ={{ protected | }}global i32 0,
+// CHECK-DAG: @bbb = {{protected | }}global i32 0,
 // CHECK-DAG: weak constant %struct.__tgt_offload_entry { ptr @bbb,
 // CHECK-DAG: @ccc = external global i32,
-// CHECK-DAG: @ddd ={{ protected | }}global i32 0,
+// CHECK-DAG: @ddd = {{protected | }}global i32 0,
 // CHECK-DAG: @hhh_decl_tgt_ref_ptr = weak global ptr null
 // CHECK-DAG: @ggg_decl_tgt_ref_ptr = weak global ptr null
 // CHECK-DAG: @fff_decl_tgt_ref_ptr = weak global ptr null
@@ -51,10 +53,21 @@
 // CHECK-DAG: define {{.*}}i32 @{{.*}}{{foo|bar|baz2|baz3|FA|f_method}}{{.*}}()
 // CHECK-DAG: define {{.*}}void @{{.*}}TemplateClass{{.*}}(ptr {{[^,]*}} %{{.*}})
 // CHECK-DAG: define {{.*}}i32 @{{.*}}TemplateClass{{.*}}f_method{{.*}}(ptr {{[^,]*}} %{{.*}})
-// CHECK-DAG: define {{.*}}void @__omp_offloading_{{.*}}_globals_l[[@LINE+78]]_ctor()
+// CHECK-DAG: define {{.*}}void @__omp_offloading_{{.*}}_globals_l[[@LINE+89]]_ctor()
 
 #ifndef HEADER
 #define HEADER
+
+int dx = 0;
+extern int dx;
+#pragma omp declare target to(dx)
+
+int dy = 0;
+#pragma omp begin d

[PATCH] D153369: [OpenMP] Always apply target declarations to canonical definitions

2023-06-27 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev accepted this revision.
ABataev added a comment.
This revision is now accepted and ready to land.

LG with a nit




Comment at: clang/lib/Sema/SemaOpenMP.cpp:22991
 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
+
   checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc);

Remove new line here


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153369/new/

https://reviews.llvm.org/D153369

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153369: [OpenMP] Always apply target declarations to canonical definitions

2023-06-27 Thread Joseph Huber via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG1d699bf2664d: [OpenMP] Always apply target declarations to 
canonical definitions (authored by jhuber6).

Changed prior to commit:
  https://reviews.llvm.org/D153369?vs=534950&id=534970#toc

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153369/new/

https://reviews.llvm.org/D153369

Files:
  clang/lib/AST/AttrImpl.cpp
  clang/test/OpenMP/declare_target_codegen.cpp


Index: clang/test/OpenMP/declare_target_codegen.cpp
===
--- clang/test/OpenMP/declare_target_codegen.cpp
+++ clang/test/OpenMP/declare_target_codegen.cpp
@@ -27,11 +27,13 @@
 // CHECK-DAG: Bake
 // CHECK-NOT: @{{hhh|ggg|fff|eee}} =
 // CHECK-DAG: @flag = protected global i8 undef,
+// CHECK-DAG: @dx = {{protected | }}global i32 0,
+// CHECK-DAG: @dy = {{protected | }}global i32 0,
 // CHECK-DAG: @aaa = external global i32,
-// CHECK-DAG: @bbb ={{ protected | }}global i32 0,
+// CHECK-DAG: @bbb = {{protected | }}global i32 0,
 // CHECK-DAG: weak constant %struct.__tgt_offload_entry { ptr @bbb,
 // CHECK-DAG: @ccc = external global i32,
-// CHECK-DAG: @ddd ={{ protected | }}global i32 0,
+// CHECK-DAG: @ddd = {{protected | }}global i32 0,
 // CHECK-DAG: @hhh_decl_tgt_ref_ptr = weak global ptr null
 // CHECK-DAG: @ggg_decl_tgt_ref_ptr = weak global ptr null
 // CHECK-DAG: @fff_decl_tgt_ref_ptr = weak global ptr null
@@ -51,10 +53,21 @@
 // CHECK-DAG: define {{.*}}i32 @{{.*}}{{foo|bar|baz2|baz3|FA|f_method}}{{.*}}()
 // CHECK-DAG: define {{.*}}void @{{.*}}TemplateClass{{.*}}(ptr {{[^,]*}} 
%{{.*}})
 // CHECK-DAG: define {{.*}}i32 @{{.*}}TemplateClass{{.*}}f_method{{.*}}(ptr 
{{[^,]*}} %{{.*}})
-// CHECK-DAG: define {{.*}}void 
@__omp_offloading_{{.*}}_globals_l[[@LINE+78]]_ctor()
+// CHECK-DAG: define {{.*}}void 
@__omp_offloading_{{.*}}_globals_l[[@LINE+89]]_ctor()
 
 #ifndef HEADER
 #define HEADER
+
+int dx = 0;
+extern int dx;
+#pragma omp declare target to(dx)
+
+int dy = 0;
+#pragma omp begin declare target
+
+extern int dy;
+#pragma omp end declare target
+
 #pragma omp declare target
 bool flag [[clang::loader_uninitialized]];
 extern int bbb;
Index: clang/lib/AST/AttrImpl.cpp
===
--- clang/lib/AST/AttrImpl.cpp
+++ clang/lib/AST/AttrImpl.cpp
@@ -151,14 +151,16 @@
 
 std::optional
 OMPDeclareTargetDeclAttr::getActiveAttr(const ValueDecl *VD) {
-  if (!VD->hasAttrs())
+  if (llvm::all_of(VD->redecls(), [](const Decl *D) { return !D->hasAttrs(); 
}))
 return std::nullopt;
   unsigned Level = 0;
   OMPDeclareTargetDeclAttr *FoundAttr = nullptr;
-  for (auto *Attr : VD->specific_attrs()) {
-if (Level <= Attr->getLevel()) {
-  Level = Attr->getLevel();
-  FoundAttr = Attr;
+  for (const Decl *D : VD->redecls()) {
+for (auto *Attr : D->specific_attrs()) {
+  if (Level <= Attr->getLevel()) {
+Level = Attr->getLevel();
+FoundAttr = Attr;
+  }
 }
   }
   if (FoundAttr)


Index: clang/test/OpenMP/declare_target_codegen.cpp
===
--- clang/test/OpenMP/declare_target_codegen.cpp
+++ clang/test/OpenMP/declare_target_codegen.cpp
@@ -27,11 +27,13 @@
 // CHECK-DAG: Bake
 // CHECK-NOT: @{{hhh|ggg|fff|eee}} =
 // CHECK-DAG: @flag = protected global i8 undef,
+// CHECK-DAG: @dx = {{protected | }}global i32 0,
+// CHECK-DAG: @dy = {{protected | }}global i32 0,
 // CHECK-DAG: @aaa = external global i32,
-// CHECK-DAG: @bbb ={{ protected | }}global i32 0,
+// CHECK-DAG: @bbb = {{protected | }}global i32 0,
 // CHECK-DAG: weak constant %struct.__tgt_offload_entry { ptr @bbb,
 // CHECK-DAG: @ccc = external global i32,
-// CHECK-DAG: @ddd ={{ protected | }}global i32 0,
+// CHECK-DAG: @ddd = {{protected | }}global i32 0,
 // CHECK-DAG: @hhh_decl_tgt_ref_ptr = weak global ptr null
 // CHECK-DAG: @ggg_decl_tgt_ref_ptr = weak global ptr null
 // CHECK-DAG: @fff_decl_tgt_ref_ptr = weak global ptr null
@@ -51,10 +53,21 @@
 // CHECK-DAG: define {{.*}}i32 @{{.*}}{{foo|bar|baz2|baz3|FA|f_method}}{{.*}}()
 // CHECK-DAG: define {{.*}}void @{{.*}}TemplateClass{{.*}}(ptr {{[^,]*}} %{{.*}})
 // CHECK-DAG: define {{.*}}i32 @{{.*}}TemplateClass{{.*}}f_method{{.*}}(ptr {{[^,]*}} %{{.*}})
-// CHECK-DAG: define {{.*}}void @__omp_offloading_{{.*}}_globals_l[[@LINE+78]]_ctor()
+// CHECK-DAG: define {{.*}}void @__omp_offloading_{{.*}}_globals_l[[@LINE+89]]_ctor()
 
 #ifndef HEADER
 #define HEADER
+
+int dx = 0;
+extern int dx;
+#pragma omp declare target to(dx)
+
+int dy = 0;
+#pragma omp begin declare target
+
+extern int dy;
+#pragma omp end declare target
+
 #pragma omp declare target
 bool flag [[clang::loader_uninitialized]];
 extern int bbb;
Index: clang/lib/AST/AttrImpl.cpp
===
--- clang/lib/

[clang] 1d699bf - [OpenMP] Always apply target declarations to canonical definitions

2023-06-27 Thread Joseph Huber via cfe-commits

Author: Joseph Huber
Date: 2023-06-27T09:15:03-05:00
New Revision: 1d699bf2664d2a9e64024fd9eb87451d6360ea8c

URL: 
https://github.com/llvm/llvm-project/commit/1d699bf2664d2a9e64024fd9eb87451d6360ea8c
DIFF: 
https://github.com/llvm/llvm-project/commit/1d699bf2664d2a9e64024fd9eb87451d6360ea8c.diff

LOG: [OpenMP] Always apply target declarations to canonical definitions

This patch changes the handling of OpenMP to add the device attributes
to the canonical definitions when we encounter a non-canonical
definition. Previously, the following code would not work because it
would find the non-canonical definition first which would then not be
used anywhere else.

```
int x;
extern int x;
```

This patch now adds the attribute to both of them. This allows us to
perform the following operation if, for example, there were an
implementation of `stderr` on the device.

```
#include 

// List of libc symbols supported on the device.
extern FILE *stderr;
```

Unfortunately I cannot think of an equivalent solution to HIP / CUDA
device declarations as those are done with simple attributes. Attributes
themselves cannot be used to affect a definition once its canonical
definition has already been seen. Some help on that front would be
appreciated.

Fixes https://github.com/llvm/llvm-project/issues/63355

Reviewed By: ABataev

Differential Revision: https://reviews.llvm.org/D153369

Added: 


Modified: 
clang/lib/AST/AttrImpl.cpp
clang/test/OpenMP/declare_target_codegen.cpp

Removed: 




diff  --git a/clang/lib/AST/AttrImpl.cpp b/clang/lib/AST/AttrImpl.cpp
index f41ab77ef164c9..f198a9acf8481f 100644
--- a/clang/lib/AST/AttrImpl.cpp
+++ b/clang/lib/AST/AttrImpl.cpp
@@ -151,14 +151,16 @@ void OMPDeclareTargetDeclAttr::printPrettyPragma(
 
 std::optional
 OMPDeclareTargetDeclAttr::getActiveAttr(const ValueDecl *VD) {
-  if (!VD->hasAttrs())
+  if (llvm::all_of(VD->redecls(), [](const Decl *D) { return !D->hasAttrs(); 
}))
 return std::nullopt;
   unsigned Level = 0;
   OMPDeclareTargetDeclAttr *FoundAttr = nullptr;
-  for (auto *Attr : VD->specific_attrs()) {
-if (Level <= Attr->getLevel()) {
-  Level = Attr->getLevel();
-  FoundAttr = Attr;
+  for (const Decl *D : VD->redecls()) {
+for (auto *Attr : D->specific_attrs()) {
+  if (Level <= Attr->getLevel()) {
+Level = Attr->getLevel();
+FoundAttr = Attr;
+  }
 }
   }
   if (FoundAttr)

diff  --git a/clang/test/OpenMP/declare_target_codegen.cpp 
b/clang/test/OpenMP/declare_target_codegen.cpp
index aa7cf7bd038d42..f47335e2eea096 100644
--- a/clang/test/OpenMP/declare_target_codegen.cpp
+++ b/clang/test/OpenMP/declare_target_codegen.cpp
@@ -27,11 +27,13 @@
 // CHECK-DAG: Bake
 // CHECK-NOT: @{{hhh|ggg|fff|eee}} =
 // CHECK-DAG: @flag = protected global i8 undef,
+// CHECK-DAG: @dx = {{protected | }}global i32 0,
+// CHECK-DAG: @dy = {{protected | }}global i32 0,
 // CHECK-DAG: @aaa = external global i32,
-// CHECK-DAG: @bbb ={{ protected | }}global i32 0,
+// CHECK-DAG: @bbb = {{protected | }}global i32 0,
 // CHECK-DAG: weak constant %struct.__tgt_offload_entry { ptr @bbb,
 // CHECK-DAG: @ccc = external global i32,
-// CHECK-DAG: @ddd ={{ protected | }}global i32 0,
+// CHECK-DAG: @ddd = {{protected | }}global i32 0,
 // CHECK-DAG: @hhh_decl_tgt_ref_ptr = weak global ptr null
 // CHECK-DAG: @ggg_decl_tgt_ref_ptr = weak global ptr null
 // CHECK-DAG: @fff_decl_tgt_ref_ptr = weak global ptr null
@@ -51,10 +53,21 @@
 // CHECK-DAG: define {{.*}}i32 @{{.*}}{{foo|bar|baz2|baz3|FA|f_method}}{{.*}}()
 // CHECK-DAG: define {{.*}}void @{{.*}}TemplateClass{{.*}}(ptr {{[^,]*}} 
%{{.*}})
 // CHECK-DAG: define {{.*}}i32 @{{.*}}TemplateClass{{.*}}f_method{{.*}}(ptr 
{{[^,]*}} %{{.*}})
-// CHECK-DAG: define {{.*}}void 
@__omp_offloading_{{.*}}_globals_l[[@LINE+78]]_ctor()
+// CHECK-DAG: define {{.*}}void 
@__omp_offloading_{{.*}}_globals_l[[@LINE+89]]_ctor()
 
 #ifndef HEADER
 #define HEADER
+
+int dx = 0;
+extern int dx;
+#pragma omp declare target to(dx)
+
+int dy = 0;
+#pragma omp begin declare target
+
+extern int dy;
+#pragma omp end declare target
+
 #pragma omp declare target
 bool flag [[clang::loader_uninitialized]];
 extern int bbb;



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D148216: Add support for annotations in UpdateTestChecks (NFC)

2023-06-27 Thread Henrik G Olsson via Phabricator via cfe-commits
hnrklssn added a comment.

@nikic Ping :)


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D148216/new/

https://reviews.llvm.org/D148216

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D152504: [clang][ThreadSafety] Analyze cleanup functions

2023-06-27 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder marked 2 inline comments as done.
tbaeder added inline comments.



Comment at: clang/test/Sema/warn-thread-safety-analysis.c:76-77
 
+void cleanup_int(int *unused) __attribute__((release_capability(mu1))) {
+  (void)unused;
+  mutex_exclusive_unlock(&mu1);

aaronpuchert wrote:
> 
> omitting the parameter name in a function definition is a C2x extension


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D152504/new/

https://reviews.llvm.org/D152504

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153728: [llvm] Move AttributeMask to a separate header

2023-06-27 Thread Elliot Goodrich via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGf0fa2d7c2928: [llvm] Move AttributeMask to a separate header 
(authored by IncludeGuardian).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153728/new/

https://reviews.llvm.org/D153728

Files:
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  llvm/include/llvm/IR/AttributeMask.h
  llvm/include/llvm/IR/Attributes.h
  llvm/lib/Analysis/BlockFrequencyInfoImpl.cpp
  llvm/lib/Bitcode/Reader/BitcodeReader.cpp
  llvm/lib/CodeGen/MLRegallocEvictAdvisor.cpp
  llvm/lib/IR/Attributes.cpp
  llvm/lib/IR/AutoUpgrade.cpp
  llvm/lib/IR/Instruction.cpp
  llvm/lib/IR/Verifier.cpp
  llvm/lib/Target/AMDGPU/AMDGPURewriteOutArguments.cpp
  llvm/lib/Target/DirectX/DXILPrepare.cpp
  llvm/lib/Transforms/IPO/DeadArgumentElimination.cpp
  llvm/lib/Transforms/IPO/SCCP.cpp
  llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
  llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp
  llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp
  llvm/lib/Transforms/Scalar/RewriteStatepointsForGC.cpp
  llvm/lib/Transforms/Utils/CallPromotionUtils.cpp
  llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp
  llvm/tools/llvm-reduce/deltas/ReduceInstructions.cpp
  llvm/unittests/IR/AttributesTest.cpp

Index: llvm/unittests/IR/AttributesTest.cpp
===
--- llvm/unittests/IR/AttributesTest.cpp
+++ llvm/unittests/IR/AttributesTest.cpp
@@ -8,6 +8,7 @@
 
 #include "llvm/IR/Attributes.h"
 #include "llvm/AsmParser/Parser.h"
+#include "llvm/IR/AttributeMask.h"
 #include "llvm/IR/DerivedTypes.h"
 #include "llvm/IR/InstrTypes.h"
 #include "llvm/IR/LLVMContext.h"
Index: llvm/tools/llvm-reduce/deltas/ReduceInstructions.cpp
===
--- llvm/tools/llvm-reduce/deltas/ReduceInstructions.cpp
+++ llvm/tools/llvm-reduce/deltas/ReduceInstructions.cpp
@@ -14,6 +14,7 @@
 #include "ReduceInstructions.h"
 #include "Utils.h"
 #include "llvm/IR/Constants.h"
+#include 
 
 using namespace llvm;
 
Index: llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp
===
--- llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp
+++ llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp
@@ -19,6 +19,7 @@
 #include "llvm/Analysis/Loads.h"
 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
 #include "llvm/Analysis/ValueTracking.h"
+#include "llvm/IR/AttributeMask.h"
 #include "llvm/IR/DataLayout.h"
 #include "llvm/IR/Function.h"
 #include "llvm/IR/IRBuilder.h"
Index: llvm/lib/Transforms/Utils/CallPromotionUtils.cpp
===
--- llvm/lib/Transforms/Utils/CallPromotionUtils.cpp
+++ llvm/lib/Transforms/Utils/CallPromotionUtils.cpp
@@ -14,6 +14,7 @@
 #include "llvm/Transforms/Utils/CallPromotionUtils.h"
 #include "llvm/Analysis/Loads.h"
 #include "llvm/Analysis/TypeMetadataUtils.h"
+#include "llvm/IR/AttributeMask.h"
 #include "llvm/IR/IRBuilder.h"
 #include "llvm/IR/Instructions.h"
 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
Index: llvm/lib/Transforms/Scalar/RewriteStatepointsForGC.cpp
===
--- llvm/lib/Transforms/Scalar/RewriteStatepointsForGC.cpp
+++ llvm/lib/Transforms/Scalar/RewriteStatepointsForGC.cpp
@@ -27,6 +27,7 @@
 #include "llvm/Analysis/TargetLibraryInfo.h"
 #include "llvm/Analysis/TargetTransformInfo.h"
 #include "llvm/IR/Argument.h"
+#include "llvm/IR/AttributeMask.h"
 #include "llvm/IR/Attributes.h"
 #include "llvm/IR/BasicBlock.h"
 #include "llvm/IR/CallingConv.h"
Index: llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp
===
--- llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp
+++ llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp
@@ -160,6 +160,7 @@
 #include "llvm/Analysis/TargetLibraryInfo.h"
 #include "llvm/Analysis/ValueTracking.h"
 #include "llvm/IR/Argument.h"
+#include "llvm/IR/AttributeMask.h"
 #include "llvm/IR/Attributes.h"
 #include "llvm/IR/BasicBlock.h"
 #include "llvm/IR/CallingConv.h"
Index: llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp
===
--- llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp
+++ llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp
@@ -73,6 +73,7 @@
 #include "llvm/Analysis/TargetLibraryInfo.h"
 #include "llvm/Analysis/ValueTracking.h"
 #include "llvm/IR/Argument.h"
+#include "llvm/IR/AttributeMask.h"
 #include "llvm/IR/Attributes.h"
 #include "llvm/IR/BasicBlock.h"
 #include "llvm/IR/Constant.h"
Index: llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
===
--- llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
+++ llvm/lib/Transforms/InstCombine/InstCombineC

[clang] f0fa2d7 - [llvm] Move AttributeMask to a separate header

2023-06-27 Thread Elliot Goodrich via cfe-commits

Author: Elliot Goodrich
Date: 2023-06-27T15:26:17+01:00
New Revision: f0fa2d7c292853b79b5bcd16be97940859a800ec

URL: 
https://github.com/llvm/llvm-project/commit/f0fa2d7c292853b79b5bcd16be97940859a800ec
DIFF: 
https://github.com/llvm/llvm-project/commit/f0fa2d7c292853b79b5bcd16be97940859a800ec.diff

LOG: [llvm] Move AttributeMask to a separate header

Move `AttributeMask` out of `llvm/IR/Attributes.h` to a new file
`llvm/IR/AttributeMask.h`.  After doing this we can remove the
`#include ` and `#include ` directives from `Attributes.h`.
Since there are many headers including `Attributes.h`, but not needing
the definition of `AttributeMask`, this causes unnecessary bloating of
the translation units and slows down compilation.

This commit adds in the include directive for `llvm/IR/AttributeMask.h`
to the handful of source files that need to see the definition.

This reduces the total number of preprocessing tokens across the LLVM
source files in lib from (roughly) 1,917,509,187 to 1,902,982,273 - a
reduction of ~0.76%. This should result in a small improvement in
compilation time.

Differential Revision: https://reviews.llvm.org/D153728

Added: 
llvm/include/llvm/IR/AttributeMask.h

Modified: 
clang/lib/CodeGen/CGCall.cpp
clang/lib/CodeGen/CodeGenModule.cpp
llvm/include/llvm/IR/Attributes.h
llvm/lib/Analysis/BlockFrequencyInfoImpl.cpp
llvm/lib/Bitcode/Reader/BitcodeReader.cpp
llvm/lib/CodeGen/MLRegallocEvictAdvisor.cpp
llvm/lib/IR/Attributes.cpp
llvm/lib/IR/AutoUpgrade.cpp
llvm/lib/IR/Instruction.cpp
llvm/lib/IR/Verifier.cpp
llvm/lib/Target/AMDGPU/AMDGPURewriteOutArguments.cpp
llvm/lib/Target/DirectX/DXILPrepare.cpp
llvm/lib/Transforms/IPO/DeadArgumentElimination.cpp
llvm/lib/Transforms/IPO/SCCP.cpp
llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp
llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp
llvm/lib/Transforms/Scalar/RewriteStatepointsForGC.cpp
llvm/lib/Transforms/Utils/CallPromotionUtils.cpp
llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp
llvm/tools/llvm-reduce/deltas/ReduceInstructions.cpp
llvm/unittests/IR/AttributesTest.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index 6a9be661998fc..50ef440937fd9 100644
--- a/clang/lib/CodeGen/CGCall.cpp
+++ b/clang/lib/CodeGen/CGCall.cpp
@@ -31,6 +31,7 @@
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/Analysis/ValueTracking.h"
 #include "llvm/IR/Assumptions.h"
+#include "llvm/IR/AttributeMask.h"
 #include "llvm/IR/Attributes.h"
 #include "llvm/IR/CallingConv.h"
 #include "llvm/IR/DataLayout.h"

diff  --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 7a4b81a48f727..b404b92bb7638 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -52,6 +52,7 @@
 #include "llvm/ADT/StringSwitch.h"
 #include "llvm/Analysis/TargetLibraryInfo.h"
 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
+#include "llvm/IR/AttributeMask.h"
 #include "llvm/IR/CallingConv.h"
 #include "llvm/IR/DataLayout.h"
 #include "llvm/IR/Intrinsics.h"

diff  --git a/llvm/include/llvm/IR/AttributeMask.h 
b/llvm/include/llvm/IR/AttributeMask.h
new file mode 100644
index 0..857761149ff46
--- /dev/null
+++ b/llvm/include/llvm/IR/AttributeMask.h
@@ -0,0 +1,86 @@
+//===- llvm/AttributeMask.h - Mask for Attributes ---*- 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
+//
+//===--===//
+//
+/// \file
+// This file declares the AttributeMask class.
+//
+//===--===//
+
+#ifndef LLVM_IR_ATTRIBUTEMASK_H
+#define LLVM_IR_ATTRIBUTEMASK_H
+
+#include "llvm/ADT/SmallString.h"
+#include "llvm/IR/Attributes.h"
+#include 
+#include 
+#include 
+
+namespace llvm {
+
+//===--===//
+/// \class
+/// This class stores enough information to efficiently remove some attributes
+/// from an existing AttrBuilder, AttributeSet or AttributeList.
+class AttributeMask {
+  std::bitset Attrs;
+  std::set, std::less<>> TargetDepAttrs;
+
+public:
+  AttributeMask() = default;
+  AttributeMask(const AttributeMask &) = delete;
+  AttributeMask(AttributeMask &&) = default;
+
+  AttributeMask(AttributeSet AS) {
+for (Attribute A : AS)
+  addAttribute(A);
+  }
+
+  /// Add an attribute to the mask.
+  AttributeMask &addAttribute(Attribute::AttrKind Val) {
+assert((unsigned)Val < Attribute::EndAttrKinds &&
+   "Attribute out of range!");
+Attrs[Val] = true;
+  

[PATCH] D139837: [Clang] Implements CTAD for aggregates P1816R0 and P2082R1

2023-06-27 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added inline comments.



Comment at: clang/include/clang/AST/DeclBase.h:1687
+/// Only used by CXXDeductionGuideDecl. Indicates the kind
+/// of the Deduction Guide that is the implicitly generated
+/// (used during overload resolution).





Comment at: clang/include/clang/AST/DeclCXX.h:1953-1959
   bool isCopyDeductionCandidate() const {
-return FunctionDeclBits.IsCopyDeductionCandidate;
+return getDeductionCandidateKind() == DeductionCandidateKind::Copy;
+  }
+
+  bool isAggregateDeductionCandidate() const {
+return getDeductionCandidateKind() == DeductionCandidateKind::Aggregate;
   }

cor3ntin wrote:
> ychen wrote:
> > cor3ntin wrote:
> > > I'm not sure how useful these things are, isAggregateDeductionCandidate 
> > > is only used once
> > I meant to make it consistent with `isCopyDeductionCandidate` which is also 
> > used once. Maybe remove both `isCopyDeductionCandidate` and 
> > `isAggregateDeductionCandidate`?
> Yes, i think we might as well
I still think we should remove that



Comment at: clang/include/clang/Sema/Sema.h:9660
+
+struct BuildingDeductionGuides {};
+/// \brief Note that we are building deduction guides.

Maybe rename that `BuildingDeductionGuidesTag`


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D139837/new/

https://reviews.llvm.org/D139837

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D152504: [clang][ThreadSafety] Analyze cleanup functions

2023-06-27 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 534982.
tbaeder marked an inline comment as done.

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D152504/new/

https://reviews.llvm.org/D152504

Files:
  clang/include/clang/Analysis/CFG.h
  clang/lib/Analysis/CFG.cpp
  clang/lib/Analysis/ThreadSafety.cpp
  clang/test/Sema/warn-thread-safety-analysis.c

Index: clang/test/Sema/warn-thread-safety-analysis.c
===
--- clang/test/Sema/warn-thread-safety-analysis.c
+++ clang/test/Sema/warn-thread-safety-analysis.c
@@ -22,6 +22,7 @@
 #define SHARED_LOCKS_REQUIRED(...) \
   __attribute__ ((shared_locks_required(__VA_ARGS__)))
 #define NO_THREAD_SAFETY_ANALYSIS  __attribute__ ((no_thread_safety_analysis))
+#define CLEANUP(A) __attribute__ ((cleanup(A)))
 
 // Define the mutex struct.
 // Simplified only for test purpose.
@@ -72,6 +73,17 @@
   return *p;
 }
 
+void cleanup_int(int *unused) __attribute__((release_capability(mu1))) {
+  (void)unused;
+  mutex_exclusive_unlock(&mu1);
+}
+
+void broken_cleanup_int(int *unused) __attribute__((release_capability(mu1))) {
+  (void)unused;
+  mutex_exclusive_unlock(&mu1);
+  Bar_fun1(6); // expected-warning {{calling function 'Bar_fun1' requires holding mutex 'mu1' exclusively}}
+}
+
 int main(void) {
 
   Foo_fun1(1); // expected-warning{{calling function 'Foo_fun1' requires holding mutex 'mu2'}} \
@@ -127,6 +139,20 @@
 // expected-note@-1{{mutex released here}}
   mutex_shared_unlock(&mu1);// expected-warning {{releasing mutex 'mu1' that was not held}}
 
+  {
+mutex_exclusive_lock(&mu1);
+int CLEANUP(cleanup_int) i;
+
+Bar_fun1(3);
+  }
+  Bar_fun1(4); // expected-warning {{calling function 'Bar_fun1' requires holding mutex 'mu1' exclusively}}
+
+
+  {
+mutex_exclusive_lock(&mu1);
+int CLEANUP(broken_cleanup_int) i2;
+  }
+
   return 0;
 }
 
Index: clang/lib/Analysis/ThreadSafety.cpp
===
--- clang/lib/Analysis/ThreadSafety.cpp
+++ clang/lib/Analysis/ThreadSafety.cpp
@@ -2426,6 +2426,16 @@
 AD.getTriggerStmt()->getEndLoc());
   break;
 }
+
+case CFGElement::CleanupFunction: {
+  const CFGCleanupFunction &CF = BI.castAs();
+
+  LocksetBuilder.handleCall(nullptr, CF.getFunctionDecl(),
+SxBuilder.createVariable(CF.getVarDecl()),
+CF.getVarDecl()->getLocation());
+  break;
+}
+
 case CFGElement::TemporaryDtor: {
   auto TD = BI.castAs();
 
Index: clang/lib/Analysis/CFG.cpp
===
--- clang/lib/Analysis/CFG.cpp
+++ clang/lib/Analysis/CFG.cpp
@@ -866,6 +866,10 @@
 B->appendAutomaticObjDtor(VD, S, cfg->getBumpVectorContext());
   }
 
+  void appendCleanupFunction(CFGBlock *B, VarDecl *VD) {
+B->appendCleanupFunction(VD, cfg->getBumpVectorContext());
+  }
+
   void appendLifetimeEnds(CFGBlock *B, VarDecl *VD, Stmt *S) {
 B->appendLifetimeEnds(VD, S, cfg->getBumpVectorContext());
   }
@@ -1907,7 +1911,8 @@
 Decls.push_back(*I);
 
   for (VarDecl *VD : llvm::reverse(Decls)) {
-if (hasTrivialDestructor(VD)) {
+bool HasCleanupAttr = VD->hasAttr();
+if (hasTrivialDestructor(VD) && !HasCleanupAttr) {
   // If AddScopes is enabled and *I is a first variable in a scope, add a
   // ScopeEnd marker in a Block.
   if (BuildOpts.AddScopes && DeclsWithEndedScope.count(VD)) {
@@ -1925,7 +1930,8 @@
 }
 Ty = Context->getBaseElementType(Ty);
 
-if (Ty->getAsCXXRecordDecl()->isAnyDestructorNoReturn())
+bool IsCXXRecordType = Ty->getAsCXXRecordDecl() != nullptr;
+if (IsCXXRecordType && Ty->getAsCXXRecordDecl()->isAnyDestructorNoReturn())
   Block = createNoReturnBlock();
 else
   autoCreateBlock();
@@ -1933,7 +1939,12 @@
 // Add ScopeEnd just after automatic obj destructor.
 if (BuildOpts.AddScopes && DeclsWithEndedScope.count(VD))
   appendScopeEnd(Block, VD, S);
-appendAutomaticObjDtor(Block, VD, S);
+
+if (HasCleanupAttr)
+  appendCleanupFunction(Block, VD);
+
+if (IsCXXRecordType)
+  appendAutomaticObjDtor(Block, VD, S);
   }
 }
 
@@ -2090,7 +2101,8 @@
 return Scope;
 
   if (BuildOpts.AddImplicitDtors) {
-if (!hasTrivialDestructor(VD) || BuildOpts.AddScopes) {
+if (!hasTrivialDestructor(VD) || VD->hasAttr() ||
+BuildOpts.AddScopes) {
   // Add the variable to scope
   Scope = createOrReuseLocalScope(Scope);
   Scope->addVar(VD);
@@ -5288,8 +5300,9 @@
 case CFGElement::CXXRecordTypedCall:
 case CFGElement::ScopeBegin:
 case CFGElement::ScopeEnd:
-  llvm_unreachable("getDestructorDecl should only be used with "
-   "ImplicitDtors");
+case CFGElement::CleanupFunction:
+llvm_unreachable("getDestructorDecl shoul

[clang] 474ec69 - [clang] Replace uses of CGBuilderTy::CreateElementBitCast (NFC)

2023-06-27 Thread via cfe-commits

Author: Youngsuk Kim
Date: 2023-06-27T10:38:54-04:00
New Revision: 474ec694191a51d7f30a11f8b03dee911c8ef346

URL: 
https://github.com/llvm/llvm-project/commit/474ec694191a51d7f30a11f8b03dee911c8ef346
DIFF: 
https://github.com/llvm/llvm-project/commit/474ec694191a51d7f30a11f8b03dee911c8ef346.diff

LOG: [clang] Replace uses of CGBuilderTy::CreateElementBitCast (NFC)

Partial progress towards replacing `CreateElementBitCast`, as it no
longer does what its name suggests. Either replace its uses with
`Address::withElementType()`, or remove them if no longer needed.

Reviewed By: barannikov88, nikic

Differential Revision: https://reviews.llvm.org/D153314

Added: 


Modified: 
clang/lib/CodeGen/CGAtomic.cpp
clang/lib/CodeGen/CGCXXABI.cpp
clang/lib/CodeGen/CGNonTrivialStruct.cpp
clang/lib/CodeGen/MicrosoftCXXABI.cpp
clang/lib/CodeGen/Targets/AArch64.cpp
clang/lib/CodeGen/Targets/ARM.cpp
clang/lib/CodeGen/Targets/Hexagon.cpp
clang/lib/CodeGen/Targets/LoongArch.cpp
clang/lib/CodeGen/Targets/PPC.cpp
clang/lib/CodeGen/Targets/X86.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGAtomic.cpp b/clang/lib/CodeGen/CGAtomic.cpp
index 6740df8270b3d..f191829b41552 100644
--- a/clang/lib/CodeGen/CGAtomic.cpp
+++ b/clang/lib/CodeGen/CGAtomic.cpp
@@ -162,7 +162,7 @@ namespace {
 }
 
 Address getAtomicAddressAsAtomicIntPointer() const {
-  return emitCastToAtomicIntPointer(getAtomicAddress());
+  return castToAtomicIntPointer(getAtomicAddress());
 }
 
 /// Is the atomic size larger than the underlying value type?
@@ -184,7 +184,7 @@ namespace {
 
 /// Cast the given pointer to an integer pointer suitable for atomic
 /// operations if the source.
-Address emitCastToAtomicIntPointer(Address Addr) const;
+Address castToAtomicIntPointer(Address Addr) const;
 
 /// If Addr is compatible with the iN that will be used for an atomic
 /// operation, bitcast it. Otherwise, create a temporary that is suitable
@@ -979,7 +979,7 @@ RValue CodeGenFunction::EmitAtomicExpr(AtomicExpr *E) {
   AtomicInfo Atomics(*this, AtomicVal);
 
   if (ShouldCastToIntPtrTy) {
-Ptr = Atomics.emitCastToAtomicIntPointer(Ptr);
+Ptr = Atomics.castToAtomicIntPointer(Ptr);
 if (Val1.isValid())
   Val1 = Atomics.convertToAtomicIntPointer(Val1);
 if (Val2.isValid())
@@ -987,13 +987,13 @@ RValue CodeGenFunction::EmitAtomicExpr(AtomicExpr *E) {
   }
   if (Dest.isValid()) {
 if (ShouldCastToIntPtrTy)
-  Dest = Atomics.emitCastToAtomicIntPointer(Dest);
+  Dest = Atomics.castToAtomicIntPointer(Dest);
   } else if (E->isCmpXChg())
 Dest = CreateMemTemp(RValTy, "cmpxchg.bool");
   else if (!RValTy->isVoidType()) {
 Dest = Atomics.CreateTempAlloca();
 if (ShouldCastToIntPtrTy)
-  Dest = Atomics.emitCastToAtomicIntPointer(Dest);
+  Dest = Atomics.castToAtomicIntPointer(Dest);
   }
 
   // Use a library call.  See: http://gcc.gnu.org/wiki/Atomic/GCCMM/LIbrary .
@@ -1338,16 +1338,14 @@ RValue CodeGenFunction::EmitAtomicExpr(AtomicExpr *E) {
   if (E->getOp() == AtomicExpr::AO__atomic_nand_fetch)
 ResVal = Builder.CreateNot(ResVal);
 
-  Builder.CreateStore(
-  ResVal, Builder.CreateElementBitCast(Dest, ResVal->getType()));
+  Builder.CreateStore(ResVal, Dest.withElementType(ResVal->getType()));
 }
 
 if (RValTy->isVoidType())
   return RValue::get(nullptr);
 
-return convertTempToRValue(
-Builder.CreateElementBitCast(Dest, ConvertTypeForMem(RValTy)),
-RValTy, E->getExprLoc());
+return convertTempToRValue(Dest.withElementType(ConvertTypeForMem(RValTy)),
+   RValTy, E->getExprLoc());
   }
 
   bool IsStore = E->getOp() == AtomicExpr::AO__c11_atomic_store ||
@@ -1398,9 +1396,8 @@ RValue CodeGenFunction::EmitAtomicExpr(AtomicExpr *E) {
 if (RValTy->isVoidType())
   return RValue::get(nullptr);
 
-return convertTempToRValue(
-Builder.CreateElementBitCast(Dest, ConvertTypeForMem(RValTy)),
-RValTy, E->getExprLoc());
+return convertTempToRValue(Dest.withElementType(ConvertTypeForMem(RValTy)),
+   RValTy, E->getExprLoc());
   }
 
   // Long case, when Order isn't obviously constant.
@@ -1470,15 +1467,14 @@ RValue CodeGenFunction::EmitAtomicExpr(AtomicExpr *E) {
 return RValue::get(nullptr);
 
   assert(Atomics.getValueSizeInBits() <= Atomics.getAtomicSizeInBits());
-  return convertTempToRValue(
-  Builder.CreateElementBitCast(Dest, ConvertTypeForMem(RValTy)),
-  RValTy, E->getExprLoc());
+  return convertTempToRValue(Dest.withElementType(ConvertTypeForMem(RValTy)),
+ RValTy, E->getExprLoc());
 }
 
-Address AtomicInfo::emitCastToAtomicIntPointer(Address addr) const {
+Address AtomicInfo::castToAtomicIntPointer(Address addr) const {
   llvm::IntegerType *ty =
 llvm::I

[PATCH] D153314: [clang] Replace uses of CGBuilderTy::CreateElementBitCast (NFC)

2023-06-27 Thread Youngsuk Kim via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG474ec694191a: [clang] Replace uses of 
CGBuilderTy::CreateElementBitCast (NFC) (authored by JOE1994).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153314/new/

https://reviews.llvm.org/D153314

Files:
  clang/lib/CodeGen/CGAtomic.cpp
  clang/lib/CodeGen/CGCXXABI.cpp
  clang/lib/CodeGen/CGNonTrivialStruct.cpp
  clang/lib/CodeGen/MicrosoftCXXABI.cpp
  clang/lib/CodeGen/Targets/AArch64.cpp
  clang/lib/CodeGen/Targets/ARM.cpp
  clang/lib/CodeGen/Targets/Hexagon.cpp
  clang/lib/CodeGen/Targets/LoongArch.cpp
  clang/lib/CodeGen/Targets/PPC.cpp
  clang/lib/CodeGen/Targets/X86.cpp

Index: clang/lib/CodeGen/Targets/X86.cpp
===
--- clang/lib/CodeGen/Targets/X86.cpp
+++ clang/lib/CodeGen/Targets/X86.cpp
@@ -318,8 +318,7 @@
   ResultTruncRegTypes.push_back(CoerceTy);
 
   // Coerce the integer by bitcasting the return slot pointer.
-  ReturnSlot.setAddress(
-  CGF.Builder.CreateElementBitCast(ReturnSlot.getAddress(CGF), CoerceTy));
+  ReturnSlot.setAddress(ReturnSlot.getAddress(CGF).withElementType(CoerceTy));
   ResultRegDests.push_back(ReturnSlot);
 
   rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
@@ -3048,7 +3047,7 @@
 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
 llvm::StructType *ST = cast(AI.getCoerceToType());
 Address Tmp = CGF.CreateMemTemp(Ty);
-Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
+Tmp = Tmp.withElementType(ST);
 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
 llvm::Type *TyLo = ST->getElementType(0);
 llvm::Type *TyHi = ST->getElementType(1);
@@ -3076,11 +3075,10 @@
 CharUnits::fromQuantity(getDataLayout().getABITypeAlign(TyHi)));
 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
 
-RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
+RegAddr = Tmp.withElementType(LTy);
   } else if (neededInt) {
 RegAddr = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, gp_offset),
-  CGF.Int8Ty, CharUnits::fromQuantity(8));
-RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
+  LTy, CharUnits::fromQuantity(8));
 
 // Copy to a temporary if necessary to ensure the appropriate alignment.
 auto TInfo = getContext().getTypeInfoInChars(Ty);
@@ -3097,8 +3095,7 @@
 
   } else if (neededSSE == 1) {
 RegAddr = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, fp_offset),
-  CGF.Int8Ty, CharUnits::fromQuantity(16));
-RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
+  LTy, CharUnits::fromQuantity(16));
   } else {
 assert(neededSSE == 2 && "Invalid number of needed registers!");
 // SSE registers are spaced 16 bytes apart in the register save
@@ -3118,15 +3115,15 @@
  : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy);
 llvm::Value *V;
 Address Tmp = CGF.CreateMemTemp(Ty);
-Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
-V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
-RegAddrLo, ST->getStructElementType(0)));
+Tmp = Tmp.withElementType(ST);
+V = CGF.Builder.CreateLoad(
+RegAddrLo.withElementType(ST->getStructElementType(0)));
 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
-V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
-RegAddrHi, ST->getStructElementType(1)));
+V = CGF.Builder.CreateLoad(
+RegAddrHi.withElementType(ST->getStructElementType(1)));
 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
 
-RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
+RegAddr = Tmp.withElementType(LTy);
   }
 
   // AMD64-ABI 3.5.7p5: Step 5. Set:
Index: clang/lib/CodeGen/Targets/PPC.cpp
===
--- clang/lib/CodeGen/Targets/PPC.cpp
+++ clang/lib/CodeGen/Targets/PPC.cpp
@@ -31,8 +31,8 @@
   }
 
   llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
-  RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
-  ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
+  RealAddr = RealAddr.withElementType(EltTy);
+  ImagAddr = ImagAddr.withElementType(EltTy);
   llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
   llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
 
@@ -456,8 +456,7 @@
 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
 RegAddr = Address(
 Builder.CreateInBoundsGEP(CGF.Int8Ty, RegAddr.getPointer(), RegOffset),
-CGF.Int8Ty, RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
-RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
+DirectTy, RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
 

[PATCH] D105759: Implement P2361 Unevaluated string literals

2023-06-27 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/include/clang/Basic/Attr.td:1411
   let Documentation = [DeprecatedDocs];
+  let ParseArgumentsAsUnevaluated = 1;
 }

cor3ntin wrote:
> aaron.ballman wrote:
> > What is the plan for non-standard attributes? Are you planning to handle 
> > those in a follow-up, or should we be investigating those right now?
> I don't feel I'm qualified to answer that. Ideally, attributes that expect 
> string literals that are not evaluated should follow suite.
Let's do them in a follow-up. Normally I'd suggest working with @erichkeane on 
which attributes to apply that to, but he's about to go on a sabbatical and 
might not have time to help with that. So maybe you can take a first pass at it 
as best you can and then rope me in to help finalize it, if that'd work for you?



Comment at: clang/lib/Lex/LiteralSupport.cpp:2080-2082
+  if (!isUnevaluated() && Features.PascalStrings &&
+  ThisTokBuf + 1 != ThisTokEnd && ThisTokBuf[0] == '\\' &&
+  ThisTokBuf[1] == 'p') {

cor3ntin wrote:
> aaron.ballman wrote:
> > Is there test coverage that we diagnose this properly?
> What sort of test would you like to see?
Pascal strings enabled and using something like `[[deprecated("\pOh no, a 
Pascal string!")]]` (or some other unevaluated uses).



Comment at: clang/lib/Parse/ParseExpr.cpp:3501-3503
+} else if (!AllowEvaluatedString && tok::isStringLiteral(Tok.getKind())) {
+  Expr = ParseUnevaluatedStringLiteralExpression();
+} else {

cor3ntin wrote:
> aaron.ballman wrote:
> > I'm surprised we need special logic in `ParseExpressionList()` for handling 
> > unevaluated string literals; I would have expected that to be needed when 
> > parsing a string literal. Nothing changed in the grammar for 
> > http://eel.is/c++draft/expr.post.general#nt:expression-list (or 
> > initializer-list), so these changes seem wrong. Can you explain the changes 
> > a bit more?
> We use `ParseExpressionList` when parsing attribute arguments, and some 
> attributes have unevaluate string as argument - I agree with you that I'd 
> rather find a better solution for attributes, but I came up empty. There is 
> no further reason for this change, and you are right it does not match the 
> grammar.
I was thinking we'd use a new kind of evaluation context for this. We'd enter 
the evaluation context when we know we need to parse an expression that is an 
unevaluated string literal which the string literal parser would pay attention 
to. This would require knowing up-front when we want to parse an unevaluated 
string literal, but we should have that information available to us at parse 
time (I think).



Comment at: clang/lib/Sema/SemaDeclAttr.cpp:878-879
 
-  if (!isIntOrBool(AL.getArgAsExpr(0))) {
+  Expr *First = AL.getArgAsExpr(0);
+  if (isa(First) || !isIntOrBool(First)) {
 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)

cor3ntin wrote:
> aaron.ballman wrote:
> > Test coverage for these changes?
> There is one somewhere, I don;t remember where, The reason we need to do that 
> is that Unevaluated StringLiterals don''t have types
Let's try to track that down, but... an unevaluated string literal still has a 
type, surely? It'd be `const char[]` for C++?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D105759/new/

https://reviews.llvm.org/D105759

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153860: [clang-tidy] Fix modernize-use-std-print check when return value used

2023-06-27 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL accepted this revision.
PiotrZSL added a comment.
This revision is now accepted and ready to land.

LGTM




Comment at: clang-tools-extra/clang-tidy/modernize/UseStdPrintCheck.cpp:73-95
+static clang::ast_matchers::StatementMatcher
+unusedReturnValue(clang::ast_matchers::StatementMatcher MatchedCallExpr) {
+  auto UnusedInCompoundStmt =
+  compoundStmt(forEach(MatchedCallExpr),
+   // The checker can't currently differentiate between the
+   // return statement and other statements inside GNU 
statement
+   // expressions, so disable the checker inside them to avoid

NOTE: Personally I do not thing that this is right way. Instead of using 
"inclusion" matcher, better would be to use elimination.
like:
```callExpr(unless(hasParent(anyOf(varDecl(), callExpr(), ifStmt(), ...```.

But if it's working fine, then it could be for now, so lets leave it. Simply 
with this it may not find all cases.



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print-absl.cpp:63
+  // CHECK-MESSAGES-NOT: [[@LINE-1]]:10: warning: use 'std::println' instead 
of 'PrintF' [modernize-use-std-print]
+  // CHECK-FIXES-NOT: std::println("return value {}", i);
+}

NOTE: I don't think that those FIXES-NOT are needed.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153860/new/

https://reviews.llvm.org/D153860

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153612: [clang][analyzer] Add and change NoteTags in StdLibraryFunctionsChecker.

2023-06-27 Thread Balázs Kéri via Phabricator via cfe-commits
balazske updated this revision to Diff 534991.
balazske marked 5 inline comments as done.
balazske added a comment.

Fixed review issues


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153612/new/

https://reviews.llvm.org/D153612

Files:
  clang/lib/StaticAnalyzer/Checkers/ErrnoModeling.cpp
  clang/lib/StaticAnalyzer/Checkers/ErrnoModeling.h
  clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
  clang/test/Analysis/errno-stdlibraryfunctions-notes.c
  clang/test/Analysis/std-c-library-functions-arg-constraints-note-tags.cpp
  clang/test/Analysis/std-c-library-functions-path-notes.c
  clang/test/Analysis/stream-errno-note.c
  clang/test/Analysis/stream-note.c

Index: clang/test/Analysis/stream-note.c
===
--- clang/test/Analysis/stream-note.c
+++ clang/test/Analysis/stream-note.c
@@ -7,11 +7,13 @@
 
 void check_note_at_correct_open(void) {
   FILE *F1 = tmpfile(); // expected-note {{Stream opened here}}
+  // stdargs-note@-1 {{call is successful}}
   if (!F1)
 // expected-note@-1 {{'F1' is non-null}}
 // expected-note@-2 {{Taking false branch}}
 return;
   FILE *F2 = tmpfile();
+  // stdargs-note@-1 {{call is successful}}
   if (!F2) {
 // expected-note@-1 {{'F2' is non-null}}
 // expected-note@-2 {{Taking false branch}}
@@ -20,6 +22,7 @@
   }
   rewind(F2);
   fclose(F2);
+  // stdargs-note@-1 {{call fails}}
   rewind(F1);
 }
 // expected-warning@-1 {{Opened stream never closed. Potential resource leak}}
@@ -27,6 +30,7 @@
 
 void check_note_fopen(void) {
   FILE *F = fopen("file", "r"); // expected-note {{Stream opened here}}
+  // stdargs-note@-1 {{call is successful}}
   if (!F)
 // expected-note@-1 {{'F' is non-null}}
 // expected-note@-2 {{Taking false branch}}
@@ -37,11 +41,13 @@
 
 void check_note_freopen(void) {
   FILE *F = fopen("file", "r"); // expected-note {{Stream opened here}}
+  // stdargs-note@-1 {{call is successful}}
   if (!F)
 // expected-note@-1 {{'F' is non-null}}
 // expected-note@-2 {{Taking false branch}}
 return;
   F = freopen(0, "w", F); // expected-note {{Stream reopened here}}
+  // stdargs-note@-1 {{call is successful}}
   if (!F)
 // expected-note@-1 {{'F' is non-null}}
 // expected-note@-2 {{Taking false branch}}
@@ -52,6 +58,8 @@
 
 void check_note_leak_2(int c) {
   FILE *F1 = fopen("foo1.c", "r"); // expected-note {{Stream opened here}}
+  // stdargs-note@-1 {{call is successful}}
+  // stdargs-note@-2 {{call is successful}}
   if (!F1)
 // expected-note@-1 {{'F1' is non-null}}
 // expected-note@-2 {{Taking false branch}}
@@ -59,6 +67,8 @@
 // expected-note@-4 {{Taking false branch}}
 return;
   FILE *F2 = fopen("foo2.c", "r"); // expected-note {{Stream opened here}}
+  // stdargs-note@-1 {{call is successful}}
+  // stdargs-note@-2 {{call is successful}}
   if (!F2) {
 // expected-note@-1 {{'F2' is non-null}}
 // expected-note@-2 {{Taking false branch}}
@@ -84,6 +94,7 @@
 void check_track_null(void) {
   FILE *F;
   F = fopen("foo1.c", "r"); // expected-note {{Value assigned to 'F'}} expected-note {{Assuming pointer value is null}}
+  // stdargs-note@-1 {{call fails}}
   if (F != NULL) {  // expected-note {{Taking false branch}} expected-note {{'F' is equal to NULL}}
 fclose(F);
 return;
@@ -96,6 +107,7 @@
   FILE *F;
   char Buf[10];
   F = fopen("foo1.c", "r");
+  // stdargs-note@-1 {{call is successful}}
   if (F == NULL) { // expected-note {{Taking false branch}} expected-note {{'F' is not equal to NULL}}
 return;
   }
@@ -115,6 +127,7 @@
   FILE *F;
   char Buf[10];
   F = fopen("foo1.c", "r");
+  // stdargs-note@-1 {{call is successful}}
   if (F == NULL) { // expected-note {{Taking false branch}} expected-note {{'F' is not equal to NULL}}
 return;
   }
@@ -138,6 +151,7 @@
   FILE *F;
   char Buf[10];
   F = fopen("foo1.c", "r");
+  // stdargs-note@-1 {{call is successful}}
   if (F == NULL) // expected-note {{Taking false branch}} expected-note {{'F' is not equal to NULL}}
 return;
   int RRet = fread(Buf, 1, 1, F); // expected-note {{Assuming stream reaches end-of-file here}}
Index: clang/test/Analysis/stream-errno-note.c
===
--- clang/test/Analysis/stream-errno-note.c
+++ clang/test/Analysis/stream-errno-note.c
@@ -10,7 +10,8 @@
 
 void check_fopen(void) {
   FILE *F = fopen("xxx", "r");
-  // expected-note@-1{{Assuming that function 'fopen' is successful, in this case the value 'errno' may be undefined after the call and should not be used}}
+  // expected-note@-1{{'errno' may be undefined after successful call to 'fopen'}}
+  // expected-note@-2{{call is successful}}
   // expected-note@+2{{'F' is non-null}}
   // expected-note@+1{{Taking false branch}}
   if (!F)
@@ -22,7 +23,8 @@
 
 void check_tmpfile(void) {
   FILE *F = tmpfile();
-  // expected-note@-1{{Assuming that func

[PATCH] D153882: [clangd] Always allow diagnostics from stale preambles

2023-06-27 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet created this revision.
kadircet added a reviewer: hokein.
Herald added subscribers: arphaman, javed.absar.
Herald added a project: All.
kadircet requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

We've been running this internally for months now, without any
stability or correctness concerns. It has ~40% speed up on incremental
diagnostics latencies (as preamble can get invalidated through code completion
etc.).


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D153882

Files:
  clang-tools-extra/clangd/ClangdLSPServer.cpp
  clang-tools-extra/clangd/ClangdLSPServer.h
  clang-tools-extra/clangd/ClangdServer.cpp
  clang-tools-extra/clangd/ClangdServer.h
  clang-tools-extra/clangd/Config.h
  clang-tools-extra/clangd/ConfigCompile.cpp
  clang-tools-extra/clangd/ConfigFragment.h
  clang-tools-extra/clangd/ConfigYAML.cpp
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/ParsedAST.h
  clang-tools-extra/clangd/Preamble.cpp
  clang-tools-extra/clangd/Preamble.h
  clang-tools-extra/clangd/TUScheduler.cpp
  clang-tools-extra/clangd/tool/Check.cpp
  clang-tools-extra/clangd/unittests/ClangdTests.cpp
  clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp
  clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
  clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
  clang-tools-extra/clangd/unittests/FeatureModulesTests.cpp
  clang-tools-extra/clangd/unittests/ModulesTests.cpp
  clang-tools-extra/clangd/unittests/ParsedASTTests.cpp
  clang-tools-extra/clangd/unittests/PreambleTests.cpp
  clang-tools-extra/clangd/unittests/SelectionTests.cpp
  clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
  clang-tools-extra/clangd/unittests/TestTU.cpp
  clang-tools-extra/clangd/unittests/TypeHierarchyTests.cpp

Index: clang-tools-extra/clangd/unittests/TypeHierarchyTests.cpp
===
--- clang-tools-extra/clangd/unittests/TypeHierarchyTests.cpp
+++ clang-tools-extra/clangd/unittests/TypeHierarchyTests.cpp
@@ -402,7 +402,7 @@
 
   // The compiler should produce a diagnostic for hitting the
   // template instantiation depth.
-  ASSERT_TRUE(!AST.getDiagnostics()->empty());
+  ASSERT_FALSE(AST.getDiagnostics().empty());
 
   // Make sure getTypeHierarchy() doesn't get into an infinite recursion.
   // The parent is reported as "S" because "S<0>" is an invalid instantiation.
Index: clang-tools-extra/clangd/unittests/TestTU.cpp
===
--- clang-tools-extra/clangd/unittests/TestTU.cpp
+++ clang-tools-extra/clangd/unittests/TestTU.cpp
@@ -132,8 +132,6 @@
 llvm::errs() << "Failed to build code:\n" << Code;
 std::abort();
   }
-  assert(AST->getDiagnostics() &&
- "TestTU should always build an AST with a fresh Preamble");
   // Check for error diagnostics and report gtest failures (unless expected).
   // This guards against accidental syntax errors silently subverting tests.
   // error-ok is awfully primitive - using clang -verify would be nicer.
@@ -150,7 +148,7 @@
   }();
   if (!ErrorOk) {
 // We always build AST with a fresh preamble in TestTU.
-for (const auto &D : *AST->getDiagnostics())
+for (const auto &D : AST->getDiagnostics())
   if (D.Severity >= DiagnosticsEngine::Error) {
 llvm::errs()
 << "TestTU failed to build (suppress with /*error-ok*/): \n"
Index: clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
===
--- clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
+++ clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
@@ -126,7 +126,7 @@
 class CaptureDiags : public ParsingCallbacks {
 public:
   void onMainAST(PathRef File, ParsedAST &AST, PublishFn Publish) override {
-reportDiagnostics(File, *AST.getDiagnostics(), Publish);
+reportDiagnostics(File, AST.getDiagnostics(), Publish);
   }
 
   void onFailedAST(PathRef File, llvm::StringRef Version,
@@ -141,9 +141,8 @@
 if (!D)
   return;
 Publish([&]() {
-  const_cast<
-  llvm::unique_function)> &> (*D)(
-  File, std::move(Diags));
+  const_cast)> &>(
+  *D)(File, Diags);
 });
   }
 };
@@ -230,20 +229,24 @@
 Notification Ready;
 TUScheduler S(CDB, optsForTest(), captureDiags());
 auto Path = testPath("foo.cpp");
-updateWithDiags(S, Path, "", WantDiagnostics::Yes,
+// Semicolons here and in the following inputs are significant. They ensure
+// preamble stays the same across runs. Otherwise we might get multiple
+// diagnostics callbacks, once with the stale preamble and another with the
+// fresh preamble.
+updateWithDiags(S, Path, ";", WantDiagnostics::Yes,
 [&](std::vector) { Ready.wait(); });
-updateW

[PATCH] D153882: [clangd] Always allow diagnostics from stale preambles

2023-06-27 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 534995.
kadircet added a comment.

- Squash base commit


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153882/new/

https://reviews.llvm.org/D153882

Files:
  clang-tools-extra/clangd/ClangdLSPServer.cpp
  clang-tools-extra/clangd/ClangdLSPServer.h
  clang-tools-extra/clangd/ClangdServer.cpp
  clang-tools-extra/clangd/ClangdServer.h
  clang-tools-extra/clangd/Config.h
  clang-tools-extra/clangd/ConfigCompile.cpp
  clang-tools-extra/clangd/ConfigFragment.h
  clang-tools-extra/clangd/ConfigYAML.cpp
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/ParsedAST.h
  clang-tools-extra/clangd/Preamble.cpp
  clang-tools-extra/clangd/Preamble.h
  clang-tools-extra/clangd/TUScheduler.cpp
  clang-tools-extra/clangd/tool/Check.cpp
  clang-tools-extra/clangd/unittests/ClangdTests.cpp
  clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp
  clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
  clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
  clang-tools-extra/clangd/unittests/FeatureModulesTests.cpp
  clang-tools-extra/clangd/unittests/ModulesTests.cpp
  clang-tools-extra/clangd/unittests/ParsedASTTests.cpp
  clang-tools-extra/clangd/unittests/PreambleTests.cpp
  clang-tools-extra/clangd/unittests/SelectionTests.cpp
  clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
  clang-tools-extra/clangd/unittests/TestTU.cpp
  clang-tools-extra/clangd/unittests/TypeHierarchyTests.cpp

Index: clang-tools-extra/clangd/unittests/TypeHierarchyTests.cpp
===
--- clang-tools-extra/clangd/unittests/TypeHierarchyTests.cpp
+++ clang-tools-extra/clangd/unittests/TypeHierarchyTests.cpp
@@ -402,7 +402,7 @@
 
   // The compiler should produce a diagnostic for hitting the
   // template instantiation depth.
-  ASSERT_TRUE(!AST.getDiagnostics()->empty());
+  ASSERT_FALSE(AST.getDiagnostics().empty());
 
   // Make sure getTypeHierarchy() doesn't get into an infinite recursion.
   // The parent is reported as "S" because "S<0>" is an invalid instantiation.
Index: clang-tools-extra/clangd/unittests/TestTU.cpp
===
--- clang-tools-extra/clangd/unittests/TestTU.cpp
+++ clang-tools-extra/clangd/unittests/TestTU.cpp
@@ -132,8 +132,6 @@
 llvm::errs() << "Failed to build code:\n" << Code;
 std::abort();
   }
-  assert(AST->getDiagnostics() &&
- "TestTU should always build an AST with a fresh Preamble");
   // Check for error diagnostics and report gtest failures (unless expected).
   // This guards against accidental syntax errors silently subverting tests.
   // error-ok is awfully primitive - using clang -verify would be nicer.
@@ -150,7 +148,7 @@
   }();
   if (!ErrorOk) {
 // We always build AST with a fresh preamble in TestTU.
-for (const auto &D : *AST->getDiagnostics())
+for (const auto &D : AST->getDiagnostics())
   if (D.Severity >= DiagnosticsEngine::Error) {
 llvm::errs()
 << "TestTU failed to build (suppress with /*error-ok*/): \n"
Index: clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
===
--- clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
+++ clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
@@ -126,7 +126,7 @@
 class CaptureDiags : public ParsingCallbacks {
 public:
   void onMainAST(PathRef File, ParsedAST &AST, PublishFn Publish) override {
-reportDiagnostics(File, *AST.getDiagnostics(), Publish);
+reportDiagnostics(File, AST.getDiagnostics(), Publish);
   }
 
   void onFailedAST(PathRef File, llvm::StringRef Version,
@@ -141,9 +141,8 @@
 if (!D)
   return;
 Publish([&]() {
-  const_cast<
-  llvm::unique_function)> &> (*D)(
-  File, std::move(Diags));
+  const_cast)> &>(
+  *D)(File, Diags);
 });
   }
 };
@@ -230,20 +229,24 @@
 Notification Ready;
 TUScheduler S(CDB, optsForTest(), captureDiags());
 auto Path = testPath("foo.cpp");
-updateWithDiags(S, Path, "", WantDiagnostics::Yes,
+// Semicolons here and in the following inputs are significant. They ensure
+// preamble stays the same across runs. Otherwise we might get multiple
+// diagnostics callbacks, once with the stale preamble and another with the
+// fresh preamble.
+updateWithDiags(S, Path, ";", WantDiagnostics::Yes,
 [&](std::vector) { Ready.wait(); });
-updateWithDiags(S, Path, "request diags", WantDiagnostics::Yes,
+updateWithDiags(S, Path, ";request diags", WantDiagnostics::Yes,
 [&](std::vector) { ++CallbackCount; });
-updateWithDiags(S, Path, "auto (clobbered)", WantDiagnostics::Auto,
+updateWithDiags(S, Path, ";auto (clobbered)", WantDiagnostics::Auto,
   

[PATCH] D153612: [clang][analyzer] Add and change NoteTags in StdLibraryFunctionsChecker.

2023-06-27 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added inline comments.



Comment at: 
clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp:1299
+// StdLibraryFunctionsChecker.
+ExplodedNode *Pred = const_cast(Node);
+if (!Case.getNote().empty()) {

donat.nagy wrote:
> balazske wrote:
> > donat.nagy wrote:
> > > Can you explain why is it safe to use `const_cast` here? (I don't see any 
> > > concrete issue, but the engine has lots of invariants / unwritten rules 
> > > and I fear that this might break one of them.)
> > The node `Pred` should be modified only later when a successor is added 
> > (`addTransition` has non-const parameter).
> I understood that you //need// a non-const `ExplodedNode *` because 
> `addTransition` expects it; I want to understand why you are //allowed to// 
> `const_cast` it (why doesn't this confuse the engine logic).
> 
> Equivalent question from the other direction: Why did the author of 
> `CheckerContext::getPredecessor()` specify that its return value is a 
> //const// pointer to `ExplodedNode`?
> 
> If we can conclude that `const_cast` is valid in this kind of situation, then 
> I'd also consider simply removing the "const" from the return type of 
> `getPredecessor`.
The `const_cast` is not needed at all if `Pred` and `Node` is made non-const, 
and `getPredecessor` has a non-const version. The `Node` is saved because we 
want to add transitions to it, it makes no sense to have it (a pointer to) 
const. (Probably the const comes from a time when the `Node` was used only for 
the lambda? In the lambda it could be const, if it matters.)


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153612/new/

https://reviews.llvm.org/D153612

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153883: [Clang][OpenMP] Enable use of __kmpc_alloc_shared for VLAs defined in AMD GPU offloaded regions

2023-06-27 Thread Gheorghe-Teodor Bercea via Phabricator via cfe-commits
doru1004 created this revision.
doru1004 added reviewers: ronlieb, gregrodgers, carlo.bertolli, arsenm, 
jdoerfert, dhruvachak, ABataev.
doru1004 added a project: OpenMP.
Herald added subscribers: sunshaoce, guansong, yaxunl, jvesely.
Herald added a project: All.
doru1004 requested review of this revision.
Herald added subscribers: cfe-commits, jplehr, sstefan1, wdng.
Herald added a project: clang.

This patch enables the use of `___kmpc_alloc_shared` to allocate dynamically 
sized allocation on AMD GPUs. For example:

  #pragma omp target
  {
int N = 10;
double A[N];
...
  }

This will generate a pair of `__kmpc_alloc_shared / __kmpc_free_shared` to 
handle the allocation and deallocation of `A` inside the target region.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D153883

Files:
  clang/lib/CodeGen/CGDecl.cpp
  clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
  clang/lib/CodeGen/CGOpenMPRuntimeGPU.h
  clang/lib/CodeGen/CodeGenFunction.h
  clang/test/OpenMP/amdgcn_target_device_vla.cpp

Index: clang/test/OpenMP/amdgcn_target_device_vla.cpp
===
--- /dev/null
+++ clang/test/OpenMP/amdgcn_target_device_vla.cpp
@@ -0,0 +1,869 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --function-signature --include-generated-funcs --replace-value-regex "__omp_offloading_[0-9a-z]+_[0-9a-z]+" "reduction_size[.].+[.]" "pl_cond[.].+[.|,]" --prefix-filecheck-ir-name _
+// REQUIRES: amdgpu-registered-target
+
+// RUN: %clang_cc1 -fopenmp -x c++ -std=c++11 -triple x86_64-unknown-unknown -fopenmp-targets=amdgcn-amd-amdhsa -emit-llvm-bc %s -o %t-ppc-host.bc
+// RUN: %clang_cc1 -fopenmp -x c++ -std=c++11 -triple amdgcn-amd-amdhsa -fopenmp-targets=amdgcn-amd-amdhsa -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o - | FileCheck %s
+// expected-no-diagnostics
+#ifndef HEADER
+#define HEADER
+
+int foo1() {
+  int sum = 0.0;
+  #pragma omp target map(tofrom: sum)
+  {
+int N = 10;
+int A[N];
+
+for (int i = 0; i < N; i++)
+  A[i] = i;
+
+for (int i = 0; i < N; i++)
+  sum += A[i];
+  }
+  return sum;
+}
+
+int foo2() {
+  int sum = 0.0;
+  int M = 12;
+  int result[M];
+  #pragma omp target teams distribute parallel for map(from: result[:M])
+  for (int i = 0; i < M; i++) {
+int N = 10;
+int A[N];
+result[i] = i;
+
+for (int j = 0; j < N; j++)
+  A[j] = j;
+
+for (int j = 0; j < N; j++)
+  result[i] += A[j];
+  }
+
+  for (int i = 0; i < M; i++)
+sum += result[i];
+  return sum;
+}
+
+int foo3() {
+  int sum = 0.0;
+  int M = 12;
+  int result[M];
+  #pragma omp target teams distribute map(from: result[:M])
+  for (int i = 0; i < M; i++) {
+int N = 10;
+int A[N];
+result[i] = i;
+
+#pragma omp parallel for
+for (int j = 0; j < N; j++)
+  A[j] = j;
+
+for (int j = 0; j < N; j++)
+  result[i] += A[j];
+  }
+
+  for (int i = 0; i < M; i++)
+sum += result[i];
+  return sum;
+}
+
+int main() {
+  return foo1() + foo2() + foo3();
+}
+
+#endif
+// CHECK-LABEL: define {{[^@]+}}@{{__omp_offloading_[0-9a-z]+_[0-9a-z]+}}__Z4foo1v_l12
+// CHECK-SAME: (ptr noundef nonnull align 4 dereferenceable(4) [[SUM:%.*]]) #[[ATTR0:[0-9]+]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[SUM_ADDR:%.*]] = alloca ptr, align 8, addrspace(5)
+// CHECK-NEXT:[[N:%.*]] = alloca i32, align 4, addrspace(5)
+// CHECK-NEXT:[[__VLA_EXPR0:%.*]] = alloca i64, align 8, addrspace(5)
+// CHECK-NEXT:[[I:%.*]] = alloca i32, align 4, addrspace(5)
+// CHECK-NEXT:[[I1:%.*]] = alloca i32, align 4, addrspace(5)
+// CHECK-NEXT:[[SUM_ADDR_ASCAST:%.*]] = addrspacecast ptr addrspace(5) [[SUM_ADDR]] to ptr
+// CHECK-NEXT:[[N_ASCAST:%.*]] = addrspacecast ptr addrspace(5) [[N]] to ptr
+// CHECK-NEXT:[[__VLA_EXPR0_ASCAST:%.*]] = addrspacecast ptr addrspace(5) [[__VLA_EXPR0]] to ptr
+// CHECK-NEXT:[[I_ASCAST:%.*]] = addrspacecast ptr addrspace(5) [[I]] to ptr
+// CHECK-NEXT:[[I1_ASCAST:%.*]] = addrspacecast ptr addrspace(5) [[I1]] to ptr
+// CHECK-NEXT:store ptr [[SUM]], ptr [[SUM_ADDR_ASCAST]], align 8
+// CHECK-NEXT:[[TMP0:%.*]] = load ptr, ptr [[SUM_ADDR_ASCAST]], align 8
+// CHECK-NEXT:[[TMP1:%.*]] = call i32 @__kmpc_target_init(ptr addrspacecast (ptr addrspace(1) @[[GLOB1:[0-9]+]] to ptr), i8 1, i1 true)
+// CHECK-NEXT:[[EXEC_USER_CODE:%.*]] = icmp eq i32 [[TMP1]], -1
+// CHECK-NEXT:br i1 [[EXEC_USER_CODE]], label [[USER_CODE_ENTRY:%.*]], label [[WORKER_EXIT:%.*]]
+// CHECK:   user_code.entry:
+// CHECK-NEXT:store i32 10, ptr [[N_ASCAST]], align 4
+// CHECK-NEXT:[[TMP2:%.*]] = load i32, ptr [[N_ASCAST]], align 4
+// CHECK-NEXT:[[TMP3:%.*]] = zext i32 [[TMP2]] to i64
+// CHECK-NEXT:[[TMP4:%.*]] = mul nuw i64 [[TMP3]], 4
+// CHECK-NEXT:[[TMP5:%.*]] = add nuw i64 [[TMP4]], 3
+// CHECK-NEXT:[[TMP6:%.*]] = udiv i64 [[TMP5]], 4
+// CHECK-NEXT:[[TMP7:%.*]] =

[PATCH] D150978: [clang][Sema] Add CodeCompletionContext::CCC_ObjCClassForwardDecl

2023-06-27 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet accepted this revision.
kadircet added a comment.
This revision is now accepted and ready to land.

thanks


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D150978/new/

https://reviews.llvm.org/D150978

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D105759: Implement P2361 Unevaluated string literals

2023-06-27 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added inline comments.



Comment at: clang/lib/Parse/ParseExpr.cpp:3501-3503
+} else if (!AllowEvaluatedString && tok::isStringLiteral(Tok.getKind())) {
+  Expr = ParseUnevaluatedStringLiteralExpression();
+} else {

aaron.ballman wrote:
> cor3ntin wrote:
> > aaron.ballman wrote:
> > > I'm surprised we need special logic in `ParseExpressionList()` for 
> > > handling unevaluated string literals; I would have expected that to be 
> > > needed when parsing a string literal. Nothing changed in the grammar for 
> > > http://eel.is/c++draft/expr.post.general#nt:expression-list (or 
> > > initializer-list), so these changes seem wrong. Can you explain the 
> > > changes a bit more?
> > We use `ParseExpressionList` when parsing attribute arguments, and some 
> > attributes have unevaluate string as argument - I agree with you that I'd 
> > rather find a better solution for attributes, but I came up empty. There is 
> > no further reason for this change, and you are right it does not match the 
> > grammar.
> I was thinking we'd use a new kind of evaluation context for this. We'd enter 
> the evaluation context when we know we need to parse an expression that is an 
> unevaluated string literal which the string literal parser would pay 
> attention to. This would require knowing up-front when we want to parse an 
> unevaluated string literal, but we should have that information available to 
> us at parse time (I think).
After offline discussion, i think what we want to be doing is to have a

`ParseAtttributeArgumentList` function that is aware of whether the Nth 
argument is an unevaluated string - by means of modifying tablegen,
and doing the right parsing accordingly.
It would take care of all attributes automatically.
Alas that's a tad more involved.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D105759/new/

https://reviews.llvm.org/D105759

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D105759: Implement P2361 Unevaluated string literals

2023-06-27 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/lib/Parse/ParseExpr.cpp:3501-3503
+} else if (!AllowEvaluatedString && tok::isStringLiteral(Tok.getKind())) {
+  Expr = ParseUnevaluatedStringLiteralExpression();
+} else {

cor3ntin wrote:
> aaron.ballman wrote:
> > cor3ntin wrote:
> > > aaron.ballman wrote:
> > > > I'm surprised we need special logic in `ParseExpressionList()` for 
> > > > handling unevaluated string literals; I would have expected that to be 
> > > > needed when parsing a string literal. Nothing changed in the grammar 
> > > > for http://eel.is/c++draft/expr.post.general#nt:expression-list (or 
> > > > initializer-list), so these changes seem wrong. Can you explain the 
> > > > changes a bit more?
> > > We use `ParseExpressionList` when parsing attribute arguments, and some 
> > > attributes have unevaluate string as argument - I agree with you that I'd 
> > > rather find a better solution for attributes, but I came up empty. There 
> > > is no further reason for this change, and you are right it does not match 
> > > the grammar.
> > I was thinking we'd use a new kind of evaluation context for this. We'd 
> > enter the evaluation context when we know we need to parse an expression 
> > that is an unevaluated string literal which the string literal parser would 
> > pay attention to. This would require knowing up-front when we want to parse 
> > an unevaluated string literal, but we should have that information 
> > available to us at parse time (I think).
> After offline discussion, i think what we want to be doing is to have a
> 
> `ParseAtttributeArgumentList` function that is aware of whether the Nth 
> argument is an unevaluated string - by means of modifying tablegen,
> and doing the right parsing accordingly.
> It would take care of all attributes automatically.
> Alas that's a tad more involved.
+1

I agree it's more involved, but it's also a more general solution that fits 
nicely in the parser design (we do this sort of thing for other parts of 
attribute parsing).


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D105759/new/

https://reviews.llvm.org/D105759

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] f6be96a - [clang][ExprConstant] Fix display of syntactically-invalid note for member function calls

2023-06-27 Thread Takuya Shimizu via cfe-commits

Author: Takuya Shimizu
Date: 2023-06-28T00:19:46+09:00
New Revision: f6be96aa4e5e282ea52041ad6fe5fff13a3df103

URL: 
https://github.com/llvm/llvm-project/commit/f6be96aa4e5e282ea52041ad6fe5fff13a3df103
DIFF: 
https://github.com/llvm/llvm-project/commit/f6be96aa4e5e282ea52041ad6fe5fff13a3df103.diff

LOG: [clang][ExprConstant] Fix display of syntactically-invalid note for member 
function calls

This patch makes the display of member function calls more true to the 
user-written code by making use of the syntactical structure of the function 
calls.
This patch also changes the display of conventional value-based printing from 
arrow operator to dot operator.
This avoids the syntactical invalidness in notes previously caused by the 
display of & operator
(lack of parentheses and reference of rvalue)

Fixes https://github.com/llvm/llvm-project/issues/57081

Reviewed By: cjdb
Differential Revision: https://reviews.llvm.org/D151720

Added: 
clang/test/SemaCXX/constexpr-frame-describe.cpp

Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/AST/ExprConstant.cpp
clang/test/AST/Interp/constexpr-nqueens.cpp
clang/test/AST/Interp/lambda.cpp
clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p9.cpp
clang/test/CXX/temp/temp.param/p8-cxx20.cpp
clang/test/SemaCXX/constant-expression-cxx11.cpp
clang/test/SemaCXX/cxx2a-consteval.cpp
clang/test/SemaCXX/deduced-return-type-cxx14.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 1ecf620f2a768..f00082fad24dd 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -371,6 +371,10 @@ Improvements to Clang's diagnostics
   ``#pragma clang|GCC diagnostic push|pop`` directive.
   (`#13920: `_)
 - Clang now does not try to analyze cast validity on variables with dependent 
alignment (`#63007: `_).
+- Clang constexpr evaluator now displays member function calls more precisely
+  by making use of the syntactical structure of function calls. This avoids 
display
+  of syntactically invalid codes in diagnostics.
+  (`#57081: `_)
 
 Bug Fixes in This Version
 -

diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 19d8e24fef63c..777245f86bdff 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -531,6 +531,9 @@ namespace {
 /// This - The binding for the this pointer in this call, if any.
 const LValue *This;
 
+/// CallExpr - The syntactical structure of member function calls
+const Expr *CallExpr;
+
 /// Information on how to find the arguments to this call. Our arguments
 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
 /// key and this value as the version.
@@ -584,7 +587,7 @@ namespace {
 
 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
const FunctionDecl *Callee, const LValue *This,
-   CallRef Arguments);
+   const Expr *CallExpr, CallRef Arguments);
 ~CallStackFrame();
 
 // Return the temporary for Key whose version number is Version.
@@ -978,7 +981,9 @@ namespace {
   CallStackDepth(0), NextCallIndex(1),
   StepsLeft(C.getLangOpts().ConstexprStepLimit),
   EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
-  BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()),
+  BottomFrame(*this, SourceLocation(), /*Callee=*/nullptr,
+  /*This=*/nullptr,
+  /*CallExpr=*/nullptr, CallRef()),
   EvaluatingDecl((const ValueDecl *)nullptr),
   EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
   HasFoldFailureDiagnostic(false), EvalMode(Mode) {}
@@ -1436,9 +1441,10 @@ void 
SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
 
 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
const FunctionDecl *Callee, const LValue *This,
-   CallRef Call)
+   const Expr *CallExpr, CallRef Call)
 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
-  Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
+  CallExpr(CallExpr), Arguments(Call), CallLoc(CallLoc),
+  Index(Info.NextCallIndex++) {
   Info.CurrentCall = this;
   ++Info.CallStackDepth;
 }
@@ -1918,12 +1924,29 @@ void CallStackFrame::describe(raw_ostream &Out) {
 Out << *Callee << '(';
 
   if (This && IsMemberCall) {
-APValue Val;
-This->moveInto(Val);
-Val.printPretty(Out, Info.Ctx,
-This->Designator.MostDerivedType);
-// FIXME: Add parens around Val if needed.
-Out << "->"

[PATCH] D151720: [clang][ExprConstant] Fix display of syntactically-invalid note for member function calls

2023-06-27 Thread Takuya Shimizu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
hazohelet marked an inline comment as done.
Closed by commit rGf6be96aa4e5e: [clang][ExprConstant] Fix display of 
syntactically-invalid note for member… (authored by hazohelet).

Changed prior to commit:
  https://reviews.llvm.org/D151720?vs=533964&id=534997#toc

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D151720/new/

https://reviews.llvm.org/D151720

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/AST/ExprConstant.cpp
  clang/test/AST/Interp/constexpr-nqueens.cpp
  clang/test/AST/Interp/lambda.cpp
  clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p9.cpp
  clang/test/CXX/temp/temp.param/p8-cxx20.cpp
  clang/test/SemaCXX/constant-expression-cxx11.cpp
  clang/test/SemaCXX/constexpr-frame-describe.cpp
  clang/test/SemaCXX/cxx2a-consteval.cpp
  clang/test/SemaCXX/deduced-return-type-cxx14.cpp

Index: clang/test/SemaCXX/deduced-return-type-cxx14.cpp
===
--- clang/test/SemaCXX/deduced-return-type-cxx14.cpp
+++ clang/test/SemaCXX/deduced-return-type-cxx14.cpp
@@ -296,7 +296,7 @@
   void f() {
 X().f();
 Y().f();
-constexpr int q = Y().f(); // expected-error {{must be initialized by a constant expression}} expected-note {{in call to '&Y()->f()'}}
+constexpr int q = Y().f(); // expected-error {{must be initialized by a constant expression}} expected-note {{in call to 'Y().f()'}}
   }
   struct NonLiteral { ~NonLiteral(); } nl; // cxx14-note {{user-provided destructor}}
   // cxx20_23-note@-1 {{'NonLiteral' is not literal because its destructor is not constexpr}}
Index: clang/test/SemaCXX/cxx2a-consteval.cpp
===
--- clang/test/SemaCXX/cxx2a-consteval.cpp
+++ clang/test/SemaCXX/cxx2a-consteval.cpp
@@ -840,13 +840,13 @@
   copy fail1{good0}; // expected-error {{call to consteval function 'defaulted_special_member_template::copy::copy' is not a constant expression}} \
  expected-note {{in call to 'copy(good0)'}}
   fail1 = good0;  // expected-error {{call to consteval function 'defaulted_special_member_template::copy::operator=' is not a constant expression}} \
- expected-note {{in call to '&fail1->operator=(good0)'}}
+ expected-note {{in call to 'fail1.operator=(good0)'}}
 
   move good1;
   move fail2{static_cast&&>(good1)}; // expected-error {{call to consteval function 'defaulted_special_member_template::move::move' is not a constant expression}} \
expected-note {{in call to 'move(good1)'}}
   fail2 = static_cast&&>(good1);  // expected-error {{call to consteval function 'defaulted_special_member_template::move::operator=' is not a constant expression}} \
-   expected-note {{in call to '&fail2->operator=(good1)'}}
+   expected-note {{in call to 'fail2.operator=(good1)'}}
 }
 } // namespace defaulted_special_member_template
 
Index: clang/test/SemaCXX/constexpr-frame-describe.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/constexpr-frame-describe.cpp
@@ -0,0 +1,60 @@
+// RUN: %clang_cc1 -std=c++20 -fsyntax-only -verify %s
+
+
+struct Foo {
+constexpr void zomg() const { (void)(1 / 0); } // expected-error {{constant expression}} \
+  expected-warning {{division by zero}} \
+  expected-note 2{{division by zero}}
+};
+
+struct S {
+constexpr S() {}
+constexpr bool operator==(const S&) const { // expected-error {{never produces a constant expression}}
+  return 1 / 0; // expected-warning {{division by zero}} \
+   expected-note 3{{division by zero}}
+}
+
+constexpr bool heh() const {
+auto F = new Foo();
+F->zomg(); // expected-note {{in call to 'F->zomg()'}}
+delete F;
+return false;
+}
+};
+
+constexpr S s;
+
+static_assert(s.heh()); // expected-error {{constant expression}} \
+   expected-note {{in call to 's.heh()'}}
+
+constexpr S s2;
+constexpr const S *sptr = &s;
+constexpr const S *sptr2 = &s2;
+static_assert(s == s2); // expected-error {{constant expression}} \
+   expected-note {{in call to 's.operator==(s2)'}}
+static_assert(*sptr == *sptr2); // expected-error {{constant expression}} \
+   expected-note {{in call to '*sptr.operator==(s2)'}}
+
+struct A {
+  constexpr int foo() { (void)(1/0); return 1;} // expected-error {{never produces a constant expression}} \
+   expected-warning {{division by zero}} \
+  

[PATCH] D153883: [Clang][OpenMP] Enable use of __kmpc_alloc_shared for VLAs defined in AMD GPU offloaded regions

2023-06-27 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 added a comment.

So this is implementing the `stacksave` using `__kmpc_alloc_shared` instead? It 
makes sense since the OpenMP standard expects sharing for the stack. I wonder 
how this interfaces with `-fopenmp-cuda-mode`.




Comment at: clang/lib/CodeGen/CGDecl.cpp:1603
+// deallocation call of __kmpc_free_shared() is emitted later.
+if (getLangOpts().OpenMP && getTarget().getTriple().isAMDGCN()) {
+  // Emit call to __kmpc_alloc_shared() instead of the alloca.

Does NVPTX handle this already? If not, is there a compelling reason to exclude 
NVPTX? Otherwise we should check if we are the OpenMP device.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153883/new/

https://reviews.llvm.org/D153883

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153883: [Clang][OpenMP] Enable use of __kmpc_alloc_shared for VLAs defined in AMD GPU offloaded regions

2023-06-27 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added a comment.

Add the runtime test?




Comment at: clang/lib/CodeGen/CGDecl.cpp:587
+std::pair AddrSizePair;
+KmpcAllocFree(std::pair AddrSizePair)
+: AddrSizePair(AddrSizePair) {}

Better to pass it as const reference



Comment at: clang/lib/CodeGen/CGDecl.cpp:589
+: AddrSizePair(AddrSizePair) {}
+void Emit(CodeGenFunction &CGF, Flags flags) override {
+  CGOpenMPRuntimeGPU &RT =

Wrong param name, use Camel



Comment at: clang/lib/CodeGen/CGDecl.cpp:1603
+// deallocation call of __kmpc_free_shared() is emitted later.
+if (getLangOpts().OpenMP && getTarget().getTriple().isAMDGCN()) {
+  // Emit call to __kmpc_alloc_shared() instead of the alloca.

OpenMPIsDevice?



Comment at: clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp:1085
   }
-  for (const auto *VD : I->getSecond().EscapedVariableLengthDecls) {
-// Use actual memory size of the VLA object including the padding

Why this code is removed?



Comment at: clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp:1112
+
+  return std::pair({VoidPtr, Size});
+}

Use `std::make_pair(VoidPtr, Size)`.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153883/new/

https://reviews.llvm.org/D153883

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D105759: Implement P2361 Unevaluated string literals

2023-06-27 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added inline comments.



Comment at: clang/lib/Sema/SemaDeclAttr.cpp:878-879
 
-  if (!isIntOrBool(AL.getArgAsExpr(0))) {
+  Expr *First = AL.getArgAsExpr(0);
+  if (isa(First) || !isIntOrBool(First)) {
 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)

aaron.ballman wrote:
> cor3ntin wrote:
> > aaron.ballman wrote:
> > > Test coverage for these changes?
> > There is one somewhere, I don;t remember where, The reason we need to do 
> > that is that Unevaluated StringLiterals don''t have types
> Let's try to track that down, but... an unevaluated string literal still has 
> a type, surely? It'd be `const char[]` for C++?
It doesn't because it doesn't exist past phase 6.
It's not unevaluated as in decltype, it's more unevaluated as it's a weird 
token that never participate in the program, the same way a pragma or an 
attribute don't have a type. 
Note that we can revert that change if we do the whole tablegen thing

The relevant test is in test/SemaCXX/warn-thread-safety-parsing.cpp, L17


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D105759/new/

https://reviews.llvm.org/D105759

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D105759: Implement P2361 Unevaluated string literals

2023-06-27 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin updated this revision to Diff 534999.
cor3ntin added a comment.

Add tests for pascal strings (which are not a thing in C++ apparently)


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D105759/new/

https://reviews.llvm.org/D105759

Files:
  clang-tools-extra/test/clang-tidy/checkers/modernize/unary-static-assert.cpp
  clang/include/clang/AST/Expr.h
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/DiagnosticLexKinds.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Lex/LiteralSupport.h
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/Expr.cpp
  clang/lib/Lex/LiteralSupport.cpp
  clang/lib/Lex/PPMacroExpansion.cpp
  clang/lib/Lex/Pragma.cpp
  clang/lib/Parse/ParseDecl.cpp
  clang/lib/Parse/ParseDeclCXX.cpp
  clang/lib/Parse/ParseExpr.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaExprCXX.cpp
  clang/lib/Sema/SemaInit.cpp
  clang/test/CXX/dcl.dcl/dcl.link/p2.cpp
  clang/test/CXX/dcl.dcl/p4-0x.cpp
  clang/test/FixIt/fixit-static-assert.cpp
  clang/test/Parser/cxx0x-attributes.cpp
  clang/test/SemaCXX/static-assert.cpp
  clang/test/SemaCXX/warn-thread-safety-parsing.cpp

Index: clang/test/SemaCXX/warn-thread-safety-parsing.cpp
===
--- clang/test/SemaCXX/warn-thread-safety-parsing.cpp
+++ clang/test/SemaCXX/warn-thread-safety-parsing.cpp
@@ -309,7 +309,7 @@
 
 int gb_var_arg GUARDED_BY(mu1);
 
-int gb_non_ascii GUARDED_BY(L"wide"); // expected-warning {{ignoring 'guarded_by' attribute because its argument is invalid}}
+int gb_non_ascii GUARDED_BY(L"wide"); // expected-error {{an unevaluated string literal cannot have an encoding prefix}}
 
 int gb_var_args __attribute__((guarded_by(mu1, mu2))); // \
   // expected-error {{'guarded_by' attribute takes one argument}}
Index: clang/test/SemaCXX/static-assert.cpp
===
--- clang/test/SemaCXX/static-assert.cpp
+++ clang/test/SemaCXX/static-assert.cpp
@@ -29,13 +29,23 @@
 S s1; // expected-note {{in instantiation of template class 'S' requested here}}
 S s2;
 
-static_assert(false, L"\x"); // expected-error {{static assertion failed: L"\x"}}
-static_assert(false, u"\U000317FF"); // expected-error {{static assertion failed: u"\U000317FF"}}
-
-static_assert(false, u8"Ω"); // expected-error {{static assertion failed: u8"\316\251"}}
-static_assert(false, L"\u1234"); // expected-error {{static assertion failed: L"\x1234"}}
-static_assert(false, L"\x1ff" "0\x123" "fx\xf" "goop"); // expected-error {{static assertion failed: L"\x1FF""0\x123""fx\xFgoop"}}
-
+static_assert(false, L"\x"); // expected-error {{an unevaluated string literal cannot have an encoding prefix}} \
+ // expected-error {{invalid escape sequence '\x' in an unevaluated string literal}}
+static_assert(false, u"\U000317FF"); // expected-error {{an unevaluated string literal cannot have an encoding prefix}}
+// FIXME: render this as u8"\u03A9"
+static_assert(false, u8"Ω"); // expected-error {{an unevaluated string literal cannot have an encoding prefix}}
+static_assert(false, L"\u1234"); // expected-error {{an unevaluated string literal cannot have an encoding prefix}}
+static_assert(false, L"\x1ff"// expected-error {{an unevaluated string literal cannot have an encoding prefix}} \
+ // expected-error {{invalid escape sequence '\x1ff' in an unevaluated string literal}}
+ "0\x123"// expected-error {{invalid escape sequence '\x123' in an unevaluated string literal}}
+ "fx\xf" // expected-error {{invalid escape sequence '\xf' in an unevaluated string literal}}
+ "goop");
+
+static_assert(false, "\'\"\?\\\a\b\f\n\r\t\v"); // expected-error {{'"?\}}
+static_assert(true, "\xFF"); // expected-error {{invalid escape sequence '\xFF' in an unevaluated string literal}}
+static_assert(true, "\123"); // expected-error {{invalid escape sequence '\123' in an unevaluated string literal}}
+static_assert(true, "\pOh no, a Pascal string!"); // expected-warning {{unknown escape sequence '\p'}} \
+  // expected-error {{invalid escape sequence '\p' in an unevaluated string literal}}
 static_assert(false, R"(a
 \tb
 c
Index: clang/test/Parser/cxx0x-attributes.cpp
===
--- clang/test/Parser/cxx0x-attributes.cpp
+++ clang/test/Parser/cxx0x-attributes.cpp
@@ -445,3 +445,8 @@
   ) {
   }
 };
+
+namespace P2361 {
+[[deprecated(L"abc")]] void a(); // expected-error{{an unevaluated string literal cannot have an encoding prefix}}
+[[nodiscard("\123")]] int b(); // expected-error{{invalid escape sequence '\123' in an u

[PATCH] D153885: [Clang][Driver] Change missing multilib error to warning

2023-06-27 Thread Michael Platings via Phabricator via cfe-commits
michaelplatings created this revision.
michaelplatings added a reviewer: simon_tatham.
Herald added a project: All.
michaelplatings requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay.
Herald added a project: clang.

The error could be awkward to work around when experimenting with flags
that didn't have a matching multilib. It also broke many tests when
multilib.yaml was present in the build directory.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D153885

Files:
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Basic/DiagnosticGroups.td
  clang/lib/Driver/ToolChains/BareMetal.cpp
  clang/test/Driver/baremetal-multilib.yaml


Index: clang/test/Driver/baremetal-multilib.yaml
===
--- clang/test/Driver/baremetal-multilib.yaml
+++ clang/test/Driver/baremetal-multilib.yaml
@@ -23,7 +23,7 @@
 # RUN: %T/baremetal_multilib/bin/clang -no-canonical-prefixes -x c++ %s -### 
-o %t.out 2>&1 \
 # RUN: --target=thumbv7em-none-eabi -mfpu=fpv4-sp-d16 --sysroot= \
 # RUN:   | FileCheck --check-prefix=CHECK-NO-MATCH %s
-# CHECK-NO-MATCH: error: no multilib found matching flags:
+# CHECK-NO-MATCH: warning: no multilib found matching flags:
 # CHECK-NO-MATCH-SAME: --target=thumbv7em-none-unknown-eabi
 # CHECK-NO-MATCH: note: available multilibs are:
 # CHECK-NO-MATCH: --target=thumbv6m-none-unknown-eabi -mfpu=none
Index: clang/lib/Driver/ToolChains/BareMetal.cpp
===
--- clang/lib/Driver/ToolChains/BareMetal.cpp
+++ clang/lib/Driver/ToolChains/BareMetal.cpp
@@ -175,7 +175,7 @@
   Result.Multilibs = ErrorOrMultilibSet.get();
   if (Result.Multilibs.select(Flags, Result.SelectedMultilibs))
 return;
-  D.Diag(clang::diag::err_drv_no_matching_multilib) << llvm::join(Flags, " ");
+  D.Diag(clang::diag::warn_drv_no_matching_multilib) << llvm::join(Flags, " ");
   std::stringstream ss;
   for (const Multilib &Multilib : Result.Multilibs)
 ss << "\n" << llvm::join(Multilib.flags(), " ");
Index: clang/include/clang/Basic/DiagnosticGroups.td
===
--- clang/include/clang/Basic/DiagnosticGroups.td
+++ clang/include/clang/Basic/DiagnosticGroups.td
@@ -1435,3 +1435,6 @@
 
 // Warnings and fixes to support the "safe buffers" programming model.
 def UnsafeBufferUsage : DiagGroup<"unsafe-buffer-usage">;
+
+// Warnings for multilib
+def MissingMultilib : DiagGroup<"missing-multilib">;
Index: clang/include/clang/Basic/DiagnosticDriverKinds.td
===
--- clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -737,8 +737,9 @@
 def err_drv_expand_response_file : Error<
   "failed to expand response file: %0">;
 
-def err_drv_no_matching_multilib : Error<
-  "no multilib found matching flags: %0">;
+def warn_drv_no_matching_multilib : Warning<
+  "no multilib found matching flags: %0">,
+  InGroup;
 def note_drv_available_multilibs : Note<
   "available multilibs are:%0">;
 }


Index: clang/test/Driver/baremetal-multilib.yaml
===
--- clang/test/Driver/baremetal-multilib.yaml
+++ clang/test/Driver/baremetal-multilib.yaml
@@ -23,7 +23,7 @@
 # RUN: %T/baremetal_multilib/bin/clang -no-canonical-prefixes -x c++ %s -### -o %t.out 2>&1 \
 # RUN: --target=thumbv7em-none-eabi -mfpu=fpv4-sp-d16 --sysroot= \
 # RUN:   | FileCheck --check-prefix=CHECK-NO-MATCH %s
-# CHECK-NO-MATCH: error: no multilib found matching flags:
+# CHECK-NO-MATCH: warning: no multilib found matching flags:
 # CHECK-NO-MATCH-SAME: --target=thumbv7em-none-unknown-eabi
 # CHECK-NO-MATCH: note: available multilibs are:
 # CHECK-NO-MATCH: --target=thumbv6m-none-unknown-eabi -mfpu=none
Index: clang/lib/Driver/ToolChains/BareMetal.cpp
===
--- clang/lib/Driver/ToolChains/BareMetal.cpp
+++ clang/lib/Driver/ToolChains/BareMetal.cpp
@@ -175,7 +175,7 @@
   Result.Multilibs = ErrorOrMultilibSet.get();
   if (Result.Multilibs.select(Flags, Result.SelectedMultilibs))
 return;
-  D.Diag(clang::diag::err_drv_no_matching_multilib) << llvm::join(Flags, " ");
+  D.Diag(clang::diag::warn_drv_no_matching_multilib) << llvm::join(Flags, " ");
   std::stringstream ss;
   for (const Multilib &Multilib : Result.Multilibs)
 ss << "\n" << llvm::join(Multilib.flags(), " ");
Index: clang/include/clang/Basic/DiagnosticGroups.td
===
--- clang/include/clang/Basic/DiagnosticGroups.td
+++ clang/include/clang/Basic/DiagnosticGroups.td
@@ -1435,3 +1435,6 @@
 
 // Warnings and fixes to support the "safe buffers" programming model.
 def UnsafeBufferUsage : DiagGroup<"unsafe-buffer-usage">;
+
+// Warnings for multilib
+def MissingMultilib 

[PATCH] D152263: [clang][CFG] Add support for partitioning CFG into intervals.

2023-06-27 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 535002.
ymandel added a comment.

Respond to comments


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D152263/new/

https://reviews.llvm.org/D152263

Files:
  clang/include/clang/Analysis/Analyses/IntervalPartition.h
  clang/lib/Analysis/CMakeLists.txt
  clang/lib/Analysis/IntervalPartition.cpp
  clang/unittests/Analysis/CMakeLists.txt
  clang/unittests/Analysis/IntervalPartitionTest.cpp

Index: clang/unittests/Analysis/IntervalPartitionTest.cpp
===
--- /dev/null
+++ clang/unittests/Analysis/IntervalPartitionTest.cpp
@@ -0,0 +1,164 @@
+//===- unittests/Analysis/IntervalPartitionTest.cpp ---===//
+//
+// 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 "clang/Analysis/Analyses/IntervalPartition.h"
+#include "CFGBuildResult.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace analysis {
+namespace {
+
+TEST(BuildInterval, PartitionSimpleOneInterval) {
+
+  const char *Code = R"(void f() {
+  int x = 3;
+  int y = 7;
+  x = y + x;
+})";
+  BuildResult Result = BuildCFG(Code);
+  EXPECT_EQ(BuildResult::BuiltCFG, Result.getStatus());
+
+  CFG *cfg = Result.getCFG();
+
+  // Basic correctness checks.
+  ASSERT_EQ(cfg->size(), 3u);
+
+  auto &EntryBlock = cfg->getEntry();
+
+  CFGInterval I = buildInterval(*cfg, EntryBlock);
+  EXPECT_EQ(I.Blocks.size(), 3u);
+}
+
+TEST(BuildInterval, PartitionIfThenOneInterval) {
+
+  const char *Code = R"(void f() {
+  int x = 3;
+  if (x > 3)
+x = 2;
+  else
+x = 7;
+  x = x + x;
+})";
+  BuildResult Result = BuildCFG(Code);
+  EXPECT_EQ(BuildResult::BuiltCFG, Result.getStatus());
+
+  CFG *cfg = Result.getCFG();
+
+  // Basic correctness checks.
+  ASSERT_EQ(cfg->size(), 6u);
+
+  auto &EntryBlock = cfg->getEntry();
+
+  CFGInterval I = buildInterval(*cfg, EntryBlock);
+  EXPECT_EQ(I.Blocks.size(), 6u);
+}
+
+using ::testing::UnorderedElementsAre;
+
+TEST(BuildInterval, PartitionWhileMultipleIntervals) {
+
+  const char *Code = R"(void f() {
+  int x = 3;
+  while (x >= 3)
+--x;
+  x = x + x;
+})";
+  BuildResult Result = BuildCFG(Code);
+  ASSERT_EQ(BuildResult::BuiltCFG, Result.getStatus());
+
+  CFG *cfg = Result.getCFG();
+  ASSERT_EQ(cfg->size(), 7u);
+
+  auto *EntryBlock = &cfg->getEntry();
+  CFGBlock *InitXBlock = *EntryBlock->succ_begin();
+  CFGBlock *LoopHeadBlock = *InitXBlock->succ_begin();
+
+  CFGInterval I1 = buildInterval(*cfg, *EntryBlock);
+  EXPECT_THAT(I1.Blocks, UnorderedElementsAre(EntryBlock, InitXBlock));
+
+  CFGInterval I2 = buildInterval(*cfg, *LoopHeadBlock);
+  EXPECT_EQ(I2.Blocks.size(), 5u);
+}
+
+TEST(PartitionIntoIntervals, PartitionIfThenOneInterval) {
+  const char *Code = R"(void f() {
+  int x = 3;
+  if (x > 3)
+x = 2;
+  else
+x = 7;
+  x = x + x;
+})";
+  BuildResult Result = BuildCFG(Code);
+  ASSERT_EQ(BuildResult::BuiltCFG, Result.getStatus());
+
+  CFG *cfg = Result.getCFG();
+  ASSERT_EQ(cfg->size(), 6u);
+
+  auto Intervals = partitionIntoIntervals(*cfg);
+  EXPECT_EQ(Intervals.size(), 1u);
+}
+
+TEST(PartitionIntoIntervals, PartitionWhileTwoIntervals) {
+  const char *Code = R"(void f() {
+  int x = 3;
+  while (x >= 3)
+--x;
+  x = x + x;
+})";
+  BuildResult Result = BuildCFG(Code);
+  ASSERT_EQ(BuildResult::BuiltCFG, Result.getStatus());
+
+  CFG *cfg = Result.getCFG();
+  ASSERT_EQ(cfg->size(), 7u);
+
+  auto Intervals = partitionIntoIntervals(*cfg);
+  EXPECT_EQ(Intervals.size(), 2u);
+}
+
+TEST(PartitionIntoIntervals, PartitionNestedWhileThreeIntervals) {
+  const char *Code = R"(void f() {
+  int x = 3;
+  while (x >= 3) {
+--x;
+int y = x;
+while (y > 0) --y;
+  }
+  x = x + x;
+})";
+  BuildResult Result = BuildCFG(Code);
+  ASSERT_EQ(BuildResult::BuiltCFG, Result.getStatus());
+
+  CFG *cfg = 

[PATCH] D153885: [Clang][Driver] Change missing multilib error to warning

2023-06-27 Thread Simon Tatham via Phabricator via cfe-commits
simon_tatham added inline comments.



Comment at: clang/include/clang/Basic/DiagnosticDriverKinds.td:740
 
-def err_drv_no_matching_multilib : Error<
-  "no multilib found matching flags: %0">;
+def warn_drv_no_matching_multilib : Warning<
+  "no multilib found matching flags: %0">,

Tiny clarity nit: any chance of renaming this identifier to 
`warn_drv_missing_multilib`, while we're renaming it anyway? Then the 
command-line option to control the warning matches the identifier inside the 
code, and makes it easier to guess the spelling of either one if you had the 
other one already in mind.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153885/new/

https://reviews.llvm.org/D153885

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153883: [Clang][OpenMP] Enable use of __kmpc_alloc_shared for VLAs defined in AMD GPU offloaded regions

2023-06-27 Thread Gheorghe-Teodor Bercea via Phabricator via cfe-commits
doru1004 added inline comments.



Comment at: clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp:1085
   }
-  for (const auto *VD : I->getSecond().EscapedVariableLengthDecls) {
-// Use actual memory size of the VLA object including the padding

ABataev wrote:
> Why this code is removed?
I could not understand why this code is here in the first place since it 
doesn't seem that it could ever work correctly (and it doesn't seem to be 
covered by any existing tests). Maybe I'm wrong but that was my understanding 
of it. So what seems to happen is that this code attempts to emit a 
kmpc_alloc_shared before the actual size calculation is emitted. So if the VLA 
size is something that the user defines such as `int N = 10;` then that code 
will not have been emitted at this point. When the expression computing the 
size of the VLA uses `N`, the code that is deleted here would just fail to find 
the VLA size in the attempt to emit the kmpc_alloc_shared. The emission of the 
VLA as kmpc_alloc_shared needs to happen after the expression of the size is 
emitted.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153883/new/

https://reviews.llvm.org/D153883

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153883: [Clang][OpenMP] Enable use of __kmpc_alloc_shared for VLAs defined in AMD GPU offloaded regions

2023-06-27 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 added inline comments.



Comment at: clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp:1085
   }
-  for (const auto *VD : I->getSecond().EscapedVariableLengthDecls) {
-// Use actual memory size of the VLA object including the padding

doru1004 wrote:
> ABataev wrote:
> > Why this code is removed?
> I could not understand why this code is here in the first place since it 
> doesn't seem that it could ever work correctly (and it doesn't seem to be 
> covered by any existing tests). Maybe I'm wrong but that was my understanding 
> of it. So what seems to happen is that this code attempts to emit a 
> kmpc_alloc_shared before the actual size calculation is emitted. So if the 
> VLA size is something that the user defines such as `int N = 10;` then that 
> code will not have been emitted at this point. When the expression computing 
> the size of the VLA uses `N`, the code that is deleted here would just fail 
> to find the VLA size in the attempt to emit the kmpc_alloc_shared. The 
> emission of the VLA as kmpc_alloc_shared needs to happen after the expression 
> of the size is emitted.
I'm pretty sure I was the one that wrote this code, and at the time I don't 
recall it really working. I remember there was something else that expected 
this to be here, but for what utility I do not recall. VLAs were never tested 
or used.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153883/new/

https://reviews.llvm.org/D153883

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D152263: [clang][CFG] Add support for partitioning CFG into intervals.

2023-06-27 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel marked 3 inline comments as done.
ymandel added inline comments.



Comment at: clang/lib/Analysis/IntervalPartition.cpp:26
+
+  std::queue Worklist;
+  for (const CFGBlock *S : Header.succs())

xazax.hun wrote:
> ymandel wrote:
> > xazax.hun wrote:
> > > Is it possible we end up adding the same node to the queue multiple 
> > > times? Is that desirable or do we want to make sure we only have each 
> > > node at most once?
> > Added an answer in comments, but repeating here in case you want to discuss 
> > further:
> > 
> >   // The worklist *may* contain duplicates. We guard against this 
> > possibility by
> >   // checking each popped element for completion (that is, presence in
> >   // `Partitioned`). We choose this approach over using a set because the 
> > queue
> >   // allows us to flexibly insert and delete elements while iterating 
> > through
> >   // the list. A set would require two separate phases for iterating and
> >   // mutation.
> I see, thanks! This addresses my concerns. I think in some cases we use a 
> bitset with the blocks' ids to more efficiently track things like that.
Thanks. I experimented with that and added some use of bitsets here 
(`llvm::BitVector`). I didn't go all out though since the CFG doesn't provide a 
reverse mapping from block ID to block pointer, so I still used `SmallDenseSet` 
where we'll need the block pointers.



Comment at: clang/lib/Analysis/IntervalPartition.cpp:46-47
+
+// Check whether all predecessors are in the interval, in which case `B`
+// is included as well.
+bool AllInInterval = true;

xazax.hun wrote:
> ymandel wrote:
> > xazax.hun wrote:
> > > I wonder if this approach is correct. Consider the following scenario:
> > > 
> > > ```
> > >A
> > >   / \
> > >  B   C
> > >  |   |
> > >  |   D
> > >   \ /
> > >E
> > > ```
> > > 
> > > In the BFS, we might visit: ABCED. Since we visit `E` before `D`, we 
> > > might not recognize that `E` is part of the interval. Do I miss something?
> > > I wonder if this approach is correct. Consider the following scenario:
> > > 
> > > ```
> > >A
> > >   / \
> > >  B   C
> > >  |   |
> > >  |   D
> > >   \ /
> > >E
> > > ```
> > > 
> > > In the BFS, we might visit: ABCED. Since we visit `E` before `D`, we 
> > > might not recognize that `E` is part of the interval. Do I miss something?
> > 
> > When we add `D` to the interval, we'll push `E` onto the queue again (lines 
> > 58-59). The second time that `E` is considered it will have both successors 
> > in the interval and will be added as well.
> Ah, I see, makse sense, thanks! This also makes me wonder, would this 
> algorithm be more efficient if we used RPO (in case we can use that without 
> recalculating the order)? :D But we do not need to benchmark this for the 
> first version. 
I suspect it would be though I think that any traversal based ordering vs. 
random will still be pretty good, especially since the queue already pushes us 
towards breadth-first. I didn't use RPO because I figured that the cost of 
computing it would be greater than any potential benefit.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D152263/new/

https://reviews.llvm.org/D152263

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153690: [clang][Sema] Remove dead diagnostic for loss of __unaligned qualifier

2023-06-27 Thread Takuya Shimizu via Phabricator via cfe-commits
hazohelet updated this revision to Diff 535010.
hazohelet added a comment.

Added release note and test because this change is not NFC


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153690/new/

https://reviews.llvm.org/D153690

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaOverload.cpp
  clang/test/SemaCXX/MicrosoftExtensions.cpp


Index: clang/test/SemaCXX/MicrosoftExtensions.cpp
===
--- clang/test/SemaCXX/MicrosoftExtensions.cpp
+++ clang/test/SemaCXX/MicrosoftExtensions.cpp
@@ -68,19 +68,23 @@
 void (aligned_type4::*__unaligned p4_aligned_type4)();
 
 // Check that __unaligned qualifier can be used for overloading
-void foo_unaligned(int *arg) {}
-void foo_unaligned(__unaligned int *arg) {}
+void foo_unaligned(int *arg) {} // expected-note {{not viable: 1st argument 
('const __unaligned int *') would lose const qualifier}}
+void foo_unaligned(__unaligned int *arg) {} // expected-note {{not viable: 1st 
argument ('const __unaligned int *') would lose const qualifier}}
 void foo_unaligned(int arg) {} // expected-note {{previous definition is here}}
-void foo_unaligned(__unaligned int arg) {} // expected-error {{redefinition of 
'foo_unaligned'}}
+void foo_unaligned(__unaligned int arg) {} // expected-error {{redefinition of 
'foo_unaligned'}} \
+   // expected-note {{not viable: no 
known conversion from 'const __unaligned int *' to '__unaligned int'}}
 class A_unaligned {};
 class B_unaligned : public A_unaligned {};
-int foo_unaligned(__unaligned A_unaligned *arg) { return 0; }
-void *foo_unaligned(B_unaligned *arg) { return 0; }
+int foo_unaligned(__unaligned A_unaligned *arg) { return 0; } // expected-note 
{{not viable: no known conversion from 'const __unaligned int *' to 
'__unaligned A_unaligned *'}}
+void *foo_unaligned(B_unaligned *arg) { return 0; } // expected-note {{not 
viable: no known conversion from 'const __unaligned int *' to 'B_unaligned *'}}
 
 void test_unaligned() {
   int *p1 = 0;
   foo_unaligned(p1);
 
+  const __unaligned int *const_p1 = 0;
+  foo_unaligned(const_p1); // expected-error {{no matching function for call 
to 'foo_unaligned'}}
+
   __unaligned int *p2 = 0;
   foo_unaligned(p2);
 
Index: clang/lib/Sema/SemaOverload.cpp
===
--- clang/lib/Sema/SemaOverload.cpp
+++ clang/lib/Sema/SemaOverload.cpp
@@ -10821,15 +10821,6 @@
   return;
 }
 
-if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
-  S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
-  << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << 
FnDesc
-  << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
-  << FromQs.hasUnaligned() << I + 1;
-  MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
-  return;
-}
-
 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
 assert(CVR && "expected qualifiers mismatch");
 
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -4700,9 +4700,6 @@
 "%select{const|restrict|const and restrict|volatile|const and volatile|"
 "volatile and restrict|const, volatile, and restrict}4 qualifier"
 "%select{||s||s|s|s}4">;
-def note_ovl_candidate_bad_unaligned : Note<
-"candidate %sub{select_ovl_candidate_kind}0,1,2 not viable: "
-"%ordinal5 argument (%3) would lose __unaligned qualifier">;
 def note_ovl_candidate_bad_base_to_derived_conv : Note<
 "candidate %sub{select_ovl_candidate_kind}0,1,2 not viable: "
 "cannot %select{convert from|convert from|bind}3 "
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -375,6 +375,8 @@
   by making use of the syntactical structure of function calls. This avoids 
display
   of syntactically invalid codes in diagnostics.
   (`#57081: `_)
+- Clang no longer emits inappropriate notes about the loss of ``__unaligned`` 
qualifier
+  on overload resolution, when the actual reason for the failure is loss of 
other qualifiers.
 
 Bug Fixes in This Version
 -


Index: clang/test/SemaCXX/MicrosoftExtensions.cpp
===
--- clang/test/SemaCXX/MicrosoftExtensions.cpp
+++ clang/test/SemaCXX/MicrosoftExtensions.cpp
@@ -68,19 +68,23 @@
 void (aligned_type4::*__unaligned p4_aligned_type4)();
 
 // Check that __unaligned qualifier can be used for overloading
-void foo_unaligned(int *arg) {}
-void foo_unaligned(__unaligned int *arg) {}
+void foo_unaligned(int *a

[PATCH] D153883: [Clang][OpenMP] Enable use of __kmpc_alloc_shared for VLAs defined in AMD GPU offloaded regions

2023-06-27 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp:1085
   }
-  for (const auto *VD : I->getSecond().EscapedVariableLengthDecls) {
-// Use actual memory size of the VLA object including the padding

jhuber6 wrote:
> doru1004 wrote:
> > ABataev wrote:
> > > Why this code is removed?
> > I could not understand why this code is here in the first place since it 
> > doesn't seem that it could ever work correctly (and it doesn't seem to be 
> > covered by any existing tests). Maybe I'm wrong but that was my 
> > understanding of it. So what seems to happen is that this code attempts to 
> > emit a kmpc_alloc_shared before the actual size calculation is emitted. So 
> > if the VLA size is something that the user defines such as `int N = 10;` 
> > then that code will not have been emitted at this point. When the 
> > expression computing the size of the VLA uses `N`, the code that is deleted 
> > here would just fail to find the VLA size in the attempt to emit the 
> > kmpc_alloc_shared. The emission of the VLA as kmpc_alloc_shared needs to 
> > happen after the expression of the size is emitted.
> I'm pretty sure I was the one that wrote this code, and at the time I don't 
> recall it really working. I remember there was something else that expected 
> this to be here, but for what utility I do not recall. VLAs were never tested 
> or used.
They are tested, check 
test/OpenMP/nvptx_target_teams_distribute_parallel_for_codegen.cpp for example, 
where it captures VLA implicitly. I assume this should not be AMDGCN specific.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153883/new/

https://reviews.llvm.org/D153883

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D152263: [clang][CFG] Add support for partitioning CFG into intervals.

2023-06-27 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun accepted this revision.
xazax.hun added a comment.

Thanks!


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D152263/new/

https://reviews.llvm.org/D152263

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153889: [analyzer][NFC] Fix dangling StringRef in barely used code

2023-06-27 Thread Donát Nagy via Phabricator via cfe-commits
donat.nagy created this revision.
donat.nagy added reviewers: Szelethus, gamesh411, steakhal.
Herald added subscribers: manas, ASDenysPetrov, dkrupp, mikhail.ramalho, 
a.sidorin, szepet, baloghadamsoftware, xazax.hun.
Herald added a reviewer: NoQ.
Herald added a project: All.
donat.nagy requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

`CheckerContext::getNoteTag` has a shorthand version that takes a plain 
'`StringRef Note`' instead of a lambda that calculates the note.

The old implementation of this method was incorrect because it created a lambda 
that captured the StringRef, which was dereferenced much later, when the 
NoteTags were visited.

In the current codebase this does not cause errors because this method is 
called only once, and there the `Note` argument is a string literal that 
remains valid. However, I tried to use this method in a checker that I was 
prototyping, and there it printed random memory junk (instead of the message 
that I composed in a local variable).


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D153889

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h


Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
@@ -316,8 +316,8 @@
   ///bug path significantly shorter.
   const NoteTag *getNoteTag(StringRef Note, bool IsPrunable = false) {
 return getNoteTag(
-[Note](BugReporterContext &,
-   PathSensitiveBugReport &) { return std::string(Note); },
+[Note = std::string(Note)](BugReporterContext &,
+   PathSensitiveBugReport &) { return Note; },
 IsPrunable);
   }
 


Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
@@ -316,8 +316,8 @@
   ///bug path significantly shorter.
   const NoteTag *getNoteTag(StringRef Note, bool IsPrunable = false) {
 return getNoteTag(
-[Note](BugReporterContext &,
-   PathSensitiveBugReport &) { return std::string(Note); },
+[Note = std::string(Note)](BugReporterContext &,
+   PathSensitiveBugReport &) { return Note; },
 IsPrunable);
   }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153890: [clang] Fix checking the equality comparator of base classes in __is_trivially_equality_comparable

2023-06-27 Thread Nikolas Klauser via Phabricator via cfe-commits
philnik created this revision.
philnik added reviewers: aaron.ballman, cor3ntin.
Herald added a project: All.
philnik requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Fixes #63192


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D153890

Files:
  clang/lib/AST/Type.cpp
  clang/test/SemaCXX/type-traits.cpp


Index: clang/test/SemaCXX/type-traits.cpp
===
--- clang/test/SemaCXX/type-traits.cpp
+++ clang/test/SemaCXX/type-traits.cpp
@@ -3264,6 +3264,21 @@
 };
 
static_assert(!__is_trivially_equality_comparable(NotTriviallyEqualityComparableHasReferenceMember));
 
+struct NotTriviallyEqualityComparableNonTriviallyComparableBaseBase {
+  int i;
+
+  bool operator==(const 
NotTriviallyEqualityComparableNonTriviallyComparableBaseBase&) const {
+return true;
+  }
+};
+
+struct NotTriviallyEqualityComparableNonTriviallyComparableBase : 
NotTriviallyEqualityComparableNonTriviallyComparableBaseBase {
+  int i;
+
+  bool operator==(const 
NotTriviallyEqualityComparableNonTriviallyComparableBase&) const = default;
+};
+static_assert(!__is_trivially_equality_comparable(NotTriviallyEqualityComparableNonTriviallyComparableBase));
+
 enum E {
   a,
   b
Index: clang/lib/AST/Type.cpp
===
--- clang/lib/AST/Type.cpp
+++ clang/lib/AST/Type.cpp
@@ -2667,7 +2667,7 @@
   return llvm::all_of(Decl->bases(),
   [](const CXXBaseSpecifier &BS) {
 if (const auto *RD = 
BS.getType()->getAsCXXRecordDecl())
-  HasNonDeletedDefaultedEqualityComparison(RD);
+  return HasNonDeletedDefaultedEqualityComparison(RD);
 return true;
   }) &&
  llvm::all_of(Decl->fields(), [](const FieldDecl *FD) {


Index: clang/test/SemaCXX/type-traits.cpp
===
--- clang/test/SemaCXX/type-traits.cpp
+++ clang/test/SemaCXX/type-traits.cpp
@@ -3264,6 +3264,21 @@
 };
 static_assert(!__is_trivially_equality_comparable(NotTriviallyEqualityComparableHasReferenceMember));
 
+struct NotTriviallyEqualityComparableNonTriviallyComparableBaseBase {
+  int i;
+
+  bool operator==(const NotTriviallyEqualityComparableNonTriviallyComparableBaseBase&) const {
+return true;
+  }
+};
+
+struct NotTriviallyEqualityComparableNonTriviallyComparableBase : NotTriviallyEqualityComparableNonTriviallyComparableBaseBase {
+  int i;
+
+  bool operator==(const NotTriviallyEqualityComparableNonTriviallyComparableBase&) const = default;
+};
+static_assert(!__is_trivially_equality_comparable(NotTriviallyEqualityComparableNonTriviallyComparableBase));
+
 enum E {
   a,
   b
Index: clang/lib/AST/Type.cpp
===
--- clang/lib/AST/Type.cpp
+++ clang/lib/AST/Type.cpp
@@ -2667,7 +2667,7 @@
   return llvm::all_of(Decl->bases(),
   [](const CXXBaseSpecifier &BS) {
 if (const auto *RD = BS.getType()->getAsCXXRecordDecl())
-  HasNonDeletedDefaultedEqualityComparison(RD);
+  return HasNonDeletedDefaultedEqualityComparison(RD);
 return true;
   }) &&
  llvm::all_of(Decl->fields(), [](const FieldDecl *FD) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153860: [clang-tidy] Fix modernize-use-std-print check when return value used

2023-06-27 Thread Mike Crowe via Phabricator via cfe-commits
mikecrowe marked an inline comment as done.
mikecrowe added inline comments.



Comment at: clang-tools-extra/clang-tidy/modernize/UseStdPrintCheck.cpp:73-95
+static clang::ast_matchers::StatementMatcher
+unusedReturnValue(clang::ast_matchers::StatementMatcher MatchedCallExpr) {
+  auto UnusedInCompoundStmt =
+  compoundStmt(forEach(MatchedCallExpr),
+   // The checker can't currently differentiate between the
+   // return statement and other statements inside GNU 
statement
+   // expressions, so disable the checker inside them to avoid

PiotrZSL wrote:
> NOTE: Personally I do not thing that this is right way. Instead of using 
> "inclusion" matcher, better would be to use elimination.
> like:
> ```callExpr(unless(hasParent(anyOf(varDecl(), callExpr(), ifStmt(), ...```.
> 
> But if it's working fine, then it could be for now, so lets leave it. Simply 
> with this it may not find all cases.
I'm happy to try doing it a different way. I just took this code from the 
`bugprone-unused-return-value` check. I had a go at using:
```C++
Finder->addMatcher(
  callExpr(unless(hasParent(anyOf(varDecl(), callExpr(), ifStmt(), 
whileStmt(), doStmt(), forStmt(), cxxForRangeStmt(), switchCase(, 
argumentCountAtLeast(1),
```
but there's no overload of `hasParent` that will accept the return type of 
`anyOf`:
```
/home/mac/git/llvm-project/clang-tools-extra/clang-tidy/modernize/UseStdPrintCheck.cpp:100:23:
 error: no matching function for call to object of type 'const 
internal::ArgumentAdaptingMatcherFunc, 
internal::TypeList>'
  callExpr(unless(hasParent(anyOf(varDecl(), callExpr(), ifStmt(), 
whileStmt(), doStmt(), forStmt(), cxxForRangeStmt(), switchCase(, 
argumentCountAtLeast(1),
  ^
/home/mac/git/llvm-project/clang/include/clang/ASTMatchers/ASTMatchersInternal.h:1491:3:
 note: candidate template ignored: could not match 'Matcher' against 
'VariadicOperatorMatcher'
  operator()(const Matcher &InnerMatcher) const {
  ^
/home/mac/git/llvm-project/clang/include/clang/ASTMatchers/ASTMatchersInternal.h:1498:3:
 note: candidate template ignored: could not match 'MapAnyOfHelper' against 
'VariadicOperatorMatcher'
  operator()(const MapAnyOfHelper &InnerMatcher) const {
```
(Reducing the set of matchers inside the `anyOf` didn't help.)



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print-absl.cpp:63
+  // CHECK-MESSAGES-NOT: [[@LINE-1]]:10: warning: use 'std::println' instead 
of 'PrintF' [modernize-use-std-print]
+  // CHECK-FIXES-NOT: std::println("return value {}", i);
+}

PiotrZSL wrote:
> NOTE: I don't think that those FIXES-NOT are needed.
OK. I'll leave only the ones that are for deficiencies that might one day be 
fixed.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153860/new/

https://reviews.llvm.org/D153860

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153883: [Clang][OpenMP] Enable use of __kmpc_alloc_shared for VLAs defined in AMD GPU offloaded regions

2023-06-27 Thread Gheorghe-Teodor Bercea via Phabricator via cfe-commits
doru1004 added inline comments.



Comment at: clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp:1085
   }
-  for (const auto *VD : I->getSecond().EscapedVariableLengthDecls) {
-// Use actual memory size of the VLA object including the padding

ABataev wrote:
> jhuber6 wrote:
> > doru1004 wrote:
> > > ABataev wrote:
> > > > Why this code is removed?
> > > I could not understand why this code is here in the first place since it 
> > > doesn't seem that it could ever work correctly (and it doesn't seem to be 
> > > covered by any existing tests). Maybe I'm wrong but that was my 
> > > understanding of it. So what seems to happen is that this code attempts 
> > > to emit a kmpc_alloc_shared before the actual size calculation is 
> > > emitted. So if the VLA size is something that the user defines such as 
> > > `int N = 10;` then that code will not have been emitted at this point. 
> > > When the expression computing the size of the VLA uses `N`, the code that 
> > > is deleted here would just fail to find the VLA size in the attempt to 
> > > emit the kmpc_alloc_shared. The emission of the VLA as kmpc_alloc_shared 
> > > needs to happen after the expression of the size is emitted.
> > I'm pretty sure I was the one that wrote this code, and at the time I don't 
> > recall it really working. I remember there was something else that expected 
> > this to be here, but for what utility I do not recall. VLAs were never 
> > tested or used.
> They are tested, check 
> test/OpenMP/nvptx_target_teams_distribute_parallel_for_codegen.cpp for 
> example, where it captures VLA implicitly. I assume this should not be AMDGCN 
> specific.
Oh I see so this code path would cover the case when the VLA is defined outside 
the target region? I'm surprised I haven't seen any lit test fails for AMD 
GPUs, maybe this kind of test only exists for NVPTX. I'll add a test for AMD 
GPUs in that case.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153883/new/

https://reviews.llvm.org/D153883

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153536: [Clang] Implement P2169 A nice placeholder with no name

2023-06-27 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added subscribers: cjdb, aaron.ballman.
aaron.ballman added inline comments.



Comment at: clang/docs/ReleaseNotes.rst:135-136
 - Compiler flags ``-std=c++2c`` and ``-std=gnu++2c`` have been added for 
experimental C++2c implementation work.
+- Implemented `P2169R4: A nice placeholder with no name 
`_. This allows to use `_`
+  as a variable name multiple times in the same scope and is supported in all 
C++ language modes as an extension.
 

Should we consider adding this as an extension to C? It would be conforming 
there as well because it wouldn't change the behavior of any correct C code, 
right?



Comment at: clang/include/clang/AST/DeclBase.h:340-342
+  /// Whether this declaration denotes a placeholder that can be
+  /// redefined in the same scope.
+  unsigned IsPlaceholder : 1;

This seems a bit heavy to put on every `Decl`, it only matters for declarations 
with names, right? Should this be on `NamedDecl` instead? And should it be 
using terminology like "name independent"?

Actually, do we need this bit at all? Would it work for `NamedDecl` to have a 
function that returns whether the declaration name is `_` or not? Oh, I suppose 
we can't get away with that because `void _(int x);` does not introduce a 
placeholder identifier but a regular one, right?



Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:6589
+def err_using_placeholder_variable : Error<
+  "referring to placeholder '_' is not allowed">;
+def note_reference_placeholder : Note<

I don't think this helps the user understand what's wrong with their code, 
especially given the somewhat odd language rules around the feature. How about: 
`ambiguous reference to multiply-defined placeholder '_'` or something along 
those lines? Then the note can show the previous declarations of the 
placeholders that are in scope? e.g.,
```
void g() {
int _; // note: placeholder declared here
_ = 0;
int _; // note: placeholder declared here
_ = 0; // error: `ambiguous reference to multiply-defined placeholder '_'`
}
```
CC @cjdb 



Comment at: clang/include/clang/Sema/Lookup.h:121
+/// Name lookup results in an ambiguity because multiple placeholder
+/// variables were found in the same scope
+/// @code





Comment at: clang/lib/Sema/SemaDecl.cpp:2171-2172
 
+  if (VD->isPlaceholderVar())
+return;
+

What's the rationale here? I know the standard has a recommended practice, but 
I don't see why that should apply to the case where the user assigns a value to 
the placeholder but never references it otherwise.



Comment at: clang/lib/Sema/SemaDecl.cpp:7481
+if (!Previous.empty()) {
+  auto Decl = *Previous.begin();
+  const bool sameDC = Decl->getDeclContext()->getRedeclContext()->Equals(

Please spell out the type here.



Comment at: clang/lib/Sema/SemaDecl.cpp:7482
+  auto Decl = *Previous.begin();
+  const bool sameDC = Decl->getDeclContext()->getRedeclContext()->Equals(
+  DC->getRedeclContext());





Comment at: clang/lib/Sema/SemaDecl.cpp:7484-7486
+  if (sameDC && isDeclInScope(Decl, CurContext, S, false)) {
+DiagPlaceholderVariableDefinition(D.getIdentifierLoc());
+  }





Comment at: clang/lib/Sema/SemaDecl.cpp:8331
 
+  // Never warn about shadowing placeholder variable
+  if (ShadowedDecl->isPlaceholderVar())





Comment at: clang/lib/Sema/SemaDecl.cpp:18217
 
+  NewFD->setIsPlaceholderVar(LangOpts.CPlusPlus && II && II->isPlaceholder());
   if (PrevDecl && !isa(PrevDecl)) {

shafik wrote:
> cor3ntin wrote:
> > shafik wrote:
> > > Why can't we fold this into `FieldDecl::Create`? This comment applies in 
> > > some other places as well.
> > By adding a parameter to FieldDecl::Create? We could, I'm not sure it would 
> > necessarily be cleaner. Let me know what you prefer.
> It seems like having the code consolidated make for better maintainability 
> and figuring this out for future folks but I am willing to be convinced 
> otherwise.
We need to support partial construction because of AST deserialization, but it 
seems to me that we don't need to add a new parameter to `FieldDecl::Create()` 
anyway; can't we have the `FieldDecl` constructor look at the given 
`IdentifierInfo *` in that case, and if it's nonnull, set the placeholder from 
that?



Comment at: clang/lib/Sema/SemaDeclCXX.cpp:886
 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
+IdentifierInfo *VarName = B.Name;
 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,

`assert(VarName && "Cannot have an unnamed binding declaration");` ?



Comment at: clang/lib/Sema/SemaDeclCXX.cpp:917

  1   2   3   >