[PATCH] D157580: [RISCV][NFC] Use named arguments in newly added changes

2023-08-09 Thread Brandon Wu via Phabricator via cfe-commits
4vtomat accepted this revision.
4vtomat added a comment.

LGTM, thanks~


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157580

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


[PATCH] D157568: [clang-format] Handle NamespaceMacro string arg for FixNamespaceComments

2023-08-09 Thread Owen Pan via Phabricator via cfe-commits
owenpan updated this revision to Diff 548878.
owenpan added a comment.

Rebased and updated test cases.


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

https://reviews.llvm.org/D157568

Files:
  clang/lib/Format/NamespaceEndCommentsFixer.cpp
  clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp

Index: clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
===
--- clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
+++ clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
@@ -40,6 +40,18 @@
 Code,
 /*Ranges=*/{1, tooling::Range(0, Code.size())}, Style);
   }
+
+  bool isFormatted(StringRef Code, const std::vector ,
+   const FormatStyle  = getLLVMStyle()) const {
+return clang::format::fixNamespaceEndComments(Style, Code, Ranges,
+  "")
+.empty();
+  }
+
+  bool isFormatted(StringRef Code,
+   const FormatStyle  = getLLVMStyle()) const {
+return isFormatted(Code, {1, tooling::Range(0, Code.size())}, Style);
+  }
 };
 
 TEST_F(NamespaceEndCommentsFixerTest, AddsEndComment) {
@@ -688,48 +700,34 @@
   FormatStyle Style = getLLVMStyle();
   Style.NamespaceMacros.push_back("TESTSUITE");
 
-  EXPECT_EQ("TESTSUITE() {\n"
-"int i;\n"
-"} // end anonymous TESTSUITE()",
-fixNamespaceEndComments("TESTSUITE() {\n"
-"int i;\n"
-"} // end anonymous TESTSUITE()",
-Style));
-  EXPECT_EQ("TESTSUITE(A) {\n"
-"int i;\n"
-"} /* end of TESTSUITE(A) */",
-fixNamespaceEndComments("TESTSUITE(A) {\n"
-"int i;\n"
-"} /* end of TESTSUITE(A) */",
-Style));
-  EXPECT_EQ("TESTSUITE(A) {\n"
-"int i;\n"
-"}   //   TESTSUITE(A)",
-fixNamespaceEndComments("TESTSUITE(A) {\n"
-"int i;\n"
-"}   //   TESTSUITE(A)",
-Style));
-  EXPECT_EQ("TESTSUITE(A::B) {\n"
-"int i;\n"
-"} // end TESTSUITE(A::B)",
-fixNamespaceEndComments("TESTSUITE(A::B) {\n"
-"int i;\n"
-"} // end TESTSUITE(A::B)",
-Style));
-  EXPECT_EQ("TESTSUITE(A) {\n"
-"int i;\n"
-"}; // end TESTSUITE(A)",
-fixNamespaceEndComments("TESTSUITE(A) {\n"
-"int i;\n"
-"}; // end TESTSUITE(A)",
-Style));
-  EXPECT_EQ("TESTSUITE() {\n"
-"int i;\n"
-"}; /* unnamed TESTSUITE() */",
-fixNamespaceEndComments("TESTSUITE() {\n"
-"int i;\n"
-"}; /* unnamed TESTSUITE() */",
-Style));
+  EXPECT_TRUE(isFormatted("TESTSUITE() {\n"
+  "int i;\n"
+  "} // end anonymous TESTSUITE()",
+  Style));
+  EXPECT_TRUE(isFormatted("TESTSUITE(A) {\n"
+  "int i;\n"
+  "} /* end of TESTSUITE(A) */",
+  Style));
+  EXPECT_TRUE(isFormatted("TESTSUITE(A) {\n"
+  "int i;\n"
+  "}   //   TESTSUITE(A)",
+  Style));
+  EXPECT_TRUE(isFormatted("TESTSUITE(A::B) {\n"
+  "int i;\n"
+  "} // end TESTSUITE(A::B)",
+  Style));
+  EXPECT_TRUE(isFormatted("TESTSUITE(A) {\n"
+  "int i;\n"
+  "}; // end TESTSUITE(A)",
+  Style));
+  EXPECT_TRUE(isFormatted("TESTSUITE() {\n"
+  "int i;\n"
+  "}; /* unnamed TESTSUITE() */",
+  Style));
+  EXPECT_TRUE(isFormatted("TESTSUITE(\"foo\") {\n"
+  "int i;\n"
+  "} // TESTSUITE(\"foo\")",
+  Style));
 }
 
 TEST_F(NamespaceEndCommentsFixerTest, UpdatesInvalidEndLineComment) {
Index: clang/lib/Format/NamespaceEndCommentsFixer.cpp
===
--- clang/lib/Format/NamespaceEndCommentsFixer.cpp
+++ clang/lib/Format/NamespaceEndCommentsFixer.cpp
@@ -174,7 +174,7 @@
   llvm::Regex::IgnoreCase);
   static const llvm::Regex NamespaceMacroCommentPattern =
   llvm::Regex("^/[/*] *(end (of )?)? *(anonymous|unnamed)? *"
-  "([a-zA-Z0-9_]+)\\(([a-zA-Z0-9:_]*)\\)\\.? 

[PATCH] D157201: [Clang] Support qualified name as member designator in offsetof

2023-08-09 Thread Hubert Tong via Phabricator via cfe-commits
hubert.reinterpretcast added inline comments.



Comment at: clang/test/SemaCXX/offsetof.cpp:106
+int x3[__builtin_offsetof(struct X2, X2::static_a) == 0 ? 1 : -1]; // 
expected-error{{no member named 'static_a'}}
+int x4[__builtin_offsetof(struct X2, X2::X2) == 0 ? 1 : -1]; // 
expected-error{{no member named 'X2'}}
+

aaron.ballman wrote:
> yichi170 wrote:
> > aaron.ballman wrote:
> > > There's one more test I'd like to see:
> > > ```
> > > struct S {
> > >   int Foo;
> > > };
> > > 
> > > template 
> > > void func() {
> > >   static_assert(__builtin_offsetof(Ty, Ty::Foo) == 0, "");
> > > }
> > > 
> > > void inst() {
> > >   func();
> > > }
> > > ```
> > It would get the compile error in the current patch, but I think it should 
> > be compiled without any error, right?
> Correct, that should be accepted: https://godbolt.org/z/1f6a9Yaxa
Should expect this to pass too:
```
template 
struct Z {
  static_assert(!__builtin_offsetof(T, template Q::x));
};

struct A {
  template  using Q = T;
  int x;
};

Z za;
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157201

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


[PATCH] D151547: [RISCV] Remove experimental for zihintntl

2023-08-09 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.

LGTM - just see the very minor corrections inline. Thanks!




Comment at: clang/test/Preprocessor/riscv-target-features.c:146
 
 // RUN: %clang -target riscv32-unknown-linux-gnu 
-menable-experimental-extensions \
+// RUN: -march=rv32izihintntl1p0 -x c -E -dM %s \

Drop `-menable-experimental-extensions`



Comment at: clang/test/Preprocessor/riscv-target-features.c:149
+// RUN: -o - | FileCheck --check-prefix=CHECK-ZIHINTNTL %s
 // RUN: %clang -target riscv64-unknown-linux-gnu 
-menable-experimental-extensions \
+// RUN: -march=rv64izihintntl1p0 -x c -E -dM %s \

Drop `Drop `-menable-experimental-extensions`



Comment at: llvm/docs/RISCVUsage.rst:123
  ``Zifencei`` (`See Note <#riscv-i2p1-note>`__)
+ ``zihintntl``Supported
  ``Zihintpause``  Assembly Support

zihintntl -> Zihintntl


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151547

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


[PATCH] D156749: [modules] Fix error about the same module being defined in different .pcm files when using VFS overlays.

2023-08-09 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 added inline comments.



Comment at: clang/lib/Serialization/ASTWriter.cpp:1330
 AddPath(WritingModule->PresumedModuleMapFile.empty()
-? Map.getModuleMapFileForUniquing(WritingModule)->getName()
+? Map.getModuleMapFileForUniquing(WritingModule)
+  ->getNameAsRequested()

vsapsai wrote:
> jansvoboda11 wrote:
> > Can we canonicalize this also? It'd be useful in the scanner.
> I'm not sure about that. ASTReader has some complicated logic around reading 
> this value 
> https://github.com/llvm/llvm-project/blob/c1803d5366c794ecade4e4ccd0013690a1976d49/clang/lib/Serialization/ASTReader.cpp#L4005
>  So if we don't have a proven need for it with a test case, I wouldn't change 
> it.
Good point. I do have a use for it, but I think it'd be safer to do separately 
from this patch a qualify it in isolation.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156749

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


[PATCH] D152793: [RISCV] Add MC layer support for Zicfiss.

2023-08-09 Thread Yeting Kuo via Phabricator via cfe-commits
fakepaper56 added reviewers: craig.topper, frasercrmck, rogfer01, reames, asb, 
luke.
fakepaper56 marked an inline comment as done.
fakepaper56 added inline comments.



Comment at: llvm/lib/Target/RISCV/RISCVInstrInfoZicfiss.td:56
+let Predicates = [HasStdExtZicfiss] in {
+def SSLoadX1: RV_SSPop<0b1, 0b0, "ssload", "x1">;
+def SSLoadX5: RV_SSPop<0b00101, 0b0, "ssload", "x5">;

fakepaper56 wrote:
> craig.topper wrote:
> > Need to be able to parse with `ra` instead of x1 and `t0` instead of x5. 
> > 
> > I think you might need a new Operand type so the parse can parse it as a 
> > register.
> > Need to be able to parse with ra instead of x1 and t0 instead of x5.
> Actually, we can parse `ssload ra` in llvm/test/MC/RISCV/zicfiss-valid.s, but 
> the code indeed can not print `ssload ra`. I have tried to define `ssload` 
> and `sspopchk` separately, but it caused decode conflict.
The problem is fixed in latest update.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152793

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


[PATCH] D152793: [RISCV] Add MC layer support for Zicfiss.

2023-08-09 Thread Yeting Kuo via Phabricator via cfe-commits
fakepaper56 updated this revision to Diff 548873.
fakepaper56 added a comment.

Make asmprinter capable to print alias register name for 
ssload/sspopchk/c.sspush/c.sspopchk.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152793

Files:
  clang/test/Preprocessor/riscv-target-features.c
  llvm/lib/Support/RISCVISAInfo.cpp
  llvm/lib/Target/RISCV/AsmParser/RISCVAsmParser.cpp
  llvm/lib/Target/RISCV/Disassembler/RISCVDisassembler.cpp
  llvm/lib/Target/RISCV/MCTargetDesc/RISCVBaseInfo.h
  llvm/lib/Target/RISCV/RISCVFeatures.td
  llvm/lib/Target/RISCV/RISCVInstrInfo.td
  llvm/lib/Target/RISCV/RISCVInstrInfoZicfiss.td
  llvm/lib/Target/RISCV/RISCVRegisterInfo.cpp
  llvm/lib/Target/RISCV/RISCVRegisterInfo.td
  llvm/test/MC/RISCV/attribute-arch.s
  llvm/test/MC/RISCV/zicfiss-invalid.s
  llvm/test/MC/RISCV/zicfiss-valid.s

Index: llvm/test/MC/RISCV/zicfiss-valid.s
===
--- /dev/null
+++ llvm/test/MC/RISCV/zicfiss-valid.s
@@ -0,0 +1,110 @@
+# RUN: llvm-mc %s -triple=riscv32 -mattr=+experimental-zicfiss,+c -riscv-no-aliases -show-encoding \
+# RUN: | FileCheck -check-prefixes=CHECK-ASM,CHECK-ASM-AND-OBJ %s
+# RUN: llvm-mc %s -triple=riscv64 -mattr=+experimental-zicfiss,+c -riscv-no-aliases -show-encoding \
+# RUN: | FileCheck -check-prefixes=CHECK-ASM,CHECK-ASM-AND-OBJ %s
+# RUN: llvm-mc -filetype=obj -triple=riscv32 -mattr=+experimental-zicfiss,+c < %s \
+# RUN: | llvm-objdump --mattr=+experimental-zicfiss -M no-aliases -d -r - \
+# RUN: | FileCheck --check-prefix=CHECK-ASM-AND-OBJ %s
+# RUN: llvm-mc -filetype=obj -triple=riscv64 -mattr=+experimental-zicfiss,+c < %s \
+# RUN: | llvm-objdump --mattr=+experimental-zicfiss -M no-aliases -d -r - \
+# RUN: | FileCheck --check-prefix=CHECK-ASM-AND-OBJ %s
+#
+# RUN: not llvm-mc -triple riscv32 -riscv-no-aliases -show-encoding < %s 2>&1 \
+# RUN: | FileCheck -check-prefixes=CHECK-NO-EXT %s
+# RUN: not llvm-mc -triple riscv64 -riscv-no-aliases -show-encoding < %s 2>&1 \
+# RUN: | FileCheck -check-prefixes=CHECK-NO-EXT %s
+
+# CHECK-ASM-AND-OBJ: ssload ra
+# CHECK-ASM: encoding: [0xf3,0x40,0xc0,0x81]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+ssload x1
+
+# CHECK-ASM-AND-OBJ: ssload ra
+# CHECK-ASM: encoding: [0xf3,0x40,0xc0,0x81]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+ssload ra
+
+# CHECK-ASM-AND-OBJ: ssload t0
+# CHECK-ASM: encoding: [0xf3,0x42,0xc0,0x81]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+ssload x5
+
+# CHECK-ASM-AND-OBJ: ssload t0
+# CHECK-ASM: encoding: [0xf3,0x42,0xc0,0x81]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+ssload t0
+
+# CHECK-ASM-AND-OBJ: sspopchk ra
+# CHECK-ASM: encoding: [0x73,0xc0,0xc0,0x81]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+sspopchk x1
+
+# CHECK-ASM-AND-OBJ: sspopchk ra
+# CHECK-ASM: encoding: [0x73,0xc0,0xc0,0x81]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+sspopchk ra
+
+# CHECK-ASM-AND-OBJ: sspopchk t0
+# CHECK-ASM: encoding: [0x73,0xc0,0xc2,0x81]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+sspopchk x5
+
+# CHECK-ASM-AND-OBJ: sspopchk t0
+# CHECK-ASM: encoding: [0x73,0xc0,0xc2,0x81]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+sspopchk t0
+
+# CHECK-ASM-AND-OBJ: sspinc 4
+# CHECK-ASM: encoding: [0x73,0x40,0xd2,0x81]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+sspinc 4
+
+# CHECK-ASM-AND-OBJ: sspush ra
+# CHECK-ASM: encoding: [0x73,0x40,0x10,0x8a]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+sspush x1
+
+# CHECK-ASM-AND-OBJ: sspush ra
+# CHECK-ASM: encoding: [0x73,0x40,0x10,0x8a]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+sspush ra
+
+# check-asm-and-obj: sspush t0
+# check-asm: encoding: [0x73,0x40,0x50,0x8a]
+# check-no-ext: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+sspush x5
+
+# check-asm-and-obj: sspush t0
+# check-asm: encoding: [0x73,0x40,0x50,0x8a]
+# check-no-ext: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+sspush t0
+
+# CHECK-ASM-AND-OBJ: ssprr ra
+# CHECK-ASM: encoding: [0xf3,0x40,0x00,0x86]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+ssprr ra
+
+# CHECK-ASM-AND-OBJ: ssamoswap t0, zero, (a0)
+# CHECK-ASM: encoding: [0xf3,0x42,0x05,0x82]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+ssamoswap t0, x0, (a0)
+
+# CHECK-ASM-AND-OBJ: c.sspush ra
+# CHECK-ASM: encoding: [0x81,0x60]
+# CHECK-NO-EXT: error: instruction requires the following: 'C' (Compressed 

[PATCH] D157580: [RISCV][NFC] Use named arguments in newly added changes

2023-08-09 Thread Wang Pengcheng via Phabricator via cfe-commits
wangpc created this revision.
wangpc added reviewers: 4vtomat, craig.topper.
Herald added subscribers: jobnoorman, luke, VincentWu, vkmr, frasercrmck, 
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.
wangpc requested review of this revision.
Herald added subscribers: llvm-commits, cfe-commits, eopXD, MaskRay.
Herald added projects: clang, LLVM.

Named arguments have been supported in D152998 
 and most *.td files
of RISC-V target have been rewritten. This patch just makes them
consistent since some newly added changes were in this way.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D157580

Files:
  clang/include/clang/Basic/riscv_sifive_vector.td
  clang/include/clang/Basic/riscv_vector.td
  llvm/include/llvm/IR/IntrinsicsRISCV.td
  llvm/include/llvm/IR/IntrinsicsRISCVXsf.td
  llvm/lib/Target/RISCV/RISCVInstrInfoV.td
  llvm/lib/Target/RISCV/RISCVInstrInfoXTHead.td
  llvm/lib/Target/RISCV/RISCVInstrInfoZvk.td

Index: llvm/lib/Target/RISCV/RISCVInstrInfoZvk.td
===
--- llvm/lib/Target/RISCV/RISCVInstrInfoZvk.td
+++ llvm/lib/Target/RISCV/RISCVInstrInfoZvk.td
@@ -336,7 +336,7 @@
 defvar suffix = "_V_" # m.MX;
 def suffix : VPseudoUnaryNoMask;
 def suffix # "_MASK" : VPseudoUnaryMask,
-RISCVMaskedPseudo;
+RISCVMaskedPseudo;
   }
 }
 
Index: llvm/lib/Target/RISCV/RISCVInstrInfoXTHead.td
===
--- llvm/lib/Target/RISCV/RISCVInstrInfoXTHead.td
+++ llvm/lib/Target/RISCV/RISCVInstrInfoXTHead.td
@@ -236,13 +236,13 @@
 
 multiclass THVdotVMAQA_VX funct6> {
   let RVVConstraint = WidenV in
-  def _VX : THVdotALUrVX;
+  def _VX : THVdotALUrVX;
 }
 
 multiclass THVdotVMAQA funct6>
 : THVdotVMAQA_VX {
   let RVVConstraint = WidenV in
-  def _VV   : THVdotALUrVV;
+  def _VV   : THVdotALUrVV;
 }
 
 //===--===//
Index: llvm/lib/Target/RISCV/RISCVInstrInfoV.td
===
--- llvm/lib/Target/RISCV/RISCVInstrInfoV.td
+++ llvm/lib/Target/RISCV/RISCVInstrInfoV.td
@@ -620,7 +620,7 @@
 multiclass VWMAC_MV_V_X funct6>
: VWMAC_MV_X {
   let RVVConstraint = WidenV in
-  def V : VALUrVV,
+  def V : VALUrVV,
   SchedTernaryMC<"WriteVIWMulAddV", "ReadVIWMulAddV", "ReadVIWMulAddV",
  "ReadVIWMulAddV">;
 }
@@ -721,10 +721,10 @@
 
 multiclass VWMAC_FV_V_F funct6> {
   let RVVConstraint = WidenV in {
-  def V : VALUrVV,
+  def V : VALUrVV,
   SchedTernaryMC<"WriteVFWMulAddV", "ReadVFWMulAddV", "ReadVFWMulAddV",
  "ReadVFWMulAddV">;
-  def F : VALUrVF,
+  def F : VALUrVF,
   SchedTernaryMC<"WriteVFWMulAddF", "ReadVFWMulAddV", "ReadVFWMulAddF",
  "ReadVFWMulAddV">;
   }
Index: llvm/include/llvm/IR/IntrinsicsRISCVXsf.td
===
--- llvm/include/llvm/IR/IntrinsicsRISCVXsf.td
+++ llvm/include/llvm/IR/IntrinsicsRISCVXsf.td
@@ -93,38 +93,38 @@
   defvar range = ["c", "s", "i", "l"];
   foreach r = range in {
 foreach s = VCIXSuffix.suffix in {
-  def "int_riscv_sf_vc_" # t # "_se_" # s : RISCVSFCustomVC_X;
+  def "int_riscv_sf_vc_" # t # "_se_" # s : RISCVSFCustomVC_X;
 }
   }
-  def "int_riscv_sf_vc_v_" # t # "_se" : RISCVSFCustomVC_X;
-  def "int_riscv_sf_vc_v_" # t : RISCVSFCustomVC_X;
+  def "int_riscv_sf_vc_v_" # t # "_se" : RISCVSFCustomVC_X;
+  def "int_riscv_sf_vc_v_" # t : RISCVSFCustomVC_X;
 }
   }
 
   multiclass RISCVSFCustomVC_XV type> {
 foreach t = type in {
   defvar ImmScalar = !eq(t, "i");
-  def "int_riscv_sf_vc_" # t # "v_se"   : RISCVSFCustomVC_XV;
-  def "int_riscv_sf_vc_v_" # t # "v_se" : RISCVSFCustomVC_XV;
-  def "int_riscv_sf_vc_v_" # t # "v": RISCVSFCustomVC_XV;
+  def "int_riscv_sf_vc_" # t # "v_se"   : RISCVSFCustomVC_XV;
+  def "int_riscv_sf_vc_v_" # t # "v_se" : RISCVSFCustomVC_XV;
+  def "int_riscv_sf_vc_v_" # t # "v": RISCVSFCustomVC_XV;
 }
   }
 
   multiclass RISCVSFCustomVC_XVV type> {
 foreach t = type in {
   defvar ImmScalar = !eq(t, "i");
-  def "int_riscv_sf_vc_" # t # "vv_se"   : RISCVSFCustomVC_XVV;
-  def "int_riscv_sf_vc_v_" # t # "vv_se" : RISCVSFCustomVC_XVV;
-  def "int_riscv_sf_vc_v_" # t # "vv": RISCVSFCustomVC_XVV;
+  def "int_riscv_sf_vc_" # t # "vv_se"   : RISCVSFCustomVC_XVV;
+  def "int_riscv_sf_vc_v_" # t # "vv_se" : RISCVSFCustomVC_XVV;
+  def 

[PATCH] D157579: [clang][ExtractAPI] Add support for C++ global function templates

2023-08-09 Thread Erick Velez via Phabricator via cfe-commits
evelez7 created this revision.
evelez7 added a reviewer: dang.
Herald added a reviewer: ributzka.
Herald added a project: All.
evelez7 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Add records, serialization for global function templates and their 
specializations

Depends on D157350 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D157579

Files:
  clang/include/clang/ExtractAPI/API.h
  clang/include/clang/ExtractAPI/DeclarationFragments.h
  clang/include/clang/ExtractAPI/ExtractAPIVisitor.h
  clang/include/clang/ExtractAPI/Serialization/SerializerBase.h
  clang/include/clang/ExtractAPI/Serialization/SymbolGraphSerializer.h
  clang/lib/ExtractAPI/API.cpp
  clang/lib/ExtractAPI/DeclarationFragments.cpp
  clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
  clang/test/ExtractAPI/global_func_template.cpp
  clang/test/ExtractAPI/global_func_template_spec.cpp

Index: clang/test/ExtractAPI/global_func_template_spec.cpp
===
--- /dev/null
+++ clang/test/ExtractAPI/global_func_template_spec.cpp
@@ -0,0 +1,299 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: sed -e "s@INPUT_DIR@%{/t:regex_replacement}@g" \
+// RUN: %t/reference.output.json.in >> %t/reference.output.json
+// RUN: %clang_cc1 -extract-api -triple arm64-apple-macosx \
+// RUN:   -x c++-header %t/input.h -o %t/output.json -verify
+
+// Generator version is not consistent across test runs, normalize it.
+// RUN: sed -e "s@\"generator\": \".*\"@\"generator\": \"?\"@g" \
+// RUN: %t/output.json >> %t/output-normalized.json
+// RUN: diff %t/reference.output.json %t/output-normalized.json
+
+//--- input.h
+template void Foo(T Bar);
+
+template<> void Foo(int Bar);
+/// expected-no-diagnostics
+
+//--- reference.output.json.in
+{
+  "metadata": {
+"formatVersion": {
+  "major": 0,
+  "minor": 5,
+  "patch": 3
+},
+"generator": "?"
+  },
+  "module": {
+"name": "",
+"platform": {
+  "architecture": "arm64",
+  "operatingSystem": {
+"minimumVersion": {
+  "major": 11,
+  "minor": 0,
+  "patch": 0
+},
+"name": "macosx"
+  },
+  "vendor": "apple"
+}
+  },
+  "relationships": [],
+  "symbols": [
+{
+  "accessLevel": "public",
+  "declarationFragments": [
+{
+  "kind": "keyword",
+  "spelling": "template"
+},
+{
+  "kind": "text",
+  "spelling": "<"
+},
+{
+  "kind": "keyword",
+  "spelling": "typename"
+},
+{
+  "kind": "text",
+  "spelling": " "
+},
+{
+  "kind": "genericParameter",
+  "spelling": "T"
+},
+{
+  "kind": "text",
+  "spelling": "> "
+},
+{
+  "kind": "typeIdentifier",
+  "preciseIdentifier": "c:v",
+  "spelling": "void"
+},
+{
+  "kind": "text",
+  "spelling": " "
+},
+{
+  "kind": "identifier",
+  "spelling": "Foo"
+},
+{
+  "kind": "text",
+  "spelling": "("
+},
+{
+  "kind": "typeIdentifier",
+  "preciseIdentifier": "c:t0.0",
+  "spelling": "T"
+},
+{
+  "kind": "text",
+  "spelling": " "
+},
+{
+  "kind": "internalParam",
+  "spelling": "Bar"
+},
+{
+  "kind": "text",
+  "spelling": ");"
+}
+  ],
+  "functionSignature": {
+"parameters": [
+  {
+"declarationFragments": [
+  {
+"kind": "typeIdentifier",
+"preciseIdentifier": "c:t0.0",
+"spelling": "T"
+  },
+  {
+"kind": "text",
+"spelling": " "
+  },
+  {
+"kind": "internalParam",
+"spelling": "Bar"
+  }
+],
+"name": "Bar"
+  }
+],
+"returns": [
+  {
+"kind": "typeIdentifier",
+"preciseIdentifier": "c:v",
+"spelling": "void"
+  }
+]
+  },
+  "identifier": {
+"interfaceLanguage": "c++",
+"precise": "c:@FT@>1#TFoo#t0.0#v#"
+  },
+  "kind": {
+"displayName": "Function Template",
+"identifier": "c++.func"
+  },
+  "location": {
+"position": {
+  "character": 27,
+  "line": 1
+},
+"uri": "file://INPUT_DIR/input.h"
+  },
+  "names": {
+"navigator": [
+  {
+"kind": "identifier",
+"spelling": "Foo"
+  }
+],
+"subHeading": [
+  {
+"kind": 

[PATCH] D157076: [clang][ExtractAPI] Add support for C++ class templates and concepts

2023-08-09 Thread Erick Velez via Phabricator via cfe-commits
evelez7 updated this revision to Diff 548862.
evelez7 added a comment.

Fix template arg identification


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157076

Files:
  clang/include/clang/ExtractAPI/API.h
  clang/include/clang/ExtractAPI/DeclarationFragments.h
  clang/include/clang/ExtractAPI/ExtractAPIVisitor.h
  clang/include/clang/ExtractAPI/Serialization/SerializerBase.h
  clang/include/clang/ExtractAPI/Serialization/SymbolGraphSerializer.h
  clang/lib/ExtractAPI/API.cpp
  clang/lib/ExtractAPI/DeclarationFragments.cpp
  clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
  clang/test/ExtractAPI/class_template.cpp
  clang/test/ExtractAPI/class_template_partial_spec.cpp
  clang/test/ExtractAPI/class_template_spec.cpp
  clang/test/ExtractAPI/concept.cpp

Index: clang/test/ExtractAPI/concept.cpp
===
--- /dev/null
+++ clang/test/ExtractAPI/concept.cpp
@@ -0,0 +1,133 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: sed -e "s@INPUT_DIR@%{/t:regex_replacement}@g" \
+// RUN: %t/reference.output.json.in >> %t/reference.output.json
+// RUN: %clang_cc1 -std=c++20 -extract-api -triple arm64-apple-macosx \
+// RUN:   -x c++-header %t/input.h -o %t/output.json -verify
+
+// Generator version is not consistent across test runs, normalize it.
+// RUN: sed -e "s@\"generator\": \".*\"@\"generator\": \"?\"@g" \
+// RUN: %t/output.json >> %t/output-normalized.json
+// RUN: diff %t/reference.output.json %t/output-normalized.json
+
+//--- input.h
+template concept Foo = true;
+
+/// expected-no-diagnostics
+
+//--- reference.output.json.in
+{
+  "metadata": {
+"formatVersion": {
+  "major": 0,
+  "minor": 5,
+  "patch": 3
+},
+"generator": "?"
+  },
+  "module": {
+"name": "",
+"platform": {
+  "architecture": "arm64",
+  "operatingSystem": {
+"minimumVersion": {
+  "major": 11,
+  "minor": 0,
+  "patch": 0
+},
+"name": "macosx"
+  },
+  "vendor": "apple"
+}
+  },
+  "relationships": [],
+  "symbols": [
+{
+  "accessLevel": "public",
+  "declarationFragments": [
+{
+  "kind": "keyword",
+  "spelling": "template"
+},
+{
+  "kind": "text",
+  "spelling": "<"
+},
+{
+  "kind": "keyword",
+  "spelling": "typename"
+},
+{
+  "kind": "text",
+  "spelling": " "
+},
+{
+  "kind": "genericParameter",
+  "spelling": "T"
+},
+{
+  "kind": "text",
+  "spelling": "> "
+},
+{
+  "kind": "keyword",
+  "spelling": "concept"
+},
+{
+  "kind": "text",
+  "spelling": " "
+},
+{
+  "kind": "identifier",
+  "spelling": "Foo"
+},
+{
+  "kind": "text",
+  "spelling": ";"
+}
+  ],
+  "identifier": {
+"interfaceLanguage": "c++",
+"precise": "c:@CT@Foo"
+  },
+  "kind": {
+"displayName": "Concept",
+"identifier": "c++.concept"
+  },
+  "location": {
+"position": {
+  "character": 30,
+  "line": 1
+},
+"uri": "file://INPUT_DIR/input.h"
+  },
+  "names": {
+"navigator": [
+  {
+"kind": "identifier",
+"spelling": "Foo"
+  }
+],
+"subHeading": [
+  {
+"kind": "identifier",
+"spelling": "Foo"
+  }
+],
+"title": "Foo"
+  },
+  "pathComponents": [
+"Foo"
+  ],
+  "swiftGenerics": {
+"parameters": [
+  {
+"depth": 0,
+"index": 0,
+"name": "T"
+  }
+]
+  }
+}
+  ]
+}
Index: clang/test/ExtractAPI/class_template_spec.cpp
===
--- /dev/null
+++ clang/test/ExtractAPI/class_template_spec.cpp
@@ -0,0 +1,206 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: sed -e "s@INPUT_DIR@%{/t:regex_replacement}@g" \
+// RUN: %t/reference.output.json.in >> %t/reference.output.json
+// RUN: %clang_cc1 -extract-api -triple arm64-apple-macosx \
+// RUN:   -x c++-header %t/input.h -o %t/output.json -verify
+
+// Generator version is not consistent across test runs, normalize it.
+// RUN: sed -e "s@\"generator\": \".*\"@\"generator\": \"?\"@g" \
+// RUN: %t/output.json >> %t/output-normalized.json
+// RUN: diff %t/reference.output.json %t/output-normalized.json
+
+//--- input.h
+template class Foo {};
+
+template<> class Foo {};
+
+/// expected-no-diagnostics
+
+//--- reference.output.json.in
+{
+  "metadata": {
+"formatVersion": {
+  "major": 0,
+  "minor": 5,
+  "patch": 3
+},
+

[PATCH] D157572: [clang] Add `[[clang::library_extension]]` attribute

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

This allows standard libraries to mark symbols as extensions, so the compiler 
can generate extension warnings when they are used.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D157572

Files:
  clang/include/clang/AST/DeclBase.h
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/AST/DeclBase.cpp
  clang/lib/Sema/CodeCompleteConsumer.cpp
  clang/lib/Sema/SemaAvailability.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/lib/Sema/SemaStmt.cpp
  clang/test/SemaCXX/attr-library-extension.cpp
  clang/tools/libclang/CIndex.cpp

Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -8280,6 +8280,7 @@
   switch (D->getAvailability()) {
   case AR_Available:
   case AR_NotYetIntroduced:
+  case AR_Extension:
 if (const EnumConstantDecl *EnumConst = dyn_cast(D))
   return getCursorAvailabilityForDecl(
   cast(EnumConst->getDeclContext()));
Index: clang/test/SemaCXX/attr-library-extension.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/attr-library-extension.cpp
@@ -0,0 +1,130 @@
+// RUN: %clang_cc1 -Wno-unused-value -std=c++03 -verify=cxx03,cxx11,cxx14,cxx17,cxx20,cxx23,gnu -fsyntax-only %s -DGNUAttr
+// RUN: %clang_cc1 -Wno-unused-value -std=c++11 -verify=cxx11,cxx14,cxx17,cxx20,cxx23,gnu -fsyntax-only %s
+// RUN: %clang_cc1 -Wno-unused-value -std=c++14 -verify=cxx14,cxx17,cxx20,cxx23,gnu -fsyntax-only %s
+// RUN: %clang_cc1 -Wno-unused-value -std=c++17 -verify=cxx17,cxx20,cxx23,gnu -fsyntax-only %s
+// RUN: %clang_cc1 -Wno-unused-value -std=c++20 -verify=cxx20,cxx23,gnu -fsyntax-only %s
+// RUN: %clang_cc1 -Wno-unused-value -std=c++23 -verify=cxx23,gnu -fsyntax-only %s
+// RUN: %clang_cc1 -Wno-unused-value -std=c++26 -verify=gnu -fsyntax-only %s
+
+#ifdef GNUAttr
+#define EXTENSION(name) __attribute__((library_extension(name)))
+#else
+#define EXTENSION(name) [[clang::library_extension(name)]]
+#endif
+
+struct EXTENSION("C++11") StructCxx11Ext {}; // cxx03-note {{'StructCxx11Ext' has been explicitly marked as an extension here}}
+struct EXTENSION("C++14") StructCxx14Ext {}; // cxx11-note {{'StructCxx14Ext' has been explicitly marked as an extension here}}
+struct EXTENSION("C++17") StructCxx17Ext {}; // cxx14-note {{'StructCxx17Ext' has been explicitly marked as an extension here}}
+struct EXTENSION("C++20") StructCxx20Ext {}; // cxx17-note {{'StructCxx20Ext' has been explicitly marked as an extension here}}
+struct EXTENSION("C++23") StructCxx23Ext {}; // cxx20-note {{'StructCxx23Ext' has been explicitly marked as an extension here}}
+struct EXTENSION("C++26") StructCxx26Ext {}; // cxx23-note {{'StructCxx26Ext' has been explicitly marked as an extension here}}
+struct EXTENSION("GNU") GNUExt {}; // gnu-note {{'GNUExt' has been explicitly marked as an extension here}}
+
+void consume(StructCxx11Ext); // cxx03-warning {{'StructCxx11Ext' is a C++11 extension}}
+void consume(StructCxx14Ext); // cxx11-warning {{'StructCxx14Ext' is a C++14 extension}}
+void consume(StructCxx17Ext); // cxx14-warning {{'StructCxx17Ext' is a C++17 extension}}
+void consume(StructCxx20Ext); // cxx17-warning {{'StructCxx20Ext' is a C++20 extension}}
+void consume(StructCxx23Ext); // cxx20-warning {{'StructCxx23Ext' is a C++23 extension}}
+void consume(StructCxx26Ext); // cxx23-warning {{'StructCxx26Ext' is a C++2c extension}}
+void consume(GNUExt); // gnu-warning {{'GNUExt' is a GNU extension}}
+
+namespace EXTENSION("C++11") NSCxx11Ext { // cxx03-note {{'NSCxx11Ext' has been explicitly marked as an extension here}}
+  struct S {};
+}
+void consume(NSCxx11Ext::S); // cxx03-warning {{'NSCxx11Ext' is a C++11 extension}}
+
+namespace EXTENSION("C++14") NSCxx14Ext { // cxx11-note {{'NSCxx14Ext' has been explicitly marked as an extension here}}
+  struct S {};
+}
+void consume(NSCxx14Ext::S); // cxx11-warning {{'NSCxx14Ext' is a C++14 extension}}
+
+namespace EXTENSION("C++17") NSCxx17Ext { // cxx14-note {{'NSCxx17Ext' has been explicitly marked as an extension here}}
+  struct S {};
+}
+void consume(NSCxx17Ext::S); // cxx14-warning {{'NSCxx17Ext' is a C++17 extension}}
+
+namespace EXTENSION("C++20") NSCxx20Ext { // cxx17-note {{'NSCxx20Ext' has been explicitly marked as an extension here}}
+  struct S {};
+}
+void consume(NSCxx20Ext::S); // cxx17-warning {{'NSCxx20Ext' is a C++20 extension}}
+
+namespace EXTENSION("C++23") NSCxx23Ext { // cxx20-note {{'NSCxx23Ext' has been explicitly marked as an extension here}}
+  struct S {};
+}
+void consume(NSCxx23Ext::S); // cxx20-warning 

[PATCH] D157394: [clang][DeclPrinter] Improve AST print of function attributes

2023-08-09 Thread Timo Stripf via Phabricator via cfe-commits
strimo378 added a comment.

In D157394#4572777 , 
@giulianobelinassi wrote:

> This patch do not address attributes in variables nor the __declspec case, as 
> D141714  do. His patch looks cleaner and I 
> can surely coordinate with @strimo378 to also fix those cases, but I want an 
> answer to the tblgen question first to see if we decide to drop the tblgen 
> solution or not.

The patch is intended to only address function attributes to keep it simple and 
the test cases focused. Most important is that the AttrLocation is introduced 
and functionality can be easily extended to other decl types in subsequent 
patches. I did some work to address variable and record attributes but I think 
that I did not consider all cases for variables as you did.

`__declspec` should be always placed left?




Comment at: clang/lib/AST/DeclPrinter.cpp:259
+case attr::Final:
+case attr::Override:
+  return AttrLocation::AfterDecl;

giulianobelinassi wrote:
> aaron.ballman wrote:
> > giulianobelinassi wrote:
> > > @aaron.ballman @erichkeane 
> > > 
> > > Is this enough to describe the position of the attribute kind, or should 
> > > it go for a tblgen approach, as I did in D141714? This here looks much 
> > > cleaner than the tblgen IMHO.
> > Oofda, I forgot that we model those as keyword attributes. `override` and 
> > `final` (and other keyword attributes) are a bit trickier than just 
> > "before" or "after" because there's a very particular order in which those 
> > can be parsed grammatically, especially for functions: 
> > https://godbolt.org/z/ad5qecbrj
> > 
> > Thinking out loud: perhaps an approach to solving this is to sort the 
> > attributes by source location. So all the before attributes are written in 
> > the same order as they were in source, as are all of the after attributes. 
> > So long as we're skipping over implicit attributes, this seems like it 
> > should keep the order of the attributes correct.
> > 
> > A different alternative that's possibly more work than it's worth: the decl 
> > printer could dispatch to a table-genned function to ask the attribute "do 
> > you want to be printed now?" based on what part of the declaration we've 
> > already printed. This would require the decl printer to know e.g., "I've 
> > finished printing the parameter list but haven't yet printed cv qualifiers" 
> > and pass that information along to the attribute; individual attributes 
> > with special rules could supply special logic in Attr.td to say "the 
> > attribute should be printed after the function parameter list and after the 
> > cv and ref qualifiers, but before the override/final keywords" while most 
> > attributes can hopefully get away with whatever the default behavior is 
> > coming out of tablegen.
> > Oofda, I forgot that we model those as keyword attributes. `override` and 
> > `final` (and other keyword attributes) are a bit trickier than just 
> > "before" or "after" because there's a very particular order in which those 
> > can be parsed grammatically, especially for functions: 
> > https://godbolt.org/z/ad5qecbrj
> > 
> > Thinking out loud: perhaps an approach to solving this is to sort the 
> > attributes by source location. So all the before attributes are written in 
> > the same order as they were in source, as are all of the after attributes. 
> > So long as we're skipping over implicit attributes, this seems like it 
> > should keep the order of the attributes correct.
> 
> This may work in cases where clang is able to find the SourceLocation of the 
> Decl. My concern is when clang is *not* able to do it. When analyzing Linux 
> sourcecode there are cases where this happen, and I have to fallback to AST 
> dumping. The only way I see this working is by changing the parser for it to 
> mark the attribute and its position. This may be something for the future, 
> but the presented fix solves the issue for the cases we have already found. 
>  
> > A different alternative that's possibly more work than it's worth: the decl 
> > printer could dispatch to a table-genned function to ask the attribute "do 
> > you want to be printed now?" based on what part of the declaration we've 
> > already printed. This would require the decl printer to know e.g., "I've 
> > finished printing the parameter list but haven't yet printed cv qualifiers" 
> > and pass that information along to the attribute; individual attributes 
> > with special rules could supply special logic in Attr.td to say "the 
> > attribute should be printed after the function parameter list and after the 
> > cv and ref qualifiers, but before the override/final keywords" while most 
> > attributes can hopefully get away with whatever the default behavior is 
> > coming out of tablegen.
> 
> Sounds a lot of work :). Wouldn't my previous suggestion be simpler?
> 
Currently, I would not go for a tblgen approach 

[PATCH] D157454: [NFC][Clang] Fix static analyzer concern about null value dereference

2023-08-09 Thread Tom Honermann via Phabricator via cfe-commits
tahonermann accepted this revision.
tahonermann added a comment.

Looks good to me. Thanks, Elizabeth!


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

https://reviews.llvm.org/D157454

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


[PATCH] D157331: [clang] Implement C23

2023-08-09 Thread Zijun Zhao via Phabricator via cfe-commits
ZijunZhao added a comment.

Another followup question: I check 
https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2683.pdf and I only add Core 
Proposal here. Do I need to add Supplemental Proposal, like some types?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157331

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


[PATCH] D151547: [RISCV] Remove experimental for zihintntl.

2023-08-09 Thread Jianjian Guan via Phabricator via cfe-commits
jacquesguan updated this revision to Diff 548848.
jacquesguan added a comment.

rebase and add release note.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151547

Files:
  clang/include/clang/Basic/BuiltinsRISCV.def
  clang/test/CodeGen/RISCV/ntlh-intrinsics/riscv32-zihintntl.c
  clang/test/Preprocessor/riscv-target-features.c
  llvm/docs/RISCVUsage.rst
  llvm/docs/ReleaseNotes.rst
  llvm/lib/Support/RISCVISAInfo.cpp
  llvm/lib/Target/RISCV/RISCVFeatures.td
  llvm/test/CodeGen/RISCV/attributes.ll
  llvm/test/CodeGen/RISCV/nontemporal-scalable.ll
  llvm/test/CodeGen/RISCV/nontemporal.ll
  llvm/test/CodeGen/RISCV/prefetch.ll
  llvm/test/MC/RISCV/attribute-arch.s
  llvm/test/MC/RISCV/rv32zihintntl-invalid.s
  llvm/test/MC/RISCV/rv32zihintntl-valid.s
  llvm/test/MC/RISCV/rv32zihintntlc-invalid.s
  llvm/test/MC/RISCV/rv32zihintntlc-valid.s

Index: llvm/test/MC/RISCV/rv32zihintntlc-valid.s
===
--- llvm/test/MC/RISCV/rv32zihintntlc-valid.s
+++ llvm/test/MC/RISCV/rv32zihintntlc-valid.s
@@ -1,15 +1,15 @@
-# RUN: llvm-mc %s -triple=riscv32 -mattr=+experimental-zihintntl,+c -show-encoding \
+# RUN: llvm-mc %s -triple=riscv32 -mattr=+zihintntl,+c -show-encoding \
 # RUN: | FileCheck -check-prefixes=CHECK-ASM,CHECK-ASM-AND-OBJ %s
-# RUN: llvm-mc %s -triple=riscv64 -mattr=+experimental-zihintntl,+c -show-encoding \
+# RUN: llvm-mc %s -triple=riscv64 -mattr=+zihintntl,+c -show-encoding \
 # RUN: | FileCheck -check-prefixes=CHECK-ASM,CHECK-ASM-AND-OBJ %s
-# RUN: llvm-mc -filetype=obj -triple=riscv32 -mattr=+experimental-zihintntl,+c < %s \
-# RUN: | llvm-objdump --mattr=+experimental-zihintntl,+c -d -r - \
+# RUN: llvm-mc -filetype=obj -triple=riscv32 -mattr=+zihintntl,+c < %s \
+# RUN: | llvm-objdump --mattr=+zihintntl,+c -d -r - \
 # RUN: | FileCheck --check-prefix=CHECK-ASM-AND-OBJ %s
-# RUN: llvm-mc -filetype=obj -triple=riscv64 -mattr=+experimental-zihintntl,+c < %s \
-# RUN: | llvm-objdump --mattr=+experimental-zihintntl,+c -d -r - \
+# RUN: llvm-mc -filetype=obj -triple=riscv64 -mattr=+zihintntl,+c < %s \
+# RUN: | llvm-objdump --mattr=+zihintntl,+c -d -r - \
 # RUN: | FileCheck --check-prefix=CHECK-ASM-AND-OBJ %s
-# RUN: not llvm-mc %s -triple=riscv32 -mattr=+experimental-zihintntl 2>&1 | FileCheck -check-prefix=CHECK-NO-C %s
-# RUN: not llvm-mc %s -triple=riscv64 -mattr=+experimental-zihintntl 2>&1 | FileCheck -check-prefix=CHECK-NO-C %s
+# RUN: not llvm-mc %s -triple=riscv32 -mattr=+zihintntl 2>&1 | FileCheck -check-prefix=CHECK-NO-C %s
+# RUN: not llvm-mc %s -triple=riscv64 -mattr=+zihintntl 2>&1 | FileCheck -check-prefix=CHECK-NO-C %s
 
 # CHECK-ASM-AND-OBJ: ntl.p1
 # CHECK-ASM: encoding: [0x33,0x00,0x20,0x00]
Index: llvm/test/MC/RISCV/rv32zihintntlc-invalid.s
===
--- llvm/test/MC/RISCV/rv32zihintntlc-invalid.s
+++ llvm/test/MC/RISCV/rv32zihintntlc-invalid.s
@@ -1,5 +1,5 @@
-# RUN: not llvm-mc -triple riscv32 -mattr=+experimental-zihintntl,+c < %s 2>&1 | FileCheck %s
-# RUN: not llvm-mc -triple riscv64 -mattr=+experimental-zihintntl,+c < %s 2>&1 | FileCheck %s
+# RUN: not llvm-mc -triple riscv32 -mattr=+zihintntl,+c < %s 2>&1 | FileCheck %s
+# RUN: not llvm-mc -triple riscv64 -mattr=+zihintntl,+c < %s 2>&1 | FileCheck %s
 
 c.ntl.p1 1 # CHECK: :[[@LINE]]:10: error: invalid operand for instruction
 c.ntl.pall 2 # CHECK: :[[@LINE]]:12: error: invalid operand for instruction
Index: llvm/test/MC/RISCV/rv32zihintntl-valid.s
===
--- llvm/test/MC/RISCV/rv32zihintntl-valid.s
+++ llvm/test/MC/RISCV/rv32zihintntl-valid.s
@@ -1,12 +1,12 @@
-# RUN: llvm-mc %s -triple=riscv32 -mattr=+experimental-zihintntl -riscv-no-aliases -show-encoding \
+# RUN: llvm-mc %s -triple=riscv32 -mattr=+zihintntl -riscv-no-aliases -show-encoding \
 # RUN: | FileCheck -check-prefixes=CHECK-ASM,CHECK-ASM-AND-OBJ %s
-# RUN: llvm-mc %s -triple=riscv64 -mattr=+experimental-zihintntl -riscv-no-aliases -show-encoding \
+# RUN: llvm-mc %s -triple=riscv64 -mattr=+zihintntl -riscv-no-aliases -show-encoding \
 # RUN: | FileCheck -check-prefixes=CHECK-ASM,CHECK-ASM-AND-OBJ %s
-# RUN: llvm-mc -filetype=obj -triple=riscv32 -mattr=+experimental-zihintntl < %s \
-# RUN: | llvm-objdump --mattr=+experimental-zihintntl -M no-aliases -d -r - \
+# RUN: llvm-mc -filetype=obj -triple=riscv32 -mattr=+zihintntl < %s \
+# RUN: | llvm-objdump --mattr=+zihintntl -M no-aliases -d -r - \
 # RUN: | FileCheck --check-prefix=CHECK-ASM-AND-OBJ %s
-# RUN: llvm-mc -filetype=obj -triple=riscv64 -mattr=+experimental-zihintntl < %s \
-# RUN: | llvm-objdump --mattr=+experimental-zihintntl -M no-aliases -d -r - \
+# RUN: llvm-mc -filetype=obj -triple=riscv64 -mattr=+zihintntl < %s \
+# RUN: | llvm-objdump --mattr=+zihintntl -M no-aliases -d -r - \
 

[PATCH] D157441: [-Wunsafe-buffer-usage] Use `Strategy` to determine whether to fix a parameter

2023-08-09 Thread Ziqing Luo via Phabricator via cfe-commits
ziqingluo-90 added a comment.

>> Extend PointerAssignmentGadget and PointerInitGadget to generate fix-its for 
>> cases where the left-hand side 
>> has won't fix strategy and the right-hand side has std::span strategy.
>
> Hmm, is this intertwined with other changes, or is this completely separate? 
> Also my head appears to be blank;

The two `FixableGadget`s previously gave incorrect fix-its for the cases where 
only RHS need fix.  After the change made to `Strategy`, they returned 
`std::nullopt` as the case was not implemented.
So to avoid regression, I made the extension to the two Gadgets.

> did we reach any conclusion about the nature of "single" RHS-es and 
> usefulness of annotating them as such?
> Which could be an approach that would encourage people to propagate more 
> bounds in the backwards direction by default.

Can you elaborate the question a bit more?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157441

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


[clang] 4608686 - [clang][test] Fix LIT test failures for the following commit

2023-08-09 Thread Changpeng Fang via cfe-commits

Author: Changpeng Fang
Date: 2023-08-09T18:23:18-07:00
New Revision: 4608686849bcb6e20de827750862d5345cbd

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

LOG: [clang][test] Fix LIT test failures for the following commit

 commit c1803d5366c794ecade4e4ccd0013690a1976d49 (HEAD -> main, origin/main, 
origin/HEAD)
Author: Changpeng Fang 
Date:   Wed Aug 9 17:49:14 2023 -0700

[FunctionAttrs] Unconditionally perform argument attribute inference in the 
first function-attrs pass

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

Added: 


Modified: 
clang/test/CodeGenOpenCL/amdgpu-abi-struct-coerce.cl
clang/test/CodeGenOpenCL/kernel-param-alignment.cl

Removed: 




diff  --git a/clang/test/CodeGenOpenCL/amdgpu-abi-struct-coerce.cl 
b/clang/test/CodeGenOpenCL/amdgpu-abi-struct-coerce.cl
index 8c5ce6dfb704c6..1da27e54e6810d 100644
--- a/clang/test/CodeGenOpenCL/amdgpu-abi-struct-coerce.cl
+++ b/clang/test/CodeGenOpenCL/amdgpu-abi-struct-coerce.cl
@@ -307,7 +307,7 @@ void 
func_single_struct_element_struct_arg(single_struct_element_struct_arg_t ar
 // CHECK: void @func_
diff erent_size_type_pair_arg(i64 %arg1.coerce0, i32 %arg1.coerce1)
 void func_
diff erent_size_type_pair_arg(
diff erent_size_type_pair arg1) { }
 
-// CHECK: void @func_flexible_array_arg(ptr addrspace(5) nocapture noundef 
byval(%struct.flexible_array) align 4 %arg)
+// CHECK: void @func_flexible_array_arg(ptr addrspace(5) nocapture noundef 
readnone byval(%struct.flexible_array) align 4 %arg)
 void func_flexible_array_arg(flexible_array arg) { }
 
 // CHECK: define{{.*}} float @func_f32_ret()
@@ -448,11 +448,11 @@ flexible_array func_flexible_array_ret()
 // CHECK: define{{.*}} void @func_reg_state_lo(<4 x i32> noundef %arg0, <4 x 
i32> noundef %arg1, <4 x i32> noundef %arg2, i32 noundef %arg3, i32 %s.coerce0, 
float %s.coerce1, i32 %s.coerce2)
 void func_reg_state_lo(int4 arg0, int4 arg1, int4 arg2, int arg3, struct_arg_t 
s) { }
 
-// CHECK: define{{.*}} void @func_reg_state_hi(<4 x i32> noundef %arg0, <4 x 
i32> noundef %arg1, <4 x i32> noundef %arg2, i32 noundef %arg3, i32 noundef 
%arg4, ptr addrspace(5) nocapture noundef byval(%struct.struct_arg) align 4 %s)
+// CHECK: define{{.*}} void @func_reg_state_hi(<4 x i32> noundef %arg0, <4 x 
i32> noundef %arg1, <4 x i32> noundef %arg2, i32 noundef %arg3, i32 noundef 
%arg4, ptr addrspace(5) nocapture noundef readnone byval(%struct.struct_arg) 
align 4 %s)
 void func_reg_state_hi(int4 arg0, int4 arg1, int4 arg2, int arg3, int arg4, 
struct_arg_t s) { }
 
 // XXX - Why don't the inner structs flatten?
-// CHECK: define{{.*}} void @func_reg_state_num_regs_nested_struct(<4 x i32> 
noundef %arg0, i32 noundef %arg1, i32 %arg2.coerce0, %struct.nested 
%arg2.coerce1, i32 %arg3.coerce0, %struct.nested %arg3.coerce1, ptr 
addrspace(5) nocapture noundef byval(%struct.num_regs_nested_struct) align 8 
%arg4)
+// CHECK: define{{.*}} void @func_reg_state_num_regs_nested_struct(<4 x i32> 
noundef %arg0, i32 noundef %arg1, i32 %arg2.coerce0, %struct.nested 
%arg2.coerce1, i32 %arg3.coerce0, %struct.nested %arg3.coerce1, ptr 
addrspace(5) nocapture noundef readnone byval(%struct.num_regs_nested_struct) 
align 8 %arg4)
 void func_reg_state_num_regs_nested_struct(int4 arg0, int arg1, 
num_regs_nested_struct arg2, num_regs_nested_struct arg3, 
num_regs_nested_struct arg4) { }
 
 // CHECK: define{{.*}} void @func_double_nested_struct_arg(<4 x i32> noundef 
%arg0, i32 noundef %arg1, i32 %arg2.coerce0, %struct.double_nested 
%arg2.coerce1, i16 %arg2.coerce2)
@@ -477,7 +477,7 @@ void v3i32_reg_count(int3 arg1, int3 arg2, int3 arg3, int3 
arg4, struct_arg_t ar
 
 // Function signature from blender, nothing should be passed byval. The v3i32
 // should not count as 4 passed registers.
-// CHECK: define{{.*}} void @v3i32_pair_reg_count(ptr addrspace(5) nocapture 
noundef %arg0, <3 x i32> %arg1.coerce0, <3 x i32> %arg1.coerce1, <3 x i32> 
noundef %arg2, <3 x i32> %arg3.coerce0, <3 x i32> %arg3.coerce1, <3 x i32> 
noundef %arg4, float noundef %arg5)
+// CHECK: define{{.*}} void @v3i32_pair_reg_count(ptr addrspace(5) nocapture 
noundef readnone %arg0, <3 x i32> %arg1.coerce0, <3 x i32> %arg1.coerce1, <3 x 
i32> noundef %arg2, <3 x i32> %arg3.coerce0, <3 x i32> %arg3.coerce1, <3 x i32> 
noundef %arg4, float noundef %arg5)
 void v3i32_pair_reg_count(int3_pair *arg0, int3_pair arg1, int3 arg2, 
int3_pair arg3, int3 arg4, float arg5) { }
 
 // Each short4 should fit pack into 2 registers.
@@ -485,7 +485,7 @@ void v3i32_pair_reg_count(int3_pair *arg0, int3_pair arg1, 
int3 arg2, int3_pair
 void v4i16_reg_count(short4 arg0, short4 arg1, short4 arg2, short4 arg3,
  short4 arg4, short4 arg5, struct_4regs arg6) { }
 
-// CHECK: define{{.*}} void 

[PATCH] D157474: [RISCV] Add missing Xsfvcp extension check in clang sema

2023-08-09 Thread Brandon Wu via Phabricator via cfe-commits
4vtomat marked an inline comment as done.
4vtomat added inline comments.



Comment at: clang/test/Sema/rvv-required-features-invalid.c:16
+void test_sf_vc_x_se_u64m1(uint64_t rs1, size_t vl) { // expected-note 
{{'test_sf_vc_x_se_u64m1' declared here}}
+  __riscv_sf_vc_x_se_u64m1(1, 1, 1, rs1, vl); // expected-error {{call to 
undeclared function '__riscv_sf_vc_x_se_u64m1'}} expected-note {{did you mean 
'test_sf_vc_x_se_u64m1'?}}
+}

craig.topper wrote:
> This doesn't mention the xsfvcp extension. So it doesn't look like the 
> diagnostic in the code is being hit.
I guess it's just because `__riscv_sf_vc_x_se_u64m1` is too similar to 
`test_sf_vc_x_se_u64m1`, I just changed the name of the function, and the 
diagnostic just disappeared.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157474

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


[PATCH] D157474: [RISCV] Add missing Xsfvcp extension check in clang sema

2023-08-09 Thread Brandon Wu via Phabricator via cfe-commits
4vtomat updated this revision to Diff 548843.
4vtomat added a comment.

Rename the function in the test case.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157474

Files:
  clang/lib/Sema/SemaRISCVVectorLookup.cpp
  clang/test/Sema/rvv-required-features-invalid.c
  clang/test/Sema/rvv-required-features.c


Index: clang/test/Sema/rvv-required-features.c
===
--- /dev/null
+++ clang/test/Sema/rvv-required-features.c
@@ -0,0 +1,19 @@
+// REQUIRES: riscv-registered-target
+// RUN: %clang_cc1 -triple riscv64 -target-feature +v -target-feature +xsfvcp 
%s -fsyntax-only -verify
+
+// expected-no-diagnostics
+
+#include 
+#include 
+
+vint8m1_t test_vloxei64_v_i8m1(const int8_t *base, vuint64m8_t bindex, size_t 
vl) {
+  return __riscv_vloxei64(base, bindex, vl);
+}
+
+void test_vsoxei64_v_i8m1(int8_t *base, vuint64m8_t bindex, vint8m1_t value, 
size_t vl) {
+  __riscv_vsoxei64(base, bindex, value, vl);
+}
+
+void test_sf_vc_x_se_u64m1(uint64_t rs1, size_t vl) {
+  __riscv_sf_vc_x_se_u64m1(1, 1, 1, rs1, vl);
+}
Index: clang/test/Sema/rvv-required-features-invalid.c
===
--- /dev/null
+++ clang/test/Sema/rvv-required-features-invalid.c
@@ -0,0 +1,17 @@
+// REQUIRES: riscv-registered-target
+// RUN: %clang_cc1 -triple riscv32 -target-feature +v %s -fsyntax-only -verify
+
+#include 
+#include 
+
+vint8m1_t test_vloxei64_v_i8m1(const int8_t *base, vuint64m8_t bindex, size_t 
vl) {
+  return __riscv_vloxei64(base, bindex, vl); // expected-error {{call to 
undeclared function '__riscv_vloxei64'}} expected-error {{returning 'int' from 
a function with incompatible result type 'vint8m1_t'}}
+}
+
+void test_vsoxei64_v_i8m1(int8_t *base, vuint64m8_t bindex, vint8m1_t value, 
size_t vl) {
+  __riscv_vsoxei64(base, bindex, value, vl); // expected-error {{call to 
undeclared function '__riscv_vsoxei64'}}
+}
+
+void test_xsfvcp_sf_vc_x_se_u64m1(uint64_t rs1, size_t vl) {
+  __riscv_sf_vc_x_se_u64m1(1, 1, 1, rs1, vl); // expected-error {{call to 
undeclared function '__riscv_sf_vc_x_se_u64m1'}}
+}
Index: clang/lib/Sema/SemaRISCVVectorLookup.cpp
===
--- clang/lib/Sema/SemaRISCVVectorLookup.cpp
+++ clang/lib/Sema/SemaRISCVVectorLookup.cpp
@@ -202,10 +202,20 @@
 void RISCVIntrinsicManagerImpl::ConstructRVVIntrinsics(
 ArrayRef Recs, IntrinsicKind K) {
   const TargetInfo  = Context.getTargetInfo();
-  bool HasRV64 = TI.hasFeature("64bit");
+  static const std::pair FeatureCheckList[] = {
+  {"64bit", RVV_REQ_RV64},
+  {"xsfvcp", RVV_REQ_Xsfvcp}};
+
   // Construction of RVVIntrinsicRecords need to sync with createRVVIntrinsics
   // in RISCVVEmitter.cpp.
   for (auto  : Recs) {
+// Check requirements.
+if (llvm::any_of(FeatureCheckList, [&](const auto ) {
+  return (Record.RequiredExtensions & Item.second) == Item.second &&
+ !TI.hasFeature(Item.first);
+}))
+  continue;
+
 // Create Intrinsics for each type and LMUL.
 BasicType BaseType = BasicType::Unknown;
 ArrayRef BasicProtoSeq =
@@ -251,11 +261,6 @@
   if ((BaseTypeI & Record.TypeRangeMask) != BaseTypeI)
 continue;
 
-  // Check requirement.
-  if (((Record.RequiredExtensions & RVV_REQ_RV64) == RVV_REQ_RV64) &&
-  !HasRV64)
-continue;
-
   // Expanded with different LMUL.
   for (int Log2LMUL = -3; Log2LMUL <= 3; Log2LMUL++) {
 if (!(Record.Log2LMULMask & (1 << (Log2LMUL + 3


Index: clang/test/Sema/rvv-required-features.c
===
--- /dev/null
+++ clang/test/Sema/rvv-required-features.c
@@ -0,0 +1,19 @@
+// REQUIRES: riscv-registered-target
+// RUN: %clang_cc1 -triple riscv64 -target-feature +v -target-feature +xsfvcp %s -fsyntax-only -verify
+
+// expected-no-diagnostics
+
+#include 
+#include 
+
+vint8m1_t test_vloxei64_v_i8m1(const int8_t *base, vuint64m8_t bindex, size_t vl) {
+  return __riscv_vloxei64(base, bindex, vl);
+}
+
+void test_vsoxei64_v_i8m1(int8_t *base, vuint64m8_t bindex, vint8m1_t value, size_t vl) {
+  __riscv_vsoxei64(base, bindex, value, vl);
+}
+
+void test_sf_vc_x_se_u64m1(uint64_t rs1, size_t vl) {
+  __riscv_sf_vc_x_se_u64m1(1, 1, 1, rs1, vl);
+}
Index: clang/test/Sema/rvv-required-features-invalid.c
===
--- /dev/null
+++ clang/test/Sema/rvv-required-features-invalid.c
@@ -0,0 +1,17 @@
+// REQUIRES: riscv-registered-target
+// RUN: %clang_cc1 -triple riscv32 -target-feature +v %s -fsyntax-only -verify
+
+#include 
+#include 
+
+vint8m1_t test_vloxei64_v_i8m1(const int8_t *base, vuint64m8_t bindex, size_t vl) {
+  return __riscv_vloxei64(base, bindex, vl); // expected-error {{call to undeclared function '__riscv_vloxei64'}} 

[PATCH] D156749: [modules] Fix error about the same module being defined in different .pcm files when using VFS overlays.

2023-08-09 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai added a comment.

In D156749#4565994 , @jansvoboda11 
wrote:

> I think your solution is the most pragmatic. If you're confident this doesn't 
> break anything internally, I say go for it. But I think it's good to be aware 
> of the pitfall I mentioned, and make sure the build system doesn't trigger 
> that.

As far as I have tested, it isn't breaking anything.




Comment at: clang/lib/Serialization/ASTWriter.cpp:1330
 AddPath(WritingModule->PresumedModuleMapFile.empty()
-? Map.getModuleMapFileForUniquing(WritingModule)->getName()
+? Map.getModuleMapFileForUniquing(WritingModule)
+  ->getNameAsRequested()

jansvoboda11 wrote:
> Can we canonicalize this also? It'd be useful in the scanner.
I'm not sure about that. ASTReader has some complicated logic around reading 
this value 
https://github.com/llvm/llvm-project/blob/c1803d5366c794ecade4e4ccd0013690a1976d49/clang/lib/Serialization/ASTReader.cpp#L4005
 So if we don't have a proven need for it with a test case, I wouldn't change 
it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156749

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


[PATCH] D157568: [clang-format] Handle NamespaceMacro string arg for FixNamespaceComments

2023-08-09 Thread Owen Pan via Phabricator via cfe-commits
owenpan created this revision.
Herald added projects: All, clang, clang-format.
Herald added a subscriber: cfe-commits.
Herald added reviewers: rymiel, HazardyKnusperkeks, MyDeveloperDay.
owenpan requested review of this revision.

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


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D157568

Files:
  clang/lib/Format/NamespaceEndCommentsFixer.cpp
  clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp


Index: clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
===
--- clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
+++ clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
@@ -40,8 +40,30 @@
 Code,
 /*Ranges=*/{1, tooling::Range(0, Code.size())}, Style);
   }
+
+  bool isFormatted(StringRef Code, const std::vector ,
+   const FormatStyle  = getLLVMStyle()) const {
+return clang::format::fixNamespaceEndComments(Style, Code, Ranges,
+  "")
+.empty();
+  }
+
+  bool isFormatted(StringRef Code,
+   const FormatStyle  = getLLVMStyle()) const {
+return isFormatted(Code, {1, tooling::Range(0, Code.size())}, Style);
+  }
 };
 
+TEST_F(NamespaceEndCommentsFixerTest, IsFormatted) {
+  auto Style = getLLVMStyle();
+  Style.NamespaceMacros.push_back("SUITE");
+  EXPECT_TRUE(isFormatted("SUITE(\"foo\") {\n"
+  "int i;\n"
+  "int j;\n"
+  "} // SUITE(\"foo\")",
+  Style));
+}
+
 TEST_F(NamespaceEndCommentsFixerTest, AddsEndComment) {
   EXPECT_EQ("namespace {\n"
 "int i;\n"
Index: clang/lib/Format/NamespaceEndCommentsFixer.cpp
===
--- clang/lib/Format/NamespaceEndCommentsFixer.cpp
+++ clang/lib/Format/NamespaceEndCommentsFixer.cpp
@@ -174,7 +174,8 @@
   llvm::Regex::IgnoreCase);
   static const llvm::Regex NamespaceMacroCommentPattern =
   llvm::Regex("^/[/*] *(end (of )?)? *(anonymous|unnamed)? *"
-  "([a-zA-Z0-9_]+)\\(([a-zA-Z0-9:_]*)\\)\\.? *(\\*/)?$",
+  // NamespaceMacro arguments can also be string literals.
+  "([a-zA-Z0-9_]+)\\(([a-zA-Z0-9:_]*|\".+\")\\)\\.? *(\\*/)?$",
   llvm::Regex::IgnoreCase);
 
   SmallVector Groups;


Index: clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
===
--- clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
+++ clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
@@ -40,8 +40,30 @@
 Code,
 /*Ranges=*/{1, tooling::Range(0, Code.size())}, Style);
   }
+
+  bool isFormatted(StringRef Code, const std::vector ,
+   const FormatStyle  = getLLVMStyle()) const {
+return clang::format::fixNamespaceEndComments(Style, Code, Ranges,
+  "")
+.empty();
+  }
+
+  bool isFormatted(StringRef Code,
+   const FormatStyle  = getLLVMStyle()) const {
+return isFormatted(Code, {1, tooling::Range(0, Code.size())}, Style);
+  }
 };
 
+TEST_F(NamespaceEndCommentsFixerTest, IsFormatted) {
+  auto Style = getLLVMStyle();
+  Style.NamespaceMacros.push_back("SUITE");
+  EXPECT_TRUE(isFormatted("SUITE(\"foo\") {\n"
+  "int i;\n"
+  "int j;\n"
+  "} // SUITE(\"foo\")",
+  Style));
+}
+
 TEST_F(NamespaceEndCommentsFixerTest, AddsEndComment) {
   EXPECT_EQ("namespace {\n"
 "int i;\n"
Index: clang/lib/Format/NamespaceEndCommentsFixer.cpp
===
--- clang/lib/Format/NamespaceEndCommentsFixer.cpp
+++ clang/lib/Format/NamespaceEndCommentsFixer.cpp
@@ -174,7 +174,8 @@
   llvm::Regex::IgnoreCase);
   static const llvm::Regex NamespaceMacroCommentPattern =
   llvm::Regex("^/[/*] *(end (of )?)? *(anonymous|unnamed)? *"
-  "([a-zA-Z0-9_]+)\\(([a-zA-Z0-9:_]*)\\)\\.? *(\\*/)?$",
+  // NamespaceMacro arguments can also be string literals.
+  "([a-zA-Z0-9_]+)\\(([a-zA-Z0-9:_]*|\".+\")\\)\\.? *(\\*/)?$",
   llvm::Regex::IgnoreCase);
 
   SmallVector Groups;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D157566: [SEH] fix assertion when -fasy-exceptions is used.

2023-08-09 Thread Jennifer Yu via Phabricator via cfe-commits
jyu2 created this revision.
jyu2 added reviewers: asmith, tentzen, rnk, efriedma, pengfei.
jyu2 added a project: clang.
Herald added a project: All.
jyu2 requested review of this revision.

The assertion only happens with use of -fasy-exception without
-fexcessions.

The assertion appen during the call to generate SehScopeBegin(), where
assert with:
assert(CGF.Builder.GetInsertBlock() && InvokeDest);
InvokeDest is null. Because exceptions are disabled, and SEH is not
in use.
The fix is before call EmitSehCppScopeBegin check getInvokeDest(),
to avoid assert during the emit llvm.seh.scope.begin()


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D157566

Files:
  clang/lib/CodeGen/CGCleanup.cpp
  clang/test/CodeGen/windows-seh-async-exceptions.cpp


Index: clang/test/CodeGen/windows-seh-async-exceptions.cpp
===
--- /dev/null
+++ clang/test/CodeGen/windows-seh-async-exceptions.cpp
@@ -0,0 +1,23 @@
+// RUN: %clang_cc1 -triple x86_64-windows -fasync-exceptions -x c++ \
+// RUN:  -emit-llvm %s -o -| FileCheck %s
+
+
+extern "C" int printf(const char*,...);
+class PrintfArg
+{
+public:
+PrintfArg();
+PrintfArg(const char* s);
+
+// compiler crash fixed if this destructor removed
+~PrintfArg() {int x; printf("ddd\n");  }
+};
+
+void devif_Warning(const char* fmt, PrintfArg arg1 = PrintfArg());
+// CHECK-NOT: invoke void @llvm.seh.scope.begin()
+// CHECK-NOT: invoke void @llvm.seh.scope.end()
+unsigned myfunc(unsigned index)
+{
+devif_Warning("");
+return 0;
+}
Index: clang/lib/CodeGen/CGCleanup.cpp
===
--- clang/lib/CodeGen/CGCleanup.cpp
+++ clang/lib/CodeGen/CGCleanup.cpp
@@ -207,8 +207,13 @@
 Scope->setLifetimeMarker();
 
   // With Windows -EHa, Invoke llvm.seh.scope.begin() for EHCleanup
+  // If exceptions are disabled/ignored and SEH is not in use, then there is no
+  // invoke destination. SEH "works" even if exceptions are off. In practice,
+  // this means that C++ destructors and other EH cleanups don't run, which is
+  // consistent with MSVC's behavior, except in the presence of -EHa.
+  // Check getInvokeDest() to generate llvm.seh.scope.begin() as needed.
   if (CGF->getLangOpts().EHAsynch && IsEHCleanup && !IsLifetimeMarker &&
-  CGF->getTarget().getCXXABI().isMicrosoft())
+  CGF->getTarget().getCXXABI().isMicrosoft() && CGF->getInvokeDest())
 CGF->EmitSehCppScopeBegin();
 
   return Scope->getCleanupBuffer();


Index: clang/test/CodeGen/windows-seh-async-exceptions.cpp
===
--- /dev/null
+++ clang/test/CodeGen/windows-seh-async-exceptions.cpp
@@ -0,0 +1,23 @@
+// RUN: %clang_cc1 -triple x86_64-windows -fasync-exceptions -x c++ \
+// RUN:  -emit-llvm %s -o -| FileCheck %s
+
+
+extern "C" int printf(const char*,...);
+class PrintfArg
+{
+public:
+PrintfArg();
+PrintfArg(const char* s);
+
+// compiler crash fixed if this destructor removed
+~PrintfArg() {int x; printf("ddd\n");  }
+};
+
+void devif_Warning(const char* fmt, PrintfArg arg1 = PrintfArg());
+// CHECK-NOT: invoke void @llvm.seh.scope.begin()
+// CHECK-NOT: invoke void @llvm.seh.scope.end()
+unsigned myfunc(unsigned index)
+{
+devif_Warning("");
+return 0;
+}
Index: clang/lib/CodeGen/CGCleanup.cpp
===
--- clang/lib/CodeGen/CGCleanup.cpp
+++ clang/lib/CodeGen/CGCleanup.cpp
@@ -207,8 +207,13 @@
 Scope->setLifetimeMarker();
 
   // With Windows -EHa, Invoke llvm.seh.scope.begin() for EHCleanup
+  // If exceptions are disabled/ignored and SEH is not in use, then there is no
+  // invoke destination. SEH "works" even if exceptions are off. In practice,
+  // this means that C++ destructors and other EH cleanups don't run, which is
+  // consistent with MSVC's behavior, except in the presence of -EHa.
+  // Check getInvokeDest() to generate llvm.seh.scope.begin() as needed.
   if (CGF->getLangOpts().EHAsynch && IsEHCleanup && !IsLifetimeMarker &&
-  CGF->getTarget().getCXXABI().isMicrosoft())
+  CGF->getTarget().getCXXABI().isMicrosoft() && CGF->getInvokeDest())
 CGF->EmitSehCppScopeBegin();
 
   return Scope->getCleanupBuffer();
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D157149: [Option] Add "Visibility" field and clone the OptTable APIs to use it

2023-08-09 Thread Justin Bogner via Phabricator via cfe-commits
bogner updated this revision to Diff 548832.
bogner added a comment.

Rebase/resolve conflicts


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157149

Files:
  clang-tools-extra/clangd/CompileCommands.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  lld/MachO/DriverUtils.cpp
  lld/MinGW/Driver.cpp
  lld/wasm/Driver.cpp
  llvm/include/llvm/Option/OptParser.td
  llvm/include/llvm/Option/OptTable.h
  llvm/include/llvm/Option/Option.h
  llvm/lib/ExecutionEngine/JITLink/COFFDirectiveParser.cpp
  llvm/lib/Option/OptTable.cpp
  llvm/lib/ToolDrivers/llvm-dlltool/DlltoolDriver.cpp
  llvm/lib/ToolDrivers/llvm-lib/LibDriver.cpp
  llvm/tools/dsymutil/dsymutil.cpp
  llvm/tools/llvm-cvtres/llvm-cvtres.cpp
  llvm/tools/llvm-cxxfilt/llvm-cxxfilt.cpp
  llvm/tools/llvm-debuginfod/llvm-debuginfod.cpp
  llvm/tools/llvm-dwarfutil/llvm-dwarfutil.cpp
  llvm/tools/llvm-dwp/llvm-dwp.cpp
  llvm/tools/llvm-lipo/llvm-lipo.cpp
  llvm/tools/llvm-mt/llvm-mt.cpp
  llvm/tools/llvm-objcopy/ObjcopyOptions.cpp
  llvm/tools/llvm-rc/llvm-rc.cpp
  llvm/tools/llvm-strings/llvm-strings.cpp
  llvm/tools/llvm-symbolizer/llvm-symbolizer.cpp
  llvm/tools/llvm-tli-checker/llvm-tli-checker.cpp
  llvm/unittests/Option/OptionMarshallingTest.cpp
  llvm/unittests/Option/OptionParsingTest.cpp
  llvm/unittests/Option/Opts.td
  llvm/utils/TableGen/OptParserEmitter.cpp

Index: llvm/utils/TableGen/OptParserEmitter.cpp
===
--- llvm/utils/TableGen/OptParserEmitter.cpp
+++ llvm/utils/TableGen/OptParserEmitter.cpp
@@ -320,7 +320,7 @@
   OS << "INVALID";
 
 // The other option arguments (unused for groups).
-OS << ", INVALID, nullptr, 0, 0";
+OS << ", INVALID, nullptr, 0, 0, 0";
 
 // The option help text.
 if (!isa(R.getValueInit("HelpText"))) {
@@ -358,8 +358,10 @@
 // The containing option group (if any).
 OS << ", ";
 const ListInit *GroupFlags = nullptr;
+const ListInit *GroupVis = nullptr;
 if (const DefInit *DI = dyn_cast(R.getValueInit("Group"))) {
   GroupFlags = DI->getDef()->getValueAsListInit("Flags");
+  GroupVis = DI->getDef()->getValueAsListInit("Vis");
   OS << getOptionName(*DI->getDef());
 } else
   OS << "INVALID";
@@ -400,6 +402,21 @@
 if (NumFlags == 0)
   OS << '0';
 
+// The option visibility flags.
+OS << ", ";
+int NumVisFlags = 0;
+LI = R.getValueAsListInit("Vis");
+for (Init *I : *LI)
+  OS << (NumVisFlags++ ? " | " : "")
+ << cast(I)->getDef()->getName();
+if (GroupVis) {
+  for (Init *I : *GroupVis)
+OS << (NumVisFlags++ ? " | " : "")
+   << cast(I)->getDef()->getName();
+}
+if (NumVisFlags == 0)
+  OS << '0';
+
 // The option parameter field.
 OS << ", " << R.getValueAsInt("NumArgs");
 
Index: llvm/unittests/Option/Opts.td
===
--- llvm/unittests/Option/Opts.td
+++ llvm/unittests/Option/Opts.td
@@ -4,6 +4,8 @@
 def OptFlag2 : OptionFlag;
 def OptFlag3 : OptionFlag;
 
+def SubtoolVis : OptionVisibility;
+
 def A : Flag<["-"], "A">, HelpText<"The A option">, Flags<[OptFlag1]>;
 def AB : Flag<["-"], "AB">;
 def B : Joined<["-"], "B">, HelpText<"The B option">, MetaVarName<"B">, Flags<[OptFlag2]>;
@@ -35,6 +37,8 @@
 def Cramb : Joined<["/"], "cramb:">, HelpText<"The cramb option">, MetaVarName<"CRAMB">, Flags<[OptFlag1]>;
 def Doopf1 : Flag<["-"], "doopf1">, HelpText<"The doopf1 option">, Flags<[OptFlag1]>;
 def Doopf2 : Flag<["-"], "doopf2">, HelpText<"The doopf2 option">, Flags<[OptFlag2]>;
+def Xyzzy1 : Flag<["-"], "xyzzy1">, HelpText<"The xyzzy1 option">, Vis<[SubtoolVis]>;
+def Xyzzy2 : Flag<["-"], "xyzzy2">, HelpText<"The xyzzy2 option">, Vis<[Default]>;
 def Ermgh : Joined<["--"], "ermgh">, HelpText<"The ermgh option">, MetaVarName<"ERMGH">, Flags<[OptFlag1]>;
 def Fjormp : Flag<["--"], "fjormp">, HelpText<"The fjormp option">, Flags<[OptFlag1]>;
 
@@ -43,6 +47,9 @@
 def Blurmpq : Flag<["--"], "blurmp">;
 def Blurmpq_eq : Flag<["--"], "blurmp=">;
 
+def Q : Flag<["-"], "Q">, Vis<[SubtoolVis]>;
+def R : Flag<["-"], "R">, Vis<[Default, SubtoolVis]>;
+
 class XOpts : KeyPathAndMacro<"X->", base> {}
 
 def marshalled_flag_d : Flag<["-"], "marshalled-flag-d">,
Index: llvm/unittests/Option/OptionParsingTest.cpp
===
--- llvm/unittests/Option/OptionParsingTest.cpp
+++ llvm/unittests/Option/OptionParsingTest.cpp
@@ -44,6 +44,10 @@
   OptFlag3 = (1 << 6)
 };
 
+enum OptionVisibility {
+  SubtoolVis = (1 << 2),
+};
+
 static constexpr OptTable::Info InfoTable[] = {
 #define OPTION(...) LLVM_CONSTRUCT_OPT_INFO(__VA_ARGS__),
 #include "Opts.inc"
@@ -163,6 +167,43 @@
   EXPECT_EQ("bar", AL.getLastArgValue(OPT_C));
 }
 
+TYPED_TEST(OptTableTest, ParseWithVisibility) {
+  TypeParam T;
+  unsigned MAI, MAC;
+
+  const char 

[PATCH] D152436: [clang][analyzer] Move checker alpha.unix.StdCLibraryFunctions out of alpha.

2023-08-09 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added a comment.

It doesn't have to be in `core` just because it's dealing with "core features" 
of the language.

The `core` package is for checks without which path-sensitive analysis becomes 
//so incredibly incorrect// that we don't want to support such configuration, 
we don't want our users to ever use it.

(Ideally `core` checkers shouldn't emit any warnings at all. It has to be 
possible to disable every particular warning and still have other warnings work 
correctly. But unfortunately that's not the reality of the situation.)

(I agree `unix` doesn't sound right though. But we already have `MallocChecker` 
in `unix`, which is arguably way worse. What we really need is, to replace our 
package system with a hashtag system.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152436

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


[PATCH] D152770: [clang][ExtractAPI] Add support for Objective-C categories

2023-08-09 Thread R4444 via Phabricator via cfe-commits
Ruturaj4 updated this revision to Diff 548825.
Ruturaj4 added a comment.

- [clang][ExtractAPI] Add support for Objective-C categories
- [clang][ExtractAPI] Add support for Objective-C categories
- [clang][ExtractAPI] Add support for Objective-C categories
- [clang][ExtractAPI] Add support for Objective-C categories

1. Updating D152770 : [clang][ExtractAPI] Add 
support for Objective-C categories #
2. Enter a brief description of the changes included in this update.
3. The first line is used as subject, next lines as comment. #
4. If you intended to create a new revision, use:
5. $ arc diff --create

Fix test cases, and simulate the library interface.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152770

Files:
  clang/include/clang/ExtractAPI/API.h
  clang/include/clang/ExtractAPI/ExtractAPIVisitor.h
  clang/include/clang/ExtractAPI/Serialization/SerializerBase.h
  clang/include/clang/ExtractAPI/Serialization/SymbolGraphSerializer.h
  clang/lib/ExtractAPI/API.cpp
  clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
  clang/test/ExtractAPI/objc_module_category.m
  clang/test/ExtractAPI/objc_various_categories.m

Index: clang/test/ExtractAPI/objc_various_categories.m
===
--- /dev/null
+++ clang/test/ExtractAPI/objc_various_categories.m
@@ -0,0 +1,675 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: sed -e "s@INPUT_DIR@%{/t:regex_replacement}@g" \
+// RUN: %t/reference.output.json.in >> %t/reference.output.json
+// RUN: %clang -extract-api -x objective-c-header \
+// RUN: -target arm64-apple-macosx \
+// RUN: %t/myclass_1.h \
+// RUN: %t/input.h -o %t/output.json | FileCheck -allow-empty %s
+
+// Generator version is not consistent across test runs, normalize it.
+// RUN: sed -e "s@\"generator\": \".*\"@\"generator\": \"?\"@g" \
+// RUN: %t/output.json >> %t/output-normalized.json
+// RUN: diff %t/reference.output.json %t/output-normalized.json
+
+// CHECK-NOT: error:
+// CHECK-NOT: warning:
+
+//--- input.h
+#import "myclass_1.h"
+#import "myclass_2.h"
+#import "Foundation.h"
+
+@interface MyClass1 (MyCategory1)
+- (int) SomeMethod;
+@end
+
+@interface MyClass2 (MyCategory2)
+- (int) SomeMethod2;
+@end
+
+@interface NSString (Category1)
+-(void) StringMethod;
+@end
+
+@interface NSString (Category2)
+-(void) StringMethod2;
+@end
+
+//--- myclass_1.h
+@interface MyClass1
+@end
+
+//--- myclass_2.h
+@interface MyClass2
+@end
+
+//--- Foundation.h
+@interface NSString
+@end
+
+//--- reference.output.json.in
+{
+  "metadata": {
+"formatVersion": {
+  "major": 0,
+  "minor": 5,
+  "patch": 3
+},
+"generator": "?"
+  },
+  "module": {
+"name": "",
+"platform": {
+  "architecture": "arm64",
+  "operatingSystem": {
+"minimumVersion": {
+  "major": 11,
+  "minor": 0,
+  "patch": 0
+},
+"name": "macosx"
+  },
+  "vendor": "apple"
+}
+  },
+  "relationships": [
+{
+  "kind": "memberOf",
+  "source": "c:objc(cs)MyClass1(im)SomeMethod",
+  "target": "c:objc(cs)MyClass1",
+  "targetFallback": "MyClass1"
+},
+{
+  "kind": "extensionTo",
+  "source": "c:objc(cy)MyClass2@MyCategory2",
+  "target": "c:objc(cs)MyClass2",
+  "targetFallback": "MyClass2"
+},
+{
+  "kind": "memberOf",
+  "source": "c:objc(cs)MyClass2(im)SomeMethod2",
+  "target": "c:objc(cy)MyClass2@MyCategory2",
+  "targetFallback": "MyCategory2"
+},
+{
+  "kind": "extensionTo",
+  "source": "c:objc(cy)NSString@Category1",
+  "target": "c:objc(cs)NSString",
+  "targetFallback": "NSString"
+},
+{
+  "kind": "memberOf",
+  "source": "c:objc(cs)NSString(im)StringMethod",
+  "target": "c:objc(cy)NSString@Category1",
+  "targetFallback": "Category1"
+},
+{
+  "kind": "extensionTo",
+  "source": "c:objc(cy)NSString@Category2",
+  "target": "c:objc(cs)NSString",
+  "targetFallback": "NSString"
+},
+{
+  "kind": "memberOf",
+  "source": "c:objc(cs)NSString(im)StringMethod2",
+  "target": "c:objc(cy)NSString@Category2",
+  "targetFallback": "Category2"
+}
+  ],
+  "symbols": [
+{
+  "accessLevel": "public",
+  "declarationFragments": [
+{
+  "kind": "keyword",
+  "spelling": "@interface"
+},
+{
+  "kind": "text",
+  "spelling": " "
+},
+{
+  "kind": "identifier",
+  "spelling": "MyClass1"
+}
+  ],
+  "identifier": {
+"interfaceLanguage": "objective-c",
+"precise": "c:objc(cs)MyClass1"
+  },
+  "kind": {
+"displayName": "Class",
+"identifier": "objective-c.class"
+  },
+  "location": {
+"position": {
+  "character": 12,
+ 

[PATCH] D157296: [AST][Coroutine] Fix CoyieldExpr missing end loc

2023-08-09 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG8d60e10ce4bd: [AST][Coroutine] Fix CoyieldExpr missing end 
loc (authored by dingfei fd...@feysh.com).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157296

Files:
  clang/lib/Sema/SemaCoroutine.cpp
  clang/test/AST/Inputs/std-coroutine.h
  clang/test/AST/coroutine-co_yield-source-range.cpp


Index: clang/test/AST/coroutine-co_yield-source-range.cpp
===
--- /dev/null
+++ clang/test/AST/coroutine-co_yield-source-range.cpp
@@ -0,0 +1,49 @@
+// RUN: %clang_cc1 -triple x86_64-apple-darwin9 %s -std=c++20 \
+// RUN:-fsyntax-only -ast-dump | FileCheck %s
+
+#include "Inputs/std-coroutine.h"
+
+using namespace std;
+
+struct Chat {
+  struct promise_type {
+std::suspend_always initial_suspend() { return {}; }
+Chat get_return_object() {
+  return std::coroutine_handle::from_promise(*this);
+}
+std::suspend_always yield_value(int m) { return {}; }
+std::suspend_always final_suspend() noexcept { return {}; }
+std::suspend_always return_value(int) { return {}; }
+void unhandled_exception() {}
+
+auto await_transform(int s) {
+  struct awaiter {
+promise_type *promise;
+bool await_ready() { return true; }
+int await_resume() { return promise->message; }
+void await_suspend(std::coroutine_handle<>) {}
+  };
+
+  return awaiter{this};
+}
+int message;
+  };
+
+  Chat(std::coroutine_handle promise);
+
+  std::coroutine_handle handle;
+};
+
+Chat f(int s)  {
+  // CHECK:  CoyieldExpr {{.*}} 
+  // CHECK-NEXT:   CXXMemberCallExpr {{.*}}  {{.*}}
+  // CHECK-NEXT: MemberExpr {{.*}}  {{.*}}
+  // CHECK-NEXT:   DeclRefExpr {{.*}}  {{.*}}
+  // CHECK-NEXT: ImplicitCastExpr {{.*}}  {{.*}}
+  // CHECK-NEXT:   DeclRefExpr {{.*}}  {{.*}}
+  co_yield s;
+  // CHECK:  CoreturnStmt {{.*}} 
+  co_return s;
+  // CHECK:  CoawaitExpr {{.*}}  'int'
+  co_await s;
+}
Index: clang/test/AST/Inputs/std-coroutine.h
===
--- clang/test/AST/Inputs/std-coroutine.h
+++ clang/test/AST/Inputs/std-coroutine.h
@@ -55,9 +55,9 @@
 };
 
 struct suspend_always {
-  bool await_ready() { return false; }
-  void await_suspend(coroutine_handle<>) {}
-  void await_resume() {}
+  bool await_ready() noexcept { return false; }
+  void await_suspend(coroutine_handle<>) noexcept {}
+  void await_resume() noexcept {}
 };
 
 struct suspend_never {
Index: clang/lib/Sema/SemaCoroutine.cpp
===
--- clang/lib/Sema/SemaCoroutine.cpp
+++ clang/lib/Sema/SemaCoroutine.cpp
@@ -318,7 +318,8 @@
 return ExprError();
   }
 
-  return S.BuildCallExpr(nullptr, Result.get(), Loc, Args, Loc, nullptr);
+  auto EndLoc = Args.empty() ? Loc : Args.back()->getEndLoc();
+  return S.BuildCallExpr(nullptr, Result.get(), Loc, Args, EndLoc, nullptr);
 }
 
 // See if return type is coroutine-handle and if so, invoke builtin coro-resume


Index: clang/test/AST/coroutine-co_yield-source-range.cpp
===
--- /dev/null
+++ clang/test/AST/coroutine-co_yield-source-range.cpp
@@ -0,0 +1,49 @@
+// RUN: %clang_cc1 -triple x86_64-apple-darwin9 %s -std=c++20 \
+// RUN:-fsyntax-only -ast-dump | FileCheck %s
+
+#include "Inputs/std-coroutine.h"
+
+using namespace std;
+
+struct Chat {
+  struct promise_type {
+std::suspend_always initial_suspend() { return {}; }
+Chat get_return_object() {
+  return std::coroutine_handle::from_promise(*this);
+}
+std::suspend_always yield_value(int m) { return {}; }
+std::suspend_always final_suspend() noexcept { return {}; }
+std::suspend_always return_value(int) { return {}; }
+void unhandled_exception() {}
+
+auto await_transform(int s) {
+  struct awaiter {
+promise_type *promise;
+bool await_ready() { return true; }
+int await_resume() { return promise->message; }
+void await_suspend(std::coroutine_handle<>) {}
+  };
+
+  return awaiter{this};
+}
+int message;
+  };
+
+  Chat(std::coroutine_handle promise);
+
+  std::coroutine_handle handle;
+};
+
+Chat f(int s)  {
+  // CHECK:  CoyieldExpr {{.*}} 
+  // CHECK-NEXT:   CXXMemberCallExpr {{.*}}  {{.*}}
+  // CHECK-NEXT: MemberExpr {{.*}}  {{.*}}
+  // CHECK-NEXT:   DeclRefExpr {{.*}}  {{.*}}
+  // CHECK-NEXT: ImplicitCastExpr {{.*}}  {{.*}}
+  // CHECK-NEXT:   DeclRefExpr {{.*}}  {{.*}}
+  co_yield s;
+  // CHECK:  CoreturnStmt {{.*}} 
+  co_return s;
+  // CHECK:  CoawaitExpr {{.*}}  'int'
+  co_await s;
+}
Index: clang/test/AST/Inputs/std-coroutine.h
===
--- 

[clang] 8d60e10 - [AST][Coroutine] Fix CoyieldExpr missing end loc

2023-08-09 Thread via cfe-commits

Author: dingfei
Date: 2023-08-10T08:02:32+08:00
New Revision: 8d60e10ce4bd428577ef441eb77b260ec3c14088

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

LOG: [AST][Coroutine] Fix CoyieldExpr missing end loc

Coroutine co_yield/co_await/co_return are implemented by a serious of
synthesized CXXMemberExpr which have no lexical right-side parenthesis.

This fix uses the end loc of inner expr as the hypothetical RParenLoc of
CXXMemberExpr. For tools this might be an issue since the RParen token doesn't
exist (but has a valid location).

For future improvement, we might:
1. mark those inner (generated) exprs as implict (tools have chances to skip
   these nodes) (by @aaron.ballman)
2. borrow the idea from InitListExpr, there are two forms, one is for semantic,
   the other one is for syntactic, having these two split can make everything
   easier (by @hokein)

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

Reviewed By: aaron.ballman, hokein

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

Added: 
clang/test/AST/coroutine-co_yield-source-range.cpp

Modified: 
clang/lib/Sema/SemaCoroutine.cpp
clang/test/AST/Inputs/std-coroutine.h

Removed: 




diff  --git a/clang/lib/Sema/SemaCoroutine.cpp 
b/clang/lib/Sema/SemaCoroutine.cpp
index deb67337a2aec0..c7d88f7784c187 100644
--- a/clang/lib/Sema/SemaCoroutine.cpp
+++ b/clang/lib/Sema/SemaCoroutine.cpp
@@ -318,7 +318,8 @@ static ExprResult buildMemberCall(Sema , Expr *Base, 
SourceLocation Loc,
 return ExprError();
   }
 
-  return S.BuildCallExpr(nullptr, Result.get(), Loc, Args, Loc, nullptr);
+  auto EndLoc = Args.empty() ? Loc : Args.back()->getEndLoc();
+  return S.BuildCallExpr(nullptr, Result.get(), Loc, Args, EndLoc, nullptr);
 }
 
 // See if return type is coroutine-handle and if so, invoke builtin coro-resume

diff  --git a/clang/test/AST/Inputs/std-coroutine.h 
b/clang/test/AST/Inputs/std-coroutine.h
index c3ce6543ea5db3..12b0ad093656f7 100644
--- a/clang/test/AST/Inputs/std-coroutine.h
+++ b/clang/test/AST/Inputs/std-coroutine.h
@@ -55,9 +55,9 @@ template  struct coroutine_handle : 
coroutine_handle<> {
 };
 
 struct suspend_always {
-  bool await_ready() { return false; }
-  void await_suspend(coroutine_handle<>) {}
-  void await_resume() {}
+  bool await_ready() noexcept { return false; }
+  void await_suspend(coroutine_handle<>) noexcept {}
+  void await_resume() noexcept {}
 };
 
 struct suspend_never {

diff  --git a/clang/test/AST/coroutine-co_yield-source-range.cpp 
b/clang/test/AST/coroutine-co_yield-source-range.cpp
new file mode 100644
index 00..c5766a6d718940
--- /dev/null
+++ b/clang/test/AST/coroutine-co_yield-source-range.cpp
@@ -0,0 +1,49 @@
+// RUN: %clang_cc1 -triple x86_64-apple-darwin9 %s -std=c++20 \
+// RUN:-fsyntax-only -ast-dump | FileCheck %s
+
+#include "Inputs/std-coroutine.h"
+
+using namespace std;
+
+struct Chat {
+  struct promise_type {
+std::suspend_always initial_suspend() { return {}; }
+Chat get_return_object() {
+  return std::coroutine_handle::from_promise(*this);
+}
+std::suspend_always yield_value(int m) { return {}; }
+std::suspend_always final_suspend() noexcept { return {}; }
+std::suspend_always return_value(int) { return {}; }
+void unhandled_exception() {}
+
+auto await_transform(int s) {
+  struct awaiter {
+promise_type *promise;
+bool await_ready() { return true; }
+int await_resume() { return promise->message; }
+void await_suspend(std::coroutine_handle<>) {}
+  };
+
+  return awaiter{this};
+}
+int message;
+  };
+
+  Chat(std::coroutine_handle promise);
+
+  std::coroutine_handle handle;
+};
+
+Chat f(int s)  {
+  // CHECK:  CoyieldExpr {{.*}} 
+  // CHECK-NEXT:   CXXMemberCallExpr {{.*}}  {{.*}}
+  // CHECK-NEXT: MemberExpr {{.*}}  {{.*}}
+  // CHECK-NEXT:   DeclRefExpr {{.*}}  {{.*}}
+  // CHECK-NEXT: ImplicitCastExpr {{.*}}  {{.*}}
+  // CHECK-NEXT:   DeclRefExpr {{.*}}  {{.*}}
+  co_yield s;
+  // CHECK:  CoreturnStmt {{.*}} 
+  co_return s;
+  // CHECK:  CoawaitExpr {{.*}}  'int'
+  co_await s;
+}



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


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

2023-08-09 Thread Hubert Tong via Phabricator via cfe-commits
hubert.reinterpretcast added a comment.

In D153701#4563919 , @yronglin wrote:

> The gap between these two numbers is very large. So I'think we can create 
> additional materializations only within for-range initializers. I'm not sure 
> if I can find a way to only create materializes for temporaries that need to 
> have an extended lifetime, WDYT?

@rsmith asked for something slightly different (but I am not sure how to 
collect that info): He wanted the AST size delta.

For what we have, I think the detailed results table would be more useful if we 
add some size metric for the files and the increase expressed as a percentage. 
Perhaps sorting by file size would help contextualize the significance of the 
percentage change.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153701

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


[PATCH] D155540: [clangd] Remove extra dependancies for clangd

2023-08-09 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

In D155540#4574613 , @lei wrote:

> I was thinking to commit this patch to minimize the dependencies if there are 
> no objections. @MaskRay @nemanjai any preferences?

LGTM. Please commit it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155540

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


[PATCH] D156312: [analyzer] Upstream BitwiseShiftChecker

2023-08-09 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added inline comments.



Comment at: clang/lib/StaticAnalyzer/Checkers/BitwiseShiftChecker.cpp:301-302
+  pluralSuffix(MaximalAllowedShift));
+R->addNote(LeftNote, PathDiagnosticLocation{LHS, Ctx.getSourceManager(),
+Ctx.getLocationContext()});
+Ctx.emitReport(std::move(R));

donat.nagy wrote:
> donat.nagy wrote:
> > donat.nagy wrote:
> > > gamesh411 wrote:
> > > > donat.nagy wrote:
> > > > > NoQ wrote:
> > > > > > Can we just append this to the warning? The `addNote()` is useful 
> > > > > > for notes that need to be placed in code outside of the execution 
> > > > > > path, but if it's always next to the warning, it probably doesn't 
> > > > > > make sense to display it separately.
> > > > > I didn't append this to the warning because I felt that the warning 
> > > > > text is already too long. (By the way, an earlier internal variant of 
> > > > > this checker produced two separate notes next to the warning message.)
> > > > > 
> > > > > I tweaked the messages of this checker before initiating this review, 
> > > > > but I feel that there's still some room for improvements. (E.g. in 
> > > > > this particular case perhaps we could omit some of the details that 
> > > > > are not immediately useful and could be manually calculated from 
> > > > > other parts of the message...) 
> > > > Just a thought on simplifying the diagnostics a bit:
> > > > 
> > > > Warning: "Right operand is negative in left shift"
> > > > Note: "The result of left shift is undefined because the right operand 
> > > > is negative"
> > > > Shortened: "Undefined left shift due to negative right operand"
> > > > 
> > > > Warning: "Left shift by '34' overflows the capacity of 'int'"
> > > > Note: "The result of left shift is undefined because the right operand 
> > > > '34' is not smaller than 32, the capacity of 'int'"
> > > > Shortened: "Undefined left shift: '34' exceeds 'int' capacity (32 bits)"
> > > > 
> > > > The more complex notes are a bit sketchy, as relevant information can 
> > > > be lost, and the following solution is probably a bit too much, but 
> > > > could prove to be an inspiration:
> > > > 
> > > > Warning: "Left shift of '1024' overflows the capacity of 'int'"
> > > > CXX Note: "Left shift of '1024' is undefined because 'int' can hold 
> > > > only 32 bits (including the sign bit), so some bits overflow"
> > > > CXX Note: "The value '1024' is represented by 11 bits, allowing at most 
> > > > 21 bits for bitshift"
> > > > C Note: "Left shift of '1024' is undefined because 'int' can hold only 
> > > > 31 bits (excluding the sign bit), so some bits overflow"
> > > > C Note: "The value '1024' is represented by 11 bits, allowing at most 
> > > > 20 bits for bitshift"
> > > > 
> > > > Shortened:
> > > > CXX Warning: "Undefined left shift: '1024' (11 bits) exceeds 'int' 
> > > > capacity (32 bits, including sign)"
> > > > C Warning: "Undefined left shift: '1024' (11 bits) exceeds 'int' 
> > > > capacity (31 bits, excluding sign)"
> > > Clarification about the `Msg`/`ShortMsg` distinction:
> > > I'm intentionally separating the short warning messages and the longer 
> > > note messages because `createBugReport()` enforces the convention that it 
> > > will always emit a warning and a note at the bug location.
> > > 
> > > According to the comments in the source code, the intention is that the 
> > > note contains all the relevant information, while the warning is a brief 
> > > summary that can be displayed in situations where the notes wouldn't fit 
> > > the UI.
> > > 
> > > IIUC many checkers ignore this distinction and emit the same (often long 
> > > and cumbersome) message both as a note and as a warning 
> > > (`createBugReport()` has a variant which takes only one message parameter 
> > > and passes it to both locations), but I tried to follow it because I 
> > > think it's ugly when the same message is repeated twice and there is some 
> > > sense in providing both a brief summary and a full description that 
> > > doesn't use potentially-ambiguous abbreviations to save space.
> > > 
> > > Of course I could also accept a community decision that this "brief 
> > > warning / full note" distinction is deprecated and will be eliminated 
> > > (because e.g. front-end utilities are not prepared to handle it), but in 
> > > that case I'd strongly suggest a redesign where we eliminate the 
> > > redundantly printed 'note' message. (There is no reason to say the same 
> > > thing twice! There is no reason to say the same thing twice!)
> > > 
> > > On the other hand, in addition to this `Msg`/`ShortMsg` distinction, this 
> > > part of the code also adds the extra `LeftNote` (as a remnant from an 
> > > earlier internal version of this checker), and that's that's what I'd 
> > > like to merge into `Msg` (following NoQ's suggestion and keeping it 
> > > distinct from the `ShortMsg`).
> > Among notes, my only 

[PATCH] D157227: [Clang] Don't add `undef` for `operator new` under -fno-exceptions.

2023-08-09 Thread DianQK via Phabricator via cfe-commits
DianQK abandoned this revision.
DianQK added a comment.

Track this issue at https://github.com/llvm/llvm-project/issues/60717.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157227

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


[PATCH] D157445: [CodeGen][UBSan] Add support for handling attributed functions in getUBSanFunctionTypeHash.

2023-08-09 Thread Julian Lettner via Phabricator via cfe-commits
yln added inline comments.



Comment at: clang/test/CodeGen/ubsan-function-attributed.c:4
+//Make sure compiler does not crash inside getUBSanFunctionTypeHash while 
compiling this
+long __attribute__((ms_abi)) f() {}

MaskRay wrote:
> https://maskray.me/blog/2021-08-08-toolchain-testing#the-test-checks-too-little
> 
> "A regression test which simply runs the compiler and expects it not to crash 
> has low utilization. It is often better to additionally test some properties 
> of the produced object file."
> 
> I think it's better to define another function without 
> `__attribute__((ms_abi))`, and check that the two functions have the same 
> type hash.
I agree with this and particularly this sounds like a good approach:
> I think it's better to define another function without 
> __attribute__((ms_abi)), and check that the two functions have the same type 
> hash.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157445

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


[PATCH] D156596: [Clang] Produce a warning instead of an error in unevaluated strings before C++26

2023-08-09 Thread Hubert Tong via Phabricator via cfe-commits
hubert.reinterpretcast accepted this revision.
hubert.reinterpretcast added a comment.

In D156596#4573354 , @aaron.ballman 
wrote:

> LGTM but please wait for @hubert.reinterpretcast to confirm the new tests 
> cover what he was looking for.

LGTM; thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156596

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


[PATCH] D157562: [Driver][DXC] Treat stdin as HLSL

2023-08-09 Thread Justin Bogner via Phabricator via cfe-commits
bogner created this revision.
bogner added reviewers: beanz, python3kgae.
Herald added subscribers: Anastasia, mcrosier.
Herald added a project: All.
bogner requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay.
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D157562

Files:
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/dxc_stdin.hlsl


Index: clang/test/Driver/dxc_stdin.hlsl
===
--- /dev/null
+++ clang/test/Driver/dxc_stdin.hlsl
@@ -0,0 +1,3 @@
+// RUN: %clang_dxc -Tlib_6_7 - -### 2>&1 | FileCheck %s
+// CHECK: "-cc1"
+// CHECK-SAME: "-x" "hlsl" "-"
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -2648,6 +2648,8 @@
 if (memcmp(Value, "-", 2) == 0) {
   if (IsFlangMode()) {
 Ty = types::TY_Fortran;
+  } else if (IsDXCMode()) {
+Ty = types::TY_HLSL;
   } else {
 // If running with -E, treat as a C input (this changes the
 // builtin macros, for example). This may be overridden by -ObjC


Index: clang/test/Driver/dxc_stdin.hlsl
===
--- /dev/null
+++ clang/test/Driver/dxc_stdin.hlsl
@@ -0,0 +1,3 @@
+// RUN: %clang_dxc -Tlib_6_7 - -### 2>&1 | FileCheck %s
+// CHECK: "-cc1"
+// CHECK-SAME: "-x" "hlsl" "-"
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -2648,6 +2648,8 @@
 if (memcmp(Value, "-", 2) == 0) {
   if (IsFlangMode()) {
 Ty = types::TY_Fortran;
+  } else if (IsDXCMode()) {
+Ty = types::TY_HLSL;
   } else {
 // If running with -E, treat as a C input (this changes the
 // builtin macros, for example). This may be overridden by -ObjC
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D157201: [Clang] Support qualified name as member designator in offsetof

2023-08-09 Thread Hubert Tong via Phabricator via cfe-commits
hubert.reinterpretcast added inline comments.



Comment at: clang/test/SemaCXX/offsetof.cpp:104
+struct X2 { int a; static int static_a; };
+int x2[__builtin_offsetof(struct X2, X2::a) == 0 ? 1 : -1];
+int x3[__builtin_offsetof(struct X2, X2::static_a) == 0 ? 1 : -1]; // 
expected-error{{no member named 'static_a'}}

Tests should include cases where the member is a direct member of a base class 
or an anonymous union therein (and named variously by the qualification with 
the base class name, the complete class name, an intermediate base class name, 
the base class name qualified with an intermediate base class, the base class 
name denoted using `::identity_t`, etc.).

Additionally, there should be a diagnostic test case where the qualifier is for 
an unrelated identically-defined class in another namespace.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157201

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


[PATCH] D157559: [clang][modules] Respect "-fmodule-name=" when serializing included files into a PCH

2023-08-09 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 created this revision.
jansvoboda11 added a reviewer: benlangmuir.
Herald added a subscriber: ributzka.
Herald added a project: All.
jansvoboda11 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Clang writes the set of textually included files into AST files, so that 
importers know to avoid including those files again and instead deserialize 
their contents from the AST on-demand.

Logic for determining the set of included files files only considers headers 
that are either non-modular or that are modular but with 
`HeaderFileInfo::isCompilingModuleHeader` set. Logic for computing that bit is 
different than the one that determines whether to include a header textually 
with the "-fmodule-name=Mod" option. That can lead to header from module "Mod" 
being included textually in a PCH, but be ommited in the serialized set of 
included files. This can then allow such header to be textually included from 
importer of the PCH, wreaking havoc.

This patch fixes that by aligning the logic for computing 
`HeaderFileInfo::isCompilingModuleHeader` with the logic for deciding whether 
to include modular header textually.

As far as I can tell, this bug has been in Clang for forever. It got 
accidentally "fixed" by D114095  (that 
changed the logic for determining the set of included files) and got broken 
again in D155131  (which is essentially a 
revert of the former).


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D157559

Files:
  clang/lib/Lex/ModuleMap.cpp
  clang/test/Modules/pch-with-module-name-import-twice.c


Index: clang/test/Modules/pch-with-module-name-import-twice.c
===
--- /dev/null
+++ clang/test/Modules/pch-with-module-name-import-twice.c
@@ -0,0 +1,19 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+
+// This test checks that headers that are part of a module named by
+// -fmodule-name= don't get included again if previously included from a PCH.
+
+//--- include/module.modulemap
+module Mod { header "Mod.h" }
+//--- include/Mod.h
+struct Symbol {};
+//--- pch.h
+#import "Mod.h"
+//--- tu.c
+#import "Mod.h" // expected-no-diagnostics
+
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t/cache 
-fimplicit-module-maps -fmodule-name=Mod -I %t/include \
+// RUN:   -emit-pch -x c-header %t/pch.h -o %t/pch.pch
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t/cache 
-fimplicit-module-maps -fmodule-name=Mod -I %t/include \
+// RUN:   -fsyntax-only %t/tu.c -include-pch %t/pch.pch -verify
Index: clang/lib/Lex/ModuleMap.cpp
===
--- clang/lib/Lex/ModuleMap.cpp
+++ clang/lib/Lex/ModuleMap.cpp
@@ -1268,8 +1268,7 @@
   HeaderList.push_back(KH);
   Mod->Headers[headerRoleToKind(Role)].push_back(Header);
 
-  bool isCompilingModuleHeader =
-  LangOpts.isCompilingModule() && Mod->getTopLevelModule() == SourceModule;
+  bool isCompilingModuleHeader = Mod->isForBuilding(LangOpts);
   if (!Imported || isCompilingModuleHeader) {
 // When we import HeaderFileInfo, the external source is expected to
 // set the isModuleHeader flag itself.


Index: clang/test/Modules/pch-with-module-name-import-twice.c
===
--- /dev/null
+++ clang/test/Modules/pch-with-module-name-import-twice.c
@@ -0,0 +1,19 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+
+// This test checks that headers that are part of a module named by
+// -fmodule-name= don't get included again if previously included from a PCH.
+
+//--- include/module.modulemap
+module Mod { header "Mod.h" }
+//--- include/Mod.h
+struct Symbol {};
+//--- pch.h
+#import "Mod.h"
+//--- tu.c
+#import "Mod.h" // expected-no-diagnostics
+
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t/cache -fimplicit-module-maps -fmodule-name=Mod -I %t/include \
+// RUN:   -emit-pch -x c-header %t/pch.h -o %t/pch.pch
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t/cache -fimplicit-module-maps -fmodule-name=Mod -I %t/include \
+// RUN:   -fsyntax-only %t/tu.c -include-pch %t/pch.pch -verify
Index: clang/lib/Lex/ModuleMap.cpp
===
--- clang/lib/Lex/ModuleMap.cpp
+++ clang/lib/Lex/ModuleMap.cpp
@@ -1268,8 +1268,7 @@
   HeaderList.push_back(KH);
   Mod->Headers[headerRoleToKind(Role)].push_back(Header);
 
-  bool isCompilingModuleHeader =
-  LangOpts.isCompilingModule() && Mod->getTopLevelModule() == SourceModule;
+  bool isCompilingModuleHeader = Mod->isForBuilding(LangOpts);
   if (!Imported || isCompilingModuleHeader) {
 // When we import HeaderFileInfo, the external source is expected to
 // set the isModuleHeader flag itself.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org

[PATCH] D156188: [-Wunsafe-buffer-usage] Refactor and improve for parameter fix-its

2023-08-09 Thread Ziqing Luo via Phabricator via cfe-commits
ziqingluo-90 added a comment.

> Btw, how does this work with `int **`? Given that the pointee type `int *` 
> isn't a simple identifier.

It does not require the pointee type to be a simple identifier.   The (source 
range of) pointee type is obtained by analyzing the `TypeLoc` of a variable 
declaration.

The limitation involving "identifiers" is that we require the pointee type to 
be completely on the left of the variable identifier in a variable declaration. 
 As the analysis is based on source locations, 
finding the pointee type source range in cases like `int a[][10]` or  `int 
(*a)[10]` is non-trivial.


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

https://reviews.llvm.org/D156188

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


[PATCH] D155290: [PGO] Use Unique Profile Files when New Processes are Forked

2023-08-09 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

In D155290#4572965 , @qiongsiwu1 
wrote:

> Ping for review.
>
> If there are no comments on whether we should add `-lpthread` for platforms 
> other than AIX, I will land this patch soon, and let the official buildbots 
> check for problems. If there are problems, I will let the bots run a bit 
> (probably a day or so) before reverting to catch as many platforms I need to 
> fix as possible, revert, and fix the patch.
>
> Thanks!

I will take a look as well but please don't land this `-lpthread` change for 
non-AIX platforms. I will think about the implication.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155290

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


[PATCH] D155610: [Clang][Sema] Fix display of characters on static assertion failure

2023-08-09 Thread Hubert Tong via Phabricator via cfe-commits
hubert.reinterpretcast added subscribers: abhina.sreeskantharajan, 
hubert.reinterpretcast.
hubert.reinterpretcast added a comment.

@abhina.sreeskantharajan, does this patch assume too much about the characters 
displayable for diagnostic output?


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

https://reviews.llvm.org/D155610

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


[PATCH] D156726: Make globals with mutable members non-constant, even in custom sections

2023-08-09 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added inline comments.



Comment at: clang/lib/Sema/SemaDecl.cpp:14254
 int SectionFlags = ASTContext::PSF_Read;
-if (var->getType().isConstQualified()) {
-  if (HasConstInit)

dblaikie wrote:
> rnk wrote:
> > rsmith wrote:
> > > efriedma wrote:
> > > > rnk wrote:
> > > > > I think this is not compatible with MSVC. MSVC uses simple logic, it 
> > > > > doesn't look for mutable: https://gcc.godbolt.org/z/sj6d4saxx
> > > > > 
> > > > > The const mutable struct appears in the myrdata section in that 
> > > > > example.
> > > > > 
> > > > > I think the solution is to separate the flag logic from the pragma 
> > > > > stack selection logic, which has to remain MSVC-compatible.
> > > > MSVC apparently looks at whether the variable is marked "const", and 
> > > > nothing else; it doesn't look at mutable, it doesn't look at whether 
> > > > the variable has a constant initializer.  So the current code isn't 
> > > > right either; if we're trying to implement MSVC-compatible logic, we 
> > > > shouldn't check HasConstInit.
> > > > 
> > > > That said, I'm not sure how precisely/in what modes we want to 
> > > > precisely emulate MSVC.  Probably anything we do here will be confusing.
> > > We should at least issue a warning if the sensible logic and the 
> > > MSVC-compatible calculation differ. @rnk, do you know how important it is 
> > > to follow the MSVC semantics in this regard?
> > I think it depends on whether you think that users are primarily using 
> > these pragmas to override the default rdata/bss/data sections without any 
> > care about precisely what goes where, or if they are using them to do 
> > something finer grained.
> > 
> > If I had to guess, I'd say it's more likely the former, given that 
> > `__declspec(allocate)` and `#pragma(section)` exist to handle cases where 
> > users are putting specific globals into specific sections.
> > 
> > Which, if we follow Richard's suggestion, would mean warning when we put a 
> > global marked `const` into a writable section when `ConstSegStack` is 
> > non-empty. That seems reasonable. `-Wmicrosoft-const-seg` for the new 
> > warning group?
> Does the MSVC situation only apply to custom sections? (presumably when not 
> customizing the section, MSVC gets it right and can support a const global 
> with a runtime initializer, mutable member, or mutating dtor?)
> 
> I think this code still needs to be modified, since this is the code that 
> drives the error about incompatible sections. So it'll need to behave 
> differently depending on the target platform?
Yes, the MSVC situation is specifically if you specify `#pragma const_seg`; 
without the pragma, it does what you'd expect.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156726

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


[PATCH] D157554: [NFC][Clang] Fix static analyzer concern about null pointer dereference

2023-08-09 Thread Elizabeth Andrews via Phabricator via cfe-commits
eandrews created this revision.
eandrews added reviewers: tahonermann, aaron.ballman.
Herald added subscribers: manas, ASDenysPetrov, dkrupp, donat.nagy, Szelethus, 
a.sidorin, baloghadamsoftware.
Herald added a project: All.
eandrews requested review of this revision.
Herald added a subscriber: wangpc.

Param->getTypeConstraint() can return nullptr, and was dereferenced without a 
check.

I followed the logic for invalid constraints and set Status as 
concepts::ExprRequirement::SS_ExprSubstitutionFailure if getTypeConstraint() 
returns null unexpectedly. I am not a 100% certain about this change since I am 
unfamiliar with concepts.


https://reviews.llvm.org/D157554

Files:
  clang/lib/Sema/SemaExprCXX.cpp


Index: clang/lib/Sema/SemaExprCXX.cpp
===
--- clang/lib/Sema/SemaExprCXX.cpp
+++ clang/lib/Sema/SemaExprCXX.cpp
@@ -9072,15 +9072,20 @@
 MultiLevelTemplateArgumentList MLTAL(Param, TAL.asArray(),
  /*Final=*/false);
 MLTAL.addOuterRetainedLevels(TPL->getDepth());
-Expr *IDC = Param->getTypeConstraint()->getImmediatelyDeclaredConstraint();
-ExprResult Constraint = SubstExpr(IDC, MLTAL);
-if (Constraint.isInvalid()) {
+const TypeConstraint *TC = Param->getTypeConstraint();
+if (!TC) {
   Status = concepts::ExprRequirement::SS_ExprSubstitutionFailure;
 } else {
-  SubstitutedConstraintExpr =
-  cast(Constraint.get());
-  if (!SubstitutedConstraintExpr->isSatisfied())
-Status = concepts::ExprRequirement::SS_ConstraintsNotSatisfied;
+  ExprResult Constraint =
+  SubstExpr(TC->getImmediatelyDeclaredConstraint(), MLTAL);
+  if (Constraint.isInvalid()) {
+Status = concepts::ExprRequirement::SS_ExprSubstitutionFailure;
+  } else {
+SubstitutedConstraintExpr =
+cast(Constraint.get());
+if (!SubstitutedConstraintExpr->isSatisfied())
+  Status = concepts::ExprRequirement::SS_ConstraintsNotSatisfied;
+  }
 }
   }
   return new (Context) concepts::ExprRequirement(E, IsSimple, NoexceptLoc,


Index: clang/lib/Sema/SemaExprCXX.cpp
===
--- clang/lib/Sema/SemaExprCXX.cpp
+++ clang/lib/Sema/SemaExprCXX.cpp
@@ -9072,15 +9072,20 @@
 MultiLevelTemplateArgumentList MLTAL(Param, TAL.asArray(),
  /*Final=*/false);
 MLTAL.addOuterRetainedLevels(TPL->getDepth());
-Expr *IDC = Param->getTypeConstraint()->getImmediatelyDeclaredConstraint();
-ExprResult Constraint = SubstExpr(IDC, MLTAL);
-if (Constraint.isInvalid()) {
+const TypeConstraint *TC = Param->getTypeConstraint();
+if (!TC) {
   Status = concepts::ExprRequirement::SS_ExprSubstitutionFailure;
 } else {
-  SubstitutedConstraintExpr =
-  cast(Constraint.get());
-  if (!SubstitutedConstraintExpr->isSatisfied())
-Status = concepts::ExprRequirement::SS_ConstraintsNotSatisfied;
+  ExprResult Constraint =
+  SubstExpr(TC->getImmediatelyDeclaredConstraint(), MLTAL);
+  if (Constraint.isInvalid()) {
+Status = concepts::ExprRequirement::SS_ExprSubstitutionFailure;
+  } else {
+SubstitutedConstraintExpr =
+cast(Constraint.get());
+if (!SubstitutedConstraintExpr->isSatisfied())
+  Status = concepts::ExprRequirement::SS_ConstraintsNotSatisfied;
+  }
 }
   }
   return new (Context) concepts::ExprRequirement(E, IsSimple, NoexceptLoc,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D157454: [NFC][Clang] Fix static analyzer concern about null value dereference

2023-08-09 Thread Elizabeth Andrews via Phabricator via cfe-commits
eandrews updated this revision to Diff 548789.
eandrews added a comment.

Applied review comments to use an assert instead


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

https://reviews.llvm.org/D157454

Files:
  clang/lib/CodeGen/CGObjC.cpp


Index: clang/lib/CodeGen/CGObjC.cpp
===
--- clang/lib/CodeGen/CGObjC.cpp
+++ clang/lib/CodeGen/CGObjC.cpp
@@ -222,6 +222,7 @@
   QualType ResultType = E->getType();
   const ObjCObjectPointerType *InterfacePointerType
 = ResultType->getAsObjCInterfacePointerType();
+  assert(InterfacePointerType && "Unexpected InterfacePointerType - null");
   ObjCInterfaceDecl *Class
 = InterfacePointerType->getObjectType()->getInterface();
   CGObjCRuntime  = CGM.getObjCRuntime();


Index: clang/lib/CodeGen/CGObjC.cpp
===
--- clang/lib/CodeGen/CGObjC.cpp
+++ clang/lib/CodeGen/CGObjC.cpp
@@ -222,6 +222,7 @@
   QualType ResultType = E->getType();
   const ObjCObjectPointerType *InterfacePointerType
 = ResultType->getAsObjCInterfacePointerType();
+  assert(InterfacePointerType && "Unexpected InterfacePointerType - null");
   ObjCInterfaceDecl *Class
 = InterfacePointerType->getObjectType()->getInterface();
   CGObjCRuntime  = CGM.getObjCRuntime();
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D156726: Make globals with mutable members non-constant, even in custom sections

2023-08-09 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added inline comments.



Comment at: clang/lib/Sema/SemaDecl.cpp:14254
 int SectionFlags = ASTContext::PSF_Read;
-if (var->getType().isConstQualified()) {
-  if (HasConstInit)

rnk wrote:
> rsmith wrote:
> > efriedma wrote:
> > > rnk wrote:
> > > > I think this is not compatible with MSVC. MSVC uses simple logic, it 
> > > > doesn't look for mutable: https://gcc.godbolt.org/z/sj6d4saxx
> > > > 
> > > > The const mutable struct appears in the myrdata section in that example.
> > > > 
> > > > I think the solution is to separate the flag logic from the pragma 
> > > > stack selection logic, which has to remain MSVC-compatible.
> > > MSVC apparently looks at whether the variable is marked "const", and 
> > > nothing else; it doesn't look at mutable, it doesn't look at whether the 
> > > variable has a constant initializer.  So the current code isn't right 
> > > either; if we're trying to implement MSVC-compatible logic, we shouldn't 
> > > check HasConstInit.
> > > 
> > > That said, I'm not sure how precisely/in what modes we want to precisely 
> > > emulate MSVC.  Probably anything we do here will be confusing.
> > We should at least issue a warning if the sensible logic and the 
> > MSVC-compatible calculation differ. @rnk, do you know how important it is 
> > to follow the MSVC semantics in this regard?
> I think it depends on whether you think that users are primarily using these 
> pragmas to override the default rdata/bss/data sections without any care 
> about precisely what goes where, or if they are using them to do something 
> finer grained.
> 
> If I had to guess, I'd say it's more likely the former, given that 
> `__declspec(allocate)` and `#pragma(section)` exist to handle cases where 
> users are putting specific globals into specific sections.
> 
> Which, if we follow Richard's suggestion, would mean warning when we put a 
> global marked `const` into a writable section when `ConstSegStack` is 
> non-empty. That seems reasonable. `-Wmicrosoft-const-seg` for the new warning 
> group?
Does the MSVC situation only apply to custom sections? (presumably when not 
customizing the section, MSVC gets it right and can support a const global with 
a runtime initializer, mutable member, or mutating dtor?)

I think this code still needs to be modified, since this is the code that 
drives the error about incompatible sections. So it'll need to behave 
differently depending on the target platform?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156726

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


[PATCH] D156237: Complete the implementation of P2361 Unevaluated string literals

2023-08-09 Thread Hubert Tong via Phabricator via cfe-commits
hubert.reinterpretcast added inline comments.



Comment at: clang/test/Parser/cxx0x-attributes.cpp:450-451
+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 unevaluated string literal}}
+}

There should be corresponding C tests if, as the release notes text implies, 
the C behaviour changes (although, again, this direction has not been adopted 
by the C committee).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156237

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


[PATCH] D155540: [clangd] Remove extra dependancies for clangd

2023-08-09 Thread Lei Huang via Phabricator via cfe-commits
lei added a comment.

I was thinking to commit this patch to minimize the dependencies if there are 
no objections. @MaskRay @nemanjai any preferences?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155540

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


[PATCH] D157394: [clang][DeclPrinter] Improve AST print of function attributes

2023-08-09 Thread Giuliano Belinassi via Phabricator via cfe-commits
giulianobelinassi added inline comments.



Comment at: clang/lib/AST/DeclPrinter.cpp:259
+case attr::Final:
+case attr::Override:
+  return AttrLocation::AfterDecl;

aaron.ballman wrote:
> giulianobelinassi wrote:
> > @aaron.ballman @erichkeane 
> > 
> > Is this enough to describe the position of the attribute kind, or should it 
> > go for a tblgen approach, as I did in D141714? This here looks much cleaner 
> > than the tblgen IMHO.
> Oofda, I forgot that we model those as keyword attributes. `override` and 
> `final` (and other keyword attributes) are a bit trickier than just "before" 
> or "after" because there's a very particular order in which those can be 
> parsed grammatically, especially for functions: 
> https://godbolt.org/z/ad5qecbrj
> 
> Thinking out loud: perhaps an approach to solving this is to sort the 
> attributes by source location. So all the before attributes are written in 
> the same order as they were in source, as are all of the after attributes. So 
> long as we're skipping over implicit attributes, this seems like it should 
> keep the order of the attributes correct.
> 
> A different alternative that's possibly more work than it's worth: the decl 
> printer could dispatch to a table-genned function to ask the attribute "do 
> you want to be printed now?" based on what part of the declaration we've 
> already printed. This would require the decl printer to know e.g., "I've 
> finished printing the parameter list but haven't yet printed cv qualifiers" 
> and pass that information along to the attribute; individual attributes with 
> special rules could supply special logic in Attr.td to say "the attribute 
> should be printed after the function parameter list and after the cv and ref 
> qualifiers, but before the override/final keywords" while most attributes can 
> hopefully get away with whatever the default behavior is coming out of 
> tablegen.
> Oofda, I forgot that we model those as keyword attributes. `override` and 
> `final` (and other keyword attributes) are a bit trickier than just "before" 
> or "after" because there's a very particular order in which those can be 
> parsed grammatically, especially for functions: 
> https://godbolt.org/z/ad5qecbrj
> 
> Thinking out loud: perhaps an approach to solving this is to sort the 
> attributes by source location. So all the before attributes are written in 
> the same order as they were in source, as are all of the after attributes. So 
> long as we're skipping over implicit attributes, this seems like it should 
> keep the order of the attributes correct.

This may work in cases where clang is able to find the SourceLocation of the 
Decl. My concern is when clang is *not* able to do it. When analyzing Linux 
sourcecode there are cases where this happen, and I have to fallback to AST 
dumping. The only way I see this working is by changing the parser for it to 
mark the attribute and its position. This may be something for the future, but 
the presented fix solves the issue for the cases we have already found. 
 
> A different alternative that's possibly more work than it's worth: the decl 
> printer could dispatch to a table-genned function to ask the attribute "do 
> you want to be printed now?" based on what part of the declaration we've 
> already printed. This would require the decl printer to know e.g., "I've 
> finished printing the parameter list but haven't yet printed cv qualifiers" 
> and pass that information along to the attribute; individual attributes with 
> special rules could supply special logic in Attr.td to say "the attribute 
> should be printed after the function parameter list and after the cv and ref 
> qualifiers, but before the override/final keywords" while most attributes can 
> hopefully get away with whatever the default behavior is coming out of 
> tablegen.

Sounds a lot of work :). Wouldn't my previous suggestion be simpler?



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157394

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


[PATCH] D157550: [clang] Drop some references to typed pointers (getInt8PtrTy). NFC

2023-08-09 Thread Bjorn Pettersson via Phabricator via cfe-commits
bjope created this revision.
Herald added a subscriber: ChuanqiXu.
Herald added a project: All.
bjope requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D157550

Files:
  clang/lib/CodeGen/CGBlocks.cpp
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/CodeGen/CGCoroutine.cpp
  clang/lib/CodeGen/CGOpenCLRuntime.cpp
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/CodeGen/CodeGenModule.cpp

Index: clang/lib/CodeGen/CodeGenModule.cpp
===
--- clang/lib/CodeGen/CodeGenModule.cpp
+++ clang/lib/CodeGen/CodeGenModule.cpp
@@ -4500,7 +4500,7 @@
 
   return llvm::ConstantExpr::getBitCast(
   llvm::NoCFIValue::get(F),
-  llvm::Type::getInt8PtrTy(VMContext, F->getAddressSpace()));
+  llvm::PointerType::get(VMContext, F->getAddressSpace()));
 }
 
 static const FunctionDecl *
Index: clang/lib/CodeGen/CodeGenFunction.cpp
===
--- clang/lib/CodeGen/CodeGenFunction.cpp
+++ clang/lib/CodeGen/CodeGenFunction.cpp
@@ -2504,7 +2504,7 @@
   // FIXME We create a new bitcast for every annotation because that's what
   // llvm-gcc was doing.
   unsigned AS = V->getType()->getPointerAddressSpace();
-  llvm::Type *I8PtrTy = Builder.getInt8PtrTy(AS);
+  llvm::Type *I8PtrTy = Builder.getPtrTy(AS);
   for (const auto *I : D->specific_attrs())
 EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation,
 {I8PtrTy, CGM.ConstGlobalsPtrTy}),
Index: clang/lib/CodeGen/CGOpenCLRuntime.cpp
===
--- clang/lib/CodeGen/CGOpenCLRuntime.cpp
+++ clang/lib/CodeGen/CGOpenCLRuntime.cpp
@@ -134,7 +134,7 @@
 
 llvm::PointerType *CGOpenCLRuntime::getGenericVoidPointerType() {
   assert(CGM.getLangOpts().OpenCL);
-  return llvm::IntegerType::getInt8PtrTy(
+  return llvm::PointerType::get(
   CGM.getLLVMContext(),
   CGM.getContext().getTargetAddressSpace(LangAS::opencl_generic));
 }
Index: clang/lib/CodeGen/CGCoroutine.cpp
===
--- clang/lib/CodeGen/CGCoroutine.cpp
+++ clang/lib/CodeGen/CGCoroutine.cpp
@@ -594,7 +594,7 @@
 }
 
 void CodeGenFunction::EmitCoroutineBody(const CoroutineBodyStmt ) {
-  auto *NullPtr = llvm::ConstantPointerNull::get(Builder.getInt8PtrTy());
+  auto *NullPtr = llvm::ConstantPointerNull::get(Builder.getPtrTy());
   auto  = CGM.getContext().getTargetInfo();
   unsigned NewAlign = TI.getNewAlign() / TI.getCharWidth();
 
@@ -783,7 +783,7 @@
 }
 CGM.Error(E->getBeginLoc(), "this builtin expect that __builtin_coro_begin "
 "has been used earlier in this function");
-auto *NullPtr = llvm::ConstantPointerNull::get(Builder.getInt8PtrTy());
+auto *NullPtr = llvm::ConstantPointerNull::get(Builder.getPtrTy());
 return RValue::get(NullPtr);
   }
   case llvm::Intrinsic::coro_size: {
Index: clang/lib/CodeGen/CGBuiltin.cpp
===
--- clang/lib/CodeGen/CGBuiltin.cpp
+++ clang/lib/CodeGen/CGBuiltin.cpp
@@ -5009,7 +5009,7 @@
 unsigned NumArgs = E->getNumArgs();
 
 llvm::Type *QueueTy = ConvertType(getContext().OCLQueueTy);
-llvm::Type *GenericVoidPtrTy = Builder.getInt8PtrTy(
+llvm::Type *GenericVoidPtrTy = Builder.getPtrTy(
 getContext().getTargetAddressSpace(LangAS::opencl_generic));
 
 llvm::Value *Queue = EmitScalarExpr(E->getArg(0));
@@ -5187,7 +5187,7 @@
   // OpenCL v2.0 s6.13.17.6 - Kernel query functions need bitcast of block
   // parameter.
   case Builtin::BIget_kernel_work_group_size: {
-llvm::Type *GenericVoidPtrTy = Builder.getInt8PtrTy(
+llvm::Type *GenericVoidPtrTy = Builder.getPtrTy(
 getContext().getTargetAddressSpace(LangAS::opencl_generic));
 auto Info =
 CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(0));
@@ -5202,7 +5202,7 @@
 {Kernel, Arg}));
   }
   case Builtin::BIget_kernel_preferred_work_group_size_multiple: {
-llvm::Type *GenericVoidPtrTy = Builder.getInt8PtrTy(
+llvm::Type *GenericVoidPtrTy = Builder.getPtrTy(
 getContext().getTargetAddressSpace(LangAS::opencl_generic));
 auto Info =
 CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(0));
@@ -5218,7 +5218,7 @@
   }
   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
   case Builtin::BIget_kernel_sub_group_count_for_ndrange: {
-llvm::Type *GenericVoidPtrTy = Builder.getInt8PtrTy(
+llvm::Type *GenericVoidPtrTy = Builder.getPtrTy(
 getContext().getTargetAddressSpace(LangAS::opencl_generic));
 LValue NDRangeL = EmitAggExprToLValue(E->getArg(0));
 llvm::Value *NDRange = NDRangeL.getAddress(*this).getPointer();
Index: clang/lib/CodeGen/CGBlocks.cpp

[PATCH] D156188: [-Wunsafe-buffer-usage] Refactor and improve for parameter fix-its

2023-08-09 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added a comment.

Btw, how does this work with `int **`? Given that the pointee type `int *` 
isn't a simple identifier.


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

https://reviews.llvm.org/D156188

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


[PATCH] D157547: Arm64EC entry/exit thunks, consolidated.

2023-08-09 Thread Eli Friedman via Phabricator via cfe-commits
efriedma created this revision.
efriedma added reviewers: dpaoliello, mstorsjo, bcl5980, jacek.
Herald added subscribers: zzheng, hiraditya, kristof.beyls.
Herald added a project: All.
efriedma requested review of this revision.
Herald added projects: clang, LLVM.
Herald added a subscriber: cfe-commits.

Arm64EC entry/exit thunks, consolidated.

This combines the previously posted patches with some additional work I've done 
to more closely match MSVC output.

Most of the important logic here is implemented in AArch64Arm64ECCallLowering.  
The purpose of the AArch64Arm64ECCallLowering is to take "normal" IR we'd 
generate for other targets, and generate most of the Arm64EC-specific bits: 
generating thunks, mangling symbols, generating aliases, and generating the 
`.hybmp$x` table.  This is all done late for a few reasons: to consolidate the 
logic as much as possible, and to ensure the IR exposed to optimization passes 
doesn't contain complex arm64ec-specific constructs.

The other changes are supporting changes, to handle the new constructs 
generated by that pass.

There's a global llvm.arm64ec.symbolmap representing the .hybmp$x entries for 
the thunks.  This gets handled directly by the AsmPrinter because it needs 
symbol indexes that aren't available before that.

There are two new calling conventions used to represent calls to and from 
thunks: ARM64EC_Thunk_X64 and ARM64EC_Thunk_Native. There are a few changes to 
handle the associated exception-handling info, SEH_SaveAnyRegQP and 
SEH_SaveAnyRegQPX.

I've intentionally left out handling for structs with small non-power-of-two 
sizes, because that's easily separated out. The rest of my current work is 
here. I squashed my current patches because they were split in ways that didn't 
really make sense. Maybe I could split out some bits, but it's hard to 
meaningfully test most of the parts independently.

I'm planning to write more IR tests for test coverage.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D157547

Files:
  clang/lib/CodeGen/CGCXX.cpp
  llvm/include/llvm/IR/CallingConv.h
  llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
  llvm/lib/Target/AArch64/AArch64.h
  llvm/lib/Target/AArch64/AArch64Arm64ECCallLowering.cpp
  llvm/lib/Target/AArch64/AArch64AsmPrinter.cpp
  llvm/lib/Target/AArch64/AArch64CallingConvention.h
  llvm/lib/Target/AArch64/AArch64CallingConvention.td
  llvm/lib/Target/AArch64/AArch64FastISel.cpp
  llvm/lib/Target/AArch64/AArch64FrameLowering.cpp
  llvm/lib/Target/AArch64/AArch64ISelLowering.cpp
  llvm/lib/Target/AArch64/AArch64ISelLowering.h
  llvm/lib/Target/AArch64/AArch64InstrInfo.cpp
  llvm/lib/Target/AArch64/AArch64InstrInfo.td
  llvm/lib/Target/AArch64/AArch64MCInstLower.cpp
  llvm/lib/Target/AArch64/AArch64RegisterInfo.cpp
  llvm/lib/Target/AArch64/AArch64Subtarget.cpp
  llvm/lib/Target/AArch64/AArch64TargetMachine.cpp
  llvm/lib/Target/AArch64/CMakeLists.txt
  llvm/lib/Target/AArch64/GISel/AArch64CallLowering.cpp
  llvm/lib/Target/AArch64/Utils/AArch64BaseInfo.h
  llvm/test/CodeGen/AArch64/arm64ec-dllimport.ll
  llvm/test/CodeGen/AArch64/arm64ec-reservedregs.ll
  llvm/test/CodeGen/AArch64/arm64ec-varargs.ll
  llvm/test/CodeGen/AArch64/stack-protector-target.ll

Index: llvm/test/CodeGen/AArch64/stack-protector-target.ll
===
--- llvm/test/CodeGen/AArch64/stack-protector-target.ll
+++ llvm/test/CodeGen/AArch64/stack-protector-target.ll
@@ -39,6 +39,6 @@
 ; WINDOWS-ARM64EC: adrp x8, __security_cookie
 ; WINDOWS-ARM64EC: ldr x8, [x8, :lo12:__security_cookie]
 ; WINDOWS-ARM64EC: str x8, [sp, #8]
-; WINDOWS-ARM64EC: bl  _Z7CapturePi
+; WINDOWS-ARM64EC: bl "#_Z7CapturePi"
 ; WINDOWS-ARM64EC: ldr x0, [sp, #8]
-; WINDOWS-ARM64EC: bl  __security_check_cookie_arm64ec
+; WINDOWS-ARM64EC: bl "#__security_check_cookie_arm64ec"
Index: llvm/test/CodeGen/AArch64/arm64ec-varargs.ll
===
--- llvm/test/CodeGen/AArch64/arm64ec-varargs.ll
+++ llvm/test/CodeGen/AArch64/arm64ec-varargs.ll
@@ -1,6 +1,6 @@
 ; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
-; RUN: llc -mtriple=arm64ec-pc-windows-msvc < %s | FileCheck %s
-; RUN: llc -mtriple=arm64ec-pc-windows-msvc < %s -global-isel=1 -global-isel-abort=0 | FileCheck %s
+; RUN: llc -mtriple=arm64ec-pc-windows-msvc -arm64ec-generate-thunks=false < %s | FileCheck %s
+; RUN: llc -mtriple=arm64ec-pc-windows-msvc -arm64ec-generate-thunks=false < %s -global-isel=1 -global-isel-abort=0 | FileCheck %s
 
 define void @varargs_callee(double %x, ...) nounwind {
 ; CHECK-LABEL: varargs_callee:
@@ -35,16 +35,20 @@
 ; CHECK-NEXT:sub sp, sp, #48
 ; CHECK-NEXT:mov x4, sp
 ; CHECK-NEXT:add x8, sp, #16
-; CHECK-NEXT:mov x9, #4617315517961601024
-; CHECK-NEXT:mov x0, #4607182418800017408
-; CHECK-NEXT:mov w1, #2
-; CHECK-NEXT:mov x2, #4613937818241073152
-; CHECK-NEXT:mov w3, #4
-; CHECK-NEXT:mov w5, #16
+; 

[PATCH] D156188: [-Wunsafe-buffer-usage] Refactor and improve for parameter fix-its

2023-08-09 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ accepted this revision.
NoQ added a comment.
This revision is now accepted and ready to land.

Very nice, everything looks great!




Comment at: clang/lib/Analysis/UnsafeBufferUsage.cpp:1777-1778
+
+  StringRef SpanOpen = "std::span<";
+  StringRef SpanClose = ">";
+  std::string SpanTyText = SpanOpen.str();

I'd rather just use literals in expressions. Saves a couple mallocs, a couple 
memcpys, and a couple lines of code.

(They'll probably turn into variables later anyway, when we transcend beyond 
`span`, so arguably not worth fixing.)



Comment at: 
clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-parm-unsupported.cpp:141-143
+// CHECK-NOT: fix-it:{{.*}}:{[[@LINE+1]]
+void macroIdentifier(int * MACRO_NAME) { // The fix-it ends with a macro. It 
will be discarded due to overlap with macros. \
+   expected-warning{{'MyName' is an 
unsafe pointer used for buffer access}}

(a bit narrower and less fancy)


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

https://reviews.llvm.org/D156188

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


[clang] 872d22c - [NFC][Clang][Test] Fix warning-as-error

2023-08-09 Thread Michael Platings via cfe-commits

Author: Michael Platings
Date: 2023-08-09T21:29:53+01:00
New Revision: 872d22c735b83d39cbd7660e4678a9c0d42fe36a

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

LOG: [NFC][Clang][Test] Fix warning-as-error

Since D149444 this test has been failing with -Wmissing-multilib if
multilib is configured for the BareMetal toolchain.
By setting sysroot the test is more hermetic and the failure is avoided.

Added: 


Modified: 
clang/test/Driver/arm-execute-only.c

Removed: 




diff  --git a/clang/test/Driver/arm-execute-only.c 
b/clang/test/Driver/arm-execute-only.c
index 3c3af5fd690db4..1b2fad7299484a 100644
--- a/clang/test/Driver/arm-execute-only.c
+++ b/clang/test/Driver/arm-execute-only.c
@@ -1,4 +1,4 @@
-// RUN: %clang -c -fdriver-only -Werror --target=arm-arm-none-eabi \
+// RUN: %clang --sysroot=%S/Inputs -c -fdriver-only -Werror 
--target=arm-arm-none-eabi \
 // RUN:   -march=armv6-m -mexecute-only %s 2>&1 | count 0
 
 // RUN: not %clang -### -c --target=arm-arm-none-eabi -march=armv6 
-mexecute-only %s 2>&1 |\



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


[PATCH] D157445: [CodeGen][UBSan] Add support for handling attributed functions in getUBSanFunctionTypeHash.

2023-08-09 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added inline comments.



Comment at: clang/test/CodeGen/ubsan-function-attributed.c:4
+//Make sure compiler does not crash inside getUBSanFunctionTypeHash while 
compiling this
+long __attribute__((ms_abi)) f() {}

https://maskray.me/blog/2021-08-08-toolchain-testing#the-test-checks-too-little

"A regression test which simply runs the compiler and expects it not to crash 
has low utilization. It is often better to additionally test some properties of 
the produced object file."

I think it's better to define another function without 
`__attribute__((ms_abi))`, and check that the two functions have the same type 
hash.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157445

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


[PATCH] D156704: [clang][HeaderSearch] Treat framework headers as System for suggestPath

2023-08-09 Thread David Goldman via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG9fe632ba18f1: [clang][HeaderSearch] Treat framework headers 
as Angled for suggestPath (authored by dgoldman).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156704

Files:
  clang-tools-extra/clang-include-fixer/IncludeFixer.cpp
  clang-tools-extra/clangd/Headers.cpp
  clang-tools-extra/clangd/index/SymbolCollector.cpp
  clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
  clang-tools-extra/include-cleaner/lib/HTMLReport.cpp
  clang-tools-extra/include-cleaner/lib/IncludeSpeller.cpp
  clang/include/clang/Lex/HeaderSearch.h
  clang/lib/Lex/HeaderSearch.cpp
  clang/lib/Sema/SemaLookup.cpp
  clang/unittests/Lex/HeaderSearchTest.cpp

Index: clang/unittests/Lex/HeaderSearchTest.cpp
===
--- clang/unittests/Lex/HeaderSearchTest.cpp
+++ clang/unittests/Lex/HeaderSearchTest.cpp
@@ -47,14 +47,18 @@
 Search.AddSearchPath(DL, /*isAngled=*/false);
   }
 
-  void addSystemFrameworkSearchDir(llvm::StringRef Dir) {
+  void addFrameworkSearchDir(llvm::StringRef Dir, bool IsSystem = true) {
 VFS->addFile(
 Dir, 0, llvm::MemoryBuffer::getMemBuffer(""), /*User=*/std::nullopt,
 /*Group=*/std::nullopt, llvm::sys::fs::file_type::directory_file);
 auto DE = FileMgr.getOptionalDirectoryRef(Dir);
 assert(DE);
-auto DL = DirectoryLookup(*DE, SrcMgr::C_System, /*isFramework=*/true);
-Search.AddSystemSearchPath(DL);
+auto DL = DirectoryLookup(*DE, IsSystem ? SrcMgr::C_System : SrcMgr::C_User,
+  /*isFramework=*/true);
+if (IsSystem)
+  Search.AddSystemSearchPath(DL);
+else
+  Search.AddSearchPath(DL, /*isAngled=*/true);
   }
 
   void addHeaderMap(llvm::StringRef Filename,
@@ -175,20 +179,32 @@
 }
 
 TEST_F(HeaderSearchTest, SdkFramework) {
-  addSystemFrameworkSearchDir(
+  addFrameworkSearchDir(
   "/Platforms/MacOSX.platform/Developer/SDKs/MacOSX11.3.sdk/Frameworks/");
-  bool IsSystem = false;
+  bool IsAngled = false;
   EXPECT_EQ(Search.suggestPathToFileForDiagnostics(
 "/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/"
 "Frameworks/AppKit.framework/Headers/NSView.h",
 /*WorkingDir=*/"",
-/*MainFile=*/"", ),
+/*MainFile=*/"", ),
 "AppKit/NSView.h");
-  EXPECT_TRUE(IsSystem);
+  EXPECT_TRUE(IsAngled);
+
+  addFrameworkSearchDir("/System/Developer/Library/Framworks/",
+/*IsSystem*/ false);
+  EXPECT_EQ(Search.suggestPathToFileForDiagnostics(
+"/System/Developer/Library/Framworks/"
+"Foo.framework/Headers/Foo.h",
+/*WorkingDir=*/"",
+/*MainFile=*/"", ),
+"Foo/Foo.h");
+  // Expect to be true even though we passed false to IsSystem earlier since
+  // all frameworks should be treated as <>.
+  EXPECT_TRUE(IsAngled);
 }
 
 TEST_F(HeaderSearchTest, NestedFramework) {
-  addSystemFrameworkSearchDir("/Platforms/MacOSX/Frameworks");
+  addFrameworkSearchDir("/Platforms/MacOSX/Frameworks");
   EXPECT_EQ(Search.suggestPathToFileForDiagnostics(
 "/Platforms/MacOSX/Frameworks/AppKit.framework/Frameworks/"
 "Sub.framework/Headers/Sub.h",
@@ -199,7 +215,7 @@
 
 TEST_F(HeaderSearchTest, HeaderFrameworkLookup) {
   std::string HeaderPath = "/tmp/Frameworks/Foo.framework/Headers/Foo.h";
-  addSystemFrameworkSearchDir("/tmp/Frameworks");
+  addFrameworkSearchDir("/tmp/Frameworks");
   VFS->addFile(HeaderPath, 0,
llvm::MemoryBuffer::getMemBufferCopy("", HeaderPath),
/*User=*/std::nullopt, /*Group=*/std::nullopt,
Index: clang/lib/Sema/SemaLookup.cpp
===
--- clang/lib/Sema/SemaLookup.cpp
+++ clang/lib/Sema/SemaLookup.cpp
@@ -5701,10 +5701,10 @@
 /// suggesting the addition of a #include of the specified file.
 static std::string getHeaderNameForHeader(Preprocessor , const FileEntry *E,
   llvm::StringRef IncludingFile) {
-  bool IsSystem = false;
+  bool IsAngled = false;
   auto Path = PP.getHeaderSearchInfo().suggestPathToFileForDiagnostics(
-  E, IncludingFile, );
-  return (IsSystem ? '<' : '"') + Path + (IsSystem ? '>' : '"');
+  E, IncludingFile, );
+  return (IsAngled ? '<' : '"') + Path + (IsAngled ? '>' : '"');
 }
 
 void Sema::diagnoseMissingImport(SourceLocation UseLoc, const NamedDecl *Decl,
Index: clang/lib/Lex/HeaderSearch.cpp
===
--- clang/lib/Lex/HeaderSearch.cpp
+++ clang/lib/Lex/HeaderSearch.cpp
@@ -1928,17 +1928,17 @@
 }
 
 std::string HeaderSearch::suggestPathToFileForDiagnostics(
-const FileEntry *File, llvm::StringRef MainFile, bool *IsSystem) const {
+

[clang] 9fe632b - [clang][HeaderSearch] Treat framework headers as Angled for suggestPath

2023-08-09 Thread David Goldman via cfe-commits

Author: David Goldman
Date: 2023-08-09T15:51:02-04:00
New Revision: 9fe632ba18f1398aa9e6fd531a2ed98fd79eba40

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

LOG: [clang][HeaderSearch] Treat framework headers as Angled for suggestPath

- Rename the IsSystem flag to be IsAngled since that's how callers
  actually use the flag.

- Since frameworks by convention use <> style includes, make sure
  we treat them as Angled

Also update clangd's custom logic for frameworks accordingly.

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

Added: 


Modified: 
clang-tools-extra/clang-include-fixer/IncludeFixer.cpp
clang-tools-extra/clangd/Headers.cpp
clang-tools-extra/clangd/index/SymbolCollector.cpp
clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
clang-tools-extra/include-cleaner/lib/HTMLReport.cpp
clang-tools-extra/include-cleaner/lib/IncludeSpeller.cpp
clang/include/clang/Lex/HeaderSearch.h
clang/lib/Lex/HeaderSearch.cpp
clang/lib/Sema/SemaLookup.cpp
clang/unittests/Lex/HeaderSearchTest.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-include-fixer/IncludeFixer.cpp 
b/clang-tools-extra/clang-include-fixer/IncludeFixer.cpp
index 45fc15619ecab0..1bb5cf756b95b4 100644
--- a/clang-tools-extra/clang-include-fixer/IncludeFixer.cpp
+++ b/clang-tools-extra/clang-include-fixer/IncludeFixer.cpp
@@ -314,11 +314,11 @@ std::string IncludeFixerSemaSource::minimizeInclude(
   if (!Entry)
 return std::string(Include);
 
-  bool IsSystem = false;
+  bool IsAngled = false;
   std::string Suggestion =
-  HeaderSearch.suggestPathToFileForDiagnostics(*Entry, "", );
+  HeaderSearch.suggestPathToFileForDiagnostics(*Entry, "", );
 
-  return IsSystem ? '<' + Suggestion + '>' : '"' + Suggestion + '"';
+  return IsAngled ? '<' + Suggestion + '>' : '"' + Suggestion + '"';
 }
 
 /// Get the include fixer context for the queried symbol.

diff  --git a/clang-tools-extra/clangd/Headers.cpp 
b/clang-tools-extra/clangd/Headers.cpp
index 83fba21b1d931a..6005069be01160 100644
--- a/clang-tools-extra/clangd/Headers.cpp
+++ b/clang-tools-extra/clangd/Headers.cpp
@@ -286,11 +286,11 @@ IncludeInserter::calculateIncludePath(const HeaderFile 
,
   assert(InsertedHeader.valid());
   if (InsertedHeader.Verbatim)
 return InsertedHeader.File;
-  bool IsSystem = false;
+  bool IsAngled = false;
   std::string Suggested;
   if (HeaderSearchInfo) {
 Suggested = HeaderSearchInfo->suggestPathToFileForDiagnostics(
-InsertedHeader.File, BuildDir, IncludingFile, );
+InsertedHeader.File, BuildDir, IncludingFile, );
   } else {
 // Calculate include relative to including file only.
 StringRef IncludingDir = llvm::sys::path::parent_path(IncludingFile);
@@ -303,7 +303,7 @@ IncludeInserter::calculateIncludePath(const HeaderFile 
,
   // FIXME: should we allow (some limited number of) "../header.h"?
   if (llvm::sys::path::is_absolute(Suggested))
 return std::nullopt;
-  if (IsSystem)
+  if (IsAngled)
 Suggested = "<" + Suggested + ">";
   else
 Suggested = "\"" + Suggested + "\"";

diff  --git a/clang-tools-extra/clangd/index/SymbolCollector.cpp 
b/clang-tools-extra/clangd/index/SymbolCollector.cpp
index c9a211b9c4fc2c..e843413601f5a2 100644
--- a/clang-tools-extra/clangd/index/SymbolCollector.cpp
+++ b/clang-tools-extra/clangd/index/SymbolCollector.cpp
@@ -328,42 +328,33 @@ class SymbolCollector::HeaderFileURICache {
   //  instead of
   //  which should be used instead of directly
   // importing the header.
-  std::optional getFrameworkUmbrellaSpelling(
-  llvm::StringRef Framework, SrcMgr::CharacteristicKind HeadersDirKind,
-  const HeaderSearch , FrameworkHeaderPath ) {
+  std::optional
+  getFrameworkUmbrellaSpelling(llvm::StringRef Framework,
+   const HeaderSearch ,
+   FrameworkHeaderPath ) {
 auto Res = CacheFrameworkToUmbrellaHeaderSpelling.try_emplace(Framework);
 auto *CachedSpelling = >second;
 if (!Res.second) {
   return HeaderPath.IsPrivateHeader ? CachedSpelling->PrivateHeader
 : CachedSpelling->PublicHeader;
 }
-bool IsSystem = isSystem(HeadersDirKind);
 SmallString<256> UmbrellaPath(HeaderPath.HeadersParentDir);
 llvm::sys::path::append(UmbrellaPath, "Headers", Framework + ".h");
 
 llvm::vfs::Status Status;
 auto StatErr = HS.getFileMgr().getNoncachedStatValue(UmbrellaPath, Status);
-if (!StatErr) {
-  if (IsSystem)
-CachedSpelling->PublicHeader = llvm::formatv("<{0}/{0}.h>", Framework);
-  else
-CachedSpelling->PublicHeader =
-llvm::formatv("\"{0}/{0}.h\"", Framework);
-}
+if (!StatErr)
+  

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

2023-08-09 Thread Chi Chun Chen via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG8ab62da18d47: [Clang][OpenMP] Support for Code Generation of 
loop bind clause (authored by cchen).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144634

Files:
  clang/include/clang/AST/StmtOpenMP.h
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/StmtOpenMP.cpp
  clang/lib/Sema/SemaOpenMP.cpp
  clang/lib/Sema/TreeTransform.h
  clang/lib/Serialization/ASTReaderStmt.cpp
  clang/lib/Serialization/ASTWriterStmt.cpp
  clang/test/OpenMP/generic_loop_ast_print.cpp
  clang/test/OpenMP/generic_loop_codegen.cpp
  clang/test/OpenMP/loop_bind_codegen.cpp
  clang/test/OpenMP/loop_bind_enclosed.cpp
  clang/test/OpenMP/loop_bind_messages.cpp
  clang/test/OpenMP/nested_loop_codegen.cpp
  clang/test/PCH/pragma-loop.cpp

Index: clang/test/PCH/pragma-loop.cpp
===
--- clang/test/PCH/pragma-loop.cpp
+++ clang/test/PCH/pragma-loop.cpp
@@ -1,5 +1,5 @@
-// RUN: %clang_cc1 -emit-pch -o %t.a %s
-// RUN: %clang_cc1 -include-pch %t.a %s -ast-print -o - | FileCheck %s
+// RUN: %clang_cc1 -fopenmp -emit-pch -o %t.a %s
+// RUN: %clang_cc1 -fopenmp -include-pch %t.a %s -ast-print -o - | FileCheck %s
 
 // CHECK: #pragma clang loop vectorize_width(4)
 // CHECK: #pragma clang loop interleave_count(8)
@@ -18,6 +18,9 @@
 // CHECK: #pragma nounroll{{$}}
 // CHECK: #pragma clang loop vectorize_width(V)
 // CHECK: #pragma clang loop interleave_count(I)
+// CHECK: #pragma omp simd
+// CHECK: #pragma omp for
+// CHECK: #pragma omp distribute
 
 #ifndef HEADER
 #define HEADER
@@ -94,9 +97,33 @@
   List[i] = i;
 }
   }
+
+  inline void run8(int *List, int Length) {
+int i = 0;
+#pragma omp loop bind(thread)
+for (int i = 0; i < Length; i++) {
+  List[i] = i;
+}
+  }
+
+  inline void run9(int *List, int Length) {
+int i = 0;
+#pragma omp loop bind(parallel)
+for (int i = 0; i < Length; i++) {
+  List[i] = i;
+}
+  }
+
+  inline void run10(int *List, int Length) {
+int i = 0;
+#pragma omp loop bind(teams)
+for (int i = 0; i < Length; i++) {
+  List[i] = i;
+}
+  }
+
 };
 #else
-
 void test() {
   int List[100];
 
@@ -109,6 +136,9 @@
   pt.run5(List, 100);
   pt.run6(List, 100);
   pt.run7<2, 4>(List, 100);
+  pt.run8(List, 100);
+  pt.run9(List, 100);
+  pt.run10(List, 100);
 }
 
 #endif
Index: clang/test/OpenMP/nested_loop_codegen.cpp
===
--- clang/test/OpenMP/nested_loop_codegen.cpp
+++ clang/test/OpenMP/nested_loop_codegen.cpp
@@ -58,6 +58,12 @@
 // CHECK1-NEXT:[[DOTGLOBAL_TID__ADDR:%.*]] = alloca ptr, align 8
 // CHECK1-NEXT:[[DOTBOUND_TID__ADDR:%.*]] = alloca ptr, align 8
 // CHECK1-NEXT:[[I_ADDR:%.*]] = alloca ptr, align 8
+// CHECK1-NEXT:[[TMP:%.*]] = alloca i32, align 4
+// CHECK1-NEXT:[[DOTOMP_IV:%.*]] = alloca i32, align 4
+// CHECK1-NEXT:[[DOTOMP_LB:%.*]] = alloca i32, align 4
+// CHECK1-NEXT:[[DOTOMP_UB:%.*]] = alloca i32, align 4
+// CHECK1-NEXT:[[DOTOMP_STRIDE:%.*]] = alloca i32, align 4
+// CHECK1-NEXT:[[DOTOMP_IS_LAST:%.*]] = alloca i32, align 4
 // CHECK1-NEXT:[[K:%.*]] = alloca i32, align 4
 // CHECK1-NEXT:store ptr [[DOTGLOBAL_TID_]], ptr [[DOTGLOBAL_TID__ADDR]], align 8
 // CHECK1-NEXT:store ptr [[DOTBOUND_TID_]], ptr [[DOTBOUND_TID__ADDR]], align 8
@@ -66,35 +72,27 @@
 // CHECK1-NEXT:store i32 0, ptr [[TMP0]], align 4
 // CHECK1-NEXT:br label [[FOR_COND:%.*]]
 // CHECK1:   for.cond:
-// CHECK1-NEXT:[[TMP1:%.*]] = load i32, ptr [[TMP0]], align 4
-// CHECK1-NEXT:[[CMP:%.*]] = icmp slt i32 [[TMP1]], 10
-// CHECK1-NEXT:br i1 [[CMP]], label [[FOR_BODY:%.*]], label [[FOR_END7:%.*]]
 // CHECK1:   for.body:
-// CHECK1-NEXT:store i32 0, ptr [[K]], align 4
-// CHECK1-NEXT:br label [[FOR_COND1:%.*]]
-// CHECK1:   for.cond1:
-// CHECK1-NEXT:[[TMP2:%.*]] = load i32, ptr [[K]], align 4
-// CHECK1-NEXT:[[CMP2:%.*]] = icmp slt i32 [[TMP2]], 5
-// CHECK1-NEXT:br i1 [[CMP2]], label [[FOR_BODY3:%.*]], label [[FOR_END:%.*]]
-// CHECK1:   for.body3:
-// CHECK1-NEXT:[[TMP3:%.*]] = load i32, ptr [[K]], align 4
-// CHECK1-NEXT:[[INC:%.*]] = add nsw i32 [[TMP3]], 1
-// CHECK1-NEXT:store i32 [[INC]], ptr [[K]], align 4
-// CHECK1-NEXT:br label [[FOR_INC:%.*]]
-// CHECK1:   for.inc:
-// CHECK1-NEXT:[[TMP4:%.*]] = load i32, ptr [[K]], align 4
-// CHECK1-NEXT:[[INC4:%.*]] = add nsw i32 [[TMP4]], 1
-// CHECK1-NEXT:store i32 [[INC4]], ptr [[K]], align 4
-// CHECK1-NEXT:br label [[FOR_COND1]], !llvm.loop [[LOOP3:![0-9]+]]
-// CHECK1:   for.end:
-// CHECK1-NEXT:br label [[FOR_INC5:%.*]]
-// CHECK1:   for.inc5:
-// CHECK1-NEXT:[[TMP5:%.*]] = load i32, ptr [[TMP0]], align 4
-// CHECK1-NEXT:

[clang] 8ab62da - [Clang][OpenMP] Support for Code Generation of loop bind clause

2023-08-09 Thread Chi Chun Chen via cfe-commits

Author: Chi Chun Chen
Date: 2023-08-09T14:26:38-05:00
New Revision: 8ab62da18d47fa0ce6aef9da50cca34a26ea775c

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

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

Support for Code Generation of "#pragma loop bind" clause.
1) bind(parallel)
2) bind(teams)
3) bind(thread)

Reviewed By: ABataev

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

Added: 
clang/test/OpenMP/loop_bind_codegen.cpp
clang/test/OpenMP/loop_bind_enclosed.cpp
clang/test/OpenMP/loop_bind_messages.cpp

Modified: 
clang/include/clang/AST/StmtOpenMP.h
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/include/clang/Sema/Sema.h
clang/lib/AST/StmtOpenMP.cpp
clang/lib/Sema/SemaOpenMP.cpp
clang/lib/Sema/TreeTransform.h
clang/lib/Serialization/ASTReaderStmt.cpp
clang/lib/Serialization/ASTWriterStmt.cpp
clang/test/OpenMP/generic_loop_ast_print.cpp
clang/test/OpenMP/generic_loop_codegen.cpp
clang/test/OpenMP/nested_loop_codegen.cpp
clang/test/PCH/pragma-loop.cpp

Removed: 




diff  --git a/clang/include/clang/AST/StmtOpenMP.h 
b/clang/include/clang/AST/StmtOpenMP.h
index 2d37fdbf4ca8fb..20cd198f5f0cc5 100644
--- a/clang/include/clang/AST/StmtOpenMP.h
+++ b/clang/include/clang/AST/StmtOpenMP.h
@@ -281,6 +281,15 @@ class OMPExecutableDirective : public Stmt {
 return Data->getClauses();
   }
 
+  /// Was this directive mapped from an another directive?
+  /// e.g. 1) omp loop bind(parallel) is mapped to OMPD_for
+  ///  2) omp loop bind(teams) is mapped to OMPD_distribute
+  ///  3) omp loop bind(thread) is mapped to OMPD_simd
+  /// It was necessary to note it down in the Directive because of
+  /// clang::TreeTransform::TransformOMPExecutableDirective() pass in
+  /// the frontend.
+  OpenMPDirectiveKind PrevMappedDirective = llvm::omp::OMPD_unknown;
+
 protected:
   /// Data, associated with the directive.
   OMPChildren *Data = nullptr;
@@ -345,6 +354,10 @@ class OMPExecutableDirective : public Stmt {
 return Inst;
   }
 
+  void setMappedDirective(OpenMPDirectiveKind MappedDirective) {
+PrevMappedDirective = MappedDirective;
+  }
+
 public:
   /// Iterates over expressions/statements used in the construct.
   class used_clauses_child_iterator
@@ -598,6 +611,8 @@ class OMPExecutableDirective : public Stmt {
"Expected directive with the associated statement.");
 return Data->getRawStmt();
   }
+
+  OpenMPDirectiveKind getMappedDirective() const { return PrevMappedDirective; 
}
 };
 
 /// This represents '#pragma omp parallel' directive.
@@ -1604,7 +1619,8 @@ class OMPSimdDirective : public OMPLoopDirective {
   SourceLocation EndLoc, unsigned CollapsedNum,
   ArrayRef Clauses,
   Stmt *AssociatedStmt,
-  const HelperExprs );
+  const HelperExprs ,
+  OpenMPDirectiveKind 
ParamPrevMappedDirective);
 
   /// Creates an empty directive with the place
   /// for \a NumClauses clauses.
@@ -1682,7 +1698,8 @@ class OMPForDirective : public OMPLoopDirective {
  SourceLocation EndLoc, unsigned CollapsedNum,
  ArrayRef Clauses,
  Stmt *AssociatedStmt, const HelperExprs 
,
- Expr *TaskRedRef, bool HasCancel);
+ Expr *TaskRedRef, bool HasCancel,
+ OpenMPDirectiveKind ParamPrevMappedDirective);
 
   /// Creates an empty directive with the place
   /// for \a NumClauses clauses.
@@ -4406,7 +4423,8 @@ class OMPDistributeDirective : public OMPLoopDirective {
   static OMPDistributeDirective *
   Create(const ASTContext , SourceLocation StartLoc, SourceLocation EndLoc,
  unsigned CollapsedNum, ArrayRef Clauses,
- Stmt *AssociatedStmt, const HelperExprs );
+ Stmt *AssociatedStmt, const HelperExprs ,
+ OpenMPDirectiveKind ParamPrevMappedDirective);
 
   /// Creates an empty directive with the place
   /// for \a NumClauses clauses.

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index f767dde3c55918..7e271ba166077b 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -9886,6 +9886,11 @@ def err_break_not_in_loop_or_switch : Error<
 def warn_loop_ctrl_binds_to_inner : Warning<
   "'%0' is bound to current loop, GCC binds it to the enclosing loop">,
   InGroup;
+def err_omp_bind_required_on_loop : Error<
+  "expected 'bind' clause for 

[PATCH] D157334: [clang] Define _MSC_EXTENSIONS on -gnu if -fms-extensions is set

2023-08-09 Thread Aiden Grossman via Phabricator via cfe-commits
aidengrossman added a comment.

It's something set on by default in MSVC 
(https://learn.microsoft.com/en-us/cpp/preprocessor/predefined-macros?view=msvc-170).
 It's interesting that GCC doesn't set the `_MSC_EXTENSIONS` macro with 
`-fms-extensions`. It should if it wants to match the behavior of MSVC. It 
might cause an issue somewhere, but I think it'll probably be exceedingly rare 
and I think would be resulting from incorrect user code (assuming all the 
extensions enabled by MSVC with the flag they use are present in clang). I 
would've thought not having the macro defined would cause more issues, but 
given this part of the code hasn't been touched in six years (and that was a 
refactoring that was presumably NFC), it doesn't seem like people rely on this 
macro too much. Thanks for running the tests though! Having concrete data to 
back up hypotheses is always great to have.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157334

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


[PATCH] D156816: [Clang] Make generic aliases to OpenCL address spaces

2023-08-09 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 added a comment.

In D156816#4574190 , @arsenm wrote:

> Probably should just wrap uses in macros for now

In clang? Or just have users deal with `opencl_` on everything and rename it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156816

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


[PATCH] D156816: [Clang] Make generic aliases to OpenCL address spaces

2023-08-09 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm requested changes to this revision.
arsenm added a comment.
This revision now requires changes to proceed.

Probably should just wrap uses in macros for now


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156816

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


[PATCH] D157331: [clang] Implement C23

2023-08-09 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/test/Headers/stdckdint.cpp:1
+// RUN: %clang_cc1 -emit-llvm -fgnuc-version=4.2.1 -std=gnu++11 %s -o - | 
FileCheck %s
+

hiraditya wrote:
> aaron.ballman wrote:
> > ZijunZhao wrote:
> > > enh wrote:
> > > > ZijunZhao wrote:
> > > > > enh wrote:
> > > > > > ZijunZhao wrote:
> > > > > > > enh wrote:
> > > > > > > > hiraditya wrote:
> > > > > > > > > seems like we don't have a -std=gnu23, or -std=c23 standard 
> > > > > > > > > flag for this in clang yet.
> > > > > > > > > 
> > > > > > > > > https://godbolt.org/z/7dKnGEWWE
> > > > > > > > > 
> > > > > > > > > we probably need it before testing stdckdint i guess?
> > > > > > > > other headers just use > and the previous version. (though see 
> > > > > > > > stdalign.h if you're looking for some random cleanup to do!)
> > > > > > > > seems like we don't have a -std=gnu23, or -std=c23 standard 
> > > > > > > > flag for this in clang yet.
> > > > > > > 
> > > > > > > In the local testing, `-std=c++23` works  and all tests pass 
> > > > > > > 
> > > > > > > 
> > > > > > C23 != C++23... they don't even really coordinate with one 
> > > > > > another... talk to hboehm about that some time :-)
> > > > > ohhh I think `gnu++23` != `gnu23` either  
> > > > correct. the "c" or "c++" part means "standard stuff" and replacing it 
> > > > with "gnu" or "gnu++" means "standard stuff _and_ extensions".
> > > I try to grep "std>" in `clang/test/Headers` but find nothing, and 
> > > nothing in stdalign.h is about `>`
> > This isn't a GNU feature, so we don't need to enable a GNU mode or set a 
> > gnu version. (Note, the file should be a .c file, not a .cpp file)
> Do we have plans to add -std=c23 anytime soon? `-std=c2x` defines 
> `__STDC_VERSION__ 202000L`
> Do we have plans to add -std=c23 anytime soon? -std=c2x defines 
> __STDC_VERSION__ 202000L

We needed to wait for WG14 to finalize the standard before we could decide what 
name to use or what macro value to pick. Both are settled now, so I plan to 
make those changes Sometime Soon™ 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157331

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


[PATCH] D157331: [clang] Implement C23

2023-08-09 Thread Aditya Kumar via Phabricator via cfe-commits
hiraditya added inline comments.



Comment at: clang/lib/Headers/stdckdint.h:13
+
+#if defined(__GNUC__)
+#define ckd_add(R, A, B) __builtin_add_overflow((A), (B), (R))

aaron.ballman wrote:
> enh wrote:
> > ZijunZhao wrote:
> > > cor3ntin wrote:
> > > > aaron.ballman wrote:
> > > > > hiraditya wrote:
> > > > > > enh wrote:
> > > > > > > hiraditya wrote:
> > > > > > > > xbolva00 wrote:
> > > > > > > > > yabinc wrote:
> > > > > > > > > > enh wrote:
> > > > > > > > > > > enh wrote:
> > > > > > > > > > > > enh wrote:
> > > > > > > > > > > > > ZijunZhao wrote:
> > > > > > > > > > > > > > enh wrote:
> > > > > > > > > > > > > > > is this ever _not_ set for clang?
> > > > > > > > > > > > > > https://github.com/llvm/llvm-project/blob/main/clang/lib/Headers/stdbool.h#L23
> > > > > > > > > > > > > > I think it is set?
> > > > > > > > > > > > > i get an error from
> > > > > > > > > > > > > ```
> > > > > > > > > > > > > /tmp$ cat x.c
> > > > > > > > > > > > > #if defined(__GNUC__)
> > > > > > > > > > > > > #error foo
> > > > > > > > > > > > > #endif
> > > > > > > > > > > > > ```
> > > > > > > > > > > > > regardless of whether i compile with -std=c11 or 
> > > > > > > > > > > > > -std=gnu11.
> > > > > > > > > > > > > neither -ansi nor -pedantic seem to stop it either.
> > > > > > > > > > > > it does look like it _should_ be possible to not have 
> > > > > > > > > > > > it set though? 
> > > > > > > > > > > > llvm/llvm-project/clang/lib/Frontend/InitPreprocessor.cpp
> > > > > > > > > > > >  has:
> > > > > > > > > > > > ```
> > > > > > > > > > > >   if (LangOpts.GNUCVersion != 0) {
> > > > > > > > > > > > // Major, minor, patch, are given two decimal 
> > > > > > > > > > > > places each, so 4.2.1 becomes
> > > > > > > > > > > > // 40201.
> > > > > > > > > > > > unsigned GNUCMajor = LangOpts.GNUCVersion / 100 / 
> > > > > > > > > > > > 100;
> > > > > > > > > > > > unsigned GNUCMinor = LangOpts.GNUCVersion / 100 % 
> > > > > > > > > > > > 100;
> > > > > > > > > > > > unsigned GNUCPatch = LangOpts.GNUCVersion % 100;
> > > > > > > > > > > > Builder.defineMacro("__GNUC__", Twine(GNUCMajor));
> > > > > > > > > > > > Builder.defineMacro("__GNUC_MINOR__", 
> > > > > > > > > > > > Twine(GNUCMinor));
> > > > > > > > > > > > Builder.defineMacro("__GNUC_PATCHLEVEL__", 
> > > > > > > > > > > > Twine(GNUCPatch));
> > > > > > > > > > > > Builder.defineMacro("__GXX_ABI_VERSION", "1002");
> > > > > > > > > > > > 
> > > > > > > > > > > > if (LangOpts.CPlusPlus) {
> > > > > > > > > > > >   Builder.defineMacro("__GNUG__", Twine(GNUCMajor));
> > > > > > > > > > > >   Builder.defineMacro("__GXX_WEAK__");
> > > > > > > > > > > > }
> > > > > > > > > > > >   }
> > > > > > > > > > > > ```
> > > > > > > > > > > /me wonders whether the right test here is actually `#if 
> > > > > > > > > > > __has_feature(__builtin_add_overflow)` (etc)...
> > > > > > > > > > > 
> > > > > > > > > > > but at this point, you definitely need an llvm person :-)
> > > > > > > > > > From 
> > > > > > > > > > https://clang.llvm.org/docs/LanguageExtensions.html#checked-arithmetic-builtins,
> > > > > > > > > >  we can check them with
> > > > > > > > > >  __has_builtin(__builtin_add_overflow) && 
> > > > > > > > > > __has_builtin(__builtin_sub_overflow) && 
> > > > > > > > > > __has_builtin(__builtin_mul_overflow).
> > > > > > > > > > I saw some code also checks if __GNUC__ >= 5:
> > > > > > > > > > 
> > > > > > > > > > // The __GNUC__ checks can not be removed until we depend 
> > > > > > > > > > on GCC >= 10.1
> > > > > > > > > > // which is the first version that returns true for 
> > > > > > > > > > __has_builtin(__builtin_add_overflow)
> > > > > > > > > > #if __GNUC__ >= 5 || __has_builtin(__builtin_add_overflow)
> > > > > > > > > > 
> > > > > > > > > > I guess we don't need to support real gcc using this header 
> > > > > > > > > > here. So maybe only checking __has_builtin is enough?
> > > > > > > > > > 
> > > > > > > > > > By the way, if __builtin_add_overflow may not appear on 
> > > > > > > > > > some targets, do we need to modify tests to specify triple 
> > > > > > > > > > like "-triple "x86_64-unknown-unknown"" in 
> > > > > > > > > > https://github.com/llvm/llvm-project/blob/main/clang/test/CodeGen/builtins-overflow.c#L5
> > > > > > > > > >  ?
> > > > > > > > > > 
> > > > > > > > > #ifndef __has_builtin // Optional of course.
> > > > > > > > >   #define __has_builtin(x) 0  // Compatibility with non-clang 
> > > > > > > > > compilers.
> > > > > > > > > #endif
> > > > > > > > > 
> > > > > > > > > ...
> > > > > > > > > #if __has_builtin(__builtin_trap)
> > > > > > > > >   __builtin_trap();
> > > > > > > > > #else
> > > > > > > > >   abort();
> > > > > > > > > #endif
> > > > > > > > > /me wonders whether the right test here is actually #if 
> > > > > > > > > __has_feature(__builtin_add_overflow) (etc)...
> > > > > > > > 
> > > > > > > > i think that should be added.
> > > > 

[PATCH] D157334: [clang] Define _MSC_EXTENSIONS on -gnu if -fms-extensions is set

2023-08-09 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo added a comment.

I think this makes sense in principle - however it does diverge from GCC. GCC 
also supports `-fms-extensions` (but I'm not sure if the set of extensions that 
are enabled by the option is an exact match between the two cases), but GCC 
doesn't expose any extra define in that mode. I don't foresee that it'll cause 
any concrete harm though...

Which toolchain is the original source for the name `_MSC_EXTENSIONS` - is it 
something that MSVC itself sets (always, or optionally?), or something that 
Clang itself has made up?

I tried including this patch in a nightly build run (building llvm-mingw and a 
handful of projects with it, including VLC as a large testcase), and it didn't 
trip up anything, so it seems mostly safe in that aspect at least.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157334

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


[PATCH] D157445: [CodeGen][UBSan] getUBSanFunctionTypeHash does not handle the attributed function case correctly, leading to an assertion failure. This patch desugars the QualType if it is of Attribu

2023-08-09 Thread Usama Hameed via Phabricator via cfe-commits
usama54321 updated this revision to Diff 548723.
usama54321 added a comment.

Fix commit message and description, and added comment explaining the test.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157445

Files:
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/test/CodeGen/ubsan-function-attributed.c


Index: clang/test/CodeGen/ubsan-function-attributed.c
===
--- /dev/null
+++ clang/test/CodeGen/ubsan-function-attributed.c
@@ -0,0 +1,4 @@
+// RUN: %clang_cc1 -emit-llvm -triple x86_64 -std=c17 -fsanitize=function %s 
-o /dev/null
+
+//Make sure compiler does not crash inside getUBSanFunctionTypeHash while 
compiling this
+long __attribute__((ms_abi)) f() {}
Index: clang/lib/CodeGen/CodeGenFunction.cpp
===
--- clang/lib/CodeGen/CodeGenFunction.cpp
+++ clang/lib/CodeGen/CodeGenFunction.cpp
@@ -570,6 +570,9 @@
 
 llvm::ConstantInt *
 CodeGenFunction::getUBSanFunctionTypeHash(QualType Ty) const {
+  if (isa(Ty))
+Ty = Ty.getDesugaredType(getContext());
+
   // Remove any (C++17) exception specifications, to allow calling e.g. a
   // noexcept function through a non-noexcept pointer.
   if (!isa(Ty))


Index: clang/test/CodeGen/ubsan-function-attributed.c
===
--- /dev/null
+++ clang/test/CodeGen/ubsan-function-attributed.c
@@ -0,0 +1,4 @@
+// RUN: %clang_cc1 -emit-llvm -triple x86_64 -std=c17 -fsanitize=function %s -o /dev/null
+
+//Make sure compiler does not crash inside getUBSanFunctionTypeHash while compiling this
+long __attribute__((ms_abi)) f() {}
Index: clang/lib/CodeGen/CodeGenFunction.cpp
===
--- clang/lib/CodeGen/CodeGenFunction.cpp
+++ clang/lib/CodeGen/CodeGenFunction.cpp
@@ -570,6 +570,9 @@
 
 llvm::ConstantInt *
 CodeGenFunction::getUBSanFunctionTypeHash(QualType Ty) const {
+  if (isa(Ty))
+Ty = Ty.getDesugaredType(getContext());
+
   // Remove any (C++17) exception specifications, to allow calling e.g. a
   // noexcept function through a non-noexcept pointer.
   if (!isa(Ty))
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D157454: [NFC][Clang] Fix static analyzer concern about null value dereference

2023-08-09 Thread Tom Honermann via Phabricator via cfe-commits
tahonermann added inline comments.



Comment at: clang/lib/CodeGen/CGObjC.cpp:222-223
   Selector Sel = MethodWithObjects->getSelector();
-  QualType ResultType = E->getType();
-  const ObjCObjectPointerType *InterfacePointerType
-= ResultType->getAsObjCInterfacePointerType();
+  const ObjCObjectPointerType *InterfacePointerType =
+  cast(E->getType());
   ObjCInterfaceDecl *Class

eandrews wrote:
> tahonermann wrote:
> > The previous code included a guarantee that 
> > `InterfacePointerType->getInterfaceType()` is non-null and this change 
> > loses that assurance. Presumably, we never ran into a violation of that 
> > guarantee in the past (since a SIGSEGV would likely have occurred below 
> > otherwise), but perhaps we should consider an assertion to ensure that 
> > guarantee is still met.
> Hmmm... I guess in that case it was just make more sense to keep the old code 
> and add an assert for InterfacePointerType?
Ah, yes, I think that is a better approach!


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

https://reviews.llvm.org/D157454

___
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-08-09 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

In D144634#4573483 , @koops wrote:

> Can someone please check for MacOS? Yesterday when this support was 
> committed, the CHECK statements in tests loop_bind_codegen.cpp and  
> loop_bind_enclosed.cpp had failed on Mac

I patched this in and verified that `check-clang` now passes on macOS. Thanks!

> and I received a comment as follows:
>
>>   When relanding, please remember to put a link to the review in the commit 
>> message.

To do this, run `git commit --amend` and put `Differential Revision: 
https://reviews.llvm.org/D144634` at the bottom of the commit message. `git 
log` has many, many examples of this :)


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] D157331: [clang] Implement C23

2023-08-09 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/lib/Headers/stdckdint.h:13
+
+#if defined(__GNUC__)
+#define ckd_add(R, A, B) __builtin_add_overflow((A), (B), (R))

enh wrote:
> ZijunZhao wrote:
> > cor3ntin wrote:
> > > aaron.ballman wrote:
> > > > hiraditya wrote:
> > > > > enh wrote:
> > > > > > hiraditya wrote:
> > > > > > > xbolva00 wrote:
> > > > > > > > yabinc wrote:
> > > > > > > > > enh wrote:
> > > > > > > > > > enh wrote:
> > > > > > > > > > > enh wrote:
> > > > > > > > > > > > ZijunZhao wrote:
> > > > > > > > > > > > > enh wrote:
> > > > > > > > > > > > > > is this ever _not_ set for clang?
> > > > > > > > > > > > > https://github.com/llvm/llvm-project/blob/main/clang/lib/Headers/stdbool.h#L23
> > > > > > > > > > > > > I think it is set?
> > > > > > > > > > > > i get an error from
> > > > > > > > > > > > ```
> > > > > > > > > > > > /tmp$ cat x.c
> > > > > > > > > > > > #if defined(__GNUC__)
> > > > > > > > > > > > #error foo
> > > > > > > > > > > > #endif
> > > > > > > > > > > > ```
> > > > > > > > > > > > regardless of whether i compile with -std=c11 or 
> > > > > > > > > > > > -std=gnu11.
> > > > > > > > > > > > neither -ansi nor -pedantic seem to stop it either.
> > > > > > > > > > > it does look like it _should_ be possible to not have it 
> > > > > > > > > > > set though? 
> > > > > > > > > > > llvm/llvm-project/clang/lib/Frontend/InitPreprocessor.cpp 
> > > > > > > > > > > has:
> > > > > > > > > > > ```
> > > > > > > > > > >   if (LangOpts.GNUCVersion != 0) {
> > > > > > > > > > > // Major, minor, patch, are given two decimal places 
> > > > > > > > > > > each, so 4.2.1 becomes
> > > > > > > > > > > // 40201.
> > > > > > > > > > > unsigned GNUCMajor = LangOpts.GNUCVersion / 100 / 100;
> > > > > > > > > > > unsigned GNUCMinor = LangOpts.GNUCVersion / 100 % 100;
> > > > > > > > > > > unsigned GNUCPatch = LangOpts.GNUCVersion % 100;
> > > > > > > > > > > Builder.defineMacro("__GNUC__", Twine(GNUCMajor));
> > > > > > > > > > > Builder.defineMacro("__GNUC_MINOR__", 
> > > > > > > > > > > Twine(GNUCMinor));
> > > > > > > > > > > Builder.defineMacro("__GNUC_PATCHLEVEL__", 
> > > > > > > > > > > Twine(GNUCPatch));
> > > > > > > > > > > Builder.defineMacro("__GXX_ABI_VERSION", "1002");
> > > > > > > > > > > 
> > > > > > > > > > > if (LangOpts.CPlusPlus) {
> > > > > > > > > > >   Builder.defineMacro("__GNUG__", Twine(GNUCMajor));
> > > > > > > > > > >   Builder.defineMacro("__GXX_WEAK__");
> > > > > > > > > > > }
> > > > > > > > > > >   }
> > > > > > > > > > > ```
> > > > > > > > > > /me wonders whether the right test here is actually `#if 
> > > > > > > > > > __has_feature(__builtin_add_overflow)` (etc)...
> > > > > > > > > > 
> > > > > > > > > > but at this point, you definitely need an llvm person :-)
> > > > > > > > > From 
> > > > > > > > > https://clang.llvm.org/docs/LanguageExtensions.html#checked-arithmetic-builtins,
> > > > > > > > >  we can check them with
> > > > > > > > >  __has_builtin(__builtin_add_overflow) && 
> > > > > > > > > __has_builtin(__builtin_sub_overflow) && 
> > > > > > > > > __has_builtin(__builtin_mul_overflow).
> > > > > > > > > I saw some code also checks if __GNUC__ >= 5:
> > > > > > > > > 
> > > > > > > > > // The __GNUC__ checks can not be removed until we depend on 
> > > > > > > > > GCC >= 10.1
> > > > > > > > > // which is the first version that returns true for 
> > > > > > > > > __has_builtin(__builtin_add_overflow)
> > > > > > > > > #if __GNUC__ >= 5 || __has_builtin(__builtin_add_overflow)
> > > > > > > > > 
> > > > > > > > > I guess we don't need to support real gcc using this header 
> > > > > > > > > here. So maybe only checking __has_builtin is enough?
> > > > > > > > > 
> > > > > > > > > By the way, if __builtin_add_overflow may not appear on some 
> > > > > > > > > targets, do we need to modify tests to specify triple like 
> > > > > > > > > "-triple "x86_64-unknown-unknown"" in 
> > > > > > > > > https://github.com/llvm/llvm-project/blob/main/clang/test/CodeGen/builtins-overflow.c#L5
> > > > > > > > >  ?
> > > > > > > > > 
> > > > > > > > #ifndef __has_builtin // Optional of course.
> > > > > > > >   #define __has_builtin(x) 0  // Compatibility with non-clang 
> > > > > > > > compilers.
> > > > > > > > #endif
> > > > > > > > 
> > > > > > > > ...
> > > > > > > > #if __has_builtin(__builtin_trap)
> > > > > > > >   __builtin_trap();
> > > > > > > > #else
> > > > > > > >   abort();
> > > > > > > > #endif
> > > > > > > > /me wonders whether the right test here is actually #if 
> > > > > > > > __has_feature(__builtin_add_overflow) (etc)...
> > > > > > > 
> > > > > > > i think that should be added.
> > > > > > > 
> > > > > > > I guess we also need a with `__STDC_VERSION__ > 202000L`? in 
> > > > > > > princple we'd have a C23 number for it but i'm not sure if that 
> > > > > > > has been added to clang yet.
> > > > > > > i think that should be added.
> > > 

[PATCH] D157280: [PGO] Enable `-fprofile-update` for `-fprofile-generate`

2023-08-09 Thread Qiongsi Wu via Phabricator via cfe-commits
qiongsiwu1 updated this revision to Diff 548695.
qiongsiwu1 added a comment.

Update clang users manual.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157280

Files:
  clang/docs/UsersManual.rst
  clang/lib/CodeGen/BackendUtil.cpp
  clang/test/CodeGen/tsan-instrprof-atomic.c
  llvm/include/llvm/Passes/PassBuilder.h
  llvm/include/llvm/Support/PGOOptions.h
  llvm/lib/Passes/PassBuilderPipelines.cpp
  llvm/lib/Support/PGOOptions.cpp

Index: llvm/lib/Support/PGOOptions.cpp
===
--- llvm/lib/Support/PGOOptions.cpp
+++ llvm/lib/Support/PGOOptions.cpp
@@ -16,13 +16,14 @@
std::string MemoryProfile,
IntrusiveRefCntPtr FS, PGOAction Action,
CSPGOAction CSAction, bool DebugInfoForProfiling,
-   bool PseudoProbeForProfiling)
+   bool PseudoProbeForProfiling, bool AtomicCounterUpdate)
 : ProfileFile(ProfileFile), CSProfileGenFile(CSProfileGenFile),
   ProfileRemappingFile(ProfileRemappingFile), MemoryProfile(MemoryProfile),
   Action(Action), CSAction(CSAction),
   DebugInfoForProfiling(DebugInfoForProfiling ||
 (Action == SampleUse && !PseudoProbeForProfiling)),
-  PseudoProbeForProfiling(PseudoProbeForProfiling), FS(std::move(FS)) {
+  PseudoProbeForProfiling(PseudoProbeForProfiling),
+  AtomicCounterUpdate(AtomicCounterUpdate), FS(std::move(FS)) {
   // Note, we do allow ProfileFile.empty() for Action=IRUse LTO can
   // callback with IRUse action without ProfileFile.
 
Index: llvm/lib/Passes/PassBuilderPipelines.cpp
===
--- llvm/lib/Passes/PassBuilderPipelines.cpp
+++ llvm/lib/Passes/PassBuilderPipelines.cpp
@@ -724,7 +724,8 @@
 
 void PassBuilder::addPGOInstrPasses(ModulePassManager ,
 OptimizationLevel Level, bool RunProfileGen,
-bool IsCS, std::string ProfileFile,
+bool IsCS, bool AtomicCounterUpdate,
+std::string ProfileFile,
 std::string ProfileRemappingFile,
 ThinOrFullLTOPhase LTOPhase,
 IntrusiveRefCntPtr FS) {
@@ -793,13 +794,14 @@
   // Do counter promotion at Level greater than O0.
   Options.DoCounterPromotion = true;
   Options.UseBFIInPromotion = IsCS;
+  Options.Atomic = AtomicCounterUpdate;
   MPM.addPass(InstrProfiling(Options, IsCS));
 }
 
 void PassBuilder::addPGOInstrPassesForO0(
 ModulePassManager , bool RunProfileGen, bool IsCS,
-std::string ProfileFile, std::string ProfileRemappingFile,
-IntrusiveRefCntPtr FS) {
+bool AtomicCounterUpdate, std::string ProfileFile,
+std::string ProfileRemappingFile, IntrusiveRefCntPtr FS) {
   if (!RunProfileGen) {
 assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
 MPM.addPass(
@@ -819,6 +821,7 @@
   // Do not do counter promotion at O0.
   Options.DoCounterPromotion = false;
   Options.UseBFIInPromotion = IsCS;
+  Options.Atomic = AtomicCounterUpdate;
   MPM.addPass(InstrProfiling(Options, IsCS));
 }
 
@@ -1094,8 +1097,9 @@
PGOOpt->Action == PGOOptions::IRUse)) {
 addPGOInstrPasses(MPM, Level,
   /* RunProfileGen */ PGOOpt->Action == PGOOptions::IRInstr,
-  /* IsCS */ false, PGOOpt->ProfileFile,
-  PGOOpt->ProfileRemappingFile, Phase, PGOOpt->FS);
+  /* IsCS */ false, PGOOpt->AtomicCounterUpdate,
+  PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile, Phase,
+  PGOOpt->FS);
 MPM.addPass(PGOIndirectCallPromotion(false, false));
   }
   if (PGOOpt && Phase != ThinOrFullLTOPhase::ThinLTOPostLink &&
@@ -1307,12 +1311,14 @@
   if (!LTOPreLink && PGOOpt) {
 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
   addPGOInstrPasses(MPM, Level, /* RunProfileGen */ true,
-/* IsCS */ true, PGOOpt->CSProfileGenFile,
-PGOOpt->ProfileRemappingFile, LTOPhase, PGOOpt->FS);
+/* IsCS */ true, PGOOpt->AtomicCounterUpdate,
+PGOOpt->CSProfileGenFile, PGOOpt->ProfileRemappingFile,
+LTOPhase, PGOOpt->FS);
 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
   addPGOInstrPasses(MPM, Level, /* RunProfileGen */ false,
-/* IsCS */ true, PGOOpt->ProfileFile,
-PGOOpt->ProfileRemappingFile, LTOPhase, PGOOpt->FS);
+/* IsCS */ true, PGOOpt->AtomicCounterUpdate,
+PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile,
+LTOPhase, PGOOpt->FS);
   }

[PATCH] D154014: [SpecialCaseList] Use Globs instead of Regex

2023-08-09 Thread Ellis Hoag via Phabricator via cfe-commits
ellis updated this revision to Diff 548693.
ellis added a comment.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154014

Files:
  clang/docs/SanitizerSpecialCaseList.rst
  clang/lib/Basic/ProfileList.cpp
  clang/lib/Basic/SanitizerSpecialCaseList.cpp
  llvm/include/llvm/Support/SpecialCaseList.h
  llvm/lib/Support/SpecialCaseList.cpp
  llvm/unittests/Support/SpecialCaseListTest.cpp

Index: llvm/unittests/Support/SpecialCaseListTest.cpp
===
--- llvm/unittests/Support/SpecialCaseListTest.cpp
+++ llvm/unittests/Support/SpecialCaseListTest.cpp
@@ -10,8 +10,11 @@
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/VirtualFileSystem.h"
+#include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
+using testing::HasSubstr;
+using testing::StartsWith;
 using namespace llvm;
 
 namespace {
@@ -19,24 +22,32 @@
 class SpecialCaseListTest : public ::testing::Test {
 protected:
   std::unique_ptr makeSpecialCaseList(StringRef List,
-   std::string ) {
-std::unique_ptr MB = MemoryBuffer::getMemBuffer(List);
+   std::string ,
+   bool UseGlobs = true) {
+auto S = List.str();
+if (UseGlobs)
+  S = (Twine("#!special-case-list-v2\n") + S).str();
+std::unique_ptr MB = MemoryBuffer::getMemBuffer(S);
 return SpecialCaseList::create(MB.get(), Error);
   }
 
-  std::unique_ptr makeSpecialCaseList(StringRef List) {
+  std::unique_ptr makeSpecialCaseList(StringRef List,
+   bool UseGlobs = true) {
 std::string Error;
-auto SCL = makeSpecialCaseList(List, Error);
+auto SCL = makeSpecialCaseList(List, Error, UseGlobs);
 assert(SCL);
 assert(Error == "");
 return SCL;
   }
 
-  std::string makeSpecialCaseListFile(StringRef Contents) {
+  std::string makeSpecialCaseListFile(StringRef Contents,
+  bool UseGlobs = true) {
 int FD;
 SmallString<64> Path;
 sys::fs::createTemporaryFile("SpecialCaseListTest", "temp", FD, Path);
 raw_fd_ostream OF(FD, true, true);
+if (UseGlobs)
+  OF << "#!special-case-list-v2\n";
 OF << Contents;
 OF.close();
 return std::string(Path.str());
@@ -59,10 +70,10 @@
   EXPECT_FALSE(SCL->inSection("", "fun", "hello"));
   EXPECT_FALSE(SCL->inSection("", "src", "hello", "category"));
 
-  EXPECT_EQ(3u, SCL->inSectionBlame("", "src", "hello"));
-  EXPECT_EQ(4u, SCL->inSectionBlame("", "src", "bye"));
-  EXPECT_EQ(5u, SCL->inSectionBlame("", "src", "hi", "category"));
-  EXPECT_EQ(6u, SCL->inSectionBlame("", "src", "", "category"));
+  EXPECT_EQ(4u, SCL->inSectionBlame("", "src", "hello"));
+  EXPECT_EQ(5u, SCL->inSectionBlame("", "src", "bye"));
+  EXPECT_EQ(6u, SCL->inSectionBlame("", "src", "hi", "category"));
+  EXPECT_EQ(7u, SCL->inSectionBlame("", "src", "", "category"));
   EXPECT_EQ(0u, SCL->inSectionBlame("", "src", "hi"));
   EXPECT_EQ(0u, SCL->inSectionBlame("", "fun", "hello"));
   EXPECT_EQ(0u, SCL->inSectionBlame("", "src", "hello", "category"));
@@ -74,31 +85,31 @@
  "\n"
  "[not valid\n",
  Error));
-  EXPECT_TRUE(
-  ((StringRef)Error).startswith("malformed section header on line 3:"));
+  EXPECT_THAT(Error, StartsWith("malformed section header on line 4:"));
 
   EXPECT_EQ(nullptr, makeSpecialCaseList("\n\n\n"
  "[not valid\n",
  Error));
-  EXPECT_TRUE(
-  ((StringRef)Error).startswith("malformed section header on line 4:"));
+  EXPECT_THAT(Error, StartsWith("malformed section header on line 5:"));
 }
 
-TEST_F(SpecialCaseListTest, SectionRegexErrorHandling) {
+TEST_F(SpecialCaseListTest, SectionGlobErrorHandling) {
   std::string Error;
   EXPECT_EQ(makeSpecialCaseList("[address", Error), nullptr);
-  EXPECT_TRUE(((StringRef)Error).startswith("malformed section header "));
+  EXPECT_THAT(Error, StartsWith("malformed section header "));
 
   EXPECT_EQ(makeSpecialCaseList("[[]", Error), nullptr);
-  EXPECT_TRUE(((StringRef)Error).startswith("malformed regex for section [: "));
+  EXPECT_EQ(
+  Error,
+  "malformed section at line 2: '[': invalid glob pattern, unmatched '['");
 
   EXPECT_EQ(makeSpecialCaseList("src:=", Error), nullptr);
-  EXPECT_TRUE(((StringRef)Error).endswith("Supplied regexp was blank"));
+  EXPECT_THAT(Error, HasSubstr("Supplied glob was blank"));
 }
 
 TEST_F(SpecialCaseListTest, Section) {
   std::unique_ptr SCL = makeSpecialCaseList("src:global\n"
- "[sect1|sect2]\n"
+ 

[PATCH] D157334: [clang] Define _MSC_EXTENSIONS on -gnu if -fms-extensions is set

2023-08-09 Thread Aiden Grossman via Phabricator via cfe-commits
aidengrossman added a comment.

Since `-fms-extensions` can be enabled on Linux as well, we should probably 
hoist this further since this patch only accounts for the windows case as I 
just hoist the conditional to be in `addWindowsDefines`. I'll work on getting 
another patch version up in a bit.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157334

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


[PATCH] D157334: [clang] Define _MSC_EXTENSIONS on -gnu if -fms-extensions is set

2023-08-09 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

I'm curious to hear what others think about this (especially @rnk and @hans). I 
think this is the correct approach -- `-fms-extensions` is separate from the 
Windows target; for example, users can enable `__declspec` attributes this way: 
https://godbolt.org/z/GEa3oqWPb So I think that it makes sense to define 
`_MSC_EXTENSIONS` whenever `-fms-extensions` is enabled. But I'm not certain if 
others feel the same way or not or if this approach will cause problems anyone 
can think of.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157334

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


[PATCH] D157331: [clang] Implement C23

2023-08-09 Thread Elliott Hughes via Phabricator via cfe-commits
enh added inline comments.



Comment at: clang/lib/Headers/stdckdint.h:13
+
+#if defined(__GNUC__)
+#define ckd_add(R, A, B) __builtin_add_overflow((A), (B), (R))

ZijunZhao wrote:
> cor3ntin wrote:
> > aaron.ballman wrote:
> > > hiraditya wrote:
> > > > enh wrote:
> > > > > hiraditya wrote:
> > > > > > xbolva00 wrote:
> > > > > > > yabinc wrote:
> > > > > > > > enh wrote:
> > > > > > > > > enh wrote:
> > > > > > > > > > enh wrote:
> > > > > > > > > > > ZijunZhao wrote:
> > > > > > > > > > > > enh wrote:
> > > > > > > > > > > > > is this ever _not_ set for clang?
> > > > > > > > > > > > https://github.com/llvm/llvm-project/blob/main/clang/lib/Headers/stdbool.h#L23
> > > > > > > > > > > > I think it is set?
> > > > > > > > > > > i get an error from
> > > > > > > > > > > ```
> > > > > > > > > > > /tmp$ cat x.c
> > > > > > > > > > > #if defined(__GNUC__)
> > > > > > > > > > > #error foo
> > > > > > > > > > > #endif
> > > > > > > > > > > ```
> > > > > > > > > > > regardless of whether i compile with -std=c11 or 
> > > > > > > > > > > -std=gnu11.
> > > > > > > > > > > neither -ansi nor -pedantic seem to stop it either.
> > > > > > > > > > it does look like it _should_ be possible to not have it 
> > > > > > > > > > set though? 
> > > > > > > > > > llvm/llvm-project/clang/lib/Frontend/InitPreprocessor.cpp 
> > > > > > > > > > has:
> > > > > > > > > > ```
> > > > > > > > > >   if (LangOpts.GNUCVersion != 0) {
> > > > > > > > > > // Major, minor, patch, are given two decimal places 
> > > > > > > > > > each, so 4.2.1 becomes
> > > > > > > > > > // 40201.
> > > > > > > > > > unsigned GNUCMajor = LangOpts.GNUCVersion / 100 / 100;
> > > > > > > > > > unsigned GNUCMinor = LangOpts.GNUCVersion / 100 % 100;
> > > > > > > > > > unsigned GNUCPatch = LangOpts.GNUCVersion % 100;
> > > > > > > > > > Builder.defineMacro("__GNUC__", Twine(GNUCMajor));
> > > > > > > > > > Builder.defineMacro("__GNUC_MINOR__", Twine(GNUCMinor));
> > > > > > > > > > Builder.defineMacro("__GNUC_PATCHLEVEL__", 
> > > > > > > > > > Twine(GNUCPatch));
> > > > > > > > > > Builder.defineMacro("__GXX_ABI_VERSION", "1002");
> > > > > > > > > > 
> > > > > > > > > > if (LangOpts.CPlusPlus) {
> > > > > > > > > >   Builder.defineMacro("__GNUG__", Twine(GNUCMajor));
> > > > > > > > > >   Builder.defineMacro("__GXX_WEAK__");
> > > > > > > > > > }
> > > > > > > > > >   }
> > > > > > > > > > ```
> > > > > > > > > /me wonders whether the right test here is actually `#if 
> > > > > > > > > __has_feature(__builtin_add_overflow)` (etc)...
> > > > > > > > > 
> > > > > > > > > but at this point, you definitely need an llvm person :-)
> > > > > > > > From 
> > > > > > > > https://clang.llvm.org/docs/LanguageExtensions.html#checked-arithmetic-builtins,
> > > > > > > >  we can check them with
> > > > > > > >  __has_builtin(__builtin_add_overflow) && 
> > > > > > > > __has_builtin(__builtin_sub_overflow) && 
> > > > > > > > __has_builtin(__builtin_mul_overflow).
> > > > > > > > I saw some code also checks if __GNUC__ >= 5:
> > > > > > > > 
> > > > > > > > // The __GNUC__ checks can not be removed until we depend on 
> > > > > > > > GCC >= 10.1
> > > > > > > > // which is the first version that returns true for 
> > > > > > > > __has_builtin(__builtin_add_overflow)
> > > > > > > > #if __GNUC__ >= 5 || __has_builtin(__builtin_add_overflow)
> > > > > > > > 
> > > > > > > > I guess we don't need to support real gcc using this header 
> > > > > > > > here. So maybe only checking __has_builtin is enough?
> > > > > > > > 
> > > > > > > > By the way, if __builtin_add_overflow may not appear on some 
> > > > > > > > targets, do we need to modify tests to specify triple like 
> > > > > > > > "-triple "x86_64-unknown-unknown"" in 
> > > > > > > > https://github.com/llvm/llvm-project/blob/main/clang/test/CodeGen/builtins-overflow.c#L5
> > > > > > > >  ?
> > > > > > > > 
> > > > > > > #ifndef __has_builtin // Optional of course.
> > > > > > >   #define __has_builtin(x) 0  // Compatibility with non-clang 
> > > > > > > compilers.
> > > > > > > #endif
> > > > > > > 
> > > > > > > ...
> > > > > > > #if __has_builtin(__builtin_trap)
> > > > > > >   __builtin_trap();
> > > > > > > #else
> > > > > > >   abort();
> > > > > > > #endif
> > > > > > > /me wonders whether the right test here is actually #if 
> > > > > > > __has_feature(__builtin_add_overflow) (etc)...
> > > > > > 
> > > > > > i think that should be added.
> > > > > > 
> > > > > > I guess we also need a with `__STDC_VERSION__ > 202000L`? in 
> > > > > > princple we'd have a C23 number for it but i'm not sure if that has 
> > > > > > been added to clang yet.
> > > > > > i think that should be added.
> > > > > 
> > > > > i was advising the opposite --- now this is a standard C23 feature, 
> > > > > any architectures where __builtin_*_overflow doesn't work need to be 
> > > > > found and fixed. and we'll do that quicker if we unconditionally 

[PATCH] D153914: [clang-cl] Enable concatenation of predefined identifiers

2023-08-09 Thread Aaron Ballman via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG66c43fbd271a: Enable concatenation of predefined identifiers 
(authored by RIscRIpt, committed by aaron.ballman).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153914

Files:
  clang/include/clang/Basic/DiagnosticGroups.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Lex/LiteralSupport.h
  clang/include/clang/Sema/Sema.h
  clang/lib/Lex/LiteralSupport.cpp
  clang/lib/Parse/ParseDeclCXX.cpp
  clang/lib/Parse/ParseExpr.cpp
  clang/lib/Sema/Sema.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/test/Sema/ms_predefined_expr.cpp
  clang/test/Sema/ms_wide_predefined_expr.cpp

Index: clang/test/Sema/ms_wide_predefined_expr.cpp
===
--- clang/test/Sema/ms_wide_predefined_expr.cpp
+++ /dev/null
@@ -1,28 +0,0 @@
-// RUN: %clang_cc1 %s -fsyntax-only -Wno-unused-value -Wmicrosoft -verify -fms-extensions
-// expected-no-diagnostics
-
-// Wide character predefined identifiers
-#define _STR2WSTR(str) L##str
-#define STR2WSTR(str) _STR2WSTR(str)
-void abcdefghi12(void) {
- const wchar_t (*ss)[12] = (__FUNCTION__);
- static int arr[sizeof(STR2WSTR(__FUNCTION__))==12*sizeof(wchar_t) ? 1 : -1];
- const wchar_t (*ss2)[31] = (__FUNCSIG__);
- static int arr2[sizeof(STR2WSTR(__FUNCSIG__))==31*sizeof(wchar_t) ? 1 : -1];
-}
-
-namespace PR13206 {
-void foo(const wchar_t *);
-
-template class A {
-public:
- void method() {
-  foo(L__FUNCTION__);
- }
-};
-
-void bar() {
- A x;
- x.method();
-}
-}
Index: clang/test/Sema/ms_predefined_expr.cpp
===
--- clang/test/Sema/ms_predefined_expr.cpp
+++ clang/test/Sema/ms_predefined_expr.cpp
@@ -1,9 +1,170 @@
 // RUN: %clang_cc1 %s -fsyntax-only -Wmicrosoft -verify -fms-extensions
 
-void f() {
+using size_t = __SIZE_TYPE__;
+
+// Test array initialization
+void array_init() {
  const char a[] = __FUNCTION__; // expected-warning{{initializing an array from a '__FUNCTION__' predefined identifier is a Microsoft extension}}
  const char b[] = __FUNCDNAME__; // expected-warning{{initializing an array from a '__FUNCDNAME__' predefined identifier is a Microsoft extension}}
  const char c[] = __FUNCSIG__; // expected-warning{{initializing an array from a '__FUNCSIG__' predefined identifier is a Microsoft extension}}
  const char d[] = __func__; // expected-warning{{initializing an array from a '__func__' predefined identifier is a Microsoft extension}}
  const char e[] = __PRETTY_FUNCTION__; // expected-warning{{initializing an array from a '__PRETTY_FUNCTION__' predefined identifier is a Microsoft extension}}
+ const wchar_t f[] = L__FUNCTION__; // expected-warning{{initializing an array from a 'L__FUNCTION__' predefined identifier is a Microsoft extension}}
+ const wchar_t g[] = L__FUNCSIG__; // expected-warning{{initializing an array from a 'L__FUNCSIG__' predefined identifier is a Microsoft extension}}
+}
+
+// Test function local identifiers outside of a function
+const char* g_function = __FUNCTION__;// expected-warning{{predefined identifier is only valid inside function}}
+const char* g_function_lconcat = "" __FUNCTION__; // expected-warning{{predefined identifier is only valid inside function}} \
+  // expected-warning{{expansion of predefined identifier '__FUNCTION__' to a string literal is a Microsoft extension}}
+const char* g_function_rconcat = __FUNCTION__ ""; // expected-warning{{predefined identifier is only valid inside function}} \
+  // expected-warning{{expansion of predefined identifier '__FUNCTION__' to a string literal is a Microsoft extension}}
+
+namespace NS
+{
+  const char* function = __FUNCTION__;// expected-warning{{predefined identifier is only valid inside function}}
+  const char* function_lconcat = "" __FUNCTION__; // expected-warning{{predefined identifier is only valid inside function}} \
+  // expected-warning{{expansion of predefined identifier '__FUNCTION__' to a string literal is a Microsoft extension}}
+  const char* function_rconcat = __FUNCTION__ ""; // expected-warning{{predefined identifier is only valid inside function}} \
+  // expected-warning{{expansion of predefined identifier '__FUNCTION__' to a string literal is a Microsoft extension}}
+
+  struct S
+  {
+static constexpr const char* function = __FUNCTION__;// expected-warning{{predefined identifier is only valid inside function}}
+static constexpr const char* function_lconcat = "" __FUNCTION__; // expected-warning{{predefined identifier is only valid inside function}} \
+ // 

[clang] 66c43fb - Enable concatenation of predefined identifiers

2023-08-09 Thread Aaron Ballman via cfe-commits

Author: Richard Dzenis
Date: 2023-08-09T13:55:03-04:00
New Revision: 66c43fbd271a8231187bfcb73428ed663606585d

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

LOG: Enable concatenation of predefined identifiers

Predefined identifiers like __FUNCTION__ are treated like string
literals in MSVC, which means they can be concatentated together with
an adjacent string literal. Clang now supports this behavior as well,
in Microsoft extensions mode.

Fixes https://github.com/llvm/llvm-project/issues/63563
Differential Revision: https://reviews.llvm.org/D153914

Added: 


Modified: 
clang/include/clang/Basic/DiagnosticGroups.td
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/include/clang/Lex/LiteralSupport.h
clang/include/clang/Sema/Sema.h
clang/lib/Lex/LiteralSupport.cpp
clang/lib/Parse/ParseDeclCXX.cpp
clang/lib/Parse/ParseExpr.cpp
clang/lib/Sema/Sema.cpp
clang/lib/Sema/SemaExpr.cpp
clang/test/Sema/ms_predefined_expr.cpp

Removed: 
clang/test/Sema/ms_wide_predefined_expr.cpp



diff  --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index a399b63161f894..850c3a092e6a9c 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -1207,6 +1207,8 @@ def MicrosoftEndOfFile : 
DiagGroup<"microsoft-end-of-file">;
 def MicrosoftInaccessibleBase : DiagGroup<"microsoft-inaccessible-base">;
 def MicrosoftStaticAssert : DiagGroup<"microsoft-static-assert">;
 def MicrosoftInitFromPredefined : DiagGroup<"microsoft-init-from-predefined">;
+def MicrosoftStringLiteralFromPredefined : DiagGroup<
+"microsoft-string-literal-from-predefined">;
 
 // Aliases.
 def : DiagGroup<"msvc-include", [MicrosoftInclude]>;
@@ -1224,7 +1226,8 @@ def Microsoft : DiagGroup<"microsoft",
  MicrosoftFlexibleArray, MicrosoftExtraQualification, MicrosoftCast,
  MicrosoftConstInit, MicrosoftVoidPseudoDtor, MicrosoftAnonTag,
  MicrosoftCommentPaste, MicrosoftEndOfFile, MicrosoftStaticAssert,
- MicrosoftInitFromPredefined, MicrosoftInconsistentDllImport]>;
+ MicrosoftInitFromPredefined, MicrosoftStringLiteralFromPredefined,
+ MicrosoftInconsistentDllImport]>;
 
 def ClangClPch : DiagGroup<"clang-cl-pch">;
 

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index bbd40a16040398..f767dde3c55918 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -115,6 +115,9 @@ def ext_predef_outside_function : Warning<
 def ext_init_from_predefined : ExtWarn<
   "initializing an array from a '%0' predefined identifier is a Microsoft 
extension">,
   InGroup;
+def ext_string_literal_from_predefined : ExtWarn<
+  "expansion of predefined identifier '%0' to a string literal is a Microsoft 
extension">,
+  InGroup;
 def warn_float_overflow : Warning<
   "magnitude of floating-point constant too large for type %0; maximum is %1">,
InGroup;

diff  --git a/clang/include/clang/Lex/LiteralSupport.h 
b/clang/include/clang/Lex/LiteralSupport.h
index 0a45f32326f4d1..8926577be764d0 100644
--- a/clang/include/clang/Lex/LiteralSupport.h
+++ b/clang/include/clang/Lex/LiteralSupport.h
@@ -36,6 +36,15 @@ class LangOptions;
 /// Copy characters from Input to Buf, expanding any UCNs.
 void expandUCNs(SmallVectorImpl , StringRef Input);
 
+/// Return true if the token corresponds to a function local predefined macro,
+/// which expands to a string literal, that can be concatenated with other
+/// string literals (only in Microsoft mode).
+bool isFunctionLocalStringLiteralMacro(tok::TokenKind K, const LangOptions 
);
+
+/// Return true if the token is a string literal, or a function local
+/// predefined macro, which expands to a string literal.
+bool tokenIsLikeStringLiteral(const Token , const LangOptions );
+
 /// NumericLiteralParser - This performs strict semantic analysis of the 
content
 /// of a ppnumber, classifying it as either integer, floating, or erroneous,
 /// determines the radix of the value and can convert it to a useful value.

diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 2b96369b76fb46..0316036f89a5bc 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -3613,6 +3613,10 @@ class Sema final {
   /// in a 'block', this returns the containing context.
   NamedDecl *getCurFunctionOrMethodDecl() const;
 
+  /// getCurLocalScopeDecl - Return the Decl for either of:
+  /// block, lambda, captured statement, function, or nullptr.
+  Decl *getCurLocalScopeDecl();
+
   /// Add this decl to the scope shadowed decl chains.
   void PushOnScopeChains(NamedDecl *D, Scope 

[PATCH] D157331: [clang] Implement C23

2023-08-09 Thread Zijun Zhao via Phabricator via cfe-commits
ZijunZhao added inline comments.



Comment at: clang/lib/Headers/stdckdint.h:13
+
+#if defined(__GNUC__)
+#define ckd_add(R, A, B) __builtin_add_overflow((A), (B), (R))

cor3ntin wrote:
> aaron.ballman wrote:
> > hiraditya wrote:
> > > enh wrote:
> > > > hiraditya wrote:
> > > > > xbolva00 wrote:
> > > > > > yabinc wrote:
> > > > > > > enh wrote:
> > > > > > > > enh wrote:
> > > > > > > > > enh wrote:
> > > > > > > > > > ZijunZhao wrote:
> > > > > > > > > > > enh wrote:
> > > > > > > > > > > > is this ever _not_ set for clang?
> > > > > > > > > > > https://github.com/llvm/llvm-project/blob/main/clang/lib/Headers/stdbool.h#L23
> > > > > > > > > > > I think it is set?
> > > > > > > > > > i get an error from
> > > > > > > > > > ```
> > > > > > > > > > /tmp$ cat x.c
> > > > > > > > > > #if defined(__GNUC__)
> > > > > > > > > > #error foo
> > > > > > > > > > #endif
> > > > > > > > > > ```
> > > > > > > > > > regardless of whether i compile with -std=c11 or -std=gnu11.
> > > > > > > > > > neither -ansi nor -pedantic seem to stop it either.
> > > > > > > > > it does look like it _should_ be possible to not have it set 
> > > > > > > > > though? 
> > > > > > > > > llvm/llvm-project/clang/lib/Frontend/InitPreprocessor.cpp has:
> > > > > > > > > ```
> > > > > > > > >   if (LangOpts.GNUCVersion != 0) {
> > > > > > > > > // Major, minor, patch, are given two decimal places 
> > > > > > > > > each, so 4.2.1 becomes
> > > > > > > > > // 40201.
> > > > > > > > > unsigned GNUCMajor = LangOpts.GNUCVersion / 100 / 100;
> > > > > > > > > unsigned GNUCMinor = LangOpts.GNUCVersion / 100 % 100;
> > > > > > > > > unsigned GNUCPatch = LangOpts.GNUCVersion % 100;
> > > > > > > > > Builder.defineMacro("__GNUC__", Twine(GNUCMajor));
> > > > > > > > > Builder.defineMacro("__GNUC_MINOR__", Twine(GNUCMinor));
> > > > > > > > > Builder.defineMacro("__GNUC_PATCHLEVEL__", 
> > > > > > > > > Twine(GNUCPatch));
> > > > > > > > > Builder.defineMacro("__GXX_ABI_VERSION", "1002");
> > > > > > > > > 
> > > > > > > > > if (LangOpts.CPlusPlus) {
> > > > > > > > >   Builder.defineMacro("__GNUG__", Twine(GNUCMajor));
> > > > > > > > >   Builder.defineMacro("__GXX_WEAK__");
> > > > > > > > > }
> > > > > > > > >   }
> > > > > > > > > ```
> > > > > > > > /me wonders whether the right test here is actually `#if 
> > > > > > > > __has_feature(__builtin_add_overflow)` (etc)...
> > > > > > > > 
> > > > > > > > but at this point, you definitely need an llvm person :-)
> > > > > > > From 
> > > > > > > https://clang.llvm.org/docs/LanguageExtensions.html#checked-arithmetic-builtins,
> > > > > > >  we can check them with
> > > > > > >  __has_builtin(__builtin_add_overflow) && 
> > > > > > > __has_builtin(__builtin_sub_overflow) && 
> > > > > > > __has_builtin(__builtin_mul_overflow).
> > > > > > > I saw some code also checks if __GNUC__ >= 5:
> > > > > > > 
> > > > > > > // The __GNUC__ checks can not be removed until we depend on GCC 
> > > > > > > >= 10.1
> > > > > > > // which is the first version that returns true for 
> > > > > > > __has_builtin(__builtin_add_overflow)
> > > > > > > #if __GNUC__ >= 5 || __has_builtin(__builtin_add_overflow)
> > > > > > > 
> > > > > > > I guess we don't need to support real gcc using this header here. 
> > > > > > > So maybe only checking __has_builtin is enough?
> > > > > > > 
> > > > > > > By the way, if __builtin_add_overflow may not appear on some 
> > > > > > > targets, do we need to modify tests to specify triple like 
> > > > > > > "-triple "x86_64-unknown-unknown"" in 
> > > > > > > https://github.com/llvm/llvm-project/blob/main/clang/test/CodeGen/builtins-overflow.c#L5
> > > > > > >  ?
> > > > > > > 
> > > > > > #ifndef __has_builtin // Optional of course.
> > > > > >   #define __has_builtin(x) 0  // Compatibility with non-clang 
> > > > > > compilers.
> > > > > > #endif
> > > > > > 
> > > > > > ...
> > > > > > #if __has_builtin(__builtin_trap)
> > > > > >   __builtin_trap();
> > > > > > #else
> > > > > >   abort();
> > > > > > #endif
> > > > > > /me wonders whether the right test here is actually #if 
> > > > > > __has_feature(__builtin_add_overflow) (etc)...
> > > > > 
> > > > > i think that should be added.
> > > > > 
> > > > > I guess we also need a with `__STDC_VERSION__ > 202000L`? in princple 
> > > > > we'd have a C23 number for it but i'm not sure if that has been added 
> > > > > to clang yet.
> > > > > i think that should be added.
> > > > 
> > > > i was advising the opposite --- now this is a standard C23 feature, any 
> > > > architectures where __builtin_*_overflow doesn't work need to be found 
> > > > and fixed. and we'll do that quicker if we unconditionally expose these 
> > > > and (more importantly!) run the tests.
> > > > 
> > > > > I guess we also need a with __STDC_VERSION__ > 202000L?
> > > > 
> > > > _personally_ i think that's silly because you can't hide the header 
> > > > file, so it doesn't 

[PATCH] D154784: [clang] Fix crash caused by PseudoObjectExprBitfields::NumSubExprs overflow

2023-08-09 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added inline comments.



Comment at: clang/include/clang/AST/Stmt.h:596-597
 
-// These don't need to be particularly wide, because they're
-// strictly limited by the forms of expressions we permit.
-unsigned NumSubExprs : 8;
-unsigned ResultIndex : 32 - 8 - NumExprBits;
+unsigned NumSubExprs : 16;
+unsigned ResultIndex : 16;
   };

aaron.ballman wrote:
> yronglin wrote:
> > dblaikie wrote:
> > > dblaikie wrote:
> > > > aaron.ballman wrote:
> > > > > dblaikie wrote:
> > > > > > Could/should we add some error checking in the ctor to assert that 
> > > > > > we don't overflow these longer values/just hit the bug later on?
> > > > > > 
> > > > > > (& could we use `unsigned short` here rather than bitfields?)
> > > > > We've already got them packed in with other bit-fields from the 
> > > > > expression bits, so I think it's reasonable to continue the pattern 
> > > > > of using bit-fields (that way we don't accidentally end up with 
> > > > > padding between the unnamed bits at the start and the named bits in 
> > > > > this object).
> > > > > 
> > > > > I think adding some assertions would not be a bad idea as a follow-up.
> > > > Maybe some unconditional (rather than only in asserts builds) error 
> > > > handling? (report_fatal_error, if this is low priority enough to not 
> > > > have an elegant failure mode, but something where we don't just 
> > > > overflow and carry on would be good... )
> > > Ping on this? I worry this code has just punted the same bug further 
> > > down, but not plugged the hole/ensured we don't overflow on novel/larger 
> > > inputs.
> > Sorry for the late reply, I was looking through the emails and found this. 
> > I agree add some assertions to check the value is a good idea, It's easy to 
> > help people catch bugs, at least with when `-DLLVM_ENABLE_ASSERTIONS=ON`, 
> > and I'm glad to work on it, but one thing that worries me is that, in 
> > ASTReader, we access this field directly, not through the constructor or 
> > accessor, and we have to add assertions everywhere. 
> > https://github.com/llvm/llvm-project/blob/05b4310c8aec7a050574277ced08a0ab86b27681/clang/lib/Serialization/ASTReaderStmt.cpp#L1382
> I don't think we have to add too many assertions. As best I can tell, we'll 
> need one in each of the `PseudoObjectExpr` constructors and one in 
> `ASTStmtReader::VisitPseudoObjectExpr()`, but those are the only places we 
> assign a value into the bit-field. Three assertions isn't a lot, but if we're 
> worried, we could add a setter method that does the assertion and use the 
> setter in all three places.
My concern wasn't (well, wasn't entirely) about adding more assertions - but 
about having a reliable error here. The patch only makes the sizes larger, but 
doesn't have a hard-stop in case those sizes are exceeded again (which, 
admittedly, is much harder to do - maybe it's totally unreachable now, for all 
practical purposes?) 

I suspect with more carefully constructed recursive inputs could still reach 
the higher limit & I think it'd be good to fail hard in that case in some way? 
(it's probably rare enough that a report_fatal_error would be 
not-the-worst-thing-ever)

But good assertions would be nice too (the old code only failed when you hit 
/exactly/ on just the overflow value, and any more than that the wraparound 
would not crash/fail, but misbehave) - I did add the necessary assertion to 
ArrayRef (begin <= end) which would've helped detect this more reliably, but 
some assert checking for overflow in the ctor would be good too (with all the 
usual nuance/care in checking for overflow) - unless we're going to make that 
into a fatal or other real error.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154784

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


[PATCH] D157526: [clang][Sema] Remove irrelevant diagnostics from constraint satisfaction failure

2023-08-09 Thread Takuya Shimizu via Phabricator via cfe-commits
hazohelet created this revision.
hazohelet added reviewers: aaron.ballman, erichkeane, tbaeder, shafik.
Herald added a project: All.
hazohelet requested review of this revision.
Herald added a project: clang.

BEFORE this patch, when clang handles constraints like `C1 || C2` where `C1` 
evaluates to false and `C2` evaluates to true, it emitted irrelevant 
diagnostics about the falsity of `C1`.
This patch removes the irrelevant diagnostic information generated during the 
evaluation of `C1` if `C2` evaluates to true.

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


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D157526

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Sema/SemaConcept.cpp
  clang/test/SemaTemplate/concepts.cpp


Index: clang/test/SemaTemplate/concepts.cpp
===
--- clang/test/SemaTemplate/concepts.cpp
+++ clang/test/SemaTemplate/concepts.cpp
@@ -994,3 +994,40 @@
 }
 
 }
+
+namespace GH54678 {
+template
+concept True = true;
+
+template
+concept False = false; // expected-note 9 {{'false' evaluated to false}}
+
+template
+concept Irrelevant = false;
+
+template 
+concept ErrorRequires = requires(ErrorRequires auto x) { x; }; // 
expected-error {{unknown type name 'ErrorRequires'}}
+
+template void aaa(T t) // expected-note {{candidate template ignored: 
constraints not satisfied}}
+requires (False || False) || False {} // expected-note 3 {{'int' does 
not satisfy 'False'}}
+template void bbb(T t) // expected-note {{candidate template ignored: 
constraints not satisfied}}
+requires (False || False) && True {} // expected-note 2 {{'long' does 
not satisfy 'False'}}
+template void ccc(T t) // expected-note {{candidate template ignored: 
constraints not satisfied}}
+requires (True || Irrelevant) && False {} // expected-note 
{{'unsigned long' does not satisfy 'False'}}
+template void ddd(T t) // expected-note {{candidate template ignored: 
constraints not satisfied}}
+requires (Irrelevant || True) && False {} // expected-note {{'int' 
does not satisfy 'False'}}
+template void eee(T t) // expected-note {{candidate template ignored: 
constraints not satisfied}}
+requires (Irrelevant || Irrelevant || True) && False {} // 
expected-note {{'long' does not satisfy 'False'}}
+
+template void fff(T t) // expected-note {{candidate template ignored: 
constraints not satisfied}}
+requires((ErrorRequires || False || True) && False) {} // 
expected-note {{'unsigned long' does not satisfy 'False'}}
+
+void test() {
+aaa(42); // expected-error {{no matching function}}
+bbb(42L); // expected-error{{no matching function}}
+ccc(42UL); // expected-error {{no matching function}}
+ddd(42); // expected-error {{no matching function}}
+eee(42L); // expected-error {{no matching function}}
+fff(42UL); // expected-error {{no matching function}}
+}
+}
Index: clang/lib/Sema/SemaConcept.cpp
===
--- clang/lib/Sema/SemaConcept.cpp
+++ clang/lib/Sema/SemaConcept.cpp
@@ -183,6 +183,7 @@
   ConstraintExpr = ConstraintExpr->IgnoreParenImpCasts();
 
   if (LogicalBinOp BO = ConstraintExpr) {
+auto EffectiveDetailEnd = Satisfaction.Details.end();
 ExprResult LHSRes = calculateConstraintSatisfaction(
 S, BO.getLHS(), Satisfaction, Evaluator);
 
@@ -216,6 +217,11 @@
 if (RHSRes.isInvalid())
   return ExprError();
 
+bool IsRHSSatisfied = Satisfaction.IsSatisfied;
+if (BO.isOr() && IsRHSSatisfied)
+  Satisfaction.Details.erase(EffectiveDetailEnd,
+ Satisfaction.Details.end());
+
 return BO.recreateBinOp(S, LHSRes, RHSRes);
   }
 
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -125,6 +125,8 @@
   of a base class is not called in the constructor of its derived class.
 - Clang no longer emits ``-Wmissing-variable-declarations`` for variables 
declared
   with the ``register`` storage class.
+- Clang no longer emits irrelevant notes about unsatisfied constraint 
expressions
+  on the left-hand side of ``||`` when the right-hand side constraint is 
satisfied.
 
 Bug Fixes in This Version
 -


Index: clang/test/SemaTemplate/concepts.cpp
===
--- clang/test/SemaTemplate/concepts.cpp
+++ clang/test/SemaTemplate/concepts.cpp
@@ -994,3 +994,40 @@
 }
 
 }
+
+namespace GH54678 {
+template
+concept True = true;
+
+template
+concept False = false; // expected-note 9 {{'false' evaluated to false}}
+
+template
+concept Irrelevant = false;
+
+template 
+concept ErrorRequires = requires(ErrorRequires auto x) { x; }; // expected-error {{unknown type name 'ErrorRequires'}}
+
+template void aaa(T t) // expected-note {{candidate template ignored: constraints not satisfied}}
+requires (False || False) || 

[PATCH] D157394: [clang][DeclPrinter] Improve AST print of function attributes

2023-08-09 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D157394#4572777 , 
@giulianobelinassi wrote:

> This patch do not address attributes in variables nor the __declspec case, as 
> D141714  do. His patch looks cleaner and I 
> can surely coordinate with @strimo378 to also fix those cases, but I want an 
> answer to the tblgen question first to see if we decide to drop the tblgen 
> solution or not.

Yeah, the two patches are trying to solve the same problem but for different 
parts of the language.

In terms of the tablegen approach, what you have in D141714 
 is along the same lines of what I was 
thinking of, though I've not had the chance to give it a thorough review yet. 
It keeps all of the knowledge about the specifics of the attributes in Attr.td 
instead of putting special per-attribute logic into the declaration printer, 
which is what I was mostly concerned about.




Comment at: clang/lib/AST/DeclPrinter.cpp:259
+case attr::Final:
+case attr::Override:
+  return AttrLocation::AfterDecl;

giulianobelinassi wrote:
> @aaron.ballman @erichkeane 
> 
> Is this enough to describe the position of the attribute kind, or should it 
> go for a tblgen approach, as I did in D141714? This here looks much cleaner 
> than the tblgen IMHO.
Oofda, I forgot that we model those as keyword attributes. `override` and 
`final` (and other keyword attributes) are a bit trickier than just "before" or 
"after" because there's a very particular order in which those can be parsed 
grammatically, especially for functions: https://godbolt.org/z/ad5qecbrj

Thinking out loud: perhaps an approach to solving this is to sort the 
attributes by source location. So all the before attributes are written in the 
same order as they were in source, as are all of the after attributes. So long 
as we're skipping over implicit attributes, this seems like it should keep the 
order of the attributes correct.

A different alternative that's possibly more work than it's worth: the decl 
printer could dispatch to a table-genned function to ask the attribute "do you 
want to be printed now?" based on what part of the declaration we've already 
printed. This would require the decl printer to know e.g., "I've finished 
printing the parameter list but haven't yet printed cv qualifiers" and pass 
that information along to the attribute; individual attributes with special 
rules could supply special logic in Attr.td to say "the attribute should be 
printed after the function parameter list and after the cv and ref qualifiers, 
but before the override/final keywords" while most attributes can hopefully get 
away with whatever the default behavior is coming out of tablegen.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157394

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


[PATCH] D156948: [clang][modules] Add -Wsystem-headers-in-module=

2023-08-09 Thread Ben Langmuir 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 rGdc5cbba3196d: [clang][modules] Add 
-Wsystem-headers-in-module= (authored by benlangmuir).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156948

Files:
  clang/include/clang/Basic/DiagnosticOptions.h
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Frontend/CompilerInstance.cpp
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
  clang/test/ClangScanDeps/Wsystem-headers-in-module.c
  clang/test/Modules/Wsystem-headers-in-module.c

Index: clang/test/Modules/Wsystem-headers-in-module.c
===
--- /dev/null
+++ clang/test/Modules/Wsystem-headers-in-module.c
@@ -0,0 +1,32 @@
+// Check that Wsystem-headers-in-module shows diagnostics in the named system
+// module, but not in other system headers or modules.
+
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+
+// RUN: %clang_cc1 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t/mcp \
+// RUN:   -isystem %t/sys %t/tu.c -fsyntax-only -Wextra-semi -Wsystem-headers-in-module=sys_mod \
+// RUN:   2>&1 | FileCheck %s
+
+// CHECK-NOT: warning:
+// CHECK: sys_mod.h:2:7: warning: extra ';'
+// CHECK-NOT: warning:
+
+//--- sys/other_sys_header.h
+int x;;
+//--- sys_mod.h
+#include "dependent_sys_mod.h"
+int y;;
+//--- other_sys_mod.h
+int z;;
+//--- dependent_sys_mod.h
+int w;;
+//--- module.modulemap
+module sys_mod [system] { header "sys_mod.h" }
+module other_sys_mod [system] { header "other_sys_mod.h" }
+module dependent_sys_mod [system] { header "dependent_sys_mod.h" }
+
+//--- tu.c
+#include "sys_mod.h"
+#include "other_sys_mod.h"
+#include "other_sys_header.h"
Index: clang/test/ClangScanDeps/Wsystem-headers-in-module.c
===
--- /dev/null
+++ clang/test/ClangScanDeps/Wsystem-headers-in-module.c
@@ -0,0 +1,56 @@
+// Check that Wsystem-headers-in-module shows diagnostics in the named system
+// module, but not in other system headers or modules when built with explicit
+// modules.
+
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: sed "s|DIR|%/t|g" %t/cdb.json.template > %t/cdb.json
+
+// RUN: clang-scan-deps -compilation-database %t/cdb.json -format experimental-full > %t/deps.json
+
+// RUN: %deps-to-rsp %t/deps.json --module-name=dependent_sys_mod > %t/dependent_sys_mod.rsp
+// RUN: %deps-to-rsp %t/deps.json --module-name=sys_mod > %t/sys_mod.rsp
+// RUN: %deps-to-rsp %t/deps.json --module-name=other_sys_mod > %t/other_sys_mod.rsp
+// RUN: %deps-to-rsp %t/deps.json --tu-index 0 > %t/tu.rsp
+
+// RUN: %clang @%t/dependent_sys_mod.rsp -verify
+// RUN: %clang @%t/sys_mod.rsp -verify
+// RUN: %clang @%t/other_sys_mod.rsp -verify
+// RUN: %clang @%t/tu.rsp -verify
+
+// CHECK-NOT: warning:
+// CHECK: sys_mod.h:2:7: warning: extra ';'
+// CHECK-NOT: warning:
+
+//--- cdb.json.template
+[{
+  "directory": "DIR",
+  "command": "clang -fsyntax-only -fmodules -fimplicit-module-maps -fmodules-cache-path=DIR/mcp DIR/tu.c -isystem DIR/sys -Wextra-semi -Wsystem-headers-in-module=sys_mod",
+  "file": "DIR/tu.c"
+}]
+
+//--- sys/other_sys_header.h
+int x;;
+
+//--- sys_mod.h
+#include "dependent_sys_mod.h"
+int y;; // expected-warning {{extra ';' outside of a function}}
+
+//--- other_sys_mod.h
+int z;;
+// expected-no-diagnostics
+
+//--- dependent_sys_mod.h
+int w;;
+// expected-no-diagnostics
+
+//--- module.modulemap
+module sys_mod [system] { header "sys_mod.h" }
+module other_sys_mod [system] { header "other_sys_mod.h" }
+module dependent_sys_mod [system] { header "dependent_sys_mod.h" }
+
+//--- tu.c
+#include "sys_mod.h"
+#include "other_sys_mod.h"
+#include "other_sys_header.h"
+// expected-no-diagnostics
Index: clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
===
--- clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
+++ clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
@@ -12,6 +12,7 @@
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Tooling/DependencyScanning/DependencyScanningWorker.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/Support/BLAKE3.h"
 #include "llvm/Support/StringSaver.h"
 #include 
@@ -172,6 +173,13 @@
 CI.getHeaderSearchOpts().ModulesIgnoreMacros.clear();
   }
 
+  // Apply -Wsystem-headers-in-module for the current module.
+  if (llvm::is_contained(CI.getDiagnosticOpts().SystemHeaderWarningsModules,
+ Deps.ID.ModuleName))
+CI.getDiagnosticOpts().Warnings.push_back("system-headers");
+  // Remove the now unused option(s).
+  CI.getDiagnosticOpts().SystemHeaderWarningsModules.clear();
+
   Optimize(CI);
 
   return 

[clang] dc5cbba - [clang][modules] Add -Wsystem-headers-in-module=

2023-08-09 Thread Ben Langmuir via cfe-commits

Author: Ben Langmuir
Date: 2023-08-09T10:40:53-07:00
New Revision: dc5cbba3196db61d57b7d84118732a6c96d8ee64

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

LOG: [clang][modules] Add -Wsystem-headers-in-module=

Add a way to enable -Wsystem-headers only for a specific module. This is
useful for validating a module that would otherwise not see system
header diagnostics without being flooded by diagnostics for unrelated
headers/modules. It's relatively common for a module to be marked
[system] but still wish to validate itself explicitly.

rdar://113401565

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

Added: 
clang/test/ClangScanDeps/Wsystem-headers-in-module.c
clang/test/Modules/Wsystem-headers-in-module.c

Modified: 
clang/include/clang/Basic/DiagnosticOptions.h
clang/include/clang/Driver/Options.td
clang/lib/Driver/ToolChains/Clang.cpp
clang/lib/Frontend/CompilerInstance.cpp
clang/lib/Serialization/ASTReader.cpp
clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticOptions.h 
b/clang/include/clang/Basic/DiagnosticOptions.h
index 7e218b9c71e69e..0f3120859ecef6 100644
--- a/clang/include/clang/Basic/DiagnosticOptions.h
+++ b/clang/include/clang/Basic/DiagnosticOptions.h
@@ -123,6 +123,10 @@ class DiagnosticOptions : public 
RefCountedBase{
   /// default).
   std::vector VerifyPrefixes;
 
+  /// The list of -Wsystem-header-in-module=... options used to override
+  /// whether -Wsystem-headers is enabled on a per-module basis.
+  std::vector SystemHeaderWarningsModules;
+
 public:
   // Define accessors/mutators for diagnostic options of enumeration type.
 #define DIAGOPT(Name, Bits, Default)

diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 0ad2fa0112328d..1166dd28b8331c 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -843,6 +843,10 @@ def Wall : Flag<["-"], "Wall">, Group, 
Flags<[CC1Option, HelpHidden]>;
 def WCL4 : Flag<["-"], "WCL4">, Group, Flags<[CC1Option, HelpHidden]>;
 def Wsystem_headers : Flag<["-"], "Wsystem-headers">, Group, 
Flags<[CC1Option, HelpHidden]>;
 def Wno_system_headers : Flag<["-"], "Wno-system-headers">, Group, 
Flags<[CC1Option, HelpHidden]>;
+def Wsystem_headers_in_module_EQ : Joined<["-"], "Wsystem-headers-in-module=">,
+  Flags<[CC1Option, HelpHidden]>, MetaVarName<"">,
+  HelpText<"Enable -Wsystem-headers when building ">,
+  MarshallingInfoStringVector>;
 def Wdeprecated : Flag<["-"], "Wdeprecated">, Group, 
Flags<[CC1Option]>,
   HelpText<"Enable warnings for deprecated constructs and define 
__DEPRECATED">;
 def Wno_deprecated : Flag<["-"], "Wno-deprecated">, Group, 
Flags<[CC1Option]>;

diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index ec01264bbc9926..00f2d7140db5d5 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -5973,6 +5973,8 @@ void Clang::ConstructJob(Compilation , const JobAction 
,
 A->render(Args, CmdArgs);
   }
 
+  Args.AddAllArgs(CmdArgs, options::OPT_Wsystem_headers_in_module_EQ);
+
   if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
 CmdArgs.push_back("-pedantic");
   Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);

diff  --git a/clang/lib/Frontend/CompilerInstance.cpp 
b/clang/lib/Frontend/CompilerInstance.cpp
index 92e0b74e38f0af..0bbfb2a81acae6 100644
--- a/clang/lib/Frontend/CompilerInstance.cpp
+++ b/clang/lib/Frontend/CompilerInstance.cpp
@@ -39,6 +39,7 @@
 #include "clang/Serialization/ASTReader.h"
 #include "clang/Serialization/GlobalModuleIndex.h"
 #include "clang/Serialization/InMemoryModuleCache.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/ScopeExit.h"
 #include "llvm/ADT/Statistic.h"
 #include "llvm/Config/llvm-config.h"
@@ -1216,7 +1217,9 @@ compileModuleImpl(CompilerInstance , 
SourceLocation ImportLoc,
   // Don't free the remapped file buffers; they are owned by our caller.
   PPOpts.RetainRemappedFileBuffers = true;
 
-  Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
+  DiagnosticOptions  = Invocation->getDiagnosticOpts();
+
+  DiagOpts.VerifyDiagnostics = 0;
   assert(ImportingInstance.getInvocation().getModuleHash() ==
  Invocation->getModuleHash() && "Module hash mismatch!");
 
@@ -1233,6 +1236,9 @@ compileModuleImpl(CompilerInstance , 
SourceLocation ImportLoc,
ImportingInstance.getDiagnosticClient()),
  /*ShouldOwnClient=*/true);
 
+  if (llvm::is_contained(DiagOpts.SystemHeaderWarningsModules, ModuleName))
+Instance.getDiagnostics().setSuppressSystemWarnings(false);
+
   if 

[PATCH] D157410: [Flang][Driver] Enable Rpass and other R family options.

2023-08-09 Thread victorkingi via Phabricator via cfe-commits
victorkingi updated this revision to Diff 548675.
victorkingi added a comment.

refactoring Options.td


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157410

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Flang.cpp
  flang/test/Driver/driver-help-hidden.f90
  flang/test/Driver/driver-help.f90
  flang/test/Driver/frontend-forwarding.f90

Index: flang/test/Driver/frontend-forwarding.f90
===
--- flang/test/Driver/frontend-forwarding.f90
+++ flang/test/Driver/frontend-forwarding.f90
@@ -22,6 +22,13 @@
 ! RUN: -fppc-native-vector-element-order \
 ! RUN: -mllvm -print-before-all \
 ! RUN: -save-temps=obj \
+! RUN: -Rpass \
+! RUN: -Rpass-missed \
+! RUN: -Rpass-analysis \
+! RUN: -Rno-pass \
+! RUN: -Reverything \
+! RUN: -Rno-everything \
+! RUN: -Rpass=inline \
 ! RUN: -P \
 ! RUN:   | FileCheck %s
 
@@ -44,5 +51,12 @@
 ! CHECK: "-flang-experimental-hlfir"
 ! CHECK: "-fno-ppc-native-vector-element-order"
 ! CHECK: "-fppc-native-vector-element-order"
+! CHECK: "-Rpass"
+! CHECK: "-Rpass-missed"
+! CHECK: "-Rpass-analysis"
+! CHECK: "-Rno-pass"
+! CHECK: "-Reverything"
+! CHECK: "-Rno-everything"
+! CHECK: "-Rpass=inline"
 ! CHECK: "-mllvm" "-print-before-all"
 ! CHECK: "-save-temps=obj"
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -91,6 +91,10 @@
 ! HELP-NEXT: -print-effective-triple Print the effective target triple
 ! HELP-NEXT: -print-target-triplePrint the normalized target triple
 ! HELP-NEXT: -P Disable linemarker output in -E mode
+! HELP-NEXT: -Rpass-analysis= Report transformation analysis from optimization passes whose name matches the given POSIX regular expression
+! HELP-NEXT: -Rpass-missed=   Report missed transformations by optimization passes whose name matches the given POSIX regular expression
+! HELP-NEXT: -Rpass=  Report transformations performed by optimization passes whose name matches the given POSIX regular expression
+! HELP-NEXT: -R  Enable the specified remark
 ! HELP-NEXT: -save-temps=Save intermediate compilation results.
 ! HELP-NEXT: -save-tempsSave intermediate compilation results
 ! HELP-NEXT: -std=   Language standard to compile for
@@ -214,6 +218,10 @@
 ! HELP-FC1-NEXT: -pic-level   Value for __PIC__
 ! HELP-FC1-NEXT: -plugin  Use the named plugin action instead of the default action (use "help" to list available options)
 ! HELP-FC1-NEXT: -P Disable linemarker output in -E mode
+! HELP-FC1-NEXT: -Rpass-analysis= Report transformation analysis from optimization passes whose name matches the given POSIX regular expression
+! HELP-FC1-NEXT: -Rpass-missed=   Report missed transformations by optimization passes whose name matches the given POSIX regular expression
+! HELP-FC1-NEXT: -Rpass=  Report transformations performed by optimization passes whose name matches the given POSIX regular expression
+! HELP-FC1-NEXT: -R  Enable the specified remark
 ! HELP-FC1-NEXT: -save-temps=Save intermediate compilation results.
 ! HELP-FC1-NEXT: -save-tempsSave intermediate compilation results
 ! HELP-FC1-NEXT: -std=   Language standard to compile for
Index: flang/test/Driver/driver-help-hidden.f90
===
--- flang/test/Driver/driver-help-hidden.f90
+++ flang/test/Driver/driver-help-hidden.f90
@@ -95,6 +95,10 @@
 ! CHECK-NEXT: -print-effective-triple Print the effective target triple
 ! CHECK-NEXT: -print-target-triplePrint the normalized target triple
 ! CHECK-NEXT: -P Disable linemarker output in -E mode
+! CHECK-NEXT: -Rpass-analysis= Report transformation analysis from optimization passes whose name matches the given POSIX regular expression
+! CHECK-NEXT: -Rpass-missed=   Report missed transformations by optimization passes whose name matches the given POSIX regular expression
+! CHECK-NEXT: -Rpass=  Report transformations performed by optimization passes whose name matches the given POSIX regular expression
+! CHECK-NEXT: -R  Enable the specified remark
 ! CHECK-NEXT: -save-temps=Save intermediate compilation results.
 ! CHECK-NEXT: -save-tempsSave intermediate compilation results
 ! CHECK-NEXT: -std=   Language standard to compile for
Index: clang/lib/Driver/ToolChains/Flang.cpp
===
--- clang/lib/Driver/ToolChains/Flang.cpp
+++ clang/lib/Driver/ToolChains/Flang.cpp
@@ -518,6 +518,9 @@
   // Add Codegen options
   addCodegenOptions(Args, CmdArgs);
 
+  // Add R Group options
+  

[PATCH] D157474: [RISCV] Add missing Xsfvcp extension check in clang sema

2023-08-09 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added inline comments.



Comment at: clang/test/Sema/rvv-required-features-invalid.c:16
+void test_sf_vc_x_se_u64m1(uint64_t rs1, size_t vl) { // expected-note 
{{'test_sf_vc_x_se_u64m1' declared here}}
+  __riscv_sf_vc_x_se_u64m1(1, 1, 1, rs1, vl); // expected-error {{call to 
undeclared function '__riscv_sf_vc_x_se_u64m1'}} expected-note {{did you mean 
'test_sf_vc_x_se_u64m1'?}}
+}

This doesn't mention the xsfvcp extension. So it doesn't look like the 
diagnostic in the code is being hit.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157474

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


[PATCH] D156320: [Flang][Driver] Add support for Rpass and related options

2023-08-09 Thread victorkingi via Phabricator via cfe-commits
victorkingi marked an inline comment as done.
victorkingi added inline comments.



Comment at: flang/lib/Frontend/CompilerInvocation.cpp:786
   parseShowColorsArgs(args, /*defaultDiagColor=*/false);
+  res.getDiagnosticOpts().ShowColors = res.getFrontendOpts().showColors;
 

Apparently without forwarding the color option to the CompilerInvocation, flang 
doesn't print remark errors with color. Hence the need for this.
Also, a question, why do we have 2 instances of DiagnosticsEngine, one in 
CompilerInvocation and the other passed as an argument?



Comment at: flang/test/Driver/optimization-remark.f90:17-18
+
+! Check error on bad regex
+! RUN: not %flang %s -O1 -Rpass=[ 2>&1 | FileCheck %s 
--check-prefix=CHECK-REMARKS-ERROR
+

Testing error produced given a bad regex


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156320

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


[PATCH] D157066: [clang][modules][deps] Create more efficient API for visitation of `ModuleFile` inputs

2023-08-09 Thread Jan Svoboda 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 rGdcd3a0c9f13b: [clang][modules][deps] Create more efficient 
API for visitation of `ModuleFile`… (authored by jansvoboda11).

Changed prior to commit:
  https://reviews.llvm.org/D157066?vs=547097=548666#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157066

Files:
  clang/include/clang/Serialization/ASTBitCodes.h
  clang/include/clang/Serialization/ASTReader.h
  clang/include/clang/Serialization/ModuleFile.h
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp

Index: clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
===
--- clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
+++ clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
@@ -459,18 +459,19 @@
   serialization::ModuleFile *MF =
   MDC.ScanInstance.getASTReader()->getModuleManager().lookup(
   M->getASTFile());
-  MDC.ScanInstance.getASTReader()->visitInputFiles(
-  *MF, true, true, [&](const serialization::InputFile , bool isSystem) {
+  MDC.ScanInstance.getASTReader()->visitInputFileInfos(
+  *MF, /*IncludeSystem=*/true,
+  [&](const serialization::InputFileInfo , bool IsSystem) {
 // __inferred_module.map is the result of the way in which an implicit
 // module build handles inferred modules. It adds an overlay VFS with
 // this file in the proper directory and relies on the rest of Clang to
 // handle it like normal. With explicitly built modules we don't need
 // to play VFS tricks, so replace it with the correct module map.
-if (IF.getFile()->getName().endswith("__inferred_module.map")) {
+if (StringRef(IFI.Filename).endswith("__inferred_module.map")) {
   MDC.addFileDep(MD, ModuleMap->getName());
   return;
 }
-MDC.addFileDep(MD, IF.getFile()->getName());
+MDC.addFileDep(MD, IFI.Filename);
   });
 
   llvm::DenseSet SeenDeps;
@@ -478,11 +479,15 @@
   addAllSubmoduleDeps(M, MD, SeenDeps);
   addAllAffectingClangModules(M, MD, SeenDeps);
 
-  MDC.ScanInstance.getASTReader()->visitTopLevelModuleMaps(
-  *MF, [&](FileEntryRef FE) {
-if (FE.getNameAsRequested().endswith("__inferred_module.map"))
+  MDC.ScanInstance.getASTReader()->visitInputFileInfos(
+  *MF, /*IncludeSystem=*/true,
+  [&](const serialization::InputFileInfo , bool IsSystem) {
+if (!(IFI.TopLevel && IFI.ModuleMap))
   return;
-MD.ModuleMapFileDeps.emplace_back(FE.getNameAsRequested());
+if (StringRef(IFI.FilenameAsRequested)
+.endswith("__inferred_module.map"))
+  return;
+MD.ModuleMapFileDeps.emplace_back(IFI.FilenameAsRequested);
   });
 
   CompilerInvocation CI = MDC.makeInvocationForModuleBuildWithoutOutputs(
Index: clang/lib/Serialization/ASTWriter.cpp
===
--- clang/lib/Serialization/ASTWriter.cpp
+++ clang/lib/Serialization/ASTWriter.cpp
@@ -1525,7 +1525,8 @@
   bool IsSystemFile;
   bool IsTransient;
   bool BufferOverridden;
-  bool IsTopLevelModuleMap;
+  bool IsTopLevel;
+  bool IsModuleMap;
   uint32_t ContentHash[2];
 
   InputFileEntry(FileEntryRef File) : File(File) {}
@@ -1547,8 +1548,10 @@
   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Transient
+  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Top-level
   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Module map
-  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
+  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // Name as req. len
+  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name as req. + name
   unsigned IFAbbrevCode = Stream.EmitAbbrev(std::move(IFAbbrev));
 
   // Create input file hash abbreviation.
@@ -1582,8 +1585,8 @@
 Entry.IsSystemFile = isSystem(File.getFileCharacteristic());
 Entry.IsTransient = Cache->IsTransient;
 Entry.BufferOverridden = Cache->BufferOverridden;
-Entry.IsTopLevelModuleMap = isModuleMap(File.getFileCharacteristic()) &&
-File.getIncludeLoc().isInvalid();
+Entry.IsTopLevel = File.getIncludeLoc().isInvalid();
+Entry.IsModuleMap = isModuleMap(File.getFileCharacteristic());
 
 auto ContentHash = hash_code(-1);
 if (PP->getHeaderSearchInfo()
@@ -1631,6 +1634,15 @@
 // Emit size/modification time for this file.
 // And whether this file was overridden.
 {
+  SmallString<128> 

[clang] dcd3a0c - [clang][modules][deps] Create more efficient API for visitation of `ModuleFile` inputs

2023-08-09 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2023-08-09T10:19:36-07:00
New Revision: dcd3a0c9f13b551ca2bcefa0dd181a383f44df49

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

LOG: [clang][modules][deps] Create more efficient API for visitation of 
`ModuleFile` inputs

The current `ASTReader::visitInputFiles()` function calls into `FileManager` to 
create `FileEntryRef` objects. This ends up being fairly costly in 
`clang-scan-deps`, where we mostly only care about file paths.

This patch introduces new `ASTReader` API that gives clients access to just the 
serialized paths. Since the scanner needs both the as-requested path and the 
on-disk one (and doesn't want to transform the former into the latter via 
`FileManager`), this patch starts serializing both of them into the PCM file if 
they differ.

This increases the size of scanning PCMs by 0.1% and speeds up scanning by 5%.

Reviewed By: benlangmuir, vsapsai

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

Added: 


Modified: 
clang/include/clang/Serialization/ASTBitCodes.h
clang/include/clang/Serialization/ASTReader.h
clang/include/clang/Serialization/ModuleFile.h
clang/lib/Serialization/ASTReader.cpp
clang/lib/Serialization/ASTWriter.cpp
clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp

Removed: 




diff  --git a/clang/include/clang/Serialization/ASTBitCodes.h 
b/clang/include/clang/Serialization/ASTBitCodes.h
index 2ae9e09998c4c1..3ad22bbcf5d12d 100644
--- a/clang/include/clang/Serialization/ASTBitCodes.h
+++ b/clang/include/clang/Serialization/ASTBitCodes.h
@@ -41,7 +41,7 @@ namespace serialization {
 /// Version 4 of AST files also requires that the version control branch and
 /// revision match exactly, since there is no backward compatibility of
 /// AST files at this time.
-const unsigned VERSION_MAJOR = 27;
+const unsigned VERSION_MAJOR = 28;
 
 /// AST file minor version number supported by this version of
 /// Clang.

diff  --git a/clang/include/clang/Serialization/ASTReader.h 
b/clang/include/clang/Serialization/ASTReader.h
index d56e2117a53f0d..7706de74d3632d 100644
--- a/clang/include/clang/Serialization/ASTReader.h
+++ b/clang/include/clang/Serialization/ASTReader.h
@@ -2373,6 +2373,13 @@ class ASTReader
   /// Loads comments ranges.
   void ReadComments() override;
 
+  /// Visit all the input file infos of the given module file.
+  void visitInputFileInfos(
+  serialization::ModuleFile , bool IncludeSystem,
+  llvm::function_ref
+  Visitor);
+
   /// Visit all the input files of the given module file.
   void visitInputFiles(serialization::ModuleFile ,
bool IncludeSystem, bool Complain,

diff  --git a/clang/include/clang/Serialization/ModuleFile.h 
b/clang/include/clang/Serialization/ModuleFile.h
index b632b4e3e7a7ce..8c4067853d6646 100644
--- a/clang/include/clang/Serialization/ModuleFile.h
+++ b/clang/include/clang/Serialization/ModuleFile.h
@@ -61,13 +61,15 @@ enum ModuleKind {
 
 /// The input file info that has been loaded from an AST file.
 struct InputFileInfo {
+  std::string FilenameAsRequested;
   std::string Filename;
   uint64_t ContentHash;
   off_t StoredSize;
   time_t StoredTime;
   bool Overridden;
   bool Transient;
-  bool TopLevelModuleMap;
+  bool TopLevel;
+  bool ModuleMap;
 };
 
 /// The input file that has been loaded from this AST file, along with

diff  --git a/clang/lib/Serialization/ASTReader.cpp 
b/clang/lib/Serialization/ASTReader.cpp
index dcb845dd551e8d..f6c643d9113d8a 100644
--- a/clang/lib/Serialization/ASTReader.cpp
+++ b/clang/lib/Serialization/ASTReader.cpp
@@ -2342,9 +2342,22 @@ InputFileInfo ASTReader::getInputFileInfo(ModuleFile , 
unsigned ID) {
   R.StoredTime = static_cast(Record[2]);
   R.Overridden = static_cast(Record[3]);
   R.Transient = static_cast(Record[4]);
-  R.TopLevelModuleMap = static_cast(Record[5]);
-  R.Filename = std::string(Blob);
-  ResolveImportedPath(F, R.Filename);
+  R.TopLevel = static_cast(Record[5]);
+  R.ModuleMap = static_cast(Record[6]);
+  std::tie(R.FilenameAsRequested, R.Filename) = [&]() {
+uint16_t AsRequestedLength = Record[7];
+
+std::string NameAsRequested = Blob.substr(0, AsRequestedLength).str();
+std::string Name = Blob.substr(AsRequestedLength).str();
+
+ResolveImportedPath(F, NameAsRequested);
+ResolveImportedPath(F, Name);
+
+if (Name.empty())
+  Name = NameAsRequested;
+
+return std::make_pair(std::move(NameAsRequested), std::move(Name));
+  }();
 
   Expected MaybeEntry = Cursor.advance();
   if (!MaybeEntry) // FIXME this drops errors on the floor.
@@ -2395,7 +2408,7 @@ InputFile ASTReader::getInputFile(ModuleFile , unsigned 
ID, bool Complain) {
   time_t StoredTime = FI.StoredTime;
   bool Overridden = FI.Overridden;
   

[PATCH] D157066: [clang][modules][deps] Create more efficient API for visitation of `ModuleFile` inputs

2023-08-09 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 added a comment.

Landing with one more use of `Filename` converted to `FilenameAsRequested` (in 
call to `Listener.visitInputFile()`). The only remaining usages of `Filename` 
is now in the scanner (intentional) and in `ASTReader` when deciding whether an 
`InputFileInfo` has already been deserialized or not (default-initialized 
`InputFileInfo` has an empty `Filename`).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157066

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


[PATCH] D156320: [Flang][Driver] Add support for Rpass and related options

2023-08-09 Thread victorkingi via Phabricator via cfe-commits
victorkingi updated this revision to Diff 548664.
victorkingi edited the summary of this revision.
victorkingi added a comment.

Added remark error test and color printing for remark errors


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156320

Files:
  flang/include/flang/Frontend/CodeGenOptions.h
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/lib/Frontend/TextDiagnosticPrinter.cpp
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/test/Driver/optimization-remark.f90

Index: flang/test/Driver/optimization-remark.f90
===
--- /dev/null
+++ flang/test/Driver/optimization-remark.f90
@@ -0,0 +1,55 @@
+! This file tests the -Rpass family of flags (-Rpass, -Rpass-missed
+! and -Rpass-analysis)
+! loop-delete isn't enabled at O0 so we use at least O1
+
+! Check that we can override -Rpass= with -Rno-pass.
+! RUN: %flang_fc1 %s -O1 -Rpass=loop-delete -emit-llvm -o - 2>&1 | FileCheck %s --check-prefix=CHECK-REMARKS
+! RUN: %flang_fc1 %s -O1 -Rpass=loop-delete -Rno-pass -emit-llvm -o - 2>&1 | FileCheck %s --check-prefix=CHECK-NO-REMARKS
+! RUN: %flang_fc1 %s -O1 -Rpass=loop-delete -Rno-everything -emit-llvm -o - 2>&1 | FileCheck %s --check-prefix=CHECK-NO-REMARKS
+! RUN: %flang_fc1 %s -O1 -Rpass=loop-delete -Rno-everything -Reverything -emit-llvm -o - 2>&1 | FileCheck %s --check-prefix=CHECK-REMARKS
+
+! -Reverything implies -Rpass=.*.
+! RUN: %flang_fc1 %s -O1 -Reverything -emit-llvm -o - 2>&1 | FileCheck %s --check-prefix=CHECK-REMARKS
+
+! -Rpass implies -Rpass=.*
+! RUN: %flang_fc1 %s -O1 -Rpass -emit-llvm -o - 2>&1 | FileCheck %s --check-prefix=CHECK-REMARKS
+
+! Check error on bad regex
+! RUN: not %flang %s -O1 -Rpass=[ 2>&1 | FileCheck %s --check-prefix=CHECK-REMARKS-ERROR
+
+! Check full -Rpass message is emitted
+! RUN: %flang %s -O1 -Rpass=loop-delete 2>&1 | FileCheck %s
+
+! Check full -Rpass-missed message is emitted
+! RUN: %flang %s -O1 -Rpass-missed=loop-vectorize 2>&1 | FileCheck %s --check-prefix=CHECK-REMARKS-MISSED
+
+! Check full -Rpass-analysis message is emitted
+! RUN: %flang %s -O1 -Rpass-analysis=loop-vectorize 2>&1 | FileCheck %s --check-prefix=CHECK-REMARKS-ANALYSIS
+
+
+! CHECK: remark: Loop deleted because it is invariant
+
+! CHECK-REMARKS-MISSED: remark: loop not vectorized
+! CHECK-REMARKS-ANALYSIS: remark: loop not vectorized: call instruction cannot be vectorized
+! CHECK-REMARKS: remark:
+
+! CHECK-NO-REMARKS-NOT: remark:
+
+! CHECK-REMARKS-ERROR: error: in pattern '-Rpass=[': brackets ([ ]) not balanced
+
+
+program forttest
+implicit none
+real, dimension(1:50) :: aR1
+integer :: n
+
+do n = 1,50
+aR1(n) = n * 1.34
+print *, "hello"
+end do
+
+do n = 1,50
+aR1(n) = n * 1.34
+end do
+
+end program forttest
Index: flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
===
--- flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
+++ flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
@@ -165,6 +165,10 @@
 
   // Honor color diagnostics.
   flang->getDiagnosticOpts().ShowColors = flang->getFrontendOpts().showColors;
+  flang->getDiagnosticOpts().ShowOptionNames = 1;
+
+  clang::ProcessWarningOptions(flang->getDiagnostics(),
+   flang->getDiagnosticOpts(), false);
 
   // Create and execute the frontend action.
   std::unique_ptr act(createFrontendAction(*flang));
Index: flang/lib/Frontend/TextDiagnosticPrinter.cpp
===
--- flang/lib/Frontend/TextDiagnosticPrinter.cpp
+++ flang/lib/Frontend/TextDiagnosticPrinter.cpp
@@ -20,6 +20,10 @@
 #include "llvm/ADT/SmallString.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/raw_ostream.h"
+#include 
+#include 
+#include 
+#include 
 
 using namespace Fortran::frontend;
 
@@ -29,6 +33,28 @@
 
 TextDiagnosticPrinter::~TextDiagnosticPrinter() {}
 
+// Print any diagnostic option information to a raw_ostream.
+static void printDiagnosticOptions(llvm::raw_ostream ,
+   clang::DiagnosticsEngine::Level level,
+   const clang::Diagnostic ,
+   const clang::DiagnosticOptions ) {
+  bool started = false;
+  if (diagOpts.ShowOptionNames) {
+llvm::StringRef opt =
+clang::DiagnosticIDs::getWarningOptionForDiag(info.getID());
+if (!opt.empty()) {
+  os << (started ? "," : " [")
+ << (level == clang::DiagnosticsEngine::Remark ? "-R" : "-W") << opt;
+  llvm::StringRef optValue = info.getDiags()->getFlagValue();
+  if (!optValue.empty())
+os << "=" << optValue;
+  started = true;
+}
+  }
+  if (started)
+os << ']';
+}
+
 void TextDiagnosticPrinter::HandleDiagnostic(
 

[PATCH] D157454: [NFC][Clang] Fix static analyzer concern about null value dereference

2023-08-09 Thread Elizabeth Andrews via Phabricator via cfe-commits
eandrews added inline comments.



Comment at: clang/lib/CodeGen/CGObjC.cpp:222-223
   Selector Sel = MethodWithObjects->getSelector();
-  QualType ResultType = E->getType();
-  const ObjCObjectPointerType *InterfacePointerType
-= ResultType->getAsObjCInterfacePointerType();
+  const ObjCObjectPointerType *InterfacePointerType =
+  cast(E->getType());
   ObjCInterfaceDecl *Class

tahonermann wrote:
> The previous code included a guarantee that 
> `InterfacePointerType->getInterfaceType()` is non-null and this change loses 
> that assurance. Presumably, we never ran into a violation of that guarantee 
> in the past (since a SIGSEGV would likely have occurred below otherwise), but 
> perhaps we should consider an assertion to ensure that guarantee is still met.
Hmmm... I guess in that case it was just make more sense to keep the old code 
and add an assert for InterfacePointerType?


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

https://reviews.llvm.org/D157454

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


[PATCH] D157445: [CodeGen][UBSan] getUBSanFunctionTypeHash does not handle the attributed function case correctly, leading to an assertion failure. This patch desugars the QualType if it is of Attribu

2023-08-09 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

The title is very long. Can you shorten it and put additional description to 
the body of the commit message (aka summary)?

What does the test `ubsan-function-attributed.c` do? It lacks comments to help 
reader understand the issue.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157445

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


[PATCH] D157520: [Driver] Replace a link to openradar with a comment. NFC

2023-08-09 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

https://openradar.appspot.com/7198997 says `Date Originated:04-Sep-2009 
06:00 PM`. Is the very old linker bug still relevant?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157520

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


[PATCH] D156948: [clang][modules] Add -Wsystem-headers-in-module=

2023-08-09 Thread Ben Langmuir via Phabricator via cfe-commits
benlangmuir marked an inline comment as done.
benlangmuir added inline comments.



Comment at: clang/include/clang/Basic/DiagnosticOptions.h:128
+  /// whether -Wsystem-headers is enabled on a per-module basis.
+  std::vector SystemHeaderWarningsModules;
+

iana wrote:
> benlangmuir wrote:
> > jansvoboda11 wrote:
> > > Out of interest, is there an existing use-case for having multiple 
> > > modules here, or is this just future-proofing?
> > I'm not using it currently, but I think it makes sense to handle any 
> > number. You could have multiple such modules you're testing together.
> I'd imagine you'd typically have Framework and Framework_Private in there
Ah, good point. I am in fact doing that already and just forgot.


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

https://reviews.llvm.org/D156948

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


[clang] acf5785 - [clang] NFC: Use compile-time option spelling when generating command line

2023-08-09 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2023-08-09T09:55:07-07:00
New Revision: acf57858c1acb4ff776a1d734b86e1c05303132a

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

LOG: [clang] NFC: Use compile-time option spelling when generating command line

When generating command lines, use the option spelling generated by TableGen 
(`StringLiteral`) instead of constructing it at runtime. This saves some 
needless allocations.

Depends on D157029.

Reviewed By: benlangmuir, MaskRay

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

Added: 


Modified: 
clang/lib/Frontend/CompilerInvocation.cpp

Removed: 




diff  --git a/clang/lib/Frontend/CompilerInvocation.cpp 
b/clang/lib/Frontend/CompilerInvocation.cpp
index c4082db0090733..87190093767b05 100644
--- a/clang/lib/Frontend/CompilerInvocation.cpp
+++ b/clang/lib/Frontend/CompilerInvocation.cpp
@@ -615,7 +615,7 @@ static unsigned getOptimizationLevelSize(ArgList ) {
 static void GenerateArg(ArgumentConsumer Consumer,
 llvm::opt::OptSpecifier OptSpecifier) {
   Option Opt = getDriverOptTable().getOption(OptSpecifier);
-  denormalizeSimpleFlag(Consumer, Opt.getPrefix() + Opt.getName(),
+  denormalizeSimpleFlag(Consumer, Opt.getPrefixedName(),
 Option::OptionClass::FlagClass, 0);
 }
 
@@ -623,8 +623,7 @@ static void GenerateArg(ArgumentConsumer Consumer,
 llvm::opt::OptSpecifier OptSpecifier,
 const Twine ) {
   Option Opt = getDriverOptTable().getOption(OptSpecifier);
-  denormalizeString(Consumer, Opt.getPrefix() + Opt.getName(), Opt.getKind(), 
0,
-Value);
+  denormalizeString(Consumer, Opt.getPrefixedName(), Opt.getKind(), 0, Value);
 }
 
 // Parse command line arguments into CompilerInvocation.



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


[PATCH] D157054: [clang] NFC: Use compile-time option spelling when generating command line

2023-08-09 Thread Jan Svoboda via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGacf57858c1ac: [clang] NFC: Use compile-time option spelling 
when generating command line (authored by jansvoboda11).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157054

Files:
  clang/lib/Frontend/CompilerInvocation.cpp


Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -615,7 +615,7 @@
 static void GenerateArg(ArgumentConsumer Consumer,
 llvm::opt::OptSpecifier OptSpecifier) {
   Option Opt = getDriverOptTable().getOption(OptSpecifier);
-  denormalizeSimpleFlag(Consumer, Opt.getPrefix() + Opt.getName(),
+  denormalizeSimpleFlag(Consumer, Opt.getPrefixedName(),
 Option::OptionClass::FlagClass, 0);
 }
 
@@ -623,8 +623,7 @@
 llvm::opt::OptSpecifier OptSpecifier,
 const Twine ) {
   Option Opt = getDriverOptTable().getOption(OptSpecifier);
-  denormalizeString(Consumer, Opt.getPrefix() + Opt.getName(), Opt.getKind(), 
0,
-Value);
+  denormalizeString(Consumer, Opt.getPrefixedName(), Opt.getKind(), 0, Value);
 }
 
 // Parse command line arguments into CompilerInvocation.


Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -615,7 +615,7 @@
 static void GenerateArg(ArgumentConsumer Consumer,
 llvm::opt::OptSpecifier OptSpecifier) {
   Option Opt = getDriverOptTable().getOption(OptSpecifier);
-  denormalizeSimpleFlag(Consumer, Opt.getPrefix() + Opt.getName(),
+  denormalizeSimpleFlag(Consumer, Opt.getPrefixedName(),
 Option::OptionClass::FlagClass, 0);
 }
 
@@ -623,8 +623,7 @@
 llvm::opt::OptSpecifier OptSpecifier,
 const Twine ) {
   Option Opt = getDriverOptTable().getOption(OptSpecifier);
-  denormalizeString(Consumer, Opt.getPrefix() + Opt.getName(), Opt.getKind(), 0,
-Value);
+  denormalizeString(Consumer, Opt.getPrefixedName(), Opt.getKind(), 0, Value);
 }
 
 // Parse command line arguments into CompilerInvocation.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D157520: [Driver] Replace a link to openradar with a comment. NFC

2023-08-09 Thread Akira Hatanaka via Phabricator via cfe-commits
ahatanak created this revision.
ahatanak added a reviewer: ravikandhadai.
ahatanak added a project: clang.
Herald added a project: All.
ahatanak requested review of this revision.
Herald added a subscriber: MaskRay.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D157520

Files:
  clang/lib/Driver/ToolChains/Clang.cpp


Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -5578,8 +5578,9 @@
   }
 
   // Enable -mconstructor-aliases except on darwin, where we have to work 
around
-  // a linker bug (see https://openradar.appspot.com/7198997), and CUDA device
-  // code, where aliases aren't supported.
+  // a linker bug where aliasing symbols are not moved to the new locations 
when
+  // the aliased symbol is moved, and CUDA device code, where aliases aren't
+  // supported.
   if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
 CmdArgs.push_back("-mconstructor-aliases");
 


Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -5578,8 +5578,9 @@
   }
 
   // Enable -mconstructor-aliases except on darwin, where we have to work around
-  // a linker bug (see https://openradar.appspot.com/7198997), and CUDA device
-  // code, where aliases aren't supported.
+  // a linker bug where aliasing symbols are not moved to the new locations when
+  // the aliased symbol is moved, and CUDA device code, where aliases aren't
+  // supported.
   if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
 CmdArgs.push_back("-mconstructor-aliases");
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D144457: [clang][Interp] Handle global composite temporaries

2023-08-09 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/D144457/new/

https://reviews.llvm.org/D144457

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


[PATCH] D157518: Avoid running optimization passes in frontend test

2023-08-09 Thread Matthias Braun via Phabricator via cfe-commits
MatzeB updated this revision to Diff 548657.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157518

Files:
  clang/test/CodeGenCXX/attr-likelihood-if-branch-weights.cpp

Index: clang/test/CodeGenCXX/attr-likelihood-if-branch-weights.cpp
===
--- clang/test/CodeGenCXX/attr-likelihood-if-branch-weights.cpp
+++ clang/test/CodeGenCXX/attr-likelihood-if-branch-weights.cpp
@@ -1,14 +1,31 @@
-// RUN: %clang_cc1 -O1 -emit-llvm %s -o - -triple=x86_64-linux-gnu | FileCheck -DLIKELY=2000 -DUNLIKELY=1 %s
-// RUN: %clang_cc1 -O1 -emit-llvm %s -triple=x86_64-linux-gnu -mllvm -likely-branch-weight=99 -mllvm -unlikely-branch-weight=42 -o - | FileCheck -DLIKELY=99 -DUNLIKELY=42 %s
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+// RUN: %clang_cc1 -O1 -disable-llvm-passes -emit-llvm %s -o - -triple=x86_64-- | FileCheck %s
 
 extern volatile bool b;
 extern volatile int i;
 extern bool A();
 extern bool B();
 
+// CHECK-LABEL: @_Z1fv(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[RETVAL:%.*]] = alloca i1, align 1
+// CHECK-NEXT:[[TMP0:%.*]] = load volatile i8, ptr @b, align 1, !tbaa [[TBAA2:![0-9]+]], !range [[RNG6:![0-9]+]]
+// CHECK-NEXT:[[TOBOOL:%.*]] = trunc i8 [[TMP0]] to i1
+// CHECK-NEXT:[[TOBOOL_EXPVAL:%.*]] = call i1 @llvm.expect.i1(i1 [[TOBOOL]], i1 true)
+// CHECK-NEXT:br i1 [[TOBOOL_EXPVAL]], label [[IF_THEN:%.*]], label [[IF_END:%.*]]
+// CHECK:   if.then:
+// CHECK-NEXT:[[CALL:%.*]] = call noundef zeroext i1 @_Z1Av()
+// CHECK-NEXT:store i1 [[CALL]], ptr [[RETVAL]], align 1
+// CHECK-NEXT:br label [[RETURN:%.*]]
+// CHECK:   if.end:
+// CHECK-NEXT:[[CALL1:%.*]] = call noundef zeroext i1 @_Z1Bv()
+// CHECK-NEXT:store i1 [[CALL1]], ptr [[RETVAL]], align 1
+// CHECK-NEXT:br label [[RETURN]]
+// CHECK:   return:
+// CHECK-NEXT:[[TMP1:%.*]] = load i1, ptr [[RETVAL]], align 1
+// CHECK-NEXT:ret i1 [[TMP1]]
+//
 bool f() {
-  // CHECK-LABEL: define{{.*}} zeroext i1 @_Z1fv
-  // CHECK: br {{.*}} !prof ![[PROF_LIKELY:[0-9]+]]
   if (b)
 [[likely]] {
   return A();
@@ -16,9 +33,26 @@
   return B();
 }
 
+// CHECK-LABEL: @_Z1gv(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[RETVAL:%.*]] = alloca i1, align 1
+// CHECK-NEXT:[[TMP0:%.*]] = load volatile i8, ptr @b, align 1, !tbaa [[TBAA2]], !range [[RNG6]]
+// CHECK-NEXT:[[TOBOOL:%.*]] = trunc i8 [[TMP0]] to i1
+// CHECK-NEXT:[[TOBOOL_EXPVAL:%.*]] = call i1 @llvm.expect.i1(i1 [[TOBOOL]], i1 false)
+// CHECK-NEXT:br i1 [[TOBOOL_EXPVAL]], label [[IF_THEN:%.*]], label [[IF_END:%.*]]
+// CHECK:   if.then:
+// CHECK-NEXT:[[CALL:%.*]] = call noundef zeroext i1 @_Z1Av()
+// CHECK-NEXT:store i1 [[CALL]], ptr [[RETVAL]], align 1
+// CHECK-NEXT:br label [[RETURN:%.*]]
+// CHECK:   if.end:
+// CHECK-NEXT:[[CALL1:%.*]] = call noundef zeroext i1 @_Z1Bv()
+// CHECK-NEXT:store i1 [[CALL1]], ptr [[RETVAL]], align 1
+// CHECK-NEXT:br label [[RETURN]]
+// CHECK:   return:
+// CHECK-NEXT:[[TMP1:%.*]] = load i1, ptr [[RETVAL]], align 1
+// CHECK-NEXT:ret i1 [[TMP1]]
+//
 bool g() {
-  // CHECK-LABEL: define{{.*}} zeroext i1 @_Z1gv
-  // CHECK: br {{.*}} !prof ![[PROF_UNLIKELY:[0-9]+]]
   if (b)
 [[unlikely]] {
   return A();
@@ -27,18 +61,47 @@
   return B();
 }
 
+// CHECK-LABEL: @_Z1hv(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[RETVAL:%.*]] = alloca i1, align 1
+// CHECK-NEXT:[[TMP0:%.*]] = load volatile i8, ptr @b, align 1, !tbaa [[TBAA2]], !range [[RNG6]]
+// CHECK-NEXT:[[TOBOOL:%.*]] = trunc i8 [[TMP0]] to i1
+// CHECK-NEXT:[[TOBOOL_EXPVAL:%.*]] = call i1 @llvm.expect.i1(i1 [[TOBOOL]], i1 false)
+// CHECK-NEXT:br i1 [[TOBOOL_EXPVAL]], label [[IF_THEN:%.*]], label [[IF_END:%.*]]
+// CHECK:   if.then:
+// CHECK-NEXT:[[CALL:%.*]] = call noundef zeroext i1 @_Z1Av()
+// CHECK-NEXT:store i1 [[CALL]], ptr [[RETVAL]], align 1
+// CHECK-NEXT:br label [[RETURN:%.*]]
+// CHECK:   if.end:
+// CHECK-NEXT:[[CALL1:%.*]] = call noundef zeroext i1 @_Z1Bv()
+// CHECK-NEXT:store i1 [[CALL1]], ptr [[RETVAL]], align 1
+// CHECK-NEXT:br label [[RETURN]]
+// CHECK:   return:
+// CHECK-NEXT:[[TMP1:%.*]] = load i1, ptr [[RETVAL]], align 1
+// CHECK-NEXT:ret i1 [[TMP1]]
+//
 bool h() {
-  // CHECK-LABEL: define{{.*}} zeroext i1 @_Z1hv
-  // CHECK: br {{.*}} !prof ![[PROF_UNLIKELY]]
   if (b)
 [[unlikely]] return A();
 
   return B();
 }
 
+// CHECK-LABEL: @_Z8NullStmtv(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[TMP0:%.*]] = load volatile i8, ptr @b, align 1, !tbaa [[TBAA2]], !range [[RNG6]]
+// CHECK-NEXT:[[TOBOOL:%.*]] = trunc i8 [[TMP0]] to i1
+// CHECK-NEXT:[[TOBOOL_EXPVAL:%.*]] = call i1 @llvm.expect.i1(i1 [[TOBOOL]], i1 false)
+// CHECK-NEXT:br i1 [[TOBOOL_EXPVAL]], label [[IF_THEN:%.*]], label [[IF_ELSE:%.*]]
+// 

[PATCH] D157518: Avoid running optimization passes in frontend test

2023-08-09 Thread Arthur Eubanks via Phabricator via cfe-commits
aeubanks accepted this revision.
aeubanks added a comment.
This revision is now accepted and ready to land.

seems fine if nobody else objects


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157518

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


[PATCH] D157029: [llvm] Construct option's prefixed name at compile-time

2023-08-09 Thread Jan Svoboda via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG501f92d34382: [llvm] Construct options prefixed name 
at compile-time (authored by jansvoboda11).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157029

Files:
  clang-tools-extra/clangd/CompileCommands.cpp
  clang/lib/Driver/Driver.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/lib/Tooling/Tooling.cpp
  llvm/include/llvm/Option/OptTable.h
  llvm/include/llvm/Option/Option.h
  llvm/lib/Option/OptTable.cpp
  llvm/unittests/Option/OptionMarshallingTest.cpp
  llvm/utils/TableGen/OptParserEmitter.cpp

Index: llvm/utils/TableGen/OptParserEmitter.cpp
===
--- llvm/utils/TableGen/OptParserEmitter.cpp
+++ llvm/utils/TableGen/OptParserEmitter.cpp
@@ -34,30 +34,14 @@
   return OS;
 }
 
-static std::string getOptionSpelling(const Record , size_t ) {
+static std::string getOptionPrefixedName(const Record ) {
   std::vector Prefixes = R.getValueAsListOfStrings("Prefixes");
   StringRef Name = R.getValueAsString("Name");
 
-  if (Prefixes.empty()) {
-PrefixLength = 0;
+  if (Prefixes.empty())
 return Name.str();
-  }
-
-  PrefixLength = Prefixes[0].size();
-  return (Twine(Prefixes[0]) + Twine(Name)).str();
-}
 
-static std::string getOptionSpelling(const Record ) {
-  size_t PrefixLength;
-  return getOptionSpelling(R, PrefixLength);
-}
-
-static void emitNameUsingSpelling(raw_ostream , const Record ) {
-  size_t PrefixLength;
-  OS << "llvm::StringLiteral(";
-  write_cstring(
-  OS, StringRef(getOptionSpelling(R, PrefixLength)).substr(PrefixLength));
-  OS << ")";
+  return (Prefixes[0] + Twine(Name)).str();
 }
 
 class MarshallingInfo {
@@ -105,8 +89,6 @@
   }
 
   void emit(raw_ostream ) const {
-write_cstring(OS, StringRef(getOptionSpelling(R)));
-OS << ", ";
 OS << ShouldParse;
 OS << ", ";
 OS << ShouldAlwaysEmit;
@@ -346,8 +328,8 @@
 std::vector RPrefixes = R.getValueAsListOfStrings("Prefixes");
 OS << Prefixes[PrefixKeyT(RPrefixes.begin(), RPrefixes.end())] << ", ";
 
-// The option string.
-emitNameUsingSpelling(OS, R);
+// The option prefixed name.
+write_cstring(OS, getOptionPrefixedName(R));
 
 // The option identifier name.
 OS << ", " << getOptionName(R);
Index: llvm/unittests/Option/OptionMarshallingTest.cpp
===
--- llvm/unittests/Option/OptionMarshallingTest.cpp
+++ llvm/unittests/Option/OptionMarshallingTest.cpp
@@ -10,7 +10,7 @@
 #include "gtest/gtest.h"
 
 struct OptionWithMarshallingInfo {
-  llvm::StringRef Name;
+  llvm::StringLiteral PrefixedName;
   const char *KeyPath;
   const char *ImpliedCheck;
   const char *ImpliedValue;
@@ -18,20 +18,20 @@
 
 static const OptionWithMarshallingInfo MarshallingTable[] = {
 #define OPTION_WITH_MARSHALLING(   \
-PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,\
-HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
+PREFIX_TYPE, PREFIXED_NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS,  \
+PARAM, HELPTEXT, METAVAR, VALUES, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,  \
 DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
 MERGER, EXTRACTOR, TABLE_INDEX)\
-  {NAME, #KEYPATH, #IMPLIED_CHECK, #IMPLIED_VALUE},
+  {PREFIXED_NAME, #KEYPATH, #IMPLIED_CHECK, #IMPLIED_VALUE},
 #include "Opts.inc"
 #undef OPTION_WITH_MARSHALLING
 };
 
 TEST(OptionMarshalling, EmittedOrderSameAsDefinitionOrder) {
-  ASSERT_STREQ(MarshallingTable[0].Name.data(), "marshalled-flag-d");
-  ASSERT_STREQ(MarshallingTable[1].Name.data(), "marshalled-flag-c");
-  ASSERT_STREQ(MarshallingTable[2].Name.data(), "marshalled-flag-b");
-  ASSERT_STREQ(MarshallingTable[3].Name.data(), "marshalled-flag-a");
+  ASSERT_EQ(MarshallingTable[0].PrefixedName, "-marshalled-flag-d");
+  ASSERT_EQ(MarshallingTable[1].PrefixedName, "-marshalled-flag-c");
+  ASSERT_EQ(MarshallingTable[2].PrefixedName, "-marshalled-flag-b");
+  ASSERT_EQ(MarshallingTable[3].PrefixedName, "-marshalled-flag-a");
 }
 
 TEST(OptionMarshalling, EmittedSpecifiedKeyPath) {
Index: llvm/lib/Option/OptTable.cpp
===
--- llvm/lib/Option/OptTable.cpp
+++ llvm/lib/Option/OptTable.cpp
@@ -59,7 +59,7 @@
   if ( == )
 return false;
 
-  if (int N = StrCmpOptionName(A.Name, B.Name))
+  if (int N = StrCmpOptionName(A.getName(), B.getName()))
 return N < 0;
 
   for (size_t I = 0, K = std::min(A.Prefixes.size(), B.Prefixes.size()); I != K;
@@ -77,7 +77,7 @@
 
 // Support lower_bound between info and an option name.
 static inline bool operator<(const OptTable::Info , StringRef Name) {
-  return 

[clang] 501f92d - [llvm] Construct option's prefixed name at compile-time

2023-08-09 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2023-08-09T09:52:34-07:00
New Revision: 501f92d343828c0066d3286c3ae6606021b8b271

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

LOG: [llvm] Construct option's prefixed name at compile-time

Some Clang command-line handling code could benefit from the option's prefixed 
name being a `StringLiteral`. This patch changes the `llvm::opt` TableGen 
backend to generate and emit that into the .inc file.

Depends on D157028.

Reviewed By: MaskRay

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

Added: 


Modified: 
clang-tools-extra/clangd/CompileCommands.cpp
clang/lib/Driver/Driver.cpp
clang/lib/Frontend/CompilerInvocation.cpp
clang/lib/Tooling/Tooling.cpp
llvm/include/llvm/Option/OptTable.h
llvm/include/llvm/Option/Option.h
llvm/lib/Option/OptTable.cpp
llvm/unittests/Option/OptionMarshallingTest.cpp
llvm/utils/TableGen/OptParserEmitter.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/CompileCommands.cpp 
b/clang-tools-extra/clangd/CompileCommands.cpp
index 957a6f873e1022..00f4c4ca9fef0a 100644
--- a/clang-tools-extra/clangd/CompileCommands.cpp
+++ b/clang-tools-extra/clangd/CompileCommands.cpp
@@ -493,8 +493,8 @@ llvm::ArrayRef 
ArgStripper::rulesFor(llvm::StringRef Arg) {
   static constexpr llvm::StringLiteral NAME##_init[] = VALUE;  
\
   static constexpr llvm::ArrayRef NAME(   
\
   NAME##_init, std::size(NAME##_init) - 1);
-#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,  
\
-   HELP, METAVAR, VALUES)  
\
+#define OPTION(PREFIX, PREFIXED_NAME, ID, KIND, GROUP, ALIAS, ALIASARGS,   
\
+   FLAGS, PARAM, HELP, METAVAR, VALUES)
\
   Prefixes[DriverID::OPT_##ID] = PREFIX;
 #include "clang/Driver/Options.inc"
 #undef OPTION
@@ -505,8 +505,8 @@ llvm::ArrayRef 
ArgStripper::rulesFor(llvm::StringRef Arg) {
   DriverID AliasID;
   const void *AliasArgs;
 } AliasTable[] = {
-#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,  
\
-   HELP, METAVAR, VALUES)  
\
+#define OPTION(PREFIX, PREFIXED_NAME, ID, KIND, GROUP, ALIAS, ALIASARGS,   
\
+   FLAGS, PARAM, HELP, METAVAR, VALUES)
\
   {DriverID::OPT_##ID, DriverID::OPT_##ALIAS, ALIASARGS},
 #include "clang/Driver/Options.inc"
 #undef OPTION

diff  --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index b34003041373f5..60f5eed8e2d729 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -238,7 +238,7 @@ Driver::Driver(StringRef ClangExecutable, StringRef 
TargetTriple,
 }
 
 void Driver::setDriverMode(StringRef Value) {
-  static const std::string OptName =
+  static StringRef OptName =
   getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
   if (auto M = llvm::StringSwitch>(Value)
.Case("gcc", GCCMode)
@@ -6554,7 +6554,7 @@ bool clang::driver::willEmitRemarks(const ArgList ) {
 
 llvm::StringRef clang::driver::getDriverMode(StringRef ProgName,
  ArrayRef Args) {
-  static const std::string OptName =
+  static StringRef OptName =
   
getDriverOptTable().getOption(options::OPT_driver_mode).getPrefixedName();
   llvm::StringRef Opt;
   for (StringRef Arg : Args) {

diff  --git a/clang/lib/Frontend/CompilerInvocation.cpp 
b/clang/lib/Frontend/CompilerInvocation.cpp
index be53ce3e472659..c4082db0090733 100644
--- a/clang/lib/Frontend/CompilerInvocation.cpp
+++ b/clang/lib/Frontend/CompilerInvocation.cpp
@@ -422,8 +422,8 @@ static T extractMaskValue(T KeyPath) {
 }
 
 #define PARSE_OPTION_WITH_MARSHALLING( 
\
-ARGS, DIAGS, PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS,  
\
-PARAM, HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, 
\
+ARGS, DIAGS, PREFIX_TYPE, SPELLING, ID, KIND, GROUP, ALIAS, ALIASARGS, 
\
+FLAGS, PARAM, HELPTEXT, METAVAR, VALUES, SHOULD_PARSE, ALWAYS_EMIT,
\
 KEYPATH, DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER,  
\
 DENORMALIZER, MERGER, EXTRACTOR, TABLE_INDEX)  
\
   if ((FLAGS)::CC1Option) {
\
@@ -439,10 +439,10 @@ static T extractMaskValue(T KeyPath) {
 // Capture the extracted value as a lambda argument to avoid potential issues
 // with lifetime extension of the reference.
 #define GENERATE_OPTION_WITH_MARSHALLING(  
\
-CONSUMER, PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, 
\
- 

[PATCH] D157518: Avoid running optimization passes in frontend test

2023-08-09 Thread Matthias Braun via Phabricator via cfe-commits
MatzeB updated this revision to Diff 548655.
MatzeB added a comment.

Decided to just use "utils/update_cc_test_checks.py" so we can inspect the 
generate llvm.expect calls directly.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157518

Files:
  clang/test/CodeGenCXX/attr-likelihood-if-branch-weights.cpp

Index: clang/test/CodeGenCXX/attr-likelihood-if-branch-weights.cpp
===
--- clang/test/CodeGenCXX/attr-likelihood-if-branch-weights.cpp
+++ clang/test/CodeGenCXX/attr-likelihood-if-branch-weights.cpp
@@ -1,14 +1,31 @@
-// RUN: %clang_cc1 -O1 -emit-llvm %s -o - -triple=x86_64-linux-gnu | FileCheck -DLIKELY=2000 -DUNLIKELY=1 %s
-// RUN: %clang_cc1 -O1 -emit-llvm %s -triple=x86_64-linux-gnu -mllvm -likely-branch-weight=99 -mllvm -unlikely-branch-weight=42 -o - | FileCheck -DLIKELY=99 -DUNLIKELY=42 %s
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+// RUN: %clang_cc1 -O1 -disable-llvm-passes -emit-llvm %s -o - -triple=x86_64-linux-gnu | FileCheck -DLIKELY=2000 -DUNLIKELY=1 %s
 
 extern volatile bool b;
 extern volatile int i;
 extern bool A();
 extern bool B();
 
+// CHECK-LABEL: @_Z1fv(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[RETVAL:%.*]] = alloca i1, align 1
+// CHECK-NEXT:[[TMP0:%.*]] = load volatile i8, ptr @b, align 1, !tbaa [[TBAA2:![0-9]+]], !range [[RNG6:![0-9]+]]
+// CHECK-NEXT:[[TOBOOL:%.*]] = trunc i8 [[TMP0]] to i1
+// CHECK-NEXT:[[TOBOOL_EXPVAL:%.*]] = call i1 @llvm.expect.i1(i1 [[TOBOOL]], i1 true)
+// CHECK-NEXT:br i1 [[TOBOOL_EXPVAL]], label [[IF_THEN:%.*]], label [[IF_END:%.*]]
+// CHECK:   if.then:
+// CHECK-NEXT:[[CALL:%.*]] = call noundef zeroext i1 @_Z1Av()
+// CHECK-NEXT:store i1 [[CALL]], ptr [[RETVAL]], align 1
+// CHECK-NEXT:br label [[RETURN:%.*]]
+// CHECK:   if.end:
+// CHECK-NEXT:[[CALL1:%.*]] = call noundef zeroext i1 @_Z1Bv()
+// CHECK-NEXT:store i1 [[CALL1]], ptr [[RETVAL]], align 1
+// CHECK-NEXT:br label [[RETURN]]
+// CHECK:   return:
+// CHECK-NEXT:[[TMP1:%.*]] = load i1, ptr [[RETVAL]], align 1
+// CHECK-NEXT:ret i1 [[TMP1]]
+//
 bool f() {
-  // CHECK-LABEL: define{{.*}} zeroext i1 @_Z1fv
-  // CHECK: br {{.*}} !prof ![[PROF_LIKELY:[0-9]+]]
   if (b)
 [[likely]] {
   return A();
@@ -16,9 +33,26 @@
   return B();
 }
 
+// CHECK-LABEL: @_Z1gv(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[RETVAL:%.*]] = alloca i1, align 1
+// CHECK-NEXT:[[TMP0:%.*]] = load volatile i8, ptr @b, align 1, !tbaa [[TBAA2]], !range [[RNG6]]
+// CHECK-NEXT:[[TOBOOL:%.*]] = trunc i8 [[TMP0]] to i1
+// CHECK-NEXT:[[TOBOOL_EXPVAL:%.*]] = call i1 @llvm.expect.i1(i1 [[TOBOOL]], i1 false)
+// CHECK-NEXT:br i1 [[TOBOOL_EXPVAL]], label [[IF_THEN:%.*]], label [[IF_END:%.*]]
+// CHECK:   if.then:
+// CHECK-NEXT:[[CALL:%.*]] = call noundef zeroext i1 @_Z1Av()
+// CHECK-NEXT:store i1 [[CALL]], ptr [[RETVAL]], align 1
+// CHECK-NEXT:br label [[RETURN:%.*]]
+// CHECK:   if.end:
+// CHECK-NEXT:[[CALL1:%.*]] = call noundef zeroext i1 @_Z1Bv()
+// CHECK-NEXT:store i1 [[CALL1]], ptr [[RETVAL]], align 1
+// CHECK-NEXT:br label [[RETURN]]
+// CHECK:   return:
+// CHECK-NEXT:[[TMP1:%.*]] = load i1, ptr [[RETVAL]], align 1
+// CHECK-NEXT:ret i1 [[TMP1]]
+//
 bool g() {
-  // CHECK-LABEL: define{{.*}} zeroext i1 @_Z1gv
-  // CHECK: br {{.*}} !prof ![[PROF_UNLIKELY:[0-9]+]]
   if (b)
 [[unlikely]] {
   return A();
@@ -27,18 +61,47 @@
   return B();
 }
 
+// CHECK-LABEL: @_Z1hv(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[RETVAL:%.*]] = alloca i1, align 1
+// CHECK-NEXT:[[TMP0:%.*]] = load volatile i8, ptr @b, align 1, !tbaa [[TBAA2]], !range [[RNG6]]
+// CHECK-NEXT:[[TOBOOL:%.*]] = trunc i8 [[TMP0]] to i1
+// CHECK-NEXT:[[TOBOOL_EXPVAL:%.*]] = call i1 @llvm.expect.i1(i1 [[TOBOOL]], i1 false)
+// CHECK-NEXT:br i1 [[TOBOOL_EXPVAL]], label [[IF_THEN:%.*]], label [[IF_END:%.*]]
+// CHECK:   if.then:
+// CHECK-NEXT:[[CALL:%.*]] = call noundef zeroext i1 @_Z1Av()
+// CHECK-NEXT:store i1 [[CALL]], ptr [[RETVAL]], align 1
+// CHECK-NEXT:br label [[RETURN:%.*]]
+// CHECK:   if.end:
+// CHECK-NEXT:[[CALL1:%.*]] = call noundef zeroext i1 @_Z1Bv()
+// CHECK-NEXT:store i1 [[CALL1]], ptr [[RETVAL]], align 1
+// CHECK-NEXT:br label [[RETURN]]
+// CHECK:   return:
+// CHECK-NEXT:[[TMP1:%.*]] = load i1, ptr [[RETVAL]], align 1
+// CHECK-NEXT:ret i1 [[TMP1]]
+//
 bool h() {
-  // CHECK-LABEL: define{{.*}} zeroext i1 @_Z1hv
-  // CHECK: br {{.*}} !prof ![[PROF_UNLIKELY]]
   if (b)
 [[unlikely]] return A();
 
   return B();
 }
 
+// CHECK-LABEL: @_Z8NullStmtv(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[TMP0:%.*]] = load volatile i8, ptr @b, align 1, !tbaa [[TBAA2]], !range [[RNG6]]
+// CHECK-NEXT:[[TOBOOL:%.*]] = trunc i8 [[TMP0]] to i1
+// CHECK-NEXT:  

[PATCH] D157324: [clang] Move the Clang CI jobs off of the libc++ builders

2023-08-09 Thread Mark de Wever via Phabricator via cfe-commits
Mordante accepted this revision.
Mordante added a comment.

Nice to see the Clang CI new builder! Thanks for working on this, LGTM!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157324

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


  1   2   3   >