[PATCH] D133092: [clang] fix generation of .debug_aranges with LTO

2022-08-31 Thread Azat Khuzhin via Phabricator via cfe-commits
azat created this revision.
Herald added a subscriber: inglorion.
Herald added a project: All.
azat requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay.
Herald added a project: clang.

Right now in case of LTO the section is not emited:

  $ cat test.c
  void __attribute__((optnone)) bar()
  {
  }
  void __attribute__((optnone)) foo()
  {
  bar();
  }
  int main()
  {
  foo();
  }
  
  $ clang -flto=thin -gdwarf-aranges -g -O3 test.c
  $ eu-readelf -waranges a.out  | fgrep -c -e foo -e bar
  0
  
  $ clang -gdwarf-aranges -g -O3 test.c
  $ eu-readelf -waranges a.out  | fgrep -c -e foo -e bar
  2

Fix this by passing explicitly -mllvm -generate-arange-section.

P.S. although this looks like a hack, since none of -mllvm was passed to
the lld before.

Signed-off-by: Azat Khuzhin 
Suggested-by: OCHyams 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D133092

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


Index: clang/lib/Driver/ToolChains/CommonArgs.cpp
===
--- clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -506,6 +506,9 @@
 Suffix,
 Plugin);
 CmdArgs.push_back(Args.MakeArgString(Plugin));
+  } else if (Args.hasArg(options::OPT_gdwarf_aranges)) {
+CmdArgs.push_back(Args.MakeArgString("-mllvm"));
+CmdArgs.push_back(Args.MakeArgString("-generate-arange-section"));
   }
 
   // Try to pass driver level flags relevant to LTO code generation down to


Index: clang/lib/Driver/ToolChains/CommonArgs.cpp
===
--- clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -506,6 +506,9 @@
 Suffix,
 Plugin);
 CmdArgs.push_back(Args.MakeArgString(Plugin));
+  } else if (Args.hasArg(options::OPT_gdwarf_aranges)) {
+CmdArgs.push_back(Args.MakeArgString("-mllvm"));
+CmdArgs.push_back(Args.MakeArgString("-generate-arange-section"));
   }
 
   // Try to pass driver level flags relevant to LTO code generation down to
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D133085: [clang] trim trailing space in format tests. NFC

2022-08-31 Thread YingChi Long via Phabricator via cfe-commits
inclyc added a comment.

In D133085#3763198 , @ChuanqiXu wrote:

> Do you have commit access? If you have, I remember LLVM encourages to land 
> such fixes directly without reviewed. (+ @aaron.ballman to make sure)

Thanks! I'm just not sure whether these changes are necessary or not. :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133085

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


[clang] 5ee51e8 - [clang] trim trailing space in format tests. NFC

2022-08-31 Thread YingChi Long via cfe-commits

Author: YingChi Long
Date: 2022-09-01T13:30:40+08:00
New Revision: 5ee51e8154253088b333c8e82c64d0f00d7d0524

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

LOG: [clang] trim trailing space in format tests. NFC

Found in https://reviews.llvm.org/D132568

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

Added: 


Modified: 
clang/test/FixIt/format.m
clang/test/FixIt/format.mm
clang/test/Sema/format-strings-scanf.c

Removed: 




diff  --git a/clang/test/FixIt/format.m b/clang/test/FixIt/format.m
index 966cf79b2e0f7..950765bad9339 100644
--- a/clang/test/FixIt/format.m
+++ b/clang/test/FixIt/format.m
@@ -37,7 +37,7 @@ void test_string_correction (char *x) {
   // CHECK: fix-it:"{{.*}}":{34:11-34:13}:"%s"
 }
 
-void test_object_correction (id x) {  
+void test_object_correction (id x) {
   NSLog(@"%d", x); // expected-warning{{format specifies type 'int' but the 
argument has type 'id'}}
   NSLog(@"%s", x); // expected-warning{{format specifies type 'char *' but the 
argument has type 'id'}}
   NSLog(@"%lf", x); // expected-warning{{format specifies type 'double' but 
the argument has type 'id'}}
@@ -108,7 +108,7 @@ void test_char(char c, signed char s, unsigned char u, 
uint8_t n) {
   NSLog(@"%c", c); // no-warning
   // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]:11-[[@LINE-1]]:13}:"%c"
 
-  
+
   NSLog(@"%s", s); // expected-warning{{format specifies type 'char *' but the 
argument has type 'signed char'}}
   // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:11-[[@LINE-1]]:13}:"%c"
 
@@ -197,11 +197,11 @@ void test_percent_C(void) {
   // CHECK: fix-it:"{{.*}}":{[[@LINE-2]]:16-[[@LINE-2]]:16}:"(unsigned short)"
 
   typedef unsigned short unichar;
-  
+
   NSLog(@"%C", 0x260300);  // expected-warning{{format specifies type 
'unichar' (aka 'unsigned short') but the argument has type 'int'}}
   // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]:11-[[@LINE-1]]:13}:"%d"
   // CHECK: fix-it:"{{.*}}":{[[@LINE-2]]:16-[[@LINE-2]]:16}:"(unichar)"
-  
+
   NSLog(@"%C", data ? 0x2F : 0x260300); // expected-warning{{format 
specifies type 'unichar' (aka 'unsigned short') but the argument has type 
'int'}}
   // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]:11-[[@LINE-1]]:13}:"%d"
   // CHECK: fix-it:"{{.*}}":{[[@LINE-2]]:16-[[@LINE-2]]:16}:"(unichar)("
@@ -239,7 +239,7 @@ void testSizeTypes(void) {
 
   printf("%zd", 0.f); // expected-warning-re{{format specifies type 'ssize_t' 
(aka '{{.+}}') but the argument has type 'float'}}
   // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:11-[[@LINE-1]]:14}:"%f"
-  
+
   short x;
 #if !defined(__ANDROID__) && !defined(__Fuchsia__)
   printf("%zn", ); // expected-warning-re{{format specifies type 'ssize_t *' 
(aka '{{.+}}') but the argument has type 'short *'}}
@@ -266,7 +266,7 @@ void testPtrDiffTypes(void) {
 
   printf("%tu", 0.f); // expected-warning-re{{format specifies type 'unsigned 
ptr
diff _t' (aka '{{.+}}') but the argument has type 'float'}}
   // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:11-[[@LINE-1]]:14}:"%f"
-  
+
   ptr
diff _t p2 = 0;
   printf("%td", p2);  // No warning.
 

diff  --git a/clang/test/FixIt/format.mm b/clang/test/FixIt/format.mm
index 9d89c062faa97..eed7c981f2c45 100644
--- a/clang/test/FixIt/format.mm
+++ b/clang/test/FixIt/format.mm
@@ -19,11 +19,11 @@ void test_percent_C() {
 
   NSLog(@"%C", wchar_data);  // expected-warning{{format specifies type 
'unichar' (aka 'unsigned short') but the argument has type 'wchar_t'}}
   // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:16-[[@LINE-1]]:16}:"(unichar)"
-  
+
   NSLog(@"%C", 0x260300);  // expected-warning{{format specifies type 
'unichar' (aka 'unsigned short') but the argument has type 'int'}}
   // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]:11-[[@LINE-1]]:13}:"%d"
   // CHECK: fix-it:"{{.*}}":{[[@LINE-2]]:16-[[@LINE-2]]:16}:"(unichar)"
-  
+
   NSLog(@"%C", 0.0); // expected-warning{{format specifies type 'unichar' (aka 
'unsigned short') but the argument has type 'double'}}
   // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:11-[[@LINE-1]]:13}:"%f"
   // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-2]]:16-[[@LINE-2]]:16}:"(unichar)"

diff  --git a/clang/test/Sema/format-strings-scanf.c 
b/clang/test/Sema/format-strings-scanf.c
index 054439ecaf5a7..aebb68c37fb98 100644
--- a/clang/test/Sema/format-strings-scanf.c
+++ b/clang/test/Sema/format-strings-scanf.c
@@ -12,7 +12,7 @@ typedef __SIZE_TYPE__ size_t;
   unsigned int : (int)0,   
\
   unsigned short : (short)0,   
\
   unsigned char : (signed char)0))
-typedef __SSIZE_TYPE__ ssize_t; 
+typedef __SSIZE_TYPE__ ssize_t;
 
 typedef __PTRDIFF_TYPE__ ptr
diff _t;
 #define __UNSIGNED_PTRDIFF_TYPE__ 

[PATCH] D133085: [clang] trim trailing space in format tests. NFC

2022-08-31 Thread YingChi Long via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG5ee51e815425: [clang] trim trailing space in format tests. 
NFC (authored by inclyc).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133085

Files:
  clang/test/FixIt/format.m
  clang/test/FixIt/format.mm
  clang/test/Sema/format-strings-scanf.c

Index: clang/test/Sema/format-strings-scanf.c
===
--- clang/test/Sema/format-strings-scanf.c
+++ clang/test/Sema/format-strings-scanf.c
@@ -12,7 +12,7 @@
   unsigned int : (int)0,   \
   unsigned short : (short)0,   \
   unsigned char : (signed char)0))
-typedef __SSIZE_TYPE__ ssize_t; 
+typedef __SSIZE_TYPE__ ssize_t;
 
 typedef __PTRDIFF_TYPE__ ptrdiff_t;
 #define __UNSIGNED_PTRDIFF_TYPE__  \
@@ -224,13 +224,13 @@
 
   ptrdiff_t p2 = 0;
   scanf("%td", ); // No warning.
-  
+
   double d2 = 0.;
   scanf("%td", ); // expected-warning-re{{format specifies type 'ptrdiff_t *' (aka '{{.+}}') but the argument has type 'double *'}}
 
   ptrdiff_t p3 = 0;
   scanf("%tn", ); // No warning.
-  
+
   double d3 = 0.;
   scanf("%tn", ); // expected-warning-re{{format specifies type 'ptrdiff_t *' (aka '{{.+}}') but the argument has type 'double *'}}
 }
Index: clang/test/FixIt/format.mm
===
--- clang/test/FixIt/format.mm
+++ clang/test/FixIt/format.mm
@@ -19,11 +19,11 @@
 
   NSLog(@"%C", wchar_data);  // expected-warning{{format specifies type 'unichar' (aka 'unsigned short') but the argument has type 'wchar_t'}}
   // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:16-[[@LINE-1]]:16}:"(unichar)"
-  
+
   NSLog(@"%C", 0x260300);  // expected-warning{{format specifies type 'unichar' (aka 'unsigned short') but the argument has type 'int'}}
   // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]:11-[[@LINE-1]]:13}:"%d"
   // CHECK: fix-it:"{{.*}}":{[[@LINE-2]]:16-[[@LINE-2]]:16}:"(unichar)"
-  
+
   NSLog(@"%C", 0.0); // expected-warning{{format specifies type 'unichar' (aka 'unsigned short') but the argument has type 'double'}}
   // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:11-[[@LINE-1]]:13}:"%f"
   // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-2]]:16-[[@LINE-2]]:16}:"(unichar)"
Index: clang/test/FixIt/format.m
===
--- clang/test/FixIt/format.m
+++ clang/test/FixIt/format.m
@@ -37,7 +37,7 @@
   // CHECK: fix-it:"{{.*}}":{34:11-34:13}:"%s"
 }
 
-void test_object_correction (id x) {  
+void test_object_correction (id x) {
   NSLog(@"%d", x); // expected-warning{{format specifies type 'int' but the argument has type 'id'}}
   NSLog(@"%s", x); // expected-warning{{format specifies type 'char *' but the argument has type 'id'}}
   NSLog(@"%lf", x); // expected-warning{{format specifies type 'double' but the argument has type 'id'}}
@@ -108,7 +108,7 @@
   NSLog(@"%c", c); // no-warning
   // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]:11-[[@LINE-1]]:13}:"%c"
 
-  
+
   NSLog(@"%s", s); // expected-warning{{format specifies type 'char *' but the argument has type 'signed char'}}
   // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:11-[[@LINE-1]]:13}:"%c"
 
@@ -197,11 +197,11 @@
   // CHECK: fix-it:"{{.*}}":{[[@LINE-2]]:16-[[@LINE-2]]:16}:"(unsigned short)"
 
   typedef unsigned short unichar;
-  
+
   NSLog(@"%C", 0x260300);  // expected-warning{{format specifies type 'unichar' (aka 'unsigned short') but the argument has type 'int'}}
   // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]:11-[[@LINE-1]]:13}:"%d"
   // CHECK: fix-it:"{{.*}}":{[[@LINE-2]]:16-[[@LINE-2]]:16}:"(unichar)"
-  
+
   NSLog(@"%C", data ? 0x2F : 0x260300); // expected-warning{{format specifies type 'unichar' (aka 'unsigned short') but the argument has type 'int'}}
   // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]:11-[[@LINE-1]]:13}:"%d"
   // CHECK: fix-it:"{{.*}}":{[[@LINE-2]]:16-[[@LINE-2]]:16}:"(unichar)("
@@ -239,7 +239,7 @@
 
   printf("%zd", 0.f); // expected-warning-re{{format specifies type 'ssize_t' (aka '{{.+}}') but the argument has type 'float'}}
   // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:11-[[@LINE-1]]:14}:"%f"
-  
+
   short x;
 #if !defined(__ANDROID__) && !defined(__Fuchsia__)
   printf("%zn", ); // expected-warning-re{{format specifies type 'ssize_t *' (aka '{{.+}}') but the argument has type 'short *'}}
@@ -266,7 +266,7 @@
 
   printf("%tu", 0.f); // expected-warning-re{{format specifies type 'unsigned ptrdiff_t' (aka '{{.+}}') but the argument has type 'float'}}
   // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:11-[[@LINE-1]]:14}:"%f"
-  
+
   ptrdiff_t p2 = 0;
   printf("%td", p2);  // No warning.
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org

[PATCH] D133052: [clang] Avoid crash when expanding conversion templates in concepts.

2022-08-31 Thread Yuanfang Chen via Phabricator via cfe-commits
ychen added a comment.

In D133052#3763041 , @luken-google 
wrote:

> In D133052#3762596 , @ychen wrote:
>
>> Like mentioned in 
>> https://stackoverflow.com/questions/68853472/is-this-a-bug-in-clangs-c20-concepts-implementation-unnecessary-checking-of,
>>  could we not go down the path of considering conversion candidates? It 
>> seems that's blessed by the standard.
>
> If I'm understanding the code correctly, the intent of this patch is to 
> definitely consider conversion candidates, only to exclude those conversion 
> candidates that are templated methods where the From type is the same as the 
> To type, which to me mean they are possibly redundant?

Excluding them is basically saying "because it may be a redundant conversion, 
we should not consider it as the best via function." which doesn't seem correct 
to me.

I think the straightforward approach would be to check if we're in the 
`ConstraintCheck` instantiation context, and if so check if any template 
parameter is constrained by the same concept. However, I'm worried about the 
overhead. So I'd prefer to skip this add-conv-candicates-for-copy-elision path 
(https://github.com/llvm/llvm-project/blob/main/clang/lib/Sema/SemaInit.cpp#L4012-L4053)
 during the concept check. The compiler guarantees copy elision under certain 
conditions (C++17) but I could not think of any situation that users want to or 
could check copy elision inside the concept. So I think we're safe.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133052

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


[PATCH] D133085: [clang] trim trailing space in format tests. NFC

2022-08-31 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added subscribers: aaron.ballman, ChuanqiXu.
ChuanqiXu accepted this revision.
ChuanqiXu added a comment.
This revision is now accepted and ready to land.

Do you have commit access? If you have, I remember LLVM encourages such fixes 
landed directly without review. (+ @aaron.ballman to make sure)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133085

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


[PATCH] D132975: [clang][BOLT] Add clang-bolt target (WIP)

2022-08-31 Thread Amir Ayupov via Phabricator via cfe-commits
Amir updated this revision to Diff 457172.
Amir added a comment.

Successfully invoke the bootstrap/profiling build


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132975

Files:
  clang/CMakeLists.txt
  clang/cmake/caches/BOLT.cmake

Index: clang/cmake/caches/BOLT.cmake
===
--- /dev/null
+++ clang/cmake/caches/BOLT.cmake
@@ -0,0 +1,14 @@
+set(CMAKE_BUILD_TYPE Release CACHE STRING "")
+set(CLANG_BOLT_INSTRUMENT ON CACHE BOOL "")
+set(CLANG_BOLT_INSTRUMENT_PROJECTS "lld" CACHE STRING "")
+set(CLANG_BOLT_INSTRUMENT_TARGETS "lld" CACHE STRING "")
+set(CMAKE_EXE_LINKER_FLAGS "-Wl,--emit-relocs,-znow" CACHE STRING "")
+
+set(LLVM_ENABLE_PROJECTS "bolt;clang" CACHE STRING "")
+set(LLVM_TARGETS_TO_BUILD Native CACHE STRING "")
+
+# Disable function splitting enabled by default in GCC8+
+if("${CMAKE_CXX_COMPILER_ID}" MATCHES "GNU")
+  set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fno-reorder-blocks-and-partition")
+  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-reorder-blocks-and-partition")
+endif()
Index: clang/CMakeLists.txt
===
--- clang/CMakeLists.txt
+++ clang/CMakeLists.txt
@@ -443,7 +443,7 @@
   "HAVE_CLANG_PLUGIN_SUPPORT" OFF)
 
 # If libstdc++ is statically linked, clang-repl needs to statically link libstdc++
-# itself, which is not possible in many platforms because of current limitations in 
+# itself, which is not possible in many platforms because of current limitations in
 # JIT stack. (more platforms need to be supported by JITLink)
 if(NOT LLVM_STATIC_LINK_CXX_STDLIB)
   set(HAVE_CLANG_REPL_SUPPORT ON)
@@ -878,6 +878,97 @@
   endforeach()
 endif()
 
+if (CLANG_BOLT_INSTRUMENT)
+  set(C_COMPILER "clang-bolt.inst")
+  set(CXX_COMPILER "clang++-bolt.inst")
+  set(C_COMPILER_PATH ${CMAKE_BINARY_DIR}/bin/${C_COMPILER})
+  set(CXX_COMPILER_PATH ${CMAKE_BINARY_DIR}/bin/${CXX_COMPILER})
+
+  # Instrument clang with BOLT
+  add_custom_target(clang-instrumented
+DEPENDS ${C_COMPILER_PATH}
+  )
+  add_custom_command(OUTPUT ${C_COMPILER_PATH}
+DEPENDS clang llvm-bolt
+COMMAND llvm-bolt $ -o ${C_COMPILER_PATH}
+  -instrument --instrumentation-file-append-pid
+  --instrumentation-file=${CMAKE_CURRENT_BINARY_DIR}/prof.fdata
+COMMENT "Instrumenting clang binary with BOLT"
+VERBATIM
+  )
+
+  # Make a symlink from ${C_COMPILER} to ${CXX_COMPILER}
+  add_custom_target(clang++-instrumented
+DEPENDS ${CXX_COMPILER_PATH}
+  )
+  add_custom_command(OUTPUT ${CXX_COMPILER_PATH}
+DEPENDS clang-instrumented
+COMMAND ${CMAKE_COMMAND} -E create_symlink
+  ${C_COMPILER_PATH}
+  ${CXX_COMPILER_PATH}
+COMMENT "Creating symlink from BOLT instrumented clang to clang++"
+VERBATIM
+  )
+
+  # Configure and build Clang with instrumented Clang to collect the profile
+  set(STAMP_DIR ${CMAKE_CURRENT_BINARY_DIR}/bolt-instrumented-clang-stamps/)
+  set(BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR}/bolt-instrumented-clang-bins/)
+  set(build_configuration "$")
+  include(ExternalProject)
+  ExternalProject_Add(bolt-instrumentation-profile
+DEPENDS clang++-instrumented
+PREFIX bolt-instrumentation-profile
+SOURCE_DIR ${CMAKE_SOURCE_DIR}
+STAMP_DIR ${STAMP_DIR}
+BINARY_DIR ${BINARY_DIR}
+EXCLUDE_FROM_ALL 1
+CMAKE_ARGS
+# We shouldn't need to set this here, but INSTALL_DIR doesn't
+# seem to work, so instead I'm passing this through
+-DCMAKE_INSTALL_PREFIX=${CMAKE_INSTALL_PREFIX}
+-DCMAKE_C_COMPILER=${C_COMPILER_PATH}
+-DCMAKE_CXX_COMPILER=${CXX_COMPILER_PATH}
+-DCMAKE_ASM_COMPILER=${C_COMPILER_PATH}
+-DCMAKE_ASM_COMPILER_ID=Clang
+-DCMAKE_BUILD_TYPE=Release
+-DLLVM_ENABLE_PROJECTS=${CLANG_BOLT_INSTRUMENT_PROJECTS}
+-DLLVM_TARGETS_TO_BUILD=${LLVM_TARGETS_TO_BUILD}
+BUILD_COMMAND ${CMAKE_COMMAND} --build ${BINARY_DIR}
+   --config ${build_configuration}
+   --target ${CLANG_BOLT_INSTRUMENT_TARGETS}
+INSTALL_COMMAND ""
+STEP_TARGETS configure build
+USES_TERMINAL_CONFIGURE 1
+USES_TERMINAL_BUILD 1
+USES_TERMINAL_INSTALL 1
+  )
+
+  # Merge profiles into one using merge-fdata
+  add_custom_target(clang-bolt-profile
+DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/prof.fdata
+  )
+  add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/prof.fdata
+DEPENDS merge-fdata bolt-instrumentation-profile-build
+COMMAND merge-fdata ${CMAKE_CURRENT_BINARY_DIR}/prof.fdata.*
+  -o ${CMAKE_CURRENT_BINARY_DIR}/prof.fdata
+COMMENT "Preparing BOLT profile"
+VERBATIM
+  )
+
+  # Optimize original (pre-bolt) Clang using the collected profile
+  add_custom_target(clang-bolt
+DEPENDS ${CMAKE_BINARY_DIR}/bin/clang-bolt
+  )
+  

[PATCH] D132421: [HLSL] Support PCH for cc1 mode

2022-08-31 Thread Xiang Li via Phabricator via cfe-commits
python3kgae marked an inline comment as done.
python3kgae added inline comments.



Comment at: clang/include/clang/Sema/HLSLExternalSemaSource.h:58
+/// them before we initialize the ExternalSemaSource base class.
+struct ChainedHLSLExternalSemaSourceMembers {
+  ChainedHLSLExternalSemaSourceMembers(ExternalSemaSource *ExtSema)

beanz wrote:
> python3kgae wrote:
> > beanz wrote:
> > > IIUC, this code just exists to make sure that the `ASTReader` 
> > > deserializes before the external sema source starts adding things. Is 
> > > that correct?
> > > 
> > > If so, you don't need to do this, instead you can just add this code to 
> > > `InitializeSema()` to force the `ASTReader` to de-serialize the decls:
> > > 
> > > ```
> > > // If the translation unit has external storage force external decls to 
> > > load.
> > > if (AST.getTranslationUnitDecl()->hasExternalLexicalStorage())
> > > (void)AST.getTranslationUnitDecl()->decls_begin();
> > > ```
> > Still need this to make sure HLSLSema and ExternalSema are initialized 
> > before  MultiplexExternalSemaSource.
> In FrontendAction, where you are creating the Chained source, you can instead 
> create a Multiplex source, and put the PCH external source in as the first 
> source and the HLSL one second. The PCH will get initialized first, the HLSL 
> one can force the PCH one to populate the decls.
Asked how to resolve the issue in 
https://discourse.llvm.org/t/is-it-possible-for-multiplexexternalsemasource-to-own-the-sources/64990

Hope someone can explain why multiplexexternalsemasource doesn't own the 
Sources.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132421

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


[PATCH] D133088: [Clang] Fix wrong diagnostic for scope identifier with internal linkage

2022-08-31 Thread Jun Zhang via Phabricator via cfe-commits
junaire updated this revision to Diff 457171.
junaire added a comment.

Simpify code a little bit.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133088

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaDecl.cpp
  clang/test/Sema/error-decl-block-internal-linkage-no-init.c


Index: clang/test/Sema/error-decl-block-internal-linkage-no-init.c
===
--- /dev/null
+++ clang/test/Sema/error-decl-block-internal-linkage-no-init.c
@@ -0,0 +1,7 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -fsyntax-only -verify %s
+static int x;
+
+void f(void)
+{
+extern int x = 1; // expected-error {{declaration of block scope 
identifier with internal linkage shall have no initializer}}
+}
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -12771,9 +12771,14 @@
 return;
   }
 
+  // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
-// C99 6.7.8p5. C++ has no such restriction, but that is a defect.
-Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
+unsigned DiagKind = diag::err_block_extern_cant_init;
+// C2x 6.7.10p6.
+if (VDecl->getFormalLinkage() == InternalLinkage)
+  DiagKind = diag::err_block_internal_linkage_no_init;
+
+Diag(VDecl->getLocation(), DiagKind);
 VDecl->setInvalidDecl();
 return;
   }
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -5896,6 +5896,9 @@
 "'loader_uninitialized' attribute">;
 def err_block_extern_cant_init : Error<
   "'extern' variable cannot have an initializer">;
+def err_block_internal_linkage_no_init : Error<
+  "declaration of block scope identifier with internal linkage shall "
+  "have no initializer">;
 def warn_extern_init : Warning<"'extern' variable has an initializer">,
   InGroup>;
 def err_variable_object_no_init : Error<
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -116,6 +116,9 @@
 - Correctly diagnose a future keyword if it exist as a keyword in the higher
   language version and specifies in which version it will be a keyword. This
   supports both c and c++ language.
+- Clang will now give a new more accurate diagnostic for declaration of block
+  scope identifiers that have internal linkage that has an initializer.
+  Fixes `Issue 57478: `_.
 
 Non-comprehensive list of changes in this release
 -


Index: clang/test/Sema/error-decl-block-internal-linkage-no-init.c
===
--- /dev/null
+++ clang/test/Sema/error-decl-block-internal-linkage-no-init.c
@@ -0,0 +1,7 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -fsyntax-only -verify %s
+static int x;
+
+void f(void)
+{
+extern int x = 1; // expected-error {{declaration of block scope identifier with internal linkage shall have no initializer}}
+}
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -12771,9 +12771,14 @@
 return;
   }
 
+  // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
-// C99 6.7.8p5. C++ has no such restriction, but that is a defect.
-Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
+unsigned DiagKind = diag::err_block_extern_cant_init;
+// C2x 6.7.10p6.
+if (VDecl->getFormalLinkage() == InternalLinkage)
+  DiagKind = diag::err_block_internal_linkage_no_init;
+
+Diag(VDecl->getLocation(), DiagKind);
 VDecl->setInvalidDecl();
 return;
   }
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -5896,6 +5896,9 @@
 "'loader_uninitialized' attribute">;
 def err_block_extern_cant_init : Error<
   "'extern' variable cannot have an initializer">;
+def err_block_internal_linkage_no_init : Error<
+  "declaration of block scope identifier with internal linkage shall "
+  "have no initializer">;
 def warn_extern_init : Warning<"'extern' variable has an initializer">,
   InGroup>;
 def err_variable_object_no_init : Error<
Index: 

[PATCH] D133088: [Clang] Fix wrong diagnostic for scope identifier with internal linkage

2022-08-31 Thread Jun Zhang via Phabricator via cfe-commits
junaire created this revision.
junaire added a reviewer: aaron.ballman.
Herald added a project: All.
junaire requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

If the declaration of an identifier has block scope, and the identifier has
external or internal linkage, the declaration shall have no initializer for
the identifier.

Clang now gives a correct diagnostic for this case.
Fixes https://github.com/llvm/llvm-project/issues/57478

Signed-off-by: Jun Zhang 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D133088

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaDecl.cpp
  clang/test/Sema/error-decl-block-internal-linkage-no-init.c


Index: clang/test/Sema/error-decl-block-internal-linkage-no-init.c
===
--- /dev/null
+++ clang/test/Sema/error-decl-block-internal-linkage-no-init.c
@@ -0,0 +1,7 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -fsyntax-only -verify %s
+static int x;
+
+void f(void)
+{
+extern int x = 1; // expected-error {{declaration of block scope 
identifier with internal linkage shall have no initializer}}
+}
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -12771,9 +12771,17 @@
 return;
   }
 
+  // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
-// C99 6.7.8p5. C++ has no such restriction, but that is a defect.
-Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
+
+// C2x 6.7.10p6.
+unsigned DiagKind = diag::err_block_extern_cant_init;
+bool IsInBlock =
+getCurScope()->getFlags() & (Scope::FnScope | Scope::BlockScope);
+if (IsInBlock && VDecl->getFormalLinkage() == InternalLinkage)
+  DiagKind = diag::err_block_internal_linkage_no_init;
+
+Diag(VDecl->getLocation(), DiagKind);
 VDecl->setInvalidDecl();
 return;
   }
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -5896,6 +5896,9 @@
 "'loader_uninitialized' attribute">;
 def err_block_extern_cant_init : Error<
   "'extern' variable cannot have an initializer">;
+def err_block_internal_linkage_no_init : Error<
+  "declaration of block scope identifier with internal linkage shall "
+  "have no initializer">;
 def warn_extern_init : Warning<"'extern' variable has an initializer">,
   InGroup>;
 def err_variable_object_no_init : Error<
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -116,6 +116,9 @@
 - Correctly diagnose a future keyword if it exist as a keyword in the higher
   language version and specifies in which version it will be a keyword. This
   supports both c and c++ language.
+- Clang will now give a new more accurate diagnostic for declaration of block
+  scope identifiers that have internal linkage that has an initializer.
+  Fixes `Issue 57478: `_.
 
 Non-comprehensive list of changes in this release
 -


Index: clang/test/Sema/error-decl-block-internal-linkage-no-init.c
===
--- /dev/null
+++ clang/test/Sema/error-decl-block-internal-linkage-no-init.c
@@ -0,0 +1,7 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -fsyntax-only -verify %s
+static int x;
+
+void f(void)
+{
+extern int x = 1; // expected-error {{declaration of block scope identifier with internal linkage shall have no initializer}}
+}
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -12771,9 +12771,17 @@
 return;
   }
 
+  // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
-// C99 6.7.8p5. C++ has no such restriction, but that is a defect.
-Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
+
+// C2x 6.7.10p6.
+unsigned DiagKind = diag::err_block_extern_cant_init;
+bool IsInBlock =
+getCurScope()->getFlags() & (Scope::FnScope | Scope::BlockScope);
+if (IsInBlock && VDecl->getFormalLinkage() == InternalLinkage)
+  DiagKind = diag::err_block_internal_linkage_no_init;
+
+Diag(VDecl->getLocation(), DiagKind);
 VDecl->setInvalidDecl();
 return;
   }
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td

[PATCH] D133087: [Docs] fix wrong example of warping class definitions

2022-08-31 Thread passw_passw via Phabricator via cfe-commits
Passw created this revision.
Herald added a project: All.
Passw requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

  example of
  BraceWrapping
AfterClass
  is wrong


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D133087

Files:
  clang/docs/ClangFormatStyleOptions.rst


Index: clang/docs/ClangFormatStyleOptions.rst
===
--- clang/docs/ClangFormatStyleOptions.rst
+++ clang/docs/ClangFormatStyleOptions.rst
@@ -1439,12 +1439,12 @@
 .. code-block:: c++
 
   true:
-  class foo {};
-
-  false:
   class foo
   {};
 
+  false:
+  class foo {};
+
   * ``BraceWrappingAfterControlStatementStyle AfterControlStatement``
 Wrap control statements (``if``/``for``/``while``/``switch``/..).
 


Index: clang/docs/ClangFormatStyleOptions.rst
===
--- clang/docs/ClangFormatStyleOptions.rst
+++ clang/docs/ClangFormatStyleOptions.rst
@@ -1439,12 +1439,12 @@
 .. code-block:: c++
 
   true:
-  class foo {};
-
-  false:
   class foo
   {};
 
+  false:
+  class foo {};
+
   * ``BraceWrappingAfterControlStatementStyle AfterControlStatement``
 Wrap control statements (``if``/``for``/``while``/``switch``/..).
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D133029: [Sema] Allow to diagnose the references to std::vector with incomplete T

2022-08-31 Thread Shafik Yaghmour via Phabricator via cfe-commits
shafik added a comment.

Do you have an idea of how common this might be?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133029

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


[PATCH] D133085: [clang] trim trailing space in format tests. NFC

2022-08-31 Thread YingChi Long via Phabricator via cfe-commits
inclyc created this revision.
inclyc added a reviewer: clang-language-wg.
Herald added a project: All.
inclyc requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Found in https://reviews.llvm.org/D132568


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D133085

Files:
  clang/test/FixIt/format.m
  clang/test/FixIt/format.mm
  clang/test/Sema/format-strings-scanf.c

Index: clang/test/Sema/format-strings-scanf.c
===
--- clang/test/Sema/format-strings-scanf.c
+++ clang/test/Sema/format-strings-scanf.c
@@ -12,7 +12,7 @@
   unsigned int : (int)0,   \
   unsigned short : (short)0,   \
   unsigned char : (signed char)0))
-typedef __SSIZE_TYPE__ ssize_t; 
+typedef __SSIZE_TYPE__ ssize_t;
 
 typedef __PTRDIFF_TYPE__ ptrdiff_t;
 #define __UNSIGNED_PTRDIFF_TYPE__  \
@@ -224,13 +224,13 @@
 
   ptrdiff_t p2 = 0;
   scanf("%td", ); // No warning.
-  
+
   double d2 = 0.;
   scanf("%td", ); // expected-warning-re{{format specifies type 'ptrdiff_t *' (aka '{{.+}}') but the argument has type 'double *'}}
 
   ptrdiff_t p3 = 0;
   scanf("%tn", ); // No warning.
-  
+
   double d3 = 0.;
   scanf("%tn", ); // expected-warning-re{{format specifies type 'ptrdiff_t *' (aka '{{.+}}') but the argument has type 'double *'}}
 }
Index: clang/test/FixIt/format.mm
===
--- clang/test/FixIt/format.mm
+++ clang/test/FixIt/format.mm
@@ -19,11 +19,11 @@
 
   NSLog(@"%C", wchar_data);  // expected-warning{{format specifies type 'unichar' (aka 'unsigned short') but the argument has type 'wchar_t'}}
   // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:16-[[@LINE-1]]:16}:"(unichar)"
-  
+
   NSLog(@"%C", 0x260300);  // expected-warning{{format specifies type 'unichar' (aka 'unsigned short') but the argument has type 'int'}}
   // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]:11-[[@LINE-1]]:13}:"%d"
   // CHECK: fix-it:"{{.*}}":{[[@LINE-2]]:16-[[@LINE-2]]:16}:"(unichar)"
-  
+
   NSLog(@"%C", 0.0); // expected-warning{{format specifies type 'unichar' (aka 'unsigned short') but the argument has type 'double'}}
   // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:11-[[@LINE-1]]:13}:"%f"
   // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-2]]:16-[[@LINE-2]]:16}:"(unichar)"
Index: clang/test/FixIt/format.m
===
--- clang/test/FixIt/format.m
+++ clang/test/FixIt/format.m
@@ -37,7 +37,7 @@
   // CHECK: fix-it:"{{.*}}":{34:11-34:13}:"%s"
 }
 
-void test_object_correction (id x) {  
+void test_object_correction (id x) {
   NSLog(@"%d", x); // expected-warning{{format specifies type 'int' but the argument has type 'id'}}
   NSLog(@"%s", x); // expected-warning{{format specifies type 'char *' but the argument has type 'id'}}
   NSLog(@"%lf", x); // expected-warning{{format specifies type 'double' but the argument has type 'id'}}
@@ -108,7 +108,7 @@
   NSLog(@"%c", c); // no-warning
   // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]:11-[[@LINE-1]]:13}:"%c"
 
-  
+
   NSLog(@"%s", s); // expected-warning{{format specifies type 'char *' but the argument has type 'signed char'}}
   // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:11-[[@LINE-1]]:13}:"%c"
 
@@ -197,11 +197,11 @@
   // CHECK: fix-it:"{{.*}}":{[[@LINE-2]]:16-[[@LINE-2]]:16}:"(unsigned short)"
 
   typedef unsigned short unichar;
-  
+
   NSLog(@"%C", 0x260300);  // expected-warning{{format specifies type 'unichar' (aka 'unsigned short') but the argument has type 'int'}}
   // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]:11-[[@LINE-1]]:13}:"%d"
   // CHECK: fix-it:"{{.*}}":{[[@LINE-2]]:16-[[@LINE-2]]:16}:"(unichar)"
-  
+
   NSLog(@"%C", data ? 0x2F : 0x260300); // expected-warning{{format specifies type 'unichar' (aka 'unsigned short') but the argument has type 'int'}}
   // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]:11-[[@LINE-1]]:13}:"%d"
   // CHECK: fix-it:"{{.*}}":{[[@LINE-2]]:16-[[@LINE-2]]:16}:"(unichar)("
@@ -239,7 +239,7 @@
 
   printf("%zd", 0.f); // expected-warning-re{{format specifies type 'ssize_t' (aka '{{.+}}') but the argument has type 'float'}}
   // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:11-[[@LINE-1]]:14}:"%f"
-  
+
   short x;
 #if !defined(__ANDROID__) && !defined(__Fuchsia__)
   printf("%zn", ); // expected-warning-re{{format specifies type 'ssize_t *' (aka '{{.+}}') but the argument has type 'short *'}}
@@ -266,7 +266,7 @@
 
   printf("%tu", 0.f); // expected-warning-re{{format specifies type 'unsigned ptrdiff_t' (aka '{{.+}}') but the argument has type 'float'}}
   // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:11-[[@LINE-1]]:14}:"%f"
-  
+
   ptrdiff_t p2 = 0;
   printf("%td", p2);  // No warning.
 
___
cfe-commits mailing list

[PATCH] D132997: [clang][Interp] Handle DeclRefExpr of reference types

2022-08-31 Thread Shafik Yaghmour via Phabricator via cfe-commits
shafik added a comment.

I think like @aaron.ballman was saying in another PR you should aim for as 
complete set of tests as possible even if you have to comment one that can't 
work yet. For example cases that would involve `MemberExpr` or `UsingShadow` 
for example as well as the cases you mentioned not implemented in your 
description.


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

https://reviews.llvm.org/D132997

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


[PATCH] D133082: WIP: [clang] Implement setting crash_diagnostics_dir through env variable

2022-08-31 Thread Matheus Izvekov via Phabricator via cfe-commits
mizvekov updated this revision to Diff 457159.
mizvekov planned changes to this revision.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133082

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/crash-diagnostics-dir-3.c
  libcxx/test/libcxx/crash.sh.cpp
  libcxx/utils/ci/buildkite-pipeline.yml


Index: libcxx/utils/ci/buildkite-pipeline.yml
===
--- libcxx/utils/ci/buildkite-pipeline.yml
+++ libcxx/utils/ci/buildkite-pipeline.yml
@@ -369,10 +369,12 @@
 artifact_paths:
   - "**/test-results.xml"
   - "**/*.abilist"
+  - "**/crash_diagnostics/*"
 env:
 CC: "clang-${LLVM_HEAD_VERSION}"
 CXX: "clang++-${LLVM_HEAD_VERSION}"
 LLVM_SYMBOLIZER_PATH: "/usr/bin/llvm-symbolizer-${LLVM_HEAD_VERSION}"
+CLANG_CRASH_DIAGNOSTICS_DIR: "crash_diagnostics"
 agents:
   queue: "libcxx-builders"
   os: "linux"
Index: libcxx/test/libcxx/crash.sh.cpp
===
--- /dev/null
+++ libcxx/test/libcxx/crash.sh.cpp
@@ -0,0 +1,15 @@
+//===--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+// Test that we produce the crash artifacts in the pipeline
+// For exposition only
+// FIXME: Delete this file
+
+// RUN: not %{cxx} %{flags} %{compile_flags} -fsyntax-only %s
+
+#pragma clang __debug parser_crash
Index: clang/test/Driver/crash-diagnostics-dir-3.c
===
--- /dev/null
+++ clang/test/Driver/crash-diagnostics-dir-3.c
@@ -0,0 +1,5 @@
+// RUN: rm -rf %t
+// RUN: not env CLANG_CRASH_DIAGNOSTICS_DIR=%t %clang -c %s -o - 2>&1 | 
FileCheck %s
+#pragma clang __debug parser_crash
+// CHECK: Preprocessed source(s) and associated run script(s) are located at:
+// CHECK: diagnostic msg: 
{{.*}}{{/|\\}}crash-diagnostics-dir-3.c.tmp{{(/|\\).*}}.c
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -5422,15 +5422,17 @@
StringRef BoundArch) const {
   SmallString<128> TmpName;
   Arg *A = C.getArgs().getLastArg(options::OPT_fcrash_diagnostics_dir);
-  if (CCGenDiagnostics && A) {
-SmallString<128> CrashDirectory(A->getValue());
+  const char *CrashDirectory = CCGenDiagnostics && A
+   ? A->getValue()
+   : 
std::getenv("CLANG_CRASH_DIAGNOSTICS_DIR");
+  if (CrashDirectory) {
 if (!getVFS().exists(CrashDirectory))
   llvm::sys::fs::create_directories(CrashDirectory);
-llvm::sys::path::append(CrashDirectory, Prefix);
+SmallString<128> Path(CrashDirectory);
+llvm::sys::path::append(Path, Prefix);
 const char *Middle = !Suffix.empty() ? "-%%." : "-%%";
-std::error_code EC = llvm::sys::fs::createUniqueFile(
-CrashDirectory + Middle + Suffix, TmpName);
-if (EC) {
+if (std::error_code EC =
+llvm::sys::fs::createUniqueFile(Path + Middle + Suffix, TmpName)) {
   Diag(clang::diag::err_unable_to_make_temp) << EC.message();
   return "";
 }
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -137,6 +137,10 @@
 
 New Compiler Flags
 --
+- It's now possible to set the crash diagnostics directory through
+  the environment variable 'CLANG_CRASH_DIAGNOSTICS_DIR'.
+  The '-fcrash-diagnostics-dir' flag takes precedence.
+
 
 Deprecated Compiler Flags
 -


Index: libcxx/utils/ci/buildkite-pipeline.yml
===
--- libcxx/utils/ci/buildkite-pipeline.yml
+++ libcxx/utils/ci/buildkite-pipeline.yml
@@ -369,10 +369,12 @@
 artifact_paths:
   - "**/test-results.xml"
   - "**/*.abilist"
+  - "**/crash_diagnostics/*"
 env:
 CC: "clang-${LLVM_HEAD_VERSION}"
 CXX: "clang++-${LLVM_HEAD_VERSION}"
 LLVM_SYMBOLIZER_PATH: "/usr/bin/llvm-symbolizer-${LLVM_HEAD_VERSION}"
+CLANG_CRASH_DIAGNOSTICS_DIR: "crash_diagnostics"
 agents:
   queue: "libcxx-builders"
   os: "linux"
Index: libcxx/test/libcxx/crash.sh.cpp
===
--- /dev/null
+++ libcxx/test/libcxx/crash.sh.cpp
@@ -0,0 +1,15 @@
+//===--===//
+//
+// Part of 

[PATCH] D133082: WIP: [clang] Implement setting crash_diagnostics_dir through env variable

2022-08-31 Thread Matheus Izvekov via Phabricator via cfe-commits
mizvekov created this revision.
Herald added subscribers: libcxx-commits, cfe-commits, arichardson.
Herald added projects: clang, libc++, All.
Herald added a reviewer: libc++.
mizvekov requested review of this revision.
Herald added a subscriber: MaskRay.

This implements setting the equivalent of `-fcrash-diagnostics-dir`
through the environment variable `CLANG_CRASH_DIAGNOSTICS_DIR`.
If present, the flag still takes precedence.

This helps integration with test frameworks and pipelines.

With this feature, we change the libcxx bootstrapping build
pipeline to produce clang crash reproducers as artifacts.

Signed-off-by: Matheus Izvekov 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D133082

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/crash-diagnostics-dir-3.c
  libcxx/test/libcxx/crash.sh.cpp
  libcxx/utils/ci/buildkite-pipeline.yml


Index: libcxx/utils/ci/buildkite-pipeline.yml
===
--- libcxx/utils/ci/buildkite-pipeline.yml
+++ libcxx/utils/ci/buildkite-pipeline.yml
@@ -369,10 +369,12 @@
 artifact_paths:
   - "**/test-results.xml"
   - "**/*.abilist"
+  - "**/crash_diagnostics/*"
 env:
 CC: "clang-${LLVM_HEAD_VERSION}"
 CXX: "clang++-${LLVM_HEAD_VERSION}"
 LLVM_SYMBOLIZER_PATH: "/usr/bin/llvm-symbolizer-${LLVM_HEAD_VERSION}"
+CLANG_CRASH_DIAGNOSTICS_DIR: "crash_diagnostics"
 agents:
   queue: "libcxx-builders"
   os: "linux"
Index: libcxx/test/libcxx/crash.sh.cpp
===
--- /dev/null
+++ libcxx/test/libcxx/crash.sh.cpp
@@ -0,0 +1,15 @@
+//===--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+// Test that we produce the crash artifacts in the pipeline
+// For exposition only
+// FIXME: Delete this file
+
+// RUN: %{cxx} %{flags} %{compile_flags} -fsyntax-only %s
+
+#pragma clang __debug parser_crash
Index: clang/test/Driver/crash-diagnostics-dir-3.c
===
--- /dev/null
+++ clang/test/Driver/crash-diagnostics-dir-3.c
@@ -0,0 +1,5 @@
+// RUN: rm -rf %t
+// RUN: not env CLANG_CRASH_DIAGNOSTICS_DIR=%t %clang -c %s -o - 2>&1 | 
FileCheck %s
+#pragma clang __debug parser_crash
+// CHECK: Preprocessed source(s) and associated run script(s) are located at:
+// CHECK: diagnostic msg: 
{{.*}}{{/|\\}}crash-diagnostics-dir-3.c.tmp{{(/|\\).*}}.c
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -5422,15 +5422,17 @@
StringRef BoundArch) const {
   SmallString<128> TmpName;
   Arg *A = C.getArgs().getLastArg(options::OPT_fcrash_diagnostics_dir);
-  if (CCGenDiagnostics && A) {
-SmallString<128> CrashDirectory(A->getValue());
+  const char *CrashDirectory = CCGenDiagnostics && A
+   ? A->getValue()
+   : 
std::getenv("CLANG_CRASH_DIAGNOSTICS_DIR");
+  if (CrashDirectory) {
 if (!getVFS().exists(CrashDirectory))
   llvm::sys::fs::create_directories(CrashDirectory);
-llvm::sys::path::append(CrashDirectory, Prefix);
+SmallString<128> Path(CrashDirectory);
+llvm::sys::path::append(Path, Prefix);
 const char *Middle = !Suffix.empty() ? "-%%." : "-%%";
-std::error_code EC = llvm::sys::fs::createUniqueFile(
-CrashDirectory + Middle + Suffix, TmpName);
-if (EC) {
+if (std::error_code EC =
+llvm::sys::fs::createUniqueFile(Path + Middle + Suffix, TmpName)) {
   Diag(clang::diag::err_unable_to_make_temp) << EC.message();
   return "";
 }
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -137,6 +137,10 @@
 
 New Compiler Flags
 --
+- It's now possible to set the crash diagnostics directory through
+  the environment variable 'CLANG_CRASH_DIAGNOSTICS_DIR'.
+  The '-fcrash-diagnostics-dir' flag takes precedence.
+
 
 Deprecated Compiler Flags
 -


Index: libcxx/utils/ci/buildkite-pipeline.yml
===
--- libcxx/utils/ci/buildkite-pipeline.yml
+++ libcxx/utils/ci/buildkite-pipeline.yml
@@ -369,10 +369,12 @@
 artifact_paths:
   - "**/test-results.xml"
   - "**/*.abilist"
+  - "**/crash_diagnostics/*"
 env:
 CC: "clang-${LLVM_HEAD_VERSION}"
 CXX: 

[PATCH] D133052: [clang] Avoid crash when expanding conversion templates in concepts.

2022-08-31 Thread Luke Nihlen via Phabricator via cfe-commits
luken-google added a comment.

In D133052#3762596 , @ychen wrote:

> Like mentioned in 
> https://stackoverflow.com/questions/68853472/is-this-a-bug-in-clangs-c20-concepts-implementation-unnecessary-checking-of,
>  could we not go down the path of considering conversion candidates? It seems 
> that's blessed by the standard.

If I'm understanding the code correctly, the intent of this patch is to 
definitely consider conversion candidates, only to exclude those conversion 
candidates that are templated methods where the From type is the same as the To 
type, which to me mean they are possibly redundant?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133052

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


[PATCH] D132568: [clang][Sema] check default argument promotions for printf

2022-08-31 Thread YingChi Long 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 rGe3bd67eddf65: [clang][Sema] check default argument 
promotions for printf (authored by inclyc).

Changed prior to commit:
  https://reviews.llvm.org/D132568?vs=457153=457157#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132568

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/AST/FormatString.h
  clang/lib/AST/FormatString.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/test/Sema/format-strings-freebsd.c
  clang/test/Sema/format-strings-scanf.c
  clang/test/Sema/format-strings.c
  clang/www/c_status.html

Index: clang/www/c_status.html
===
--- clang/www/c_status.html
+++ clang/www/c_status.html
@@ -819,13 +819,7 @@
 
   Unclear type relationship between a format specifier and its argument
   https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2562.pdf;>N2562
-  
-Partial
-  Clang supports diagnostics checking format specifier validity, but
-  does not yet account for all of the changes in this paper, especially
-  regarding length modifiers like h and hh.
-
-  
+  Clang 16
 
 
 
Index: clang/test/Sema/format-strings.c
===
--- clang/test/Sema/format-strings.c
+++ clang/test/Sema/format-strings.c
@@ -830,3 +830,57 @@
   printf_arg2("foo", "%s string %i\n", "aaa", 123);
   printf_arg2("%s string\n", "foo", "bar"); // expected-warning{{data argument not used by format string}}
 }
+
+void test_promotion(void) {
+  // Default argument promotions for *printf in N2562
+  // https://github.com/llvm/llvm-project/issues/57102
+  // N2562: https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2562.pdf
+  int i;
+  signed char sc;
+  unsigned char uc;
+  char c;
+  short ss;
+  unsigned short us;
+
+  printf("%hhd %hd %d %hhd %hd %d", i, i, i, sc, sc, sc); // no-warning
+  printf("%hhd %hd %d %hhd %hd %d", uc, uc, uc, c, c, c); // no-warning
+
+  // %ld %lld %llx
+  printf("%ld", i); // expected-warning{{format specifies type 'long' but the argument has type 'int'}}
+  printf("%lld", i); // expected-warning{{format specifies type 'long long' but the argument has type 'int'}}
+  printf("%ld", sc); // expected-warning{{format specifies type 'long' but the argument has type 'signed char'}}
+  printf("%lld", sc); // expected-warning{{format specifies type 'long long' but the argument has type 'signed char'}}
+  printf("%ld", uc); // expected-warning{{format specifies type 'long' but the argument has type 'unsigned char'}}
+  printf("%lld", uc); // expected-warning{{format specifies type 'long long' but the argument has type 'unsigned char'}}
+  printf("%llx", i); // expected-warning{{format specifies type 'unsigned long long' but the argument has type 'int'}}
+
+  // ill formed spec for floats
+  printf("%hf", // expected-warning{{length modifier 'h' results in undefined behavior or no effect with 'f' conversion specifier}}
+  sc); // expected-warning{{format specifies type 'double' but the argument has type 'signed char'}}
+
+  // for %hhd and `short` they are compatible by promotions but more likely misuse
+  printf("%hd", ss); // no-warning
+  printf("%hhd", ss); // expected-warning{{format specifies type 'char' but the argument has type 'short'}}
+  printf("%hu", us); // no-warning
+  printf("%hhu", ss); // expected-warning{{format specifies type 'unsigned char' but the argument has type 'short'}}
+
+  // floats & integers are not compatible
+  printf("%f", i); // expected-warning{{format specifies type 'double' but the argument has type 'int'}}
+  printf("%f", sc); // expected-warning{{format specifies type 'double' but the argument has type 'signed char'}}
+  printf("%f", uc); // expected-warning{{format specifies type 'double' but the argument has type 'unsigned char'}}
+  printf("%f", c); // expected-warning{{format specifies type 'double' but the argument has type 'char'}}
+  printf("%f", ss); // expected-warning{{format specifies type 'double' but the argument has type 'short'}}
+  printf("%f", us); // expected-warning{{format specifies type 'double' but the argument has type 'unsigned short'}}
+
+  // character literals
+  // In C language engineering practice, printing a character literal with %hhd or %d is common, but %hd may be misuse.
+  printf("%hhu", 'a'); // no-warning
+  printf("%hhd", 'a'); // no-warning
+  printf("%hd", 'a'); // expected-warning{{format specifies type 'short' but the argument has type 'char'}}
+  printf("%hu", 'a'); // expected-warning{{format specifies type 'unsigned short' but the argument has type 'char'}}
+  printf("%d", 'a'); // no-warning
+  printf("%u", 'a'); // no-warning
+  
+  // pointers
+  printf("%s", i); // expected-warning{{format 

[clang] e3bd67e - [clang][Sema] check default argument promotions for printf

2022-08-31 Thread YingChi Long via cfe-commits

Author: YingChi Long
Date: 2022-09-01T10:10:10+08:00
New Revision: e3bd67eddf65b20956513e91715b1f997dae2690

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

LOG: [clang][Sema] check default argument promotions for printf

The main focus of this patch is to make ArgType::matchesType check for
possible default parameter promotions when the argType is not a pointer.
If so, no warning will be given for `int`, `unsigned int` types as
corresponding arguments to %hhd and %hd. However, the usage of %hhd
corresponding to short is relatively rare, and it is more likely to be a
misuse. This patch keeps the original behavior of clang like this as
much as possible, while making it more convenient to consider the
default arguments promotion.

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

Reviewed By: aaron.ballman, nickdesaulniers, #clang-language-wg

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

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/AST/FormatString.h
clang/lib/AST/FormatString.cpp
clang/lib/Sema/SemaChecking.cpp
clang/test/Sema/format-strings-freebsd.c
clang/test/Sema/format-strings-scanf.c
clang/test/Sema/format-strings.c
clang/www/c_status.html

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2251993a7c72b..bb7c508001db4 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -175,6 +175,10 @@ AIX Support
 C Language Changes in Clang
 ---
 
+- Adjusted ``-Wformat`` warnings according to `WG14 N2562 
`_.
+  Clang will now consider default argument promotions in printf, and remove 
unnecessary warnings.
+  Especially ``int`` argument with specifier ``%hhd`` and ``%hd``.
+
 C2x Feature Support
 ---
 

diff  --git a/clang/include/clang/AST/FormatString.h 
b/clang/include/clang/AST/FormatString.h
index 0f1f6b1340ff1..a2b8122890b92 100644
--- a/clang/include/clang/AST/FormatString.h
+++ b/clang/include/clang/AST/FormatString.h
@@ -261,8 +261,14 @@ class ArgType {
 /// instance, "%d" and float.
 NoMatch = 0,
 /// The conversion specifier and the argument type are compatible. For
-/// instance, "%d" and _Bool.
+/// instance, "%d" and int.
 Match = 1,
+/// The conversion specifier and the argument type are compatible because 
of
+/// default argument promotions. For instance, "%hhd" and int.
+MatchPromotion,
+/// The conversion specifier and the argument type are compatible but still
+/// seems likely to be an error. For instanace, "%hhd" and short.
+NoMatchPromotionTypeConfusion,
 /// The conversion specifier and the argument type are disallowed by the C
 /// standard, but are in practice harmless. For instance, "%p" and int*.
 NoMatchPedantic,

diff  --git a/clang/lib/AST/FormatString.cpp b/clang/lib/AST/FormatString.cpp
index cf41228ba2f09..83846438a05f5 100644
--- a/clang/lib/AST/FormatString.cpp
+++ b/clang/lib/AST/FormatString.cpp
@@ -348,7 +348,7 @@ ArgType::matchesType(ASTContext , QualType argTy) const {
   return Match;
 
 case AnyCharTy: {
-  if (const EnumType *ETy = argTy->getAs()) {
+  if (const auto *ETy = argTy->getAs()) {
 // If the enum is incomplete we know nothing about the underlying type.
 // Assume that it's 'int'.
 if (!ETy->getDecl()->isComplete())
@@ -356,17 +356,34 @@ ArgType::matchesType(ASTContext , QualType argTy) const 
{
 argTy = ETy->getDecl()->getIntegerType();
   }
 
-  if (const BuiltinType *BT = argTy->getAs())
+  if (const auto *BT = argTy->getAs()) {
+// The types are perfectly matched?
 switch (BT->getKind()) {
+default:
+  break;
+case BuiltinType::Char_S:
+case BuiltinType::SChar:
+case BuiltinType::UChar:
+case BuiltinType::Char_U:
+case BuiltinType::Bool:
+  return Match;
+}
+// "Partially matched" because of promotions?
+if (!Ptr) {
+  switch (BT->getKind()) {
   default:
 break;
-  case BuiltinType::Char_S:
-  case BuiltinType::SChar:
-  case BuiltinType::UChar:
-  case BuiltinType::Char_U:
-  case BuiltinType::Bool:
-return Match;
+  case BuiltinType::Int:
+  case BuiltinType::UInt:
+return MatchPromotion;
+  case BuiltinType::Short:
+  case BuiltinType::UShort:
+  case BuiltinType::WChar_S:
+  case BuiltinType::WChar_U:
+return NoMatchPromotionTypeConfusion;
+  }
 }
+  }
   return NoMatch;
 }
 
@@ -383,8 

[PATCH] D132568: [clang][Sema] check default argument promotions for printf

2022-08-31 Thread YingChi Long via Phabricator via cfe-commits
inclyc updated this revision to Diff 457153.
inclyc added a comment.

Update comments according to review feedback


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132568

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/AST/FormatString.h
  clang/lib/AST/FormatString.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/test/Sema/format-strings-freebsd.c
  clang/test/Sema/format-strings-scanf.c
  clang/test/Sema/format-strings.c
  clang/www/c_status.html

Index: clang/www/c_status.html
===
--- clang/www/c_status.html
+++ clang/www/c_status.html
@@ -819,13 +819,7 @@
 
   Unclear type relationship between a format specifier and its argument
   https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2562.pdf;>N2562
-  
-Partial
-  Clang supports diagnostics checking format specifier validity, but
-  does not yet account for all of the changes in this paper, especially
-  regarding length modifiers like h and hh.
-
-  
+  Clang 16
 
 
 
Index: clang/test/Sema/format-strings.c
===
--- clang/test/Sema/format-strings.c
+++ clang/test/Sema/format-strings.c
@@ -830,3 +830,57 @@
   printf_arg2("foo", "%s string %i\n", "aaa", 123);
   printf_arg2("%s string\n", "foo", "bar"); // expected-warning{{data argument not used by format string}}
 }
+
+void test_promotion(void) {
+  // Default argument promotions for *printf in N2562
+  // https://github.com/llvm/llvm-project/issues/57102
+  // N2562: https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2562.pdf
+  int i;
+  signed char sc;
+  unsigned char uc;
+  char c;
+  short ss;
+  unsigned short us;
+
+  printf("%hhd %hd %d %hhd %hd %d", i, i, i, sc, sc, sc); // no-warning
+  printf("%hhd %hd %d %hhd %hd %d", uc, uc, uc, c, c, c); // no-warning
+
+  // %ld %lld %llx
+  printf("%ld", i); // expected-warning{{format specifies type 'long' but the argument has type 'int'}}
+  printf("%lld", i); // expected-warning{{format specifies type 'long long' but the argument has type 'int'}}
+  printf("%ld", sc); // expected-warning{{format specifies type 'long' but the argument has type 'signed char'}}
+  printf("%lld", sc); // expected-warning{{format specifies type 'long long' but the argument has type 'signed char'}}
+  printf("%ld", uc); // expected-warning{{format specifies type 'long' but the argument has type 'unsigned char'}}
+  printf("%lld", uc); // expected-warning{{format specifies type 'long long' but the argument has type 'unsigned char'}}
+  printf("%llx", i); // expected-warning{{format specifies type 'unsigned long long' but the argument has type 'int'}}
+
+  // ill formed spec for floats
+  printf("%hf", // expected-warning{{length modifier 'h' results in undefined behavior or no effect with 'f' conversion specifier}}
+  sc); // expected-warning{{format specifies type 'double' but the argument has type 'signed char'}}
+
+  // for %hhd and `short` they are compatible by promotions but more likely misuse
+  printf("%hd", ss); // no-warning
+  printf("%hhd", ss); // expected-warning{{format specifies type 'char' but the argument has type 'short'}}
+  printf("%hu", us); // no-warning
+  printf("%hhu", ss); // expected-warning{{format specifies type 'unsigned char' but the argument has type 'short'}}
+
+  // floats & integers are not compatible
+  printf("%f", i); // expected-warning{{format specifies type 'double' but the argument has type 'int'}}
+  printf("%f", sc); // expected-warning{{format specifies type 'double' but the argument has type 'signed char'}}
+  printf("%f", uc); // expected-warning{{format specifies type 'double' but the argument has type 'unsigned char'}}
+  printf("%f", c); // expected-warning{{format specifies type 'double' but the argument has type 'char'}}
+  printf("%f", ss); // expected-warning{{format specifies type 'double' but the argument has type 'short'}}
+  printf("%f", us); // expected-warning{{format specifies type 'double' but the argument has type 'unsigned short'}}
+
+  // character literals
+  // In C language engineering practice, printing a character literal with %hhd or %d is common, but %hd may be misuse.
+  printf("%hhu", 'a'); // no-warning
+  printf("%hhd", 'a'); // no-warning
+  printf("%hd", 'a'); // expected-warning{{format specifies type 'short' but the argument has type 'char'}}
+  printf("%hu", 'a'); // expected-warning{{format specifies type 'unsigned short' but the argument has type 'char'}}
+  printf("%d", 'a'); // no-warning
+  printf("%u", 'a'); // no-warning
+  
+  // pointers
+  printf("%s", i); // expected-warning{{format specifies type 'char *' but the argument has type 'int'}}
+}
Index: clang/test/Sema/format-strings-scanf.c
===
--- 

[PATCH] D132636: [X86][bugfix] redefine __SSC_MARK to escape cpp string literal concatenation problem

2022-08-31 Thread Xiang Zhang via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG2da0df5e7cac: [X86][bugfix] redefine __SSC_MARK to escape 
cpp string literal concatenation… (authored by xiangzhangllvm).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132636

Files:
  clang/lib/Headers/x86gprintrin.h


Index: clang/lib/Headers/x86gprintrin.h
===
--- clang/lib/Headers/x86gprintrin.h
+++ clang/lib/Headers/x86gprintrin.h
@@ -26,22 +26,19 @@
 #endif
 
 #if defined(__i386__)
-#define __FULLBX "ebx"
+#define __SAVE_GPRBX "mov {%%ebx, %%eax |eax, ebx};"
+#define __RESTORE_GPRBX "mov {%%eax, %%ebx |ebx, eax};"
 #define __TMPGPR "eax"
 #else
 // When in 64-bit target, the 32-bit operands generate a 32-bit result,
 // zero-extended to a 64-bit result in the destination general-purpose,
 // It means "mov x %ebx" will clobber the higher 32 bits of rbx, so we
 // should preserve the 64-bit register rbx.
-#define __FULLBX "rbx"
+#define __SAVE_GPRBX "mov {%%rbx, %%rax |rax, rbx};"
+#define __RESTORE_GPRBX "mov {%%rax, %%rbx |rbx, rax};"
 #define __TMPGPR "rax"
 #endif
 
-#define __MOVEGPR(__r1, __r2) "mov {%%"__r1 ", %%"__r2 "|"__r2 ", "__r1"};"
-
-#define __SAVE_GPRBX __MOVEGPR(__FULLBX, __TMPGPR)
-#define __RESTORE_GPRBX __MOVEGPR(__TMPGPR, __FULLBX)
-
 #define __SSC_MARK(__Tag)  
\
   __asm__ __volatile__( __SAVE_GPRBX   
\
"mov {%0, %%ebx|ebx, %0}; " 
\


Index: clang/lib/Headers/x86gprintrin.h
===
--- clang/lib/Headers/x86gprintrin.h
+++ clang/lib/Headers/x86gprintrin.h
@@ -26,22 +26,19 @@
 #endif
 
 #if defined(__i386__)
-#define __FULLBX "ebx"
+#define __SAVE_GPRBX "mov {%%ebx, %%eax |eax, ebx};"
+#define __RESTORE_GPRBX "mov {%%eax, %%ebx |ebx, eax};"
 #define __TMPGPR "eax"
 #else
 // When in 64-bit target, the 32-bit operands generate a 32-bit result,
 // zero-extended to a 64-bit result in the destination general-purpose,
 // It means "mov x %ebx" will clobber the higher 32 bits of rbx, so we
 // should preserve the 64-bit register rbx.
-#define __FULLBX "rbx"
+#define __SAVE_GPRBX "mov {%%rbx, %%rax |rax, rbx};"
+#define __RESTORE_GPRBX "mov {%%rax, %%rbx |rbx, rax};"
 #define __TMPGPR "rax"
 #endif
 
-#define __MOVEGPR(__r1, __r2) "mov {%%"__r1 ", %%"__r2 "|"__r2 ", "__r1"};"
-
-#define __SAVE_GPRBX __MOVEGPR(__FULLBX, __TMPGPR)
-#define __RESTORE_GPRBX __MOVEGPR(__TMPGPR, __FULLBX)
-
 #define __SSC_MARK(__Tag)  \
   __asm__ __volatile__( __SAVE_GPRBX   \
"mov {%0, %%ebx|ebx, %0}; " \
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 2da0df5 - [X86][bugfix] redefine __SSC_MARK to escape cpp string literal concatenation problem

2022-08-31 Thread Xiang1 Zhang via cfe-commits

Author: Xiang1 Zhang
Date: 2022-09-01T09:37:23+08:00
New Revision: 2da0df5e7cac2d06e0632522a3451e3a2dbd1a37

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

LOG: [X86][bugfix] redefine __SSC_MARK to escape cpp string literal 
concatenation problem

Reviewed By: pengfei, RKSimon

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

Added: 


Modified: 
clang/lib/Headers/x86gprintrin.h

Removed: 




diff  --git a/clang/lib/Headers/x86gprintrin.h 
b/clang/lib/Headers/x86gprintrin.h
index 2c2fbb97c9ac8..81d736086cf5d 100644
--- a/clang/lib/Headers/x86gprintrin.h
+++ b/clang/lib/Headers/x86gprintrin.h
@@ -26,22 +26,19 @@
 #endif
 
 #if defined(__i386__)
-#define __FULLBX "ebx"
+#define __SAVE_GPRBX "mov {%%ebx, %%eax |eax, ebx};"
+#define __RESTORE_GPRBX "mov {%%eax, %%ebx |ebx, eax};"
 #define __TMPGPR "eax"
 #else
 // When in 64-bit target, the 32-bit operands generate a 32-bit result,
 // zero-extended to a 64-bit result in the destination general-purpose,
 // It means "mov x %ebx" will clobber the higher 32 bits of rbx, so we
 // should preserve the 64-bit register rbx.
-#define __FULLBX "rbx"
+#define __SAVE_GPRBX "mov {%%rbx, %%rax |rax, rbx};"
+#define __RESTORE_GPRBX "mov {%%rax, %%rbx |rbx, rax};"
 #define __TMPGPR "rax"
 #endif
 
-#define __MOVEGPR(__r1, __r2) "mov {%%"__r1 ", %%"__r2 "|"__r2 ", "__r1"};"
-
-#define __SAVE_GPRBX __MOVEGPR(__FULLBX, __TMPGPR)
-#define __RESTORE_GPRBX __MOVEGPR(__TMPGPR, __FULLBX)
-
 #define __SSC_MARK(__Tag)  
\
   __asm__ __volatile__( __SAVE_GPRBX   
\
"mov {%0, %%ebx|ebx, %0}; " 
\



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


[clang] 58a4b4f - [Driver][test] Fix incorrect -arch= -amx-int8

2022-08-31 Thread Fangrui Song via cfe-commits

Author: Fangrui Song
Date: 2022-08-31T18:13:16-07:00
New Revision: 58a4b4fcebf45eecafab00d006de019d76f828d8

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

LOG: [Driver][test] Fix incorrect -arch= -amx-int8

This is not a driver option. It happens to work because of an ignored Joined -a.

Added: 


Modified: 
clang/test/Driver/darwin-version.c
clang/test/Preprocessor/x86_amx_target_features.c

Removed: 




diff  --git a/clang/test/Driver/darwin-version.c 
b/clang/test/Driver/darwin-version.c
index 82c6fbe556b49..db6a81cd65424 100644
--- a/clang/test/Driver/darwin-version.c
+++ b/clang/test/Driver/darwin-version.c
@@ -309,7 +309,7 @@
 
 // Target with OS version is not overridden by arch:
 
-// RUN: %clang -target uknown-apple-macos10.11.2 -arch=armv7k -c %s -### 2>&1 
| \
+// RUN: %clang -target uknown-apple-macos10.11.2 -c %s -### 2>&1 | \
 // RUN:   FileCheck --check-prefix=CHECK-VERSION-TIGNORE-ARCH1 %s
 // CHECK-VERSION-TIGNORE-ARCH1: "unknown-apple-macosx10.11.2"
 

diff  --git a/clang/test/Preprocessor/x86_amx_target_features.c 
b/clang/test/Preprocessor/x86_amx_target_features.c
index 68a3d7f950b10..644f160a0f6c5 100644
--- a/clang/test/Preprocessor/x86_amx_target_features.c
+++ b/clang/test/Preprocessor/x86_amx_target_features.c
@@ -20,7 +20,7 @@
 
 // NOAMX-BF16-NOT: #define __AMXBF16__ 1
 
-// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -amx-bf16 
-mno-amx-tile -x c -E -dM -o - %s | FileCheck  -check-prefix=NOAMX-BF16 %s
+// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mamx-bf16 
-mno-amx-tile -x c -E -dM -o - %s | FileCheck  -check-prefix=NOAMX-BF16 %s
 
 // NOAMX-BF16-NOT: #define __AMXTILE__ 1
 // NOAMX-BF16-NOT: #define __AMXBF16__ 1
@@ -29,7 +29,7 @@
 
 // NOAMX-INT8-NOT: #define __AMXINT8__ 1
 
-// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -amx-int8 
-mno-amx-tile -x c -E -dM -o - %s | FileCheck  -check-prefix=NOAMX-INT8 %s
+// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mamx-int8 
-mno-amx-tile -x c -E -dM -o - %s | FileCheck  -check-prefix=NOAMX-INT8 %s
 
 // NOAMX-INT8-NOT: #define __AMXTILE__ 1
 // NOAMX-INT8-NOT: #define __AMXINT8__ 1



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


[clang] 08d9912 - [Driver] Remove unimplemented Joined -a / --profile-blocks

2022-08-31 Thread Fangrui Song via cfe-commits

Author: Fangrui Song
Date: 2022-08-31T18:13:16-07:00
New Revision: 08d9912d1c599b5d79d4f2cd6f6be2cdb2bbfa83

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

LOG: [Driver] Remove unimplemented Joined -a / --profile-blocks

GCC removed the option on 2010-08-03.
We support a few -a*. Having the Joined -a may make typos unnoticed.

Added: 


Modified: 
clang/include/clang/Driver/Options.td

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 606b1d588955..2aef6d5d9572 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -850,7 +850,6 @@ def ansi : Flag<["-", "--"], "ansi">, 
Group;
 def arch__errors__fatal : Flag<["-"], "arch_errors_fatal">;
 def arch : Separate<["-"], "arch">, Flags<[NoXarchOption]>;
 def arch__only : Separate<["-"], "arch_only">;
-def a : Joined<["-"], "a">;
 def autocomplete : Joined<["--"], "autocomplete=">;
 def bind__at__load : Flag<["-"], "bind_at_load">;
 def bundle__loader : Separate<["-"], "bundle_loader">;
@@ -4364,7 +4363,6 @@ def _print_diagnostic_categories : Flag<["--"], 
"print-diagnostic-categories">;
 def _print_file_name : Separate<["--"], "print-file-name">, 
Alias;
 def _print_missing_file_dependencies : Flag<["--"], 
"print-missing-file-dependencies">, Alias;
 def _print_prog_name : Separate<["--"], "print-prog-name">, 
Alias;
-def _profile_blocks : Flag<["--"], "profile-blocks">, Alias;
 def _profile : Flag<["--"], "profile">, Alias;
 def _resource_EQ : Joined<["--"], "resource=">, Alias;
 def _resource : Separate<["--"], "resource">, Alias;



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


[clang] 23ce683 - [Driver] Remove Joined -Z and err_drv_use_of_Z_option

2022-08-31 Thread Fangrui Song via cfe-commits

Author: Fangrui Song
Date: 2022-08-31T17:58:04-07:00
New Revision: 23ce683eea358f0cf82ef51692bba6c86ffcf4a8

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

LOG: [Driver] Remove Joined -Z and err_drv_use_of_Z_option

This takes a detour to report an error, but we can just remove Joined -Z
which is rejected by GCC.

Added: 


Modified: 
clang/include/clang/Basic/DiagnosticDriverKinds.td
clang/include/clang/Driver/Options.td
clang/lib/Driver/Driver.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index 2f600d28fea0c..63be59082e7e0 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -128,8 +128,6 @@ def err_drv_invalid_stdlib_name : Error<
 def err_drv_invalid_output_with_multiple_archs : Error<
   "cannot use '%0' output with multiple -arch options">;
 def err_drv_no_input_files : Error<"no input files">;
-def err_drv_use_of_Z_option : Error<
-  "unsupported use of internal gcc -Z option '%0'">;
 def err_drv_output_argument_with_multiple_files : Error<
   "cannot specify -o when generating multiple output files">;
 def err_drv_out_file_argument_with_multiple_sources : Error<

diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 0967fea650e41..606b1d588955a 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -844,8 +844,6 @@ def Xpreprocessor : Separate<["-"], "Xpreprocessor">, 
Group,
   HelpText<"Pass  to the preprocessor">, MetaVarName<"">;
 def X_Flag : Flag<["-"], "X">, Group;
 def Z_Flag : Flag<["-"], "Z">, Group;
-// FIXME: All we do with this is reject it. Remove.
-def Z_Joined : Joined<["-"], "Z">;
 def all__load : Flag<["-"], "all_load">;
 def allowable__client : Separate<["-"], "allowable_client">;
 def ansi : Flag<["-", "--"], "ansi">, Group;

diff  --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index db6e4898ed551..ac8aa8ac8f707 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -3869,11 +3869,6 @@ void Driver::BuildActions(Compilation , DerivedArgList 
,
 return;
   }
 
-  // Reject -Z* at the top level, these options should never have been exposed
-  // by gcc.
-  if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
-Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
-
   // Diagnose misuse of /Fo.
   if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
 StringRef V = A->getValue();



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


[clang] 98615fd - [Driver] Remove Joined -X

2022-08-31 Thread Fangrui Song via cfe-commits

Author: Fangrui Song
Date: 2022-08-31T17:30:51-07:00
New Revision: 98615fd376cea15af21e120e0e3ffa5ba68c2b6d

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

LOG: [Driver] Remove Joined -X

The untested option triggers an IgnoredGCCCompat warning while GCC reports an 
error.
We support a few -X{assembler,linker,...}. Having the Joined -X may make typos 
unnoticed.

Added: 


Modified: 
clang/include/clang/Driver/Options.td

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 2b284b405e61c..0967fea650e41 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -843,7 +843,6 @@ def Xoffload_linker : JoinedAndSeparate<["-"], 
"Xoffload-linker">,
 def Xpreprocessor : Separate<["-"], "Xpreprocessor">, 
Group,
   HelpText<"Pass  to the preprocessor">, MetaVarName<"">;
 def X_Flag : Flag<["-"], "X">, Group;
-def X_Joined : Joined<["-"], "X">, IgnoredGCCCompat;
 def Z_Flag : Flag<["-"], "Z">, Group;
 // FIXME: All we do with this is reject it. Remove.
 def Z_Joined : Joined<["-"], "Z">;



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


[PATCH] D132550: Changes to code ownership in clang and clang-tidy

2022-08-31 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh accepted this revision.
alexfh added a comment.

LGTM. Thanks for driving this!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132550

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


[PATCH] D132998: [clang-tidy] Restrict use-equals-default to c++11-or-later

2022-08-31 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh accepted this revision.
alexfh added a comment.
This revision is now accepted and ready to land.

In D132998#3762578 , 
@alexander-shaposhnikov wrote:

> Regarding the practical side - yeah, I've come across this issue (and others) 
> while trying to run this check over a few large codebases (including Chrome 
> and LLVM),
> and this particular issue accounts for a few hundreds of build breakages.

Then I would be in favor of this change. The only downside I see is that it 
will require first ensuring the project compiles in C++11 or later. This 
doesn't look like a major inconvenience to me (unlike modernize-use-nullptr, 
for example).

Looks good!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132998

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


[PATCH] D133009: [libclang] Fix conversion from `StringRef` to `CXString`

2022-08-31 Thread Aaron Puchert via Phabricator via cfe-commits
aaronpuchert added inline comments.



Comment at: clang/test/Index/comment-lots-of-unknown-commands.c:3
 
+// XFAIL: *
+

egorzhdan wrote:
> gribozavr2 wrote:
> > egorzhdan wrote:
> > > This test was never properly passing. Because of the bug in string 
> > > conversion, the printed comments contained the entire source file and not 
> > > just the comments' text, which was enough to cause `// CHECK`-s in the 
> > > test to succeed.
> > > ```
> > > // CHECK: (CXComment_InlineCommand CommandName=[tel] RenderNormal 
> > > HasTrailingNewline)
> > > // CHECK: (CXComment_InlineCommand CommandName=[n] RenderNormal 
> > > HasTrailingNewline))
> > > // CHECK:   (CXComment_VerbatimLine 
> > > Text=[\n@Lo\n@il\n@tle\n@axt\n@ba\n@ust\n@ac\n@tpe\n@tpl\n@ctG\n@ru\n@m\n@tG\n@it\n@rh\n@G\n@rpc\n@el\n@er\n@w\n@eo\n@tx\n@oo\n@dD\n@dD\n*/\nvoid
> > >  f();\n\n// CHECK:  CommentAST=[\n// CHECK:(CXComment_FullComment\n// 
> > > CHECK:   (CXComment_Paragraph\n// CHECK:  ...
> > > ```
> > Please update the test to pass then. Here's the diff:
> > 
> > ```
> > diff --git a/clang/test/Index/comment-lots-of-unknown-commands.c 
> > b/clang/test/Index/comment-lots-of-unknown-commands.c
> > index 41a03d394488..e1adcc150b1e 100644
> > --- a/clang/test/Index/comment-lots-of-unknown-commands.c
> > +++ b/clang/test/Index/comment-lots-of-unknown-commands.c
> > @@ -1,6 +1,5 @@
> >  // RUN: c-index-test -test-load-source-reparse 1 local %s | FileCheck %s
> > 
> > -// XFAIL: *
> > 
> >  // See PR 21254. We had too few bits to encode command IDs so if you 
> > created
> >  // enough of them the ID codes would wrap around. This test creates 
> > commands up
> > @@ -183,7 +182,7 @@ void f();
> >  // CHECK: (CXComment_InlineCommand CommandName=[ei] RenderNormal 
> > HasTrailingNewline)
> >  // CHECK: (CXComment_InlineCommand CommandName=[oun] RenderNormal 
> > HasTrailingNewline)
> >  // CHECK: (CXComment_InlineCommand CommandName=[ou] RenderNormal 
> > HasTrailingNewline)
> > -// CHECK: (CXComment_InlineCommand CommandName=[nl] RenderNormal 
> > HasTrailingNewline)
> > +// CHECK: (CXComment_InlineCommand CommandName=[n] RenderNormal 
> > HasTrailingNewline)
> >  // CHECK: (CXComment_InlineCommand CommandName=[ien] RenderNormal 
> > HasTrailingNewline)
> >  // CHECK: (CXComment_InlineCommand CommandName=[fr] RenderNormal 
> > HasTrailingNewline)
> >  // CHECK: (CXComment_InlineCommand CommandName=[en] RenderNormal 
> > HasTrailingNewline)
> > @@ -204,7 +203,7 @@ void f();
> >  // CHECK: (CXComment_InlineCommand CommandName=[fro] RenderNormal 
> > HasTrailingNewline)
> >  // CHECK: (CXComment_InlineCommand CommandName=[ast] RenderNormal 
> > HasTrailingNewline)
> >  // CHECK: (CXComment_InlineCommand CommandName=[ae] RenderNormal 
> > HasTrailingNewline)
> > -// CHECK: (CXComment_InlineCommand CommandName=[nN] RenderNormal 
> > HasTrailingNewline)
> > +// CHECK: (CXComment_InlineCommand CommandName=[n] RenderNormal 
> > HasTrailingNewline)
> >  // CHECK: (CXComment_InlineCommand CommandName=[pc] RenderNormal 
> > HasTrailingNewline)
> >  // CHECK: (CXComment_InlineCommand CommandName=[tae] RenderNormal 
> > HasTrailingNewline)
> >  // CHECK: (CXComment_InlineCommand CommandName=[ws] RenderNormal 
> > HasTrailingNewline)
> > @@ -268,10 +267,8 @@ void f();
> >  // CHECK: (CXComment_InlineCommand CommandName=[an] RenderNormal 
> > HasTrailingNewline)
> >  // CHECK: (CXComment_InlineCommand CommandName=[de] RenderNormal 
> > HasTrailingNewline)
> >  // CHECK: (CXComment_InlineCommand CommandName=[tel] RenderNormal 
> > HasTrailingNewline)
> > -// CHECK: (CXComment_InlineCommand CommandName=[nd] RenderNormal 
> > HasTrailingNewline)
> > -// CHECK: (CXComment_InlineCommand CommandName=[dic] RenderNormal 
> > HasTrailingNewline)
> > +// CHECK: (CXComment_InlineCommand CommandName=[n] RenderNormal 
> > HasTrailingNewline)
> >  // CHECK: (CXComment_InlineCommand CommandName=[Lo] RenderNormal 
> > HasTrailingNewline)
> > -// CHECK: (CXComment_InlineCommand CommandName=[il] RenderNormal 
> > HasTrailingNewline)
> >  // CHECK: (CXComment_InlineCommand CommandName=[tle] RenderNormal 
> > HasTrailingNewline)
> >  // CHECK: (CXComment_InlineCommand CommandName=[axt] RenderNormal 
> > HasTrailingNewline)
> >  // CHECK: (CXComment_InlineCommand CommandName=[ba] RenderNormal 
> > HasTrailingNewline)
> > @@ -283,7 +280,6 @@ void f();
> >  // CHECK: (CXComment_InlineCommand CommandName=[ru] RenderNormal 
> > HasTrailingNewline)
> >  // CHECK: (CXComment_InlineCommand CommandName=[m] RenderNormal 
> > HasTrailingNewline)
> >  // CHECK: (CXComment_InlineCommand CommandName=[tG] RenderNormal 
> > HasTrailingNewline)
> > -// CHECK: (CXComment_InlineCommand 

[PATCH] D133072: WIP: [clang] fix profiling of template arguments of template and declaration kind

2022-08-31 Thread Matheus Izvekov via Phabricator via cfe-commits
mizvekov created this revision.
Herald added projects: clang, libc++, All.
Herald added subscribers: libcxx-commits, cfe-commits.
Herald added a reviewer: libc++.
mizvekov requested review of this revision.

Template arguments of template and declaration kind were being profiled
only by their canonical properties, which would cause incorrect
uniquing of constrained AutoTypes, leading to a crash in some cases.

This exposed some places in CheckTemplateArguments where non-canonical
arguments where being pushed into the resulting converted list.

We also throw in some asserts to catch early and explain the crashes.

Note that the fix for the 'declaration' kind is untestable at this point,
because there should be no cases right now in the AST where we try
to unique a non-canonical converted template argument.

This fixes GH55567.

Signed-off-by: Matheus Izvekov 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D133072

Files:
  clang/lib/AST/ASTContext.cpp
  clang/lib/AST/TemplateBase.cpp
  clang/lib/Sema/SemaTemplate.cpp
  clang/test/SemaTemplate/concepts.cpp
  libcxx/DELETE.ME

Index: clang/test/SemaTemplate/concepts.cpp
===
--- clang/test/SemaTemplate/concepts.cpp
+++ clang/test/SemaTemplate/concepts.cpp
@@ -256,3 +256,9 @@
 C auto ** = g();  // expected-error {{deduced type 'int' does not satisfy 'C'}}
 C auto **& = g(); // expected-error {{deduced type 'int' does not satisfy 'C'}}
 }
+
+namespace GH55567 {
+template class> concept C = true;
+template  struct S {};
+void f(C auto);
+} // namespace GH55567
Index: clang/lib/Sema/SemaTemplate.cpp
===
--- clang/lib/Sema/SemaTemplate.cpp
+++ clang/lib/Sema/SemaTemplate.cpp
@@ -5643,7 +5643,8 @@
 if (CheckTemplateTemplateArgument(TempParm, Params, Arg))
   return true;
 
-Converted.push_back(Arg.getArgument());
+Converted.push_back(
+Context.getCanonicalTemplateArgument(Arg.getArgument()));
 break;
 
   case TemplateArgument::Expression:
@@ -5813,13 +5814,14 @@
 if (!ArgumentPack.empty()) {
   // If we were part way through filling in an expanded parameter pack,
   // fall back to just producing individual arguments.
-  Converted.insert(Converted.end(),
-   ArgumentPack.begin(), ArgumentPack.end());
+  for (const TemplateArgument  : ArgumentPack)
+Converted.push_back(Context.getCanonicalTemplateArgument(I));
   ArgumentPack.clear();
 }
 
 while (ArgIdx < NumArgs) {
-  Converted.push_back(NewArgs[ArgIdx].getArgument());
+  Converted.push_back(Context.getCanonicalTemplateArgument(
+  NewArgs[ArgIdx].getArgument()));
   ++ArgIdx;
 }
 
@@ -5952,7 +5954,8 @@
   if (ArgIdx < NumArgs && CurrentInstantiationScope &&
   CurrentInstantiationScope->getPartiallySubstitutedPack()) {
 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
-  Converted.push_back(NewArgs[ArgIdx++].getArgument());
+  Converted.push_back(Context.getCanonicalTemplateArgument(
+  NewArgs[ArgIdx++].getArgument()));
   }
 
   // If we have any leftover arguments, then there were too many arguments.
Index: clang/lib/AST/TemplateBase.cpp
===
--- clang/lib/AST/TemplateBase.cpp
+++ clang/lib/AST/TemplateBase.cpp
@@ -321,26 +321,15 @@
 
   case Declaration:
 getParamTypeForDecl().Profile(ID);
-ID.AddPointer(getAsDecl()? getAsDecl()->getCanonicalDecl() : nullptr);
+ID.AddPointer(getAsDecl());
 break;
 
+  case TemplateExpansion:
+ID.AddInteger(TemplateArg.NumExpansions);
+LLVM_FALLTHROUGH;
   case Template:
-  case TemplateExpansion: {
-TemplateName Template = getAsTemplateOrTemplatePattern();
-if (TemplateTemplateParmDecl *TTP
-  = dyn_cast_or_null(
-Template.getAsTemplateDecl())) {
-  ID.AddBoolean(true);
-  ID.AddInteger(TTP->getDepth());
-  ID.AddInteger(TTP->getPosition());
-  ID.AddBoolean(TTP->isParameterPack());
-} else {
-  ID.AddBoolean(false);
-  ID.AddPointer(Context.getCanonicalTemplateName(Template)
-  .getAsVoidPointer());
-}
+getAsTemplateOrTemplatePattern().Profile(ID);
 break;
-  }
 
   case Integral:
 getAsIntegral().Profile(ID);
Index: clang/lib/AST/ASTContext.cpp
===
--- clang/lib/AST/ASTContext.cpp
+++ clang/lib/AST/ASTContext.cpp
@@ -5116,7 +5116,9 @@
CanonArgs);
 
 // Find the insert position again.
-DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
+[[maybe_unused]] auto *Nothing =
+

[PATCH] D133006: [clang-tidy] Skip copy assignment operators with nonstandard return types

2022-08-31 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh accepted this revision.
alexfh added a comment.
This revision is now accepted and ready to land.

Looks good!


Repository:
  rL LLVM

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

https://reviews.llvm.org/D133006

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


[PATCH] D133066: fix a typo in comment of AddConversionCandidate

2022-08-31 Thread zhouyizhou via Phabricator via cfe-commits
zhouyizhou created this revision.
zhouyizhou added reviewers: MikeStump, riccibruno, rsmith.
Herald added a project: All.
zhouyizhou requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Hi 
I think the comment above the condition expression ICS.Standard.First == 
ICK_Lvalue_To_Rvalue should be:

//In the second case, if the reference is an rvalue reference and   
  
//the first standard conversion sequence of the user-defined
  
//conversion sequence includes an lvalue-to-rvalue conversion, the  
  
 //program is ill-formed.

Many thanks
Zhouyi Zhou 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D133066

Files:
  clang/lib/Sema/SemaOverload.cpp


Index: clang/lib/Sema/SemaOverload.cpp
===
--- clang/lib/Sema/SemaOverload.cpp
+++ clang/lib/Sema/SemaOverload.cpp
@@ -7495,7 +7495,7 @@
 
 // C++0x [dcl.init.ref]p5:
 //In the second case, if the reference is an rvalue reference and
-//the second standard conversion sequence of the user-defined
+//the first standard conversion sequence of the user-defined
 //conversion sequence includes an lvalue-to-rvalue conversion, the
 //program is ill-formed.
 if (ToType->isRValueReferenceType() &&


Index: clang/lib/Sema/SemaOverload.cpp
===
--- clang/lib/Sema/SemaOverload.cpp
+++ clang/lib/Sema/SemaOverload.cpp
@@ -7495,7 +7495,7 @@
 
 // C++0x [dcl.init.ref]p5:
 //In the second case, if the reference is an rvalue reference and
-//the second standard conversion sequence of the user-defined
+//the first standard conversion sequence of the user-defined
 //conversion sequence includes an lvalue-to-rvalue conversion, the
 //program is ill-formed.
 if (ToType->isRValueReferenceType() &&
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D133052: [clang] Avoid crash when expanding conversion templates in concepts.

2022-08-31 Thread Yuanfang Chen via Phabricator via cfe-commits
ychen added a comment.

Like mentioned in 
https://stackoverflow.com/questions/68853472/is-this-a-bug-in-clangs-c20-concepts-implementation-unnecessary-checking-of,
 could we not go down the path of considering conversion candidates? It seems 
that's blessed by the standard.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133052

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


[PATCH] D132998: [clang-tidy] Restrict use-equals-default to c++11-or-later

2022-08-31 Thread Alexander Shaposhnikov via Phabricator via cfe-commits
alexander-shaposhnikov added a comment.

Regarding the practical side - yeah, I've come across this issue (and others) 
while trying to run this check over a few large codebases (including LLVM and 
Chrome),
and this particular issue accounts of a few hundreds of build breakages.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132998

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


[PATCH] D129488: [Sema] Delay evaluation of std::source_location::current() in default arguments

2022-08-31 Thread James Y Knight via Phabricator via cfe-commits
jyknight added a comment.

In D129488#3761478 , @ilya-biryukov 
wrote:

> In D129488#3761398 , @jyknight 
> wrote:
>
>> I believe this should print `fn=14 fn2=14`. I don't see how we can get that 
>> by special-casing calls to `std::source_location::current`, and indeed, with 
>> this version of the patch, the program instead prints `fn=14 fn2=9`.
>
> There is another issue in Clang that prevents it from producing correct 
> results with this patch. We should not evaluate immediate calls inside 
> default arguments of immediate function parameters as they are deemed to be 
> inside the immediate function context 
> . Clang currently evaluates these 
> calls as all parameter scopes are `PotentiallyEvaluatedIfUsed` and 
> `ImmediateFunctionContext` is a different value inside the same enumeration :)

OK...So...

If the correct rule is that consteval functions must be immediately evaluated 
even when used in a default arg of a non-consteval function (rather than 
deferring evaluation to the callsite, as would otherwise be the rule for 
default args!), then GCC's behavior for "fn3" in your example 
https://gcc.godbolt.org/z/P1x8PGsh6 makes sense. And, yea, also Clang's 
_current_ behavior for `current()` makes sense! Because `current` is not 
actually generating the source location itself -- the //actual// source 
location is coming from a builtin call in a default arg of `current()`...it's 
only a wrapper, just like `fn()` is a wrapper around `current()`.

But, "makes sense" (from implementation point of view) doesn't mean 
"useful"...which is why you're adding a special case for it. And why GCC also 
did.

This is really quite awful.

The more I look at this, the more I feel like, if all the above behaviors are 
correct, source_location::current() simply shouldn't be marked consteval at 
all. If it was constexpr, instead, it'd work great _without_ needing any 
special-casing, because the "must evaluate immediately upon seeing function 
definition even in default arg position" wouldn't apply to it. And that's the 
behavior we //want// from it!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129488

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


[PATCH] D132975: [clang][BOLT] Add clang-bolt target (WIP)

2022-08-31 Thread Amir Ayupov via Phabricator via cfe-commits
Amir updated this revision to Diff 457102.
Amir added a comment.

Succeeded instrumenting Clang with BOLT


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132975

Files:
  clang/CMakeLists.txt
  clang/cmake/caches/BOLT.cmake

Index: clang/cmake/caches/BOLT.cmake
===
--- /dev/null
+++ clang/cmake/caches/BOLT.cmake
@@ -0,0 +1,14 @@
+set(CMAKE_BUILD_TYPE Release CACHE STRING "")
+set(CLANG_BOLT_INSTRUMENT ON CACHE BOOL "")
+set(CLANG_BOLT_INSTRUMENT_PROJECTS "lld" CACHE STRING "")
+set(CLANG_BOLT_INSTRUMENT_TARGETS "lld" CACHE STRING "")
+set(CMAKE_EXE_LINKER_FLAGS "-Wl,--emit-relocs,-znow" CACHE STRING "")
+
+set(LLVM_ENABLE_PROJECTS "bolt;clang;lld" CACHE STRING "")
+set(LLVM_TARGETS_TO_BUILD Native CACHE STRING "")
+
+# Disable function splitting enabled by default in GCC8+
+if("${CMAKE_CXX_COMPILER_ID}" MATCHES "GNU")
+  set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fno-reorder-blocks-and-partition")
+  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-reorder-blocks-and-partition")
+endif()
Index: clang/CMakeLists.txt
===
--- clang/CMakeLists.txt
+++ clang/CMakeLists.txt
@@ -443,7 +443,7 @@
   "HAVE_CLANG_PLUGIN_SUPPORT" OFF)
 
 # If libstdc++ is statically linked, clang-repl needs to statically link libstdc++
-# itself, which is not possible in many platforms because of current limitations in 
+# itself, which is not possible in many platforms because of current limitations in
 # JIT stack. (more platforms need to be supported by JITLink)
 if(NOT LLVM_STATIC_LINK_CXX_STDLIB)
   set(HAVE_CLANG_REPL_SUPPORT ON)
@@ -878,6 +878,97 @@
   endforeach()
 endif()
 
+if (CLANG_BOLT_INSTRUMENT)
+  set(C_COMPILER "clang.bolt.inst")
+  set(CXX_COMPILER "clang++.bolt.inst")
+  set(C_COMPILER_PATH ${CMAKE_CURRENT_BINARY_DIR}/${C_COMPILER})
+  set(CXX_COMPILER_PATH ${CMAKE_CURRENT_BINARY_DIR}/${CXX_COMPILER})
+
+  # Instrument clang with BOLT
+  add_custom_target(clang-instrumented
+DEPENDS ${C_COMPILER_PATH}
+  )
+  add_custom_command(OUTPUT ${C_COMPILER_PATH}
+DEPENDS clang llvm-bolt
+COMMAND llvm-bolt $ -o ${C_COMPILER_PATH}
+  -instrument --instrumentation-file-append-pid
+  --instrumentation-file=${CMAKE_CURRENT_BINARY_DIR}/prof.fdata
+COMMENT "Instrumenting clang binary with BOLT"
+VERBATIM
+  )
+
+  # Make a symlink from ${C_COMPILER} to ${CXX_COMPILER}
+  add_custom_target(clang++-instrumented
+DEPENDS ${CXX_COMPILER_PATH}
+  )
+  add_custom_command(OUTPUT ${CXX_COMPILER_PATH}
+DEPENDS clang-instrumented
+COMMAND ${CMAKE_COMMAND} -E create_symlink
+  ${C_COMPILER_PATH}
+  ${CXX_COMPILER_PATH}
+COMMENT "Creating a symlink from BOLT instrumented clang to clang++"
+VERBATIM
+  )
+
+  # Configure and build Clang with instrumented Clang to collect the profile
+  set(STAMP_DIR ${CMAKE_CURRENT_BINARY_DIR}/bolt-instrumented-clang-stamps/)
+  set(BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR}/bolt-instrumented-clang-bins/)
+  set(build_configuration "$")
+  include(ExternalProject)
+  ExternalProject_Add(bolt-instrumentation-profile
+DEPENDS clang-instrumented clang++-instrumented
+PREFIX bolt-instrumentation-profile
+SOURCE_DIR ${CMAKE_SOURCE_DIR}
+STAMP_DIR ${STAMP_DIR}
+BINARY_DIR ${BINARY_DIR}
+EXCLUDE_FROM_ALL 1
+CMAKE_ARGS
+# We shouldn't need to set this here, but INSTALL_DIR doesn't
+# seem to work, so instead I'm passing this through
+-DCMAKE_INSTALL_PREFIX=${CMAKE_INSTALL_PREFIX}
+-DCMAKE_C_COMPILER=${C_COMPILER_PATH}
+-DCMAKE_CXX_COMPILER=${CXX_COMPILER_PATH}
+-DCMAKE_ASM_COMPILER=${C_COMPILER_PATH}
+-DCMAKE_ASM_COMPILER_ID=Clang
+-DCMAKE_BUILD_TYPE=Release
+-DLLVM_ENABLE_PROJECTS=${CLANG_BOLT_INSTRUMENT_PROJECTS}
+BUILD_COMMAND ${CMAKE_COMMAND} --build ${BINARY_DIR}
+   --config ${build_configuration}
+   --target ${CLANG_BOLT_INSTRUMENT_TARGETS}
+INSTALL_COMMAND ""
+STEP_TARGETS configure build
+USES_TERMINAL_CONFIGURE 1
+USES_TERMINAL_BUILD 1
+USES_TERMINAL_INSTALL 1
+LIST_SEPARATOR |
+  )
+
+  # Merge profiles into one using merge-fdata
+  add_custom_target(clang-bolt-profile
+DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/prof.fdata
+  )
+  add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/prof.fdata
+DEPENDS merge-fdata bolt-instrumentation-profile-build
+COMMAND merge-fdata ${CMAKE_CURRENT_BINARY_DIR}/prof.fdata.*
+  -o ${CMAKE_CURRENT_BINARY_DIR}/prof.fdata
+COMMENT "Preparing BOLT profile"
+VERBATIM
+  )
+
+  # Optimize original (pre-bolt) Clang using the collected profile
+  add_custom_target(clang-bolt
+DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/clang.bolt
+  )
+  

[PATCH] D102107: [OpenMP] Codegen aggregate for outlined function captures

2022-08-31 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert accepted this revision.
jdoerfert added a comment.

LG, the new remarks need to be addressed in a follow up. Please test for them 
and make a TODO that they should be optimized away.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D102107

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


[PATCH] D133052: [clang] Avoid crash when expanding conversion templates in concepts.

2022-08-31 Thread Luke Nihlen via Phabricator via cfe-commits
luken-google added a reviewer: ilya-biryukov.
luken-google added a comment.

I'm open to other suggestions if this doesn't seem like the right approach. The 
problem is the concept evaluation code is fairly separated in the call stack 
from this Sema code, so it's hard to think of a minimal change to the Sema code 
that doesn't break other parts of the language standard.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133052

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


[PATCH] D132421: [HLSL] Support PCH for cc1 mode

2022-08-31 Thread Chris Bieneman via Phabricator via cfe-commits
beanz added inline comments.



Comment at: clang/include/clang/Sema/HLSLExternalSemaSource.h:58
+/// them before we initialize the ExternalSemaSource base class.
+struct ChainedHLSLExternalSemaSourceMembers {
+  ChainedHLSLExternalSemaSourceMembers(ExternalSemaSource *ExtSema)

python3kgae wrote:
> beanz wrote:
> > IIUC, this code just exists to make sure that the `ASTReader` deserializes 
> > before the external sema source starts adding things. Is that correct?
> > 
> > If so, you don't need to do this, instead you can just add this code to 
> > `InitializeSema()` to force the `ASTReader` to de-serialize the decls:
> > 
> > ```
> > // If the translation unit has external storage force external decls to 
> > load.
> > if (AST.getTranslationUnitDecl()->hasExternalLexicalStorage())
> > (void)AST.getTranslationUnitDecl()->decls_begin();
> > ```
> Still need this to make sure HLSLSema and ExternalSema are initialized before 
>  MultiplexExternalSemaSource.
In FrontendAction, where you are creating the Chained source, you can instead 
create a Multiplex source, and put the PCH external source in as the first 
source and the HLSL one second. The PCH will get initialized first, the HLSL 
one can force the PCH one to populate the decls.



Comment at: clang/lib/Sema/HLSLExternalSemaSource.cpp:314
+
+  if (!HLSLNamespace) {
+HLSLNamespace = NamespaceDecl::Create(AST, AST.getTranslationUnitDecl(),

Rather than reusing the namespace you can set the PCH one as the previous decl 
for the one you're declaring here. That will result in them basically being 
merged because Namespaces can have multiple decls.

The advantage to this is that the PCH namespace will be marked in the AST as a 
deserialized decl but the HLSL one won't. It will make debugging and AST 
visualization easier.



Comment at: clang/lib/Sema/HLSLExternalSemaSource.cpp:411
+Completions.insert(std::make_pair(
+Decl, std::bind(::completeBufferType, this,
+std::placeholders::_1)));

If the decl you put in here is the canonical decl, and you do the lookup by 
canonical decl. The conflicting decls shouldn't be an issue. That does require 
that you mark the previous decl so that they are known to be the same 
declaration.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132421

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


[PATCH] D116266: [SPIR-V] Add linking of separate translation units using spirv-link

2022-08-31 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added inline comments.
Herald added a subscriber: MaskRay.
Herald added a project: All.



Comment at: clang/docs/UsersManual.rst:3602
 
+Linking is done using ``spirv-link`` from `the SPIRV-Tools project
+`_. Similar to other 
external

bader wrote:
> @Anastasia, sorry for late feedback.
> I think being able to link SPIR-V modules is a great feature, but I have a 
> concerns regarding `spirv-link` tool.
> The documentation says that the linker tool is still under development and 
> from our experience this tool had issues blocking us from using it for SYCL 
> mode. The last time new features were added to this tool is almost 4 year ago.
> Do you know if there are any plans for to finish the development and if ? Are 
> you aware of any "real-world usages" of this tool? Have you tried to use it 
> for SPIR-V module produced from C++ (e.g. C++ for OpenCL)?
> I think supporting SPIR-V extensions like [[ 
> https://github.com/KhronosGroup/SPIRV-Registry/blob/main/extensions/KHR/SPV_KHR_linkonce_odr.asciidoc
>  | SPV_KHR_linkonce_odr ]] is quite important for code size and JIT 
> compilation time reduction. As this extension was ratified recently, I 
> suppose `spirv-link` doesn't support it yet.
Hi Alexey,

Sorry for the late reply. Do you have any other suggestions about the tools 
that can be used for linking SPIR-V binaries? 

I am not in contact with the maintainers but it is an open-source project so I 
imagine contributions to enhance or improve functionality should be welcome... 
unless you have other experiences?



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116266

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


[PATCH] D133052: [clang] Avoid crash when expanding conversion templates in concepts.

2022-08-31 Thread Luke Nihlen via Phabricator via cfe-commits
luken-google updated this revision to Diff 457084.
luken-google added a comment.

Remove extraneous header inclusion.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133052

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


Index: clang/test/SemaTemplate/concepts.cpp
===
--- clang/test/SemaTemplate/concepts.cpp
+++ clang/test/SemaTemplate/concepts.cpp
@@ -256,3 +256,20 @@
 C auto ** = g();  // expected-error {{deduced type 'int' does not satisfy 
'C'}}
 C auto **& = g(); // expected-error {{deduced type 'int' does not satisfy 
'C'}}
 }
+
+namespace Issue50891 {
+
+template 
+concept Numeric =
+requires(T a) {
+foo(a);
+};
+
+struct Deferred {
+friend void foo(Deferred);
+template  operator TO();
+};
+
+static_assert(Numeric); // should not crash clang
+
+} // namespace Issue50891
Index: clang/lib/Sema/SemaInit.cpp
===
--- clang/lib/Sema/SemaInit.cpp
+++ clang/lib/Sema/SemaInit.cpp
@@ -4033,9 +4033,16 @@
 
 FunctionTemplateDecl *ConvTemplate = dyn_cast(D);
 CXXConversionDecl *Conv;
-if (ConvTemplate)
+if (ConvTemplate) {
+  // It is possible with C++20 constraints to cause an infinite 
template
+  // expansion loop. In those instances the conversion operator has the
+  // same specialized template argument type as the destination type,
+  // and we skip it to avoid the crash.
+  if (Initializer->getType().getCanonicalType() ==
+  DestType.getCanonicalType())
+continue;
   Conv = cast(ConvTemplate->getTemplatedDecl());
-else
+} else
   Conv = cast(D);
 
 if (ConvTemplate)
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -210,7 +210,8 @@
   This fixes `GH51182 `
 - Fixes an assert crash caused by looking up missing vtable information on 
``consteval``
   virtual functions. Fixes `GH55065 
`_.
-
+- Fixed a crash during template instantiation on a conversion operator during 
constraint
+  evaulation. Fixes `GH50891 
`_.
 
 C++2b Feature Support
 ^


Index: clang/test/SemaTemplate/concepts.cpp
===
--- clang/test/SemaTemplate/concepts.cpp
+++ clang/test/SemaTemplate/concepts.cpp
@@ -256,3 +256,20 @@
 C auto ** = g();  // expected-error {{deduced type 'int' does not satisfy 'C'}}
 C auto **& = g(); // expected-error {{deduced type 'int' does not satisfy 'C'}}
 }
+
+namespace Issue50891 {
+
+template 
+concept Numeric =
+requires(T a) {
+foo(a);
+};
+
+struct Deferred {
+friend void foo(Deferred);
+template  operator TO();
+};
+
+static_assert(Numeric); // should not crash clang
+
+} // namespace Issue50891
Index: clang/lib/Sema/SemaInit.cpp
===
--- clang/lib/Sema/SemaInit.cpp
+++ clang/lib/Sema/SemaInit.cpp
@@ -4033,9 +4033,16 @@
 
 FunctionTemplateDecl *ConvTemplate = dyn_cast(D);
 CXXConversionDecl *Conv;
-if (ConvTemplate)
+if (ConvTemplate) {
+  // It is possible with C++20 constraints to cause an infinite template
+  // expansion loop. In those instances the conversion operator has the
+  // same specialized template argument type as the destination type,
+  // and we skip it to avoid the crash.
+  if (Initializer->getType().getCanonicalType() ==
+  DestType.getCanonicalType())
+continue;
   Conv = cast(ConvTemplate->getTemplatedDecl());
-else
+} else
   Conv = cast(D);
 
 if (ConvTemplate)
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -210,7 +210,8 @@
   This fixes `GH51182 `
 - Fixes an assert crash caused by looking up missing vtable information on ``consteval``
   virtual functions. Fixes `GH55065 `_.
-
+- Fixed a crash during template instantiation on a conversion operator during constraint
+  evaulation. Fixes `GH50891 `_.
 
 C++2b Feature Support
 ^
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D133052: [clang] Avoid crash when expanding conversion templates in concepts.

2022-08-31 Thread Luke Nihlen via Phabricator via cfe-commits
luken-google created this revision.
Herald added a project: All.
luken-google requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

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


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D133052

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


Index: clang/test/SemaTemplate/concepts.cpp
===
--- clang/test/SemaTemplate/concepts.cpp
+++ clang/test/SemaTemplate/concepts.cpp
@@ -256,3 +256,20 @@
 C auto ** = g();  // expected-error {{deduced type 'int' does not satisfy 
'C'}}
 C auto **& = g(); // expected-error {{deduced type 'int' does not satisfy 
'C'}}
 }
+
+namespace Issue50891 {
+
+template 
+concept Numeric =
+requires(T a) {
+foo(a);
+};
+
+struct Deferred {
+friend void foo(Deferred);
+template  operator TO();
+};
+
+static_assert(Numeric); // should not crash clang
+
+} // namespace Issue50891
Index: clang/lib/Sema/SemaInit.cpp
===
--- clang/lib/Sema/SemaInit.cpp
+++ clang/lib/Sema/SemaInit.cpp
@@ -22,6 +22,7 @@
 #include "clang/Sema/Designator.h"
 #include "clang/Sema/Initialization.h"
 #include "clang/Sema/Lookup.h"
+#include "clang/Sema/Overload.h"
 #include "clang/Sema/SemaInternal.h"
 #include "llvm/ADT/APInt.h"
 #include "llvm/ADT/PointerIntPair.h"
@@ -4033,9 +4034,16 @@
 
 FunctionTemplateDecl *ConvTemplate = dyn_cast(D);
 CXXConversionDecl *Conv;
-if (ConvTemplate)
+if (ConvTemplate) {
+  // It is possible with C++20 constraints to cause an infinite 
template
+  // expansion loop. In those instances the conversion operator has the
+  // same specialized template argument type as the destination type,
+  // and we skip it to avoid the crash.
+  if (Initializer->getType().getCanonicalType() ==
+  DestType.getCanonicalType())
+continue;
   Conv = cast(ConvTemplate->getTemplatedDecl());
-else
+} else
   Conv = cast(D);
 
 if (ConvTemplate)
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -210,7 +210,8 @@
   This fixes `GH51182 `
 - Fixes an assert crash caused by looking up missing vtable information on 
``consteval``
   virtual functions. Fixes `GH55065 
`_.
-
+- Fixed a crash during template instantiation on a conversion operator during 
constraint
+  evaulation. Fixes `GH50891 
`_.
 
 C++2b Feature Support
 ^


Index: clang/test/SemaTemplate/concepts.cpp
===
--- clang/test/SemaTemplate/concepts.cpp
+++ clang/test/SemaTemplate/concepts.cpp
@@ -256,3 +256,20 @@
 C auto ** = g();  // expected-error {{deduced type 'int' does not satisfy 'C'}}
 C auto **& = g(); // expected-error {{deduced type 'int' does not satisfy 'C'}}
 }
+
+namespace Issue50891 {
+
+template 
+concept Numeric =
+requires(T a) {
+foo(a);
+};
+
+struct Deferred {
+friend void foo(Deferred);
+template  operator TO();
+};
+
+static_assert(Numeric); // should not crash clang
+
+} // namespace Issue50891
Index: clang/lib/Sema/SemaInit.cpp
===
--- clang/lib/Sema/SemaInit.cpp
+++ clang/lib/Sema/SemaInit.cpp
@@ -22,6 +22,7 @@
 #include "clang/Sema/Designator.h"
 #include "clang/Sema/Initialization.h"
 #include "clang/Sema/Lookup.h"
+#include "clang/Sema/Overload.h"
 #include "clang/Sema/SemaInternal.h"
 #include "llvm/ADT/APInt.h"
 #include "llvm/ADT/PointerIntPair.h"
@@ -4033,9 +4034,16 @@
 
 FunctionTemplateDecl *ConvTemplate = dyn_cast(D);
 CXXConversionDecl *Conv;
-if (ConvTemplate)
+if (ConvTemplate) {
+  // It is possible with C++20 constraints to cause an infinite template
+  // expansion loop. In those instances the conversion operator has the
+  // same specialized template argument type as the destination type,
+  // and we skip it to avoid the crash.
+  if (Initializer->getType().getCanonicalType() ==
+  DestType.getCanonicalType())
+continue;
   Conv = cast(ConvTemplate->getTemplatedDecl());
-else
+} else
   Conv = cast(D);
 
 if (ConvTemplate)
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -210,7 +210,8 @@
   This fixes `GH51182 

[PATCH] D132421: [HLSL] Support PCH for cc1 mode

2022-08-31 Thread Xiang Li via Phabricator via cfe-commits
python3kgae marked an inline comment as done.
python3kgae added inline comments.



Comment at: clang/include/clang/Sema/HLSLExternalSemaSource.h:58
+/// them before we initialize the ExternalSemaSource base class.
+struct ChainedHLSLExternalSemaSourceMembers {
+  ChainedHLSLExternalSemaSourceMembers(ExternalSemaSource *ExtSema)

beanz wrote:
> IIUC, this code just exists to make sure that the `ASTReader` deserializes 
> before the external sema source starts adding things. Is that correct?
> 
> If so, you don't need to do this, instead you can just add this code to 
> `InitializeSema()` to force the `ASTReader` to de-serialize the decls:
> 
> ```
> // If the translation unit has external storage force external decls to load.
> if (AST.getTranslationUnitDecl()->hasExternalLexicalStorage())
> (void)AST.getTranslationUnitDecl()->decls_begin();
> ```
Still need this to make sure HLSLSema and ExternalSema are initialized before  
MultiplexExternalSemaSource.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132421

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


[PATCH] D132421: [HLSL] Support PCH for cc1 mode

2022-08-31 Thread Xiang Li via Phabricator via cfe-commits
python3kgae updated this revision to Diff 457081.
python3kgae added a comment.

Move reuse decl in PCH into BuiltinTypeDeclBuilder.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132421

Files:
  clang/include/clang/Sema/HLSLExternalSemaSource.h
  clang/lib/Frontend/FrontendAction.cpp
  clang/lib/Sema/HLSLExternalSemaSource.cpp
  clang/test/AST/HLSL/Inputs/pch.hlsl
  clang/test/AST/HLSL/Inputs/pch_with_buf.hlsl
  clang/test/AST/HLSL/pch.hlsl
  clang/test/AST/HLSL/pch_with_buf.hlsl

Index: clang/test/AST/HLSL/pch_with_buf.hlsl
===
--- /dev/null
+++ clang/test/AST/HLSL/pch_with_buf.hlsl
@@ -0,0 +1,18 @@
+// RUN: %clang_cc1 -triple dxil-pc-shadermodel6.3-library -x hlsl -finclude-default-header -emit-pch -o %t %S/Inputs/pch_with_buf.hlsl
+// RUN: %clang_cc1 -triple dxil-pc-shadermodel6.3-library -x hlsl \
+// RUN:  -finclude-default-header -include-pch %t -fsyntax-only -ast-dump-all %s | FileCheck  %s
+
+// Make sure PCH works by using function declared in PCH header.
+// CHECK:FunctionDecl 0x[[FOO:[0-9a-f]+]] <{{.*}}:2:1, line:4:1> line:2:8 imported used foo 'float2 (float2, float2)'
+// Make sure buffer defined in PCH works.
+// CHECK:VarDecl 0x{{[0-9a-f]+}}  col:17 imported Buf 'RWBuffer':'hlsl::RWBuffer<>'
+// Make sure declare a RWBuffer in current file works.
+// CHECK:VarDecl 0x{{[0-9a-f]+}} <{{.*}}:11:1, col:23> col:23 Buf2 'hlsl::RWBuffer':'hlsl::RWBuffer<>'
+hlsl::RWBuffer Buf2;
+
+float2 bar(float2 a, float2 b) {
+// CHECK:CallExpr 0x{{[0-9a-f]+}}  'float2':'float __attribute__((ext_vector_type(2)))'
+// CHECK-NEXT:ImplicitCastExpr 0x{{[0-9a-f]+}}  'float2 (*)(float2, float2)' 
+// CHECK-NEXT:`-DeclRefExpr 0x{{[0-9a-f]+}}  'float2 (float2, float2)' lvalue Function 0x[[FOO]] 'foo' 'float2 (float2, float2)'
+  return foo(a, b);
+}
Index: clang/test/AST/HLSL/pch.hlsl
===
--- /dev/null
+++ clang/test/AST/HLSL/pch.hlsl
@@ -0,0 +1,17 @@
+// RUN: %clang_cc1 -triple dxil-pc-shadermodel6.3-library -x hlsl \
+// RUN:  -finclude-default-header -emit-pch -o %t %S/Inputs/pch.hlsl
+// RUN: %clang_cc1 -triple dxil-pc-shadermodel6.3-library -x hlsl \
+// RUN:  -finclude-default-header -include-pch %t -fsyntax-only -ast-dump-all %s \
+// RUN: | FileCheck  %s
+
+// Make sure PCH works by using function declared in PCH header and declare a RWBuffer in current file.
+// CHECK:FunctionDecl 0x[[FOO:[0-9a-f]+]] <{{.*}}:2:1, line:4:1> line:2:8 imported used foo 'float2 (float2, float2)'
+// CHECK:VarDecl 0x{{[0-9a-f]+}} <{{.*}}:10:1, col:23> col:23 Buffer 'hlsl::RWBuffer':'hlsl::RWBuffer<>'
+hlsl::RWBuffer Buffer;
+
+float2 bar(float2 a, float2 b) {
+// CHECK:CallExpr 0x{{[0-9a-f]+}}  'float2':'float __attribute__((ext_vector_type(2)))'
+// CHECK-NEXT:ImplicitCastExpr 0x{{[0-9a-f]+}}  'float2 (*)(float2, float2)' 
+// CHECK-NEXT:`-DeclRefExpr 0x{{[0-9a-f]+}}  'float2 (float2, float2)' lvalue Function 0x[[FOO]] 'foo' 'float2 (float2, float2)'
+  return foo(a, b);
+}
Index: clang/test/AST/HLSL/Inputs/pch_with_buf.hlsl
===
--- /dev/null
+++ clang/test/AST/HLSL/Inputs/pch_with_buf.hlsl
@@ -0,0 +1,6 @@
+
+float2 foo(float2 a, float2 b) {
+  return a + b;
+}
+
+RWBuffer Buf;
Index: clang/test/AST/HLSL/Inputs/pch.hlsl
===
--- /dev/null
+++ clang/test/AST/HLSL/Inputs/pch.hlsl
@@ -0,0 +1,4 @@
+
+float2 foo(float2 a, float2 b) {
+  return a + b;
+}
Index: clang/lib/Sema/HLSLExternalSemaSource.cpp
===
--- clang/lib/Sema/HLSLExternalSemaSource.cpp
+++ clang/lib/Sema/HLSLExternalSemaSource.cpp
@@ -23,6 +23,17 @@
 using namespace clang;
 using namespace hlsl;
 
+static NamedDecl *findDecl(Sema , IdentifierInfo ,
+   Sema::LookupNameKind Kind) {
+  DeclarationNameInfo NameInfo{DeclarationName{}, SourceLocation()};
+  LookupResult R(S, NameInfo, Kind);
+  S.LookupName(R, S.getCurScope());
+  NamedDecl *D = nullptr;
+  if (!R.isAmbiguous() && !R.empty())
+D = R.getRepresentativeDecl();
+  return D;
+}
+
 namespace {
 
 struct TemplateParameterListBuilder;
@@ -32,8 +43,13 @@
   ClassTemplateDecl *Template = nullptr;
   NamespaceDecl *HLSLNamespace = nullptr;
   llvm::StringMap Fields;
+  bool ReusePrevDecl = false;
 
   BuiltinTypeDeclBuilder(CXXRecordDecl *R) : Record(R) {
+if (Record->isCompleteDefinition()) {
+  ReusePrevDecl = true;
+  return;
+}
 Record->startDefinition();
 Template = Record->getDescribedClassTemplate();
   }
@@ -42,6 +58,27 @@
   : HLSLNamespace(Namespace) {
 ASTContext  = S.getASTContext();
 IdentifierInfo  = AST.Idents.get(Name, tok::TokenKind::identifier);
+CXXRecordDecl *PrevRecord = nullptr;
+if (NamedDecl *PrevDecl =
+

[PATCH] D132991: [Clang] Give error message for invalid profile path when compiling IR

2022-08-31 Thread Aiden Grossman via Phabricator via cfe-commits
aidengrossman updated this revision to Diff 457074.
aidengrossman added a comment.

Changed error message from "Could not read profile" to "Error in reading 
profile"
to better reflect the fact that profile reading can fail for multiple reasons, 
not just
when the file path cannot be read/does not exist.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132991

Files:
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/test/Profile/profile-does-not-exist-ir.c


Index: clang/test/Profile/profile-does-not-exist-ir.c
===
--- /dev/null
+++ clang/test/Profile/profile-does-not-exist-ir.c
@@ -0,0 +1,4 @@
+// RUN: not %clang_cc1 -emit-llvm -x ir %s -o - 
-fprofile-instrument-use-path=%t.nonexistent.profdata 2>&1 | FileCheck %s
+
+// CHECK: error: Could not read profile {{.*}}.nonexistent.profdata:
+// CHECK-NOT: Assertion failed
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -1293,12 +1293,15 @@
 
 // Set the profile kind using fprofile-instrument-use-path.
 static void setPGOUseInstrumentor(CodeGenOptions ,
-  const Twine ) {
+  const Twine ,
+  DiagnosticsEngine ) {
   auto ReaderOrErr = llvm::IndexedInstrProfReader::create(ProfileName);
-  // In error, return silently and let Clang PGOUse report the error message.
   if (auto E = ReaderOrErr.takeError()) {
-llvm::consumeError(std::move(E));
-Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
+unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
+"Error in reading profile %0: %1");
+llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase ) {
+  Diags.Report(DiagID) << ProfileName.str() << EI.message();
+});
 return;
   }
   std::unique_ptr PGOReader =
@@ -1717,7 +1720,7 @@
   }
 
   if (!Opts.ProfileInstrumentUsePath.empty())
-setPGOUseInstrumentor(Opts, Opts.ProfileInstrumentUsePath);
+setPGOUseInstrumentor(Opts, Opts.ProfileInstrumentUsePath, Diags);
 
   if (const Arg *A = Args.getLastArg(OPT_ftime_report, OPT_ftime_report_EQ)) {
 Opts.TimePasses = true;


Index: clang/test/Profile/profile-does-not-exist-ir.c
===
--- /dev/null
+++ clang/test/Profile/profile-does-not-exist-ir.c
@@ -0,0 +1,4 @@
+// RUN: not %clang_cc1 -emit-llvm -x ir %s -o - -fprofile-instrument-use-path=%t.nonexistent.profdata 2>&1 | FileCheck %s
+
+// CHECK: error: Could not read profile {{.*}}.nonexistent.profdata:
+// CHECK-NOT: Assertion failed
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -1293,12 +1293,15 @@
 
 // Set the profile kind using fprofile-instrument-use-path.
 static void setPGOUseInstrumentor(CodeGenOptions ,
-  const Twine ) {
+  const Twine ,
+  DiagnosticsEngine ) {
   auto ReaderOrErr = llvm::IndexedInstrProfReader::create(ProfileName);
-  // In error, return silently and let Clang PGOUse report the error message.
   if (auto E = ReaderOrErr.takeError()) {
-llvm::consumeError(std::move(E));
-Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
+unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
+"Error in reading profile %0: %1");
+llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase ) {
+  Diags.Report(DiagID) << ProfileName.str() << EI.message();
+});
 return;
   }
   std::unique_ptr PGOReader =
@@ -1717,7 +1720,7 @@
   }
 
   if (!Opts.ProfileInstrumentUsePath.empty())
-setPGOUseInstrumentor(Opts, Opts.ProfileInstrumentUsePath);
+setPGOUseInstrumentor(Opts, Opts.ProfileInstrumentUsePath, Diags);
 
   if (const Arg *A = Args.getLastArg(OPT_ftime_report, OPT_ftime_report_EQ)) {
 Opts.TimePasses = true;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] bb9dedc - [Frontend] Restore Preprocessor::getPredefines()

2022-08-31 Thread Roy Jacobson via cfe-commits

Author: Roy Jacobson
Date: 2022-08-31T23:16:49+03:00
New Revision: bb9dedce5d01f5608acd784942481f386c710c0d

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

LOG: [Frontend] Restore Preprocessor::getPredefines()

https://reviews.llvm.org/rG6bbf51f3ed59ae37f0fec729f25af002111c9e74 from May 
removed Preprocessor::getPredefines() from Clang's API, presumably as a cleanup 
because this method is unused in the LLVM codebase.

However, it was/is used by a small number of third-party tools and is pretty 
harmless, so this patch adds it back and documents why it's here.

The issue was raised in https://github.com/llvm/llvm-project/issues/57483, it 
would be nice to be able to land it into Clang 15 as it breaks those 
third-party tools and we can't easily add it back in bug fix releases.

Reviewed By: brad.king, thieta

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

Added: 


Modified: 
clang/include/clang/Lex/Preprocessor.h

Removed: 




diff  --git a/clang/include/clang/Lex/Preprocessor.h 
b/clang/include/clang/Lex/Preprocessor.h
index c00600c68a34..7507be19f037 100644
--- a/clang/include/clang/Lex/Preprocessor.h
+++ b/clang/include/clang/Lex/Preprocessor.h
@@ -1375,6 +1375,11 @@ class Preprocessor {
   StringRef getLastMacroWithSpelling(SourceLocation Loc,
  ArrayRef Tokens) const;
 
+  /// Get the predefines for this processor.
+  /// Used by some third-party tools to inspect and add predefines (see
+  /// https://github.com/llvm/llvm-project/issues/57483).
+  const std::string () const { return Predefines; }
+
   /// Set the predefines for this Preprocessor.
   ///
   /// These predefines are automatically injected when parsing the main file.



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


[PATCH] D133044: [Frontend] Restore Preprocessor::getPredefines()

2022-08-31 Thread Roy Jacobson 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 rGbb9dedce5d01: [Frontend] Restore 
Preprocessor::getPredefines() (authored by royjacobson).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133044

Files:
  clang/include/clang/Lex/Preprocessor.h


Index: clang/include/clang/Lex/Preprocessor.h
===
--- clang/include/clang/Lex/Preprocessor.h
+++ clang/include/clang/Lex/Preprocessor.h
@@ -1375,6 +1375,11 @@
   StringRef getLastMacroWithSpelling(SourceLocation Loc,
  ArrayRef Tokens) const;
 
+  /// Get the predefines for this processor.
+  /// Used by some third-party tools to inspect and add predefines (see
+  /// https://github.com/llvm/llvm-project/issues/57483).
+  const std::string () const { return Predefines; }
+
   /// Set the predefines for this Preprocessor.
   ///
   /// These predefines are automatically injected when parsing the main file.


Index: clang/include/clang/Lex/Preprocessor.h
===
--- clang/include/clang/Lex/Preprocessor.h
+++ clang/include/clang/Lex/Preprocessor.h
@@ -1375,6 +1375,11 @@
   StringRef getLastMacroWithSpelling(SourceLocation Loc,
  ArrayRef Tokens) const;
 
+  /// Get the predefines for this processor.
+  /// Used by some third-party tools to inspect and add predefines (see
+  /// https://github.com/llvm/llvm-project/issues/57483).
+  const std::string () const { return Predefines; }
+
   /// Set the predefines for this Preprocessor.
   ///
   /// These predefines are automatically injected when parsing the main file.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D133044: [Frontend] Restore Preprocessor::getPredefines()

2022-08-31 Thread Roy Jacobson via Phabricator via cfe-commits
royjacobson updated this revision to Diff 457070.
royjacobson edited the summary of this revision.
royjacobson added a comment.

Add a link to github issue.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133044

Files:
  clang/include/clang/Lex/Preprocessor.h


Index: clang/include/clang/Lex/Preprocessor.h
===
--- clang/include/clang/Lex/Preprocessor.h
+++ clang/include/clang/Lex/Preprocessor.h
@@ -1375,6 +1375,11 @@
   StringRef getLastMacroWithSpelling(SourceLocation Loc,
  ArrayRef Tokens) const;
 
+  /// Get the predefines for this processor.
+  /// Used by some third-party tools to inspect and add predefines (see
+  /// https://github.com/llvm/llvm-project/issues/57483).
+  const std::string () const { return Predefines; }
+
   /// Set the predefines for this Preprocessor.
   ///
   /// These predefines are automatically injected when parsing the main file.


Index: clang/include/clang/Lex/Preprocessor.h
===
--- clang/include/clang/Lex/Preprocessor.h
+++ clang/include/clang/Lex/Preprocessor.h
@@ -1375,6 +1375,11 @@
   StringRef getLastMacroWithSpelling(SourceLocation Loc,
  ArrayRef Tokens) const;
 
+  /// Get the predefines for this processor.
+  /// Used by some third-party tools to inspect and add predefines (see
+  /// https://github.com/llvm/llvm-project/issues/57483).
+  const std::string () const { return Predefines; }
+
   /// Set the predefines for this Preprocessor.
   ///
   /// These predefines are automatically injected when parsing the main file.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D132909: [msan] Use Debug Info to point to affected fields

2022-08-31 Thread Vitaly Buka via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG960e7a551326: [msan] Use Debug Info to point to affected 
fields (authored by vitalybuka).

Changed prior to commit:
  https://reviews.llvm.org/D132909?vs=456541=457069#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132909

Files:
  clang/lib/CodeGen/CGClass.cpp
  clang/test/CodeGenCXX/sanitize-dtor-bit-field.cpp
  clang/test/CodeGenCXX/sanitize-dtor-callback.cpp
  clang/test/CodeGenCXX/sanitize-dtor-derived-class.cpp
  clang/test/CodeGenCXX/sanitize-dtor-nontrivial-virtual-base.cpp
  clang/test/CodeGenCXX/sanitize-dtor-trivial-base.cpp
  clang/test/CodeGenCXX/sanitize-dtor-trivial.cpp
  clang/test/CodeGenCXX/sanitize-dtor-vtable.cpp
  compiler-rt/test/msan/dtor-base-access.cpp
  compiler-rt/test/msan/use-after-dtor.cpp

Index: compiler-rt/test/msan/use-after-dtor.cpp
===
--- compiler-rt/test/msan/use-after-dtor.cpp
+++ compiler-rt/test/msan/use-after-dtor.cpp
@@ -34,7 +34,8 @@
 
   // CHECK-ORIGINS: Member fields were destroyed
   // CHECK-ORIGINS: {{#0 0x.* in __sanitizer_dtor_callback}}
-  // CHECK-ORIGINS: {{#1 0x.* in .*~Simple.*cpp:}}[[@LINE-18]]:
+  // CHECK-ORIGINS: {{#1 0x.* in .*~Simple.*cpp:}}[[@LINE-24]]:
+  // CHECK-ORIGINS: {{#2 0x.* in .*~Simple.*cpp:}}[[@LINE-19]]:
 
   // CHECK-UAD: SUMMARY: MemorySanitizer: use-of-uninitialized-value {{.*main}}
   // CHECK-UAD-OFF-NOT: SUMMARY: MemorySanitizer: use-of-uninitialized-value
Index: compiler-rt/test/msan/dtor-base-access.cpp
===
--- compiler-rt/test/msan/dtor-base-access.cpp
+++ compiler-rt/test/msan/dtor-base-access.cpp
@@ -68,17 +68,20 @@
   __msan_print_shadow(>tb0, sizeof(g->tb0));
   // CHECK: Member fields were destroyed
   // CHECK: {{#0 0x.* in __sanitizer_dtor_callback}}
-  // CHECK: {{#1 0x.* in .*~Derived.*cpp:}}[[@LINE-20]]:
+  // CHECK: {{#1 0x.* in .*~Derived.*cpp:}}[[@LINE-56]]:
+  // CHECK: {{#2 0x.* in .*~Derived.*cpp:}}[[@LINE-21]]:
 
   __msan_print_shadow(>b, sizeof(g->b));
   // CHECK: Member fields were destroyed
   // CHECK: {{#0 0x.* in __sanitizer_dtor_callback}}
-  // CHECK: {{#1 0x.* in .*~Base.*cpp:}}[[@LINE-33]]:
+  // CHECK: {{#1 0x.* in .*~Base.*cpp:}}[[@LINE-67]]:
+  // CHECK: {{#2 0x.* in .*~Base.*cpp:}}[[@LINE-35]]:
 
   __msan_print_shadow(>tb1, sizeof(g->tb1));
   // CHECK: Member fields were destroyed
   // CHECK: {{#0 0x.* in __sanitizer_dtor_callback}}
-  // CHECK: {{#1 0x.* in .*~Derived.*cpp:}}[[@LINE-30]]:
+  // CHECK: {{#1 0x.* in .*~Derived.*cpp:}}[[@LINE-62]]:
+  // CHECK: {{#2 0x.* in .*~Derived.*cpp:}}[[@LINE-33]]:
 
   return 0;
 }
Index: clang/test/CodeGenCXX/sanitize-dtor-vtable.cpp
===
--- clang/test/CodeGenCXX/sanitize-dtor-vtable.cpp
+++ clang/test/CodeGenCXX/sanitize-dtor-vtable.cpp
@@ -25,22 +25,23 @@
 // CHECK-LABEL: define {{.*}}BD1Ev
 // CHECK: call void {{.*}}BD2Ev
 // CHECK: call void {{.*}}AD2Ev
-// CHECK: call void @__sanitizer_dtor_callback_vptr({{.*}}, !dbg ![[DI1:[0-9]+]]
+// CHECK: call void @__sanitizer_dtor_callback_vptr{{.*}}, !dbg ![[DI1:[0-9]+]]
 // CHECK: ret void
 
 // Since no virtual bases, poison vtable ptr here.
 // CHECK-LABEL: define {{.*}}AD2Ev
-// CHECK: call void @__sanitizer_dtor_callback_fields({{.*}}, !dbg ![[DI2:[0-9]+]]
-// CHECK: call void @__sanitizer_dtor_callback_vptr({{.*}}, !dbg ![[DI2]]
+// CHECK: call void @__sanitizer_dtor_callback_fields{{.*}}, !dbg ![[DI2:[0-9]+]]
+// CHECK: call void @__sanitizer_dtor_callback_vptr{{.*}}, !dbg ![[DI3:[0-9]+]]
 // CHECK: ret void
 
 // Poison members
 // CHECK-LABEL: define {{.*}}BD2Ev
-// CHECK: call void @__sanitizer_dtor_callback_fields({{.*}}, !dbg ![[DI4:[0-9]+]]
+// CHECK: call void @__sanitizer_dtor_callback_fields{{.*}}, !dbg ![[DI4:[0-9]+]]
 // CHECK: ret void
 
-// CHECK-LABEL: !DIFile{{.*}}cpp
+// CHECK-LABEL: !DIFile{{.*}}sanitize-dtor-vtable.cpp
 
 // CHECK-DAG: ![[DI1]] = {{.*}}line: [[@LINE-28]]
-// CHECK-DAG: ![[DI2]] = {{.*}}line: [[@LINE-37]]
-// CHECK-DAG: ![[DI4]] = {{.*}}line: [[@LINE-30]]
+// CHECK-DAG: ![[DI2]] = {{.*}}line: [[@LINE-39]]
+// CHECK-DAG: ![[DI3]] = {{.*}}line: [[@LINE-38]]
+// CHECK-DAG: ![[DI4]] = {{.*}}line: [[@LINE-33]]
Index: clang/test/CodeGenCXX/sanitize-dtor-trivial.cpp
===
--- clang/test/CodeGenCXX/sanitize-dtor-trivial.cpp
+++ clang/test/CodeGenCXX/sanitize-dtor-trivial.cpp
@@ -16,4 +16,4 @@
 
 // CHECK-LABEL: !DIFile{{.*}}.cpp
 
-// CHECK-DAG: ![[DI]] = {{.*}}line: [[@LINE-371]]
+// CHECK: ![[DI]] = {{.*}}line: [[@LINE-9]]
Index: clang/test/CodeGenCXX/sanitize-dtor-trivial-base.cpp
===
--- clang/test/CodeGenCXX/sanitize-dtor-trivial-base.cpp
+++ 

[clang] 960e7a5 - [msan] Use Debug Info to point to affected fields

2022-08-31 Thread Vitaly Buka via cfe-commits

Author: Vitaly Buka
Date: 2022-08-31T13:12:17-07:00
New Revision: 960e7a5513267b38a07405931300bbf40ddf1902

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

LOG: [msan] Use Debug Info to point to affected fields

Reviewed By: kstoimenov

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

Added: 


Modified: 
clang/lib/CodeGen/CGClass.cpp
clang/test/CodeGenCXX/sanitize-dtor-bit-field.cpp
clang/test/CodeGenCXX/sanitize-dtor-callback.cpp
clang/test/CodeGenCXX/sanitize-dtor-derived-class.cpp
clang/test/CodeGenCXX/sanitize-dtor-nontrivial-virtual-base.cpp
clang/test/CodeGenCXX/sanitize-dtor-trivial-base.cpp
clang/test/CodeGenCXX/sanitize-dtor-trivial.cpp
clang/test/CodeGenCXX/sanitize-dtor-vtable.cpp
compiler-rt/test/msan/dtor-base-access.cpp
compiler-rt/test/msan/use-after-dtor.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGClass.cpp b/clang/lib/CodeGen/CGClass.cpp
index ec4d8e50a356..4a952b9abd55 100644
--- a/clang/lib/CodeGen/CGClass.cpp
+++ b/clang/lib/CodeGen/CGClass.cpp
@@ -1649,6 +1649,29 @@ namespace {
 }
   };
 
+  class DeclAsInlineDebugLocation {
+CGDebugInfo *DI;
+llvm::MDNode *InlinedAt;
+llvm::Optional Location;
+
+  public:
+DeclAsInlineDebugLocation(CodeGenFunction , const NamedDecl )
+: DI(CGF.getDebugInfo()) {
+  if (!DI)
+return;
+  InlinedAt = DI->getInlinedAt();
+  DI->setInlinedAt(CGF.Builder.getCurrentDebugLocation());
+  Location.emplace(CGF, Decl.getLocation());
+}
+
+~DeclAsInlineDebugLocation() {
+  if (!DI)
+return;
+  Location.reset();
+  DI->setInlinedAt(InlinedAt);
+}
+  };
+
   static void EmitSanitizerDtorCallback(
   CodeGenFunction , StringRef Name, llvm::Value *Ptr,
   llvm::Optional PoisonSize = {}) {
@@ -1699,6 +1722,9 @@ namespace {
   if (!BaseSize.isPositive())
 return;
 
+  // Use the base class declaration location as inline DebugLocation. All
+  // fields of the class are destroyed.
+  DeclAsInlineDebugLocation InlineHere(CGF, *BaseClass);
   EmitSanitizerDtorFieldsCallback(CGF, Addr.getPointer(),
   BaseSize.getQuantity());
 
@@ -1748,6 +1774,9 @@ namespace {
   if (!PoisonSize.isPositive())
 return;
 
+  // Use the top field declaration location as inline DebugLocation.
+  DeclAsInlineDebugLocation InlineHere(
+  CGF, **std::next(Dtor->getParent()->field_begin(), StartIndex));
   EmitSanitizerDtorFieldsCallback(CGF, OffsetPtr, 
PoisonSize.getQuantity());
 
   // Prevent the current stack frame from disappearing from the stack 
trace.

diff  --git a/clang/test/CodeGenCXX/sanitize-dtor-bit-field.cpp 
b/clang/test/CodeGenCXX/sanitize-dtor-bit-field.cpp
index 94571d449380..5bb48ac102ee 100644
--- a/clang/test/CodeGenCXX/sanitize-dtor-bit-field.cpp
+++ b/clang/test/CodeGenCXX/sanitize-dtor-bit-field.cpp
@@ -83,7 +83,7 @@ Adjacent ad;
 
 // CHECK-LABEL: !DIFile{{.*}}cpp
 
-// CHECK-DAG: ![[DI1]] = {{.*}}line: [[@LINE-68]]
-// CHECK-DAG: ![[DI2]] = {{.*}}line: [[@LINE-53]]
-// CHECK-DAG: ![[DI3]] = {{.*}}line: [[@LINE-41]]
-// CHECK-DAG: ![[DI4]] = {{.*}}line: [[@LINE-28]]
+// CHECK-DAG: ![[DI1]] = {{.*}}line: [[@LINE-78]]
+// CHECK-DAG: ![[DI2]] = {{.*}}line: [[@LINE-54]]
+// CHECK-DAG: ![[DI3]] = {{.*}}line: [[@LINE-46]]
+// CHECK-DAG: ![[DI4]] = {{.*}}line: [[@LINE-30]]

diff  --git a/clang/test/CodeGenCXX/sanitize-dtor-callback.cpp 
b/clang/test/CodeGenCXX/sanitize-dtor-callback.cpp
index 18c6417001fd..e4a204eab324 100644
--- a/clang/test/CodeGenCXX/sanitize-dtor-callback.cpp
+++ b/clang/test/CodeGenCXX/sanitize-dtor-callback.cpp
@@ -70,6 +70,6 @@ Defaulted_Non_Trivial def_non_trivial;
 
 // CHECK-LABEL: !DIFile{{.*}}cpp
 
-// CHECK-DAG: ![[DI1]] = {{.*}}line: [[@LINE-64]]
-// CHECK-DAG: ![[DI2]] = {{.*}}line: [[@LINE-55]]
-// CHECK-DAG: ![[DI3]] = {{.*}}line: [[@LINE-33]]
+// CHECK-DAG: ![[DI1]] = {{.*}}line: [[@LINE-65]]
+// CHECK-DAG: ![[DI2]] = {{.*}}line: [[@LINE-56]]
+// CHECK-DAG: ![[DI3]] = {{.*}}line: [[@LINE-34]]

diff  --git a/clang/test/CodeGenCXX/sanitize-dtor-derived-class.cpp 
b/clang/test/CodeGenCXX/sanitize-dtor-derived-class.cpp
index 1d5accb8bfd0..e3d83a9d06a5 100644
--- a/clang/test/CodeGenCXX/sanitize-dtor-derived-class.cpp
+++ b/clang/test/CodeGenCXX/sanitize-dtor-derived-class.cpp
@@ -50,17 +50,19 @@ Derived d;
 // Poison members and vtable ptr.
 // CHECK-LABEL: define {{.*}}BaseD2Ev
 // CHECK: call void @__sanitizer_dtor_callback_fields({{.*}}, !dbg 
![[DI1:[0-9]+]]
-// CHECK: call void @__sanitizer_dtor_callback_vptr({{.*}}){{.*}}, !dbg 
![[DI1]]
+// CHECK: call void @__sanitizer_dtor_callback_vptr({{.*}}){{.*}}, !dbg 
![[DI2:[0-9]+]]
 // CHECK: ret void
 
 // Poison members and 

[PATCH] D132962: [clangd][ObjC] Improve completions for protocols + category names

2022-08-31 Thread David Goldman via Phabricator via cfe-commits
dgoldman updated this revision to Diff 457067.
dgoldman added a comment.

Run clang format


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132962

Files:
  clang-tools-extra/clangd/CodeComplete.cpp
  clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
  clang-tools-extra/clangd/unittests/TestIndex.cpp
  clang-tools-extra/clangd/unittests/TestIndex.h

Index: clang-tools-extra/clangd/unittests/TestIndex.h
===
--- clang-tools-extra/clangd/unittests/TestIndex.h
+++ clang-tools-extra/clangd/unittests/TestIndex.h
@@ -39,6 +39,8 @@
llvm::StringRef USRPrefix);
 // Create an @interface or @implementation.
 Symbol objcClass(llvm::StringRef Name);
+// Create an @interface or @implementation category.
+Symbol objcCategory(llvm::StringRef Name, llvm::StringRef CategoryName);
 // Create an @protocol.
 Symbol objcProtocol(llvm::StringRef Name);
 
Index: clang-tools-extra/clangd/unittests/TestIndex.cpp
===
--- clang-tools-extra/clangd/unittests/TestIndex.cpp
+++ clang-tools-extra/clangd/unittests/TestIndex.cpp
@@ -99,6 +99,11 @@
   return objcSym(Name, index::SymbolKind::Class, "objc(cs)");
 }
 
+Symbol objcCategory(llvm::StringRef Name, llvm::StringRef CategoryName) {
+  std::string USRPrefix = ("objc(cy)" + Name + "@").str();
+  return objcSym(CategoryName, index::SymbolKind::Extension, USRPrefix);
+}
+
 Symbol objcProtocol(llvm::StringRef Name) {
   return objcSym(Name, index::SymbolKind::Protocol, "objc(pl)");
 }
Index: clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
===
--- clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
+++ clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
@@ -1493,12 +1493,16 @@
 
 class IndexRequestCollector : public SymbolIndex {
 public:
+  IndexRequestCollector(std::vector Syms = {}) : Symbols(Syms) {}
+
   bool
   fuzzyFind(const FuzzyFindRequest ,
 llvm::function_ref Callback) const override {
 std::unique_lock Lock(Mut);
 Requests.push_back(Req);
 ReceivedRequestCV.notify_one();
+for (const auto  : Symbols)
+  Callback(Sym);
 return true;
   }
 
@@ -1533,6 +1537,7 @@
   }
 
 private:
+  std::vector Symbols;
   // We need a mutex to handle async fuzzy find requests.
   mutable std::condition_variable ReceivedRequestCV;
   mutable std::mutex Mut;
@@ -3214,8 +3219,73 @@
  {SymFood, FoodClass, SymFooey},
  /*Opts=*/{}, "Foo.m");
 
-  auto C = Results.Completions;
-  EXPECT_THAT(C, UnorderedElementsAre(named("Food"), named("Fooey")));
+  // Should only give protocols for ObjC protocol completions.
+  EXPECT_THAT(Results.Completions,
+  UnorderedElementsAre(
+  AllOf(named("Food"), kind(CompletionItemKind::Interface)),
+  AllOf(named("Fooey"), kind(CompletionItemKind::Interface;
+
+  Results = completions(R"objc(
+  Fo^
+)objc",
+{SymFood, FoodClass, SymFooey},
+/*Opts=*/{}, "Foo.m");
+  // Shouldn't give protocols for non protocol completions.
+  EXPECT_THAT(
+  Results.Completions,
+  ElementsAre(AllOf(named("FoodClass"), kind(CompletionItemKind::Class;
+}
+
+TEST(CompletionTest, ObjectiveCProtocolFromIndexSpeculation) {
+  MockFS FS;
+  MockCompilationDatabase CDB;
+  ClangdServer Server(CDB, FS, ClangdServer::optsForTest());
+
+  auto File = testPath("Foo.m");
+  Annotations Test(R"cpp(
+  @protocol Food
+  @end
+  id foo;
+  )cpp");
+  runAddDocument(Server, File, Test.code());
+  clangd::CodeCompleteOptions Opts = {};
+
+  Symbol FoodClass = objcClass("FoodClass");
+  IndexRequestCollector Requests({FoodClass});
+  Opts.Index = 
+
+  auto CompleteAtPoint = [&](StringRef P) {
+return cantFail(runCodeComplete(Server, File, Test.point(P), Opts))
+.Completions;
+  };
+
+  auto C = CompleteAtPoint("1");
+  auto Reqs1 = Requests.consumeRequests(1);
+  ASSERT_EQ(Reqs1.size(), 1u);
+  EXPECT_THAT(C, ElementsAre(AllOf(named("Food"),
+   kind(CompletionItemKind::Interface;
+
+  C = CompleteAtPoint("1");
+  auto Reqs2 = Requests.consumeRequests(1);
+  // Speculation succeeded. Used speculative index result, keeping the same
+  // exact filtering as before to exclude the FoodClass result.
+  ASSERT_EQ(Reqs2.size(), 1u);
+  EXPECT_EQ(Reqs2[0], Reqs1[0]);
+  EXPECT_THAT(C, ElementsAre(AllOf(named("Food"),
+   kind(CompletionItemKind::Interface;
+}
+
+TEST(CompletionTest, ObjectiveCCategoryFromIndexIgnored) {
+  Symbol FoodCategory = objcCategory("FoodClass", "Extension");
+  auto Results = completions(R"objc(
+  @interface Foo
+  @end
+  @interface Foo (^)
+  @end
+

[PATCH] D133044: [Frontend] Restore Preprocessor::getPredefines()

2022-08-31 Thread Tobias Hieta via Phabricator via cfe-commits
thieta accepted this revision.
thieta added a comment.

LGTM and seems pretty safe so I am not opposed to merge it before 15 final.

I would maybe add a link to the GitHub issue in the comment, but that's a nit.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133044

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


[PATCH] D133044: [Frontend] Restore Preprocessor::getPredefines()

2022-08-31 Thread Brad King via Phabricator via cfe-commits
brad.king accepted this revision.
brad.king added a comment.
This revision is now accepted and ready to land.

LGTM.  After applying this patch locally on top of the release/15.x branch, 
CastXML builds again.   Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133044

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


[PATCH] D133044: [Frontend] Restore Preprocessor::getPredefines()

2022-08-31 Thread Roy Jacobson via Phabricator via cfe-commits
royjacobson created this revision.
Herald added a subscriber: kristof.beyls.
Herald added a project: All.
royjacobson requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

A patch from May removed Preprocessor::getPredefines() from Clang's API, 
probably as a cleanup because
this method was unused in the LLVM codebase.

However, it was/is used by a small number of third-party tools and is pretty 
harmless, so this patch adds it back
and documents why it's here.

The issue was raised in https://github.com/llvm/llvm-project/issues/57483, it 
would be nice to be able to
land it into Clang 15 as it breaks those third-party tools and we can't easily 
add it back in bug fix releases.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D133044

Files:
  clang/include/clang/Lex/Preprocessor.h


Index: clang/include/clang/Lex/Preprocessor.h
===
--- clang/include/clang/Lex/Preprocessor.h
+++ clang/include/clang/Lex/Preprocessor.h
@@ -1375,6 +1375,10 @@
   StringRef getLastMacroWithSpelling(SourceLocation Loc,
  ArrayRef Tokens) const;
 
+  /// Get the predefines for this processor.
+  /// Used by some third-party tools to inspect and add predefines.
+  const std::string () const { return Predefines; }
+
   /// Set the predefines for this Preprocessor.
   ///
   /// These predefines are automatically injected when parsing the main file.


Index: clang/include/clang/Lex/Preprocessor.h
===
--- clang/include/clang/Lex/Preprocessor.h
+++ clang/include/clang/Lex/Preprocessor.h
@@ -1375,6 +1375,10 @@
   StringRef getLastMacroWithSpelling(SourceLocation Loc,
  ArrayRef Tokens) const;
 
+  /// Get the predefines for this processor.
+  /// Used by some third-party tools to inspect and add predefines.
+  const std::string () const { return Predefines; }
+
   /// Set the predefines for this Preprocessor.
   ///
   /// These predefines are automatically injected when parsing the main file.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D132998: [clang-tidy] Restrict use-equals-default to c++11-or-later

2022-08-31 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh added a comment.

In D132998#3760603 , 
@alexander-shaposhnikov wrote:

> My assumption was that a codebase needs to compile with c++11 in the first 
> place - otherwise the automatic fixit will break the build (as it happens 
> right now).
> I was looking at modernize/UseOverrideCheck.h - it requires c++11 and this 
> seemed to be quite natural.

There may be cases when the code needs to be "modernized" to compile in C++11 
mode. But I can only recall some uses of NULL and the corresponding 
modernize-use-nullptr check. In other cases one can switch compiler options 
first and then apply clang-tidy fixes. That has a benefit of being able to 
apply fixes incrementally and is probably a more convenient approach.

This patch would likely make it more convenient to use clang-tidy in codebases 
with mixed C++ standards. I'm not sure whether it's an important or even 
practical use case.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132998

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


[PATCH] D133043: [clangd] Fix tests for implicit C function declaration

2022-08-31 Thread Aleksandr Platonov via Phabricator via cfe-commits
ArcsinX created this revision.
ArcsinX added reviewers: aaron.ballman, sammccall, kadircet.
Herald added a subscriber: arphaman.
Herald added a project: All.
ArcsinX requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

clangd code fixes at D122983  were not right.
We need to check that clangd provides IncludeFixer fixits for implicit function 
declaration even if this is not an error (e.g. implicit function declaration in 
C89).


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D133043

Files:
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp


Index: clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
===
--- clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
+++ clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
@@ -1465,11 +1465,12 @@
 TEST(IncludeFixerTest, HeaderNamedInDiag) {
   Annotations Test(R"cpp(
 $insert[[]]int main() {
-  [[printf]](""); // error-ok
+  [[printf]]("");
 }
   )cpp");
   auto TU = TestTU::withCode(Test.code());
-  TU.ExtraArgs = {"-xc"};
+  TU.ExtraArgs = {"-xc", "-std=c99",
+  "-Wno-error=implicit-function-declaration"};
   auto Index = buildIndexWithSymbol({});
   TU.ExternalIndex = Index.get();
 
@@ -1482,13 +1483,22 @@
  "declarations"),
   withFix(Fix(Test.range("insert"), "#include \n",
   "Include  for symbol printf");
+
+  TU.ExtraArgs = {"-xc", "-std=c89"};
+  EXPECT_THAT(
+  *TU.build().getDiagnostics(),
+  ElementsAre(AllOf(
+  Diag(Test.range(), "implicitly declaring library function 'printf' "
+ "with type 'int (const char *, ...)'"),
+  withFix(Fix(Test.range("insert"), "#include \n",
+  "Include  for symbol printf");
 }
 
 TEST(IncludeFixerTest, CImplicitFunctionDecl) {
-  Annotations Test("void x() { [[foo]](); /* error-ok */ }");
+  Annotations Test("void x() { [[foo]](); }");
   auto TU = TestTU::withCode(Test.code());
   TU.Filename = "test.c";
-  TU.ExtraArgs.push_back("-std=c99");
+  TU.ExtraArgs = {"-std=c99", "-Wno-error=implicit-function-declaration"};
 
   Symbol Sym = func("foo");
   Sym.Flags |= Symbol::IndexedForCodeCompletion;
@@ -1509,6 +1519,13 @@
"support implicit function declarations"),
   withFix(Fix(Range{}, "#include \"foo.h\"\n",
   "Include \"foo.h\" for symbol foo");
+
+  TU.ExtraArgs = {"-std=c89", "-Wall"};
+  EXPECT_THAT(*TU.build().getDiagnostics(),
+  ElementsAre(AllOf(
+  Diag(Test.range(), "implicit declaration of function 'foo'"),
+  withFix(Fix(Range{}, "#include \"foo.h\"\n",
+  "Include \"foo.h\" for symbol foo");
 }
 
 TEST(DiagsInHeaders, DiagInsideHeader) {
Index: clang-tools-extra/clangd/ParsedAST.cpp
===
--- clang-tools-extra/clangd/ParsedAST.cpp
+++ clang-tools-extra/clangd/ParsedAST.cpp
@@ -493,6 +493,7 @@
 // We restore the original severity in the level adjuster.
 // FIXME: It would be better to have a real API for this, but what?
 for (auto ID : {diag::ext_implicit_function_decl_c99,
+diag::ext_implicit_lib_function_decl,
 diag::ext_implicit_lib_function_decl_c99,
 diag::warn_implicit_function_decl}) {
   OverriddenSeverity.try_emplace(


Index: clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
===
--- clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
+++ clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
@@ -1465,11 +1465,12 @@
 TEST(IncludeFixerTest, HeaderNamedInDiag) {
   Annotations Test(R"cpp(
 $insert[[]]int main() {
-  [[printf]](""); // error-ok
+  [[printf]]("");
 }
   )cpp");
   auto TU = TestTU::withCode(Test.code());
-  TU.ExtraArgs = {"-xc"};
+  TU.ExtraArgs = {"-xc", "-std=c99",
+  "-Wno-error=implicit-function-declaration"};
   auto Index = buildIndexWithSymbol({});
   TU.ExternalIndex = Index.get();
 
@@ -1482,13 +1483,22 @@
  "declarations"),
   withFix(Fix(Test.range("insert"), "#include \n",
   "Include  for symbol printf");
+
+  TU.ExtraArgs = {"-xc", "-std=c89"};
+  EXPECT_THAT(
+  *TU.build().getDiagnostics(),
+  ElementsAre(AllOf(
+  Diag(Test.range(), "implicitly declaring library function 'printf' "
+ "with type 'int (const char *, ...)'"),
+  withFix(Fix(Test.range("insert"), "#include \n",
+  "Include  for symbol printf");
 }
 
 TEST(IncludeFixerTest, 

[clang] 41b1c9f - Re-add the REQUIRES line to fix a failed build on builder llvm-clang-win-x-aarch64.

2022-08-31 Thread Ying Yi via cfe-commits

Author: Ying Yi
Date: 2022-08-31T20:22:18+01:00
New Revision: 41b1c9ff70142dc38a381517718cd3f95e8d62b7

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

LOG: Re-add the REQUIRES line to fix a failed build on builder 
llvm-clang-win-x-aarch64.

Added: 


Modified: 
clang/test/Driver/ps4-ps5-header-search.c

Removed: 




diff  --git a/clang/test/Driver/ps4-ps5-header-search.c 
b/clang/test/Driver/ps4-ps5-header-search.c
index 6762c707dde6..6848901df559 100644
--- a/clang/test/Driver/ps4-ps5-header-search.c
+++ b/clang/test/Driver/ps4-ps5-header-search.c
@@ -1,3 +1,5 @@
+// REQUIRES: x86-registered-target
+
 /// PS4 and PS5 use the same SDK layout, so use the same tree for both.
 // RUN: env SCE_ORBIS_SDK_DIR=%S/Inputs/scei-ps4_tree %clang -target 
x86_64-scei-ps4 -E -v %s 2>&1 | FileCheck %s --check-prefix=ENVPS4
 // RUN: env SCE_PROSPERO_SDK_DIR=%S/Inputs/scei-ps4_tree %clang -target 
x86_64-sie-ps5 -E -v %s 2>&1 | FileCheck %s --check-prefix=ENVPS4



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


[PATCH] D132421: [HLSL] Support PCH for cc1 mode

2022-08-31 Thread Xiang Li via Phabricator via cfe-commits
python3kgae added inline comments.



Comment at: clang/lib/Sema/HLSLExternalSemaSource.cpp:297
+  }
+
   IdentifierInfo  = AST.Idents.get("hlsl", tok::TokenKind::identifier);

beanz wrote:
> I think the core of what you'e doing here is not far off, but I think this 
> pattern doesn't scale or cover all the use cases that matter.
> 
> The cases that come to my mind are:
> 1) PCH has a forward declaration, source doesn't use the type so we shouldn't 
> complete the type.
> 2) PCH has a forward declaration, source uses the type, so we need to 
> generate a complete decl.
> 3) PCH has a complete declaration, so we should re-use the declaration and 
> not need to do anything.
> 
> We also need to keep in mind that we're going to keep adding more and more 
> types, so this pattern where each new type needs to add code to lookup is 
> going to be a challenge. It is also going to be a challenge to manage the 
> complexity of PCH defines one thing but not another.
> 
> One thing you should look at is how clang handles the following C++ code:
> 
> ```
> template
> class Foo;
> 
> template
> class Foo {
>   T Val;
> };
> ```
> 
> This results in two decls. One for the forward decl and the second for the 
> definition. The definition lists the forward declaration as the previous 
> decl. We should do that here.
> 
> When we generate the HLSL namespace, we can do a lookup and if we find a 
> previous decl, set the previous decl.
> 
> When we generate any of the builtin types, we can lookup the previous decl, 
> and annotate as the previous decl. We'll can also handle the case where a 
> decl from the PCH is complete. If the PCH provides a complete decl, we can 
> skip generating any decls for it, and the lookups should just work.
Set previous decl not work.
It goes to "For most kinds of declaration, it doesn't really matter which one 
we pick." before checking PreviousDecl.


```
   // For most kinds of declaration, it doesn't really matter which one we pick.
  if (!isa(DUnderlying) && !isa(DUnderlying)) {
// If the existing declaration is hidden, prefer the new one. Otherwise,
// keep what we've got.
return !S.isVisible(Existing);
  }



  // Pick the newer declaration; it might have a more precise type.
  for (Decl *Prev = DUnderlying->getPreviousDecl(); Prev;
   Prev = Prev->getPreviousDecl())
if (Prev == EUnderlying)
  return true;
  return false;
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132421

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


[clang] cdf3de4 - [CodeGen] fix misnamed "not" operation; NFC

2022-08-31 Thread Sanjay Patel via cfe-commits

Author: Sanjay Patel
Date: 2022-08-31T15:11:48-04:00
New Revision: cdf3de45d282694290011a2949bdcc61cabb47ef

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

LOG: [CodeGen] fix misnamed "not" operation; NFC

Seeing the wrong instruction for this name in IR is confusing.
Most of the tests are not even checking a subsequent use of
the value, so I just deleted the over-specified CHECKs.

Added: 


Modified: 
clang/lib/CodeGen/CGExprScalar.cpp
clang/test/CodeGen/PowerPC/builtins-ppc-p10vector.c
clang/test/CodeGen/X86/avx512f-builtins.c

Removed: 




diff  --git a/clang/lib/CodeGen/CGExprScalar.cpp 
b/clang/lib/CodeGen/CGExprScalar.cpp
index 9def1285fbc1d..a724f8b6afd76 100644
--- a/clang/lib/CodeGen/CGExprScalar.cpp
+++ b/clang/lib/CodeGen/CGExprScalar.cpp
@@ -2904,7 +2904,7 @@ Value *ScalarExprEmitter::VisitMinus(const UnaryOperator 
*E,
 Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
   TestAndClearIgnoreResultAssign();
   Value *Op = Visit(E->getSubExpr());
-  return Builder.CreateNot(Op, "neg");
+  return Builder.CreateNot(Op, "not");
 }
 
 Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {

diff  --git a/clang/test/CodeGen/PowerPC/builtins-ppc-p10vector.c 
b/clang/test/CodeGen/PowerPC/builtins-ppc-p10vector.c
index 694d2795d335b..312b5fe1894ea 100644
--- a/clang/test/CodeGen/PowerPC/builtins-ppc-p10vector.c
+++ b/clang/test/CodeGen/PowerPC/builtins-ppc-p10vector.c
@@ -1863,15 +1863,15 @@ vector bool __int128 test_vec_cmpeq_bool_int128(void) {
 vector bool __int128 test_vec_cmpne_s128(void) {
   // CHECK-LABEL: @test_vec_cmpne_s128(
   // CHECK: call <1 x i128> @llvm.ppc.altivec.vcmpequq(<1 x i128>
-  // CHECK-NEXT: %neg.i = xor <1 x i128> %4, 
-  // CHECK-NEXT: ret <1 x i128> %neg.i
+  // CHECK-NEXT: %not.i = xor <1 x i128> %4, 
+  // CHECK-NEXT: ret <1 x i128> %not.i
   return vec_cmpne(vsi128a, vsi128b);
 }
 
 vector bool __int128 test_vec_cmpne_u128(void) {
   // CHECK-LABEL: @test_vec_cmpne_u128(
   // CHECK: call <1 x i128> @llvm.ppc.altivec.vcmpequq(<1 x i128>
-  // CHECK-NEXT: %neg.i = xor <1 x i128> %4, 
+  // CHECK-NEXT: xor <1 x i128> %4, 
   // CHECK-NEXT: ret <1 x i128>
   return vec_cmpne(vui128a, vui128b);
 }
@@ -1879,7 +1879,7 @@ vector bool __int128 test_vec_cmpne_u128(void) {
 vector bool __int128 test_vec_cmpne_bool_int128(void) {
   // CHECK-LABEL: @test_vec_cmpne_bool_int128(
   // CHECK: call <1 x i128> @llvm.ppc.altivec.vcmpequq(<1 x i128>
-  // CHECK-NEXT: %neg.i = xor <1 x i128> %4, 
+  // CHECK-NEXT: xor <1 x i128> %4, 
   // CHECK-NEXT: ret <1 x i128>
   return vec_cmpne(vbi128a, vbi128b);
 }
@@ -1915,7 +1915,7 @@ vector bool __int128 test_vec_cmplt_u128(void) {
 vector bool __int128 test_vec_cmpge_s128(void) {
   // CHECK-LABEL: @test_vec_cmpge_s128(
   // CHECK: call <1 x i128> @llvm.ppc.altivec.vcmpgtsq(<1 x i128>
-  // CHECK-NEXT: %neg.i = xor <1 x i128> %6, 
+  // CHECK-NEXT: xor <1 x i128> %6, 
   // CHECK-NEXT: ret <1 x i128>
   return vec_cmpge(vsi128a, vsi128b);
 }
@@ -1923,7 +1923,7 @@ vector bool __int128 test_vec_cmpge_s128(void) {
 vector bool __int128 test_vec_cmpge_u128(void) {
   // CHECK-LABEL: @test_vec_cmpge_u128(
   // CHECK: call <1 x i128> @llvm.ppc.altivec.vcmpgtuq(<1 x i128>
-  // CHECK-NEXT: %neg.i = xor <1 x i128> %6, 
+  // CHECK-NEXT: xor <1 x i128> %6, 
   // CHECK-NEXT: ret <1 x i128>
   return vec_cmpge(vui128a, vui128b);
 }
@@ -1931,7 +1931,7 @@ vector bool __int128 test_vec_cmpge_u128(void) {
 vector bool __int128 test_vec_cmple_s128(void) {
   // CHECK-LABEL: @test_vec_cmple_s128(
   // CHECK: call <1 x i128> @llvm.ppc.altivec.vcmpgtsq(<1 x i128>
-  // CHECK-NEXT: %neg.i.i = xor <1 x i128> %8, 
+  // CHECK-NEXT: xor <1 x i128> %8, 
   // CHECK-NEXT: ret <1 x i128>
   return vec_cmple(vsi128a, vsi128b);
 }
@@ -1939,7 +1939,7 @@ vector bool __int128 test_vec_cmple_s128(void) {
 vector bool __int128 test_vec_cmple_u128(void) {
   // CHECK-LABEL: @test_vec_cmple_u128(
   // CHECK: call <1 x i128> @llvm.ppc.altivec.vcmpgtuq(<1 x i128>
-  // CHECK-NEXT: %neg.i.i = xor <1 x i128> %8, 
+  // CHECK-NEXT: xor <1 x i128> %8, 
   // CHECK-NEXT: ret <1 x i128>
   return vec_cmple(vui128a, vui128b);
 }

diff  --git a/clang/test/CodeGen/X86/avx512f-builtins.c 
b/clang/test/CodeGen/X86/avx512f-builtins.c
index a803bcfff156c..8a0c273415275 100644
--- a/clang/test/CodeGen/X86/avx512f-builtins.c
+++ b/clang/test/CodeGen/X86/avx512f-builtins.c
@@ -2866,9 +2866,9 @@ __m512i test_mm512_andnot_si512(__m512i __A, __m512i __B)
 {
   //CHECK-LABEL: @test_mm512_andnot_si512
   //CHECK: load {{.*}}%__A.addr.i, align 64
-  //CHECK: %neg.i = xor{{.*}}, 
+  //CHECK: %not.i = xor{{.*}}, 
   //CHECK: load {{.*}}%__B.addr.i, align 64
-  //CHECK: and <8 x i64> %neg.i,{{.*}}
+  //CHECK: and <8 x i64> 

[PATCH] D131616: [clang][dataflow] Generalise match switch utility to other AST types and add a `CFGMatchSwitch` which currently handles `CFGStmt` and `CFGInitializer`.

2022-08-31 Thread weiyi via Phabricator via cfe-commits
wyt updated this revision to Diff 457052.
wyt added a comment.

Use `u` suffix to declare constants as unsigned in `CFGMatchSwitchTest.cpp`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131616

Files:
  clang/include/clang/Analysis/FlowSensitive/CFGMatchSwitch.h
  clang/include/clang/Analysis/FlowSensitive/MatchSwitch.h
  clang/unittests/Analysis/FlowSensitive/CFGMatchSwitchTest.cpp
  clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
  clang/unittests/Analysis/FlowSensitive/MatchSwitchTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/MatchSwitchTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/MatchSwitchTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/MatchSwitchTest.cpp
@@ -5,12 +5,6 @@
 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
 //
 //===--===//
-//
-//  This file defines a simplistic version of Constant Propagation as an example
-//  of a forward, monotonic dataflow analysis. The analysis tracks all
-//  variables in the scope, but lacks escape analysis.
-//
-//===--===//
 
 #include "clang/Analysis/FlowSensitive/MatchSwitch.h"
 #include "TestingSupport.h"
Index: clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
===
--- clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
+++ clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
@@ -4,6 +4,7 @@
   )
 
 add_clang_unittest(ClangAnalysisFlowSensitiveTests
+  CFGMatchSwitchTest.cpp
   ChromiumCheckModelTest.cpp
   DataflowAnalysisContextTest.cpp
   DataflowEnvironmentTest.cpp
Index: clang/unittests/Analysis/FlowSensitive/CFGMatchSwitchTest.cpp
===
--- /dev/null
+++ clang/unittests/Analysis/FlowSensitive/CFGMatchSwitchTest.cpp
@@ -0,0 +1,124 @@
+//===- unittests/Analysis/FlowSensitive/CFGMatchSwitchTest.cpp ===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/Analysis/FlowSensitive/CFGMatchSwitch.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/Stmt.h"
+#include "clang/Analysis/CFG.h"
+#include "clang/Tooling/Tooling.h"
+#include "llvm/ADT/StringRef.h"
+#include "gtest/gtest.h"
+
+using namespace clang;
+using namespace dataflow;
+using namespace ast_matchers;
+
+namespace {
+// State for tracking the number of matches on each kind of CFGElement by the
+// CFGMatchSwitch. Currently only tracks CFGStmt and CFGInitializer.
+struct CFGElementMatches {
+  unsigned StmtMatches = 0;
+  unsigned InitializerMatches = 0;
+};
+
+// Returns a match switch that counts the number of local variables
+// (singly-declared) and fields initialized to the integer literal 42.
+auto buildCFGMatchSwitch() {
+  return CFGMatchSwitchBuilder()
+  .CaseOfCFGStmt(
+  declStmt(hasSingleDecl(
+  varDecl(hasInitializer(integerLiteral(equals(42)),
+  [](const DeclStmt *, const MatchFinder::MatchResult &,
+ CFGElementMatches ) { Counter.StmtMatches++; })
+  .CaseOfCFGInit(
+  cxxCtorInitializer(withInitializer(integerLiteral(equals(42,
+  [](const CXXCtorInitializer *, const MatchFinder::MatchResult &,
+ CFGElementMatches ) { Counter.InitializerMatches++; })
+  .Build();
+}
+
+// Runs the match switch `MS` on the control flow graph generated from `Code`,
+// tracking information in state `S`. For simplicity, this test utility is
+// restricted to CFGs with a single control flow block (excluding entry and
+// exit blocks) - generated by `Code` with sequential flow (i.e. no branching).
+//
+// Requirements:
+//
+//  `Code` must contain a function named `f`, the body of this function will be
+//  used to generate the CFG.
+template 
+void applySwitchToCode(CFGMatchSwitch , State ,
+   llvm::StringRef Code) {
+  auto Unit = tooling::buildASTFromCodeWithArgs(Code, {"-Wno-unused-value"});
+  auto  = Unit->getASTContext();
+  const auto *F = selectFirst(
+  "f", match(functionDecl(isDefinition(), hasName("f")).bind("f"), Ctx));
+
+  CFG::BuildOptions BO;
+  BO.AddInitializers = true;
+
+  auto CFG = CFG::buildCFG(F, F->getBody(), , BO);
+  auto CFGBlock = *CFG->getEntry().succ_begin();
+  for (auto  : CFGBlock->Elements) {
+MS(Elt, Ctx, S);
+  }
+}
+
+TEST(CFGMatchSwitchTest, NoInitializationTo42) {
+  CFGMatchSwitch Switch = buildCFGMatchSwitch();
+  CFGElementMatches Counter;
+  applySwitchToCode(Switch, Counter, R"(
+ 

[PATCH] D132962: [clangd][ObjC] Improve completions for protocols + category names

2022-08-31 Thread David Goldman via Phabricator via cfe-commits
dgoldman added a comment.

In D132962#3761463 , @kadircet wrote:

> can you also add test cases for the other two (filtering both for speculative 
> index queries/regular ones, and making sure we don't suggest symbols from 
> index for category names), so that we don't regress in the future?

Done


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132962

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


[PATCH] D132962: [clangd][ObjC] Improve completions for protocols + category names

2022-08-31 Thread David Goldman via Phabricator via cfe-commits
dgoldman updated this revision to Diff 457049.
dgoldman added a comment.

Add tests


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132962

Files:
  clang-tools-extra/clangd/CodeComplete.cpp
  clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
  clang-tools-extra/clangd/unittests/TestIndex.cpp
  clang-tools-extra/clangd/unittests/TestIndex.h

Index: clang-tools-extra/clangd/unittests/TestIndex.h
===
--- clang-tools-extra/clangd/unittests/TestIndex.h
+++ clang-tools-extra/clangd/unittests/TestIndex.h
@@ -39,6 +39,8 @@
llvm::StringRef USRPrefix);
 // Create an @interface or @implementation.
 Symbol objcClass(llvm::StringRef Name);
+// Create an @interface or @implementation category.
+Symbol objcCategory(llvm::StringRef Name, llvm::StringRef CategoryName);
 // Create an @protocol.
 Symbol objcProtocol(llvm::StringRef Name);
 
Index: clang-tools-extra/clangd/unittests/TestIndex.cpp
===
--- clang-tools-extra/clangd/unittests/TestIndex.cpp
+++ clang-tools-extra/clangd/unittests/TestIndex.cpp
@@ -99,6 +99,11 @@
   return objcSym(Name, index::SymbolKind::Class, "objc(cs)");
 }
 
+Symbol objcCategory(llvm::StringRef Name, llvm::StringRef CategoryName) {
+  std::string USRPrefix = ("objc(cy)" + Name + "@").str();
+  return objcSym(CategoryName, index::SymbolKind::Extension, USRPrefix);
+}
+
 Symbol objcProtocol(llvm::StringRef Name) {
   return objcSym(Name, index::SymbolKind::Protocol, "objc(pl)");
 }
Index: clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
===
--- clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
+++ clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
@@ -1493,12 +1493,16 @@
 
 class IndexRequestCollector : public SymbolIndex {
 public:
+  IndexRequestCollector(std::vector Syms = {}) : Symbols(Syms) {}
+
   bool
   fuzzyFind(const FuzzyFindRequest ,
 llvm::function_ref Callback) const override {
 std::unique_lock Lock(Mut);
 Requests.push_back(Req);
 ReceivedRequestCV.notify_one();
+for (const auto  : Symbols)
+  Callback(Sym);
 return true;
   }
 
@@ -1533,6 +1537,7 @@
   }
 
 private:
+  std::vector Symbols;
   // We need a mutex to handle async fuzzy find requests.
   mutable std::condition_variable ReceivedRequestCV;
   mutable std::mutex Mut;
@@ -3214,8 +3219,74 @@
  {SymFood, FoodClass, SymFooey},
  /*Opts=*/{}, "Foo.m");
 
-  auto C = Results.Completions;
-  EXPECT_THAT(C, UnorderedElementsAre(named("Food"), named("Fooey")));
+  // Should only give protocols for ObjC protocol completions.
+  EXPECT_THAT(Results.Completions,
+  UnorderedElementsAre(
+  AllOf(named("Food"), kind(CompletionItemKind::Interface)),
+  AllOf(named("Fooey"), kind(CompletionItemKind::Interface;
+
+  Results = completions(R"objc(
+  Fo^
+)objc",
+{SymFood, FoodClass, SymFooey},
+/*Opts=*/{}, "Foo.m");
+  // Shouldn't give protocols for non protocol completions.
+  EXPECT_THAT(Results.Completions,
+  ElementsAre(
+  AllOf(named("FoodClass"), kind(CompletionItemKind::Class;
+}
+
+TEST(CompletionTest, ObjectiveCProtocolFromIndexSpeculation) {
+  MockFS FS;
+  MockCompilationDatabase CDB;
+  ClangdServer Server(CDB, FS, ClangdServer::optsForTest());
+
+  auto File = testPath("Foo.m");
+  Annotations Test(R"cpp(
+  @protocol Food
+  @end
+  id foo;
+  )cpp");
+  runAddDocument(Server, File, Test.code());
+  clangd::CodeCompleteOptions Opts = {};
+
+  Symbol FoodClass = objcClass("FoodClass");
+  IndexRequestCollector Requests({FoodClass});
+  Opts.Index = 
+
+  auto CompleteAtPoint = [&](StringRef P) {
+return cantFail(runCodeComplete(Server, File, Test.point(P), Opts)).Completions;
+  };
+
+  auto C = CompleteAtPoint("1");
+  auto Reqs1 = Requests.consumeRequests(1);
+  ASSERT_EQ(Reqs1.size(), 1u);
+  EXPECT_THAT(C,
+  ElementsAre(
+  AllOf(named("Food"), kind(CompletionItemKind::Interface;
+
+  C = CompleteAtPoint("1");
+  auto Reqs2 = Requests.consumeRequests(1);
+  // Speculation succeeded. Used speculative index result, keeping the same
+  // exact filtering as before to exclude the FoodClass result.
+  ASSERT_EQ(Reqs2.size(), 1u);
+  EXPECT_EQ(Reqs2[0], Reqs1[0]);
+  EXPECT_THAT(C,
+  ElementsAre(
+  AllOf(named("Food"), kind(CompletionItemKind::Interface;
+}
+
+TEST(CompletionTest, ObjectiveCCategoryFromIndexIgnored) {
+  Symbol FoodCategory = objcCategory("FoodClass", "Extension");
+  auto Results = completions(R"objc(
+  @interface Foo
+  @end
+  @interface Foo (^)
+  @end
+

[PATCH] D131979: [clang][UBSan] Fix __builtin_assume_aligned crash

2022-08-31 Thread John McCall via Phabricator via cfe-commits
rjmccall added inline comments.



Comment at: clang/lib/Sema/SemaChecking.cpp:7671
+ AllArgs, CallType))
+return true;
+

yihanaa wrote:
> rjmccall wrote:
> > You can just pull the argument expressions out of the `CallExpr`; you don't 
> > need to call `GatherArgumentsForCall`.
> > You can just pull the argument expressions out of the `CallExpr`; you don't 
> > need to call `GatherArgumentsForCall`.
> 
> This GatherArgumentsForCall  was used to do the common sema checking and emit 
> warning, like './main.cpp:5:40: warning: passing 'volatile char *' to 
> parameter of type 'const void *' discards qualifiers 
> [-Wincompatible-pointer-types-discards-qualifiers]' hahaha, for this is a 
> common case, I also think  GatherArgumentsForCall is not a good choice
> , so I try to find a replacement, e.g. ImpCastExprToType or other ways, what 
> do you think about?
`convertArgumentToType` should trigger any useful warnings in the second and 
third arguments.  For the first, I don't actually think there are any warnings 
we care about.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131979

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


[clang] 74c8d9d - Revert "[clang][dataflow] Generalise match switch utility to other AST types and add a `CFGMatchSwitch` which currently handles `CFGStmt` and `CFGInitializer`."

2022-08-31 Thread Wei Yi Tee via cfe-commits

Author: Wei Yi Tee
Date: 2022-08-31T18:49:56Z
New Revision: 74c8d9d5fc83868977d497c4376296bc27319622

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

LOG: Revert "[clang][dataflow] Generalise match switch utility to other AST 
types and add a `CFGMatchSwitch` which currently handles `CFGStmt` and 
`CFGInitializer`."

This reverts commit c9033eeb2e59c0157b84adfc6b0fe345f6f03113.
https://lab.llvm.org/buildbot#builders/57/builds/21618
Build failure due to comparison between unsigned int and const int
originating from EXPECT_EQ.

Added: 


Modified: 
clang/include/clang/Analysis/FlowSensitive/MatchSwitch.h
clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
clang/unittests/Analysis/FlowSensitive/MatchSwitchTest.cpp

Removed: 
clang/include/clang/Analysis/FlowSensitive/CFGMatchSwitch.h
clang/unittests/Analysis/FlowSensitive/CFGMatchSwitchTest.cpp



diff  --git a/clang/include/clang/Analysis/FlowSensitive/CFGMatchSwitch.h 
b/clang/include/clang/Analysis/FlowSensitive/CFGMatchSwitch.h
deleted file mode 100644
index ecd8558970f93..0
--- a/clang/include/clang/Analysis/FlowSensitive/CFGMatchSwitch.h
+++ /dev/null
@@ -1,98 +0,0 @@
-//=== CFGMatchSwitch.h --*- C++ 
-*-===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===--===//
-//
-//  This file defines the `CFGMatchSwitch` abstraction for building a "switch"
-//  statement for control flow graph elements. Each case of the switch is
-//  defined by an ASTMatcher which is applied on the AST node contained in the
-//  input `CFGElement`.
-//
-//  Currently, the `CFGMatchSwitch` only handles `CFGElement`s of
-//  `Kind::Statement` and `Kind::Initializer`.
-//
-//===--===//
-
-#ifndef LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_CFGMATCHSWITCH_H_
-#define LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_CFGMATCHSWITCH_H_
-
-#include "clang/AST/ASTContext.h"
-#include "clang/AST/Stmt.h"
-#include "clang/Analysis/CFG.h"
-#include "clang/Analysis/FlowSensitive/MatchSwitch.h"
-#include 
-#include 
-
-namespace clang {
-namespace dataflow {
-
-template 
-using CFGMatchSwitch =
-std::function;
-
-/// Collects cases of a "match switch": a collection of matchers paired with
-/// callbacks, which together define a switch that can be applied to an AST 
node
-/// contained in a CFG element.
-template  class CFGMatchSwitchBuilder {
-public:
-  /// Registers an action `A` for `CFGStmt`s that will be triggered by the 
match
-  /// of the pattern `M` against the `Stmt` contained in the input `CFGStmt`.
-  ///
-  /// Requirements:
-  ///
-  ///  `NodeT` should be derived from `Stmt`.
-  template 
-  CFGMatchSwitchBuilder &&
-  CaseOfCFGStmt(MatchSwitchMatcher M,
-MatchSwitchAction A) && {
-std::move(StmtBuilder).template CaseOf(M, A);
-return std::move(*this);
-  }
-
-  /// Registers an action `A` for `CFGInitializer`s that will be triggered by
-  /// the match of the pattern `M` against the `CXXCtorInitializer` contained 
in
-  /// the input `CFGInitializer`.
-  ///
-  /// Requirements:
-  ///
-  ///  `NodeT` should be derived from `CXXCtorInitializer`.
-  template 
-  CFGMatchSwitchBuilder &&
-  CaseOfCFGInit(MatchSwitchMatcher M,
-MatchSwitchAction A) && {
-std::move(InitBuilder).template CaseOf(M, A);
-return std::move(*this);
-  }
-
-  CFGMatchSwitch Build() && {
-return [StmtMS = std::move(StmtBuilder).Build(),
-InitMS = std::move(InitBuilder).Build()](const CFGElement ,
- ASTContext ,
- State ) -> Result {
-  switch (Element.getKind()) {
-  case CFGElement::Initializer:
-return InitMS(*Element.castAs().getInitializer(),
-  Context, S);
-  case CFGElement::Statement:
-  case CFGElement::Constructor:
-  case CFGElement::CXXRecordTypedCall:
-return StmtMS(*Element.castAs().getStmt(), Context, S);
-  default:
-// FIXME: Handle other kinds of CFGElement.
-return Result();
-  }
-};
-  }
-
-private:
-  ASTMatchSwitchBuilder StmtBuilder;
-  ASTMatchSwitchBuilder InitBuilder;
-};
-
-} // namespace dataflow
-} // namespace clang
-
-#endif // LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_CFGMATCHSWITCH_H_

diff  --git a/clang/include/clang/Analysis/FlowSensitive/MatchSwitch.h 
b/clang/include/clang/Analysis/FlowSensitive/MatchSwitch.h
index 76d18c1d24463..927aec7df5731 100644

[PATCH] D132952: [Sema] disable -Wvla for function array parameters

2022-08-31 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D132952#3759731 , @efriedma wrote:

> As a practical matter, there isn't any reason to force variably modified 
> parameters to make a function variably modified.  The types of parameters 
> aren't visible in the caller of a function; we only check the compatibility 
> for calls.

There are constraints in C based on whether something is or isn't a variably 
modified type, so I think there is a reason to make sure we're correct here. 
For example:

  // All at file scope
  int n = 100;
  void func(int array[n++]);
  typedef typeof(func) other_func;

C2x 6.7.8p2: "If a typedef name specifies a variably modified type then it 
shall have block scope." Even more interesting is C2x 6.7.2.5p4 (typeof, which 
is new in C2x): "If the type of the operand is a variably modified type, the 
operand is evaluated; otherwise the operand is not evaluated."

> Trying to treat `void (*)(int, int *)` as variably modified would have 
> additional complications, in that clang would internally need to have two 
> canonical types for `void (*)(int, int *)`: one variably modified, one not 
> variably modified.
>
> So if there's a disagreement between clang and the standard, I'd rather just 
> try to fix the standard.

I'll ask on the WG14 reflectors to see if I'm interpreting the variably 
modified type specification wrong or not.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132952

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


[PATCH] D131979: [clang][UBSan] Fix __builtin_assume_aligned crash

2022-08-31 Thread Wang Yihan via Phabricator via cfe-commits
yihanaa added a comment.

Thanks for your review John, I'll try to fix these problem later which you 
point out.




Comment at: clang/lib/Sema/SemaChecking.cpp:7659
+   << 0 << 2 << TheCall->getNumArgs() << Callee->getSourceRange();
+  }
+

rjmccall wrote:
> It looks like this should be `if (NumArgs < 2)`.
> 
> We actually have helper functions in this file for doing this kind of 
> arg-count checking, but it looks like we don't have one that takes a range.  
> Could you just generalize `checkArgCount` so that it takes a min and max arg 
> count?  You can make the existing function call your generalization.
It's my fault, I'll fix it, thanks!



Comment at: clang/lib/Sema/SemaChecking.cpp:7671
+ AllArgs, CallType))
+return true;
+

rjmccall wrote:
> You can just pull the argument expressions out of the `CallExpr`; you don't 
> need to call `GatherArgumentsForCall`.
> You can just pull the argument expressions out of the `CallExpr`; you don't 
> need to call `GatherArgumentsForCall`.

This GatherArgumentsForCall  was used to do the common sema checking and emit 
warning, like './main.cpp:5:40: warning: passing 'volatile char *' to parameter 
of type 'const void *' discards qualifiers 
[-Wincompatible-pointer-types-discards-qualifiers]' hahaha, for this is a 
common case, I also think  GatherArgumentsForCall is not a good choice
, so I try to find a replacement, e.g. ImpCastExprToType or other ways, what do 
you think about?



Comment at: clang/lib/Sema/SemaChecking.cpp:7690
+  // cast instruction which cast type from user-written-type to VoidPtr in
+  // CodeGen.
+  AllArgs[0] = FirstArgResult.get();

rjmccall wrote:
> This comment doesn't mean anything in the context of the current 
> implementation.  If you want to keep something like it (you really don't need 
> to), you could have a comment at the top explaining that we use custom 
> type-checking because it accepts an arbitrary pointer type as the first 
> argument.
+1



Comment at: clang/lib/Sema/SemaChecking.cpp:7695
+TheCall->setArg(i, AllArgs[i]);
+  TheCall->computeDependence();
+

rjmccall wrote:
> This is really just `TheCall->setArg(i, FirstArgResult.get())`.
+1



Comment at: clang/lib/Sema/SemaChecking.cpp:7701
   // We can't check the value of a dependent argument.
-  if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
+  if (!SecondArg->isTypeDependent() && !SecondArg->isValueDependent()) {
 llvm::APSInt Result;

rjmccall wrote:
> Type-dependence implies value-dependence, so you can just check for the 
> latter.
> 
> You should call `convertArgumentToType` with `size_t` in this block, just in 
> case the argument is something like an l-value reference to a `const` integer 
> variable.
+1



Comment at: clang/lib/Sema/SemaChecking.cpp:7719
+Context, Context.getSizeType(), false);
+ThirdArg = PerformCopyInitialization(Entity, SourceLocation(), ThirdArg);
+if (ThirdArg.isInvalid())

rjmccall wrote:
> You can use `convertArgumentToType` here.
+1


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131979

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


[clang] 66f3e90 - [Driver][test] Test -dumpmachine

2022-08-31 Thread Fangrui Song via cfe-commits

Author: Fangrui Song
Date: 2022-08-31T10:31:45-07:00
New Revision: 66f3e90cf8225333273bfaddc1a7f832fe0c263d

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

LOG: [Driver][test] Test -dumpmachine

Added: 
clang/test/Driver/dumpmachine.c

Modified: 


Removed: 




diff  --git a/clang/test/Driver/dumpmachine.c b/clang/test/Driver/dumpmachine.c
new file mode 100644
index 0..41dda5590eb82
--- /dev/null
+++ b/clang/test/Driver/dumpmachine.c
@@ -0,0 +1,12 @@
+/// Test that -dumpmachine prints the target triple.
+
+/// Note: Debian GCC may omit "unknown-".
+// RUN: %clang --target=x86_64-linux-gnu -dumpmachine | FileCheck %s 
--check-prefix=X86_64
+// X86_64: x86_64-unknown-linux-gnu
+
+/// Note: GCC doesn't convert -dumpmachine output for multilib -m32/-mx32/-m64.
+// RUN: %clang --target=x86_64-redhat-linux -m32 -dumpmachine | FileCheck %s 
--check-prefix=X86_64_M32
+// X86_64_M32: i386-redhat-linux
+
+// RUN: %clang --target=xxx-pc-freebsd -dumpmachine | FileCheck %s 
--check-prefix=FREEBSD
+// FREEBSD: xxx-pc-freebsd



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


[PATCH] D132991: [Clang] Give error message for invalid profile path when compiling IR

2022-08-31 Thread Rong Xu via Phabricator via cfe-commits
xur added a comment.

I'm fine with this change.




Comment at: clang/lib/Frontend/CompilerInvocation.cpp:1301
+unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
+"Could not read profile %0: %1");
+llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase ) {

Should we use "Error in reading profile ..."?
Reader still can return error even if the profile can be read.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132991

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


[PATCH] D132568: [clang][Sema] check default argument promotions for printf

2022-08-31 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added inline comments.



Comment at: clang/docs/ReleaseNotes.rst:141
 
+- Implemented `WG14 N2562 
`_.
+  Clang will now consider default argument promotions in printf, and remove 
unnecessary warnings.

It seems a little weird to say we "implemented" this.  The standard doesn't 
require any warnings for misuse of printf etc., and clang doesn't actually 
implement printf, so we don't need to do anything to be standard-compliant.  
I'd just say that we adjusted -Wformat warnings to avoid false positives.



Comment at: clang/lib/Sema/SemaChecking.cpp:10124
+// Consider character literal is a 'char' in C
+// printf("%hd", 'a'); is more likey a type confusion situation
+// We will suggest our users to use %hhd by discarding MatchPromotion

*likely


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132568

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


[PATCH] D131979: [clang][UBSan] Fix __builtin_assume_aligned crash

2022-08-31 Thread John McCall via Phabricator via cfe-commits
rjmccall added a comment.

Thanks.  Just a few small requests to re-use more of the existing logic here.




Comment at: clang/lib/Sema/SemaChecking.cpp:7659
+   << 0 << 2 << TheCall->getNumArgs() << Callee->getSourceRange();
+  }
+

It looks like this should be `if (NumArgs < 2)`.

We actually have helper functions in this file for doing this kind of arg-count 
checking, but it looks like we don't have one that takes a range.  Could you 
just generalize `checkArgCount` so that it takes a min and max arg count?  You 
can make the existing function call your generalization.



Comment at: clang/lib/Sema/SemaChecking.cpp:7671
+ AllArgs, CallType))
+return true;
+

You can just pull the argument expressions out of the `CallExpr`; you don't 
need to call `GatherArgumentsForCall`.



Comment at: clang/lib/Sema/SemaChecking.cpp:7684
+  if (FirstArgResult.isInvalid())
+return true;
+

There is in fact a `DefaultFunctionArrayLvalueConversion` method you can use to 
do all of this at once, and you don't need to explicitly check for a function 
or array type first.



Comment at: clang/lib/Sema/SemaChecking.cpp:7690
+  // cast instruction which cast type from user-written-type to VoidPtr in
+  // CodeGen.
+  AllArgs[0] = FirstArgResult.get();

This comment doesn't mean anything in the context of the current 
implementation.  If you want to keep something like it (you really don't need 
to), you could have a comment at the top explaining that we use custom 
type-checking because it accepts an arbitrary pointer type as the first 
argument.



Comment at: clang/lib/Sema/SemaChecking.cpp:7695
+TheCall->setArg(i, AllArgs[i]);
+  TheCall->computeDependence();
+

This is really just `TheCall->setArg(i, FirstArgResult.get())`.



Comment at: clang/lib/Sema/SemaChecking.cpp:7701
   // We can't check the value of a dependent argument.
-  if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
+  if (!SecondArg->isTypeDependent() && !SecondArg->isValueDependent()) {
 llvm::APSInt Result;

Type-dependence implies value-dependence, so you can just check for the latter.

You should call `convertArgumentToType` with `size_t` in this block, just in 
case the argument is something like an l-value reference to a `const` integer 
variable.



Comment at: clang/lib/Sema/SemaChecking.cpp:7719
+Context, Context.getSizeType(), false);
+ThirdArg = PerformCopyInitialization(Entity, SourceLocation(), ThirdArg);
+if (ThirdArg.isInvalid())

You can use `convertArgumentToType` here.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131979

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


[PATCH] D131616: [clang][dataflow] Generalise match switch utility to other AST types and add a `CFGMatchSwitch` which currently handles `CFGStmt` and `CFGInitializer`.

2022-08-31 Thread weiyi via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGc9033eeb2e59: [clang][dataflow] Generalise match switch 
utility to other AST types and add a… (authored by wyt).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131616

Files:
  clang/include/clang/Analysis/FlowSensitive/CFGMatchSwitch.h
  clang/include/clang/Analysis/FlowSensitive/MatchSwitch.h
  clang/unittests/Analysis/FlowSensitive/CFGMatchSwitchTest.cpp
  clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
  clang/unittests/Analysis/FlowSensitive/MatchSwitchTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/MatchSwitchTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/MatchSwitchTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/MatchSwitchTest.cpp
@@ -5,12 +5,6 @@
 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
 //
 //===--===//
-//
-//  This file defines a simplistic version of Constant Propagation as an example
-//  of a forward, monotonic dataflow analysis. The analysis tracks all
-//  variables in the scope, but lacks escape analysis.
-//
-//===--===//
 
 #include "clang/Analysis/FlowSensitive/MatchSwitch.h"
 #include "TestingSupport.h"
Index: clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
===
--- clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
+++ clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
@@ -4,6 +4,7 @@
   )
 
 add_clang_unittest(ClangAnalysisFlowSensitiveTests
+  CFGMatchSwitchTest.cpp
   ChromiumCheckModelTest.cpp
   DataflowAnalysisContextTest.cpp
   DataflowEnvironmentTest.cpp
Index: clang/unittests/Analysis/FlowSensitive/CFGMatchSwitchTest.cpp
===
--- /dev/null
+++ clang/unittests/Analysis/FlowSensitive/CFGMatchSwitchTest.cpp
@@ -0,0 +1,124 @@
+//===- unittests/Analysis/FlowSensitive/CFGMatchSwitchTest.cpp ===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/Analysis/FlowSensitive/CFGMatchSwitch.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/Stmt.h"
+#include "clang/Analysis/CFG.h"
+#include "clang/Tooling/Tooling.h"
+#include "llvm/ADT/StringRef.h"
+#include "gtest/gtest.h"
+
+using namespace clang;
+using namespace dataflow;
+using namespace ast_matchers;
+
+namespace {
+// State for tracking the number of matches on each kind of CFGElement by the
+// CFGMatchSwitch. Currently only tracks CFGStmt and CFGInitializer.
+struct CFGElementMatches {
+  unsigned StmtMatches = 0;
+  unsigned InitializerMatches = 0;
+};
+
+// Returns a match switch that counts the number of local variables
+// (singly-declared) and fields initialized to the integer literal 42.
+auto buildCFGMatchSwitch() {
+  return CFGMatchSwitchBuilder()
+  .CaseOfCFGStmt(
+  declStmt(hasSingleDecl(
+  varDecl(hasInitializer(integerLiteral(equals(42)),
+  [](const DeclStmt *, const MatchFinder::MatchResult &,
+ CFGElementMatches ) { Counter.StmtMatches++; })
+  .CaseOfCFGInit(
+  cxxCtorInitializer(withInitializer(integerLiteral(equals(42,
+  [](const CXXCtorInitializer *, const MatchFinder::MatchResult &,
+ CFGElementMatches ) { Counter.InitializerMatches++; })
+  .Build();
+}
+
+// Runs the match switch `MS` on the control flow graph generated from `Code`,
+// tracking information in state `S`. For simplicity, this test utility is
+// restricted to CFGs with a single control flow block (excluding entry and
+// exit blocks) - generated by `Code` with sequential flow (i.e. no branching).
+//
+// Requirements:
+//
+//  `Code` must contain a function named `f`, the body of this function will be
+//  used to generate the CFG.
+template 
+void applySwitchToCode(CFGMatchSwitch , State ,
+   llvm::StringRef Code) {
+  auto Unit = tooling::buildASTFromCodeWithArgs(Code, {"-Wno-unused-value"});
+  auto  = Unit->getASTContext();
+  const auto *F = selectFirst(
+  "f", match(functionDecl(isDefinition(), hasName("f")).bind("f"), Ctx));
+
+  CFG::BuildOptions BO;
+  BO.AddInitializers = true;
+
+  auto CFG = CFG::buildCFG(F, F->getBody(), , BO);
+  auto CFGBlock = *CFG->getEntry().succ_begin();
+  for (auto  : CFGBlock->Elements) {
+MS(Elt, Ctx, S);
+  }
+}
+
+TEST(CFGMatchSwitchTest, NoInitializationTo42) {
+  CFGMatchSwitch Switch = buildCFGMatchSwitch();
+  

[clang] c9033ee - [clang][dataflow] Generalise match switch utility to other AST types and add a `CFGMatchSwitch` which currently handles `CFGStmt` and `CFGInitializer`.

2022-08-31 Thread Wei Yi Tee via cfe-commits

Author: Wei Yi Tee
Date: 2022-08-31T17:02:07Z
New Revision: c9033eeb2e59c0157b84adfc6b0fe345f6f03113

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

LOG: [clang][dataflow] Generalise match switch utility to other AST types and 
add a `CFGMatchSwitch` which currently handles `CFGStmt` and `CFGInitializer`.

`MatchSwitch` currently takes in matchers and functions for the `Stmt` class.

This patch generalises the match switch utility (renamed to `ASTMatchSwitch`) 
to work for different AST node types by introducing a template argument which 
is the base type for the AST nodes that the match switch will handle.

A `CFGMatchSwitch` is introduced as a wrapper around multiple `ASTMatchSwitch`s 
for different base types. It works by unwrapping `CFGElement`s into their 
contained AST nodes and passing the nodes to the relevant `ASTMatchSwitch`. The 
`CFGMatchSwitch` currently only handles `CFGStmt` and `CFGInitializer`.

Reviewed By: gribozavr2, sgatev

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

Added: 
clang/include/clang/Analysis/FlowSensitive/CFGMatchSwitch.h
clang/unittests/Analysis/FlowSensitive/CFGMatchSwitchTest.cpp

Modified: 
clang/include/clang/Analysis/FlowSensitive/MatchSwitch.h
clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
clang/unittests/Analysis/FlowSensitive/MatchSwitchTest.cpp

Removed: 




diff  --git a/clang/include/clang/Analysis/FlowSensitive/CFGMatchSwitch.h 
b/clang/include/clang/Analysis/FlowSensitive/CFGMatchSwitch.h
new file mode 100644
index 0..ecd8558970f93
--- /dev/null
+++ b/clang/include/clang/Analysis/FlowSensitive/CFGMatchSwitch.h
@@ -0,0 +1,98 @@
+//=== CFGMatchSwitch.h --*- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file defines the `CFGMatchSwitch` abstraction for building a "switch"
+//  statement for control flow graph elements. Each case of the switch is
+//  defined by an ASTMatcher which is applied on the AST node contained in the
+//  input `CFGElement`.
+//
+//  Currently, the `CFGMatchSwitch` only handles `CFGElement`s of
+//  `Kind::Statement` and `Kind::Initializer`.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_CFGMATCHSWITCH_H_
+#define LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_CFGMATCHSWITCH_H_
+
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Stmt.h"
+#include "clang/Analysis/CFG.h"
+#include "clang/Analysis/FlowSensitive/MatchSwitch.h"
+#include 
+#include 
+
+namespace clang {
+namespace dataflow {
+
+template 
+using CFGMatchSwitch =
+std::function;
+
+/// Collects cases of a "match switch": a collection of matchers paired with
+/// callbacks, which together define a switch that can be applied to an AST 
node
+/// contained in a CFG element.
+template  class CFGMatchSwitchBuilder {
+public:
+  /// Registers an action `A` for `CFGStmt`s that will be triggered by the 
match
+  /// of the pattern `M` against the `Stmt` contained in the input `CFGStmt`.
+  ///
+  /// Requirements:
+  ///
+  ///  `NodeT` should be derived from `Stmt`.
+  template 
+  CFGMatchSwitchBuilder &&
+  CaseOfCFGStmt(MatchSwitchMatcher M,
+MatchSwitchAction A) && {
+std::move(StmtBuilder).template CaseOf(M, A);
+return std::move(*this);
+  }
+
+  /// Registers an action `A` for `CFGInitializer`s that will be triggered by
+  /// the match of the pattern `M` against the `CXXCtorInitializer` contained 
in
+  /// the input `CFGInitializer`.
+  ///
+  /// Requirements:
+  ///
+  ///  `NodeT` should be derived from `CXXCtorInitializer`.
+  template 
+  CFGMatchSwitchBuilder &&
+  CaseOfCFGInit(MatchSwitchMatcher M,
+MatchSwitchAction A) && {
+std::move(InitBuilder).template CaseOf(M, A);
+return std::move(*this);
+  }
+
+  CFGMatchSwitch Build() && {
+return [StmtMS = std::move(StmtBuilder).Build(),
+InitMS = std::move(InitBuilder).Build()](const CFGElement ,
+ ASTContext ,
+ State ) -> Result {
+  switch (Element.getKind()) {
+  case CFGElement::Initializer:
+return InitMS(*Element.castAs().getInitializer(),
+  Context, S);
+  case CFGElement::Statement:
+  case CFGElement::Constructor:
+  case CFGElement::CXXRecordTypedCall:
+return StmtMS(*Element.castAs().getStmt(), Context, S);
+  default:
+  

[PATCH] D132568: [clang][Sema] check default argument promotions for printf

2022-08-31 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.

Basically LGTM as well, just some nits about comments and a small fix to the c 
status page.

In D132568#3753512 , @inclyc wrote:

> Currently this patch has not fully implemented `wchar_t` related support, this
> type seems to be even platform dependent in C language, if possible, maybe we
> can consider support in subsequent patches?

I think that's reasonable.




Comment at: clang/lib/AST/FormatString.cpp:360
+  if (const auto *BT = argTy->getAs()) {
+// the types are perfectly matched?
 switch (BT->getKind()) {





Comment at: clang/lib/AST/FormatString.cpp:371
+}
+// "partially matched" because of promotions?
+if (!Ptr) {





Comment at: clang/lib/AST/FormatString.cpp:404
+  if (const auto *BT = argTy->getAs()) {
+// check if the only difference between them is signed vs unsigned
+// if true, we consider they are compatible.





Comment at: clang/lib/AST/FormatString.cpp:452
+  }
+  // "partially matched" because of promotions?
+  if (!Ptr) {





Comment at: clang/lib/AST/FormatString.cpp:401
+  if (const auto *BT = argTy->getAs()) {
+if (!Ptr) {
+  switch (BT->getKind()) {

nickdesaulniers wrote:
> inclyc wrote:
> > nickdesaulniers wrote:
> > > aaron.ballman wrote:
> > > > It's a bit strange that we have two switches over the same 
> > > > `BT->getKind()` and the only difference is `!Ptr`; would it be easier 
> > > > to read if we combined the two switches into one and had logic in the 
> > > > individual cases for `Ptr` vs not `Ptr`?
> > > I almost made the same recommendation myself.  For the below switch pair, 
> > > and the pair above.
> > > It's a bit strange that we have two switches over the same 
> > > `BT->getKind()` and the only difference is `!Ptr`; would it be easier to 
> > > read if we combined the two switches into one and had logic in the 
> > > individual cases for `Ptr` vs not `Ptr`?
> > 
> > These two switch pairs have different functions. The lower one is only 
> > responsible for checking whether there is a signed or unsigned integer, and 
> > the upper one is checking whether there is a promotion (or type confusing). 
> > Will they be more difficult to understand if they are written together? 
> Perhaps.  I think the comments you added to all switches are helpful!
Yeah, let's leave the structure be for now, we can always clarify it further in 
an NFC follow-up if it turns out to be a reasonable suggestion.



Comment at: clang/lib/Sema/SemaChecking.cpp:10123-10125
+// Consider character literal is a 'char' in C
+// printf("%hd", 'a'); is more likey a type confusion situation
+// We will suggest our users to use %hhd by discarding MatchPromotion





Comment at: clang/lib/Sema/SemaChecking.cpp:10131
+  if (Match == ArgType::MatchPromotion) {
+if (!S.getLangOpts().ObjC &&
+ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&

We should probably have a comment here about why ObjC is special..



Comment at: clang/www/c_status.html:822
   https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2562.pdf;>N2562
-  
-Partial
-  Clang supports diagnostics checking format specifier validity, but
-  does not yet account for all of the changes in this paper, especially
-  regarding length modifiers like h and hh.
-
-  
+  Clang 16
 




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132568

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


[clang] 83902c4 - Reapply "[clang][deps] Split translation units into individual -cc1 or other commands"

2022-08-31 Thread Ben Langmuir via cfe-commits

Author: Ben Langmuir
Date: 2022-08-31T09:45:11-07:00
New Revision: 83902c403611af3a52453867cb8848fb3fd6a39c

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

LOG: Reapply "[clang][deps] Split translation units into individual -cc1 or 
other commands"

Attempt to fix the test failures observed in CI:
* Add Option dependency, which caused BUILD_SHARED_LIBS builds to fail
* Adapt tests that accidentally depended on the host platform: platforms
  that don't use an integrated assembler (e.g. AIX) get a different set
  of commands from the driver. Most dependency scanner tests can use
  -fsyntax-only or -E instead of -c to avoid this, and in the rare case
  we want to check -c specifically, set an explicit target so the
  behaviour is independent of the host.

Original commit message follows.

---

Instead of trying to "fix" the original driver invocation by appending
arguments to it, split it into multiple commands, and for each -cc1
command use a CompilerInvocation to give precise control over the
invocation.

This change should make it easier to (in the future) canonicalize the
command-line (e.g. to improve hits in something like ccache), apply
optimizations, or start supporting multi-arch builds, which would
require different modules for each arch.

In the long run it may make sense to treat the TU commands as a
dependency graph, each with their own dependencies on modules or earlier
TU commands, but for now they are simply a list that is executed in
order, and the dependencies are simply duplicated. Since we currently
only support single-arch builds, there is no parallelism available in
the execution.

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

Added: 
clang/test/ClangScanDeps/deprecated-driver-api.c
clang/test/ClangScanDeps/multiple-commands.c

Modified: 
clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h
clang/include/clang/Tooling/DependencyScanning/DependencyScanningWorker.h
clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
clang/lib/Tooling/DependencyScanning/CMakeLists.txt
clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
clang/test/ClangScanDeps/diagnostics.c
clang/test/ClangScanDeps/header-search-pruning-transitive.c
clang/test/ClangScanDeps/modules-context-hash-ignore-macros.c
clang/test/ClangScanDeps/modules-context-hash-outputs.c
clang/test/ClangScanDeps/modules-context-hash-warnings.c
clang/test/ClangScanDeps/modules-context-hash.c
clang/test/ClangScanDeps/modules-dep-args.c
clang/test/ClangScanDeps/modules-fmodule-name-no-module-built.m
clang/test/ClangScanDeps/modules-full.cpp
clang/test/ClangScanDeps/modules-implicit-dot-private.m
clang/test/ClangScanDeps/modules-incomplete-umbrella.c
clang/test/ClangScanDeps/modules-inferred.m
clang/test/ClangScanDeps/modules-no-undeclared-includes.c
clang/test/ClangScanDeps/modules-pch-common-submodule.c
clang/test/ClangScanDeps/modules-pch-common-via-submodule.c
clang/test/ClangScanDeps/modules-pch.c
clang/test/ClangScanDeps/removed-args.c
clang/tools/clang-scan-deps/ClangScanDeps.cpp
clang/utils/module-deps-to-rsp.py

Removed: 




diff  --git 
a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h 
b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h
index cc3f330828a39..c0d273297f18f 100644
--- a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h
+++ b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h
@@ -49,8 +49,16 @@ struct FullDependencies {
   /// determined that the 
diff erences are benign for this compilation.
   std::vector ClangModuleDeps;
 
-  /// The command line of the TU (excluding the compiler executable).
-  std::vector CommandLine;
+  /// The sequence of commands required to build the translation unit. Commands
+  /// should be executed in order.
+  ///
+  /// FIXME: If we add support for multi-arch builds in clang-scan-deps, we
+  /// should make the dependencies between commands explicit to enable parallel
+  /// builds of each architecture.
+  std::vector Commands;
+
+  /// Deprecated driver command-line. This will be removed in a future version.
+  std::vector DriverCommandLine;
 };
 
 struct FullDependenciesResult {
@@ -99,6 +107,12 @@ class DependencyScanningTool {
   LookupModuleOutputCallback LookupModuleOutput,
   llvm::Optional ModuleName = None);
 
+  llvm::Expected 
getFullDependenciesLegacyDriverCommand(
+  const std::vector , StringRef CWD,
+  const llvm::StringSet<> ,
+

[PATCH] D132932: [Clang][Comments] Parse `` in doc comments correctly

2022-08-31 Thread Egor Zhdan via Phabricator via cfe-commits
egorzhdan updated this revision to Diff 456989.
egorzhdan added a comment.

Rebase to apply fixes to string conversion


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132932

Files:
  clang/lib/AST/CommentLexer.cpp
  clang/test/Index/comment-to-html-xml-conversion.cpp
  clang/test/Sema/warn-documentation.cpp

Index: clang/test/Sema/warn-documentation.cpp
===
--- clang/test/Sema/warn-documentation.cpp
+++ clang/test/Sema/warn-documentation.cpp
@@ -62,6 +62,21 @@
 /// 
 int test_html11(int);
 
+/// Aaa bbb
+int test_html12(int);
+
+/// Aaa bbb
+int test_html13(int);
+
+/// Aaa bbb
+int test_html14(int);
+
+/// Aaa bbb
+int test_html15(int);
+
+/// Aaa bbb
+int test_html16(int);
+
 /// Meow
 int test_html_nesting1(int);
 
Index: clang/test/Index/comment-to-html-xml-conversion.cpp
===
--- clang/test/Index/comment-to-html-xml-conversion.cpp
+++ clang/test/Index/comment-to-html-xml-conversion.cpp
@@ -744,6 +744,26 @@
 // CHECK-NEXT: (CXComment_Text Text=[ ] IsWhitespace)
 // CHECK-NEXT: (CXComment_InlineCommand CommandName=[anchor] RenderAnchor Arg[0]=A)))]
 
+/// Aaa bbb
+void comment_to_html_conversion_38();
+
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:6: FunctionDecl=comment_to_html_conversion_38:{{.*}} FullCommentAsHTML=[ Aaa bbb] FullCommentAsXML=[comment_to_html_conversion_38c:@F@comment_to_html_conversion_38#void comment_to_html_conversion_38() Aaa bbb]
+// CHECK-NEXT:  CommentAST=[
+// CHECK-NEXT:(CXComment_FullComment
+// CHECK-NEXT:   (CXComment_Paragraph
+// CHECK-NEXT: (CXComment_Text Text=[ Aaa bbb])
+// CHECK-NEXT: (CXComment_HTMLStartTag Name=[img] SelfClosing)
+
+/// Aaa ccc
+void comment_to_html_conversion_39();
+
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:6: FunctionDecl=comment_to_html_conversion_39:{{.*}} FullCommentAsHTML=[ Aaa ccc] FullCommentAsXML=[comment_to_html_conversion_39c:@F@comment_to_html_conversion_39#void comment_to_html_conversion_39() Aaa ccc]
+// CHECK-NEXT:  CommentAST=[
+// CHECK-NEXT:(CXComment_FullComment
+// CHECK-NEXT:   (CXComment_Paragraph
+// CHECK-NEXT: (CXComment_Text Text=[ Aaa ccc])
+// CHECK-NEXT: (CXComment_HTMLStartTag Name=[img] SelfClosing)
+
 /// Aaa ccc
 void comment_to_html_conversion_40();
 
@@ -754,6 +774,36 @@
 // CHECK-NEXT: (CXComment_Text Text=[ Aaa ccc])
 // CHECK-NEXT: (CXComment_HTMLStartTag Name=[img] Attrs: src=)
 
+/// Aaa ccc
+void comment_to_html_conversion_41();
+
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:6: FunctionDecl=comment_to_html_conversion_41:{{.*}} FullCommentAsHTML=[ Aaa ccc] FullCommentAsXML=[comment_to_html_conversion_41c:@F@comment_to_html_conversion_41#void comment_to_html_conversion_41() Aaa ccc]
+// CHECK-NEXT:  CommentAST=[
+// CHECK-NEXT:(CXComment_FullComment
+// CHECK-NEXT:   (CXComment_Paragraph
+// CHECK-NEXT: (CXComment_Text Text=[ Aaa ccc])
+// CHECK-NEXT: (CXComment_HTMLStartTag Name=[img] Attrs: src=path)
+
+/// Aaa ccc
+void comment_to_html_conversion_42();
+
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:6: FunctionDecl=comment_to_html_conversion_42:{{.*}} FullCommentAsHTML=[ Aaa ccc] FullCommentAsXML=[comment_to_html_conversion_42c:@F@comment_to_html_conversion_42#void comment_to_html_conversion_42() Aaa ccc]
+// CHECK-NEXT:  CommentAST=[
+// CHECK-NEXT:(CXComment_FullComment
+// CHECK-NEXT:   (CXComment_Paragraph
+// CHECK-NEXT: (CXComment_Text Text=[ Aaa ccc])
+// CHECK-NEXT: (CXComment_HTMLStartTag Name=[img] Attrs: src=path SelfClosing)
+
+/// Aaa ddd
+void comment_to_html_conversion_43();
+
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:6: FunctionDecl=comment_to_html_conversion_43:{{.*}} FullCommentAsHTML=[ Aaa ddd] FullCommentAsXML=[comment_to_html_conversion_43c:@F@comment_to_html_conversion_43#void comment_to_html_conversion_43() Aaa ddd]
+// CHECK-NEXT:  CommentAST=[
+// CHECK-NEXT:(CXComment_FullComment
+// CHECK-NEXT:   (CXComment_Paragraph
+// CHECK-NEXT: (CXComment_Text Text=[ Aaa ddd])
+// CHECK-NEXT: (CXComment_HTMLStartTag Name=[img] Attrs: src= SelfClosing)
+
 /// Aaa.
 class comment_to_xml_conversion_01 {
 // CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-1]]:7: ClassDecl=comment_to_xml_conversion_01:{{.*}} FullCommentAsXML=[comment_to_xml_conversion_01c:@S@comment_to_xml_conversion_01class comment_to_xml_conversion_01 {} Aaa.]
Index: clang/lib/AST/CommentLexer.cpp
===
--- clang/lib/AST/CommentLexer.cpp
+++ clang/lib/AST/CommentLexer.cpp
@@ -701,7 +701,7 @@
 
   C = *BufferPtr;
   if (!isHTMLIdentifierStartingCharacter(C) &&
-  C != '=' && C != '\"' && C != '\'' && C != '>') {
+  C != '=' && C 

[PATCH] D131563: [clang] Fix clang multiarch isssue with musl

2022-08-31 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay requested changes to this revision.
MaskRay added a comment.
This revision now requires changes to proceed.

This may not be the right direction. If GCC is not configured with 
`--enable-multi-arch`, `--print-multiarch` output is an empty line.
The `x86_64-linux-gnu` style output is for Debian and its derivatives which 
omit `vendor` in the target triple.
Clang just prints this unconditionally, but the string is not really expected 
for non-Debian distributions.

If a build system needs to detect this (it really shouldn't), it probably 
should hard code Debian hierarchy, instead of expecting Clang to do something.


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

https://reviews.llvm.org/D131563

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


[PATCH] D132131: [clang-format] Adds a formatter for aligning trailing comments over empty lines

2022-08-31 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks added inline comments.



Comment at: clang/include/clang/Format/Format.h:141
 
-  /// Alignment options.
-  ///
-  /// They can also be read as a whole for compatibility. The choices are:
+  /// Alignment styles of ``AlignConsecutiveStyle`` are:
   /// - None

That I wouldn't change.



Comment at: clang/include/clang/Format/Format.h:154
   /// \code
   ///   AlignConsecutiveMacros: AcrossEmptyLines
   ///

The change/addition has to be here, since here it directly states 
`AlignConsecutiveMacros`.



Comment at: clang/unittests/Format/FormatTestComments.cpp:2863
+  FormatStyle Style = getLLVMStyle();
+  Style.AlignConsecutiveTrailingComments.AcrossEmptyLines = true;
+  verifyFormat("#include \"a.h\"  // simple\n"

yusuke-kadowaki wrote:
> HazardyKnusperkeks wrote:
> > Interesting would be a comment which is split, do we continue to align, or 
> > not?
> Could you give me a specific example?
Something like
```
int foo = 2323234; // Comment
int bar = 52323;   // This is a very long comment, ...
   // which is wrapped around.

int x = 2; // Is this still aligned?
```
You may need to make the comment longer or reduce the column limit, as often 
used for testing the wrapping behavior.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132131

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


[PATCH] D133009: [libclang] Fix conversion from `StringRef` to `CXString`

2022-08-31 Thread Egor Zhdan via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG8c0935238527: [libclang] Fix conversion from `StringRef` to 
`CXString` (authored by egorzhdan).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133009

Files:
  clang/test/Index/comment-lots-of-unknown-commands.c
  clang/test/Index/comment-to-html-xml-conversion.cpp
  clang/tools/libclang/CXString.cpp


Index: clang/tools/libclang/CXString.cpp
===
--- clang/tools/libclang/CXString.cpp
+++ clang/tools/libclang/CXString.cpp
@@ -78,13 +78,22 @@
 }
 
 CXString createRef(StringRef String) {
+  if (!String.data())
+return createNull();
+
+  // If the string is empty, it might point to a position in another string
+  // while having zero length. Make sure we don't create a reference to the
+  // larger string.
+  if (String.empty())
+return createEmpty();
+
   // If the string is not nul-terminated, we have to make a copy.
 
   // FIXME: This is doing a one past end read, and should be removed! For 
memory
   // we don't manage, the API string can become unterminated at any time 
outside
   // our control.
 
-  if (!String.empty() && String.data()[String.size()] != 0)
+  if (String.data()[String.size()] != 0)
 return createDup(String);
 
   CXString Result;
Index: clang/test/Index/comment-to-html-xml-conversion.cpp
===
--- clang/test/Index/comment-to-html-xml-conversion.cpp
+++ clang/test/Index/comment-to-html-xml-conversion.cpp
@@ -744,6 +744,15 @@
 // CHECK-NEXT: (CXComment_Text Text=[ ] IsWhitespace)
 // CHECK-NEXT: (CXComment_InlineCommand CommandName=[anchor] 
RenderAnchor Arg[0]=A)))]
 
+/// Aaa ccc
+void comment_to_html_conversion_40();
+
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:6: 
FunctionDecl=comment_to_html_conversion_40:{{.*}} FullCommentAsHTML=[ Aaa ccc] FullCommentAsXML=[comment_to_html_conversion_40c:@F@comment_to_html_conversion_40#void
 comment_to_html_conversion_40() Aaa 
ccc]
+// CHECK-NEXT:  CommentAST=[
+// CHECK-NEXT:(CXComment_FullComment
+// CHECK-NEXT:   (CXComment_Paragraph
+// CHECK-NEXT: (CXComment_Text Text=[ Aaa ccc])
+// CHECK-NEXT: (CXComment_HTMLStartTag Name=[img] Attrs: src=)
 
 /// Aaa.
 class comment_to_xml_conversion_01 {
Index: clang/test/Index/comment-lots-of-unknown-commands.c
===
--- clang/test/Index/comment-lots-of-unknown-commands.c
+++ clang/test/Index/comment-lots-of-unknown-commands.c
@@ -1,5 +1,7 @@
 // RUN: c-index-test -test-load-source-reparse 1 local %s | FileCheck %s
 
+// XFAIL: *
+
 // See PR 21254. We had too few bits to encode command IDs so if you created
 // enough of them the ID codes would wrap around. This test creates commands up
 // to an ID of 258. Ideally we should check for large numbers, but that would


Index: clang/tools/libclang/CXString.cpp
===
--- clang/tools/libclang/CXString.cpp
+++ clang/tools/libclang/CXString.cpp
@@ -78,13 +78,22 @@
 }
 
 CXString createRef(StringRef String) {
+  if (!String.data())
+return createNull();
+
+  // If the string is empty, it might point to a position in another string
+  // while having zero length. Make sure we don't create a reference to the
+  // larger string.
+  if (String.empty())
+return createEmpty();
+
   // If the string is not nul-terminated, we have to make a copy.
 
   // FIXME: This is doing a one past end read, and should be removed! For memory
   // we don't manage, the API string can become unterminated at any time outside
   // our control.
 
-  if (!String.empty() && String.data()[String.size()] != 0)
+  if (String.data()[String.size()] != 0)
 return createDup(String);
 
   CXString Result;
Index: clang/test/Index/comment-to-html-xml-conversion.cpp
===
--- clang/test/Index/comment-to-html-xml-conversion.cpp
+++ clang/test/Index/comment-to-html-xml-conversion.cpp
@@ -744,6 +744,15 @@
 // CHECK-NEXT: (CXComment_Text Text=[ ] IsWhitespace)
 // CHECK-NEXT: (CXComment_InlineCommand CommandName=[anchor] RenderAnchor Arg[0]=A)))]
 
+/// Aaa ccc
+void comment_to_html_conversion_40();
+
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:6: FunctionDecl=comment_to_html_conversion_40:{{.*}} FullCommentAsHTML=[ Aaa ccc] FullCommentAsXML=[comment_to_html_conversion_40c:@F@comment_to_html_conversion_40#void comment_to_html_conversion_40() Aaa ccc]
+// CHECK-NEXT:  CommentAST=[
+// CHECK-NEXT:(CXComment_FullComment
+// CHECK-NEXT:   (CXComment_Paragraph
+// CHECK-NEXT: (CXComment_Text Text=[ Aaa ccc])
+// CHECK-NEXT: (CXComment_HTMLStartTag Name=[img] Attrs: src=)
 
 /// Aaa.
 class 

[clang] 8c09352 - [libclang] Fix conversion from `StringRef` to `CXString`

2022-08-31 Thread Egor Zhdan via cfe-commits

Author: Egor Zhdan
Date: 2022-08-31T17:39:45+01:00
New Revision: 8c0935238527622ba0a7e78e8a1ee2d36026961c

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

LOG: [libclang] Fix conversion from `StringRef` to `CXString`

`CXString createRef(StringRef String)` used to return an invalid string when 
invoked with some empty strings:

If a `StringRef` holds a non-nullptr pointer, for instance, pointing into 
contents of a larger string, and has a zero length, `createRef` previously 
returned the entire larger string, ignoring the fact that the actual string 
passed to it as a param is empty.

This was discovered when invoking `c-index-test` to dump the contents of 
documentation comments, in case the comment contains an empty HTML attribute, 
such as `src=""`.

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

Added: 


Modified: 
clang/test/Index/comment-lots-of-unknown-commands.c
clang/test/Index/comment-to-html-xml-conversion.cpp
clang/tools/libclang/CXString.cpp

Removed: 




diff  --git a/clang/test/Index/comment-lots-of-unknown-commands.c 
b/clang/test/Index/comment-lots-of-unknown-commands.c
index 119a34566094c..41a03d394488c 100644
--- a/clang/test/Index/comment-lots-of-unknown-commands.c
+++ b/clang/test/Index/comment-lots-of-unknown-commands.c
@@ -1,5 +1,7 @@
 // RUN: c-index-test -test-load-source-reparse 1 local %s | FileCheck %s
 
+// XFAIL: *
+
 // See PR 21254. We had too few bits to encode command IDs so if you created
 // enough of them the ID codes would wrap around. This test creates commands up
 // to an ID of 258. Ideally we should check for large numbers, but that would

diff  --git a/clang/test/Index/comment-to-html-xml-conversion.cpp 
b/clang/test/Index/comment-to-html-xml-conversion.cpp
index bba5cf8f0bf42..1fedd382365cf 100644
--- a/clang/test/Index/comment-to-html-xml-conversion.cpp
+++ b/clang/test/Index/comment-to-html-xml-conversion.cpp
@@ -744,6 +744,15 @@ void comment_to_html_conversion_37();
 // CHECK-NEXT: (CXComment_Text Text=[ ] IsWhitespace)
 // CHECK-NEXT: (CXComment_InlineCommand CommandName=[anchor] 
RenderAnchor Arg[0]=A)))]
 
+/// Aaa ccc
+void comment_to_html_conversion_40();
+
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:6: 
FunctionDecl=comment_to_html_conversion_40:{{.*}} FullCommentAsHTML=[ Aaa ccc] FullCommentAsXML=[comment_to_html_conversion_40c:@F@comment_to_html_conversion_40#void
 comment_to_html_conversion_40() Aaa 
ccc]
+// CHECK-NEXT:  CommentAST=[
+// CHECK-NEXT:(CXComment_FullComment
+// CHECK-NEXT:   (CXComment_Paragraph
+// CHECK-NEXT: (CXComment_Text Text=[ Aaa ccc])
+// CHECK-NEXT: (CXComment_HTMLStartTag Name=[img] Attrs: src=)
 
 /// Aaa.
 class comment_to_xml_conversion_01 {

diff  --git a/clang/tools/libclang/CXString.cpp 
b/clang/tools/libclang/CXString.cpp
index 2754795f4a647..5e427957a1092 100644
--- a/clang/tools/libclang/CXString.cpp
+++ b/clang/tools/libclang/CXString.cpp
@@ -78,13 +78,22 @@ CXString createDup(const char *String) {
 }
 
 CXString createRef(StringRef String) {
+  if (!String.data())
+return createNull();
+
+  // If the string is empty, it might point to a position in another string
+  // while having zero length. Make sure we don't create a reference to the
+  // larger string.
+  if (String.empty())
+return createEmpty();
+
   // If the string is not nul-terminated, we have to make a copy.
 
   // FIXME: This is doing a one past end read, and should be removed! For 
memory
   // we don't manage, the API string can become unterminated at any time 
outside
   // our control.
 
-  if (!String.empty() && String.data()[String.size()] != 0)
+  if (String.data()[String.size()] != 0)
 return createDup(String);
 
   CXString Result;



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


[PATCH] D132568: [clang][Sema] check default argument promotions for printf

2022-08-31 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers accepted this revision.
nickdesaulniers added a comment.
This revision is now accepted and ready to land.

@aaron.ballman should review+accept this before you land it, but I'm satisfied 
with the result. Thank you @inclyc for working on this!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132568

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


[PATCH] D132142: [analyzer] Prefer wrapping SymbolicRegions by ElementRegions

2022-08-31 Thread Gabor Marton via Phabricator via cfe-commits
martong accepted this revision.
martong added a comment.
This revision is now accepted and ready to land.

I am okay with this change, it does give a proper canonical form, which is 
good. On the other hand, I agree that (on the long term) base regions and 
offsets would be a better memory model than what we have now with field and 
element regions.




Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h:799
+  /// we actually know their types.
+  QualType getApproximatedType() const {
+return sym->getType()->getPointeeType();

I think we should express that this returns the


  - type of the pointee
  - the type that is the "static" type, id est, the type of the declaration; 
`void`, `char` and `base` in your example above.

In this sense, what about `getPointeeStaticType`?





Comment at: clang/test/Analysis/ctor.mm:221
   clang_analyzer_eval(p4.x > 0); // expected-warning{{TRUE}}
-// FIXME: Element region gets in the way, so these aren't the same symbols
-// as they should be.
-clang_analyzer_eval(pp.x == p4.x); // expected-warning{{UNKNOWN}}
+clang_analyzer_eval(pp.x == p4.x); // expected-warning{{TRUE}}
 

Nice!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132142

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


[PATCH] D129488: [Sema] Delay evaluation of std::source_location::current() in default arguments

2022-08-31 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

In D129488#3761398 , @jyknight wrote:

> I believe this should print `fn=14 fn2=14`. I don't see how we can get that 
> by special-casing calls to `std::source_location::current`, and indeed, with 
> this version of the patch, the program instead prints `fn=14 fn2=9`.

There is another issue in Clang that prevents it from producing correct results 
with this patch. We should not evaluate immediate calls inside default 
arguments of immediate function parameters as they are deemed to be inside the 
immediate function context . Clang 
currently evaluates these calls as all parameter scopes are 
`PotentiallyEvaluatedIfUsed` and `ImmediateFunctionContext` is a different 
value inside the same enumeration :)

Notice how GCC does not produce an error here as it does not attempt to run the 
invalid constant calculation:
https://gcc.godbolt.org/z/Encr3Kzbs
I believe the GCC behavior is correct here. If we fix this bug, Clang will stop 
producing an error too and we will have the behavior you described.

The results of calling `fn()` are also different if you do it inside a default 
argument for non-consteval function (I use `constexpr` here for static assert, 
but dynamic calls will give the same result):
https://gcc.godbolt.org/z/P1x8PGsh6
MSVC and GCC disagree about the value for a recursive call here, I would say 
that GCC behavior seems reasonable to me (it evaluates consteval calls at the 
first non-immediate function context).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129488

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


[PATCH] D129008: [Clang][OpenMP] Fix the issue that globalization doesn't work with byval struct function argument

2022-08-31 Thread Shilei Tian via Phabricator via cfe-commits
tianshilei1992 added a comment.

In D129008#3640233 , @jdoerfert wrote:

> In D129008#3640194 , 
> @tianshilei1992 wrote:
>
>> `callCStructCopyConstructor` is actually for Objective-C…Cannot use it here.
>
> Don't we generate copies of things elsewhere already?

No we don't. I think the best place to emit copy is where the globalized 
variable is generated.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129008

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


[PATCH] D132962: [clangd][ObjC] Improve completions for protocols + category names

2022-08-31 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added a comment.

can you also add test cases for the other two (filtering both for speculative 
index queries/regular ones, and making sure we don't suggest symbols from index 
for category names), so that we don't regress in the future?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132962

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


[PATCH] D132756: [clang][dataflow] Refactor `TypeErasedDataflowAnalysisTest` - replace usage of the deprecated overload of `checkDataflow`.

2022-08-31 Thread weiyi via Phabricator via cfe-commits
wyt updated this revision to Diff 456986.
wyt added a comment.

Update according to change in preceding patches to replace use of designated 
initialisers when constructing `AnalysisInputs`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132756

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

Index: clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
@@ -24,8 +24,10 @@
 #include "llvm/ADT/Optional.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallSet.h"
+#include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Error.h"
+#include "llvm/Testing/ADT/StringMapEntry.h"
 #include "llvm/Testing/Support/Error.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
@@ -42,12 +44,10 @@
 using namespace dataflow;
 using namespace test;
 using namespace ast_matchers;
-using ::testing::_;
-using ::testing::ElementsAre;
+using llvm::IsStringMapEntry;
+using ::testing::DescribeMatcher;
 using ::testing::IsEmpty;
-using ::testing::IsNull;
 using ::testing::NotNull;
-using ::testing::Pair;
 using ::testing::Test;
 using ::testing::UnorderedElementsAre;
 
@@ -129,7 +129,8 @@
 }
 
 struct FunctionCallLattice {
-  llvm::SmallSet CalledFunctions;
+  using FunctionSet = llvm::SmallSet;
+  FunctionSet CalledFunctions;
 
   bool operator==(const FunctionCallLattice ) const {
 return CalledFunctions == Other.CalledFunctions;
@@ -195,16 +196,20 @@
 
 ASSERT_THAT_ERROR(
 test::checkDataflow(
-Code, "target",
-[](ASTContext , Environment &) {
-  return FunctionCallAnalysis(C);
-},
+AnalysisInputs(
+Code, ast_matchers::hasName("target"),
+[](ASTContext , Environment &) {
+  return FunctionCallAnalysis(C);
+})
+.withASTBuildArgs({"-fsyntax-only", "-std=c++17"})
+.withASTBuildVirtualMappedFiles(std::move(FilesContents)),
+/*VerifyResults=*/
 [](
-llvm::ArrayRef>>
-Results,
-ASTContext &) { EXPECT_THAT(Results, Expectations); },
-{"-fsyntax-only", "-std=c++17"}, FilesContents),
+const llvm::StringMap<
+DataflowAnalysisState> ,
+const AnalysisOutputs &) {
+  EXPECT_THAT(Results, Expectations);
+}),
 llvm::Succeeded());
   }
 };
@@ -212,12 +217,16 @@
 MATCHER_P(HoldsFunctionCallLattice, m,
   ((negation ? "doesn't hold" : "holds") +
llvm::StringRef(" a lattice element that ") +
-   ::testing::DescribeMatcher(m, negation))
+   DescribeMatcher(m))
   .str()) {
   return ExplainMatchResult(m, arg.Lattice, result_listener);
 }
 
-MATCHER_P(HasCalledFunctions, m, "") {
+MATCHER_P(HasCalledFunctions, m,
+  ((negation ? "doesn't hold" : "holds") +
+   llvm::StringRef(" a set of called functions that ") +
+   DescribeMatcher(m))
+  .str()) {
   return ExplainMatchResult(m, arg.CalledFunctions, result_listener);
 }
 
@@ -231,9 +240,9 @@
   // [[p]]
 }
   )";
-  runDataflow(Code, UnorderedElementsAre(
-Pair("p", HoldsFunctionCallLattice(HasCalledFunctions(
-  UnorderedElementsAre("foo", "bar"));
+  runDataflow(Code, UnorderedElementsAre(IsStringMapEntry(
+"p", HoldsFunctionCallLattice(HasCalledFunctions(
+ UnorderedElementsAre("foo", "bar"));
 }
 
 TEST_F(NoreturnDestructorTest, ConditionalOperatorLeftBranchReturns) {
@@ -246,9 +255,9 @@
   // [[p]]
 }
   )";
-  runDataflow(Code, UnorderedElementsAre(
-Pair("p", HoldsFunctionCallLattice(HasCalledFunctions(
-  UnorderedElementsAre("foo"));
+  runDataflow(Code, UnorderedElementsAre(IsStringMapEntry(
+"p", HoldsFunctionCallLattice(HasCalledFunctions(
+ UnorderedElementsAre("foo"));
 }
 
 TEST_F(NoreturnDestructorTest, ConditionalOperatorRightBranchReturns) {
@@ -261,9 +270,9 @@
   // [[p]]
 }
   )";
-  runDataflow(Code, UnorderedElementsAre(
-Pair("p", HoldsFunctionCallLattice(HasCalledFunctions(
-  UnorderedElementsAre("foo"));
+  runDataflow(Code, UnorderedElementsAre(IsStringMapEntry(
+"p", HoldsFunctionCallLattice(HasCalledFunctions(
+   

[PATCH] D132763: [clang][dataflow] Use `StringMap` for storing analysis states at annotated points instead of `vector>`.

2022-08-31 Thread weiyi via Phabricator via cfe-commits
wyt updated this revision to Diff 456983.
wyt added a comment.

Propagate change from parent patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132763

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

Index: clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
@@ -426,12 +426,12 @@
std::pair>>
Results,
ASTContext ) {
-ASSERT_THAT(Results, ElementsAre(Pair("p4", _), Pair("p3", _),
- Pair("p2", _), Pair("p1", _)));
-const Environment  = Results[3].second.Env;
-const Environment  = Results[2].second.Env;
-const Environment  = Results[1].second.Env;
-const Environment  = Results[0].second.Env;
+ASSERT_THAT(Results, ElementsAre(Pair("p1", _), Pair("p2", _),
+ Pair("p3", _), Pair("p4", _)));
+const Environment  = Results[0].second.Env;
+const Environment  = Results[1].second.Env;
+const Environment  = Results[2].second.Env;
+const Environment  = Results[3].second.Env;
 
 const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
 ASSERT_THAT(FooDecl, NotNull());
@@ -579,10 +579,10 @@
  Results,
  ASTContext ) {
 ASSERT_THAT(Results,
-ElementsAre(Pair("p3", _), Pair("p2", _), Pair("p1", _)));
-const Environment  = Results[2].second.Env;
+ElementsAre(Pair("p1", _), Pair("p2", _), Pair("p3", _)));
+const Environment  = Results[0].second.Env;
 const Environment  = Results[1].second.Env;
-const Environment  = Results[0].second.Env;
+const Environment  = Results[2].second.Env;
 
 const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
 ASSERT_THAT(FooDecl, NotNull());
@@ -622,12 +622,12 @@
  std::pair>>
  Results,
  ASTContext ) {
-ASSERT_THAT(Results, ElementsAre(Pair("p4", _), Pair("p3", _),
- Pair("p2", _), Pair("p1", _)));
-const Environment  = Results[3].second.Env;
-const Environment  = Results[2].second.Env;
-const Environment  = Results[1].second.Env;
-const Environment  = Results[0].second.Env;
+ASSERT_THAT(Results, ElementsAre(Pair("p1", _), Pair("p2", _),
+ Pair("p3", _), Pair("p4", _)));
+const Environment  = Results[0].second.Env;
+const Environment  = Results[1].second.Env;
+const Environment  = Results[2].second.Env;
+const Environment  = Results[3].second.Env;
 
 const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
 ASSERT_THAT(FooDecl, NotNull());
@@ -751,14 +751,14 @@
 const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
 ASSERT_THAT(FooDecl, NotNull());
 
-ASSERT_THAT(Results, ElementsAre(Pair("p2", _), Pair("p1", _)));
+ASSERT_THAT(Results, ElementsAre(Pair("p1", _), Pair("p2", _)));
 
-const Environment  = Results[1].second.Env;
+const Environment  = Results[0].second.Env;
 auto *FooVal1 =
 cast(Env1.getValue(*FooDecl, SkipPast::None));
 EXPECT_TRUE(Env1.flowConditionImplies(*FooVal1));
 
-const Environment  = Results[0].second.Env;
+const Environment  = Results[1].second.Env;
 auto *FooVal2 =
 cast(Env2.getValue(*FooDecl, SkipPast::None));
 EXPECT_FALSE(Env2.flowConditionImplies(*FooVal2));
@@ -785,14 +785,14 @@
 const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
 ASSERT_THAT(FooDecl, NotNull());
 
-ASSERT_THAT(Results, ElementsAre(Pair("p2", _), Pair("p1", _)));
+ASSERT_THAT(Results, ElementsAre(Pair("p1", _), Pair("p2", _)));
 
-const Environment  = Results[1].second.Env;
+const Environment  = Results[0].second.Env;
 auto *FooVal1 =
 cast(Env1.getValue(*FooDecl, SkipPast::None));
 EXPECT_FALSE(Env1.flowConditionImplies(*FooVal1));
 
-const Environment  = 

[PATCH] D129664: [Clang] Adjust extension warnings for delimited sequences

2022-08-31 Thread Tom Honermann via Phabricator via cfe-commits
tahonermann added a comment.

> While accepting all these inside of string and character literals in C and 
> C++20 and older is fine, accepting them inside of identifiers can change 
> meaning of valid programs.

Thank you for reporting this impact, @jakubjelinek! I'll copy you on an email 
to WG21 that discussed the impact, specifically with regard to the glibc header 
for which Joseph reported failures.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129664

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


[PATCH] D132377: [clang][dataflow] Add `SetupTest` parameter for `AnalysisInputs`.

2022-08-31 Thread weiyi via Phabricator via cfe-commits
wyt updated this revision to Diff 456982.
wyt added a comment.

Update according to change in parent patch to replace designated initialisers 
when constructing `AnalysisInputs`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132377

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

Index: clang/unittests/Analysis/FlowSensitive/TestingSupport.h
===
--- clang/unittests/Analysis/FlowSensitive/TestingSupport.h
+++ clang/unittests/Analysis/FlowSensitive/TestingSupport.h
@@ -96,6 +96,11 @@
 
   /// Optional fields can be set with methods of the form `withFieldName(...)`.
   AnalysisInputs &&
+  withSetupTest(std::function Arg) && {
+SetupTest = std::move(Arg);
+return std::move(*this);
+  }
+  AnalysisInputs &&
   withPostVisitCFG(std::function
Arg) && {
@@ -120,6 +125,11 @@
   /// takes as argument the AST generated from the code being analyzed and the
   /// initial state from which the analysis starts with.
   std::function MakeAnalysis;
+  /// Optional. If provided, this function is executed immediately before
+  /// running the dataflow analysis to allow for additional setup. All fields in
+  /// the `AnalysisOutputs` argument will be initialized except for the
+  /// `BlockStates` field which is only computed later during the analysis.
+  std::function SetupTest = nullptr;
   /// Optional. If provided, this function is applied on each CFG element after
   /// the analysis has been run.
   std::function
-getAnnotationLinesAndContent(const AnalysisOutputs );
-
-// FIXME: Return a string map instead of a vector of pairs.
-//
-/// Returns the analysis states at each annotated statement in `AO.Code`.
-template 
-llvm::Expected>>>
-getAnnotationStates(const AnalysisOutputs ) {
-  using StateT = DataflowAnalysisState;
-  // FIXME: Extend to annotations on non-statement constructs.
-  // Get annotated statements.
-  llvm::Expected>
-  MaybeStmtToAnnotations =
-  buildStatementToAnnotationMapping(AO.Target, AO.Code);
-  if (!MaybeStmtToAnnotations)
-return MaybeStmtToAnnotations.takeError();
-  auto  = *MaybeStmtToAnnotations;
-
-  // Compute a map from statement annotations to the state computed
-  // for the program point immediately after the annotated statement.
-  std::vector> Results;
-  for (const CFGBlock *Block : AO.CFCtx.getCFG()) {
-// Skip blocks that were not evaluated.
-if (!AO.BlockStates[Block->getBlockID()])
-  continue;
-
-transferBlock(
-AO.CFCtx, AO.BlockStates, *Block, AO.InitEnv, AO.Analysis,
-[,
- ](const clang::CFGElement ,
- const TypeErasedDataflowAnalysisState ) {
-  auto Stmt = Element.getAs();
-  if (!Stmt)
-return;
-  auto It = StmtToAnnotations.find(Stmt->getStmt());
-  if (It == StmtToAnnotations.end())
-return;
-  auto *Lattice =
-  llvm::any_cast();
-  Results.emplace_back(It->second, StateT{*Lattice, State.Env});
-});
-  }
-
-  return Results;
-}
+buildLineToAnnotationMapping(SourceManager ,
+ llvm::Annotations AnnotatedCode);
 
 /// Runs dataflow specified from `AI.MakeAnalysis` and `AI.PostVisitCFG` on the
 /// body of the function that matches `AI.TargetFuncMatcher` in `AI.Code`.
@@ -200,9 +166,9 @@
 ///
 ///   `VerifyResults` must be provided.
 template 
-llvm::Error checkDataflow(
-AnalysisInputs AI,
-std::function VerifyResults) {
+llvm::Error
+checkDataflow(AnalysisInputs AI,
+  std::function VerifyResults) {
   // Build AST context from code.
   llvm::Annotations AnnotatedCode(AI.Code);
   auto Unit = tooling::buildASTFromCodeWithArgs(
@@ -236,7 +202,7 @@
 return MaybeCFCtx.takeError();
   auto  = *MaybeCFCtx;
 
-  // Initialize states and run dataflow analysis.
+  // Initialize states for running dataflow analysis.
   DataflowAnalysisContext DACtx(std::make_unique());
   Environment InitEnv(DACtx, *Target);
   auto Analysis = AI.MakeAnalysis(Context, InitEnv);
@@ -251,19 +217,26 @@
 };
   }
 
-  // If successful, the run returns a mapping from block IDs to the
-  // post-analysis states for the CFG blocks that have been evaluated.
+  // Additional test setup.
+  AnalysisOutputs AO{AnnotatedCode, Context, Target, CFCtx,
+ Analysis,  InitEnv, {}};
+  if (AI.SetupTest) {
+if (auto Error = AI.SetupTest(AO))
+  return Error;
+  }
+
+  // If successful, the dataflow analysis returns a mapping from block IDs to
+  // the post-analysis states for the CFG blocks that have been evaluated.
   llvm::Expected>>
   MaybeBlockStates = runTypeErasedDataflowAnalysis(CFCtx, Analysis, InitEnv,

[PATCH] D132944: [clang] cleanup -fstrict-flex-arrays implementation

2022-08-31 Thread James Y Knight via Phabricator via cfe-commits
jyknight added a comment.

(please ignore the last comment, I sent it to the wrong review thread)


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

https://reviews.llvm.org/D132944

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


[PATCH] D133029: [Sema] Allow to diagnose the references to std::vector with incomplete T

2022-08-31 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

In D133029#3761400 , @gribozavr2 
wrote:

> In D133029#3761344 , @ilya-biryukov 
> wrote:
>
>> [...] I don't think there is an easy way to write it outside `Sema` and 
>> `Sema` is not readily available for `clang-tidy`.
>
> What information is missing, exactly?

Whether a type was incomplete at a certain point in code.

  struct IncompleteAtUse;
  std::vector x; // want to catch this, not visible in the 
resulting AST.
  struct IncompleteAtUse {};


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133029

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


[PATCH] D132147: [clang][dataflow] Refactor `TestingSupport.h`

2022-08-31 Thread weiyi via Phabricator via cfe-commits
wyt updated this revision to Diff 456980.
wyt added a comment.

This is a re-update of a previous update which uploaded the wrong diff.
Remove use of designated initializers which are only allowed on C++20. Instead, 
introduce a constructor that sets required fields, and withFieldName methods 
that sets optional fields when constructing an AnalysisInputs struct.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132147

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

Index: clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
@@ -1234,49 +1234,48 @@
   template 
   T Make();
 )");
-const tooling::FileContentMappings FileContents(Headers.begin(),
-Headers.end());
 UncheckedOptionalAccessModelOptions Options{
 /*IgnoreSmartPointerDereference=*/true};
 std::vector Diagnostics;
 llvm::Error Error = checkDataflow(
-SourceCode, FuncMatcher,
-[Options](ASTContext , Environment &) {
-  return UncheckedOptionalAccessModel(Ctx, Options);
-},
-[, Diagnoser = UncheckedOptionalAccessDiagnoser(Options)](
-ASTContext , const CFGStmt ,
-const TypeErasedDataflowAnalysisState ) mutable {
-  auto StmtDiagnostics =
-  Diagnoser.diagnose(Ctx, Stmt.getStmt(), State.Env);
-  llvm::move(StmtDiagnostics, std::back_inserter(Diagnostics));
-},
-[](AnalysisData AnalysisData) {
-  auto  = AnalysisData.ASTCtx.getSourceManager();
-
+AnalysisInputs(
+SourceCode, std::move(FuncMatcher),
+[Options](ASTContext , Environment &) {
+  return UncheckedOptionalAccessModel(Ctx, Options);
+})
+.withPostVisitCFG(
+[,
+ Diagnoser = UncheckedOptionalAccessDiagnoser(Options)](
+ASTContext , const CFGElement ,
+const TypeErasedDataflowAnalysisState ) mutable {
+  auto Stmt = Elt.getAs();
+  if (!Stmt) {
+return;
+  }
+  auto StmtDiagnostics =
+  Diagnoser.diagnose(Ctx, Stmt->getStmt(), State.Env);
+  llvm::move(StmtDiagnostics, std::back_inserter(Diagnostics));
+})
+.withASTBuildArgs(
+{"-fsyntax-only", "-std=c++17", "-Wno-undefined-inline"})
+.withASTBuildVirtualMappedFiles(
+tooling::FileContentMappings(Headers.begin(), Headers.end())),
+/*VerifyResults=*/[](
+  const llvm::DenseMap
+  ,
+  const AnalysisOutputs ) {
   llvm::DenseSet AnnotationLines;
-  for (const auto  : AnalysisData.Annotations) {
-auto *Stmt = Pair.getFirst();
-AnnotationLines.insert(
-SrcMgr.getPresumedLineNumber(Stmt->getBeginLoc()));
-// We add both the begin and end locations, so that if the
-// statement spans multiple lines then the test will fail.
-//
-// FIXME: Going forward, we should change this to instead just
-// get the single line number from the annotation itself, rather
-// than looking at the statement it's attached to.
-AnnotationLines.insert(
-SrcMgr.getPresumedLineNumber(Stmt->getEndLoc()));
+  for (const auto &[Line, _] : Annotations) {
+AnnotationLines.insert(Line);
   }
-
+  auto  = AO.ASTCtx.getSourceManager();
   llvm::DenseSet DiagnosticLines;
   for (SourceLocation  : Diagnostics) {
 DiagnosticLines.insert(SrcMgr.getPresumedLineNumber(Loc));
   }
 
   EXPECT_THAT(DiagnosticLines, ContainerEq(AnnotationLines));
-},
-{"-fsyntax-only", "-std=c++17", "-Wno-undefined-inline"}, FileContents);
+});
 if (Error)
   FAIL() << llvm::toString(std::move(Error));
   }
Index: clang/unittests/Analysis/FlowSensitive/TestingSupport.h
===
--- clang/unittests/Analysis/FlowSensitive/TestingSupport.h
+++ clang/unittests/Analysis/FlowSensitive/TestingSupport.h
@@ -56,47 +56,160 @@
 
 namespace test {
 
-// Returns assertions based on annotations that are present after statements in
-// `AnnotatedCode`.
-llvm::Expected>

[PATCH] D133009: [libclang] Fix conversion from `StringRef` to `CXString`

2022-08-31 Thread Egor Zhdan via Phabricator via cfe-commits
egorzhdan added inline comments.



Comment at: clang/test/Index/comment-lots-of-unknown-commands.c:3
 
+// XFAIL: *
+

gribozavr2 wrote:
> egorzhdan wrote:
> > This test was never properly passing. Because of the bug in string 
> > conversion, the printed comments contained the entire source file and not 
> > just the comments' text, which was enough to cause `// CHECK`-s in the test 
> > to succeed.
> > ```
> > // CHECK: (CXComment_InlineCommand CommandName=[tel] RenderNormal 
> > HasTrailingNewline)
> > // CHECK: (CXComment_InlineCommand CommandName=[n] RenderNormal 
> > HasTrailingNewline))
> > // CHECK:   (CXComment_VerbatimLine 
> > Text=[\n@Lo\n@il\n@tle\n@axt\n@ba\n@ust\n@ac\n@tpe\n@tpl\n@ctG\n@ru\n@m\n@tG\n@it\n@rh\n@G\n@rpc\n@el\n@er\n@w\n@eo\n@tx\n@oo\n@dD\n@dD\n*/\nvoid
> >  f();\n\n// CHECK:  CommentAST=[\n// CHECK:(CXComment_FullComment\n// 
> > CHECK:   (CXComment_Paragraph\n// CHECK:  ...
> > ```
> Please update the test to pass then. Here's the diff:
> 
> ```
> diff --git a/clang/test/Index/comment-lots-of-unknown-commands.c 
> b/clang/test/Index/comment-lots-of-unknown-commands.c
> index 41a03d394488..e1adcc150b1e 100644
> --- a/clang/test/Index/comment-lots-of-unknown-commands.c
> +++ b/clang/test/Index/comment-lots-of-unknown-commands.c
> @@ -1,6 +1,5 @@
>  // RUN: c-index-test -test-load-source-reparse 1 local %s | FileCheck %s
> 
> -// XFAIL: *
> 
>  // See PR 21254. We had too few bits to encode command IDs so if you created
>  // enough of them the ID codes would wrap around. This test creates commands 
> up
> @@ -183,7 +182,7 @@ void f();
>  // CHECK: (CXComment_InlineCommand CommandName=[ei] RenderNormal 
> HasTrailingNewline)
>  // CHECK: (CXComment_InlineCommand CommandName=[oun] RenderNormal 
> HasTrailingNewline)
>  // CHECK: (CXComment_InlineCommand CommandName=[ou] RenderNormal 
> HasTrailingNewline)
> -// CHECK: (CXComment_InlineCommand CommandName=[nl] RenderNormal 
> HasTrailingNewline)
> +// CHECK: (CXComment_InlineCommand CommandName=[n] RenderNormal 
> HasTrailingNewline)
>  // CHECK: (CXComment_InlineCommand CommandName=[ien] RenderNormal 
> HasTrailingNewline)
>  // CHECK: (CXComment_InlineCommand CommandName=[fr] RenderNormal 
> HasTrailingNewline)
>  // CHECK: (CXComment_InlineCommand CommandName=[en] RenderNormal 
> HasTrailingNewline)
> @@ -204,7 +203,7 @@ void f();
>  // CHECK: (CXComment_InlineCommand CommandName=[fro] RenderNormal 
> HasTrailingNewline)
>  // CHECK: (CXComment_InlineCommand CommandName=[ast] RenderNormal 
> HasTrailingNewline)
>  // CHECK: (CXComment_InlineCommand CommandName=[ae] RenderNormal 
> HasTrailingNewline)
> -// CHECK: (CXComment_InlineCommand CommandName=[nN] RenderNormal 
> HasTrailingNewline)
> +// CHECK: (CXComment_InlineCommand CommandName=[n] RenderNormal 
> HasTrailingNewline)
>  // CHECK: (CXComment_InlineCommand CommandName=[pc] RenderNormal 
> HasTrailingNewline)
>  // CHECK: (CXComment_InlineCommand CommandName=[tae] RenderNormal 
> HasTrailingNewline)
>  // CHECK: (CXComment_InlineCommand CommandName=[ws] RenderNormal 
> HasTrailingNewline)
> @@ -268,10 +267,8 @@ void f();
>  // CHECK: (CXComment_InlineCommand CommandName=[an] RenderNormal 
> HasTrailingNewline)
>  // CHECK: (CXComment_InlineCommand CommandName=[de] RenderNormal 
> HasTrailingNewline)
>  // CHECK: (CXComment_InlineCommand CommandName=[tel] RenderNormal 
> HasTrailingNewline)
> -// CHECK: (CXComment_InlineCommand CommandName=[nd] RenderNormal 
> HasTrailingNewline)
> -// CHECK: (CXComment_InlineCommand CommandName=[dic] RenderNormal 
> HasTrailingNewline)
> +// CHECK: (CXComment_InlineCommand CommandName=[n] RenderNormal 
> HasTrailingNewline)
>  // CHECK: (CXComment_InlineCommand CommandName=[Lo] RenderNormal 
> HasTrailingNewline)
> -// CHECK: (CXComment_InlineCommand CommandName=[il] RenderNormal 
> HasTrailingNewline)
>  // CHECK: (CXComment_InlineCommand CommandName=[tle] RenderNormal 
> HasTrailingNewline)
>  // CHECK: (CXComment_InlineCommand CommandName=[axt] RenderNormal 
> HasTrailingNewline)
>  // CHECK: (CXComment_InlineCommand CommandName=[ba] RenderNormal 
> HasTrailingNewline)
> @@ -283,7 +280,6 @@ void f();
>  // CHECK: (CXComment_InlineCommand CommandName=[ru] RenderNormal 
> HasTrailingNewline)
>  // CHECK: (CXComment_InlineCommand CommandName=[m] RenderNormal 
> HasTrailingNewline)
>  // CHECK: (CXComment_InlineCommand CommandName=[tG] RenderNormal 
> HasTrailingNewline)
> -// CHECK: (CXComment_InlineCommand CommandName=[it] RenderNormal 
> HasTrailingNewline)
>  // CHECK: (CXComment_InlineCommand CommandName=[rh] RenderNormal 
> HasTrailingNewline)
>  // CHECK: (CXComment_InlineCommand CommandName=[G] RenderNormal 

[PATCH] D133029: [Sema] Allow to diagnose the references to std::vector with incomplete T

2022-08-31 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr2 added a comment.

In D133029#3761344 , @ilya-biryukov 
wrote:

> [...] I don't think there is an easy way to write it outside `Sema` and 
> `Sema` is not readily available for `clang-tidy`.

What information is missing, exactly?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133029

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


[PATCH] D129488: [Sema] Delay evaluation of std::source_location::current() in default arguments

2022-08-31 Thread James Y Knight via Phabricator via cfe-commits
jyknight added a comment.

  #include 
  #include 
  
  
  consteval int fn(std::source_location sl = std::source_location::current()) {
return sl.line();
  }
  
  consteval int fn2(int line = fn()) {
return line;
  }
  
  int main() {
printf("fn=%d fn2=%d\n", fn(), fn2());
  }

I believe this should print `fn=14 fn2=14`. I don't see how we can get that by 
special-casing calls to `std::source_location::current`, and indeed, with this 
version of the patch, the program instead prints `fn=14 fn2=9`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129488

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


[PATCH] D132944: [clang] cleanup -fstrict-flex-arrays implementation

2022-08-31 Thread James Y Knight via Phabricator via cfe-commits
jyknight added a comment.

  #include 
  #include 
  
  
  consteval int fn(std::source_location sl = std::source_location::current()) {
return sl.line();
  }
  
  consteval int fn2(int line = fn()) {
return line;
  }
  
  int main() {
printf("fn=%d fn2=%d\n", fn(), fn2());
  }

I believe this should print `fn=14 fn2=14`. I don't see how we can get that by 
special-casing calls to `std::source_location::current`, and indeed, with this 
version of the patch, the program instead prints `fn=14 fn2=9`.


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

https://reviews.llvm.org/D132944

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


[PATCH] D133009: [libclang] Fix conversion from `StringRef` to `CXString`

2022-08-31 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr2 added inline comments.



Comment at: clang/test/Index/comment-lots-of-unknown-commands.c:3
 
+// XFAIL: *
+

egorzhdan wrote:
> This test was never properly passing. Because of the bug in string 
> conversion, the printed comments contained the entire source file and not 
> just the comments' text, which was enough to cause `// CHECK`-s in the test 
> to succeed.
> ```
> // CHECK: (CXComment_InlineCommand CommandName=[tel] RenderNormal 
> HasTrailingNewline)
> // CHECK: (CXComment_InlineCommand CommandName=[n] RenderNormal 
> HasTrailingNewline))
> // CHECK:   (CXComment_VerbatimLine 
> Text=[\n@Lo\n@il\n@tle\n@axt\n@ba\n@ust\n@ac\n@tpe\n@tpl\n@ctG\n@ru\n@m\n@tG\n@it\n@rh\n@G\n@rpc\n@el\n@er\n@w\n@eo\n@tx\n@oo\n@dD\n@dD\n*/\nvoid
>  f();\n\n// CHECK:  CommentAST=[\n// CHECK:(CXComment_FullComment\n// 
> CHECK:   (CXComment_Paragraph\n// CHECK:  ...
> ```
Please update the test to pass then. Here's the diff:

```
diff --git a/clang/test/Index/comment-lots-of-unknown-commands.c 
b/clang/test/Index/comment-lots-of-unknown-commands.c
index 41a03d394488..e1adcc150b1e 100644
--- a/clang/test/Index/comment-lots-of-unknown-commands.c
+++ b/clang/test/Index/comment-lots-of-unknown-commands.c
@@ -1,6 +1,5 @@
 // RUN: c-index-test -test-load-source-reparse 1 local %s | FileCheck %s

-// XFAIL: *

 // See PR 21254. We had too few bits to encode command IDs so if you created
 // enough of them the ID codes would wrap around. This test creates commands up
@@ -183,7 +182,7 @@ void f();
 // CHECK: (CXComment_InlineCommand CommandName=[ei] RenderNormal 
HasTrailingNewline)
 // CHECK: (CXComment_InlineCommand CommandName=[oun] RenderNormal 
HasTrailingNewline)
 // CHECK: (CXComment_InlineCommand CommandName=[ou] RenderNormal 
HasTrailingNewline)
-// CHECK: (CXComment_InlineCommand CommandName=[nl] RenderNormal 
HasTrailingNewline)
+// CHECK: (CXComment_InlineCommand CommandName=[n] RenderNormal 
HasTrailingNewline)
 // CHECK: (CXComment_InlineCommand CommandName=[ien] RenderNormal 
HasTrailingNewline)
 // CHECK: (CXComment_InlineCommand CommandName=[fr] RenderNormal 
HasTrailingNewline)
 // CHECK: (CXComment_InlineCommand CommandName=[en] RenderNormal 
HasTrailingNewline)
@@ -204,7 +203,7 @@ void f();
 // CHECK: (CXComment_InlineCommand CommandName=[fro] RenderNormal 
HasTrailingNewline)
 // CHECK: (CXComment_InlineCommand CommandName=[ast] RenderNormal 
HasTrailingNewline)
 // CHECK: (CXComment_InlineCommand CommandName=[ae] RenderNormal 
HasTrailingNewline)
-// CHECK: (CXComment_InlineCommand CommandName=[nN] RenderNormal 
HasTrailingNewline)
+// CHECK: (CXComment_InlineCommand CommandName=[n] RenderNormal 
HasTrailingNewline)
 // CHECK: (CXComment_InlineCommand CommandName=[pc] RenderNormal 
HasTrailingNewline)
 // CHECK: (CXComment_InlineCommand CommandName=[tae] RenderNormal 
HasTrailingNewline)
 // CHECK: (CXComment_InlineCommand CommandName=[ws] RenderNormal 
HasTrailingNewline)
@@ -268,10 +267,8 @@ void f();
 // CHECK: (CXComment_InlineCommand CommandName=[an] RenderNormal 
HasTrailingNewline)
 // CHECK: (CXComment_InlineCommand CommandName=[de] RenderNormal 
HasTrailingNewline)
 // CHECK: (CXComment_InlineCommand CommandName=[tel] RenderNormal 
HasTrailingNewline)
-// CHECK: (CXComment_InlineCommand CommandName=[nd] RenderNormal 
HasTrailingNewline)
-// CHECK: (CXComment_InlineCommand CommandName=[dic] RenderNormal 
HasTrailingNewline)
+// CHECK: (CXComment_InlineCommand CommandName=[n] RenderNormal 
HasTrailingNewline)
 // CHECK: (CXComment_InlineCommand CommandName=[Lo] RenderNormal 
HasTrailingNewline)
-// CHECK: (CXComment_InlineCommand CommandName=[il] RenderNormal 
HasTrailingNewline)
 // CHECK: (CXComment_InlineCommand CommandName=[tle] RenderNormal 
HasTrailingNewline)
 // CHECK: (CXComment_InlineCommand CommandName=[axt] RenderNormal 
HasTrailingNewline)
 // CHECK: (CXComment_InlineCommand CommandName=[ba] RenderNormal 
HasTrailingNewline)
@@ -283,7 +280,6 @@ void f();
 // CHECK: (CXComment_InlineCommand CommandName=[ru] RenderNormal 
HasTrailingNewline)
 // CHECK: (CXComment_InlineCommand CommandName=[m] RenderNormal 
HasTrailingNewline)
 // CHECK: (CXComment_InlineCommand CommandName=[tG] RenderNormal 
HasTrailingNewline)
-// CHECK: (CXComment_InlineCommand CommandName=[it] RenderNormal 
HasTrailingNewline)
 // CHECK: (CXComment_InlineCommand CommandName=[rh] RenderNormal 
HasTrailingNewline)
 // CHECK: (CXComment_InlineCommand CommandName=[G] RenderNormal 
HasTrailingNewline)
 // CHECK: (CXComment_InlineCommand CommandName=[rpc] RenderNormal 
HasTrailingNewline)
```



Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  

[PATCH] D132147: [clang][dataflow] Refactor `TestingSupport.h`

2022-08-31 Thread weiyi via Phabricator via cfe-commits
wyt updated this revision to Diff 456978.
wyt added a comment.
Herald added subscribers: llvm-commits, mgrang, mgorny.
Herald added a project: LLVM.

Remove use of designated initializers which are only allowed on C++20. Instead, 
introduce a constructor that sets required fields, and `withFieldName` methods 
that sets optional fields when constructing an `AnalysisInputs` struct.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132147

Files:
  clang/unittests/Analysis/FlowSensitive/TestingSupport.cpp
  clang/unittests/Analysis/FlowSensitive/TestingSupport.h
  clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
  clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
  llvm/include/llvm/ADT/StringMapEntry.h
  llvm/include/llvm/Testing/ADT/StringMap.h
  llvm/include/llvm/Testing/ADT/StringMapEntry.h
  llvm/unittests/Testing/ADT/CMakeLists.txt
  llvm/unittests/Testing/ADT/StringMapEntryTest.cpp
  llvm/unittests/Testing/ADT/StringMapTest.cpp
  llvm/unittests/Testing/CMakeLists.txt
  utils/bazel/llvm-project-overlay/llvm/BUILD.bazel
  utils/bazel/llvm-project-overlay/llvm/unittests/BUILD.bazel

Index: utils/bazel/llvm-project-overlay/llvm/unittests/BUILD.bazel
===
--- utils/bazel/llvm-project-overlay/llvm/unittests/BUILD.bazel
+++ utils/bazel/llvm-project-overlay/llvm/unittests/BUILD.bazel
@@ -644,6 +644,23 @@
 ],
 )
 
+cc_test(
+name = "testing_adt_tests",
+size = "small",
+srcs = glob(
+[
+"Testing/ADT/*.cpp",
+],
+allow_empty = False,
+),
+deps = [
+"//llvm:Support",
+"//llvm:TestingADT",
+"//llvm:gtest",
+"//llvm:gtest_main",
+],
+)
+
 cc_test(
 name = "transforms_tests",
 size = "small",
Index: utils/bazel/llvm-project-overlay/llvm/BUILD.bazel
===
--- utils/bazel/llvm-project-overlay/llvm/BUILD.bazel
+++ utils/bazel/llvm-project-overlay/llvm/BUILD.bazel
@@ -4181,6 +4181,19 @@
 srcs = ["utils/lit/lit.py"] + glob(["utils/lit/lit/**/*.py"]),
 )
 
+cc_library(
+name = "TestingADT",
+testonly = True,
+hdrs = glob([
+"include/llvm/Testing/ADT/*.h",
+]),
+copts = llvm_copts,
+deps = [
+":Support",
+":gmock",
+],
+)
+
 cc_library(
 name = "TestingSupport",
 testonly = True,
Index: llvm/unittests/Testing/CMakeLists.txt
===
--- llvm/unittests/Testing/CMakeLists.txt
+++ llvm/unittests/Testing/CMakeLists.txt
@@ -1 +1,2 @@
+add_subdirectory(ADT)
 add_subdirectory(Support)
Index: llvm/unittests/Testing/ADT/StringMapTest.cpp
===
--- /dev/null
+++ llvm/unittests/Testing/ADT/StringMapTest.cpp
@@ -0,0 +1,55 @@
+//===- StringMapTest.cpp --===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "llvm/Testing/ADT/StringMap.h"
+#include "llvm/ADT/StringMap.h"
+
+#include "gtest/gtest.h"
+#include 
+
+namespace llvm {
+namespace {
+
+TEST(StringMapTest, StringMapStream) {
+  std::ostringstream OS;
+  StringMap Map;
+  Map["A"] = 42;
+  Map["Z"] = 35;
+  Map["B"] = 7;
+  OS << Map;
+
+  EXPECT_EQ(OS.str(), R"({
+{"A": 42},
+{"B": 7},
+{"Z": 35},
+})");
+}
+
+TEST(StringMapTest, NestedStringMapStream) {
+  std::ostringstream OS;
+  StringMap> Map;
+  Map["Z"];
+  Map["A"]["Apple"] = 5;
+  Map["B"]["Bee"] = 3;
+  Map["A"]["Axe"] = 3;
+  OS << Map;
+
+  EXPECT_EQ(OS.str(), R"({
+{"A": {
+{"Apple": 5},
+{"Axe": 3},
+}},
+{"B": {
+{"Bee": 3},
+}},
+{"Z": { }},
+})");
+}
+
+} // namespace
+} // namespace llvm
Index: llvm/unittests/Testing/ADT/StringMapEntryTest.cpp
===
--- /dev/null
+++ llvm/unittests/Testing/ADT/StringMapEntryTest.cpp
@@ -0,0 +1,88 @@
+//===- StringMapEntryTest.cpp -===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "llvm/Testing/ADT/StringMapEntry.h"
+#include "llvm/ADT/StringMap.h"
+
+#include "gtest/gtest.h"
+#include 
+
+namespace llvm {
+namespace {
+
+using testing::Gt;
+using testing::Matcher;
+using testing::StrCaseEq;
+using testing::StringMatchResultListener;
+using testing::UnorderedElementsAre;
+
+template  std::string 

[PATCH] D131879: [clang][analyzer] Errno modeling code refactor (NFC).

2022-08-31 Thread Gabor Marton via Phabricator via cfe-commits
martong accepted this revision.
martong added a comment.
Herald added a subscriber: rnkovacs.

LGTM!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131879

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


[PATCH] D133029: [Sema] Allow to diagnose the references to std::vector with incomplete T

2022-08-31 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

This warning might be a little verbose and pedantic for Clang, but I still 
wanted to share the code.
I would be more comfortable doing this a `clang-tidy` check, but I don't think 
there is an easy way to write it outside `Sema` and `Sema` is not readily 
available for `clang-tidy`.

I will try to find ways to patch this in locally for my use-case, but also 
happy to submit this if others think it is useful.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133029

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


[PATCH] D132944: [clang] cleanup -fstrict-flex-arrays implementation

2022-08-31 Thread serge via Phabricator via cfe-commits
serge-sans-paille updated this revision to Diff 456971.
serge-sans-paille edited the summary of this revision.

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

https://reviews.llvm.org/D132944

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/CodeGen/CGExpr.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/test/CodeGen/bounds-checking-fam.c
  clang/test/CodeGen/object-size-flex-array.c

Index: clang/test/CodeGen/object-size-flex-array.c
===
--- clang/test/CodeGen/object-size-flex-array.c
+++ clang/test/CodeGen/object-size-flex-array.c
@@ -24,7 +24,7 @@
   double c[2];
 } foo2_t;
 
-// CHECK-LABEL: @bar
+// CHECK-LABEL: @bar(
 unsigned bar(foo_t *f) {
   // CHECK-STRICT-0: ret i32 %
   // CHECK-STRICT-1: ret i32 %
@@ -32,7 +32,7 @@
   return OBJECT_SIZE_BUILTIN(f->c, 1);
 }
 
-// CHECK-LABEL: @bar0
+// CHECK-LABEL: @bar0(
 unsigned bar0(foo0_t *f) {
   // CHECK-STRICT-0: ret i32 %
   // CHECK-STRICT-1: ret i32 %
@@ -40,7 +40,7 @@
   return OBJECT_SIZE_BUILTIN(f->c, 1);
 }
 
-// CHECK-LABEL: @bar1
+// CHECK-LABEL: @bar1(
 unsigned bar1(foo1_t *f) {
   // CHECK-STRICT-0: ret i32 %
   // CHECK-STRICT-1: ret i32 %
@@ -48,7 +48,7 @@
   return OBJECT_SIZE_BUILTIN(f->c, 1);
 }
 
-// CHECK-LABEL: @bar2
+// CHECK-LABEL: @bar2(
 unsigned bar2(foo2_t *f) {
   // CHECK-STRICT-0: ret i32 %
   // CHECK-STRICT-1: ret i32 16
@@ -73,7 +73,7 @@
   float f;
 } foofoo2_t;
 
-// CHECK-LABEL: @babar0
+// CHECK-LABEL: @babar0(
 unsigned babar0(foofoo0_t *f) {
   // CHECK-STRICT-0: ret i32 0
   // CHECK-STRICT-1: ret i32 0
@@ -81,7 +81,7 @@
   return OBJECT_SIZE_BUILTIN(f->c, 1);
 }
 
-// CHECK-LABEL: @babar1
+// CHECK-LABEL: @babar1(
 unsigned babar1(foofoo1_t *f) {
   // CHECK-STRICT-0: ret i32 8
   // CHECK-STRICT-1: ret i32 8
@@ -89,7 +89,7 @@
   return OBJECT_SIZE_BUILTIN(f->c, 1);
 }
 
-// CHECK-LABEL: @babar2
+// CHECK-LABEL: @babar2(
 unsigned babar2(foofoo2_t *f) {
   // CHECK-STRICT-0: ret i32 16
   // CHECK-STRICT-1: ret i32 16
Index: clang/test/CodeGen/bounds-checking-fam.c
===
--- clang/test/CodeGen/bounds-checking-fam.c
+++ clang/test/CodeGen/bounds-checking-fam.c
@@ -35,6 +35,51 @@
   return p->a[i] + (p->a)[i];
 }
 
+union uZero {
+  int a[0];
+};
+union uOne {
+  int a[1];
+};
+union uTwo {
+  int a[2];
+};
+union uThree {
+  int a[3];
+};
+
+// CHECK-LABEL: define {{.*}} @{{.*}}test_uzero{{.*}}(
+int test_uzero(union uZero *p, int i) {
+  // CHECK-STRICT-0-NOT: @__ubsan
+  // CHECK-STRICT-1-NOT: @__ubsan
+  // CHECK-STRICT-2-NOT: @__ubsan
+  return p->a[i] + (p->a)[i];
+}
+
+// CHECK-LABEL: define {{.*}} @{{.*}}test_uone{{.*}}(
+int test_uone(union uOne *p, int i) {
+  // CHECK-STRICT-0-NOT: @__ubsan
+  // CHECK-STRICT-1-NOT: @__ubsan
+  // CHECK-STRICT-2: @__ubsan
+  return p->a[i] + (p->a)[i];
+}
+
+// CHECK-LABEL: define {{.*}} @{{.*}}test_utwo{{.*}}(
+int test_utwo(union uTwo *p, int i) {
+  // CHECK-STRICT-0: @__ubsan
+  // CHECK-STRICT-1: @__ubsan
+  // CHECK-STRICT-2: @__ubsan
+  return p->a[i] + (p->a)[i];
+}
+
+// CHECK-LABEL: define {{.*}} @{{.*}}test_uthree{{.*}}(
+int test_uthree(union uThree *p, int i) {
+  // CHECK-STRICT-0: @__ubsan
+  // CHECK-STRICT-1: @__ubsan
+  // CHECK-STRICT-2: @__ubsan
+  return p->a[i] + (p->a)[i];
+}
+
 // CHECK-LABEL: define {{.*}} @{{.*}}test_three{{.*}}(
 int test_three(struct Three *p, int i) {
   // CHECK-STRICT-0: call void @__ubsan_handle_out_of_bounds_abort(
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -15849,16 +15849,10 @@
   if (!ND)
 return false;
 
-  if (StrictFlexArraysLevel >= 2 && Size != 0)
-return false;
-
-  if (StrictFlexArraysLevel == 1 && Size.uge(2))
-return false;
-
   // FIXME: While the default -fstrict-flex-arrays=0 permits Size>1 trailing
   // arrays to be treated as flexible-array-members, we still emit diagnostics
   // as if they are not. Pending further discussion...
-  if (StrictFlexArraysLevel == 0 && Size != 1)
+  if (StrictFlexArraysLevel >= 2 || Size.uge(2))
 return false;
 
   const FieldDecl *FD = dyn_cast(ND);
@@ -16026,8 +16020,8 @@
 if (BaseType->isIncompleteType())
   return;
 
-// FIXME: this check should belong to the IsTailPaddedMemberArray call
-// below.
+// FIXME: this check should be used to set IsUnboundedArray from the
+// beginning.
 llvm::APInt size = ArrayTy->getSize();
 if (!size.isStrictlyPositive())
   return;
Index: clang/lib/CodeGen/CGExpr.cpp
===
--- clang/lib/CodeGen/CGExpr.cpp
+++ clang/lib/CodeGen/CGExpr.cpp
@@ -906,10 +906,8 @@
 if (const auto *FD = dyn_cast(ME->getMemberDecl())) {
   // FIXME: Sema doesn't treat a T[1] union member as a flexible array
   // member, only a T[0] or T[] member 

  1   2   >