[PATCH] D106027: Allow setting CLANG_LINKS_TO_CREATE to an empty list

2021-07-14 Thread Dmitry Kalinkin via Phabricator via cfe-commits
veprbl created this revision.
Herald added a subscriber: mgorny.
veprbl requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

A user might want to redefine CLANG_LINKS_TO_CREATE to an empty list `""`, but 
such a value would be considered as a `FALSE` by cmake.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D106027

Files:
  clang/tools/driver/CMakeLists.txt


Index: clang/tools/driver/CMakeLists.txt
===
--- clang/tools/driver/CMakeLists.txt
+++ clang/tools/driver/CMakeLists.txt
@@ -58,7 +58,7 @@
 
 add_dependencies(clang clang-resource-headers)
 
-if(NOT CLANG_LINKS_TO_CREATE)
+if(NOT DEFINED CLANG_LINKS_TO_CREATE)
   set(CLANG_LINKS_TO_CREATE clang++ clang-cl clang-cpp)
 endif()
 


Index: clang/tools/driver/CMakeLists.txt
===
--- clang/tools/driver/CMakeLists.txt
+++ clang/tools/driver/CMakeLists.txt
@@ -58,7 +58,7 @@
 
 add_dependencies(clang clang-resource-headers)
 
-if(NOT CLANG_LINKS_TO_CREATE)
+if(NOT DEFINED CLANG_LINKS_TO_CREATE)
   set(CLANG_LINKS_TO_CREATE clang++ clang-cl clang-cpp)
 endif()
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D105974: [analyzer] Do not assume that all pointers have the same bitwidth as void*

2021-07-14 Thread Vince Bridgers via Phabricator via cfe-commits
vabridgers updated this revision to Diff 358792.
vabridgers added a comment.

address comments, add test case suggested by @bjope


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105974

Files:
  clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
  clang/test/Analysis/solver-sym-simplification-ptr-bool.cl


Index: clang/test/Analysis/solver-sym-simplification-ptr-bool.cl
===
--- /dev/null
+++ clang/test/Analysis/solver-sym-simplification-ptr-bool.cl
@@ -0,0 +1,23 @@
+// RUN: %clang_analyze_cc1 -triple amdgcn-unknown-unknown -target-cpu verde 
-analyze -analyzer-checker=core %s
+
+// expected-no-diagnostics
+
+// This test case covers an issue found in the static analyzer
+// solver where pointer sizes were assumed. Pointer sizes may vary on other
+// architectures. This issue was originally discovered on a downstream,
+// custom target, this assert occurs on the custom target and this one
+// without the fix, and is fixed with this change.
+//
+// The assertion appears to be happening as a result of evaluating the
+// SymIntExpr (reg_$0) != 0U in VisitSymIntExpr located in
+// SimpleSValBuilder.cpp. The LHS is evaluated to 32b and the RHS is
+// evaluated to 16b. This eventually leads to the assertion in APInt.h.
+//
+// APInt.h:1151: bool llvm::APInt::operator==(const llvm::APInt &) const: 
Assertion `BitWidth == RHS.BitWidth && "Comparison requires equal bit widths"'
+// 
+void test(__attribute__((address_space(256))) int * p) {
+  __attribute__((address_space(256))) int * q = p-1;
+  if (q) {}
+  if (q) {}
+  (void)q;
+} 
Index: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
@@ -712,9 +712,23 @@
   // symbols to use, only content metadata.
   return nonloc::SymbolVal(SymMgr.getExtentSymbol(FTR));
 
-if (const SymbolicRegion *SymR = R->getSymbolicBase())
-  return makeNonLoc(SymR->getSymbol(), BO_NE,
-BasicVals.getZeroWithPtrWidth(), CastTy);
+if (const SymbolicRegion *SymR = R->getSymbolicBase()) {
+  SymbolRef Sym = SymR->getSymbol();
+  QualType Ty = Sym->getType();
+  // This change is needed for architectures with varying
+  // pointer widths. See the amdgcn opencl reproducer with
+  // this change as an example: solver-sym-simplification-ptr-bool.cl
+  // FIXME: We could encounter a reference here,
+  //try returning a concrete 'true' since it might
+  //be easier on the solver.
+  // FIXME: Cleanup remainder of `getZeroWithPtrWidth ()`
+  //and `getIntWithPtrWidth()` functions to prevent future
+  //confusion
+  const llvm::APSInt &Zero = Ty->isReferenceType()
+ ? BasicVals.getZeroWithPtrWidth()
+ : BasicVals.getZeroWithTypeSize(Ty);
+  return makeNonLoc(Sym, BO_NE, Zero, CastTy);
+}
 // Non-symbolic memory regions are always true.
 return makeTruthVal(true, CastTy);
   }


Index: clang/test/Analysis/solver-sym-simplification-ptr-bool.cl
===
--- /dev/null
+++ clang/test/Analysis/solver-sym-simplification-ptr-bool.cl
@@ -0,0 +1,23 @@
+// RUN: %clang_analyze_cc1 -triple amdgcn-unknown-unknown -target-cpu verde -analyze -analyzer-checker=core %s
+
+// expected-no-diagnostics
+
+// This test case covers an issue found in the static analyzer
+// solver where pointer sizes were assumed. Pointer sizes may vary on other
+// architectures. This issue was originally discovered on a downstream,
+// custom target, this assert occurs on the custom target and this one
+// without the fix, and is fixed with this change.
+//
+// The assertion appears to be happening as a result of evaluating the
+// SymIntExpr (reg_$0) != 0U in VisitSymIntExpr located in
+// SimpleSValBuilder.cpp. The LHS is evaluated to 32b and the RHS is
+// evaluated to 16b. This eventually leads to the assertion in APInt.h.
+//
+// APInt.h:1151: bool llvm::APInt::operator==(const llvm::APInt &) const: Assertion `BitWidth == RHS.BitWidth && "Comparison requires equal bit widths"'
+// 
+void test(__attribute__((address_space(256))) int * p) {
+  __attribute__((address_space(256))) int * q = p-1;
+  if (q) {}
+  if (q) {}
+  (void)q;
+} 
Index: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
@@ -712,9 +712,23 @@
   // symbols to use, only content metadata.
   return nonloc::SymbolVal(SymMgr.getExtentSymbol(FTR));
 
-if (const SymbolicRegion *SymR = R->getSymbolicBase())
-  re

[PATCH] D105974: [analyzer] Do not assume that all pointers have the same bitwidth as void*

2021-07-14 Thread Vince Bridgers via Phabricator via cfe-commits
vabridgers added a comment.

Thanks for the updates, comments and the reproducer. I've added those in this 
update. If possible, I'd like to get this change accepted to avoid the crash we 
currently see, and I'll immediately follow up with the FIXMEs. Otherwise, I'll 
iterate quickly on the FIXMEs. - Vince




Comment at: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp:718
+  QualType Ty = Sym->getType();
+  // FIXME: Why did we have references at this point?
+  // FIXME: Cleanup remainder of `getZeroWithPtrWidth ()`

NoQ wrote:
> I guess something like this?
> ```lang=c++
> void foo(int &x) {
>   int *p = &x; // 'p' is the same SVal as 'x'
>   bool b = p;
> }
> ```
> I think we should return a concrete `true` in the reference case. We already 
> know that such symbol is true-ish but returning a concrete `true` might be 
> easier on the solver.
I think this comment is addressed by changing the comment, and deferring a 
subsequent follow up. I'd like to get this change submitted to at least avoid 
the crash if possible? Otherwise, if needed, I'll iterate quickly on trying to 
return a concrete 'true' for the reference case. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105974

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


[libclc] ea469b0 - libclc: Add -cl-no-stdinc to clang flags on clang >=13

2021-07-14 Thread Dave Airlie via cfe-commits

Author: Jan Vesely
Date: 2021-07-15T10:43:26+10:00
New Revision: ea469b08b847cef5f4c8187228f1e4bbf881706a

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

LOG: libclc: Add -cl-no-stdinc to clang flags on clang >=13

cf3ef15a6ec5e5b45c6c54e8fbe3769255e815ce ("[OpenCL] Add builtin
declarations by default.")
 switched behaviour to include "opencl-c-base.h". We don't want or need
 that for libclc so pass the flag to revert to old behaviour.

Fixes build since cf3ef15a6ec5e5b45c6c54e8fbe3769255e815ce

Reviewed By: tstellar

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

Added: 


Modified: 
libclc/CMakeLists.txt

Removed: 




diff  --git a/libclc/CMakeLists.txt b/libclc/CMakeLists.txt
index 7f8d81e9036ab..ec39ea63f2d02 100644
--- a/libclc/CMakeLists.txt
+++ b/libclc/CMakeLists.txt
@@ -124,7 +124,6 @@ set( CMAKE_CLC_ARCHIVE ${LLVM_LINK} )
 set( CMAKE_LLAsm_PREPROCESSOR ${LLVM_CLANG} )
 set( CMAKE_LLAsm_COMPILER ${LLVM_AS} )
 set( CMAKE_LLAsm_ARCHIVE ${LLVM_LINK} )
-enable_language( CLC LLAsm )
 
 # Construct LLVM version define
 string( REPLACE "." ";" LLVM_VERSION_LIST ${LLVM_VERSION} )
@@ -132,6 +131,15 @@ list( GET LLVM_VERSION_LIST 0 LLVM_MAJOR )
 list( GET LLVM_VERSION_LIST 1 LLVM_MINOR )
 set( LLVM_VERSION_DEFINE "-DHAVE_LLVM=0x${LLVM_MAJOR}0${LLVM_MINOR}" )
 
+
+# LLVM 13 enables standard includes by default
+if( ${LLVM_VERSION} VERSION_GREATER "12.99.99" )
+   set( CMAKE_LLAsm_FLAGS ${CMAKE_LLAsm_FLAGS} 
-cl-no-stdinc )
+   set( CMAKE_CLC_FLAGS ${CMAKE_CLC_FLAGS} 
-cl-no-stdinc )
+endif()
+
+enable_language( CLC LLAsm )
+
 # This needs to be set before any target that needs it
 link_directories( ${LLVM_LIBDIR} )
 



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


[clang] 090f007 - [OpenCL][NFC] opencl-c.h: reorder atomic operations

2021-07-14 Thread Dave Airlie via cfe-commits

Author: Dave Airlie
Date: 2021-07-15T10:48:44+10:00
New Revision: 090f007e3481863430e4443765769e73f8f40e5f

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

LOG: [OpenCL][NFC] opencl-c.h: reorder atomic operations

This just reorders the atomics, it doesn't change anything except their layout 
in the header.

This is a prep patch for adding some conditionals around these for CL3.0 but 
that patch is much easier to review if all the atomic operations are grouped 
together like this.

Reviewed By: Anastasia

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

Added: 


Modified: 
clang/lib/Headers/opencl-c.h

Removed: 




diff  --git a/clang/lib/Headers/opencl-c.h b/clang/lib/Headers/opencl-c.h
index bfdd9b84dced..8a5b6c2919ad 100644
--- a/clang/lib/Headers/opencl-c.h
+++ b/clang/lib/Headers/opencl-c.h
@@ -13306,91 +13306,35 @@ void __ovld atomic_work_item_fence(cl_mem_fence_flags 
flags, memory_order order,
 // atomic_fetch()
 
 int __ovld atomic_fetch_add(volatile atomic_int *object, int operand);
-int __ovld atomic_fetch_add_explicit(volatile atomic_int *object, int operand, 
memory_order order);
-int __ovld atomic_fetch_add_explicit(volatile atomic_int *object, int operand, 
memory_order order, memory_scope scope);
 uint __ovld atomic_fetch_add(volatile atomic_uint *object, uint operand);
-uint __ovld atomic_fetch_add_explicit(volatile atomic_uint *object, uint 
operand, memory_order order);
-uint __ovld atomic_fetch_add_explicit(volatile atomic_uint *object, uint 
operand, memory_order order, memory_scope scope);
 int __ovld atomic_fetch_sub(volatile atomic_int *object, int operand);
-int __ovld atomic_fetch_sub_explicit(volatile atomic_int *object, int operand, 
memory_order order);
-int __ovld atomic_fetch_sub_explicit(volatile atomic_int *object, int operand, 
memory_order order, memory_scope scope);
 uint __ovld atomic_fetch_sub(volatile atomic_uint *object, uint operand);
-uint __ovld atomic_fetch_sub_explicit(volatile atomic_uint *object, uint 
operand, memory_order order);
-uint __ovld atomic_fetch_sub_explicit(volatile atomic_uint *object, uint 
operand, memory_order order, memory_scope scope);
 int __ovld atomic_fetch_or(volatile atomic_int *object, int operand);
-int __ovld atomic_fetch_or_explicit(volatile atomic_int *object, int operand, 
memory_order order);
-int __ovld atomic_fetch_or_explicit(volatile atomic_int *object, int operand, 
memory_order order, memory_scope scope);
 uint __ovld atomic_fetch_or(volatile atomic_uint *object, uint operand);
-uint __ovld atomic_fetch_or_explicit(volatile atomic_uint *object, uint 
operand, memory_order order);
-uint __ovld atomic_fetch_or_explicit(volatile atomic_uint *object, uint 
operand, memory_order order, memory_scope scope);
 int __ovld atomic_fetch_xor(volatile atomic_int *object, int operand);
-int __ovld atomic_fetch_xor_explicit(volatile atomic_int *object, int operand, 
memory_order order);
-int __ovld atomic_fetch_xor_explicit(volatile atomic_int *object, int operand, 
memory_order order, memory_scope scope);
 uint __ovld atomic_fetch_xor(volatile atomic_uint *object, uint operand);
-uint __ovld atomic_fetch_xor_explicit(volatile atomic_uint *object, uint 
operand, memory_order order);
-uint __ovld atomic_fetch_xor_explicit(volatile atomic_uint *object, uint 
operand, memory_order order, memory_scope scope);
 int __ovld atomic_fetch_and(volatile atomic_int *object, int operand);
-int __ovld atomic_fetch_and_explicit(volatile atomic_int *object, int operand, 
memory_order order);
-int __ovld atomic_fetch_and_explicit(volatile atomic_int *object, int operand, 
memory_order order, memory_scope scope);
 uint __ovld atomic_fetch_and(volatile atomic_uint *object, uint operand);
-uint __ovld atomic_fetch_and_explicit(volatile atomic_uint *object, uint 
operand, memory_order order);
-uint __ovld atomic_fetch_and_explicit(volatile atomic_uint *object, uint 
operand, memory_order order, memory_scope scope);
 int __ovld atomic_fetch_min(volatile atomic_int *object, int operand);
-int __ovld atomic_fetch_min_explicit(volatile atomic_int *object, int operand, 
memory_order order);
-int __ovld atomic_fetch_min_explicit(volatile atomic_int *object, int operand, 
memory_order order, memory_scope scope);
 uint __ovld atomic_fetch_min(volatile atomic_uint *object, uint operand);
-uint __ovld atomic_fetch_min_explicit(volatile atomic_uint *object, uint 
operand, memory_order order);
-uint __ovld atomic_fetch_min_explicit(volatile atomic_uint *object, uint 
operand, memory_order order, memory_scope scope);
 int __ovld atomic_fetch_max(volatile atomic_int *object, int operand);
-int __ovld atomic_fetch_max_explicit(volatile atomic_int *object, int operand, 
memory_order order);
-int __ovld atomic_fetch_max_explicit(volatil

[PATCH] D105601: opencl-c.h: reorder atomic operations

2021-07-14 Thread Dave Airlie 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 rG090f007e3481: [OpenCL][NFC] opencl-c.h: reorder atomic 
operations (authored by airlied).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105601

Files:
  clang/lib/Headers/opencl-c.h

Index: clang/lib/Headers/opencl-c.h
===
--- clang/lib/Headers/opencl-c.h
+++ clang/lib/Headers/opencl-c.h
@@ -13306,91 +13306,35 @@
 // atomic_fetch()
 
 int __ovld atomic_fetch_add(volatile atomic_int *object, int operand);
-int __ovld atomic_fetch_add_explicit(volatile atomic_int *object, int operand, memory_order order);
-int __ovld atomic_fetch_add_explicit(volatile atomic_int *object, int operand, memory_order order, memory_scope scope);
 uint __ovld atomic_fetch_add(volatile atomic_uint *object, uint operand);
-uint __ovld atomic_fetch_add_explicit(volatile atomic_uint *object, uint operand, memory_order order);
-uint __ovld atomic_fetch_add_explicit(volatile atomic_uint *object, uint operand, memory_order order, memory_scope scope);
 int __ovld atomic_fetch_sub(volatile atomic_int *object, int operand);
-int __ovld atomic_fetch_sub_explicit(volatile atomic_int *object, int operand, memory_order order);
-int __ovld atomic_fetch_sub_explicit(volatile atomic_int *object, int operand, memory_order order, memory_scope scope);
 uint __ovld atomic_fetch_sub(volatile atomic_uint *object, uint operand);
-uint __ovld atomic_fetch_sub_explicit(volatile atomic_uint *object, uint operand, memory_order order);
-uint __ovld atomic_fetch_sub_explicit(volatile atomic_uint *object, uint operand, memory_order order, memory_scope scope);
 int __ovld atomic_fetch_or(volatile atomic_int *object, int operand);
-int __ovld atomic_fetch_or_explicit(volatile atomic_int *object, int operand, memory_order order);
-int __ovld atomic_fetch_or_explicit(volatile atomic_int *object, int operand, memory_order order, memory_scope scope);
 uint __ovld atomic_fetch_or(volatile atomic_uint *object, uint operand);
-uint __ovld atomic_fetch_or_explicit(volatile atomic_uint *object, uint operand, memory_order order);
-uint __ovld atomic_fetch_or_explicit(volatile atomic_uint *object, uint operand, memory_order order, memory_scope scope);
 int __ovld atomic_fetch_xor(volatile atomic_int *object, int operand);
-int __ovld atomic_fetch_xor_explicit(volatile atomic_int *object, int operand, memory_order order);
-int __ovld atomic_fetch_xor_explicit(volatile atomic_int *object, int operand, memory_order order, memory_scope scope);
 uint __ovld atomic_fetch_xor(volatile atomic_uint *object, uint operand);
-uint __ovld atomic_fetch_xor_explicit(volatile atomic_uint *object, uint operand, memory_order order);
-uint __ovld atomic_fetch_xor_explicit(volatile atomic_uint *object, uint operand, memory_order order, memory_scope scope);
 int __ovld atomic_fetch_and(volatile atomic_int *object, int operand);
-int __ovld atomic_fetch_and_explicit(volatile atomic_int *object, int operand, memory_order order);
-int __ovld atomic_fetch_and_explicit(volatile atomic_int *object, int operand, memory_order order, memory_scope scope);
 uint __ovld atomic_fetch_and(volatile atomic_uint *object, uint operand);
-uint __ovld atomic_fetch_and_explicit(volatile atomic_uint *object, uint operand, memory_order order);
-uint __ovld atomic_fetch_and_explicit(volatile atomic_uint *object, uint operand, memory_order order, memory_scope scope);
 int __ovld atomic_fetch_min(volatile atomic_int *object, int operand);
-int __ovld atomic_fetch_min_explicit(volatile atomic_int *object, int operand, memory_order order);
-int __ovld atomic_fetch_min_explicit(volatile atomic_int *object, int operand, memory_order order, memory_scope scope);
 uint __ovld atomic_fetch_min(volatile atomic_uint *object, uint operand);
-uint __ovld atomic_fetch_min_explicit(volatile atomic_uint *object, uint operand, memory_order order);
-uint __ovld atomic_fetch_min_explicit(volatile atomic_uint *object, uint operand, memory_order order, memory_scope scope);
 int __ovld atomic_fetch_max(volatile atomic_int *object, int operand);
-int __ovld atomic_fetch_max_explicit(volatile atomic_int *object, int operand, memory_order order);
-int __ovld atomic_fetch_max_explicit(volatile atomic_int *object, int operand, memory_order order, memory_scope scope);
 uint __ovld atomic_fetch_max(volatile atomic_uint *object, uint operand);
-uint __ovld atomic_fetch_max_explicit(volatile atomic_uint *object, uint operand, memory_order order);
-uint __ovld atomic_fetch_max_explicit(volatile atomic_uint *object, uint operand, memory_order order, memory_scope scope);
 
 #if defined(cl_khr_int64_base_atomics) && defined(cl_khr_int64_extended_atomics)
 long __ovld atomic_fetch_add(volatile atomic_long *object, long operand);
-long __ovld atomic_fetch_add_e

[clang] de79ba9 - [OpenCL] opencl-c.h: CL3.0 generic address space

2021-07-14 Thread Dave Airlie via cfe-commits

Author: Dave Airlie
Date: 2021-07-15T10:51:04+10:00
New Revision: de79ba9f9a2de3d86fa3f44b57e147844b6f2625

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

LOG: [OpenCL] opencl-c.h: CL3.0 generic address space

This is one of the easier pieces of adding CL3.0 support.

Reviewed By: Anastasia

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

Added: 


Modified: 
clang/lib/Headers/opencl-c.h

Removed: 




diff  --git a/clang/lib/Headers/opencl-c.h b/clang/lib/Headers/opencl-c.h
index 8a5b6c2919ad..d50f0b8d2e8f 100644
--- a/clang/lib/Headers/opencl-c.h
+++ b/clang/lib/Headers/opencl-c.h
@@ -7259,7 +7259,7 @@ half16 __ovld __cnfn fmod(half16 x, half16 y);
  * Returns fmin(x - floor (x), 0x1.fep-1f ).
  * floor(x) is returned in iptr.
  */
-#if defined(__OPENCL_CPP_VERSION__) || (__OPENCL_C_VERSION__ >= CL_VERSION_2_0)
+#if defined(__opencl_c_generic_address_space)
 float __ovld fract(float x, float *iptr);
 float2 __ovld fract(float2 x, float2 *iptr);
 float3 __ovld fract(float3 x, float3 *iptr);
@@ -7341,7 +7341,7 @@ half4 __ovld fract(half4 x, __private half4 *iptr);
 half8 __ovld fract(half8 x, __private half8 *iptr);
 half16 __ovld fract(half16 x, __private half16 *iptr);
 #endif //cl_khr_fp16
-#endif //defined(__OPENCL_CPP_VERSION__) || (__OPENCL_C_VERSION__ >= 
CL_VERSION_2_0)
+#endif //defined(__opencl_c_generic_address_space)
 
 /**
  * Extract mantissa and exponent from x. For each
@@ -7349,7 +7349,7 @@ half16 __ovld fract(half16 x, __private half16 *iptr);
  * magnitude in the interval [1/2, 1) or 0. Each
  * component of x equals mantissa returned * 2^exp.
  */
-#if defined(__OPENCL_CPP_VERSION__) || (__OPENCL_C_VERSION__ >= CL_VERSION_2_0)
+#if defined(__opencl_c_generic_address_space)
 float __ovld frexp(float x, int *exp);
 float2 __ovld frexp(float2 x, int2 *exp);
 float3 __ovld frexp(float3 x, int3 *exp);
@@ -7431,7 +7431,7 @@ half4 __ovld frexp(half4 x, __private int4 *exp);
 half8 __ovld frexp(half8 x, __private int8 *exp);
 half16 __ovld frexp(half16 x, __private int16 *exp);
 #endif //cl_khr_fp16
-#endif //defined(__OPENCL_CPP_VERSION__) || (__OPENCL_C_VERSION__ >= 
CL_VERSION_2_0)
+#endif //defined(__opencl_c_generic_address_space)
 
 /**
  * Compute the value of the square root of x^2 + y^2
@@ -7556,7 +7556,7 @@ half8 __ovld __cnfn lgamma(half8 x);
 half16 __ovld __cnfn lgamma(half16 x);
 #endif //cl_khr_fp16
 
-#if defined(__OPENCL_CPP_VERSION__) || (__OPENCL_C_VERSION__ >= CL_VERSION_2_0)
+#if defined(__opencl_c_generic_address_space)
 float __ovld lgamma_r(float x, int *signp);
 float2 __ovld lgamma_r(float2 x, int2 *signp);
 float3 __ovld lgamma_r(float3 x, int3 *signp);
@@ -7638,7 +7638,7 @@ half4 __ovld lgamma_r(half4 x, __private int4 *signp);
 half8 __ovld lgamma_r(half8 x, __private int8 *signp);
 half16 __ovld lgamma_r(half16 x, __private int16 *signp);
 #endif //cl_khr_fp16
-#endif //defined(__OPENCL_CPP_VERSION__) || (__OPENCL_C_VERSION__ >= 
CL_VERSION_2_0)
+#endif //defined(__opencl_c_generic_address_space)
 
 /**
  * Compute natural logarithm.
@@ -7862,7 +7862,7 @@ half16 __ovld __cnfn minmag(half16 x, half16 y);
  * the argument. It stores the integral part in the object
  * pointed to by iptr.
  */
-#if defined(__OPENCL_CPP_VERSION__) || (__OPENCL_C_VERSION__ >= CL_VERSION_2_0)
+#if defined(__opencl_c_generic_address_space)
 float __ovld modf(float x, float *iptr);
 float2 __ovld modf(float2 x, float2 *iptr);
 float3 __ovld modf(float3 x, float3 *iptr);
@@ -7944,7 +7944,7 @@ half4 __ovld modf(half4 x, __private half4 *iptr);
 half8 __ovld modf(half8 x, __private half8 *iptr);
 half16 __ovld modf(half16 x, __private half16 *iptr);
 #endif //cl_khr_fp16
-#endif //defined(__OPENCL_CPP_VERSION__) || (__OPENCL_C_VERSION__ >= 
CL_VERSION_2_0)
+#endif //defined(__opencl_c_generic_address_space)
 
 /**
  * Returns a quiet NaN. The nancode may be placed
@@ -8122,7 +8122,7 @@ half16 __ovld __cnfn remainder(half16 x, half16 y);
  * sign as x/y. It stores this signed value in the object
  * pointed to by quo.
  */
-#if defined(__OPENCL_CPP_VERSION__) || (__OPENCL_C_VERSION__ >= CL_VERSION_2_0)
+#if defined(__opencl_c_generic_address_space)
 float __ovld remquo(float x, float y, int *quo);
 float2 __ovld remquo(float2 x, float2 y, int2 *quo);
 float3 __ovld remquo(float3 x, float3 y, int3 *quo);
@@ -8205,7 +8205,7 @@ half4 __ovld remquo(half4 x, half4 y, __private int4 
*quo);
 half8 __ovld remquo(half8 x, half8 y, __private int8 *quo);
 half16 __ovld remquo(half16 x, half16 y, __private int16 *quo);
 #endif //cl_khr_fp16
-#endif //defined(__OPENCL_CPP_VERSION__) || (__OPENCL_C_VERSION__ >= 
CL_VERSION_2_0)
+#endif //defined(__opencl_c_generic_address_space)
 /**
  * Round to integral value (using round to nearest
  * even rounding mode) in f

[PATCH] D105526: opencl-c.h: CL3.0 generic address space

2021-07-14 Thread Dave Airlie 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 rGde79ba9f9a2d: [OpenCL] opencl-c.h: CL3.0 generic address 
space (authored by airlied).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105526

Files:
  clang/lib/Headers/opencl-c.h

Index: clang/lib/Headers/opencl-c.h
===
--- clang/lib/Headers/opencl-c.h
+++ clang/lib/Headers/opencl-c.h
@@ -7259,7 +7259,7 @@
  * Returns fmin(x - floor (x), 0x1.fep-1f ).
  * floor(x) is returned in iptr.
  */
-#if defined(__OPENCL_CPP_VERSION__) || (__OPENCL_C_VERSION__ >= CL_VERSION_2_0)
+#if defined(__opencl_c_generic_address_space)
 float __ovld fract(float x, float *iptr);
 float2 __ovld fract(float2 x, float2 *iptr);
 float3 __ovld fract(float3 x, float3 *iptr);
@@ -7341,7 +7341,7 @@
 half8 __ovld fract(half8 x, __private half8 *iptr);
 half16 __ovld fract(half16 x, __private half16 *iptr);
 #endif //cl_khr_fp16
-#endif //defined(__OPENCL_CPP_VERSION__) || (__OPENCL_C_VERSION__ >= CL_VERSION_2_0)
+#endif //defined(__opencl_c_generic_address_space)
 
 /**
  * Extract mantissa and exponent from x. For each
@@ -7349,7 +7349,7 @@
  * magnitude in the interval [1/2, 1) or 0. Each
  * component of x equals mantissa returned * 2^exp.
  */
-#if defined(__OPENCL_CPP_VERSION__) || (__OPENCL_C_VERSION__ >= CL_VERSION_2_0)
+#if defined(__opencl_c_generic_address_space)
 float __ovld frexp(float x, int *exp);
 float2 __ovld frexp(float2 x, int2 *exp);
 float3 __ovld frexp(float3 x, int3 *exp);
@@ -7431,7 +7431,7 @@
 half8 __ovld frexp(half8 x, __private int8 *exp);
 half16 __ovld frexp(half16 x, __private int16 *exp);
 #endif //cl_khr_fp16
-#endif //defined(__OPENCL_CPP_VERSION__) || (__OPENCL_C_VERSION__ >= CL_VERSION_2_0)
+#endif //defined(__opencl_c_generic_address_space)
 
 /**
  * Compute the value of the square root of x^2 + y^2
@@ -7556,7 +7556,7 @@
 half16 __ovld __cnfn lgamma(half16 x);
 #endif //cl_khr_fp16
 
-#if defined(__OPENCL_CPP_VERSION__) || (__OPENCL_C_VERSION__ >= CL_VERSION_2_0)
+#if defined(__opencl_c_generic_address_space)
 float __ovld lgamma_r(float x, int *signp);
 float2 __ovld lgamma_r(float2 x, int2 *signp);
 float3 __ovld lgamma_r(float3 x, int3 *signp);
@@ -7638,7 +7638,7 @@
 half8 __ovld lgamma_r(half8 x, __private int8 *signp);
 half16 __ovld lgamma_r(half16 x, __private int16 *signp);
 #endif //cl_khr_fp16
-#endif //defined(__OPENCL_CPP_VERSION__) || (__OPENCL_C_VERSION__ >= CL_VERSION_2_0)
+#endif //defined(__opencl_c_generic_address_space)
 
 /**
  * Compute natural logarithm.
@@ -7862,7 +7862,7 @@
  * the argument. It stores the integral part in the object
  * pointed to by iptr.
  */
-#if defined(__OPENCL_CPP_VERSION__) || (__OPENCL_C_VERSION__ >= CL_VERSION_2_0)
+#if defined(__opencl_c_generic_address_space)
 float __ovld modf(float x, float *iptr);
 float2 __ovld modf(float2 x, float2 *iptr);
 float3 __ovld modf(float3 x, float3 *iptr);
@@ -7944,7 +7944,7 @@
 half8 __ovld modf(half8 x, __private half8 *iptr);
 half16 __ovld modf(half16 x, __private half16 *iptr);
 #endif //cl_khr_fp16
-#endif //defined(__OPENCL_CPP_VERSION__) || (__OPENCL_C_VERSION__ >= CL_VERSION_2_0)
+#endif //defined(__opencl_c_generic_address_space)
 
 /**
  * Returns a quiet NaN. The nancode may be placed
@@ -8122,7 +8122,7 @@
  * sign as x/y. It stores this signed value in the object
  * pointed to by quo.
  */
-#if defined(__OPENCL_CPP_VERSION__) || (__OPENCL_C_VERSION__ >= CL_VERSION_2_0)
+#if defined(__opencl_c_generic_address_space)
 float __ovld remquo(float x, float y, int *quo);
 float2 __ovld remquo(float2 x, float2 y, int2 *quo);
 float3 __ovld remquo(float3 x, float3 y, int3 *quo);
@@ -8205,7 +8205,7 @@
 half8 __ovld remquo(half8 x, half8 y, __private int8 *quo);
 half16 __ovld remquo(half16 x, half16 y, __private int16 *quo);
 #endif //cl_khr_fp16
-#endif //defined(__OPENCL_CPP_VERSION__) || (__OPENCL_C_VERSION__ >= CL_VERSION_2_0)
+#endif //defined(__opencl_c_generic_address_space)
 /**
  * Round to integral value (using round to nearest
  * even rounding mode) in floating-point format.
@@ -8346,7 +8346,7 @@
  * is the return value and computed cosine is returned
  * in cosval.
  */
-#if defined(__OPENCL_CPP_VERSION__) || (__OPENCL_C_VERSION__ >= CL_VERSION_2_0)
+#if defined(__opencl_c_generic_address_space)
 float __ovld sincos(float x, float *cosval);
 float2 __ovld sincos(float2 x, float2 *cosval);
 float3 __ovld sincos(float3 x, float3 *cosval);
@@ -8428,7 +8428,7 @@
 half8 __ovld sincos(half8 x, __private half8 *cosval);
 half16 __ovld sincos(half16 x, __private half16 *cosval);
 #endif //cl_khr_fp16
-#endif //defined(__OPENCL_CPP_VERSION__) || (__OPENCL_C_VERSION__ >= CL_VERSION_2_0)
+#endif //defined(__opencl_c_generic_address_space)
 
 /**
  * Compute hyperbolic sine.
@@ -11249,7 +11249,7 @@
 half16 __ovl

[PATCH] D105328: [Frontend] Only compile modules if not already finalized

2021-07-14 Thread Ben Barham via Phabricator via cfe-commits
bnbarham updated this revision to Diff 358798.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105328

Files:
  clang/include/clang/Basic/DiagnosticCommonKinds.td
  clang/include/clang/Basic/DiagnosticSerializationKinds.td
  clang/include/clang/Serialization/ASTReader.h
  clang/lib/Frontend/CompilerInstance.cpp
  clang/lib/Serialization/ASTReader.cpp
  clang/unittests/Serialization/CMakeLists.txt
  clang/unittests/Serialization/ModuleCacheTest.cpp

Index: clang/unittests/Serialization/ModuleCacheTest.cpp
===
--- /dev/null
+++ clang/unittests/Serialization/ModuleCacheTest.cpp
@@ -0,0 +1,179 @@
+//===- unittests/Serialization/ModuleCacheTest.cpp - CI tests -===//
+//
+// 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/Basic/FileManager.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Frontend/CompilerInvocation.h"
+#include "clang/Frontend/FrontendActions.h"
+#include "clang/Lex/HeaderSearch.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/raw_ostream.h"
+
+#include "gtest/gtest.h"
+
+using namespace llvm;
+using namespace clang;
+
+namespace {
+
+class ModuleCacheTest : public ::testing::Test {
+  void SetUp() override {
+ASSERT_FALSE(sys::fs::createUniqueDirectory("modulecache-test", TestDir));
+
+ModuleCachePath = SmallString<256>(TestDir);
+sys::path::append(ModuleCachePath, "mcp");
+ASSERT_FALSE(sys::fs::create_directories(ModuleCachePath));
+  }
+
+  void TearDown() override { sys::fs::remove_directories(TestDir); }
+
+public:
+  SmallString<256> TestDir;
+  SmallString<256> ModuleCachePath;
+
+  void addFile(StringRef Path, StringRef Contents) {
+ASSERT_FALSE(sys::path::is_absolute(Path));
+
+SmallString<256> AbsPath(TestDir);
+sys::path::append(AbsPath, Path);
+
+std::error_code EC;
+ASSERT_FALSE(
+sys::fs::create_directories(llvm::sys::path::parent_path(AbsPath)));
+llvm::raw_fd_ostream OS(AbsPath, EC);
+ASSERT_FALSE(EC);
+OS << Contents;
+  }
+
+  void addDuplicateFrameworks() {
+addFile("test.m", R"cpp(
+@import Top;
+)cpp");
+
+addFile("frameworks/Top.framework/Headers/top.h", R"cpp(
+@import M;
+)cpp");
+addFile("frameworks/Top.framework/Modules/module.modulemap", R"cpp(
+framework module Top [system] {
+  header "top.h"
+  export *
+}
+)cpp");
+
+addFile("frameworks/M.framework/Headers/m.h", R"cpp(
+void foo();
+)cpp");
+addFile("frameworks/M.framework/Modules/module.modulemap", R"cpp(
+framework module M [system] {
+  header "m.h"
+  export *
+}
+)cpp");
+
+addFile("frameworks2/M.framework/Headers/m.h", R"cpp(
+void foo();
+)cpp");
+addFile("frameworks2/M.framework/Modules/module.modulemap", R"cpp(
+framework module M [system] {
+  header "m.h"
+  export *
+}
+)cpp");
+  }
+};
+
+TEST_F(ModuleCacheTest, CachedModuleNewPath) {
+  addDuplicateFrameworks();
+
+  SmallString<256> MCPArg("-fmodules-cache-path=");
+  MCPArg.append(ModuleCachePath);
+  IntrusiveRefCntPtr Diags =
+  CompilerInstance::createDiagnostics(new DiagnosticOptions());
+
+  // First run should pass with no errors
+  const char *Args[] = {"clang","-fmodules",  "-Fframeworks",
+MCPArg.c_str(), "-working-directory", TestDir.c_str(),
+"test.m"};
+  std::shared_ptr Invocation =
+  createInvocationFromCommandLine(Args, Diags);
+  ASSERT_TRUE(Invocation);
+  CompilerInstance Instance;
+  Instance.setDiagnostics(Diags.get());
+  Instance.setInvocation(Invocation);
+  SyntaxOnlyAction Action;
+  ASSERT_TRUE(Instance.ExecuteAction(Action));
+  ASSERT_FALSE(Diags->hasErrorOccurred());
+
+  // Now add `frameworks2` to the search path. `Top.pcm` will have a reference
+  // to the `M` from `frameworks`, but a search will find the `M` from
+  // `frameworks2` - causing a mismatch and it to be considered out of date.
+  //
+  // Normally this would be fine - `M` and the modules it depends on would be
+  // rebuilt. However, since we have a shared module cache and thus an already
+  // finalized `Top`, recompiling `Top` will cause the existing module to be
+  // removed from the cache, causing possible crashed if it is ever used.
+  //
+  // Make sure that an error occurs instead.
+  const char *Args2[] = {"clang", "-fmodules","-Fframeworks2",
+ "-Fframeworks",  MCPArg.c_str(), "-working-directory",
+ 

[PATCH] D105328: [Frontend] Only compile modules if not already finalized

2021-07-14 Thread Ben Barham via Phabricator via cfe-commits
bnbarham marked 2 inline comments as done.
bnbarham added inline comments.



Comment at: clang/lib/Frontend/CompilerInstance.cpp:1063
+<< ModuleName;
+return ImportingInstance.getFrontendOpts().AllowPCMWithCompilerErrors;
+  }

vsapsai wrote:
> bnbarham wrote:
> > bnbarham wrote:
> > > vsapsai wrote:
> > > > Can we get in infinite loop with `AllowPCMWithCompilerErrors = true`? 
> > > > Specifically, I'm thinking about the scenario
> > > > 
> > > > 1. `compileModuleAndReadAST` obtains a file lock and calls 
> > > > `compileModule`
> > > > 2. `compileModule` calls `compileModuleImpl`
> > > > 3. Module is finalized but `AllowPCMWithCompilerErrors` is true, so 
> > > > `compileModuleImpl` returns true
> > > > 4. `compileModule` returns true
> > > > 5. `compileModuleAndReadAST` tries to read AST because compilation was 
> > > > successful
> > > > 6. AST is out of date, so `compileModuleAndReadAST` decides to try 
> > > > again, goto 1
> > > > 
> > > > Haven't tried to reproduce it locally but even if this scenario is 
> > > > impossible, a corresponding test case can be useful.
> > > Nice catch, that does seem likely - I'll see if I can add a test for this.
> > It doesn't end up causing an infinite recursion as `false` will end up 
> > being returned from `compileModuleAndReadAST`, but in that case there's no 
> > point returning `true` from `compileModuleImpl` in the first place so I've 
> > changed it anyway. Have also added that as a test case, just to make sure.
> Thanks for investigating it and adding a test case.
> 
> And appreciate that the error message mentions the module name. It is so hard 
> to work with errors like "cannot rebuild this module".
Note that this error is really just a fallback - it will be silenced by the 
previous fatal errors in ASTReader.



Comment at: clang/lib/Serialization/ASTReader.cpp:2859-2860
   << F.FileName << !F.ModuleName.empty() << F.ModuleName;
+if (recompileFinalized)
+  Diag(diag::note_module_file_conflict);
 

The failing test was because this note was being output when if `OutOfDate` 
wasn't in `Capabilities`. It should only get output when `OutOfDate` can be 
handled (ie. it'd be recompiled) *and* the module is already finalized.



Comment at: clang/lib/Serialization/ASTReader.cpp:5929
 
+bool ASTReader::diagnoseOutOfDate(StringRef ModuleFileName,
+  unsigned int ClientLoadCapabilities) {

vsapsai wrote:
> bnbarham wrote:
> > bnbarham wrote:
> > > vsapsai wrote:
> > > > Based on the rest of the code in clang, the expectation for 
> > > > `diagnose...` methods is to emit diagnostic in some cases. Personally, 
> > > > I'm often confused what true/false means for these methods, so I'm 
> > > > thinking about renaming the method to something like 
> > > > isRecoverableOutOfDateModule, canRecoverOutOfDateModule or some such. 
> > > > Feel free to pick a name you believe is appropriate, mine are just 
> > > > examples.
> > > Fair enough, `canRecoverOutOfDateModule` sounds reasonable to me. Or 
> > > maybe `canRecoverFromOutOfDate`?
> > I went with the latter.
> I think with the current naming we need to flip the conditions to opposite. 
> Currently,
> 
> ```lang=c++
>   return !(ClientLoadCapabilities & ARR_OutOfDate) ||
>  getModuleManager().getModuleCache().isPCMFinal(ModuleFileName);
> ```
> 
> corresponds to `cannotRecoverFromOutOfDate`. But to avoid double negations it 
> is better to have `canRecoverFromOutOfDate` (with `(ClientLoadCapabilities & 
> ARR_OutOfDate) && !isPCMFinal(ModuleFileName)`) and call it as 
> `!canRecoverFromOutOfDate` when necessary.
Argh, sorry - just did a find + replace without thinking. Have flipped that 
function and its calls.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105328

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


[PATCH] D106030: [Clang] add support for error+warning fn attrs

2021-07-14 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers created this revision.
nickdesaulniers added reviewers: rsmith, aaron.ballman, craig.topper, efriedma, 
lebedev.ri, jdoerfert, arsenm.
Herald added subscribers: dexonsmith, hiraditya.
nickdesaulniers requested review of this revision.
Herald added subscribers: llvm-commits, cfe-commits, wdng.
Herald added projects: clang, LLVM.

Add support for the GNU C style __attribute__((error(""))) and
__attribute__((warning(""))). These attributes are meant to be put on
definitions of functions whom should not be called.

They are frequently used to provide compile time diagnostics similar to
_Static_assert, but which may rely on non-ICE conditions (ie. relying on
compiler optimizations). While users may instead simply call undefined
functions in such cases to get a linkage failure from the linker, these
provide a much more ergonomic and actionable diagnostic to users and do
so at compile time rather than at link time.

These are used throughout the Linux kernel in its implementation of
BUILD_BUG and BUILD_BUG_ON macros. These macros generally cannot be
converted to use _Static_assert because many of the parameters are not
ICEs. The Linux kernel still needs to be modified to make use of these
when building with Clang; I have a patch that does so I will send once
this feature is landed.

To do so, we create a new IR level Function attribute,
"user-diagnostic"="" which contains the string parameter from source
language function attributes (both error and warning boil down to one IR
Fn Attr). Then, similar to calls to inline asm, we attach a !srcloc
Metadata node to call sites of such attributed callees.

The backend diagnoses these before instruction selection, while we still
know that a call is a call (vs say a JMP that's a tail call) in an arch
agnostic manner.

The frontend then reconstructs the SourceLocation from that Metadata,
and determines whether to emit an error or warning based on the callee's
attribute.

Some things to iron out TODO:

- Is user-diagnostic the best identifier for the new fn attr? Maybe 
"diagnose-if-called"? I also use `UserDiagnostic` throughout much of this patch 
for C++ class names; surely there's something better?
- When is the best time for the backend to produce such diagnostics? If we wait 
until post-ISEL, then we need to diagnose instructions which may be JMPs, not 
just CALLs.

Link: https://bugs.llvm.org/show_bug.cgi?id=16428
Link: https://github.com/ClangBuiltLinux/linux/issues/1173


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D106030

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/include/clang/Basic/DiagnosticFrontendKinds.td
  clang/include/clang/Basic/DiagnosticGroups.td
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CodeGenAction.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/test/CodeGen/attr-error.c
  clang/test/CodeGen/attr-warning.c
  clang/test/Frontend/backend-attribute-error-warning-optimize.c
  clang/test/Frontend/backend-attribute-error-warning.c
  clang/test/Frontend/backend-attribute-error-warning.cpp
  clang/test/Misc/pragma-attribute-supported-attributes-list.test
  clang/test/Sema/attr-error.c
  clang/test/Sema/attr-warning.c
  llvm/docs/LangRef.rst
  llvm/include/llvm/IR/DiagnosticInfo.h
  llvm/lib/CodeGen/PreISelIntrinsicLowering.cpp
  llvm/lib/IR/DiagnosticInfo.cpp
  llvm/test/CodeGen/Generic/attr-user-diagnostic.ll

Index: llvm/test/CodeGen/Generic/attr-user-diagnostic.ll
===
--- /dev/null
+++ llvm/test/CodeGen/Generic/attr-user-diagnostic.ll
@@ -0,0 +1,9 @@
+; RUN: not llc -stop-after=pre-isel-intrinsic-lowering %s 2>&1 | FileCheck %s
+
+declare void @foo() "user-diagnostic"="oh no"
+define void @bar() {
+  call void @foo()
+  ret void
+}
+
+; CHECK: error: call to foo: oh no
Index: llvm/lib/IR/DiagnosticInfo.cpp
===
--- llvm/lib/IR/DiagnosticInfo.cpp
+++ llvm/lib/IR/DiagnosticInfo.cpp
@@ -401,3 +401,7 @@
 
 void OptimizationRemarkAnalysisFPCommute::anchor() {}
 void OptimizationRemarkAnalysisAliasing::anchor() {}
+
+void DiagnosticInfoUser::print(DiagnosticPrinter &DP) const {
+  DP << "call to " << getFunctionName() << ": " << getMsgStr();
+}
Index: llvm/lib/CodeGen/PreISelIntrinsicLowering.cpp
===
--- llvm/lib/CodeGen/PreISelIntrinsicLowering.cpp
+++ llvm/lib/CodeGen/PreISelIntrinsicLowering.cpp
@@ -14,6 +14,7 @@
 #include "llvm/CodeGen/PreISelIntrinsicLowering.h"
 #include "llvm/Analysis/ObjCARCInstKind.h"
 #include "llvm/CodeGen/Passes.h"
+#include "llvm/IR/DiagnosticInfo.h"
 #include "llvm/IR/Function.h"
 #include "llvm/IR/IRBuilder.h"
 #include "llvm/IR/Instructions.h"
@@ -204,6 +205,25 @@
   Changed |= lowerObjCCall(F, "objc_sync_exit");
   break;
 }
+// TODO: is this the best pass for this?
+ 

[PATCH] D106030: [Clang] add support for error+warning fn attrs

2021-07-14 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm added inline comments.



Comment at: llvm/lib/CodeGen/PreISelIntrinsicLowering.cpp:208
 }
+// TODO: is this the best pass for this?
+for (BasicBlock &BB : F) {

Why not just do in in codegen in IRTranslator/SelectionDAGBuilder?



Comment at: llvm/lib/CodeGen/PreISelIntrinsicLowering.cpp:212
+if (CallBase *CB = dyn_cast(&I)) {
+  if (Function *Callee = CB->getCalledFunction()) {
+if (Callee->hasFnAttribute("user-diagnostic")) {

What's the expected behavior if the function is called indirectly?



Comment at: llvm/lib/CodeGen/PreISelIntrinsicLowering.cpp:219
+  DiagnosticInfoUser DU(
+  Callee->getFnAttribute("user-diagnostic").getValueAsString(),
+  Callee->getName(), LocCookie);

Just do one getFnAttribute instead of pre-checking it?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106030

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


[PATCH] D106030: [Clang] add support for error+warning fn attrs

2021-07-14 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers updated this revision to Diff 358814.
nickdesaulniers added a comment.

- remove accidentally committed logging statement


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106030

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/include/clang/Basic/DiagnosticFrontendKinds.td
  clang/include/clang/Basic/DiagnosticGroups.td
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CodeGenAction.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/test/CodeGen/attr-error.c
  clang/test/CodeGen/attr-warning.c
  clang/test/Frontend/backend-attribute-error-warning-optimize.c
  clang/test/Frontend/backend-attribute-error-warning.c
  clang/test/Frontend/backend-attribute-error-warning.cpp
  clang/test/Misc/pragma-attribute-supported-attributes-list.test
  clang/test/Sema/attr-error.c
  clang/test/Sema/attr-warning.c
  llvm/docs/LangRef.rst
  llvm/include/llvm/IR/DiagnosticInfo.h
  llvm/lib/CodeGen/PreISelIntrinsicLowering.cpp
  llvm/lib/IR/DiagnosticInfo.cpp
  llvm/test/CodeGen/Generic/attr-user-diagnostic.ll

Index: llvm/test/CodeGen/Generic/attr-user-diagnostic.ll
===
--- /dev/null
+++ llvm/test/CodeGen/Generic/attr-user-diagnostic.ll
@@ -0,0 +1,9 @@
+; RUN: not llc -stop-after=pre-isel-intrinsic-lowering %s 2>&1 | FileCheck %s
+
+declare void @foo() "user-diagnostic"="oh no"
+define void @bar() {
+  call void @foo()
+  ret void
+}
+
+; CHECK: error: call to foo: oh no
Index: llvm/lib/IR/DiagnosticInfo.cpp
===
--- llvm/lib/IR/DiagnosticInfo.cpp
+++ llvm/lib/IR/DiagnosticInfo.cpp
@@ -401,3 +401,7 @@
 
 void OptimizationRemarkAnalysisFPCommute::anchor() {}
 void OptimizationRemarkAnalysisAliasing::anchor() {}
+
+void DiagnosticInfoUser::print(DiagnosticPrinter &DP) const {
+  DP << "call to " << getFunctionName() << ": " << getMsgStr();
+}
Index: llvm/lib/CodeGen/PreISelIntrinsicLowering.cpp
===
--- llvm/lib/CodeGen/PreISelIntrinsicLowering.cpp
+++ llvm/lib/CodeGen/PreISelIntrinsicLowering.cpp
@@ -14,6 +14,7 @@
 #include "llvm/CodeGen/PreISelIntrinsicLowering.h"
 #include "llvm/Analysis/ObjCARCInstKind.h"
 #include "llvm/CodeGen/Passes.h"
+#include "llvm/IR/DiagnosticInfo.h"
 #include "llvm/IR/Function.h"
 #include "llvm/IR/IRBuilder.h"
 #include "llvm/IR/Instructions.h"
@@ -204,6 +205,25 @@
   Changed |= lowerObjCCall(F, "objc_sync_exit");
   break;
 }
+// TODO: is this the best pass for this?
+for (BasicBlock &BB : F) {
+  for (Instruction &I : BB) {
+if (CallBase *CB = dyn_cast(&I)) {
+  if (Function *Callee = CB->getCalledFunction()) {
+if (Callee->hasFnAttribute("user-diagnostic")) {
+  unsigned LocCookie = 0;
+  if (MDNode *MD = CB->getMetadata("srcloc"))
+LocCookie = mdconst::extract(MD->getOperand(0))
+->getZExtValue();
+  DiagnosticInfoUser DU(
+  Callee->getFnAttribute("user-diagnostic").getValueAsString(),
+  Callee->getName(), LocCookie);
+  F.getContext().diagnose(DU);
+}
+  }
+}
+  }
+}
   }
   return Changed;
 }
Index: llvm/include/llvm/IR/DiagnosticInfo.h
===
--- llvm/include/llvm/IR/DiagnosticInfo.h
+++ llvm/include/llvm/IR/DiagnosticInfo.h
@@ -79,6 +79,7 @@
   DK_PGOProfile,
   DK_Unsupported,
   DK_SrcMgr,
+  DK_UserDiagnostic,
   DK_FirstPluginKind // Must be last value to work with
  // getNextAvailablePluginDiagnosticKind
 };
@@ -1070,6 +1071,25 @@
   }
 };
 
+class DiagnosticInfoUser : public DiagnosticInfo {
+  StringRef MsgStr;
+  StringRef CalleeName;
+  unsigned LocCookie;
+
+public:
+  DiagnosticInfoUser(StringRef MsgStr, StringRef CalleeName, unsigned LocCookie,
+ DiagnosticSeverity Severity = DS_Error)
+  : DiagnosticInfo(DK_UserDiagnostic, Severity), MsgStr(MsgStr),
+CalleeName(CalleeName), LocCookie(LocCookie) {}
+  StringRef getMsgStr() const { return MsgStr; }
+  StringRef getFunctionName() const { return CalleeName; }
+  unsigned getLocCookie() const { return LocCookie; }
+  void print(DiagnosticPrinter &DP) const override;
+  static bool classof(const DiagnosticInfo *DI) {
+return DI->getKind() == DK_UserDiagnostic;
+  }
+};
+
 } // end namespace llvm
 
 #endif // LLVM_IR_DIAGNOSTICINFO_H
Index: llvm/docs/LangRef.rst
===
--- llvm/docs/LangRef.rst
+++ llvm/docs/LangRef.rst
@@ -2037,6 +2037,12 @@
 show that no exceptions passes by it. This is normally the case for
 the ELF x86-64 abi, but it can be d

[PATCH] D106030: [Clang] add support for error+warning fn attrs

2021-07-14 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm added a comment.

Adding something to the IR for the sole purpose of producing a diagnostic feels 
really weird. I'm not sure I see why the frontend can't see this attribute and 
directly warn


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106030

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


[PATCH] D105984: [PowerPC] Restore FastMathFlags of Builder for Vector FDiv Builtins

2021-07-14 Thread Qiu Chaofan via Phabricator via cfe-commits
qiucf added inline comments.



Comment at: clang/lib/CodeGen/CGBuiltin.cpp:15140
+  Value *fdiv = Builder.CreateFDiv(X, Y, "recipdiv");
+  Builder.getFastMathFlags().operator&=(FMF);
+  return fdiv;




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105984

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


[PATCH] D105269: [X86] AVX512FP16 instructions enabling 6/6

2021-07-14 Thread LuoYuanke via Phabricator via cfe-commits
LuoYuanke added inline comments.



Comment at: llvm/test/CodeGen/X86/avx512cfma-intrinsics.ll:3
+; RUN: llc < %s -mtriple=x86_64-apple-darwin -mcpu=knl -mattr=+avx512bw 
-mattr=+avx512fp16 -mattr=+avx512vl | FileCheck %s
+
+declare <4 x float> @llvm.x86.avx512fp16.mask.vfmaddc.ph.128(<4 x float>, <4 x 
float>, <4 x float>, i8)

Do we miss broadcast test case?



Comment at: llvm/test/CodeGen/X86/avx512cfmul-intrinsics.ll:3
+; RUN: llc < %s -mtriple=x86_64-apple-darwin -mcpu=knl -mattr=+avx512bw 
-mattr=+avx512fp16 -mattr=+avx512vl | FileCheck %s
+
+declare <4 x float> @llvm.x86.avx512fp16.mask.vfmulc.ph.128(<4 x float>, <4 x 
float>, <4 x float>, i8)

Do we miss broadcast test case?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105269

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


[PATCH] D105328: [Frontend] Only compile modules if not already finalized

2021-07-14 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai accepted this revision.
vsapsai added a comment.
This revision is now accepted and ready to land.

Have 1 punctuation nit (that I'm not sure about), the rest looks good.




Comment at: clang/lib/Serialization/ASTReader.cpp:2854
+bool recompileFinalized =
+Result == OutOfDate && Capabilities & ARR_OutOfDate &&
+getModuleManager().getModuleCache().isPCMFinal(F.FileName);

I don't remember recommended LLVM style or if clang-tidy would complain about 
it but `... & ... && ...` can be unclear regarding the priority of operations. 
Personally, I would do `(... & ...) && ...` but I don't know what is the rule, 
so not insisting.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105328

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


[PATCH] D105328: [Frontend] Only compile modules if not already finalized

2021-07-14 Thread Ben Barham via Phabricator via cfe-commits
bnbarham updated this revision to Diff 358826.
bnbarham marked 2 inline comments as done.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105328

Files:
  clang/include/clang/Basic/DiagnosticCommonKinds.td
  clang/include/clang/Basic/DiagnosticSerializationKinds.td
  clang/include/clang/Serialization/ASTReader.h
  clang/lib/Frontend/CompilerInstance.cpp
  clang/lib/Serialization/ASTReader.cpp
  clang/unittests/Serialization/CMakeLists.txt
  clang/unittests/Serialization/ModuleCacheTest.cpp

Index: clang/unittests/Serialization/ModuleCacheTest.cpp
===
--- /dev/null
+++ clang/unittests/Serialization/ModuleCacheTest.cpp
@@ -0,0 +1,179 @@
+//===- unittests/Serialization/ModuleCacheTest.cpp - CI tests -===//
+//
+// 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/Basic/FileManager.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Frontend/CompilerInvocation.h"
+#include "clang/Frontend/FrontendActions.h"
+#include "clang/Lex/HeaderSearch.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/raw_ostream.h"
+
+#include "gtest/gtest.h"
+
+using namespace llvm;
+using namespace clang;
+
+namespace {
+
+class ModuleCacheTest : public ::testing::Test {
+  void SetUp() override {
+ASSERT_FALSE(sys::fs::createUniqueDirectory("modulecache-test", TestDir));
+
+ModuleCachePath = SmallString<256>(TestDir);
+sys::path::append(ModuleCachePath, "mcp");
+ASSERT_FALSE(sys::fs::create_directories(ModuleCachePath));
+  }
+
+  void TearDown() override { sys::fs::remove_directories(TestDir); }
+
+public:
+  SmallString<256> TestDir;
+  SmallString<256> ModuleCachePath;
+
+  void addFile(StringRef Path, StringRef Contents) {
+ASSERT_FALSE(sys::path::is_absolute(Path));
+
+SmallString<256> AbsPath(TestDir);
+sys::path::append(AbsPath, Path);
+
+std::error_code EC;
+ASSERT_FALSE(
+sys::fs::create_directories(llvm::sys::path::parent_path(AbsPath)));
+llvm::raw_fd_ostream OS(AbsPath, EC);
+ASSERT_FALSE(EC);
+OS << Contents;
+  }
+
+  void addDuplicateFrameworks() {
+addFile("test.m", R"cpp(
+@import Top;
+)cpp");
+
+addFile("frameworks/Top.framework/Headers/top.h", R"cpp(
+@import M;
+)cpp");
+addFile("frameworks/Top.framework/Modules/module.modulemap", R"cpp(
+framework module Top [system] {
+  header "top.h"
+  export *
+}
+)cpp");
+
+addFile("frameworks/M.framework/Headers/m.h", R"cpp(
+void foo();
+)cpp");
+addFile("frameworks/M.framework/Modules/module.modulemap", R"cpp(
+framework module M [system] {
+  header "m.h"
+  export *
+}
+)cpp");
+
+addFile("frameworks2/M.framework/Headers/m.h", R"cpp(
+void foo();
+)cpp");
+addFile("frameworks2/M.framework/Modules/module.modulemap", R"cpp(
+framework module M [system] {
+  header "m.h"
+  export *
+}
+)cpp");
+  }
+};
+
+TEST_F(ModuleCacheTest, CachedModuleNewPath) {
+  addDuplicateFrameworks();
+
+  SmallString<256> MCPArg("-fmodules-cache-path=");
+  MCPArg.append(ModuleCachePath);
+  IntrusiveRefCntPtr Diags =
+  CompilerInstance::createDiagnostics(new DiagnosticOptions());
+
+  // First run should pass with no errors
+  const char *Args[] = {"clang","-fmodules",  "-Fframeworks",
+MCPArg.c_str(), "-working-directory", TestDir.c_str(),
+"test.m"};
+  std::shared_ptr Invocation =
+  createInvocationFromCommandLine(Args, Diags);
+  ASSERT_TRUE(Invocation);
+  CompilerInstance Instance;
+  Instance.setDiagnostics(Diags.get());
+  Instance.setInvocation(Invocation);
+  SyntaxOnlyAction Action;
+  ASSERT_TRUE(Instance.ExecuteAction(Action));
+  ASSERT_FALSE(Diags->hasErrorOccurred());
+
+  // Now add `frameworks2` to the search path. `Top.pcm` will have a reference
+  // to the `M` from `frameworks`, but a search will find the `M` from
+  // `frameworks2` - causing a mismatch and it to be considered out of date.
+  //
+  // Normally this would be fine - `M` and the modules it depends on would be
+  // rebuilt. However, since we have a shared module cache and thus an already
+  // finalized `Top`, recompiling `Top` will cause the existing module to be
+  // removed from the cache, causing possible crashed if it is ever used.
+  //
+  // Make sure that an error occurs instead.
+  const char *Args2[] = {"clang", "-fmodules","-Fframeworks2",
+ "-Fframeworks",  MCPArg.c_str(), "-wor

[PATCH] D105328: [Frontend] Only compile modules if not already finalized

2021-07-14 Thread Ben Barham via Phabricator via cfe-commits
bnbarham marked an inline comment as done.
bnbarham added inline comments.



Comment at: clang/lib/Serialization/ASTReader.cpp:2854
+bool recompileFinalized =
+Result == OutOfDate && Capabilities & ARR_OutOfDate &&
+getModuleManager().getModuleCache().isPCMFinal(F.FileName);

vsapsai wrote:
> I don't remember recommended LLVM style or if clang-tidy would complain about 
> it but `... & ... && ...` can be unclear regarding the priority of 
> operations. Personally, I would do `(... & ...) && ...` but I don't know what 
> is the rule, so not insisting.
I don't feel particularly strongly about it either way, so have just updated to 
add the parentheses :).

Also renamed `recompileFinalized` to `recompilingFinalized` as I thought that 
made more sense after coming back to it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105328

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


[PATCH] D105973: [ASTMatchers] NFC: Fix the annotation.

2021-07-14 Thread gehry via Phabricator via cfe-commits
Sockke updated this revision to Diff 358820.
Sockke edited the summary of this revision.
Sockke added a comment.

Thanks for your review! I have run clang/docs/tools/dump_ast_matchers.py to 
regenerate the documentation.


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

https://reviews.llvm.org/D105973

Files:
  clang/docs/LibASTMatchersReference.html
  clang/include/clang/ASTMatchers/ASTMatchers.h


Index: clang/include/clang/ASTMatchers/ASTMatchers.h
===
--- clang/include/clang/ASTMatchers/ASTMatchers.h
+++ clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -913,7 +913,7 @@
 ///varDecl(hasInitializer(integerLiteral()))
 ///varDecl(hasInitializer(declRefExpr()))
 /// \endcode
-/// only match the declarations for b, c, and d.
+/// only match the declarations for a.
 AST_MATCHER_P(Expr, ignoringImpCasts,
   internal::Matcher, InnerMatcher) {
   return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder);
Index: clang/docs/LibASTMatchersReference.html
===
--- clang/docs/LibASTMatchersReference.html
+++ clang/docs/LibASTMatchersReference.html
@@ -7701,7 +7721,7 @@
 While
varDecl(hasInitializer(integerLiteral()))
varDecl(hasInitializer(declRefExpr()))
-only match the declarations for b, c, and d.
+only match the declarations for a.
 
 
 


Index: clang/include/clang/ASTMatchers/ASTMatchers.h
===
--- clang/include/clang/ASTMatchers/ASTMatchers.h
+++ clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -913,7 +913,7 @@
 ///varDecl(hasInitializer(integerLiteral()))
 ///varDecl(hasInitializer(declRefExpr()))
 /// \endcode
-/// only match the declarations for b, c, and d.
+/// only match the declarations for a.
 AST_MATCHER_P(Expr, ignoringImpCasts,
   internal::Matcher, InnerMatcher) {
   return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder);
Index: clang/docs/LibASTMatchersReference.html
===
--- clang/docs/LibASTMatchersReference.html
+++ clang/docs/LibASTMatchersReference.html
@@ -7701,7 +7721,7 @@
 While
varDecl(hasInitializer(integerLiteral()))
varDecl(hasInitializer(declRefExpr()))
-only match the declarations for b, c, and d.
+only match the declarations for a.
 
 
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D105957: [PowerPC] Implement intrinsics for mtfsf[i]

2021-07-14 Thread Qiu Chaofan via Phabricator via cfe-commits
qiucf accepted this revision.
qiucf added a comment.
This revision is now accepted and ready to land.

The PPC instructions tablegen part looks good to me.




Comment at: llvm/include/llvm/IR/IntrinsicsPowerPC.td:1589
[IntrNoMem, IntrHasSideEffects]>;
   def int_ppc_mtfsfi
   : GCCBuiltin<"__builtin_ppc_mtfsfi">,

If `mtfsf` was changed, `mtfsfi` `mtfsb0` `mtfsb1` should also be changed?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105957

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


[PATCH] D105973: [ASTMatchers] NFC: Fix the annotation.

2021-07-14 Thread liushuai wang via Phabricator via cfe-commits
MTC accepted this revision.
MTC added a comment.
This revision is now accepted and ready to land.

LGTM, thanks for your cleanup.


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

https://reviews.llvm.org/D105973

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


[PATCH] D106030: [Clang] add support for error+warning fn attrs

2021-07-14 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added a comment.

In D106030#2878897 , @arsenm wrote:

> Adding something to the IR for the sole purpose of producing a diagnostic 
> feels really weird. I'm not sure I see why the frontend can't see this 
> attribute and directly warn

In C++, you can do trickery with template arguments to trigger compile errors, 
for example, the following:

  #include 
  template struct dependent_false : std::false_type {};
  template inline void f() {
if constexpr (x == 0) {
  /* do something */
} else if constexpr (x == 1) {
  /* do something else */
} else {
  static_assert(dependent_false() && "Invalid argument");
}
  }
  void g() { f<1>(); }

Now suppose you're an enterprising Linux kernel developer, and you decide you 
want this in C.  You don't really care about portability to compilers other 
than gcc, or compiling at any optimization level less than -O2, so instead of 
using a real language feature, you decide to depend on a combination of 
unintentional compiler semantics and linker diagnostics.  So you write 
something like the following:

  #define BUILD_BUG() undefined_symbol()
  extern void undefined_symbol();
  
  inline void f(int x) {
if (x == 0) {
  /* do something */
} else if (x == 1) {
  /* do something else */
} else {
  BUILD_BUG();
}
  }
  void g() { f(1); }

Then, after you're doing this for a while, you ask the gcc developers for a 
simple feature: an attribute you can apply to undefined_symbol that makes the 
compiler print the error message at compile-time instead of link-time.

---

Actually, in clang, you could probably use inline asm like the following to 
accomplish roughly the same thing, assuming you aren't building with 
-fno-integrated-as:

  #define BUILD_BUG() asm(".err \"BUILD_BUG\"")
  static inline void f(int x) {
if (x == 0) {
  /* do something */
} else if (x == 1) {
  /* do something else */
} else {
  BUILD_BUG();
}
  }
  void g() { f(2); }


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106030

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


[PATCH] D105973: [ASTMatchers] NFC: Fix the annotation.

2021-07-14 Thread gehry via Phabricator via cfe-commits
Sockke updated this revision to Diff 358835.
Sockke added a comment.

update to display context.


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

https://reviews.llvm.org/D105973

Files:
  clang/docs/LibASTMatchersReference.html
  clang/include/clang/ASTMatchers/ASTMatchers.h


Index: clang/include/clang/ASTMatchers/ASTMatchers.h
===
--- clang/include/clang/ASTMatchers/ASTMatchers.h
+++ clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -913,7 +913,7 @@
 ///varDecl(hasInitializer(integerLiteral()))
 ///varDecl(hasInitializer(declRefExpr()))
 /// \endcode
-/// only match the declarations for b, c, and d.
+/// only match the declarations for a.
 AST_MATCHER_P(Expr, ignoringImpCasts,
   internal::Matcher, InnerMatcher) {
   return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder);
Index: clang/docs/LibASTMatchersReference.html
===
--- clang/docs/LibASTMatchersReference.html
+++ clang/docs/LibASTMatchersReference.html
@@ -7701,7 +7701,7 @@
 While
varDecl(hasInitializer(integerLiteral()))
varDecl(hasInitializer(declRefExpr()))
-only match the declarations for b, c, and d.
+only match the declarations for a.
 
 
 


Index: clang/include/clang/ASTMatchers/ASTMatchers.h
===
--- clang/include/clang/ASTMatchers/ASTMatchers.h
+++ clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -913,7 +913,7 @@
 ///varDecl(hasInitializer(integerLiteral()))
 ///varDecl(hasInitializer(declRefExpr()))
 /// \endcode
-/// only match the declarations for b, c, and d.
+/// only match the declarations for a.
 AST_MATCHER_P(Expr, ignoringImpCasts,
   internal::Matcher, InnerMatcher) {
   return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder);
Index: clang/docs/LibASTMatchersReference.html
===
--- clang/docs/LibASTMatchersReference.html
+++ clang/docs/LibASTMatchersReference.html
@@ -7701,7 +7701,7 @@
 While
varDecl(hasInitializer(integerLiteral()))
varDecl(hasInitializer(declRefExpr()))
-only match the declarations for b, c, and d.
+only match the declarations for a.
 
 
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D105821: [analyzer] [WIP] Model destructor for std::unique_ptr

2021-07-14 Thread Deep Majumder via Phabricator via cfe-commits
RedDocMD updated this revision to Diff 358839.
RedDocMD added a comment.

Cleanup, still doesn't work


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105821

Files:
  clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
  clang/lib/StaticAnalyzer/Core/CheckerManager.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp


Index: clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
===
--- clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
+++ clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
@@ -19,6 +19,7 @@
 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "llvm/Support/raw_ostream.h"
 
 using namespace clang;
 using namespace ento;
@@ -757,6 +758,7 @@
   for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
I != E; ++I)
 defaultEvalCall(Bldr, *I, *Call, CallOpts);
+  getCheckerManager().runCheckersForEvalCall(DstInvalidated, DstPreCall, 
*Call, *this, CallOpts);
 
   getCheckerManager().runCheckersForPostCall(Dst, DstInvalidated,
  *Call, *this);
Index: clang/lib/StaticAnalyzer/Core/CheckerManager.cpp
===
--- clang/lib/StaticAnalyzer/Core/CheckerManager.cpp
+++ clang/lib/StaticAnalyzer/Core/CheckerManager.cpp
@@ -664,14 +664,11 @@
 for (const auto &EvalCallChecker : EvalCallCheckers) {
   // TODO: Support the situation when the call doesn't correspond
   // to any Expr.
-  ProgramPoint L = ProgramPoint::getProgramPoint(
-  Call.getOriginExpr(), ProgramPoint::PostStmtKind,
-  Pred->getLocationContext(), EvalCallChecker.Checker);
   bool evaluated = false;
   { // CheckerContext generates transitions(populates checkDest) on
 // destruction, so introduce the scope to make sure it gets properly
 // populated.
-CheckerContext C(B, Eng, Pred, L);
+CheckerContext C(B, Eng, Pred, Call.getProgramPoint());
 evaluated = EvalCallChecker(Call, C);
   }
   assert(!(evaluated && anyEvaluated)
Index: clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
+++ clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
@@ -177,7 +177,9 @@
 
 bool SmartPtrModeling::evalCall(const CallEvent &Call,
 CheckerContext &C) const {
+
   ProgramStateRef State = C.getState();
+  Call.dump();
   if (!smartptr::isStdSmartPtrCall(Call))
 return false;
 
@@ -261,6 +263,11 @@
 return true;
   }
 
+  if (const auto *DC = dyn_cast(&Call)) {
+llvm::errs() << "Wohoo\n";
+return true;
+  }
+
   if (handleAssignOp(Call, C))
 return true;
 


Index: clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
===
--- clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
+++ clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
@@ -19,6 +19,7 @@
 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "llvm/Support/raw_ostream.h"
 
 using namespace clang;
 using namespace ento;
@@ -757,6 +758,7 @@
   for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
I != E; ++I)
 defaultEvalCall(Bldr, *I, *Call, CallOpts);
+  getCheckerManager().runCheckersForEvalCall(DstInvalidated, DstPreCall, *Call, *this, CallOpts);
 
   getCheckerManager().runCheckersForPostCall(Dst, DstInvalidated,
  *Call, *this);
Index: clang/lib/StaticAnalyzer/Core/CheckerManager.cpp
===
--- clang/lib/StaticAnalyzer/Core/CheckerManager.cpp
+++ clang/lib/StaticAnalyzer/Core/CheckerManager.cpp
@@ -664,14 +664,11 @@
 for (const auto &EvalCallChecker : EvalCallCheckers) {
   // TODO: Support the situation when the call doesn't correspond
   // to any Expr.
-  ProgramPoint L = ProgramPoint::getProgramPoint(
-  Call.getOriginExpr(), ProgramPoint::PostStmtKind,
-  Pred->getLocationContext(), EvalCallChecker.Checker);
   bool evaluated = false;
   { // CheckerContext generates transitions(populates checkDest) on
 // destruction, so introduce the scope to make sure it gets properly
 // populated.
-CheckerContext C(B, Eng, Pred, L);
+CheckerContext C(B, Eng, Pred, Call.getProgramPoint());
 evaluated = EvalCallChecker(Call, C);
   }
   assert(!(evaluated && anyEvaluated)
Index: clang/lib/StaticAnalyzer/Chec

[PATCH] D104420: thread_local support for AIX

2021-07-14 Thread Hubert Tong via Phabricator via cfe-commits
hubert.reinterpretcast added inline comments.



Comment at: clang/lib/CodeGen/CGDeclCXX.cpp:265
 
+/// Create a stub function, suitable for being passed to atexit,
+/// which passes the given address to the given destructor function.

Since the function has some specifics about the stub function type and return 
value behaviour:
s/atexit/__pt_atexit_np/;




Comment at: clang/lib/CodeGen/ItaniumCXXABI.cpp:2959
+isEmittedWithConstantInitializer(VD, true) &&
+!VD->needsDestruction(getContext())) {
+  llvm::Function *Func = llvm::Function::Create(

An assertion that `Init` is null should be appropriate here: If it is non-null, 
then the pre-existing logic above would either be defining the function to be 
an alias or is declaring the function with the expectation that the definition 
of the variable is elsewhere.



Comment at: clang/lib/CodeGen/ItaniumCXXABI.cpp:2961
+  llvm::Function *Func = llvm::Function::Create(
+  InitFnTy, llvm::GlobalVariable::ExternalLinkage, InitFnName.str(),
+  &CGM.getModule());

The linkage should be weak for a variable defined to be weak. For example, the 
code higher up uses `Var->getLinkage()` to produce the alias.



Comment at: clang/lib/CodeGen/ItaniumCXXABI.cpp:2988-2989
+} else if (CGM.getTriple().isOSAIX()) {
+  // On AIX, thread_local vars, other than non-class types or (possibly
+  // multi-dimensional) arrays or such types, will have init routines
+  // regardless of whether they are const-initialized or not.  Since the

This does not say that a `thread_local` variable of type `int` that is not 
`constinit` //does// have a guaranteed init routine.

Suggestion:
On AIX, except if constinit and also neither of class type or of (possibly 
multi-dimensional) array of class type, thread_local vars will have init 
routines regardless of whether they are const-initialized.



Comment at: clang/test/CodeGenCXX/cxx11-thread-local.cpp:241
   // LINUX: call i32 @__cxa_thread_atexit({{.*}}@_ZN1SD1Ev {{.*}} 
@_ZZ8tls_dtorvE1s{{.*}} @__dso_handle
+  // AIX: call i32 (i32, i32 (i32, ...)*, ...) @__pt_atexit_np(i32 0, 
{{.*}}@__dtor__ZZ8tls_dtorvE1s){{.*}}
   // DARWIN: call i32 @_tlv_atexit({{.*}}@_ZN1SD1Ev {{.*}} 
@_ZZ8tls_dtorvE1s{{.*}} @__dso_handle

Since the code to generate the stub is new, I believe inspecting the body of 
the stub in the test would be appropriate.


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

https://reviews.llvm.org/D104420

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


[clang] 8a1727b - [Coroutines] Run coroutine passes by default

2021-07-14 Thread Chuanqi Xu via cfe-commits

Author: Chuanqi Xu
Date: 2021-07-15T14:33:40+08:00
New Revision: 8a1727ba51d262365b0d9fe10fef7e50da7022cd

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

LOG: [Coroutines] Run coroutine passes by default

This patch make coroutine passes run by default in LLVM pipeline. Now
the clang and opt could handle IR inputs containing coroutine intrinsics
without special options.
It should be fine. On the one hand, the coroutine passes seems to be stable
since there are already many projects using coroutine feature.
On the other hand, the coroutine passes should do nothing for IR who doesn't
contain coroutine intrinsic.

Test Plan: check-llvm

Reviewed by: lxfind, aeubanks

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

Added: 


Modified: 
clang/lib/CodeGen/BackendUtil.cpp
clang/test/CodeGen/lto-newpm-pipeline.c
clang/test/CodeGenCoroutines/coro-always-inline.cpp
clang/test/CodeGenCoroutines/coro-symmetric-transfer-01.cpp
llvm/include/llvm-c/Transforms/PassBuilder.h
llvm/include/llvm/Passes/PassBuilder.h
llvm/lib/Passes/PassBuilder.cpp
llvm/lib/Passes/PassBuilderBindings.cpp
llvm/lib/Transforms/Utils/InlineFunction.cpp
llvm/test/Other/new-pm-O0-defaults.ll
llvm/test/Other/new-pm-defaults.ll
llvm/test/Other/new-pm-thinlto-defaults.ll
llvm/test/Other/new-pm-thinlto-postlink-pgo-defaults.ll
llvm/test/Other/new-pm-thinlto-postlink-samplepgo-defaults.ll
llvm/test/Other/new-pm-thinlto-prelink-pgo-defaults.ll
llvm/test/Other/new-pm-thinlto-prelink-samplepgo-defaults.ll
llvm/tools/opt/NewPMDriver.cpp
llvm/tools/opt/NewPMDriver.h
llvm/tools/opt/opt.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index bafcf7cb8a8f5..9aa67ed2a67ba 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -1265,7 +1265,6 @@ void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
   // Only enable CGProfilePass when using integrated assembler, since
   // non-integrated assemblers don't recognize .cgprofile section.
   PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
-  PTO.Coroutines = LangOpts.Coroutines;
 
   LoopAnalysisManager LAM;
   FunctionAnalysisManager FAM;

diff  --git a/clang/test/CodeGen/lto-newpm-pipeline.c 
b/clang/test/CodeGen/lto-newpm-pipeline.c
index c8220e3547e14..c2cd3a4720cca 100644
--- a/clang/test/CodeGen/lto-newpm-pipeline.c
+++ b/clang/test/CodeGen/lto-newpm-pipeline.c
@@ -28,6 +28,8 @@
 // CHECK-FULL-O0: Running pass: AlwaysInlinerPass
 // CHECK-FULL-O0-NEXT: Running analysis: InnerAnalysisManagerProxy
 // CHECK-FULL-O0-NEXT: Running analysis: ProfileSummaryAnalysis
+// CHECK-FULL-O0: Running pass: CoroSplitPass
+// CHECK-FULL-O0-NEXT: Running pass: CoroCleanupPass
 // CHECK-FULL-O0-NEXT: Running pass: CanonicalizeAliasesPass
 // CHECK-FULL-O0-NEXT: Running pass: NameAnonGlobalPass
 // CHECK-FULL-O0-NEXT: Running pass: BitcodeWriterPass
@@ -35,6 +37,7 @@
 // CHECK-THIN-O0: Running pass: AlwaysInlinerPass
 // CHECK-THIN-O0-NEXT: Running analysis: InnerAnalysisManagerProxy
 // CHECK-THIN-O0-NEXT: Running analysis: ProfileSummaryAnalysis
+// CHECK-THIN-O0: Running pass: CoroCleanupPass
 // CHECK-THIN-O0-NEXT: Running pass: CanonicalizeAliasesPass
 // CHECK-THIN-O0-NEXT: Running pass: NameAnonGlobalPass
 // CHECK-THIN-O0-NEXT: Running pass: ThinLTOBitcodeWriterPass

diff  --git a/clang/test/CodeGenCoroutines/coro-always-inline.cpp 
b/clang/test/CodeGenCoroutines/coro-always-inline.cpp
index e4aa14a6ac397..ef7183b9642d5 100644
--- a/clang/test/CodeGenCoroutines/coro-always-inline.cpp
+++ b/clang/test/CodeGenCoroutines/coro-always-inline.cpp
@@ -40,15 +40,13 @@ struct coroutine_traits {
 
 // CHECK-LABEL: @_Z3foov
 // CHECK-LABEL: entry:
-// CHECK-NEXT: %this.addr.i{{[0-9]*}} = alloca 
%"struct.std::experimental::awaitable"*, align 8
-// CHECK-NEXT: %this.addr.i{{[0-9]*}} = alloca 
%"struct.std::experimental::awaitable"*, align 8
-// CHECK: [[CAST0:%[0-9]+]] = bitcast %"struct.std::experimental::awaitable"** 
%this.addr.i{{[0-9]*}} to i8*
-// CHECK-NEXT: call void @llvm.lifetime.start.p0i8(i64 8, i8* [[CAST0]])
-// CHECK: [[CAST1:%[0-9]+]] = bitcast %"struct.std::experimental::awaitable"** 
%this.addr.i{{[0-9]*}} to i8*
-// CHECK-NEXT: call void @llvm.lifetime.end.p0i8(i64 8, i8* [[CAST1]])
-
-// CHECK: [[CAST2:%[0-9]+]] = bitcast %"struct.std::experimental::awaitable"** 
%this.addr.i{{[0-9]*}} to i8*
-// CHECK-NEXT: call void @llvm.lifetime.start.p0i8(i64 8, i8* [[CAST2]])
-// CHECK: [[CAST3:%[0-9]+]] = bitcast %"struct.std::experimental::awaitable"** 
%this.addr.i{{[0-9]*}} to i8*
-// CHECK-NEXT: call void @llvm.lifetime.end.p0i8(i64 8, i8* [[CAST3]])
+// CHECK: [[CAST0:%[0-9]+]] = bitcast %"struct.std::experiment

[PATCH] D105877: [Coroutines] Run coroutine passes by default

2021-07-14 Thread Chuanqi Xu 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 rG8a1727ba51d2: [Coroutines] Run coroutine passes by default 
(authored by ChuanqiXu).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105877

Files:
  clang/lib/CodeGen/BackendUtil.cpp
  clang/test/CodeGen/lto-newpm-pipeline.c
  clang/test/CodeGenCoroutines/coro-always-inline.cpp
  clang/test/CodeGenCoroutines/coro-symmetric-transfer-01.cpp
  llvm/include/llvm-c/Transforms/PassBuilder.h
  llvm/include/llvm/Passes/PassBuilder.h
  llvm/lib/Passes/PassBuilder.cpp
  llvm/lib/Passes/PassBuilderBindings.cpp
  llvm/lib/Transforms/Utils/InlineFunction.cpp
  llvm/test/Other/new-pm-O0-defaults.ll
  llvm/test/Other/new-pm-defaults.ll
  llvm/test/Other/new-pm-thinlto-defaults.ll
  llvm/test/Other/new-pm-thinlto-postlink-pgo-defaults.ll
  llvm/test/Other/new-pm-thinlto-postlink-samplepgo-defaults.ll
  llvm/test/Other/new-pm-thinlto-prelink-pgo-defaults.ll
  llvm/test/Other/new-pm-thinlto-prelink-samplepgo-defaults.ll
  llvm/tools/opt/NewPMDriver.cpp
  llvm/tools/opt/NewPMDriver.h
  llvm/tools/opt/opt.cpp

Index: llvm/tools/opt/opt.cpp
===
--- llvm/tools/opt/opt.cpp
+++ llvm/tools/opt/opt.cpp
@@ -831,7 +831,7 @@
ThinLinkOut.get(), RemarksFile.get(), PassPipeline,
Passes, OK, VK, PreserveAssemblyUseListOrder,
PreserveBitcodeUseListOrder, EmitSummaryIndex,
-   EmitModuleHash, EnableDebugify, Coroutines)
+   EmitModuleHash, EnableDebugify)
? 0
: 1;
   }
Index: llvm/tools/opt/NewPMDriver.h
===
--- llvm/tools/opt/NewPMDriver.h
+++ llvm/tools/opt/NewPMDriver.h
@@ -73,7 +73,7 @@
  bool ShouldPreserveAssemblyUseListOrder,
  bool ShouldPreserveBitcodeUseListOrder,
  bool EmitSummaryIndex, bool EmitModuleHash,
- bool EnableDebugify, bool Coroutines);
+ bool EnableDebugify);
 } // namespace llvm
 
 #endif
Index: llvm/tools/opt/NewPMDriver.cpp
===
--- llvm/tools/opt/NewPMDriver.cpp
+++ llvm/tools/opt/NewPMDriver.cpp
@@ -241,7 +241,7 @@
bool ShouldPreserveAssemblyUseListOrder,
bool ShouldPreserveBitcodeUseListOrder,
bool EmitSummaryIndex, bool EmitModuleHash,
-   bool EnableDebugify, bool Coroutines) {
+   bool EnableDebugify) {
   bool VerifyEachPass = VK == VK_VerifyEachPass;
 
   Optional P;
@@ -305,7 +305,6 @@
   // to false above so we shouldn't necessarily need to check whether or not the
   // option has been enabled.
   PTO.LoopUnrolling = !DisableLoopUnrolling;
-  PTO.Coroutines = Coroutines;
   PassBuilder PB(TM, PTO, P, &PIC);
   registerEPCallbacks(PB);
 
Index: llvm/test/Other/new-pm-thinlto-prelink-samplepgo-defaults.ll
===
--- llvm/test/Other/new-pm-thinlto-prelink-samplepgo-defaults.ll
+++ llvm/test/Other/new-pm-thinlto-prelink-samplepgo-defaults.ll
@@ -40,6 +40,7 @@
 ; CHECK-O-NEXT: Running analysis: DominatorTreeAnalysis
 ; CHECK-O-NEXT: Running pass: EarlyCSEPass
 ; CHECK-O-NEXT: Running analysis: TargetLibraryAnalysis
+; CHECK-O-NEXT: Running pass: CoroEarlyPass
 ; CHECK-O3-NEXT: Running pass: CallSiteSplittingPass
 ; CHECK-O-NEXT: Running pass: InstCombinePass on foo
 ; CHECK-O-NEXT: Running analysis: OptimizationRemarkEmitterAnalysis on foo
@@ -146,18 +147,22 @@
 ; CHECK-O23SZ-NEXT: Running analysis: LazyValueAnalysis
 ; CHECK-O23SZ-NEXT: Running pass: CorrelatedValuePropagationPass
 ; CHECK-O23SZ-NEXT: Invalidating analysis: LazyValueAnalysis
+; CHECK-O1-NEXT: Running pass: CoroElidePass
 ; CHECK-O-NEXT: Running pass: ADCEPass
 ; CHECK-O23SZ-NEXT: Running pass: MemCpyOptPass
 ; CHECK-O23SZ-NEXT: Running pass: DSEPass
 ; CHECK-O23SZ-NEXT: Running pass: LoopSimplifyPass
 ; CHECK-O23SZ-NEXT: Running pass: LCSSAPass
 ; CHECK-O23SZ-NEXT: Running pass: LICMPass
+; CHECK-O23SZ-NEXT: Running pass: CoroElidePass
 ; CHECK-O-NEXT: Running pass: SimplifyCFGPass
 ; CHECK-O-NEXT: Running pass: InstCombinePass
 ; CHECK-O3-NEXT: Running pass: ControlHeightReductionPass on foo
 ; CHECK-O3-NEXT: Running analysis: RegionInfoAnalysis on foo
 ; CHECK-O3-NEXT: Running analysis: DominanceFrontierAnalysis on foo
+; CHECK-O-NEXT: Running pass: CoroSplitPass
 ; CHECK-O-NEXT: Running pass: GlobalOptPass
+; CHECK-O-NEXT: Running pass: CoroCleanupPass
 ; CHECK-O-NEXT: Running pass: AnnotationRemarksPa

[PATCH] D103938: Diagnose -Wunused-value in constant evaluation context

2021-07-14 Thread Yuanfang Chen via Phabricator via cfe-commits
ychen added a comment.

ping


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103938

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


[PATCH] D105964: [clang-format] Make AlwaysBreakAfterReturnType work with K&R C function definitions

2021-07-14 Thread Owen Pan via Phabricator via cfe-commits
owenpan created this revision.
owenpan added reviewers: djasper, klimek, MyDeveloperDay, curdeius, 
HazardyKnusperkeks.
owenpan added a project: clang-format.
owenpan requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

See PR50999 .


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D105964

Files:
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/FormatTest.cpp


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -8209,6 +8209,16 @@
"}\n",
Style);
 
+  Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+  Style.BraceWrapping.AfterFunction = true;
+  verifyFormat("int f(i);\n" // No break here.
+   "int\n"   // Break here.
+   "f(i)\n"
+   "{\n"
+   "  return i + 1;\n"
+   "}\n",
+   Style);
+
   Style = getGNUStyle();
 
   // Test for comments at the end of function declarations.
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -2476,6 +2476,14 @@
   if (Next->MatchingParen->Next &&
   Next->MatchingParen->Next->is(TT_PointerOrReference))
 return true;
+  // Check for K&R C function definitions, e.g.:
+  //   int f(i)
+  //   {
+  // return i + 1;
+  //   }
+  if (Next->Next && Next->Next->is(tok::identifier) &&
+  !(Next->MatchingParen->Next && Next->MatchingParen->Next->is(tok::semi)))
+return true;
   for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen;
Tok = Tok->Next) {
 if (Tok->is(TT_TypeDeclarationParen))


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -8209,6 +8209,16 @@
"}\n",
Style);
 
+  Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+  Style.BraceWrapping.AfterFunction = true;
+  verifyFormat("int f(i);\n" // No break here.
+   "int\n"   // Break here.
+   "f(i)\n"
+   "{\n"
+   "  return i + 1;\n"
+   "}\n",
+   Style);
+
   Style = getGNUStyle();
 
   // Test for comments at the end of function declarations.
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -2476,6 +2476,14 @@
   if (Next->MatchingParen->Next &&
   Next->MatchingParen->Next->is(TT_PointerOrReference))
 return true;
+  // Check for K&R C function definitions, e.g.:
+  //   int f(i)
+  //   {
+  // return i + 1;
+  //   }
+  if (Next->Next && Next->Next->is(tok::identifier) &&
+  !(Next->MatchingParen->Next && Next->MatchingParen->Next->is(tok::semi)))
+return true;
   for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen;
Tok = Tok->Next) {
 if (Tok->is(TT_TypeDeclarationParen))
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D105703: [hwasan] Use stack safety analysis.

2021-07-14 Thread Vitaly Buka via Phabricator via cfe-commits
vitalybuka added inline comments.



Comment at: clang/test/CodeGen/hwasan-stack-safety-analysis-asm.c:4
+
+int main(int argc, char **argv) {
+  char buf[10];

this patch mostly change code under llvm/ so tests should be also there, as IR 
tests





Comment at: llvm/include/llvm/Transforms/Instrumentation/HWAddressSanitizer.h:32
+  Triple TargetTriple = {});
   PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM);
   static bool isRequired() { return true; }

Why not from M.getTargetTriple() ?



Comment at: llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp:200
 
+bool shouldUsePageAliases(const Triple &TargetTriple) {
+  return ClUsePageAliases && TargetTriple.getArch() == Triple::x86_64;

Could you please extract these function in a separate patch?
LLVM likes small close to NFC patches.



Comment at: llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp:390
+  void getAnalysisUsage(AnalysisUsage &AU) const override {
+if (shouldUseStackSafetyAnalysis(TargetTriple)) {
+  AU.addRequired();

why we need to check TargetTriple for that?



Comment at: llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp:1275
 bool HWAddressSanitizer::isInterestingAlloca(const AllocaInst &AI) {
+  // clang-format off
   return (AI.getAllocatedType()->isSized() &&

Instead of // clang-format off
could you replace this with

```
# comment1
if (...)
  return false;

# comment2
if (...)
  return false;
...

```

in a separate patch?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105703

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


[PATCH] D105964: [clang-format] Make AlwaysBreakAfterReturnType work with K&R C function definitions

2021-07-14 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

Thanks for this, I'm not sure I have the heart to dig out my old K&R code to 
test it ;-),   Assuming the tests are good then it LGTM.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105964

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


[PATCH] D105964: [clang-format] Make AlwaysBreakAfterReturnType work with K&R C function definitions

2021-07-14 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay accepted this revision.
MyDeveloperDay added a comment.
This revision is now accepted and ready to land.

Myabe give the others some time to take a look too


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105964

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


[PATCH] D105679: [clangd] Add CMake option to (not) link in clang-tidy checks

2021-07-14 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
sammccall marked an inline comment as done.
Closed by commit rG462d4de35b0c: [clangd] Add CMake option to (not) link in 
clang-tidy checks (authored by sammccall).

Changed prior to commit:
  https://reviews.llvm.org/D105679?vs=358241&id=358538#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105679

Files:
  clang-tools-extra/clangd/CMakeLists.txt
  clang-tools-extra/clangd/Features.cpp
  clang-tools-extra/clangd/Features.inc.in
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/test/diagnostics-tidy.test
  clang-tools-extra/clangd/test/diagnostics.test
  clang-tools-extra/clangd/test/lit.cfg.py
  clang-tools-extra/clangd/test/lit.site.cfg.py.in
  clang-tools-extra/clangd/unittests/ConfigCompileTests.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
@@ -10,6 +10,7 @@
 #include "Config.h"
 #include "Diagnostics.h"
 #include "FeatureModule.h"
+#include "Features.h"
 #include "ParsedAST.h"
 #include "Protocol.h"
 #include "SourceCode.h"
@@ -114,6 +115,18 @@
   return Res;
 }
 
+// Normally returns the provided diagnostics matcher.
+// If clang-tidy checks are not linked in, returns a matcher for no diagnostics!
+// This is intended for tests where the diagnostics come from clang-tidy checks.
+// We don't #ifdef each individual test as it's intrusive and we want to ensure
+// that as much of the test is still compiled an run as possible.
+::testing::Matcher>
+ifTidyChecks(::testing::Matcher> M) {
+  if (!CLANGD_TIDY_CHECKS)
+return IsEmpty();
+  return M;
+}
+
 TEST(DiagnosticsTest, DiagnosticRanges) {
   // Check we report correct ranges, including various edge-cases.
   Annotations Test(R"cpp(
@@ -121,8 +134,11 @@
 #define ID(X) X
 namespace test{};
 void $decl[[foo]]();
-class T{$explicit[[]]$constructor[[T]](int a);};
 int main() {
+  struct Container { int* begin(); int* end(); } *container;
+  for (auto i : $insertstar[[]]$range[[container]]) {
+  }
+
   $typo[[go\
 o]]();
   foo()$semicolon[[]]//with comments
@@ -135,10 +151,14 @@
 }
   )cpp");
   auto TU = TestTU::withCode(Test.code());
-  TU.ClangTidyProvider = addTidyChecks("google-explicit-constructor");
   EXPECT_THAT(
   *TU.build().getDiagnostics(),
   ElementsAre(
+  // Make sure the whole token is highlighted.
+  AllOf(Diag(Test.range("range"),
+ "invalid range expression of type 'struct Container *'; "
+ "did you mean to dereference it with '*'?"),
+WithFix(Fix(Test.range("insertstar"), "*", "insert '*'"))),
   // This range spans lines.
   AllOf(Diag(Test.range("typo"),
  "use of undeclared identifier 'goo'; did you mean 'foo'?"),
@@ -163,13 +183,7 @@
   AllOf(Diag(Test.range("macro"),
  "use of undeclared identifier 'fod'; did you mean 'foo'?"),
 WithFix(Fix(Test.range("macroarg"), "foo",
-"change 'fod' to 'foo'"))),
-  // We make sure here that the entire token is highlighted
-  AllOf(Diag(Test.range("constructor"),
- "single-argument constructors must be marked explicit to "
- "avoid unintentional implicit conversions"),
-WithFix(Fix(Test.range("explicit"), "explicit ",
-"insert 'explicit '");
+"change 'fod' to 'foo'");
 }
 
 TEST(DiagnosticsTest, FlagsMatter) {
@@ -212,10 +226,10 @@
   // Verify that we filter out the duplicated diagnostic message.
   EXPECT_THAT(
   *TU.build().getDiagnostics(),
-  UnorderedElementsAre(::testing::AllOf(
+  ifTidyChecks(UnorderedElementsAre(::testing::AllOf(
   Diag(Test.range(),
"floating point literal has suffix 'f', which is not uppercase"),
-  DiagSource(Diag::ClangTidy;
+  DiagSource(Diag::ClangTidy);
 
   Test = Annotations(R"cpp(
 template
@@ -232,10 +246,10 @@
   // duplicated messages, verify that we deduplicate them.
   EXPECT_THAT(
   *TU.build().getDiagnostics(),
-  UnorderedElementsAre(::testing::AllOf(
+  ifTidyChecks(UnorderedElementsAre(::testing::AllOf(
   Diag(Test.range(),
"floating point literal has suffix 'f', which is not uppercase"),
-  DiagSource(Diag::ClangTidy;
+  DiagSource(Diag::ClangTidy);
 }
 
 TEST(DiagnosticsTest, ClangTidy) {
@@ -265,9 +279,10 @@
"modernize-deprecated-headers,"
  

[clang-tools-extra] 462d4de - [clangd] Add CMake option to (not) link in clang-tidy checks

2021-07-14 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2021-07-14T10:04:21+02:00
New Revision: 462d4de35b0c9ef7157e49e147fc448a40c829b1

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

LOG: [clangd] Add CMake option to (not) link in clang-tidy checks

This reduces the size of the dependency graph and makes incremental
development a little more pleasant (less rebuilding).

This introduces a bit of complexity/fragility as some tests verify
clang-tidy behavior. I attempted to isolate these and build/run as much
of the tests as possible in both configs to prevent rot.

Expectation is that (some) developers will use this locally, but
buildbots etc will keep testing clang-tidy.

Fixes https://github.com/clangd/clangd/issues/233

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

Added: 
clang-tools-extra/clangd/test/diagnostics-tidy.test

Modified: 
clang-tools-extra/clangd/CMakeLists.txt
clang-tools-extra/clangd/Features.cpp
clang-tools-extra/clangd/Features.inc.in
clang-tools-extra/clangd/ParsedAST.cpp
clang-tools-extra/clangd/test/lit.cfg.py
clang-tools-extra/clangd/test/lit.site.cfg.py.in
clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp
clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp

Removed: 
clang-tools-extra/clangd/test/diagnostics.test



diff  --git a/clang-tools-extra/clangd/CMakeLists.txt 
b/clang-tools-extra/clangd/CMakeLists.txt
index 3c2b097e89fd1..5aee128c9d6b5 100644
--- a/clang-tools-extra/clangd/CMakeLists.txt
+++ b/clang-tools-extra/clangd/CMakeLists.txt
@@ -19,12 +19,15 @@ if (NOT DEFINED CLANGD_BUILD_XPC)
 endif ()
 
 option(CLANGD_MALLOC_TRIM "Call malloc_trim(3) periodically in Clangd. (only 
takes effect when using glibc)" ON)
+# -DCLANG_TIDY_CHECKS=Off avoids a dependency on clang-tidy, reducing rebuilds.
+option(CLANGD_TIDY_CHECKS "Link all clang-tidy checks into clangd" ON)
 
 llvm_canonicalize_cmake_booleans(
   CLANGD_BUILD_XPC
   CLANGD_ENABLE_REMOTE
   ENABLE_GRPC_REFLECTION
   CLANGD_MALLOC_TRIM
+  CLANGD_TIDY_CHECKS
   LLVM_ENABLE_ZLIB
 )
 
@@ -162,10 +165,12 @@ target_link_libraries(clangDaemon
   ${LLVM_PTHREAD_LIB}
 
   clangTidy
-  ${ALL_CLANG_TIDY_CHECKS}
 
   clangdSupport
   )
+if(CLANGD_TIDY_CHECKS)
+  target_link_libraries(clangDaemon PRIVATE ${ALL_CLANG_TIDY_CHECKS})
+endif()
 
 add_subdirectory(refactor/tweaks)
 if (${CMAKE_SYSTEM_NAME} STREQUAL "Linux")

diff  --git a/clang-tools-extra/clangd/Features.cpp 
b/clang-tools-extra/clangd/Features.cpp
index 17f475fc4c22b..4ec03ea84bfb4 100644
--- a/clang-tools-extra/clangd/Features.cpp
+++ b/clang-tools-extra/clangd/Features.cpp
@@ -48,6 +48,10 @@ std::string featureString() {
 #if CLANGD_BUILD_XPC
   "+xpc"
 #endif
+
+#if !CLANGD_TIDY_CHECKS
+  "-tidy"
+#endif
   ;
 }
 

diff  --git a/clang-tools-extra/clangd/Features.inc.in 
b/clang-tools-extra/clangd/Features.inc.in
index 72464d89b830e..b6c3729b0bb8d 100644
--- a/clang-tools-extra/clangd/Features.inc.in
+++ b/clang-tools-extra/clangd/Features.inc.in
@@ -3,3 +3,4 @@
 #define CLANGD_ENABLE_REMOTE @CLANGD_ENABLE_REMOTE@
 #define ENABLE_GRPC_REFLECTION @ENABLE_GRPC_REFLECTION@
 #define CLANGD_MALLOC_TRIM @CLANGD_MALLOC_TRIM@
+#define CLANGD_TIDY_CHECKS @CLANGD_TIDY_CHECKS@

diff  --git a/clang-tools-extra/clangd/ParsedAST.cpp 
b/clang-tools-extra/clangd/ParsedAST.cpp
index cb8ad5a8fa9ff..2520062eed9b5 100644
--- a/clang-tools-extra/clangd/ParsedAST.cpp
+++ b/clang-tools-extra/clangd/ParsedAST.cpp
@@ -15,6 +15,7 @@
 #include "Config.h"
 #include "Diagnostics.h"
 #include "FeatureModule.h"
+#include "Features.h"
 #include "Headers.h"
 #include "HeuristicResolver.h"
 #include "IncludeFixer.h"
@@ -60,8 +61,10 @@
 
 // Force the linker to link in Clang-tidy modules.
 // clangd doesn't support the static analyzer.
+#if CLANGD_TIDY_CHECKS
 #define CLANG_TIDY_DISABLE_STATIC_ANALYZER_CHECKS
 #include "../clang-tidy/ClangTidyForceLinker.h"
+#endif
 
 namespace clang {
 namespace clangd {

diff  --git a/clang-tools-extra/clangd/test/diagnostics.test 
b/clang-tools-extra/clangd/test/diagnostics-tidy.test
similarity index 69%
rename from clang-tools-extra/clangd/test/diagnostics.test
rename to clang-tools-extra/clangd/test/diagnostics-tidy.test
index 588fefdbf2e06..1d10541be8bf0 100644
--- a/clang-tools-extra/clangd/test/diagnostics.test
+++ b/clang-tools-extra/clangd/test/diagnostics-tidy.test
@@ -1,27 +1,12 @@
+# REQUIRES: clangd-tidy-checks
 # RUN: clangd -lit-test -clang-tidy-checks=bugprone-sizeof-expression < %s | 
FileCheck -strict-whitespace %s
 
{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"processId":123,"rootPath":"clangd","capabilities":{},"trace":"off"}}
 ---
-{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"test:///foo.c","languageId":"c","text":"void
 main() {\n(void

[PATCH] D105950: [WebAssembly] Codegen for v128.loadX_lane instructions

2021-07-14 Thread Heejin Ahn via Phabricator via cfe-commits
aheejin added inline comments.



Comment at: clang/lib/Headers/wasm_simd128.h:174
+static __inline__ v128_t __DEFAULT_FN_ATTRS wasm_v128_load8_lane(
+const void *__ptr, v128_t __vec, int __i) __REQUIRE_CONSTANT(__i) {
+  struct __wasm_v128_load8_lane_struct {

Nit: Other similar functions in this file seem to be using `__mem` instead of 
`__ptr`? (Currently only builtins are using `__ptr`)



Comment at: llvm/lib/Target/WebAssembly/WebAssemblyInstrSIMD.td:324
+  PatFrag<(ops node:$ptr, node:$vec, node:$idx),
+  (vector_insert $vec, (i32 (extloadi8 $ptr)), $idx)>;
+def load16_lane :

Why are i8 and i16 are extended-loaded?



Comment at: llvm/test/CodeGen/WebAssembly/simd-build-vector.ll:7
 
-target datalayout = "e-m:e-p:32:32-i64:64-n32:64-S128"
 target triple = "wasm32-unknown-unknown"

This seems already contained in D105842? The same for the other files.



Comment at: llvm/test/CodeGen/WebAssembly/simd-build-vector.ll:214
 ; CHECK:   v128.const  $push[[L0:[0-9]+]]=, 0, 0, 0, 0, 42, 0, 0, 0, 
0, 0, 0, 0, 0, 0, 42, 0
-; CHECK:   i8x16.replace_lane
+; CHECK:   v128.load8_lane
 ; CHECK:   i8x16.replace_lane

Why the change?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105950

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


[PATCH] D105457: [clang] Refactor AST printing tests to share more infrastructure

2021-07-14 Thread Douglas Yung via Phabricator via cfe-commits
dyung added a comment.

If it helps, I have so far been able to reduce the file to this which still 
shows the failure when compiled with gcc 7.5:

  #include "ASTPrint.h"
  #include "clang/AST/ASTContext.h"
  #include "clang/ASTMatchers/ASTMatchFinder.h"
  #include "clang/Tooling/Tooling.h"
  #include "llvm/ADT/SmallString.h"
  #include "gtest/gtest.h"
  
  using namespace clang;
  using namespace ast_matchers;
  //using namespace tooling;


 
  
  namespace {
  
  enum class StdVer { CXX98, CXX11, CXX14, CXX17, CXX2a };
  
  DeclarationMatcher FunctionBodyMatcher(StringRef ContainingFunction) {
return functionDecl(hasName(ContainingFunction),
has(compoundStmt(has(stmt().bind("id");
  }
  
  static void PrintStmt(raw_ostream &Out, const ASTContext *Context,
const Stmt *S, PrintingPolicyAdjuster PolicyAdjuster) {
assert(S != nullptr && "Expected non-null Stmt");
PrintingPolicy Policy = Context->getPrintingPolicy();
if (PolicyAdjuster)
  PolicyAdjuster(Policy);
S->printPretty(Out, /*Helper*/ nullptr, Policy);
  }
  
  template 
  ::testing::AssertionResult
  PrintedStmtMatches(StringRef Code, const std::vector &Args,
 const Matcher &NodeMatch, StringRef ExpectedPrinted,
 PrintingPolicyAdjuster PolicyAdjuster = nullptr) {
return PrintedNodeMatches(Code, Args, NodeMatch, ExpectedPrinted, "",
PrintStmt, PolicyAdjuster);
  }
  
  template 
  ::testing::AssertionResult
  PrintedStmtCXXMatches(StdVer Standard, StringRef Code, const T &NodeMatch,
StringRef ExpectedPrinted,
PrintingPolicyAdjuster PolicyAdjuster = nullptr) {
const char *StdOpt;
switch (Standard) {
case StdVer::CXX98: StdOpt = "-std=c++98"; break;
case StdVer::CXX11: StdOpt = "-std=c++11"; break;
case StdVer::CXX14: StdOpt = "-std=c++14"; break;
case StdVer::CXX17: StdOpt = "-std=c++17"; break;
case StdVer::CXX2a: StdOpt = "-std=c++2a"; break;
}
  
std::vector Args = {
  StdOpt,
  "-Wno-unused-value",
};
return PrintedStmtMatches(Code, Args, NodeMatch, ExpectedPrinted,
  PolicyAdjuster);
  }
  
  } // unnamed namespace
  
  TEST(StmtPrinter, TestIntegerLiteral) {
ASSERT_TRUE(PrintedStmtCXXMatches(StdVer::CXX98,
  "void A() {"
  "  1, -1, 1U, 1u,"
  "  1L, 1l, -1L, 1UL, 1ul,"
  "  1LL, -1LL, 1ULL;"
  "}",
  FunctionBodyMatcher("A"),
  "1 , -1 , 1U , 1U , "
  "1L , 1L , -1L , 1UL , 1UL , "
  "1LL , -1LL , 1ULL"));
  // Should be: with semicolon  


 
  }
  
  TEST(StmtPrinter, TestCXXConversionDeclImplicit) {
ASSERT_TRUE(PrintedStmtCXXMatches(
StdVer::CXX98,
"struct A {"
"operator void *();"
"A operator&(A);"
"};"
"void bar(void *);"
"void foo(A a, A b) {"
"  bar(a & b);"
"}",
traverse(TK_AsIs, cxxMemberCallExpr(anything()).bind("id")), "a & b"));
  }

When compiled with gcc 7.5, it produces the attached (gzip'd) assembly file 
which is what is what is giving the errors:

  GNU assembler version 2.30 (x86_64-linux-gnu) using BFD version (GNU Binutils 
for Ubuntu) 2.30
  StmtPrinterTest2.s: Assembler messages:
  StmtPrinterTest2.s:928: Error: symbol 
`_ZNSt14_Function_base13_Base_managerIN5clangUlPKNS1_4StmtEE2_EE10_M_managerERSt9_Any_dataRKS7_St18_Manager_operation'
 is already defined
  StmtPrinterTest2.s:9924: Error: symbol 
`_ZNSt17_Function_handlerIFbPKN5clang4StmtEENS0_UlS3_E2_EE9_M_invokeERKSt9_Any_dataOS3_'
 is already defined{F17926741}


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105457

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


[PATCH] D105637: [clang][Analyzer] Add symbol uninterestingness to bug report.

2021-07-14 Thread Balázs Kéri via Phabricator via cfe-commits
balazske updated this revision to Diff 358545.
balazske added a comment.

Rename of DiagnosticVerifyConsumer.
Changes related to handling of metadata symbols.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105637

Files:
  clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
  clang/lib/StaticAnalyzer/Core/BugReporter.cpp
  clang/unittests/StaticAnalyzer/BugReportInterestingnessTest.cpp
  clang/unittests/StaticAnalyzer/CMakeLists.txt
  clang/unittests/StaticAnalyzer/Reusables.h

Index: clang/unittests/StaticAnalyzer/Reusables.h
===
--- clang/unittests/StaticAnalyzer/Reusables.h
+++ clang/unittests/StaticAnalyzer/Reusables.h
@@ -10,9 +10,10 @@
 #define LLVM_CLANG_UNITTESTS_STATICANALYZER_REUSABLES_H
 
 #include "clang/ASTMatchers/ASTMatchFinder.h"
-#include "clang/Frontend/CompilerInstance.h"
 #include "clang/CrossTU/CrossTranslationUnit.h"
+#include "clang/Frontend/CompilerInstance.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
+#include "gtest/gtest.h"
 
 namespace clang {
 namespace ento {
@@ -66,6 +67,88 @@
 Eng(CTU, AMgr, &VisitedCallees, &FS, ExprEngine::Inline_Regular) {}
 };
 
+struct ExpectedLocationTy {
+  unsigned Line;
+  unsigned Column;
+
+  void testEquality(SourceLocation L, SourceManager &SM) const {
+EXPECT_EQ(SM.getSpellingLineNumber(L), Line);
+EXPECT_EQ(SM.getSpellingColumnNumber(L), Column);
+  }
+};
+
+struct ExpectedRangeTy {
+  ExpectedLocationTy Begin;
+  ExpectedLocationTy End;
+
+  void testEquality(SourceRange R, SourceManager &SM) const {
+Begin.testEquality(R.getBegin(), SM);
+End.testEquality(R.getEnd(), SM);
+  }
+};
+
+struct ExpectedPieceTy {
+  ExpectedLocationTy Loc;
+  std::string Text;
+  std::vector Ranges;
+
+  void testEquality(const PathDiagnosticPiece &Piece, SourceManager &SM) {
+Loc.testEquality(Piece.getLocation().asLocation(), SM);
+EXPECT_EQ(Piece.getString(), Text);
+EXPECT_EQ(Ranges.size(), Piece.getRanges().size());
+for (const auto &RangeItem : llvm::enumerate(Piece.getRanges()))
+  Ranges[RangeItem.index()].testEquality(RangeItem.value(), SM);
+  }
+};
+
+struct ExpectedDiagTy {
+  ExpectedLocationTy Loc;
+  std::string VerboseDescription;
+  std::string ShortDescription;
+  std::string CheckerName;
+  std::string BugType;
+  std::string Category;
+  std::vector Path;
+
+  void testEquality(const PathDiagnostic &Diag, SourceManager &SM) {
+Loc.testEquality(Diag.getLocation().asLocation(), SM);
+EXPECT_EQ(Diag.getVerboseDescription(), VerboseDescription);
+EXPECT_EQ(Diag.getShortDescription(), ShortDescription);
+EXPECT_EQ(Diag.getCheckerName(), CheckerName);
+EXPECT_EQ(Diag.getBugType(), BugType);
+EXPECT_EQ(Diag.getCategory(), Category);
+
+EXPECT_EQ(Path.size(), Diag.path.size());
+for (const auto &PieceItem : llvm::enumerate(Diag.path)) {
+  if (PieceItem.index() < Path.size())
+Path[PieceItem.index()].testEquality(*PieceItem.value(), SM);
+}
+  }
+};
+
+using ExpectedDiagsTy = std::vector;
+
+// A consumer to verify the generated diagnostics.
+class VerifyPathDiagnosticConsumer : public PathDiagnosticConsumer {
+  ExpectedDiagsTy ExpectedDiags;
+  SourceManager &SM;
+
+public:
+  VerifyPathDiagnosticConsumer(ExpectedDiagsTy &&ExpectedDiags,
+   SourceManager &SM)
+  : ExpectedDiags(ExpectedDiags), SM(SM) {}
+
+  StringRef getName() const override { return "verify test diagnostics"; }
+
+  void FlushDiagnosticsImpl(std::vector &Diags,
+FilesMade *filesMade) override {
+EXPECT_EQ(Diags.size(), ExpectedDiags.size());
+for (const auto &Item : llvm::enumerate(Diags))
+  if (Item.index() < ExpectedDiags.size())
+ExpectedDiags[Item.index()].testEquality(*Item.value(), SM);
+  }
+};
+
 } // namespace ento
 } // namespace clang
 
Index: clang/unittests/StaticAnalyzer/CMakeLists.txt
===
--- clang/unittests/StaticAnalyzer/CMakeLists.txt
+++ clang/unittests/StaticAnalyzer/CMakeLists.txt
@@ -5,6 +5,7 @@
 
 add_clang_unittest(StaticAnalysisTests
   AnalyzerOptionsTest.cpp
+  BugReportInterestingnessTest.cpp
   CallDescriptionTest.cpp
   CallEventTest.cpp
   FalsePositiveRefutationBRVisitorTest.cpp
Index: clang/unittests/StaticAnalyzer/BugReportInterestingnessTest.cpp
===
--- /dev/null
+++ clang/unittests/StaticAnalyzer/BugReportInterestingnessTest.cpp
@@ -0,0 +1,162 @@
+//===--===//
+//
+// 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
+//
+//===-

[PATCH] D105937: [OpenMP] Encode `omp [...] assume[...]` assumptions with `omp[x]` prefix

2021-07-14 Thread Jon Chesterfield via Phabricator via cfe-commits
JonChesterfield added a comment.

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105937

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


[PATCH] D69764: [clang-format] Add East/West Const fixer capability

2021-07-14 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

Interesting reference point here 
https://blog.jetbrains.com/rscpp/2021/03/30/resharper-cpp-2021-1-syntax-style

Kind of suggests that Resharper brings many of these "mutating" capabilities 
into the same tool that fixes your style. I'd be really interest to know if 
they do that by having to have a compilation command database or if they make 
those substitutions based on on the tokens and not having full semantic 
information


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

https://reviews.llvm.org/D69764

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


[PATCH] D105679: [clangd] Add CMake option to (not) link in clang-tidy checks

2021-07-14 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

Nit: I find the name a bit confusing. When I first saw this commit, I thought 
this would be a list of clang-tidy checks to support, not a binary on/off 
toggle.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105679

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


[PATCH] D105765: Prepare Compiler-RT for GnuInstallDirs, matching libcxx, document all

2021-07-14 Thread John Ericson via Phabricator via cfe-commits
This revision was not accepted when it landed; it landed in state "Needs 
Review".
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG1e03c37b97b6: Prepare Compiler-RT for GnuInstallDirs, 
matching libcxx, document all (authored by Ericson2314).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105765

Files:
  clang/runtime/CMakeLists.txt
  compiler-rt/cmake/Modules/AddCompilerRT.cmake
  compiler-rt/cmake/Modules/CompilerRTDarwinUtils.cmake
  compiler-rt/cmake/Modules/CompilerRTUtils.cmake
  compiler-rt/cmake/base-config-ix.cmake
  compiler-rt/docs/BuildingCompilerRT.rst
  compiler-rt/include/CMakeLists.txt
  compiler-rt/lib/dfsan/CMakeLists.txt
  libcxx/CMakeLists.txt
  libcxx/docs/BuildingLibcxx.rst
  libcxxabi/CMakeLists.txt
  libunwind/CMakeLists.txt
  libunwind/docs/BuildingLibunwind.rst

Index: libunwind/docs/BuildingLibunwind.rst
===
--- libunwind/docs/BuildingLibunwind.rst
+++ libunwind/docs/BuildingLibunwind.rst
@@ -159,3 +159,10 @@
 .. option:: LIBUNWIND_SYSROOT
 
   Sysroot for cross compiling
+
+.. option:: LIBUNWIND_INSTALL_LIBRARY_DIR:PATH
+
+  **Default**: ``lib${LIBUNWIND_LIBDIR_SUFFIX}``
+
+  Path where built libunwind libraries should be installed. If a relative path,
+  relative to ``CMAKE_INSTALL_PREFIX``.
Index: libunwind/CMakeLists.txt
===
--- libunwind/CMakeLists.txt
+++ libunwind/CMakeLists.txt
@@ -116,17 +116,20 @@
 
 if(LLVM_ENABLE_PER_TARGET_RUNTIME_DIR AND NOT APPLE)
   set(LIBUNWIND_LIBRARY_DIR ${LLVM_LIBRARY_OUTPUT_INTDIR}/${LLVM_DEFAULT_TARGET_TRIPLE})
-  set(LIBUNWIND_INSTALL_LIBRARY_DIR lib${LLVM_LIBDIR_SUFFIX}/${LLVM_DEFAULT_TARGET_TRIPLE})
+  set(LIBUNWIND_INSTALL_LIBRARY_DIR lib${LLVM_LIBDIR_SUFFIX}/${LLVM_DEFAULT_TARGET_TRIPLE} CACHE PATH
+  "Path where built libunwind libraries should be installed.")
   if(LIBCXX_LIBDIR_SUBDIR)
 string(APPEND LIBUNWIND_LIBRARY_DIR /${LIBUNWIND_LIBDIR_SUBDIR})
 string(APPEND LIBUNWIND_INSTALL_LIBRARY_DIR /${LIBUNWIND_LIBDIR_SUBDIR})
   endif()
 elseif(LLVM_LIBRARY_OUTPUT_INTDIR)
   set(LIBUNWIND_LIBRARY_DIR ${LLVM_LIBRARY_OUTPUT_INTDIR})
-  set(LIBUNWIND_INSTALL_LIBRARY_DIR lib${LIBUNWIND_LIBDIR_SUFFIX})
+  set(LIBUNWIND_INSTALL_LIBRARY_DIR lib${LIBUNWIND_LIBDIR_SUFFIX} CACHE PATH
+  "Path where built libunwind libraries should be installed.")
 else()
   set(LIBUNWIND_LIBRARY_DIR ${CMAKE_BINARY_DIR}/lib${LIBUNWIND_LIBDIR_SUFFIX})
-  set(LIBUNWIND_INSTALL_LIBRARY_DIR lib${LIBUNWIND_LIBDIR_SUFFIX})
+  set(LIBUNWIND_INSTALL_LIBRARY_DIR lib${LIBUNWIND_LIBDIR_SUFFIX} CACHE PATH
+  "Path where built libunwind libraries should be installed.")
 endif()
 
 set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${LIBUNWIND_LIBRARY_DIR})
Index: libcxxabi/CMakeLists.txt
===
--- libcxxabi/CMakeLists.txt
+++ libcxxabi/CMakeLists.txt
@@ -195,7 +195,8 @@
 if(LLVM_ENABLE_PER_TARGET_RUNTIME_DIR AND NOT APPLE)
   set(LIBCXXABI_HEADER_DIR ${LLVM_BINARY_DIR})
   set(LIBCXXABI_LIBRARY_DIR ${LLVM_LIBRARY_OUTPUT_INTDIR}/${LLVM_DEFAULT_TARGET_TRIPLE})
-  set(LIBCXXABI_INSTALL_LIBRARY_DIR lib${LLVM_LIBDIR_SUFFIX}/${LLVM_DEFAULT_TARGET_TRIPLE})
+  set(LIBCXXABI_INSTALL_LIBRARY_DIR lib${LLVM_LIBDIR_SUFFIX}/${LLVM_DEFAULT_TARGET_TRIPLE} CACHE PATH
+  "Path where built libc++abi libraries should be installed.")
   if(LIBCXX_LIBDIR_SUBDIR)
 string(APPEND LIBCXXABI_LIBRARY_DIR /${LIBCXXABI_LIBDIR_SUBDIR})
 string(APPEND LIBCXXABI_INSTALL_LIBRARY_DIR /${LIBCXXABI_LIBDIR_SUBDIR})
@@ -203,11 +204,13 @@
 elseif(LLVM_LIBRARY_OUTPUT_INTDIR)
   set(LIBCXXABI_HEADER_DIR ${LLVM_BINARY_DIR})
   set(LIBCXXABI_LIBRARY_DIR ${LLVM_LIBRARY_OUTPUT_INTDIR})
-  set(LIBCXXABI_INSTALL_LIBRARY_DIR lib${LIBCXXABI_LIBDIR_SUFFIX})
+  set(LIBCXXABI_INSTALL_LIBRARY_DIR lib${LIBCXXABI_LIBDIR_SUFFIX} CACHE PATH
+  "Path where built libc++abi libraries should be installed.")
 else()
   set(LIBCXXABI_HEADER_DIR ${CMAKE_BINARY_DIR})
   set(LIBCXXABI_LIBRARY_DIR ${CMAKE_BINARY_DIR}/lib${LIBCXXABI_LIBDIR_SUFFIX})
-  set(LIBCXXABI_INSTALL_LIBRARY_DIR lib${LIBCXXABI_LIBDIR_SUFFIX})
+  set(LIBCXXABI_INSTALL_LIBRARY_DIR lib${LIBCXXABI_LIBDIR_SUFFIX} CACHE PATH
+  "Path where built libc++abi libraries should be installed.")
 endif()
 
 set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${LIBCXXABI_LIBRARY_DIR})
Index: libcxx/docs/BuildingLibcxx.rst
===
--- libcxx/docs/BuildingLibcxx.rst
+++ libcxx/docs/BuildingLibcxx.rst
@@ -251,6 +251,28 @@
This option can be used to enable or disable the filesystem components on
platforms that may not support them. For example on Windows.
 
+.. option:: LIBCXX_INSTALL_LIBRARY_DIR:PATH
+
+  **Default**: ``lib${LIBCXX_LIBDIR_SUFFI

[PATCH] D105754: [PowerPC] Fix L[D|W]ARX Implementation

2021-07-14 Thread Albion Fung via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGf1aca5ac96eb: [PowerPC] Fix L[D|W]ARX Implementation 
(authored by Conanap).

Changed prior to commit:
  https://reviews.llvm.org/D105754?vs=358032&id=358289#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105754

Files:
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/test/CodeGen/builtins-ppc-xlcompat-LoadReseve-StoreCond-64bit-only.c
  clang/test/CodeGen/builtins-ppc-xlcompat-LoadReseve-StoreCond.c
  llvm/include/llvm/IR/IntrinsicsPowerPC.td
  llvm/lib/Target/PowerPC/PPCInstr64Bit.td
  llvm/lib/Target/PowerPC/PPCInstrInfo.td
  
llvm/test/CodeGen/PowerPC/builtins-ppc-xlcompat-LoadReserve-StoreCond-64bit-only.ll
  llvm/test/CodeGen/PowerPC/builtins-ppc-xlcompat-LoadReserve-StoreCond.ll

Index: llvm/test/CodeGen/PowerPC/builtins-ppc-xlcompat-LoadReserve-StoreCond.ll
===
--- llvm/test/CodeGen/PowerPC/builtins-ppc-xlcompat-LoadReserve-StoreCond.ll
+++ llvm/test/CodeGen/PowerPC/builtins-ppc-xlcompat-LoadReserve-StoreCond.ll
@@ -12,18 +12,21 @@
 define dso_local signext i32 @test_lwarx(i32* readnone %a) {
 ; CHECK-64-LABEL: test_lwarx:
 ; CHECK-64:   # %bb.0: # %entry
+; CHECK-64-NEXT:#APP
 ; CHECK-64-NEXT:lwarx 3, 0, 3
+; CHECK-64-NEXT:#NO_APP
 ; CHECK-64-NEXT:extsw 3, 3
 ; CHECK-64-NEXT:blr
 ;
 ; CHECK-32-LABEL: test_lwarx:
 ; CHECK-32:   # %bb.0: # %entry
+; CHECK-32-NEXT:#APP
 ; CHECK-32-NEXT:lwarx 3, 0, 3
+; CHECK-32-NEXT:#NO_APP
 ; CHECK-32-NEXT:blr
 entry:
-  %0 = bitcast i32* %a to i8*
-  %1 = tail call i32 @llvm.ppc.lwarx(i8* %0)
-  ret i32 %1
+  %0 = call i32 asm sideeffect "lwarx $0, ${1:y}", "=r,*Z,~{memory}"(i32* %a)
+  ret i32 %0
 }
 
 declare i32 @llvm.ppc.stwcx(i8*, i32)
Index: llvm/test/CodeGen/PowerPC/builtins-ppc-xlcompat-LoadReserve-StoreCond-64bit-only.ll
===
--- llvm/test/CodeGen/PowerPC/builtins-ppc-xlcompat-LoadReserve-StoreCond-64bit-only.ll
+++ llvm/test/CodeGen/PowerPC/builtins-ppc-xlcompat-LoadReserve-StoreCond-64bit-only.ll
@@ -10,17 +10,18 @@
 define dso_local i64 @test_ldarx(i64* readnone %a) {
 ; CHECK-LABEL: test_ldarx:
 ; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:#APP
 ; CHECK-NEXT:ldarx 3, 0, 3
+; CHECK-NEXT:#NO_APP
 ; CHECK-NEXT:blr
 entry:
-  %0 = bitcast i64* %a to i8*
-  %1 = tail call i64 @llvm.ppc.ldarx(i8* %0)
-  ret i64 %1
+  %0 = call i64 asm sideeffect "ldarx $0, ${1:y}", "=r,*Z,~{memory}"(i64* %a)
+  ret i64 %0
 }
 
 declare i32 @llvm.ppc.stdcx(i8*, i64)
-define dso_local i64 @test(i64* %a, i64 %b) {
-; CHECK-LABEL: test:
+define dso_local i64 @test_stdcx(i64* %a, i64 %b) {
+; CHECK-LABEL: test_stdcx:
 ; CHECK:   # %bb.0: # %entry
 ; CHECK-NEXT:stdcx. 4, 0, 3
 ; CHECK-NEXT:mfocrf 3, 128
Index: llvm/lib/Target/PowerPC/PPCInstrInfo.td
===
--- llvm/lib/Target/PowerPC/PPCInstrInfo.td
+++ llvm/lib/Target/PowerPC/PPCInstrInfo.td
@@ -5413,8 +5413,6 @@
 def : Pat<(i64 (bitreverse i64:$A)),
   (OR8 (RLDICR DWBytes7654.DWord, 32, 31), DWBytes3210.DWord)>;
 
-def : Pat<(int_ppc_lwarx ForceXForm:$dst),
-  (LWARX ForceXForm:$dst)>;
 def : Pat<(int_ppc_stwcx ForceXForm:$dst, gprc:$A),
   (STWCX gprc:$A, ForceXForm:$dst)>;
 def : Pat<(int_ppc_tw gprc:$A, gprc:$B, i32:$IMM),
Index: llvm/lib/Target/PowerPC/PPCInstr64Bit.td
===
--- llvm/lib/Target/PowerPC/PPCInstr64Bit.td
+++ llvm/lib/Target/PowerPC/PPCInstr64Bit.td
@@ -1723,8 +1723,6 @@
 
 def : Pat<(int_ppc_stdcx ForceXForm:$dst, g8rc:$A),
   (STDCX g8rc:$A, ForceXForm:$dst)>;
-def : Pat<(int_ppc_ldarx ForceXForm:$dst),
-  (LDARX ForceXForm:$dst)>;
 def : Pat<(int_ppc_tdw g8rc:$A, g8rc:$B, i32:$IMM),
   (TD $IMM, $A, $B)>;
 
Index: llvm/include/llvm/IR/IntrinsicsPowerPC.td
===
--- llvm/include/llvm/IR/IntrinsicsPowerPC.td
+++ llvm/include/llvm/IR/IntrinsicsPowerPC.td
@@ -1565,9 +1565,5 @@
   def int_ppc_stwcx : GCCBuiltin<"__builtin_ppc_stwcx">,
   Intrinsic<[llvm_i32_ty], [llvm_ptr_ty, llvm_i32_ty],
 [IntrWriteMem]>;
-  def int_ppc_lwarx : GCCBuiltin<"__builtin_ppc_lwarx">,
-  Intrinsic<[llvm_i32_ty], [llvm_ptr_ty], [IntrNoMem]>;
-  def int_ppc_ldarx : GCCBuiltin<"__builtin_ppc_ldarx">,
-  Intrinsic<[llvm_i64_ty], [llvm_ptr_ty], [IntrNoMem]>;
 }
 
Index: clang/test/CodeGen/builtins-ppc-xlcompat-LoadReseve-StoreCond.c
===
--- clang/test/CodeGen/builtins-ppc-xlcompat-LoadReseve-StoreCond.c
+++ clang/test/CodeGen/builtins-ppc-xlcompat-LoadReseve-StoreCond.c
@@ -1,22 +1,20 @@
-// RU

Re: [PATCH] D69764: [clang-format] Add East/West Const fixer capability

2021-07-14 Thread Gašper Ažman via cfe-commits
It's very difficult to use a compile_commands database if you can't
actually check out all the code and a remote service builds it for you.

On Tue, Jul 13, 2021 at 6:03 PM Aaron Ballman via Phabricator <
revi...@reviews.llvm.org> wrote:

> aaron.ballman added a comment.
>
> In D69764#2874404 ,
> @MyDeveloperDay wrote:
>
> >> What you're describing sounds like clang-tidy but perhaps with improved
> support for composing source modifications from fix-its, or do you envision
> something rather different?
> >
> > All my uses of clang-tidy require extensive command line arguments to
> handle compiler flags and include paths, I don't want that for this when
> its mostly unnecessary:
> >
> >file.cxx
> >
> > is all that should be required.
>
> FWIW, if you use the compile commands database, the only thing you need to
> do on the command line is specify the checks to enable or disable.
>
>
> CHANGES SINCE LAST ACTION
>   https://reviews.llvm.org/D69764/new/
>
> https://reviews.llvm.org/D69764
>
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D103096: [analyzer] Implement cast for ranges of symbolic integers.

2021-07-14 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko added a comment.

>   // 1. `VisitSymbolCast`.
>   // Get a range for main `reg_$0` - [-2147483648, 2147483647]
>   // Cast main range to `short` - [-2147483648, 2147483647] -> [-32768, 
> 32767].
>   // Now we get a valid range for further bifurcation - [-32768, 32767].

That's a great example, thanks for putting it together.  I can see your point 
now!

Please, rebase your change and make use of `ConstraintAssignor`, and rework 
`VisitSymbolCast`.




Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h:293-296
+SymbolRef Sym = Operand;
+while (isa(Sym))
+  Sym = cast(Sym)->Operand;
+return Sym;

ASDenysPetrov wrote:
> vsavchenko wrote:
> > ASDenysPetrov wrote:
> > > vsavchenko wrote:
> > > > 
> > > Do you think the recursive call is better than the loop? But, I guess, I 
> > > see your point. You option could be safer if we had another 
> > > implementation of the virtual method. Or you think such alike cast symbol 
> > > is possible in the future? Well, for now `ignoreCasts` doesn't make sense 
> > > to any other `Expr` successors.
> > Oh, wait, why is it even virtual?  I don't think that it should be virtual.
> > Are similar functions in `Expr` virtual?
> > And I think that this implementation should live in `SymExpr` directly.  
> > Then it would look like:
> > ```
> > if (const SymbolCast *ThisAsCast = dyn_cast(this)) {
> >   return ThisAsCast->ignoreCasts();
> > }
> > return this;
> > ```
> Yes, `SymExpr` is an abstract class. And because of limitations and 
> dependency of inheritance we are not able to know the implementaion of 
> `SymbolCast`. Unfortunately, this is not a CRTP.
Re-read my comment, please.



Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:1203
+if (!Opts.ShouldSupportSymbolicIntegerCasts)
+  return VisitSymExpr(Sym);
+

ASDenysPetrov wrote:
> vsavchenko wrote:
> > ASDenysPetrov wrote:
> > > vsavchenko wrote:
> > > > ASDenysPetrov wrote:
> > > > > vsavchenko wrote:
> > > > > > Why do you use `VisitSymExpr` here?  You want to interrupt all 
> > > > > > `Visits or... I'm not sure I fully understand.
> > > > > Here we want to delegate the reasoning to another handler as we don't 
> > > > > support non-integral cast yet.
> > > > You are not delegating it here.  `Visit` includes a runtime dispatch 
> > > > that calls a correct `VisitTYPE` method.  Here you call `VisitSymExpr` 
> > > > directly, which is one of the `VisitTYPE` methods.  No dispatch will 
> > > > happen, and since we use `VisitSymExpr` as the last resort (it's the 
> > > > most base class, if we got there, we don't actually support the 
> > > > expression), you interrupt the `Visit` and go directly to "the last 
> > > > resort".
> > > > 
> > > > See the problem now?
> > > OK. I reject this idea before. If we call `Visit` inside 
> > > `VisitSymbolCast`, we will go into recursive loop, because it will return 
> > > us back to `VisitSymbolCast` as we have passed `Sym` as is. (This is 
> > > theoretically, I didn't check in practice.) Or I'm missing smth?
> > > I choosed `VisitSymExpr` here because all kinds of `SymbolCast` were 
> > > previously handled here. So I decided to pass all unsupproted forms of 
> > > casts there.
> > Did I suggest to `Visit(Sym)`?  Of course it is going to end up in a loop!  
> > Why isn't it `Visit(Sym->getOperand())` here?  Before we started producing 
> > casts, casts were transparent.  This logic would fit perfectly with that.
> > were transparent.
> Not exactly. There are still some cases when symbols are not equal to there 
> roots(aka Operands). Such cases were handled by `VisitSymExpr` which uses 
> `infer(Sym->getType());` instead of getOperand`. So this needs a sort of 
> think twice. Also I see a problem with `EquivalenceClass`'es. Consider next:
> ```
> int x, y;
> if(x == y)
>   if ((char)x == 2)
> if(y == 259)
>   // Here we shall update `(char)x` and find this branch infeasible.
> ```
> Also such cases like:
> ```
> if(x == (short)y)
>   // What we should do(store) with(in) `EquivalenceClass`es.
> ```
> Currently, I have an obscure vision of the solution.
> There are still some cases when symbols are not equal to there roots(aka 
> Operands)
Right now we don't have casts, this is what we do currently.  However faulty it 
is, it is the existing solution and we should respect that.

>  Also I see a problem with EquivalenceClass'es.
Because of the current situation with casts (or more precisely with their 
lack), `EquivalenceClass`es do not get merged for symbols with different types. 
 It is as simple as that.
You can find similar tests in `equality_tracking.c`.


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

https://reviews.llvm.org/D103096

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


[PATCH] D105728: [clang][Codegen] Directly lower `(*((volatile int *)(0))) = 0;` into a `call void @llvm.trap()`

2021-07-14 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

@rsmith ping


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105728

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


[PATCH] D103967: [Analyzer][solver] Add dump methods for (dis)equality classes.

2021-07-14 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

In D103967#2864229 , @steakhal wrote:

> AFAICT this patch does not introduce significant overhead to the exploded 
> graph DOT dumps.
> Before the patch, an exploded graph took 12G and about 55 secs for a single 
> top-level function.
> After the patch, it increased to 13G, and the runtime remained the same as 
> expected.
>
> Which is about a 1.5 % increase in size in total. TBH I expected slightly 
> higher numbers.
>
> This benchmark was done using a release build with dumps, asserts, and 
> expensive checks.

Thanks Balázs for the benchmark, this makes me confident to commit. Hopefully 
this time the tests won't be flaky.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103967

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


[PATCH] D105703: [hwasan] Use stack safety analysis.

2021-07-14 Thread Florian Mayer via Phabricator via cfe-commits
fmayer updated this revision to Diff 358564.
fmayer marked 2 inline comments as done.
fmayer added a comment.

Address some comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105703

Files:
  clang/lib/CodeGen/BackendUtil.cpp
  clang/test/CodeGen/hwasan-stack-safety-analysis-asm.c
  clang/test/CodeGen/hwasan-stack-safety-analysis.c
  llvm/include/llvm/Transforms/Instrumentation/HWAddressSanitizer.h
  llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp

Index: llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
===
--- llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
+++ llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
@@ -17,6 +17,7 @@
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/Triple.h"
+#include "llvm/Analysis/StackSafetyAnalysis.h"
 #include "llvm/BinaryFormat/ELF.h"
 #include "llvm/IR/Attributes.h"
 #include "llvm/IR/BasicBlock.h"
@@ -109,6 +110,11 @@
cl::desc("instrument stack (allocas)"),
cl::Hidden, cl::init(true));
 
+static cl::opt
+ClUseStackSafety("hwasan-use-stack-safety", cl::Hidden, cl::init(true),
+ cl::Hidden, cl::desc("Use Stack Safety analysis results"),
+ cl::Optional);
+
 static cl::opt ClUARRetagToZero(
 "hwasan-uar-retag-to-zero",
 cl::desc("Clear alloca tags before returning from the function to allow "
@@ -210,13 +216,21 @@
 #pragma GCC poison ClInstrumetnWithCalls
 }
 
+bool shouldUseStackSafetyAnalysis(const Triple &TargetTriple, bool IsOptNull) {
+  auto StackSafety =
+  ClUseStackSafety.getNumOccurrences() ? ClUseStackSafety : !IsOptNull;
+  return shouldInstrumentStack(TargetTriple) && StackSafety;
+// No one should use the option directly.
+#pragma GCC poison ClUseStackSafety
+}
 /// An instrumentation pass implementing detection of addressability bugs
 /// using tagged pointers.
 class HWAddressSanitizer {
 public:
   explicit HWAddressSanitizer(Module &M, bool CompileKernel = false,
-  bool Recover = false)
-  : M(M) {
+  bool Recover = false,
+  const StackSafetyGlobalInfo *SSI = nullptr)
+  : M(M), SSI(SSI) {
 this->Recover = ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover;
 this->CompileKernel = ClEnableKhwasan.getNumOccurrences() > 0
   ? ClEnableKhwasan
@@ -225,6 +239,8 @@
 initializeModule();
   }
 
+  void setSSI(const StackSafetyGlobalInfo *S) { SSI = S; }
+
   bool sanitizeFunction(Function &F);
   void initializeModule();
   void createHwasanCtorComdat();
@@ -277,6 +293,7 @@
 private:
   LLVMContext *C;
   Module &M;
+  const StackSafetyGlobalInfo *SSI;
   Triple TargetTriple;
   FunctionCallee HWAsanMemmove, HWAsanMemcpy, HWAsanMemset;
   FunctionCallee HWAsanHandleVfork;
@@ -347,8 +364,11 @@
   static char ID;
 
   explicit HWAddressSanitizerLegacyPass(bool CompileKernel = false,
-bool Recover = false)
-  : FunctionPass(ID), CompileKernel(CompileKernel), Recover(Recover) {
+bool Recover = false,
+Triple TargetTriple = {},
+bool IsOptNull = false)
+  : FunctionPass(ID), CompileKernel(CompileKernel), Recover(Recover),
+TargetTriple(TargetTriple) {
 initializeHWAddressSanitizerLegacyPassPass(
 *PassRegistry::getPassRegistry());
   }
@@ -356,11 +376,18 @@
   StringRef getPassName() const override { return "HWAddressSanitizer"; }
 
   bool doInitialization(Module &M) override {
-HWASan = std::make_unique(M, CompileKernel, Recover);
+HWASan = std::make_unique(M, CompileKernel, Recover,
+  /*SSI=*/nullptr);
 return true;
   }
 
   bool runOnFunction(Function &F) override {
+if (shouldUseStackSafetyAnalysis(TargetTriple, IsOptNull)) {
+  // We cannot call getAnalysis in doInitialization, that would cause a
+  // crash as the required analyses are not initialized yet.
+  HWASan->setSSI(
+  &getAnalysis().getResult());
+}
 return HWASan->sanitizeFunction(F);
   }
 
@@ -369,10 +396,18 @@
 return false;
   }
 
+  void getAnalysisUsage(AnalysisUsage &AU) const override {
+if (shouldUseStackSafetyAnalysis(TargetTriple, IsOptNull)) {
+  AU.addRequired();
+}
+  }
+
 private:
   std::unique_ptr HWASan;
   bool CompileKernel;
   bool Recover;
+  Triple TargetTriple;
+  bool IsOptNull;
 };
 
 } // end anonymous namespace
@@ -389,17 +424,27 @@
 false)
 
 FunctionPass *llvm::createHWAddressSanitizerLegacyPassPass(bool CompileKernel,
- 

[PATCH] D105703: [hwasan] Use stack safety analysis.

2021-07-14 Thread Florian Mayer via Phabricator via cfe-commits
fmayer updated this revision to Diff 358565.
fmayer added a comment.

fixup


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105703

Files:
  clang/lib/CodeGen/BackendUtil.cpp
  clang/test/CodeGen/hwasan-stack-safety-analysis-asm.c
  clang/test/CodeGen/hwasan-stack-safety-analysis.c
  llvm/include/llvm/Transforms/Instrumentation/HWAddressSanitizer.h
  llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp

Index: llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
===
--- llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
+++ llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
@@ -17,6 +17,7 @@
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/Triple.h"
+#include "llvm/Analysis/StackSafetyAnalysis.h"
 #include "llvm/BinaryFormat/ELF.h"
 #include "llvm/IR/Attributes.h"
 #include "llvm/IR/BasicBlock.h"
@@ -109,6 +110,11 @@
cl::desc("instrument stack (allocas)"),
cl::Hidden, cl::init(true));
 
+static cl::opt
+ClUseStackSafety("hwasan-use-stack-safety", cl::Hidden, cl::init(true),
+ cl::Hidden, cl::desc("Use Stack Safety analysis results"),
+ cl::Optional);
+
 static cl::opt ClUARRetagToZero(
 "hwasan-uar-retag-to-zero",
 cl::desc("Clear alloca tags before returning from the function to allow "
@@ -205,18 +211,26 @@
 }
 
 bool shouldInstrumentWithCalls(const Triple& TargetTriple) {
-  return ClInstrumentWithCalls && TargetTriple.getArch() == Triple::x86_64;
+  return ClInstrumentWithCalls || TargetTriple.getArch() == Triple::x86_64;
 // No one should use the option directly.
 #pragma GCC poison ClInstrumetnWithCalls
 }
 
+bool shouldUseStackSafetyAnalysis(const Triple &TargetTriple, bool IsOptNull) {
+  auto StackSafety =
+  ClUseStackSafety.getNumOccurrences() ? ClUseStackSafety : !IsOptNull;
+  return shouldInstrumentStack(TargetTriple) && StackSafety;
+// No one should use the option directly.
+#pragma GCC poison ClUseStackSafety
+}
 /// An instrumentation pass implementing detection of addressability bugs
 /// using tagged pointers.
 class HWAddressSanitizer {
 public:
   explicit HWAddressSanitizer(Module &M, bool CompileKernel = false,
-  bool Recover = false)
-  : M(M) {
+  bool Recover = false,
+  const StackSafetyGlobalInfo *SSI = nullptr)
+  : M(M), SSI(SSI) {
 this->Recover = ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover;
 this->CompileKernel = ClEnableKhwasan.getNumOccurrences() > 0
   ? ClEnableKhwasan
@@ -225,6 +239,8 @@
 initializeModule();
   }
 
+  void setSSI(const StackSafetyGlobalInfo *S) { SSI = S; }
+
   bool sanitizeFunction(Function &F);
   void initializeModule();
   void createHwasanCtorComdat();
@@ -277,6 +293,7 @@
 private:
   LLVMContext *C;
   Module &M;
+  const StackSafetyGlobalInfo *SSI;
   Triple TargetTriple;
   FunctionCallee HWAsanMemmove, HWAsanMemcpy, HWAsanMemset;
   FunctionCallee HWAsanHandleVfork;
@@ -347,8 +364,11 @@
   static char ID;
 
   explicit HWAddressSanitizerLegacyPass(bool CompileKernel = false,
-bool Recover = false)
-  : FunctionPass(ID), CompileKernel(CompileKernel), Recover(Recover) {
+bool Recover = false,
+Triple TargetTriple = {},
+bool IsOptNull = false)
+  : FunctionPass(ID), CompileKernel(CompileKernel), Recover(Recover),
+TargetTriple(TargetTriple) {
 initializeHWAddressSanitizerLegacyPassPass(
 *PassRegistry::getPassRegistry());
   }
@@ -356,11 +376,18 @@
   StringRef getPassName() const override { return "HWAddressSanitizer"; }
 
   bool doInitialization(Module &M) override {
-HWASan = std::make_unique(M, CompileKernel, Recover);
+HWASan = std::make_unique(M, CompileKernel, Recover,
+  /*SSI=*/nullptr);
 return true;
   }
 
   bool runOnFunction(Function &F) override {
+if (shouldUseStackSafetyAnalysis(TargetTriple, IsOptNull)) {
+  // We cannot call getAnalysis in doInitialization, that would cause a
+  // crash as the required analyses are not initialized yet.
+  HWASan->setSSI(
+  &getAnalysis().getResult());
+}
 return HWASan->sanitizeFunction(F);
   }
 
@@ -369,10 +396,18 @@
 return false;
   }
 
+  void getAnalysisUsage(AnalysisUsage &AU) const override {
+if (shouldUseStackSafetyAnalysis(TargetTriple, IsOptNull)) {
+  AU.addRequired();
+}
+  }
+
 private:
   std::unique_ptr HWASan;
   bool CompileKernel;
   bool Recover;
+  Triple TargetTriple;
+  bool IsOptNull;

[PATCH] D105703: [hwasan] Use stack safety analysis.

2021-07-14 Thread Florian Mayer via Phabricator via cfe-commits
fmayer updated this revision to Diff 358567.
fmayer added a comment.

rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105703

Files:
  clang/lib/CodeGen/BackendUtil.cpp
  clang/test/CodeGen/hwasan-stack-safety-analysis-asm.c
  clang/test/CodeGen/hwasan-stack-safety-analysis.c
  llvm/include/llvm/Transforms/Instrumentation/HWAddressSanitizer.h
  llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp

Index: llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
===
--- llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
+++ llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
@@ -17,6 +17,7 @@
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/Triple.h"
+#include "llvm/Analysis/StackSafetyAnalysis.h"
 #include "llvm/BinaryFormat/ELF.h"
 #include "llvm/IR/Attributes.h"
 #include "llvm/IR/BasicBlock.h"
@@ -109,6 +110,11 @@
cl::desc("instrument stack (allocas)"),
cl::Hidden, cl::init(true));
 
+static cl::opt
+ClUseStackSafety("hwasan-use-stack-safety", cl::Hidden, cl::init(true),
+ cl::Hidden, cl::desc("Use Stack Safety analysis results"),
+ cl::Optional);
+
 static cl::opt ClUARRetagToZero(
 "hwasan-uar-retag-to-zero",
 cl::desc("Clear alloca tags before returning from the function to allow "
@@ -210,13 +216,21 @@
 #pragma GCC poison ClInstrumentWithCalls
 }
 
+bool shouldUseStackSafetyAnalysis(const Triple &TargetTriple, bool IsOptNull) {
+  auto StackSafety =
+  ClUseStackSafety.getNumOccurrences() ? ClUseStackSafety : !IsOptNull;
+  return shouldInstrumentStack(TargetTriple) && StackSafety;
+// No one should use the option directly.
+#pragma GCC poison ClUseStackSafety
+}
 /// An instrumentation pass implementing detection of addressability bugs
 /// using tagged pointers.
 class HWAddressSanitizer {
 public:
   explicit HWAddressSanitizer(Module &M, bool CompileKernel = false,
-  bool Recover = false)
-  : M(M) {
+  bool Recover = false,
+  const StackSafetyGlobalInfo *SSI = nullptr)
+  : M(M), SSI(SSI) {
 this->Recover = ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover;
 this->CompileKernel = ClEnableKhwasan.getNumOccurrences() > 0
   ? ClEnableKhwasan
@@ -225,6 +239,8 @@
 initializeModule();
   }
 
+  void setSSI(const StackSafetyGlobalInfo *S) { SSI = S; }
+
   bool sanitizeFunction(Function &F);
   void initializeModule();
   void createHwasanCtorComdat();
@@ -277,6 +293,7 @@
 private:
   LLVMContext *C;
   Module &M;
+  const StackSafetyGlobalInfo *SSI;
   Triple TargetTriple;
   FunctionCallee HWAsanMemmove, HWAsanMemcpy, HWAsanMemset;
   FunctionCallee HWAsanHandleVfork;
@@ -347,8 +364,11 @@
   static char ID;
 
   explicit HWAddressSanitizerLegacyPass(bool CompileKernel = false,
-bool Recover = false)
-  : FunctionPass(ID), CompileKernel(CompileKernel), Recover(Recover) {
+bool Recover = false,
+Triple TargetTriple = {},
+bool IsOptNull = false)
+  : FunctionPass(ID), CompileKernel(CompileKernel), Recover(Recover),
+TargetTriple(TargetTriple) {
 initializeHWAddressSanitizerLegacyPassPass(
 *PassRegistry::getPassRegistry());
   }
@@ -356,11 +376,18 @@
   StringRef getPassName() const override { return "HWAddressSanitizer"; }
 
   bool doInitialization(Module &M) override {
-HWASan = std::make_unique(M, CompileKernel, Recover);
+HWASan = std::make_unique(M, CompileKernel, Recover,
+  /*SSI=*/nullptr);
 return true;
   }
 
   bool runOnFunction(Function &F) override {
+if (shouldUseStackSafetyAnalysis(TargetTriple, IsOptNull)) {
+  // We cannot call getAnalysis in doInitialization, that would cause a
+  // crash as the required analyses are not initialized yet.
+  HWASan->setSSI(
+  &getAnalysis().getResult());
+}
 return HWASan->sanitizeFunction(F);
   }
 
@@ -369,10 +396,18 @@
 return false;
   }
 
+  void getAnalysisUsage(AnalysisUsage &AU) const override {
+if (shouldUseStackSafetyAnalysis(TargetTriple, IsOptNull)) {
+  AU.addRequired();
+}
+  }
+
 private:
   std::unique_ptr HWASan;
   bool CompileKernel;
   bool Recover;
+  Triple TargetTriple;
+  bool IsOptNull;
 };
 
 } // end anonymous namespace
@@ -389,17 +424,27 @@
 false)
 
 FunctionPass *llvm::createHWAddressSanitizerLegacyPassPass(bool CompileKernel,
-   bool Recover) {
+  

[clang] bdf3147 - [Analyzer][solver] Add dump methods for (dis)equality classes.

2021-07-14 Thread Gabor Marton via cfe-commits

Author: Gabor Marton
Date: 2021-07-14T13:45:02+02:00
New Revision: bdf31471c76b5ded9e8d5a039250c2a7ba7aead6

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

LOG: [Analyzer][solver] Add dump methods for (dis)equality classes.

This proved to be very useful during debugging.

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

Added: 
clang/test/Analysis/expr-inspection-printState-diseq-info.c
clang/test/Analysis/expr-inspection-printState-eq-classes.c

Modified: 
clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
clang/test/Analysis/expr-inspection.c

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp 
b/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
index 9e014e9fce4e2..aba97e48756aa 100644
--- a/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
+++ b/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
@@ -592,6 +592,11 @@ class EquivalenceClass : public llvm::FoldingSetNode {
   RangeSet::Factory &F,
   ProgramStateRef State);
 
+  void dumpToStream(ProgramStateRef State, raw_ostream &os) const;
+  LLVM_DUMP_METHOD void dump(ProgramStateRef State) const {
+dumpToStream(State, llvm::errs());
+  }
+
   /// Check equivalence data for consistency.
   LLVM_NODISCARD LLVM_ATTRIBUTE_UNUSED static bool
   isClassDataConsistent(ProgramStateRef State);
@@ -1599,6 +1604,15 @@ class RangeConstraintManager : public 
RangedConstraintManager {
 
   void printJson(raw_ostream &Out, ProgramStateRef State, const char *NL = 
"\n",
  unsigned int Space = 0, bool IsDot = false) const override;
+  void printConstraints(raw_ostream &Out, ProgramStateRef State,
+const char *NL = "\n", unsigned int Space = 0,
+bool IsDot = false) const;
+  void printEquivalenceClasses(raw_ostream &Out, ProgramStateRef State,
+   const char *NL = "\n", unsigned int Space = 0,
+   bool IsDot = false) const;
+  void printDisequalities(raw_ostream &Out, ProgramStateRef State,
+  const char *NL = "\n", unsigned int Space = 0,
+  bool IsDot = false) const;
 
   //===--===//
   // Implementation for interface from RangedConstraintManager.
@@ -1749,6 +1763,15 @@ ConstraintMap ento::getConstraintMap(ProgramStateRef 
State) {
 // EqualityClass implementation details
 
//===--===//
 
+LLVM_DUMP_METHOD void EquivalenceClass::dumpToStream(ProgramStateRef State,
+ raw_ostream &os) const {
+  SymbolSet ClassMembers = getClassMembers(State);
+  for (const SymbolRef &MemberSym : ClassMembers) {
+MemberSym->dump();
+os << "\n";
+  }
+}
+
 inline EquivalenceClass EquivalenceClass::find(ProgramStateRef State,
SymbolRef Sym) {
   assert(State && "State should not be null");
@@ -2601,6 +2624,16 @@ ProgramStateRef 
RangeConstraintManager::assumeSymOutsideInclusiveRange(
 void RangeConstraintManager::printJson(raw_ostream &Out, ProgramStateRef State,
const char *NL, unsigned int Space,
bool IsDot) const {
+  printConstraints(Out, State, NL, Space, IsDot);
+  printEquivalenceClasses(Out, State, NL, Space, IsDot);
+  printDisequalities(Out, State, NL, Space, IsDot);
+}
+
+void RangeConstraintManager::printConstraints(raw_ostream &Out,
+  ProgramStateRef State,
+  const char *NL,
+  unsigned int Space,
+  bool IsDot) const {
   ConstraintRangeTy Constraints = State->get();
 
   Indent(Out, Space, IsDot) << "\"constraints\": ";
@@ -2634,3 +2667,140 @@ void RangeConstraintManager::printJson(raw_ostream 
&Out, ProgramStateRef State,
   --Space;
   Indent(Out, Space, IsDot) << "]," << NL;
 }
+
+static std::string toString(const SymbolRef &Sym) {
+  std::string S;
+  llvm::raw_string_ostream O(S);
+  Sym->dumpToStream(O);
+  return O.str();
+}
+
+static std::string toString(ProgramStateRef State, EquivalenceClass Class) {
+  SymbolSet ClassMembers = Class.getClassMembers(State);
+  llvm::SmallVector ClassMembersSorted(ClassMembers.begin(),
+ ClassMembers.end());
+  llvm::sort(ClassMembersSorted,
+ [](const SymbolRef &LHS, const SymbolRef &RHS) {
+

[PATCH] D103967: [Analyzer][solver] Add dump methods for (dis)equality classes.

2021-07-14 Thread Gabor Marton via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGbdf31471c76b: [Analyzer][solver] Add dump methods for 
(dis)equality classes. (authored by martong).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103967

Files:
  clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
  clang/test/Analysis/expr-inspection-printState-diseq-info.c
  clang/test/Analysis/expr-inspection-printState-eq-classes.c
  clang/test/Analysis/expr-inspection.c

Index: clang/test/Analysis/expr-inspection.c
===
--- clang/test/Analysis/expr-inspection.c
+++ clang/test/Analysis/expr-inspection.c
@@ -38,6 +38,8 @@
 // CHECK-NEXT:   "constraints": [
 // CHECK-NEXT: { "symbol": "reg_$0", "range": "{ [-2147483648, 13] }" }
 // CHECK-NEXT:   ],
+// CHECK-NEXT:   "equivalence_classes": null,
+// CHECK-NEXT:   "disequality_info": null,
 // CHECK-NEXT:   "dynamic_types": null,
 // CHECK-NEXT:   "dynamic_casts": null,
 // CHECK-NEXT:   "constructing_objects": null,
Index: clang/test/Analysis/expr-inspection-printState-eq-classes.c
===
--- /dev/null
+++ clang/test/Analysis/expr-inspection-printState-eq-classes.c
@@ -0,0 +1,21 @@
+// RUN: %clang_analyze_cc1 \
+// RUN:  -analyzer-checker=debug.ExprInspection %s 2>&1 | FileCheck %s
+
+void clang_analyzer_printState();
+
+void test_equivalence_classes(int a, int b, int c, int d) {
+  if (a + b != c)
+return;
+  if (a != d)
+return;
+  if (b != 0)
+return;
+  clang_analyzer_printState();
+  (void)(a * b * c * d);
+  return;
+}
+
+  // CHECK:  "equivalence_classes": [
+  // CHECK-NEXT:   [ "((reg_$0) + (reg_$1)) != (reg_$2)", "(reg_$0) != (reg_$2)" ],
+  // CHECK-NEXT:   [ "(reg_$0) + (reg_$1)", "reg_$0", "reg_$2", "reg_$3" ]
+  // CHECK-NEXT: ],
Index: clang/test/Analysis/expr-inspection-printState-diseq-info.c
===
--- /dev/null
+++ clang/test/Analysis/expr-inspection-printState-diseq-info.c
@@ -0,0 +1,34 @@
+// RUN: %clang_analyze_cc1 \
+// RUN:  -analyzer-checker=debug.ExprInspection %s 2>&1 | FileCheck %s
+
+void clang_analyzer_printState();
+
+void test_disequality_info(int e0, int b0, int b1, int c0) {
+  int e1 = e0 - b0;
+  if (b0 == 2) {
+int e2 = e1 - b1;
+if (e2 > 0) {
+  if (b1 != c0)
+clang_analyzer_printState();
+}
+  }
+}
+
+ // CHECK:"disequality_info": [
+ // CHECK-NEXT: {
+ // CHECK-NEXT:   "class": [ "(reg_$0) - 2" ],
+ // CHECK-NEXT:   "disequal_to": [
+ // CHECK-NEXT: [ "reg_$2" ]]
+ // CHECK-NEXT: },
+ // CHECK-NEXT: {
+ // CHECK-NEXT:   "class": [ "reg_$2" ],
+ // CHECK-NEXT:   "disequal_to": [
+ // CHECK-NEXT: [ "(reg_$0) - 2" ],
+ // CHECK-NEXT: [ "reg_$3" ]]
+ // CHECK-NEXT: },
+ // CHECK-NEXT: {
+ // CHECK-NEXT:   "class": [ "reg_$3" ],
+ // CHECK-NEXT:   "disequal_to": [
+ // CHECK-NEXT: [ "reg_$2" ]]
+ // CHECK-NEXT: }
+ // CHECK-NEXT:   ],
Index: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
===
--- clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
+++ clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
@@ -592,6 +592,11 @@
   RangeSet::Factory &F,
   ProgramStateRef State);
 
+  void dumpToStream(ProgramStateRef State, raw_ostream &os) const;
+  LLVM_DUMP_METHOD void dump(ProgramStateRef State) const {
+dumpToStream(State, llvm::errs());
+  }
+
   /// Check equivalence data for consistency.
   LLVM_NODISCARD LLVM_ATTRIBUTE_UNUSED static bool
   isClassDataConsistent(ProgramStateRef State);
@@ -1599,6 +1604,15 @@
 
   void printJson(raw_ostream &Out, ProgramStateRef State, const char *NL = "\n",
  unsigned int Space = 0, bool IsDot = false) const override;
+  void printConstraints(raw_ostream &Out, ProgramStateRef State,
+const char *NL = "\n", unsigned int Space = 0,
+bool IsDot = false) const;
+  void printEquivalenceClasses(raw_ostream &Out, ProgramStateRef State,
+   const char *NL = "\n", unsigned int Space = 0,
+   bool IsDot = false) const;
+  void printDisequalities(raw_ostream &Out, ProgramStateRef State,
+  const char *NL = "\n", unsigned int Space = 0,
+  bool IsDot = false) const;
 
   //===--===//
   // Implementation for interface from RangedConstraintManager.
@@ -1749,6 +1763,15 @@
 // EqualityClass implementation details
 //===--===/

[PATCH] D105964: [clang-format] Make AlwaysBreakAfterReturnType work with K&R C function definitions

2021-07-14 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius accepted this revision.
curdeius added a comment.

LGTM.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105964

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


[PATCH] D105629: [TSan] Add SystemZ support

2021-07-14 Thread Ulrich Weigand via Phabricator via cfe-commits
uweigand added a comment.

The SystemZ specific changes all look good to me now, thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105629

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


[PATCH] D105972: Fix __attribute__((annotate("")) with non-zero globals AS

2021-07-14 Thread Alexander Richardson via Phabricator via cfe-commits
arichardson created this revision.
arichardson added reviewers: rjmccall, nhaehnle, Tyker.
Herald added subscribers: jrtc27, luismarques, s.egerton, PkmX, simoncook, tpr.
arichardson requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

The existing code attempting to bitcast from a value in the default
globals AS to i8 addrspace(0)* was triggering an assertion failure for me.
I found this while compiling poppler for CHERI-RISC-V (we use AS200 for
all globals). The test case uses AMDGPU since that is one of the in-tree
targets with a non-zero default globals address space.
The new test previously triggered a "Invalid constantexpr bitcast!"
assertion an now correctly generates code with addrspace(1) pointers.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D105972

Files:
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/CodeGen/CodeGenTypeCache.h
  clang/test/CodeGen/annotations-global.c


Index: clang/test/CodeGen/annotations-global.c
===
--- clang/test/CodeGen/annotations-global.c
+++ clang/test/CodeGen/annotations-global.c
@@ -4,6 +4,7 @@
 // RUN: FileCheck --check-prefix=BAR %s < %t1
 // RUN: FileCheck --check-prefix=FOOS %s < %t1
 // RUN: FileCheck --check-prefix=ADDRSPACE %s < %t1
+// RUN: %clang_cc1 %s -triple r600 -emit-llvm -o - | FileCheck %s 
--check-prefix AS1-GLOBALS
 // END.
 
 static __attribute((annotate("sfoo_0"))) __attribute((annotate("sfoo_1"))) 
char sfoo;
@@ -45,3 +46,8 @@
 
 // ADDRSPACE: target triple
 // ADDRSPACE: @llvm.global.annotations = appending global {{.*}} addrspacecast 
(i8 addrspace(1)* @addrspace1_var to i8*), {{.*}}
+
+// AS1-GLOBALS: target datalayout = "{{.+}}-A5-G1"
+// AS1-GLOBALS: @llvm.global.annotations = appending addrspace(1) global [11 x 
{ i8 addrspace(1)*, i8 addrspace(1)*, i8 addrspace(1)*, i32, i8 addrspace(1)* }]
+// AS1-GLOBALS-SAME: { i8 addrspace(1)* @a.bar,
+// AS1-GLOBALS-SAME: { i8 addrspace(1)* @addrspace1_var,
Index: clang/lib/CodeGen/CodeGenTypeCache.h
===
--- clang/lib/CodeGen/CodeGenTypeCache.h
+++ clang/lib/CodeGen/CodeGenTypeCache.h
@@ -69,6 +69,12 @@
 llvm::PointerType *AllocaInt8PtrTy;
   };
 
+  /// void* in default globals address space
+  union {
+llvm::PointerType *GlobalsVoidPtrTy;
+llvm::PointerType *GlobalsInt8PtrTy;
+  };
+
   /// The size and alignment of the builtin C type 'int'.  This comes
   /// up enough in various ABI lowering tasks to be worth pre-computing.
   union {
Index: clang/lib/CodeGen/CodeGenModule.cpp
===
--- clang/lib/CodeGen/CodeGenModule.cpp
+++ clang/lib/CodeGen/CodeGenModule.cpp
@@ -130,8 +130,9 @@
 C.getTargetInfo().getMaxPointerWidth());
   Int8PtrTy = Int8Ty->getPointerTo(0);
   Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
-  AllocaInt8PtrTy = Int8Ty->getPointerTo(
-  M.getDataLayout().getAllocaAddrSpace());
+  const llvm::DataLayout &DL = M.getDataLayout();
+  AllocaInt8PtrTy = Int8Ty->getPointerTo(DL.getAllocaAddrSpace());
+  GlobalsInt8PtrTy = Int8Ty->getPointerTo(DL.getDefaultGlobalsAddressSpace());
   ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
 
   RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
@@ -2515,7 +2516,7 @@
 llvm::Constant *CodeGenModule::EmitAnnotationArgs(const AnnotateAttr *Attr) {
   ArrayRef Exprs = {Attr->args_begin(), Attr->args_size()};
   if (Exprs.empty())
-return llvm::ConstantPointerNull::get(Int8PtrTy);
+return llvm::ConstantPointerNull::get(GlobalsInt8PtrTy);
 
   llvm::FoldingSetNodeID ID;
   for (Expr *E : Exprs) {
@@ -2539,7 +2540,7 @@
   ".args");
   GV->setSection(AnnotationSection);
   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
-  auto *Bitcasted = llvm::ConstantExpr::getBitCast(GV, Int8PtrTy);
+  auto *Bitcasted = llvm::ConstantExpr::getBitCast(GV, GlobalsInt8PtrTy);
 
   Lookup = Bitcasted;
   return Bitcasted;
@@ -2554,17 +2555,19 @@
  *LineNoCst = EmitAnnotationLineNo(L),
  *Args = EmitAnnotationArgs(AA);
 
-  llvm::Constant *ASZeroGV = GV;
-  if (GV->getAddressSpace() != 0) {
-ASZeroGV = llvm::ConstantExpr::getAddrSpaceCast(
-   GV, GV->getValueType()->getPointerTo(0));
+  llvm::Constant *GVInGlobalsAS = GV;
+  if (GV->getAddressSpace() !=
+  getDataLayout().getDefaultGlobalsAddressSpace()) {
+GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast(
+GV, GV->getValueType()->getPointerTo(
+getDataLayout().getDefaultGlobalsAddressSpace()));
   }
 
   // Create the ConstantStruct for the global annotation.
   llvm::Constant *Fields[] = {
-  llvm::ConstantExpr::getBitCast(ASZeroGV, Int8PtrTy),
-  llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
-  llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy

[PATCH] D105973: [ASTMatchers] NFC: Fix the annotation.

2021-07-14 Thread gehry via Phabricator via cfe-commits
Sockke created this revision.
Sockke added reviewers: ymandel, aaron.ballman, MTC.
Sockke requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

The annotation about ignoringImpCasts is wrong, which will cause 
misunderstanding. Fix it.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D105973

Files:
  clang/include/clang/ASTMatchers/ASTMatchers.h


Index: clang/include/clang/ASTMatchers/ASTMatchers.h
===
--- clang/include/clang/ASTMatchers/ASTMatchers.h
+++ clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -913,7 +913,7 @@
 ///varDecl(hasInitializer(integerLiteral()))
 ///varDecl(hasInitializer(declRefExpr()))
 /// \endcode
-/// only match the declarations for b, c, and d.
+/// only match the declarations for a.
 AST_MATCHER_P(Expr, ignoringImpCasts,
   internal::Matcher, InnerMatcher) {
   return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder);


Index: clang/include/clang/ASTMatchers/ASTMatchers.h
===
--- clang/include/clang/ASTMatchers/ASTMatchers.h
+++ clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -913,7 +913,7 @@
 ///varDecl(hasInitializer(integerLiteral()))
 ///varDecl(hasInitializer(declRefExpr()))
 /// \endcode
-/// only match the declarations for b, c, and d.
+/// only match the declarations for a.
 AST_MATCHER_P(Expr, ignoringImpCasts,
   internal::Matcher, InnerMatcher) {
   return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D105974: [analyzer] Fix assertion in state split code path

2021-07-14 Thread Vince Bridgers via Phabricator via cfe-commits
vabridgers created this revision.
vabridgers added reviewers: martong, steakhal.
Herald added subscribers: manas, ASDenysPetrov, dkrupp, donat.nagy, Szelethus, 
mikhail.ramalho, a.sidorin, rnkovacs, szepet, baloghadamsoftware, xazax.hun, 
whisperity.
vabridgers requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This change addresses this assertion that occurs in a downstream
compiler with a custom target.

APInt.h:1151: bool llvm::APInt::operator==(const llvm::APInt &) const:
 Assertion `BitWidth == RHS.BitWidth && "Comparison requires equal bit widths"'

No covering test case is susbmitted with this change since this crash
cannot be reproduced using any upstream supported target. The test case
that exposes this issue is as simple as:

  void test(int * p) {
int * q = p-1;
if (q) {}
if (q) {}
(void)q;
  }

The custom target that exposes this problem supports two address spaces,
16-bit chars, and a _Bool type that maps to 16-bits. There are no upstream
supported targets with similar attributes.

The assertion appears to be happening as a result of evaluting the
SymIntExpr "(reg_$0) != 0U" in VisitSymIntExpr located in
SimpleSValBuilder.cpp. The LHS is evaluated to 32b and the RHS is
evaluated to 16b. This eventually leads to the assertion in APInt.h.

While this change addresses the crash and passes LITs, two follow ups
are required:

1. The remainder of getZeroWithPtrWidth() and getIntWithPtrWidth() should be 
cleaned up following this model to prevent future confusion.
2. We're not sure why references are found along the modified code path, that 
should not be the case. A more principled fix may be found after some further 
comprehension of why this is the case.

Acks: Thanks to steakhal and martong for the discussions leading to this

  fix.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D105974

Files:
  clang/lib/StaticAnalyzer/Core/SValBuilder.cpp


Index: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
@@ -712,9 +712,18 @@
   // symbols to use, only content metadata.
   return nonloc::SymbolVal(SymMgr.getExtentSymbol(FTR));
 
-if (const SymbolicRegion *SymR = R->getSymbolicBase())
-  return makeNonLoc(SymR->getSymbol(), BO_NE,
-BasicVals.getZeroWithPtrWidth(), CastTy);
+if (const SymbolicRegion *SymR = R->getSymbolicBase()) {
+  SymbolRef Sym = SymR->getSymbol();
+  QualType Ty = Sym->getType();
+  // FIXME: Why did we have references at this point?
+  // FIXME: Cleanup remainder of `getZeroWithPtrWidth ()`
+  //and `getIntWithPtrWidth()` functions to prevent future
+  //confusion
+  const llvm::APSInt &Zero = Ty->isReferenceType()
+ ? BasicVals.getZeroWithPtrWidth()
+ : BasicVals.getZeroWithTypeSize(Ty);
+  return makeNonLoc(Sym, BO_NE, Zero, CastTy);
+}
 // Non-symbolic memory regions are always true.
 return makeTruthVal(true, CastTy);
   }


Index: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
@@ -712,9 +712,18 @@
   // symbols to use, only content metadata.
   return nonloc::SymbolVal(SymMgr.getExtentSymbol(FTR));
 
-if (const SymbolicRegion *SymR = R->getSymbolicBase())
-  return makeNonLoc(SymR->getSymbol(), BO_NE,
-BasicVals.getZeroWithPtrWidth(), CastTy);
+if (const SymbolicRegion *SymR = R->getSymbolicBase()) {
+  SymbolRef Sym = SymR->getSymbol();
+  QualType Ty = Sym->getType();
+  // FIXME: Why did we have references at this point?
+  // FIXME: Cleanup remainder of `getZeroWithPtrWidth ()`
+  //and `getIntWithPtrWidth()` functions to prevent future
+  //confusion
+  const llvm::APSInt &Zero = Ty->isReferenceType()
+ ? BasicVals.getZeroWithPtrWidth()
+ : BasicVals.getZeroWithTypeSize(Ty);
+  return makeNonLoc(Sym, BO_NE, Zero, CastTy);
+}
 // Non-symbolic memory regions are always true.
 return makeTruthVal(true, CastTy);
   }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D105974: [analyzer] Fix assertion in state split code path

2021-07-14 Thread Vince Bridgers via Phabricator via cfe-commits
vabridgers updated this revision to Diff 358573.
vabridgers added a comment.

update commit header


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105974

Files:
  clang/lib/StaticAnalyzer/Core/SValBuilder.cpp


Index: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
@@ -712,9 +712,18 @@
   // symbols to use, only content metadata.
   return nonloc::SymbolVal(SymMgr.getExtentSymbol(FTR));
 
-if (const SymbolicRegion *SymR = R->getSymbolicBase())
-  return makeNonLoc(SymR->getSymbol(), BO_NE,
-BasicVals.getZeroWithPtrWidth(), CastTy);
+if (const SymbolicRegion *SymR = R->getSymbolicBase()) {
+  SymbolRef Sym = SymR->getSymbol();
+  QualType Ty = Sym->getType();
+  // FIXME: Why did we have references at this point?
+  // FIXME: Cleanup remainder of `getZeroWithPtrWidth ()`
+  //and `getIntWithPtrWidth()` functions to prevent future
+  //confusion
+  const llvm::APSInt &Zero = Ty->isReferenceType()
+ ? BasicVals.getZeroWithPtrWidth()
+ : BasicVals.getZeroWithTypeSize(Ty);
+  return makeNonLoc(Sym, BO_NE, Zero, CastTy);
+}
 // Non-symbolic memory regions are always true.
 return makeTruthVal(true, CastTy);
   }


Index: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
@@ -712,9 +712,18 @@
   // symbols to use, only content metadata.
   return nonloc::SymbolVal(SymMgr.getExtentSymbol(FTR));
 
-if (const SymbolicRegion *SymR = R->getSymbolicBase())
-  return makeNonLoc(SymR->getSymbol(), BO_NE,
-BasicVals.getZeroWithPtrWidth(), CastTy);
+if (const SymbolicRegion *SymR = R->getSymbolicBase()) {
+  SymbolRef Sym = SymR->getSymbol();
+  QualType Ty = Sym->getType();
+  // FIXME: Why did we have references at this point?
+  // FIXME: Cleanup remainder of `getZeroWithPtrWidth ()`
+  //and `getIntWithPtrWidth()` functions to prevent future
+  //confusion
+  const llvm::APSInt &Zero = Ty->isReferenceType()
+ ? BasicVals.getZeroWithPtrWidth()
+ : BasicVals.getZeroWithTypeSize(Ty);
+  return makeNonLoc(Sym, BO_NE, Zero, CastTy);
+}
 // Non-symbolic memory regions are always true.
 return makeTruthVal(true, CastTy);
   }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D69764: [clang-format] Add East/West Const fixer capability

2021-07-14 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius added a comment.

I've been trying to make my opinion on this patch for the last few weeks...
I was pretty much opposed to introducing non-whitespace chances previously, but 
I'm reviewing my standpoint.
As mentioned already, there are precedents (include sorting, namespace 
comments, long string splitting).
I'm however even more wary of adding yet another tool that will be almost the 
same as clang-format. It could work if it were a drop-in replacement of 
clang-format, but that seems to be very much wishful thinking to me.
First, maintenance burden to verify that the two don't diverge somehow. 
Secondly, the drop-in replacement wouldn't be possible without changing 
clang-format itself (e.g. to ignore style options that are for "clang-format++" 
only). Also, it might divide the users into clang-format camp and 
clang-format++ camp (which may or may not be a problem).
Lastly, I do think that clang-format can be as reliable with this patch as it's 
now. Breaking code is of course possible but that's the case of many style 
options. And these are bugs that will eventually get fixed. It's of course 
important that this option doesn't break anything ever by default, but given 
that the default is Leave, and it's implemented as an additional pass, that 
should be the case.
Also, I'd be a bit surprised if people used it in CI immediately after this 
feature has landed without verifying that it doesn't break anything on their 
codebase.

On the other hand, clang-tidy has a corresponding check. I do feel though 
that's a sort of heavyweight tool and much less used than clang-format. Also, 
the placing of const qualifier is by many (at least in my circles) associated 
to the latter tool.

So yes, I'm in favour of landing this patch (though not exactly in the current 
form, I'd prefer more future-proof options for instance, not only handling 
const).
My (longish) 2 cents.


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

https://reviews.llvm.org/D69764

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


[PATCH] D105221: [openmp][nfc] Simplify macros guarding math complex headers

2021-07-14 Thread Pushpinder Singh via Phabricator via cfe-commits
pdhaliwal added a comment.

Looks ok to me. Regression tests and runtime tests went fine. Tested a simple 
cuda and openmp kernel with `sin` function on sm_61, didn't see any issue.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105221

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


[PATCH] D105703: [hwasan] Use stack safety analysis.

2021-07-14 Thread Florian Mayer via Phabricator via cfe-commits
fmayer updated this revision to Diff 358577.
fmayer added a comment.

fixup


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105703

Files:
  clang/lib/CodeGen/BackendUtil.cpp
  clang/test/CodeGen/hwasan-stack-safety-analysis-asm.c
  clang/test/CodeGen/hwasan-stack-safety-analysis.c
  llvm/include/llvm/Transforms/Instrumentation/HWAddressSanitizer.h
  llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp

Index: llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
===
--- llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
+++ llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
@@ -17,6 +17,7 @@
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/Triple.h"
+#include "llvm/Analysis/StackSafetyAnalysis.h"
 #include "llvm/BinaryFormat/ELF.h"
 #include "llvm/IR/Attributes.h"
 #include "llvm/IR/BasicBlock.h"
@@ -109,6 +110,11 @@
cl::desc("instrument stack (allocas)"),
cl::Hidden, cl::init(true));
 
+static cl::opt
+ClUseStackSafety("hwasan-use-stack-safety", cl::Hidden, cl::init(true),
+ cl::Hidden, cl::desc("Use Stack Safety analysis results"),
+ cl::Optional);
+
 static cl::opt ClUARRetagToZero(
 "hwasan-uar-retag-to-zero",
 cl::desc("Clear alloca tags before returning from the function to allow "
@@ -210,13 +216,21 @@
 #pragma GCC poison ClInstrumentWithCalls
 }
 
+bool shouldUseStackSafetyAnalysis(const Triple &TargetTriple, bool IsOptNull) {
+  auto StackSafety =
+  ClUseStackSafety.getNumOccurrences() ? ClUseStackSafety : !IsOptNull;
+  return shouldInstrumentStack(TargetTriple) && StackSafety;
+// No one should use the option directly.
+#pragma GCC poison ClUseStackSafety
+}
 /// An instrumentation pass implementing detection of addressability bugs
 /// using tagged pointers.
 class HWAddressSanitizer {
 public:
   explicit HWAddressSanitizer(Module &M, bool CompileKernel = false,
-  bool Recover = false)
-  : M(M) {
+  bool Recover = false,
+  const StackSafetyGlobalInfo *SSI = nullptr)
+  : M(M), SSI(SSI) {
 this->Recover = ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover;
 this->CompileKernel = ClEnableKhwasan.getNumOccurrences() > 0
   ? ClEnableKhwasan
@@ -225,6 +239,8 @@
 initializeModule();
   }
 
+  void setSSI(const StackSafetyGlobalInfo *S) { SSI = S; }
+
   bool sanitizeFunction(Function &F);
   void initializeModule();
   void createHwasanCtorComdat();
@@ -277,6 +293,7 @@
 private:
   LLVMContext *C;
   Module &M;
+  const StackSafetyGlobalInfo *SSI;
   Triple TargetTriple;
   FunctionCallee HWAsanMemmove, HWAsanMemcpy, HWAsanMemset;
   FunctionCallee HWAsanHandleVfork;
@@ -347,8 +364,11 @@
   static char ID;
 
   explicit HWAddressSanitizerLegacyPass(bool CompileKernel = false,
-bool Recover = false)
-  : FunctionPass(ID), CompileKernel(CompileKernel), Recover(Recover) {
+bool Recover = false,
+Triple TargetTriple = {},
+bool IsOptNull = false)
+  : FunctionPass(ID), CompileKernel(CompileKernel), Recover(Recover),
+TargetTriple(TargetTriple) {
 initializeHWAddressSanitizerLegacyPassPass(
 *PassRegistry::getPassRegistry());
   }
@@ -356,11 +376,18 @@
   StringRef getPassName() const override { return "HWAddressSanitizer"; }
 
   bool doInitialization(Module &M) override {
-HWASan = std::make_unique(M, CompileKernel, Recover);
+HWASan = std::make_unique(M, CompileKernel, Recover,
+  /*SSI=*/nullptr);
 return true;
   }
 
   bool runOnFunction(Function &F) override {
+if (shouldUseStackSafetyAnalysis(TargetTriple, IsOptNull)) {
+  // We cannot call getAnalysis in doInitialization, that would cause a
+  // crash as the required analyses are not initialized yet.
+  HWASan->setSSI(
+  &getAnalysis().getResult());
+}
 return HWASan->sanitizeFunction(F);
   }
 
@@ -369,10 +396,18 @@
 return false;
   }
 
+  void getAnalysisUsage(AnalysisUsage &AU) const override {
+if (shouldUseStackSafetyAnalysis(TargetTriple, IsOptNull)) {
+  AU.addRequired();
+}
+  }
+
 private:
   std::unique_ptr HWASan;
   bool CompileKernel;
   bool Recover;
+  Triple TargetTriple;
+  bool IsOptNull;
 };
 
 } // end anonymous namespace
@@ -389,17 +424,27 @@
 false)
 
 FunctionPass *llvm::createHWAddressSanitizerLegacyPassPass(bool CompileKernel,
-   bool Recover) {
+   

[PATCH] D105221: [openmp][nfc] Simplify macros guarding math complex headers

2021-07-14 Thread Jon Chesterfield via Phabricator via cfe-commits
JonChesterfield added inline comments.



Comment at: clang/lib/Headers/openmp_wrappers/complex:21
 #define __OPENMP_NVPTX__
 #include <__clang_cuda_complex_builtins.h>
 #undef __OPENMP_NVPTX__

^ this header does not look for a macro called __CUDA__ or include any other 
headers so I believe dropping the macro can make no change to that header.

It might affect other things that happen to be included after this header, but 
iiuc cuda and openmp-nvptx both define `__CUDA__` anyway, so that could only 
break amdgpu applications that were erroneously looking for a cuda macro.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105221

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


[PATCH] D105703: [hwasan] Use stack safety analysis.

2021-07-14 Thread Florian Mayer via Phabricator via cfe-commits
fmayer marked an inline comment as done and an inline comment as not done.
fmayer added a comment.

Addressed inline comments.




Comment at: clang/test/CodeGen/hwasan-stack-safety-analysis-asm.c:4
+
+int main(int argc, char **argv) {
+  char buf[10];

vitalybuka wrote:
> this patch mostly change code under llvm/ so tests should be also there, as 
> IR tests
> 
> 
I don't have strong feelings, but clang/test/CodeGen/lifetime-sanitizer.c is a 
very similar test, so I think we should either move all of these to llvm/ or 
add the new ones here to clang/. What do you think?



Comment at: llvm/include/llvm/Transforms/Instrumentation/HWAddressSanitizer.h:32
+  Triple TargetTriple = {});
   PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM);
   static bool isRequired() { return true; }

vitalybuka wrote:
> Why not from M.getTargetTriple() ?
Mostly for consistency with the legacy pass. Either way is fine for me though, 
what do you prefer?



Comment at: llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp:390
+  void getAnalysisUsage(AnalysisUsage &AU) const override {
+if (shouldUseStackSafetyAnalysis(TargetTriple)) {
+  AU.addRequired();

vitalybuka wrote:
> why we need to check TargetTriple for that?
Because we only need the stack safety analysis if we instrument the stack, 
which we do not do on x86_64 (see shouldInstrumentStack).



Comment at: llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp:1275
 bool HWAddressSanitizer::isInterestingAlloca(const AllocaInst &AI) {
+  // clang-format off
   return (AI.getAllocatedType()->isSized() &&

vitalybuka wrote:
> Instead of // clang-format off
> could you replace this with
> 
> ```
> # comment1
> if (...)
>   return false;
> 
> # comment2
> if (...)
>   return false;
> ...
> 
> ```
> 
> in a separate patch?
OK, will do in a followup (or see how I can get clang-tidy to do the right 
thing here).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105703

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


[PATCH] D105703: [hwasan] Use stack safety analysis.

2021-07-14 Thread Florian Mayer via Phabricator via cfe-commits
fmayer updated this revision to Diff 358579.
fmayer marked an inline comment as done.
fmayer added a comment.

rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105703

Files:
  clang/lib/CodeGen/BackendUtil.cpp
  clang/test/CodeGen/hwasan-stack-safety-analysis-asm.c
  clang/test/CodeGen/hwasan-stack-safety-analysis.c
  llvm/include/llvm/Transforms/Instrumentation/HWAddressSanitizer.h
  llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp

Index: llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
===
--- llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
+++ llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
@@ -17,6 +17,7 @@
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/Triple.h"
+#include "llvm/Analysis/StackSafetyAnalysis.h"
 #include "llvm/BinaryFormat/ELF.h"
 #include "llvm/IR/Attributes.h"
 #include "llvm/IR/BasicBlock.h"
@@ -109,6 +110,11 @@
cl::desc("instrument stack (allocas)"),
cl::Hidden, cl::init(true));
 
+static cl::opt
+ClUseStackSafety("hwasan-use-stack-safety", cl::Hidden, cl::init(true),
+ cl::Hidden, cl::desc("Use Stack Safety analysis results"),
+ cl::Optional);
+
 static cl::opt ClUARRetagToZero(
 "hwasan-uar-retag-to-zero",
 cl::desc("Clear alloca tags before returning from the function to allow "
@@ -210,13 +216,21 @@
 #pragma GCC poison ClInstrumentWithCalls
 }
 
+bool shouldUseStackSafetyAnalysis(const Triple &TargetTriple, bool IsOptNull) {
+  auto StackSafety =
+  ClUseStackSafety.getNumOccurrences() ? ClUseStackSafety : !IsOptNull;
+  return shouldInstrumentStack(TargetTriple) && StackSafety;
+// No one should use the option directly.
+#pragma GCC poison ClUseStackSafety
+}
 /// An instrumentation pass implementing detection of addressability bugs
 /// using tagged pointers.
 class HWAddressSanitizer {
 public:
   explicit HWAddressSanitizer(Module &M, bool CompileKernel = false,
-  bool Recover = false)
-  : M(M) {
+  bool Recover = false,
+  const StackSafetyGlobalInfo *SSI = nullptr)
+  : M(M), SSI(SSI) {
 this->Recover = ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover;
 this->CompileKernel = ClEnableKhwasan.getNumOccurrences() > 0
   ? ClEnableKhwasan
@@ -225,6 +239,8 @@
 initializeModule();
   }
 
+  void setSSI(const StackSafetyGlobalInfo *S) { SSI = S; }
+
   bool sanitizeFunction(Function &F);
   void initializeModule();
   void createHwasanCtorComdat();
@@ -277,6 +293,7 @@
 private:
   LLVMContext *C;
   Module &M;
+  const StackSafetyGlobalInfo *SSI;
   Triple TargetTriple;
   FunctionCallee HWAsanMemmove, HWAsanMemcpy, HWAsanMemset;
   FunctionCallee HWAsanHandleVfork;
@@ -347,8 +364,11 @@
   static char ID;
 
   explicit HWAddressSanitizerLegacyPass(bool CompileKernel = false,
-bool Recover = false)
-  : FunctionPass(ID), CompileKernel(CompileKernel), Recover(Recover) {
+bool Recover = false,
+Triple TargetTriple = {},
+bool IsOptNull = false)
+  : FunctionPass(ID), CompileKernel(CompileKernel), Recover(Recover),
+TargetTriple(TargetTriple) {
 initializeHWAddressSanitizerLegacyPassPass(
 *PassRegistry::getPassRegistry());
   }
@@ -356,11 +376,18 @@
   StringRef getPassName() const override { return "HWAddressSanitizer"; }
 
   bool doInitialization(Module &M) override {
-HWASan = std::make_unique(M, CompileKernel, Recover);
+HWASan = std::make_unique(M, CompileKernel, Recover,
+  /*SSI=*/nullptr);
 return true;
   }
 
   bool runOnFunction(Function &F) override {
+if (shouldUseStackSafetyAnalysis(TargetTriple, IsOptNull)) {
+  // We cannot call getAnalysis in doInitialization, that would cause a
+  // crash as the required analyses are not initialized yet.
+  HWASan->setSSI(
+  &getAnalysis().getResult());
+}
 return HWASan->sanitizeFunction(F);
   }
 
@@ -369,10 +396,18 @@
 return false;
   }
 
+  void getAnalysisUsage(AnalysisUsage &AU) const override {
+if (shouldUseStackSafetyAnalysis(TargetTriple, IsOptNull)) {
+  AU.addRequired();
+}
+  }
+
 private:
   std::unique_ptr HWASan;
   bool CompileKernel;
   bool Recover;
+  Triple TargetTriple;
+  bool IsOptNull;
 };
 
 } // end anonymous namespace
@@ -389,17 +424,27 @@
 false)
 
 FunctionPass *llvm::createHWAddressSanitizerLegacyPassPass(bool CompileKernel,
-   bool Recov

[PATCH] D104386: [PowerPC][Builtins] Added a number of builtins for compatibility with XL.

2021-07-14 Thread Lei Huang via Phabricator via cfe-commits
lei added inline comments.



Comment at: clang/include/clang/Basic/BuiltinsPPC.def:48
 BUILTIN(__builtin_ppc_icbt, "vv*", "")
+BUILTIN(__builtin_ppc_alignx, "viCvC*", "nc")
+BUILTIN(__builtin_ppc_rdlam, "UWiUWiUWiCUWi", "nc")

I think you need sema checking for parm 1.
```
alignment
Must be a constant integer with a value greater than zero and of a power of two.
```



Comment at: clang/include/clang/Basic/BuiltinsPPC.def:49
+BUILTIN(__builtin_ppc_alignx, "viCvC*", "nc")
+BUILTIN(__builtin_ppc_rdlam, "UWiUWiUWiCUWi", "nc")
 

sema checking?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104386

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


[PATCH] D69764: [clang-format] Add East/West Const fixer capability

2021-07-14 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

> So yes, I'm in favour of landing this patch (though not exactly in the 
> current form, I'd prefer more future-proof options for instance, not only 
> handling const)

I am in agreement, but I don't want to not putting more effort into improving 
the current design of this patch to handle more cases UNTIL we round out on the 
go/no go decision.

From my perspective the use of violate is lower priority as its used like less 
than 0.01% as often as const. but I definitely think that we can add additional 
options on the lines of ReSharper to give even greater flexibility

F17930223: image.png 


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

https://reviews.llvm.org/D69764

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


Re: [PATCH] D69764: [clang-format] Add East/West Const fixer capability

2021-07-14 Thread Gašper Ažman via cfe-commits
+1 for not only handling "const". I've often tried getting the various bits
that appertain to a declaration (static const volatile constexpr inline
consteval) sorted in a consistent order - that makes them much more
greppable.

Different patch, I expect, though.

On Wed, Jul 14, 2021 at 1:47 PM Marek Kurdej via Phabricator <
revi...@reviews.llvm.org> wrote:

> curdeius added a comment.
>
> I've been trying to make my opinion on this patch for the last few weeks...
> I was pretty much opposed to introducing non-whitespace chances
> previously, but I'm reviewing my standpoint.
> As mentioned already, there are precedents (include sorting, namespace
> comments, long string splitting).
> I'm however even more wary of adding yet another tool that will be almost
> the same as clang-format. It could work if it were a drop-in replacement of
> clang-format, but that seems to be very much wishful thinking to me.
> First, maintenance burden to verify that the two don't diverge somehow.
> Secondly, the drop-in replacement wouldn't be possible without changing
> clang-format itself (e.g. to ignore style options that are for
> "clang-format++" only). Also, it might divide the users into clang-format
> camp and clang-format++ camp (which may or may not be a problem).
> Lastly, I do think that clang-format can be as reliable with this patch as
> it's now. Breaking code is of course possible but that's the case of many
> style options. And these are bugs that will eventually get fixed. It's of
> course important that this option doesn't break anything ever by default,
> but given that the default is Leave, and it's implemented as an additional
> pass, that should be the case.
> Also, I'd be a bit surprised if people used it in CI immediately after
> this feature has landed without verifying that it doesn't break anything on
> their codebase.
>
> On the other hand, clang-tidy has a corresponding check. I do feel though
> that's a sort of heavyweight tool and much less used than clang-format.
> Also, the placing of const qualifier is by many (at least in my circles)
> associated to the latter tool.
>
> So yes, I'm in favour of landing this patch (though not exactly in the
> current form, I'd prefer more future-proof options for instance, not only
> handling const).
> My (longish) 2 cents.
>
>
> CHANGES SINCE LAST ACTION
>   https://reviews.llvm.org/D69764/new/
>
> https://reviews.llvm.org/D69764
>
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D105876: OMPIRBuilder for Interop directive

2021-07-14 Thread Sri Hari Krishna Narayanan via Phabricator via cfe-commits
sriharikrishna updated this revision to Diff 358587.
sriharikrishna added a comment.

Address reviewer comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105876

Files:
  clang/lib/CodeGen/CGStmtOpenMP.cpp
  clang/test/OpenMP/interop_irbuilder.cpp
  llvm/include/llvm/Frontend/OpenMP/OMPConstants.h
  llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
  llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp

Index: llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
===
--- llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
+++ llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
@@ -2175,11 +2175,11 @@
 
 CallInst *OpenMPIRBuilder::createOMPInteropInit(const LocationDescription &Loc,
 Value *InteropVar,
-OMPInteropType InteropType,
-llvm::Value *Device,
-llvm::Value *NumDependences,
-llvm::Value *DependenceAddress,
-int HaveNowaitClause) {
+omp::OMPInteropType InteropType,
+Value *Device,
+Value *NumDependences,
+Value *DependenceAddress,
+bool HaveNowaitClause) {
   IRBuilder<>::InsertPointGuard IPG(Builder);
   Builder.restoreIP(Loc.IP);
 
@@ -2188,12 +2188,12 @@
   Value *ThreadId = getOrCreateThreadID(Ident);
   if (Device == NULL)
 Device = ConstantInt::get(M.getContext(), APInt(32, -1, true));
-  ConstantInt *InteropTypeVal =
-  ConstantInt::get(M.getContext(), APInt(64, (int)InteropType, true));
+  Constant *InteropTypeVal =
+  ConstantInt::get(Int64, (int)InteropType);
   if (NumDependences == nullptr) {
-NumDependences = ConstantInt::get(M.getContext(), APInt(32, 0, true));
-PointerType *PointerTy_0 = llvm::Type::getInt8PtrTy(M.getContext());
-DependenceAddress = ConstantPointerNull::get(PointerTy_0);
+NumDependences = ConstantInt::get(Int32, 0);
+PointerType *PointerTypeVar = Type::getInt8PtrTy(M.getContext());
+DependenceAddress = ConstantPointerNull::get(PointerTypeVar);
   }
   Value *HaveNowaitClauseVal =
   ConstantInt::get(M.getContext(), APInt(32, HaveNowaitClause, true));
@@ -2207,9 +2207,9 @@
 }
 
 CallInst *OpenMPIRBuilder::createOMPInteropDestroy(
-const LocationDescription &Loc, Value *InteropVar, llvm::Value *Device,
-llvm::Value *NumDependences, llvm::Value *DependenceAddress,
-int HaveNowaitClause) {
+const LocationDescription &Loc, Value *InteropVar, Value *Device,
+Value *NumDependences, Value *DependenceAddress,
+bool HaveNowaitClause) {
   IRBuilder<>::InsertPointGuard IPG(Builder);
   Builder.restoreIP(Loc.IP);
 
@@ -2219,9 +2219,9 @@
   if (Device == NULL)
 Device = ConstantInt::get(M.getContext(), APInt(32, -1, true));
   if (NumDependences == nullptr) {
-NumDependences = ConstantInt::get(M.getContext(), APInt(32, 0, true));
-PointerType *PointerTy_0 = llvm::Type::getInt8PtrTy(M.getContext());
-DependenceAddress = ConstantPointerNull::get(PointerTy_0);
+NumDependences = ConstantInt::get(Int32, 0);
+PointerType *PointerTypeVar = Type::getInt8PtrTy(M.getContext());
+DependenceAddress = ConstantPointerNull::get(PointerTypeVar);
   }
   Value *HaveNowaitClauseVal =
   ConstantInt::get(M.getContext(), APInt(32, HaveNowaitClause, true));
@@ -2236,10 +2236,10 @@
 
 CallInst *OpenMPIRBuilder::createOMPInteropUse(const LocationDescription &Loc,
Value *InteropVar,
-   llvm::Value *Device,
-   llvm::Value *NumDependences,
-   llvm::Value *DependenceAddress,
-   int HaveNowaitClause) {
+   Value *Device,
+   Value *NumDependences,
+   Value *DependenceAddress,
+   bool HaveNowaitClause) {
   IRBuilder<>::InsertPointGuard IPG(Builder);
   Builder.restoreIP(Loc.IP);
   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc);
@@ -2248,9 +2248,9 @@
   if (Device == NULL)
 Device = ConstantInt::get(M.getContext(), APInt(32, -1, true));
   if (NumDependences == nullptr) {
-NumDependences = ConstantInt::get(M.getContext(), APInt(32, 0, true));
-PointerType *PointerTy_0 = llvm::Type::getInt8PtrTy(M.getContext());
-DependenceAddress = ConstantPointerNull::get(PointerTy_0);
+ 

[PATCH] D105876: OMPIRBuilder for Interop directive

2021-07-14 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: clang/lib/CodeGen/CGStmtOpenMP.cpp:6348-6352
+  } else if(HaveNowaitClause == true) {
+assert("Nowait clause is used separately in OMPInteropDirective.");
   } else {
-llvm_unreachable("Missing Interop clauses.");
+assert("Unhandled or missing clause for OMPInteropDirective ");
   }

Could you merge these asserts and put them as preconditions for the `if-else` 
chain somehow?



Comment at: clang/test/OpenMP/interop_irbuilder.cpp:1
+// RUN: %clang_cc1 -verify -fopenmp  -o -  %s
+

ABataev wrote:
> Actual codegen checks are missing
Still no checks, need to add `| FileCheck %s` to the `RUN` line


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105876

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


[PATCH] D105491: [clang] Use i64 for the !srcloc metadata on asm IR nodes.

2021-07-14 Thread Tomas Matheson via Phabricator via cfe-commits
tmatheson added a comment.

Looks sensible to me, I don't think slightly expanding the size of the metadata 
and the diagnostic will be an issue.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105491

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


[PATCH] D105328: [Frontend] Only compile modules if not already finalized

2021-07-14 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai added inline comments.



Comment at: clang/lib/Frontend/CompilerInstance.cpp:1063
+<< ModuleName;
+return ImportingInstance.getFrontendOpts().AllowPCMWithCompilerErrors;
+  }

bnbarham wrote:
> bnbarham wrote:
> > vsapsai wrote:
> > > Can we get in infinite loop with `AllowPCMWithCompilerErrors = true`? 
> > > Specifically, I'm thinking about the scenario
> > > 
> > > 1. `compileModuleAndReadAST` obtains a file lock and calls `compileModule`
> > > 2. `compileModule` calls `compileModuleImpl`
> > > 3. Module is finalized but `AllowPCMWithCompilerErrors` is true, so 
> > > `compileModuleImpl` returns true
> > > 4. `compileModule` returns true
> > > 5. `compileModuleAndReadAST` tries to read AST because compilation was 
> > > successful
> > > 6. AST is out of date, so `compileModuleAndReadAST` decides to try again, 
> > > goto 1
> > > 
> > > Haven't tried to reproduce it locally but even if this scenario is 
> > > impossible, a corresponding test case can be useful.
> > Nice catch, that does seem likely - I'll see if I can add a test for this.
> It doesn't end up causing an infinite recursion as `false` will end up being 
> returned from `compileModuleAndReadAST`, but in that case there's no point 
> returning `true` from `compileModuleImpl` in the first place so I've changed 
> it anyway. Have also added that as a test case, just to make sure.
Thanks for investigating it and adding a test case.

And appreciate that the error message mentions the module name. It is so hard 
to work with errors like "cannot rebuild this module".



Comment at: clang/lib/Serialization/ASTReader.cpp:2923
   if (!BuildDir || *BuildDir != M->Directory) {
-if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
+if (diagnoseOutOfDate(F.FileName, ClientLoadCapabilities))
   Diag(diag::err_imported_module_relocated)

bnbarham wrote:
> bnbarham wrote:
> > vsapsai wrote:
> > > I'm thinking if in case of finalized modules diagnostic messages are good 
> > > enough. One concern is it won't be clear why a module wasn't rebuilt. It 
> > > can be already confusing for precompiled headers and I'm afraid we won't 
> > > be able to detect `isPCMFinal` code path without a debugger. Though I 
> > > don't know how bad that would be in practice.
> > > 
> > > Another concern is that retrying a compilation should succeed as for a 
> > > new process we have a new InMemoryModuleCache and `isPCMFinal` should 
> > > return false. So we might have non-deterministic behavior and some of the 
> > > valid error messages can seem to be non-deterministic and not reliable. I 
> > > was thinking about adding a note in case we are dealing with `isPCMFinal` 
> > > to distinguish these cases but not sure it is a good idea.
> > > I'm thinking if in case of finalized modules diagnostic messages are good 
> > > enough. One concern is it won't be clear why a module wasn't rebuilt. It 
> > > can be already confusing for precompiled headers and I'm afraid we won't 
> > > be able to detect `isPCMFinal` code path without a debugger. Though I 
> > > don't know how bad that would be in practice.
> > 
> > The error messages will mention a module in the module cache, which would 
> > be the main way to tell. We could add a note here as you suggest below, but 
> > I'm not quite sure what it would say... something about there being two 
> > modules with the same name?
> > 
> > > Another concern is that retrying a compilation should succeed as for a 
> > > new process we have a new InMemoryModuleCache and `isPCMFinal` should 
> > > return false. So we might have non-deterministic behavior and some of the 
> > > valid error messages can seem to be non-deterministic and not reliable. I 
> > > was thinking about adding a note in case we are dealing with `isPCMFinal` 
> > > to distinguish these cases but not sure it is a good idea.
> > 
> > The errors should be deterministic I believe. If one process has the issue 
> > then a new one will have the issue as well. For what it's worth, I don't 
> > think these crashes are possible from the clang frontend. They require 
> > messing around with search paths such that between two compilations in the 
> > same process, different modules are found.
> I've added an extra note "this is generally caused by modules with the same 
> name found in multiple paths". So the diagnostics would now be:
> ```
> /.../test.m:2:10: fatal error: module 'M' was built in directory 
> '/.../frameworks/M.framework' but now resides in directory 
> 'frameworks2/M.framework'
> @import Top;
>  ^
> /.../test.m:2:10: note: imported by module 'Top' in 
> '/path/to/module/cache/LGSY9KSYAKN1/Top-1MZE9QJ1AHENQ.pcm
> /.../test.m:2:10: note: this is generally caused by modules with the same 
> name found in multiple paths
> ```
> 
> I was thinking of mentioning the finalized module, but that's really just a 
> side effect of the error 

[PATCH] D105981: [AMDGPU][OpenMP] Support linking of math libraries

2021-07-14 Thread Pushpinder Singh via Phabricator via cfe-commits
pdhaliwal created this revision.
pdhaliwal added reviewers: JonChesterfield, ronlieb, jdoerfert.
Herald added subscribers: kerbowa, guansong, t-tye, tpr, dstuttard, yaxunl, 
nhaehnle, jvesely, kzhuravl.
pdhaliwal requested review of this revision.
Herald added subscribers: cfe-commits, sstefan1, wdng.
Herald added a project: clang.

Math libraries are linked only when -lm is specified. This is because
host system could be missing rocm-device-libs.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D105981

Files:
  clang/lib/Driver/ToolChains/AMDGPUOpenMP.cpp
  clang/test/Driver/amdgpu-openmp-toolchain.c


Index: clang/test/Driver/amdgpu-openmp-toolchain.c
===
--- clang/test/Driver/amdgpu-openmp-toolchain.c
+++ clang/test/Driver/amdgpu-openmp-toolchain.c
@@ -74,3 +74,6 @@
 
 // RUN:   %clang -### --target=x86_64-unknown-linux-gnu -emit-llvm -S -fopenmp 
-fopenmp-targets=amdgcn-amd-amdhsa -Xopenmp-target=amdgcn-amd-amdhsa 
-march=gfx803 -nogpulib %s 2>&1 | FileCheck %s --check-prefix=CHECK-EMIT-LLVM-IR
 // CHECK-EMIT-LLVM-IR: clang{{.*}}"-cc1"{{.*}}"-triple" 
"amdgcn-amd-amdhsa"{{.*}}"-emit-llvm"
+
+// RUN: env LIBRARY_PATH=%S/Inputs/hip_dev_lib %clang -### -target 
x86_64-pc-linux-gnu -fopenmp -fopenmp-targets=amdgcn-amd-amdhsa 
-Xopenmp-target=amdgcn-amd-amdhsa -march=gfx803 -lm 
--rocm-device-lib-path=%S/Inputs/rocm/amdgcn/bitcode %s 2>&1 | FileCheck %s 
--check-prefix=CHECK-LIB-DEVICE
+// CHECK-LIB-DEVICE: clang{{.*}}"-cc1"{{.*}}"-triple" 
"amdgcn-amd-amdhsa"{{.*}}"-mlink-builtin-bitcode"{{.*}}libomptarget-amdgcn-gfx803.bc"{{.*}}"-mlink-builtin-bitcode"{{.*}}ocml.bc"
 "-mlink-builtin-bitcode"{{.*}}ockl.bc" 
"-mlink-builtin-bitcode"{{.*}}oclc_daz_opt_on.bc" 
"-mlink-builtin-bitcode"{{.*}}oclc_unsafe_math_off.bc" 
"-mlink-builtin-bitcode"{{.*}}oclc_finite_only_off.bc" 
"-mlink-builtin-bitcode"{{.*}}oclc_correctly_rounded_sqrt_off.bc" 
"-mlink-builtin-bitcode"{{.*}}oclc_wavefrontsize64_on.bc" 
"-mlink-builtin-bitcode"{{.*}}oclc_isa_version_803.bc"
Index: clang/lib/Driver/ToolChains/AMDGPUOpenMP.cpp
===
--- clang/lib/Driver/ToolChains/AMDGPUOpenMP.cpp
+++ clang/lib/Driver/ToolChains/AMDGPUOpenMP.cpp
@@ -10,6 +10,7 @@
 #include "AMDGPU.h"
 #include "CommonArgs.h"
 #include "InputInfo.h"
+#include "ToolChains/ROCm.h"
 #include "clang/Basic/DiagnosticDriver.h"
 #include "clang/Driver/Compilation.h"
 #include "clang/Driver/Driver.h"
@@ -225,6 +226,53 @@
   std::string BitcodeSuffix = "amdgcn-" + GPUArch;
   addOpenMPDeviceRTL(getDriver(), DriverArgs, CC1Args, BitcodeSuffix,
  getTriple());
+
+  if (!DriverArgs.hasArg(options::OPT_l))
+return;
+
+  auto Lm = DriverArgs.getAllArgValues(options::OPT_l);
+  bool HasLibm = false;
+  for (auto &Lib : Lm) {
+if (Lib == "m") {
+  HasLibm = true;
+  break;
+}
+  }
+
+  if (HasLibm) {
+auto Kind = llvm::AMDGPU::parseArchAMDGCN(GPUArch);
+const StringRef CanonArch = llvm::AMDGPU::getArchNameAMDGCN(Kind);
+std::string LibDeviceFile = RocmInstallation.getLibDeviceFile(CanonArch);
+if (LibDeviceFile.empty()) {
+  getDriver().Diag(diag::err_drv_no_rocm_device_lib) << 1 << GPUArch;
+  return;
+}
+
+bool Wave64 = isWave64(DriverArgs, Kind);
+
+// TODO: There are way too many flags that change this. Do we need to check
+// them all?
+bool DAZ = DriverArgs.hasArg(options::OPT_cl_denorms_are_zero) ||
+  getDefaultDenormsAreZeroForTarget(Kind);
+bool FiniteOnly = DriverArgs.hasArg(options::OPT_cl_finite_math_only);
+
+bool UnsafeMathOpt =
+DriverArgs.hasArg(options::OPT_cl_unsafe_math_optimizations);
+bool FastRelaxedMath = 
DriverArgs.hasArg(options::OPT_cl_fast_relaxed_math);
+bool CorrectSqrt =
+DriverArgs.hasArg(options::OPT_cl_fp32_correctly_rounded_divide_sqrt);
+
+// Add the generic set of libraries.
+llvm::SmallVector BCLibs;
+BCLibs.append(RocmInstallation.getCommonBitcodeLibs(
+DriverArgs, LibDeviceFile, Wave64, DAZ, FiniteOnly, UnsafeMathOpt,
+FastRelaxedMath, CorrectSqrt));
+
+llvm::for_each(BCLibs, [&](StringRef BCFile) {
+  CC1Args.push_back("-mlink-builtin-bitcode");
+  CC1Args.push_back(DriverArgs.MakeArgString(BCFile));
+});
+  }
 }
 
 llvm::opt::DerivedArgList *AMDGPUOpenMPToolChain::TranslateArgs(


Index: clang/test/Driver/amdgpu-openmp-toolchain.c
===
--- clang/test/Driver/amdgpu-openmp-toolchain.c
+++ clang/test/Driver/amdgpu-openmp-toolchain.c
@@ -74,3 +74,6 @@
 
 // RUN:   %clang -### --target=x86_64-unknown-linux-gnu -emit-llvm -S -fopenmp -fopenmp-targets=amdgcn-amd-amdhsa -Xopenmp-target=amdgcn-amd-amdhsa -march=gfx803 -nogpulib %s 2>&1 | FileCheck %s --check-prefix=CHECK-EMIT-LLVM-IR
 // CHECK-EMIT-LLVM-IR: clang{{.*}}"-cc1"{{.*}}"-triple" "amdgcn-amd-amdhsa"{{.*}}"-emit-llvm"
+
+//

[clang] 93dc73b - [Lexer] Fix bug in `makeFileCharRange` called on split tokens.

2021-07-14 Thread Yitzhak Mandelbaum via cfe-commits

Author: Yitzhak Mandelbaum
Date: 2021-07-14T14:36:31Z
New Revision: 93dc73b1e0f31c712e5b8bbac14491ce55c414ad

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

LOG: [Lexer] Fix bug in `makeFileCharRange` called on split tokens.

When the end loc of the specified range is a split token, `makeFileCharRange`
does not process it correctly.  This patch adds proper support for split tokens.

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

Added: 


Modified: 
clang/lib/Lex/Lexer.cpp
clang/unittests/Lex/LexerTest.cpp

Removed: 




diff  --git a/clang/lib/Lex/Lexer.cpp b/clang/lib/Lex/Lexer.cpp
index cb2b19b59c4ec..2cc4cae533d07 100644
--- a/clang/lib/Lex/Lexer.cpp
+++ b/clang/lib/Lex/Lexer.cpp
@@ -877,6 +877,14 @@ static CharSourceRange 
makeRangeFromFileLocs(CharSourceRange Range,
   return CharSourceRange::getCharRange(Begin, End);
 }
 
+// Assumes that `Loc` is in an expansion.
+static bool isInExpansionTokenRange(const SourceLocation Loc,
+const SourceManager &SM) {
+  return SM.getSLocEntry(SM.getFileID(Loc))
+  .getExpansion()
+  .isExpansionTokenRange();
+}
+
 CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range,
  const SourceManager &SM,
  const LangOptions &LangOpts) {
@@ -896,10 +904,12 @@ CharSourceRange Lexer::makeFileCharRange(CharSourceRange 
Range,
   }
 
   if (Begin.isFileID() && End.isMacroID()) {
-if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpts,
-  &End)) ||
-(Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOpts,
-   &End)))
+if (Range.isTokenRange()) {
+  if (!isAtEndOfMacroExpansion(End, SM, LangOpts, &End))
+return {};
+  // Use the *original* end, not the expanded one in `End`.
+  Range.setTokenRange(isInExpansionTokenRange(Range.getEnd(), SM));
+} else if (!isAtStartOfMacroExpansion(End, SM, LangOpts, &End))
   return {};
 Range.setEnd(End);
 return makeRangeFromFileLocs(Range, SM, LangOpts);
@@ -914,6 +924,9 @@ CharSourceRange Lexer::makeFileCharRange(CharSourceRange 
Range,
  &MacroEnd {
 Range.setBegin(MacroBegin);
 Range.setEnd(MacroEnd);
+// Use the *original* `End`, not the expanded one in `MacroEnd`.
+if (Range.isTokenRange())
+  Range.setTokenRange(isInExpansionTokenRange(End, SM));
 return makeRangeFromFileLocs(Range, SM, LangOpts);
   }
 

diff  --git a/clang/unittests/Lex/LexerTest.cpp 
b/clang/unittests/Lex/LexerTest.cpp
index 4cdabe042cc83..319c63f6a50ba 100644
--- a/clang/unittests/Lex/LexerTest.cpp
+++ b/clang/unittests/Lex/LexerTest.cpp
@@ -25,6 +25,7 @@
 #include "clang/Lex/PreprocessorOptions.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
+#include 
 #include 
 
 namespace {
@@ -65,7 +66,7 @@ class LexerTest : public ::testing::Test {
 
   std::vector Lex(StringRef Source) {
 TrivialModuleLoader ModLoader;
-auto PP = CreatePP(Source, ModLoader);
+PP = CreatePP(Source, ModLoader);
 
 std::vector toks;
 while (1) {
@@ -109,6 +110,7 @@ class LexerTest : public ::testing::Test {
   LangOptions LangOpts;
   std::shared_ptr TargetOpts;
   IntrusiveRefCntPtr Target;
+  std::unique_ptr PP;
 };
 
 TEST_F(LexerTest, GetSourceTextExpandsToMaximumInMacroArgument) {
@@ -264,12 +266,14 @@ TEST_F(LexerTest, GetSourceTextExpandsRecursively) {
 
 TEST_F(LexerTest, LexAPI) {
   std::vector ExpectedTokens;
+  // Line 1 (after the #defines)
   ExpectedTokens.push_back(tok::l_square);
   ExpectedTokens.push_back(tok::identifier);
   ExpectedTokens.push_back(tok::r_square);
   ExpectedTokens.push_back(tok::l_square);
   ExpectedTokens.push_back(tok::identifier);
   ExpectedTokens.push_back(tok::r_square);
+  // Line 2
   ExpectedTokens.push_back(tok::identifier);
   ExpectedTokens.push_back(tok::identifier);
   ExpectedTokens.push_back(tok::identifier);
@@ -357,6 +361,65 @@ TEST_F(LexerTest, LexAPI) {
   EXPECT_EQ("N", Lexer::getImmediateMacroName(idLoc4, SourceMgr, LangOpts));
 }
 
+TEST_F(LexerTest, HandlesSplitTokens) {
+  std::vector ExpectedTokens;
+  // Line 1 (after the #defines)
+  ExpectedTokens.push_back(tok::identifier);
+  ExpectedTokens.push_back(tok::less);
+  ExpectedTokens.push_back(tok::identifier);
+  ExpectedTokens.push_back(tok::less);
+  ExpectedTokens.push_back(tok::greatergreater);
+  // Line 2
+  ExpectedTokens.push_back(tok::identifier);
+  ExpectedTokens.push_back(tok::less);
+  ExpectedTokens.push_back(tok::identifier);
+  ExpectedTokens.push_back(tok::less);
+  ExpectedTokens.push_ba

[PATCH] D105365: [Lexer] Fix bug in `makeFileCharRange` called on split tokens.

2021-07-14 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG93dc73b1e0f3: [Lexer] Fix bug in `makeFileCharRange` called 
on split tokens. (authored by ymandel).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105365

Files:
  clang/lib/Lex/Lexer.cpp
  clang/unittests/Lex/LexerTest.cpp

Index: clang/unittests/Lex/LexerTest.cpp
===
--- clang/unittests/Lex/LexerTest.cpp
+++ clang/unittests/Lex/LexerTest.cpp
@@ -25,6 +25,7 @@
 #include "clang/Lex/PreprocessorOptions.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
+#include 
 #include 
 
 namespace {
@@ -65,7 +66,7 @@
 
   std::vector Lex(StringRef Source) {
 TrivialModuleLoader ModLoader;
-auto PP = CreatePP(Source, ModLoader);
+PP = CreatePP(Source, ModLoader);
 
 std::vector toks;
 while (1) {
@@ -109,6 +110,7 @@
   LangOptions LangOpts;
   std::shared_ptr TargetOpts;
   IntrusiveRefCntPtr Target;
+  std::unique_ptr PP;
 };
 
 TEST_F(LexerTest, GetSourceTextExpandsToMaximumInMacroArgument) {
@@ -264,12 +266,14 @@
 
 TEST_F(LexerTest, LexAPI) {
   std::vector ExpectedTokens;
+  // Line 1 (after the #defines)
   ExpectedTokens.push_back(tok::l_square);
   ExpectedTokens.push_back(tok::identifier);
   ExpectedTokens.push_back(tok::r_square);
   ExpectedTokens.push_back(tok::l_square);
   ExpectedTokens.push_back(tok::identifier);
   ExpectedTokens.push_back(tok::r_square);
+  // Line 2
   ExpectedTokens.push_back(tok::identifier);
   ExpectedTokens.push_back(tok::identifier);
   ExpectedTokens.push_back(tok::identifier);
@@ -357,6 +361,65 @@
   EXPECT_EQ("N", Lexer::getImmediateMacroName(idLoc4, SourceMgr, LangOpts));
 }
 
+TEST_F(LexerTest, HandlesSplitTokens) {
+  std::vector ExpectedTokens;
+  // Line 1 (after the #defines)
+  ExpectedTokens.push_back(tok::identifier);
+  ExpectedTokens.push_back(tok::less);
+  ExpectedTokens.push_back(tok::identifier);
+  ExpectedTokens.push_back(tok::less);
+  ExpectedTokens.push_back(tok::greatergreater);
+  // Line 2
+  ExpectedTokens.push_back(tok::identifier);
+  ExpectedTokens.push_back(tok::less);
+  ExpectedTokens.push_back(tok::identifier);
+  ExpectedTokens.push_back(tok::less);
+  ExpectedTokens.push_back(tok::greatergreater);
+
+  std::vector toks = CheckLex("#define TY ty\n"
+ "#define RANGLE ty>\n"
+ "TY>\n"
+ "RANGLE",
+ ExpectedTokens);
+
+  SourceLocation outerTyLoc = toks[0].getLocation();
+  SourceLocation innerTyLoc = toks[2].getLocation();
+  SourceLocation gtgtLoc = toks[4].getLocation();
+  // Split the token to simulate the action of the parser and force creation of
+  // an `ExpansionTokenRange`.
+  SourceLocation rangleLoc = PP->SplitToken(gtgtLoc, 1);
+
+  // Verify that it only captures the first greater-then and not the second one.
+  CharSourceRange range = Lexer::makeFileCharRange(
+  CharSourceRange::getTokenRange(innerTyLoc, rangleLoc), SourceMgr,
+  LangOpts);
+  EXPECT_TRUE(range.isCharRange());
+  EXPECT_EQ(range.getAsRange(),
+SourceRange(innerTyLoc, gtgtLoc.getLocWithOffset(1)));
+
+  // Verify case where range begins in a macro expansion.
+  range = Lexer::makeFileCharRange(
+  CharSourceRange::getTokenRange(outerTyLoc, rangleLoc), SourceMgr,
+  LangOpts);
+  EXPECT_TRUE(range.isCharRange());
+  EXPECT_EQ(range.getAsRange(),
+SourceRange(SourceMgr.getExpansionLoc(outerTyLoc),
+gtgtLoc.getLocWithOffset(1)));
+
+  SourceLocation macroInnerTyLoc = toks[7].getLocation();
+  SourceLocation macroGtgtLoc = toks[9].getLocation();
+  // Split the token to simulate the action of the parser and force creation of
+  // an `ExpansionTokenRange`.
+  SourceLocation macroRAngleLoc = PP->SplitToken(macroGtgtLoc, 1);
+
+  // Verify that it fails (because it only captures the first greater-then and
+  // not the second one, so it doesn't span the entire macro expansion).
+  range = Lexer::makeFileCharRange(
+  CharSourceRange::getTokenRange(macroInnerTyLoc, macroRAngleLoc),
+  SourceMgr, LangOpts);
+  EXPECT_TRUE(range.isInvalid());
+}
+
 TEST_F(LexerTest, DontMergeMacroArgsFromDifferentMacroFiles) {
   std::vector toks =
   Lex("#define helper1 0\n"
Index: clang/lib/Lex/Lexer.cpp
===
--- clang/lib/Lex/Lexer.cpp
+++ clang/lib/Lex/Lexer.cpp
@@ -877,6 +877,14 @@
   return CharSourceRange::getCharRange(Begin, End);
 }
 
+// Assumes that `Loc` is in an expansion.
+static bool isInExpansionTokenRange(const SourceLocation Loc,
+const SourceManager &SM) {
+  return SM.getSLocEntry(SM.getFileID(Loc))
+  .getExpansion()
+  .isExpansionTokenRange();
+}
+
 CharSourceRange Lexer::makeFileC

[PATCH] D105984: [PowerPC] Vec Div Builtins Restore FMF of Builder

2021-07-14 Thread Quinn Pham via Phabricator via cfe-commits
quinnp created this revision.
Herald added subscribers: shchenz, kbarton, nemanjai.
quinnp requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This patch fixes `__builtin_ppc_recipdivf`, `__builtin_ppc_recipdivd`,
`__builtin_ppc_rsqrtf`, and `__builtin_ppc_rsqrtd`. FastMathFlags are
set to fast immediately before emitting these builtins. Now the flags
are restored to their previous values after the builtins are emitted.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D105984

Files:
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/test/CodeGen/builtins-ppc-fastmath.c

Index: clang/test/CodeGen/builtins-ppc-fastmath.c
===
--- /dev/null
+++ clang/test/CodeGen/builtins-ppc-fastmath.c
@@ -0,0 +1,74 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+// RUN: %clang_cc1 -triple powerpc64-unknown-unknown \
+// RUN: -emit-llvm %s -o - -target-cpu pwr7 | FileCheck %s
+// RUN: %clang_cc1 -triple powerpc64le-unknown-unknown \
+// RUN: -emit-llvm %s -o - -target-cpu pwr8 | FileCheck %s
+// RUN: %clang_cc1 -triple powerpc64-unknown-aix \
+// RUN: -emit-llvm %s -o - -target-cpu pwr7 | FileCheck %s
+// RUN: %clang_cc1 -triple powerpc-unknown-aix \
+// RUN: -emit-llvm %s -o - -target-cpu pwr7 | FileCheck %s
+
+extern vector float a;
+extern vector float b;
+extern vector float c;
+extern vector double d;
+extern vector double e;
+extern vector double f;
+
+// CHECK-LABEL: @test_flags_recipdivf(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[TMP0:%.*]] = load <4 x float>, <4 x float>* @a, align 16
+// CHECK-NEXT:[[TMP1:%.*]] = load <4 x float>, <4 x float>* @b, align 16
+// CHECK-NEXT:[[TMP2:%.*]] = load <4 x float>, <4 x float>* @a, align 16
+// CHECK-NEXT:[[TMP3:%.*]] = load <4 x float>, <4 x float>* @b, align 16
+// CHECK-NEXT:[[RECIPDIV:%.*]] = fdiv fast <4 x float> [[TMP2]], [[TMP3]]
+// CHECK-NEXT:[[TMP4:%.*]] = load <4 x float>, <4 x float>* @c, align 16
+// CHECK-NEXT:[[ADD:%.*]] = fadd <4 x float> [[RECIPDIV]], [[TMP4]]
+// CHECK-NEXT:ret <4 x float> [[ADD]]
+//
+vector float test_flags_recipdivf() {
+  return __builtin_ppc_recipdivf(a, b) + c;
+}
+
+// CHECK-LABEL: @test_flags_recipdivd(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[TMP0:%.*]] = load <2 x double>, <2 x double>* @d, align 16
+// CHECK-NEXT:[[TMP1:%.*]] = load <2 x double>, <2 x double>* @e, align 16
+// CHECK-NEXT:[[TMP2:%.*]] = load <2 x double>, <2 x double>* @d, align 16
+// CHECK-NEXT:[[TMP3:%.*]] = load <2 x double>, <2 x double>* @e, align 16
+// CHECK-NEXT:[[RECIPDIV:%.*]] = fdiv fast <2 x double> [[TMP2]], [[TMP3]]
+// CHECK-NEXT:[[TMP4:%.*]] = load <2 x double>, <2 x double>* @f, align 16
+// CHECK-NEXT:[[ADD:%.*]] = fadd <2 x double> [[RECIPDIV]], [[TMP4]]
+// CHECK-NEXT:ret <2 x double> [[ADD]]
+//
+vector double test_flags_recipdivd() {
+  return __builtin_ppc_recipdivd(d, e) + f;
+}
+
+// CHECK-LABEL: @test_flags_rsqrtf(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[TMP0:%.*]] = load <4 x float>, <4 x float>* @a, align 16
+// CHECK-NEXT:[[TMP1:%.*]] = load <4 x float>, <4 x float>* @a, align 16
+// CHECK-NEXT:[[TMP2:%.*]] = call fast <4 x float> @llvm.sqrt.v4f32(<4 x float> [[TMP1]])
+// CHECK-NEXT:[[RSQRT:%.*]] = fdiv fast <4 x float> , [[TMP2]]
+// CHECK-NEXT:[[TMP3:%.*]] = load <4 x float>, <4 x float>* @b, align 16
+// CHECK-NEXT:[[ADD:%.*]] = fadd <4 x float> [[RSQRT]], [[TMP3]]
+// CHECK-NEXT:ret <4 x float> [[ADD]]
+//
+vector float test_flags_rsqrtf() {
+  return __builtin_ppc_rsqrtf(a) + b;
+}
+
+// CHECK-LABEL: @test_flags_rsqrtd(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[TMP0:%.*]] = load <2 x double>, <2 x double>* @d, align 16
+// CHECK-NEXT:[[TMP1:%.*]] = load <2 x double>, <2 x double>* @d, align 16
+// CHECK-NEXT:[[TMP2:%.*]] = call fast <2 x double> @llvm.sqrt.v2f64(<2 x double> [[TMP1]])
+// CHECK-NEXT:[[RSQRT:%.*]] = fdiv fast <2 x double> , [[TMP2]]
+// CHECK-NEXT:[[TMP3:%.*]] = load <2 x double>, <2 x double>* @e, align 16
+// CHECK-NEXT:[[ADD:%.*]] = fadd <2 x double> [[RSQRT]], [[TMP3]]
+// CHECK-NEXT:ret <2 x double> [[ADD]]
+//
+vector double test_flags_rsqrtd() {
+  return __builtin_ppc_rsqrtd(d) + e;
+}
Index: clang/lib/CodeGen/CGBuiltin.cpp
===
--- clang/lib/CodeGen/CGBuiltin.cpp
+++ clang/lib/CodeGen/CGBuiltin.cpp
@@ -15128,6 +15128,7 @@
   case PPC::BI__builtin_ppc_recipdivd:
   case PPC::BI__builtin_ppc_rsqrtf:
   case PPC::BI__builtin_ppc_rsqrtd: {
+FastMathFlags FMF = Builder.getFastMathFlags();
 Builder.getFastMathFlags().setFast();
 llvm::Type *ResultType = ConvertType(E->getType());
 Value *X = EmitScalarExpr(E->getArg(0));
@@ -15135,11 +15136,15 @@
 if (BuiltinID == PPC::BI__builtin_ppc_recipdivf ||
 BuiltinID == PPC::BI__builtin_ppc_recipdivd) {
  

[PATCH] D105492: [clang] Introduce SourceLocation::[U]IntType typedefs.

2021-07-14 Thread Tomas Matheson via Phabricator via cfe-commits
tmatheson added a comment.

LGTM




Comment at: clang/include/clang/Basic/SourceLocation.h:97
+  using UIntType = uint32_t;
+  using IntType = int32_t;
 

Nit: the `Ty` suffix seems to be slightly more common than `Type`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105492

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


[PATCH] D105493: [clang] Change set type used for SourceLocation.

2021-07-14 Thread Tomas Matheson via Phabricator via cfe-commits
tmatheson added a comment.

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105493

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


[PATCH] D104904: [OpenMP][AMDGCN] Initial math headers support

2021-07-14 Thread Jon Chesterfield via Phabricator via cfe-commits
JonChesterfield added a comment.

Only revision I'm looking for here is to land D105221 
 or equivalent first


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104904

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


[PATCH] D104742: [UpdateCCTestChecks] Implement --global-value-regex

2021-07-14 Thread Joel E. Denny via Phabricator via cfe-commits
jdenny added a comment.

Ping.


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

https://reviews.llvm.org/D104742

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


[PATCH] D105981: [AMDGPU][OpenMP] Support linking of math libraries

2021-07-14 Thread Jon Chesterfield via Phabricator via cfe-commits
JonChesterfield added inline comments.



Comment at: clang/lib/Driver/ToolChains/AMDGPUOpenMP.cpp:252
+bool Wave64 = isWave64(DriverArgs, Kind);
+
+// TODO: There are way too many flags that change this. Do we need to check

I recognise this comment. Is this a bunch of logic that can be moved into the 
base class and then called from here and hip?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105981

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


[PATCH] D105904: [clangd] Support `#pragma mark` in the outline

2021-07-14 Thread David Goldman via Phabricator via cfe-commits
dgoldman updated this revision to Diff 358606.
dgoldman added a comment.

Fix clang tidy warnings


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105904

Files:
  clang-tools-extra/clangd/CMakeLists.txt
  clang-tools-extra/clangd/FindSymbols.cpp
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/ParsedAST.h
  clang-tools-extra/clangd/Protocol.h
  clang-tools-extra/clangd/TextMarks.cpp
  clang-tools-extra/clangd/TextMarks.h
  clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp
  clang/include/clang/Lex/PPCallbacks.h

Index: clang/include/clang/Lex/PPCallbacks.h
===
--- clang/include/clang/Lex/PPCallbacks.h
+++ clang/include/clang/Lex/PPCallbacks.h
@@ -492,6 +492,11 @@
 Second->PragmaComment(Loc, Kind, Str);
   }
 
+  void PragmaMark(SourceLocation Loc, StringRef Trivia) override {
+First->PragmaMark(Loc, Trivia);
+Second->PragmaMark(Loc, Trivia);
+  }
+
   void PragmaDetectMismatch(SourceLocation Loc, StringRef Name,
 StringRef Value) override {
 First->PragmaDetectMismatch(Loc, Name, Value);
Index: clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp
===
--- clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp
+++ clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp
@@ -1027,6 +1027,106 @@
 AllOf(WithName("-pur"), WithKind(SymbolKind::Method));
 }
 
+TEST(DocumentSymbolsTest, PragmaMarkGroups) {
+  TestTU TU;
+  TU.ExtraArgs = {"-xobjective-c++", "-Wno-objc-root-class"};
+  Annotations Main(R"cpp(
+  $DogDef[[@interface Dog
+  @end]]
+
+  $DogImpl[[@implementation Dog
+
+  + (id)sharedDoggo { return 0; }
+
+  #pragma $Overrides[[mark - Overrides
+
+  - (id)init {
+return self;
+  }
+  - (void)bark {}]]
+
+  #pragma $Specifics[[mark - Dog Specifics
+
+  - (int)isAGoodBoy {
+return 1;
+  }]]
+  @]]end  // FIXME: Why doesn't this include the 'end'?
+
+  #pragma $End[[mark - End
+]]
+)cpp");
+  TU.Code = Main.code().str();
+  EXPECT_THAT(
+  getSymbols(TU.build()),
+  ElementsAre(
+  AllOf(WithName("Dog"), SymRange(Main.range("DogDef"))),
+  AllOf(WithName("Dog"), SymRange(Main.range("DogImpl")),
+Children(AllOf(WithName("+sharedDoggo"),
+   WithKind(SymbolKind::Method)),
+ AllOf(WithName("Overrides"),
+   SymRange(Main.range("Overrides")),
+   Children(AllOf(WithName("-init"),
+  WithKind(SymbolKind::Method)),
+AllOf(WithName("-bark"),
+  WithKind(SymbolKind::Method,
+ AllOf(WithName("Dog Specifics"),
+   SymRange(Main.range("Specifics")),
+   Children(AllOf(WithName("-isAGoodBoy"),
+  WithKind(SymbolKind::Method)),
+  AllOf(WithName("End"), SymRange(Main.range("End");
+}
+
+TEST(DocumentSymbolsTest, PragmaMarkGroupsNoNesting) {
+  TestTU TU;
+  TU.ExtraArgs = {"-xobjective-c++", "-Wno-objc-root-class"};
+  Annotations Main(R"cpp(
+  // FIXME: We miss the mark below, is it in the preamble instead?
+  // Unclear if it's worth supporting, likely very uncommon.
+  #pragma mark Helpers
+  void helpA(id obj) {}
+
+  #pragma mark -
+  #pragma mark Core
+
+  void coreMethod() {}
+)cpp");
+  TU.Code = Main.code().str();
+  EXPECT_THAT(
+  getSymbols(TU.build()),
+  ElementsAre(AllOf(WithName("helpA")), AllOf(WithName("(unnamed group)")),
+  AllOf(WithName("Core")), AllOf(WithName("coreMethod";
+}
+
+TEST(DocumentSymbolsTest, SymbolsAreSorted) {
+  TestTU TU;
+  TU.ExtraArgs = {"-xobjective-c++", "-Wno-objc-root-class"};
+  Annotations Main(R"cpp(
+  @interface MYObject
+  @end
+
+  void someFunctionAbove() {}
+
+  @implementation MYObject
+  - (id)init { return self; }
+
+  void someHelperFunction() {}
+
+  - (void)retain {}
+  - (void)release {}
+  @end
+)cpp");
+  TU.Code = Main.code().str();
+  EXPECT_THAT(getSymbols(TU.build()),
+  ElementsAre(AllOf(WithName("MYObject")),
+  AllOf(WithName("someFunctionAbove")),
+  // FIXME: This should be nested under MYObject below.
+  AllOf(WithName("someHelperFunction")),
+  AllOf(WithName("MYObject"),
+Children(AllOf(WithName("-init")),
+ AllOf(WithName("-retain")),
+ AllO

[PATCH] D105194: [PowerPC] Add PowerPC cmpb builtin and emit target indepedent code for XL compatibility

2021-07-14 Thread Victor Huang via Phabricator via cfe-commits
NeHuang added inline comments.



Comment at: clang/lib/CodeGen/CGBuiltin.cpp:15081
   }
+  case PPC::BI__builtin_ppc_cmpb: {
+llvm::Type *Ty = Ops[0]->getType();

nemanjai wrote:
> I find it rather surprising that we are emitting this complex sequence for 
> this builtin. Perhaps there is a good reason for doing so, but at the very 
> least, this requires a thorough explanation in a comment.
> 
> One additional concern I have with this is that if some transformation proves 
> that some portion of this is unused (perhaps using `DemandedBits` analysis), 
> it may optimize out a portion of this, thereby making the sequence emit a 
> whole bunch of xor's, or's, rotates, etc.
> 
> For example:
> ```
> ...
> unsigned long long A = __builtin_ppc_cmpb(B, C);
> return A & 0xFF00FF00FF00FF;
> ```
> It is entirely possible that the optimizer will get rid of some of the 
> produced instructions and then the back end won't be able to emit a single 
> `cmpb` but will have to emit a whole bunch of scalar instructions.
- The backend test case define i64 @test64(i64 %x, i64 %y) is in 
llvm/test/CodeGen/PowerPC/cmpb.ll
- Also Tried the test case and results look fine.
```
$ cat test_cmpb.c
long long test_cmpb(long long a, long long b) {
  //return __cmpb(a, b);
  unsigned long long A = __builtin_ppc_cmpb(a, b);
  return A & 0xFF00FF00FF00FF;
}
$ clang -cc1 -O3 -triple powerpc-unknown-aix test_cmpb.c -target-cpu pwr9 -S -o 
test_cmpb_32bit.s
...
.test_cmpb:
# %bb.0:# %entry
cmpb 4, 6, 4
lis 6, 255
cmpb 3, 5, 3
ori 6, 6, 255
and 4, 4, 6
and 3, 3, 6
blr
$ clang -cc1 -O3 -triple powerpc64-unknown-aix test_cmpb.c -target-cpu pwr9 -S 
-o test_cmpb_64bit.s
.test_cmpb:
# %bb.0:# %entry
cmpb 3, 4, 3
lis 4, 255
ori 4, 4, 255
rldimi 4, 4, 32, 0
and 3, 3, 4
blr
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105194

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


[PATCH] D88319: [AST] Delete broken, unused template.

2021-07-14 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel abandoned this revision.
ymandel added a comment.

Fixed in another commit.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88319

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


[PATCH] D105981: [AMDGPU][OpenMP] Support linking of math libraries

2021-07-14 Thread Pushpinder Singh via Phabricator via cfe-commits
pdhaliwal added inline comments.



Comment at: clang/lib/Driver/ToolChains/AMDGPUOpenMP.cpp:252
+bool Wave64 = isWave64(DriverArgs, Kind);
+
+// TODO: There are way too many flags that change this. Do we need to check

JonChesterfield wrote:
> I recognise this comment. Is this a bunch of logic that can be moved into the 
> base class and then called from here and hip?
This is copied (after removing stuff related to opencl) from 
https://github.com/llvm/llvm-project/blob/main/clang/lib/Driver/ToolChains/AMDGPU.cpp#L841
 
I wanted to make call to `ROCMToolChain::addClangTargetOptions`, but there is 
some extra logic in it which is irrelevant to OpenMP. I will move the library 
linking into a separate common method as you suggest.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105981

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


[PATCH] D105360: [PowerPC] Fix popcntb XL Compat Builtin for 32bit

2021-07-14 Thread Quinn Pham via Phabricator via cfe-commits
quinnp updated this revision to Diff 358609.
quinnp marked 9 inline comments as done.
quinnp added a comment.

Addressing review comment about indentation.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105360

Files:
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/test/CodeGen/builtins-ppc-xlcompat-sync.c
  llvm/include/llvm/IR/IntrinsicsPowerPC.td
  llvm/lib/Target/PowerPC/P9InstrResources.td
  llvm/lib/Target/PowerPC/PPCInstr64Bit.td
  llvm/lib/Target/PowerPC/PPCInstrInfo.td
  llvm/test/CodeGen/PowerPC/builtins-ppc-xlcompat-msync.ll
  llvm/test/CodeGen/PowerPC/builtins-ppc-xlcompat-sync-32.ll
  llvm/test/CodeGen/PowerPC/builtins-ppc-xlcompat-sync-64.ll
  llvm/test/CodeGen/PowerPC/builtins-ppc-xlcompat-sync.ll

Index: llvm/test/CodeGen/PowerPC/builtins-ppc-xlcompat-sync.ll
===
--- llvm/test/CodeGen/PowerPC/builtins-ppc-xlcompat-sync.ll
+++ /dev/null
@@ -1,74 +0,0 @@
-; RUN: llc -verify-machineinstrs -mtriple=powerpcle-unknown-linux-gnu \
-; RUN: -mcpu=pwr8 < %s | FileCheck %s
-; RUN: llc -verify-machineinstrs -mtriple=powerpc-unknown-linux-gnu \
-; RUN: -mcpu=pwr8 < %s | FileCheck %s
-; RUN: llc -verify-machineinstrs -mtriple=powerpc64le-unknown-linux-gnu \
-; RUN: -mcpu=pwr8 < %s | FileCheck %s
-; RUN: llc -verify-machineinstrs -mtriple=powerpc64-unknown-linux-gnu \
-; RUN: -mcpu=pwr8 < %s | FileCheck %s
-
-define dso_local void @test_builtin_ppc_eieio() #0 {
-; CHECK-LABEL: test_builtin_ppc_eieio
-
-entry:
-  call void @llvm.ppc.eieio()
-; CHECK: ori 2, 2, 0
-; CHECK-NEXT: ori 2, 2, 0
-; CHECK-NEXT: eieio
- 
-  ret void
-}
-
-declare void @llvm.ppc.eieio() #2
-
-define dso_local void @test_builtin_ppc_iospace_eieio() #0 {
-; CHECK-LABEL: test_builtin_ppc_iospace_eieio
-
-entry:
-  call void @llvm.ppc.iospace.eieio()
-; CHECK: ori 2, 2, 0
-; CHECK-NEXT: ori 2, 2, 0
-; CHECK-NEXT: eieio
- 
-  ret void
-}
-
-declare void @llvm.ppc.iospace.eieio() #2
-
-define dso_local void @test_builtin_ppc_iospace_lwsync() #0 {
-; CHECK-LABEL: test_builtin_ppc_iospace_lwsync
-
-entry:
-  call void @llvm.ppc.iospace.lwsync()
-; CHECK: lwsync
-
-  ret void
-}
-
-declare void @llvm.ppc.iospace.lwsync() #2
-
-define dso_local void @test_builtin_ppc_iospace_sync() #0 {
-; CHECK-LABEL: test_builtin_ppc_iospace_sync
-
-entry:
-  call void @llvm.ppc.iospace.sync()
-; CHECK: sync
-
-  ret void
-}
-
-declare void @llvm.ppc.iospace.sync() #2
-
-define dso_local void @test_builtin_ppc_icbt() #0 {
-; CHECK-LABEL: test_builtin_ppc_icbt
-
-entry:
-  %a = alloca i8*, align 8
-  %0 = load i8*, i8** %a, align 8
-  call void @llvm.ppc.icbt(i8* %0)
-; CHECK: icbt 0, 0, 3
-
-  ret void
-}
-
-declare void @llvm.ppc.icbt(i8*) #2
Index: llvm/test/CodeGen/PowerPC/builtins-ppc-xlcompat-sync-64.ll
===
--- /dev/null
+++ llvm/test/CodeGen/PowerPC/builtins-ppc-xlcompat-sync-64.ll
@@ -0,0 +1,116 @@
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
+; RUN: llc -verify-machineinstrs -mtriple=powerpc64-unknown-unknown \
+; RUN:   --ppc-asm-full-reg-names -mcpu=pwr7 < %s | FileCheck %s
+; RUN: llc -verify-machineinstrs -mtriple=powerpc64le-unknown-unknown \
+; RUN:   --ppc-asm-full-reg-names -mcpu=pwr8 < %s | FileCheck %s
+; RUN: llc -verify-machineinstrs -mtriple=powerpc64-unknown-aix \
+; RUN:   --ppc-asm-full-reg-names -mcpu=pwr7 < %s | FileCheck %s --check-prefix=CHECK-AIX
+
+define dso_local i64 @test_builtin_ppc_popcntb_i64(i64 %a) local_unnamed_addr {
+; CHECK-LABEL: test_builtin_ppc_popcntb_i64:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:popcntb r3, r3
+; CHECK-NEXT:blr
+;
+; CHECK-AIX-LABEL: test_builtin_ppc_popcntb_i64:
+; CHECK-AIX:   # %bb.0: # %entry
+; CHECK-AIX-NEXT:popcntb 3, 3
+; CHECK-AIX-NEXT:blr
+entry:
+  %popcntb = tail call i64 @llvm.ppc.popcntb.i64.i64(i64 %a)
+  ret i64 %popcntb
+}
+declare i64 @llvm.ppc.popcntb.i64.i64(i64)
+
+define dso_local void @test_builtin_ppc_eieio() {
+; CHECK-LABEL: test_builtin_ppc_eieio:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:ori r2, r2, 0
+; CHECK-NEXT:ori r2, r2, 0
+; CHECK-NEXT:eieio
+; CHECK-NEXT:blr
+;
+; CHECK-AIX-LABEL: test_builtin_ppc_eieio:
+; CHECK-AIX:   # %bb.0: # %entry
+; CHECK-AIX-NEXT:ori 2, 2, 0
+; CHECK-AIX-NEXT:ori 2, 2, 0
+; CHECK-AIX-NEXT:eieio
+; CHECK-AIX-NEXT:blr
+entry:
+  call void @llvm.ppc.eieio()
+  ret void
+}
+declare void @llvm.ppc.eieio()
+
+define dso_local void @test_builtin_ppc_iospace_eieio() {
+; CHECK-LABEL: test_builtin_ppc_iospace_eieio:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:ori r2, r2, 0
+; CHECK-NEXT:ori r2, r2, 0
+; CHECK-NEXT:eieio
+; CHECK-NEXT:blr
+;
+; CHECK-AIX-LABEL: test_builtin_ppc_iospace_eieio:
+; CHECK-AIX:   # %bb.0: # %entry
+; CHECK-AIX-NEXT:ori 2, 2, 0
+; CHECK-AIX-NEXT:ori 2, 2, 0
+; CHECK-AIX-NEXT:   

[PATCH] D104917: [Analyzer] Extend exploded-graph-rewriter to support eq and diseq classes

2021-07-14 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

In D104917#2860923 , @NoQ wrote:

> WDYT about the following format:
>
>   Equality constraints:
>   reg_$0 == reg_$1
> == reg_$2
>   
>   Disequality constraints:
>   reg_$0 != reg_$3,
> != reg_$4
>
> Comma is a bit hard to notice but otherwise kinda nicely readable?

IMHO this format would be confusing if you have two SVals that include 
comparison operators:
E.g. SVal1 `(reg_$1) == (reg_$2)` and SVal2 `(reg_$0) != 
42`. They might be in the same equivalence class, that would result this format:

  Equality constraints:
  (reg_$1) == (reg_$2) == (reg_$0) != 42

Well, ... I know the current table with the borders looks a bit rough and ugly, 
but I think the information is displayed in an obvious way and can be 
interpreted unambiguously.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104917

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


[PATCH] D105987: [C++4OpenCL] NULL redefined as nullptr

2021-07-14 Thread Justas Janickas via Phabricator via cfe-commits
Topotuna created this revision.
Herald added subscribers: ldrumm, Anastasia, yaxunl.
Topotuna requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Redefines NULL as nullptr instead of ((void*)0) in C++ for OpenCL.

Such internal representation of NULL provides compatibility with
C++11 and later language standards.

Fixes llvm.org/PR48098


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D105987

Files:
  clang/lib/Headers/opencl-c-base.h
  clang/test/SemaOpenCL/null_literal.cl


Index: clang/test/SemaOpenCL/null_literal.cl
===
--- clang/test/SemaOpenCL/null_literal.cl
+++ clang/test/SemaOpenCL/null_literal.cl
@@ -1,31 +1,48 @@
-// RUN: %clang_cc1 -verify %s
-// RUN: %clang_cc1 -cl-std=CL1.0 -verify %s
-// RUN: %clang_cc1 -cl-std=CL1.1 -verify %s
-// RUN: %clang_cc1 -cl-std=CL1.2 -verify %s
-// RUN: %clang_cc1 -cl-std=CL2.0 -DCL20 -verify %s
-
-#define NULL ((void*)0)
+// RUN: %clang_cc1 -fdeclare-opencl-builtins -finclude-default-header -verify 
%s
+// RUN: %clang_cc1 -cl-std=CL1.0 -fdeclare-opencl-builtins 
-finclude-default-header -verify %s
+// RUN: %clang_cc1 -cl-std=CL1.1 -fdeclare-opencl-builtins 
-finclude-default-header -verify %s
+// RUN: %clang_cc1 -cl-std=CL1.2 -fdeclare-opencl-builtins 
-finclude-default-header -verify %s
+// RUN: %clang_cc1 -cl-std=CL2.0 -DCL20 -fdeclare-opencl-builtins 
-finclude-default-header -verify %s
+// RUN: %clang_cc1 -cl-std=clc++ -fdeclare-opencl-builtins 
-finclude-default-header -verify %s
 
 void foo(){
 
 global int* ptr1 = NULL;
 
+#if defined(__OPENCL_CPP_VERSION__)
+// expected-error@+2{{cannot initialize a variable of type '__global int 
*__private' with an rvalue of type '__global void *'}}
+#endif
 global int* ptr2 = (global void*)0;
 
 constant int* ptr3 = NULL;
 
-constant int* ptr4 = (global void*)0; // expected-error{{initializing 
'__constant int *__private' with an expression of type '__global void *' 
changes address space of pointer}}
+#if defined(__OPENCL_CPP_VERSION__)
+// expected-error@+4{{cannot initialize a variable of type '__constant int 
*__private' with an rvalue of type '__global void *'}}
+#else
+// expected-error@+2{{initializing '__constant int *__private' with an 
expression of type '__global void *' changes address space of pointer}}
+#endif
+constant int* ptr4 = (global void*)0;
 
 #ifdef CL20
 // Accept explicitly pointer to generic address space in OpenCL v2.0.
 global int* ptr5 = (generic void*)0;
 #endif
 
-global int* ptr6 = (local void*)0; // expected-error{{initializing '__global 
int *__private' with an expression of type '__local void *' changes address 
space of pointer}}
+#if defined(__OPENCL_CPP_VERSION__)
+// expected-error@+4{{cannot initialize a variable of type '__global int 
*__private' with an rvalue of type '__local void *'}}
+#else
+// expected-error@+2{{initializing '__global int *__private' with an 
expression of type '__local void *' changes address space of pointer}}
+#endif
+global int* ptr6 = (local void*)0;
 
 bool cmp = ptr1 == NULL;
 
-cmp = ptr1 == (local void*)0; // expected-error{{comparison between  
('__global int *' and '__local void *') which are pointers to non-overlapping 
address spaces}}
+#if defined(__OPENCL_CPP_VERSION__)
+// expected-error@+4{{comparison of distinct pointer types ('__global int *' 
and '__local void *')}}
+#else
+// expected-error@+2{{comparison between  ('__global int *' and '__local void 
*') which are pointers to non-overlapping address spaces}}
+#endif
+cmp = ptr1 == (local void*)0;
 
 cmp = ptr3 == NULL;
 
Index: clang/lib/Headers/opencl-c-base.h
===
--- clang/lib/Headers/opencl-c-base.h
+++ clang/lib/Headers/opencl-c-base.h
@@ -164,7 +164,9 @@
 typedef double double16 __attribute__((ext_vector_type(16)));
 #endif
 
-#if defined(__OPENCL_CPP_VERSION__) || defined(__OPENCL_C_VERSION__)
+#if defined(__OPENCL_CPP_VERSION__)
+#define NULL nullptr
+#elif defined(__OPENCL_C_VERSION__)
 #define NULL ((void*)0)
 #endif
 


Index: clang/test/SemaOpenCL/null_literal.cl
===
--- clang/test/SemaOpenCL/null_literal.cl
+++ clang/test/SemaOpenCL/null_literal.cl
@@ -1,31 +1,48 @@
-// RUN: %clang_cc1 -verify %s
-// RUN: %clang_cc1 -cl-std=CL1.0 -verify %s
-// RUN: %clang_cc1 -cl-std=CL1.1 -verify %s
-// RUN: %clang_cc1 -cl-std=CL1.2 -verify %s
-// RUN: %clang_cc1 -cl-std=CL2.0 -DCL20 -verify %s
-
-#define NULL ((void*)0)
+// RUN: %clang_cc1 -fdeclare-opencl-builtins -finclude-default-header -verify %s
+// RUN: %clang_cc1 -cl-std=CL1.0 -fdeclare-opencl-builtins -finclude-default-header -verify %s
+// RUN: %clang_cc1 -cl-std=CL1.1 -fdeclare-opencl-builtins -finclude-default-header -verify %s
+// RUN: %clang_cc1 -cl-std=CL1.2 -fdeclare-opencl-builtins -finclude-default-header -verify %s
+// RUN: %clang_cc1 -cl-std=CL2.0 -DCL20 -fdec

[PATCH] D105988: [OpenCL] NULL introduced prior to v2.0

2021-07-14 Thread Justas Janickas via Phabricator via cfe-commits
Topotuna created this revision.
Herald added subscribers: ldrumm, Anastasia, yaxunl.
Topotuna requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

NULL macro maps to ((void*)0) for OpenCL versions earlier than 2.0

NULL was undefined in OpenCL prior to version 2.0. However, the
language specification states that `macro names defined by the C99
specification but not currently supported by OpenCL are reserved
for future use`. Therefore, application developers cannot redefine
NULL.

The change is supposed to resolve inconsistency between language
versions. Currently there is no apparent reason why NULL should
be kept undefined.

Fixes llvm.org/PR48102


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D105988

Files:
  clang/lib/Headers/opencl-c-base.h
  clang/test/SemaOpenCL/null_literal.cl


Index: clang/test/SemaOpenCL/null_literal.cl
===
--- clang/test/SemaOpenCL/null_literal.cl
+++ clang/test/SemaOpenCL/null_literal.cl
@@ -1,4 +1,7 @@
 // RUN: %clang_cc1 -verify %s
+// RUN: %clang_cc1 -cl-std=CL1.0 -verify %s
+// RUN: %clang_cc1 -cl-std=CL1.1 -verify %s
+// RUN: %clang_cc1 -cl-std=CL1.2 -verify %s
 // RUN: %clang_cc1 -cl-std=CL2.0 -DCL20 -verify %s
 
 #define NULL ((void*)0)
Index: clang/lib/Headers/opencl-c-base.h
===
--- clang/lib/Headers/opencl-c-base.h
+++ clang/lib/Headers/opencl-c-base.h
@@ -164,7 +164,7 @@
 typedef double double16 __attribute__((ext_vector_type(16)));
 #endif
 
-#if defined(__OPENCL_CPP_VERSION__) || (__OPENCL_C_VERSION__ >= CL_VERSION_2_0)
+#if defined(__OPENCL_CPP_VERSION__) || defined(__OPENCL_C_VERSION__)
 #define NULL ((void*)0)
 #endif
 


Index: clang/test/SemaOpenCL/null_literal.cl
===
--- clang/test/SemaOpenCL/null_literal.cl
+++ clang/test/SemaOpenCL/null_literal.cl
@@ -1,4 +1,7 @@
 // RUN: %clang_cc1 -verify %s
+// RUN: %clang_cc1 -cl-std=CL1.0 -verify %s
+// RUN: %clang_cc1 -cl-std=CL1.1 -verify %s
+// RUN: %clang_cc1 -cl-std=CL1.2 -verify %s
 // RUN: %clang_cc1 -cl-std=CL2.0 -DCL20 -verify %s
 
 #define NULL ((void*)0)
Index: clang/lib/Headers/opencl-c-base.h
===
--- clang/lib/Headers/opencl-c-base.h
+++ clang/lib/Headers/opencl-c-base.h
@@ -164,7 +164,7 @@
 typedef double double16 __attribute__((ext_vector_type(16)));
 #endif
 
-#if defined(__OPENCL_CPP_VERSION__) || (__OPENCL_C_VERSION__ >= CL_VERSION_2_0)
+#if defined(__OPENCL_CPP_VERSION__) || defined(__OPENCL_C_VERSION__)
 #define NULL ((void*)0)
 #endif
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D105984: [PowerPC] Restore FastMathFlags of Builder for Vector FDiv Builtins

2021-07-14 Thread Quinn Pham via Phabricator via cfe-commits
quinnp updated this revision to Diff 358613.
quinnp retitled this revision from "[PowerPC] Restore FastMathFlags of Builder 
for Vector FDiv Builtins " to "[PowerPC] Restore FastMathFlags of Builder for 
Vector FDiv Builtins".
quinnp added a comment.

Fixing indentation.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105984

Files:
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/test/CodeGen/builtins-ppc-fastmath.c

Index: clang/test/CodeGen/builtins-ppc-fastmath.c
===
--- /dev/null
+++ clang/test/CodeGen/builtins-ppc-fastmath.c
@@ -0,0 +1,74 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+// RUN: %clang_cc1 -triple powerpc64-unknown-unknown \
+// RUN:   -emit-llvm %s -o - -target-cpu pwr7 | FileCheck %s
+// RUN: %clang_cc1 -triple powerpc64le-unknown-unknown \
+// RUN:   -emit-llvm %s -o - -target-cpu pwr8 | FileCheck %s
+// RUN: %clang_cc1 -triple powerpc64-unknown-aix \
+// RUN:   -emit-llvm %s -o - -target-cpu pwr7 | FileCheck %s
+// RUN: %clang_cc1 -triple powerpc-unknown-aix \
+// RUN:   -emit-llvm %s -o - -target-cpu pwr7 | FileCheck %s
+
+extern vector float a;
+extern vector float b;
+extern vector float c;
+extern vector double d;
+extern vector double e;
+extern vector double f;
+
+// CHECK-LABEL: @test_flags_recipdivf(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[TMP0:%.*]] = load <4 x float>, <4 x float>* @a, align 16
+// CHECK-NEXT:[[TMP1:%.*]] = load <4 x float>, <4 x float>* @b, align 16
+// CHECK-NEXT:[[TMP2:%.*]] = load <4 x float>, <4 x float>* @a, align 16
+// CHECK-NEXT:[[TMP3:%.*]] = load <4 x float>, <4 x float>* @b, align 16
+// CHECK-NEXT:[[RECIPDIV:%.*]] = fdiv fast <4 x float> [[TMP2]], [[TMP3]]
+// CHECK-NEXT:[[TMP4:%.*]] = load <4 x float>, <4 x float>* @c, align 16
+// CHECK-NEXT:[[ADD:%.*]] = fadd <4 x float> [[RECIPDIV]], [[TMP4]]
+// CHECK-NEXT:ret <4 x float> [[ADD]]
+//
+vector float test_flags_recipdivf() {
+  return __builtin_ppc_recipdivf(a, b) + c;
+}
+
+// CHECK-LABEL: @test_flags_recipdivd(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[TMP0:%.*]] = load <2 x double>, <2 x double>* @d, align 16
+// CHECK-NEXT:[[TMP1:%.*]] = load <2 x double>, <2 x double>* @e, align 16
+// CHECK-NEXT:[[TMP2:%.*]] = load <2 x double>, <2 x double>* @d, align 16
+// CHECK-NEXT:[[TMP3:%.*]] = load <2 x double>, <2 x double>* @e, align 16
+// CHECK-NEXT:[[RECIPDIV:%.*]] = fdiv fast <2 x double> [[TMP2]], [[TMP3]]
+// CHECK-NEXT:[[TMP4:%.*]] = load <2 x double>, <2 x double>* @f, align 16
+// CHECK-NEXT:[[ADD:%.*]] = fadd <2 x double> [[RECIPDIV]], [[TMP4]]
+// CHECK-NEXT:ret <2 x double> [[ADD]]
+//
+vector double test_flags_recipdivd() {
+  return __builtin_ppc_recipdivd(d, e) + f;
+}
+
+// CHECK-LABEL: @test_flags_rsqrtf(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[TMP0:%.*]] = load <4 x float>, <4 x float>* @a, align 16
+// CHECK-NEXT:[[TMP1:%.*]] = load <4 x float>, <4 x float>* @a, align 16
+// CHECK-NEXT:[[TMP2:%.*]] = call fast <4 x float> @llvm.sqrt.v4f32(<4 x float> [[TMP1]])
+// CHECK-NEXT:[[RSQRT:%.*]] = fdiv fast <4 x float> , [[TMP2]]
+// CHECK-NEXT:[[TMP3:%.*]] = load <4 x float>, <4 x float>* @b, align 16
+// CHECK-NEXT:[[ADD:%.*]] = fadd <4 x float> [[RSQRT]], [[TMP3]]
+// CHECK-NEXT:ret <4 x float> [[ADD]]
+//
+vector float test_flags_rsqrtf() {
+  return __builtin_ppc_rsqrtf(a) + b;
+}
+
+// CHECK-LABEL: @test_flags_rsqrtd(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[TMP0:%.*]] = load <2 x double>, <2 x double>* @d, align 16
+// CHECK-NEXT:[[TMP1:%.*]] = load <2 x double>, <2 x double>* @d, align 16
+// CHECK-NEXT:[[TMP2:%.*]] = call fast <2 x double> @llvm.sqrt.v2f64(<2 x double> [[TMP1]])
+// CHECK-NEXT:[[RSQRT:%.*]] = fdiv fast <2 x double> , [[TMP2]]
+// CHECK-NEXT:[[TMP3:%.*]] = load <2 x double>, <2 x double>* @e, align 16
+// CHECK-NEXT:[[ADD:%.*]] = fadd <2 x double> [[RSQRT]], [[TMP3]]
+// CHECK-NEXT:ret <2 x double> [[ADD]]
+//
+vector double test_flags_rsqrtd() {
+  return __builtin_ppc_rsqrtd(d) + e;
+}
Index: clang/lib/CodeGen/CGBuiltin.cpp
===
--- clang/lib/CodeGen/CGBuiltin.cpp
+++ clang/lib/CodeGen/CGBuiltin.cpp
@@ -15128,6 +15128,7 @@
   case PPC::BI__builtin_ppc_recipdivd:
   case PPC::BI__builtin_ppc_rsqrtf:
   case PPC::BI__builtin_ppc_rsqrtd: {
+FastMathFlags FMF = Builder.getFastMathFlags();
 Builder.getFastMathFlags().setFast();
 llvm::Type *ResultType = ConvertType(E->getType());
 Value *X = EmitScalarExpr(E->getArg(0));
@@ -15135,11 +15136,15 @@
 if (BuiltinID == PPC::BI__builtin_ppc_recipdivf ||
 BuiltinID == PPC::BI__builtin_ppc_recipdivd) {
   Value *Y = EmitScalarExpr(E->getArg(1));
-  return Builder.CreateFDiv(X, Y, "recipdiv");
+  Value *fdiv = Builder.Creat

[PATCH] D105981: [AMDGPU][OpenMP] Support linking of math libraries

2021-07-14 Thread Pushpinder Singh via Phabricator via cfe-commits
pdhaliwal updated this revision to Diff 358614.
pdhaliwal added a comment.

Move linking logic to a common method.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105981

Files:
  clang/lib/Driver/ToolChains/AMDGPU.cpp
  clang/lib/Driver/ToolChains/AMDGPU.h
  clang/lib/Driver/ToolChains/AMDGPUOpenMP.cpp
  clang/test/Driver/amdgpu-openmp-toolchain.c

Index: clang/test/Driver/amdgpu-openmp-toolchain.c
===
--- clang/test/Driver/amdgpu-openmp-toolchain.c
+++ clang/test/Driver/amdgpu-openmp-toolchain.c
@@ -74,3 +74,6 @@
 
 // RUN:   %clang -### --target=x86_64-unknown-linux-gnu -emit-llvm -S -fopenmp -fopenmp-targets=amdgcn-amd-amdhsa -Xopenmp-target=amdgcn-amd-amdhsa -march=gfx803 -nogpulib %s 2>&1 | FileCheck %s --check-prefix=CHECK-EMIT-LLVM-IR
 // CHECK-EMIT-LLVM-IR: clang{{.*}}"-cc1"{{.*}}"-triple" "amdgcn-amd-amdhsa"{{.*}}"-emit-llvm"
+
+// RUN: env LIBRARY_PATH=%S/Inputs/hip_dev_lib %clang -### -target x86_64-pc-linux-gnu -fopenmp -fopenmp-targets=amdgcn-amd-amdhsa -Xopenmp-target=amdgcn-amd-amdhsa -march=gfx803 -lm --rocm-device-lib-path=%S/Inputs/rocm/amdgcn/bitcode %s 2>&1 | FileCheck %s --check-prefix=CHECK-LIB-DEVICE
+// CHECK-LIB-DEVICE: clang{{.*}}"-cc1"{{.*}}"-triple" "amdgcn-amd-amdhsa"{{.*}}"-mlink-builtin-bitcode"{{.*}}libomptarget-amdgcn-gfx803.bc"{{.*}}"-mlink-builtin-bitcode"{{.*}}ocml.bc" "-mlink-builtin-bitcode"{{.*}}ockl.bc" "-mlink-builtin-bitcode"{{.*}}oclc_daz_opt_on.bc" "-mlink-builtin-bitcode"{{.*}}oclc_unsafe_math_off.bc" "-mlink-builtin-bitcode"{{.*}}oclc_finite_only_off.bc" "-mlink-builtin-bitcode"{{.*}}oclc_correctly_rounded_sqrt_off.bc" "-mlink-builtin-bitcode"{{.*}}oclc_wavefrontsize64_on.bc" "-mlink-builtin-bitcode"{{.*}}oclc_isa_version_803.bc"
Index: clang/lib/Driver/ToolChains/AMDGPUOpenMP.cpp
===
--- clang/lib/Driver/ToolChains/AMDGPUOpenMP.cpp
+++ clang/lib/Driver/ToolChains/AMDGPUOpenMP.cpp
@@ -10,6 +10,7 @@
 #include "AMDGPU.h"
 #include "CommonArgs.h"
 #include "InputInfo.h"
+#include "ToolChains/ROCm.h"
 #include "clang/Basic/DiagnosticDriver.h"
 #include "clang/Driver/Compilation.h"
 #include "clang/Driver/Driver.h"
@@ -225,6 +226,22 @@
   std::string BitcodeSuffix = "amdgcn-" + GPUArch;
   addOpenMPDeviceRTL(getDriver(), DriverArgs, CC1Args, BitcodeSuffix,
  getTriple());
+
+  if (!DriverArgs.hasArg(options::OPT_l))
+return;
+
+  auto Lm = DriverArgs.getAllArgValues(options::OPT_l);
+  bool HasLibm = false;
+  for (auto &Lib : Lm) {
+if (Lib == "m") {
+  HasLibm = true;
+  break;
+}
+  }
+
+  if (HasLibm) {
+ROCMToolChain::addDeviceLibOptions(DriverArgs, CC1Args, GPUArch);
+  }
 }
 
 llvm::opt::DerivedArgList *AMDGPUOpenMPToolChain::TranslateArgs(
Index: clang/lib/Driver/ToolChains/AMDGPU.h
===
--- clang/lib/Driver/ToolChains/AMDGPU.h
+++ clang/lib/Driver/ToolChains/AMDGPU.h
@@ -136,6 +136,10 @@
   addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
 llvm::opt::ArgStringList &CC1Args,
 Action::OffloadKind DeviceOffloadKind) const override;
+
+  void addDeviceLibOptions(const llvm::opt::ArgList &DriverArgs,
+   llvm::opt::ArgStringList &CC1Args,
+   const std::string &GPUArch) const;
 };
 
 } // end namespace toolchains
Index: clang/lib/Driver/ToolChains/AMDGPU.cpp
===
--- clang/lib/Driver/ToolChains/AMDGPU.cpp
+++ clang/lib/Driver/ToolChains/AMDGPU.cpp
@@ -826,43 +826,12 @@
 return;
   }
 
-  // Get the device name and canonicalize it
+  // Get the device name
   const StringRef GpuArch = getGPUArch(DriverArgs);
-  auto Kind = llvm::AMDGPU::parseArchAMDGCN(GpuArch);
-  const StringRef CanonArch = llvm::AMDGPU::getArchNameAMDGCN(Kind);
-  std::string LibDeviceFile = RocmInstallation.getLibDeviceFile(CanonArch);
-  if (LibDeviceFile.empty()) {
-getDriver().Diag(diag::err_drv_no_rocm_device_lib) << 1 << GpuArch;
-return;
-  }
-
-  bool Wave64 = isWave64(DriverArgs, Kind);
-
-  // TODO: There are way too many flags that change this. Do we need to check
-  // them all?
-  bool DAZ = DriverArgs.hasArg(options::OPT_cl_denorms_are_zero) ||
- getDefaultDenormsAreZeroForTarget(Kind);
-  bool FiniteOnly = DriverArgs.hasArg(options::OPT_cl_finite_math_only);
-
-  bool UnsafeMathOpt =
-  DriverArgs.hasArg(options::OPT_cl_unsafe_math_optimizations);
-  bool FastRelaxedMath = DriverArgs.hasArg(options::OPT_cl_fast_relaxed_math);
-  bool CorrectSqrt =
-  DriverArgs.hasArg(options::OPT_cl_fp32_correctly_rounded_divide_sqrt);
-
-  // Add the OpenCL specific bitcode library.
-  llvm::SmallVector BCLibs;
-  BCLibs.push_back(RocmInstallation.getOpenCLPath().str());
-
-  // 

[PATCH] D105988: [OpenCL] NULL introduced prior to v2.0

2021-07-14 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added a comment.

This seems reasonable.




Comment at: clang/test/SemaOpenCL/null_literal.cl:7
 
 #define NULL ((void*)0)
 

I think we should remove this `NULL` definition but instead add 
`-finclude-default-header -fdeclare-opencl-builtins` to test the definition you 
are adding in the header.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105988

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


[PATCH] D105904: [clangd] Support `#pragma mark` in the outline

2021-07-14 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added a comment.

So first of all, it is not clear to me if this is a useful enough improvement 
to justify all the new code, but looking at your investment I'll assume this is 
really common in ObjC land and gonna be useful for developers working with 
ObjC. That's enough of a justification for me, but I'd be more than happy to 
see some real data if you have any.

That being said, reading the code it seems like the intent is enabling `#pragma 
mark` directives the introduce symbols that are either leaves or containers:

- Leaf case is obvious and straightforward, it is just like a normal 
declaration happening at that particular location. It is unclear which kind 
should be used. It seems you've went with `File` but I don't think it is 
suitable in this case. I would suggest using `Null`.
- Container case is more sophisticated. One thing is for sure, they are nested 
under the same symbol a declaration occuring at that point would be. They also 
seem to contain all the symbols that would nest under current subtree and 
spelled after the mark and spelled before any other marks. Hence there is no 
way to explicitly terminate the scope of a mark. They are implicitly terminated 
by hitting the end of the container containing the mark or hitting a new mark 
directive. This also implies one cannot have multiple levels of nesting just by 
pragma directives, but it can be achieved if there are usual containers with 
more mark directives (see my comment around tests for an example).

Can you verify that I understood the intent correctly and make it more explicit 
in the comments as well?

(Terminating containers implicitly sounds like an unfortunate limitation to me. 
I'd rather only enable termination of them explicitly) but I suppose there's a 
lot of code that's already existing out in the world with the assumption of 
XCode's implicit termination rules, so this is probably not gonna be helpful in 
reality. Hence we can't do much.)

Before diving into the details of the implementation it looks like we are doing 
some post-processing to incorporate mark pragmas into the tree, why can't we 
just insert them while building the tree as we do with macros? for example:

- when inserting a symbol we look for a possible mark-pragma container (similar 
to macro case), a mark pragma is only eligible as a container if it is 
contained within the range of the parent && spelled before current declaration 
at hand && is a group.
- as for insertion of leaves, after traversal of all the children we can just 
add any mark pragmas that occured within the current symbol's range as a child. 
we can also drop any mark pragmas occuring inside symbols that doesn't require 
child traversal this way.

This approach relies on the fact that `range` calculated by `declToSym` will be 
correct enough. I think it should be good in most cases, but might require some 
adjustments around macros, as usual (can't think of a problematic example right 
now though).
This brings out the question about ordering of `children` in `DocumentSymbol`, 
lsp doesn't say anything about it today, but during rendering we can just order 
these based on the `selectionRange` (probably during `build`) and hope that 
clients will preserve it.

I believe implementing it as part of the traversal rather than as post 
processing both makes code easier to reason about and more efficient. So WDYT 
about going in that direction?




Comment at: clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp:1053
+  }]]
+  @]]end  // FIXME: Why doesn't this include the 'end'?
+

probably a little mix of token vs char ranges.



Comment at: clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp:1055
+
+  #pragma $End[[mark - End
+]]

can you also add something like:

```
#pragma mark - Foo
struct Foo {
  #pragma mark - Bar
  void bar() {
 #pragma mark - NotTopDecl // I don't think we want this to be part of 
documentsymbol.
  }
};
void bar() {}
```



Comment at: clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp:1122
+  AllOf(WithName("someFunctionAbove")),
+  // FIXME: This should be nested under MYObject below.
+  AllOf(WithName("someHelperFunction")),

yikes, this looks bad, but also a little bit confusing to be added with this 
change. Can you move it to a separate one? (or just create a bug report in 
github/clangd/clangd).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105904

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


[PATCH] D105981: [AMDGPU][OpenMP] Support linking of math libraries

2021-07-14 Thread Jon Chesterfield via Phabricator via cfe-commits
JonChesterfield added a reviewer: t-tye.
JonChesterfield added inline comments.



Comment at: clang/lib/Driver/ToolChains/AMDGPUOpenMP.cpp:267
+llvm::SmallVector BCLibs;
+BCLibs.append(RocmInstallation.getCommonBitcodeLibs(
+DriverArgs, LibDeviceFile, Wave64, DAZ, FiniteOnly, UnsafeMathOpt,

Gone searching. This stuff has already been copied & pasted between AMDGPU.cpp 
and HIP.cpp. And diverged, looks like HIP has gained a bunch of inverse flags 
that AMDGPU has not, and some flags are duplicated 
(OPT_cl_fp32_correctly_rounded_divide_sqrt, 
OPT_fhip_fp32_correctly_rounded_divide_sqrt).

@b-sumner / @t-tye / @yaxunl / @scchan 

I'd like to suggest that we use the same handling of these flags on opencl / 
hip / c++  openmp. Since the names have diverged and we don't want to break 
backwards compatibility, I'd like to check for all three (hip, no_hip, cl) 
flags for each one, with last one wins semantics, and do that from a single 
method called by all the amdgpu language drivers.

That way hip and opencl will continue working as they do today, except hip will 
additionally accept some opencl flags and do the right thing, and likewise 
opencl.

If that is unacceptable, the near future involves 
OPT_fopenmp_fp32_correctly_rounded_device_sqrt and similar, and I'd much rather 
use the same path for all the languages than copy&paste again.

@pdhaliwal getCommonBitcodeLibs will splice in ockl as well as ocml and 
dependencies. OpenMP doesn't call into ockl so I'd like to avoid that, 
preferably by moving the ockl append out of getCommonBitcodeLibs

@amdgpu in general can we get rid of this oclc_isa_version_xxx.bc file, which 
only defines a single constant in each case
`@__oclc_ISA_version = linkonce_odr protected local_unnamed_addr addrspace(4) 
constant i32 9006, align 4`
in favour of emitting that linkonce_odr symbol from clang? Clang already knows 
which gpu it is compiling for, and uses that to find the file with the 
corresponding name on disk, so it could instead emit that symbol, letting us 
drop the O(N) tiny files from the install tree and slightly improving compile 
time?





Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105981

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


[PATCH] D104420: thread_local support for AIX

2021-07-14 Thread Hubert Tong via Phabricator via cfe-commits
hubert.reinterpretcast added inline comments.



Comment at: clang/lib/CodeGen/ItaniumCXXABI.cpp:2971
+isEmittedWithConstantInitializer(VD, true) &&
+!VD->needsDestruction(getContext())) {
+  // Emit a weak global function referring to the initialization function.

Unfortunately `needsDestruction` cannot be counted on at this time for some 
incomplete types, see https://llvm.org/pr51079.



Comment at: clang/lib/CodeGen/ItaniumCXXABI.cpp:2972-2975
+  // Emit a weak global function referring to the initialization function.
+  // This function will not exist if the TU defining the thread_local
+  // variable in question does not need any dynamic initialization for
+  // its thread_local variables.

This comment block is a copy/paste from above and is meant to describe a case 
where only a declaration of the init func is being emitted into the IR.


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

https://reviews.llvm.org/D104420

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


[clang] aefd6c6 - Combine two diagnostics into one and correct grammar

2021-07-14 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2021-07-14T11:43:28-04:00
New Revision: aefd6c615c91a2af89fa3697cf1813aac0f622de

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

LOG: Combine two diagnostics into one and correct grammar

The anonymous and non-anonymous bit-field diagnostics are easily
combined into one diagnostic. However, the diagnostic was missing a
"the" that is present in the almost-identically worded
warn_bitfield_width_exceeds_type_width diagnostic, hence the changes to
test cases.

Added: 


Modified: 
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Sema/SemaDecl.cpp
clang/test/Sema/bitfield.c
clang/test/SemaCXX/ms_wide_bitfield.cpp
clang/test/SemaObjC/class-bitfield.m

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 422507cd2842b..f4c189a3d178f 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -5839,11 +5839,8 @@ def err_anon_bitfield_has_negative_width : Error<
   "anonymous bit-field has negative width (%0)">;
 def err_bitfield_has_zero_width : Error<"named bit-field %0 has zero width">;
 def err_bitfield_width_exceeds_type_width : Error<
-  "width of bit-field %0 (%1 bits) exceeds %select{width|size}2 "
-  "of its type (%3 bit%s3)">;
-def err_anon_bitfield_width_exceeds_type_width : Error<
-  "width of anonymous bit-field (%0 bits) exceeds %select{width|size}1 "
-  "of its type (%2 bit%s2)">;
+  "width of%select{ anonymous|}0 bit-field%select{| %1}0 (%2 bits) exceeds the 
"
+  "%select{width|size}3 of its type (%4 bit%s4)">;
 def err_incorrect_number_of_vector_initializers : Error<
   "number of elements must be either one or match the size of the vector">;
 

diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 700a6db7fea89..c2dcdf0b8d1f6 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -16685,14 +16685,9 @@ ExprResult Sema::VerifyBitField(SourceLocation 
FieldLoc,
 if (CStdConstraintViolation || MSBitfieldViolation) {
   unsigned DiagWidth =
   CStdConstraintViolation ? TypeWidth : TypeStorageSize;
-  if (FieldName)
-return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
-   << FieldName << toString(Value, 10)
-   << !CStdConstraintViolation << DiagWidth;
-
-  return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
- << toString(Value, 10) << !CStdConstraintViolation
- << DiagWidth;
+  return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
+ << (bool)FieldName << FieldName << toString(Value, 10)
+ << !CStdConstraintViolation << DiagWidth;
 }
 
 // Warn on types where the user might conceivably expect to get all

diff  --git a/clang/test/Sema/bitfield.c b/clang/test/Sema/bitfield.c
index 03b2a22d3ed9b..13b6c3e152d72 100644
--- a/clang/test/Sema/bitfield.c
+++ b/clang/test/Sema/bitfield.c
@@ -6,7 +6,7 @@ struct a {
   int a : -1; // expected-error{{bit-field 'a' has negative width}}
 
   // rdar://6081627
-  int b : 33; // expected-error{{width of bit-field 'b' (33 bits) exceeds 
width of its type (32 bits)}}
+  int b : 33; // expected-error{{width of bit-field 'b' (33 bits) exceeds the 
width of its type (32 bits)}}
 
   int c : (1 + 0.25); // expected-error{{integer constant expression must have 
integer type}}
   int d : (int)(1 + 0.25); 
@@ -22,12 +22,12 @@ struct a {
   int g : (_Bool)1;
   
   // PR4017  
-  char : 10;  // expected-error {{width of anonymous bit-field (10 bits) 
exceeds width of its type (8 bits)}}
+  char : 10;  // expected-error {{width of anonymous bit-field (10 bits) 
exceeds the width of its type (8 bits)}}
   unsigned : -2;  // expected-error {{anonymous bit-field has negative width 
(-2)}}
   float : 12; // expected-error {{anonymous bit-field has non-integral 
type 'float'}}
 
-  _Bool : 2;   // expected-error {{width of anonymous bit-field (2 bits) 
exceeds width of its type (1 bit)}}
-  _Bool h : 5; // expected-error {{width of bit-field 'h' (5 bits) exceeds 
width of its type (1 bit)}}
+  _Bool : 2;   // expected-error {{width of anonymous bit-field (2 bits) 
exceeds the width of its type (1 bit)}}
+  _Bool h : 5; // expected-error {{width of bit-field 'h' (5 bits) exceeds the 
width of its type (1 bit)}}
 };
 
 struct b {unsigned x : 2;} x;

diff  --git a/clang/test/SemaCXX/ms_wide_bitfield.cpp 
b/clang/test/SemaCXX/ms_wide_bitfield.cpp
index b634e78c70ce5..0dcc787928b0a 100644
--- a/clang/test/SemaCXX/ms_wide_bitfield.cpp
+++ b/clang/test/SemaCXX/ms_wide_bitfield.cpp
@@ -1,9 +1,9 @@
 // RUN: %clang_cc1 -fno-rtti -emit-llvm-only -triple

[PATCH] D105904: [clangd] Support `#pragma mark` in the outline

2021-07-14 Thread David Goldman via Phabricator via cfe-commits
dgoldman added a comment.

In D105904#2877184 , @kadircet wrote:

> So first of all, it is not clear to me if this is a useful enough improvement 
> to justify all the new code, but looking at your investment I'll assume this 
> is really common in ObjC land and gonna be useful for developers working with 
> ObjC. That's enough of a justification for me, but I'd be more than happy to 
> see some real data if you have any.

Yep, I can you send you some searches internally with how prevalent they are.

> That being said, reading the code it seems like the intent is enabling 
> `#pragma mark` directives the introduce symbols that are either leaves or 
> containers:
>
> - Leaf case is obvious and straightforward, it is just like a normal 
> declaration happening at that particular location. It is unclear which kind 
> should be used. It seems you've went with `File` but I don't think it is 
> suitable in this case. I would suggest using `Null`.
> - Container case is more sophisticated. One thing is for sure, they are 
> nested under the same symbol a declaration occuring at that point would be. 
> They also seem to contain all the symbols that would nest under current 
> subtree and spelled after the mark and spelled before any other marks. Hence 
> there is no way to explicitly terminate the scope of a mark. They are 
> implicitly terminated by hitting the end of the container containing the mark 
> or hitting a new mark directive. This also implies one cannot have multiple 
> levels of nesting just by pragma directives, but it can be achieved if there 
> are usual containers with more mark directives (see my comment around tests 
> for an example).
>
> Can you verify that I understood the intent correctly and make it more 
> explicit in the comments as well?

Yep, although there are some TODOs there, we could allow letting leaf nodes to 
be contained in a group parent as well as potentially merging them in the 
`#pragma mark -` followed by `#pragma mark Foo` case.

There's no good kind at the moment IMO, I don't really have a preference as 
long as it doesn't render awkwardly in VS Code.

> (Terminating containers implicitly sounds like an unfortunate limitation to 
> me. I'd rather only enable termination of them explicitly) but I suppose 
> there's a lot of code that's already existing out in the world with the 
> assumption of XCode's implicit termination rules, so this is probably not 
> gonna be helpful in reality. Hence we can't do much.)

I don't think this an Xcode limitation really - more of an LSP spec limitation. 
If we create a group inside of another symbol, we are effectively contained in 
it and cannot escape without violating the spec, right? To be clear, Xcode 
rules are a bit different - see the link above - the `#pragma mark -` just 
creates a divider which we can't mirror.

> Before diving into the details of the implementation it looks like we are 
> doing some post-processing to incorporate mark pragmas into the tree, why 
> can't we just insert them while building the tree as we do with macros? for 
> example:
>
> - when inserting a symbol we look for a possible mark-pragma container 
> (similar to macro case), a mark pragma is only eligible as a container if it 
> is contained within the range of the parent && spelled before current 
> declaration at hand && is a group.

This assumes (like this code today) that the nodes are sorted properly and the 
ranges of the parent are accurate. I was thinking of adding a proper sort in a 
post-processing phase but maybe we could do it + range fix up during insertion. 
Seems complicated to move everything over to insertion, but if you think that's 
reasonable, I can try that out.

And that case generally works but we need to be sure to handle multiple pragmas 
next to each other. `#pragma mark - Foo\n#pragma mark - Bar` turns Foo into an 
empty group and Bar takes decls after. And then, currently, a `#pragma mark 
Third` would end the group as well.

> - as for insertion of leaves, after traversal of all the children we can just 
> add any mark pragmas that occured within the current symbol's range as a 
> child. we can also drop any mark pragmas occuring inside symbols that doesn't 
> require child traversal this way.

I think it's a bit more complicated since the leaf nodes terminate the groups. 
As long as we do that it should be fine, assuming editors don't require it to 
be sorted.

> This approach relies on the fact that `range` calculated by `declToSym` will 
> be correct enough. I think it should be good in most cases, but might require 
> some adjustments around macros, as usual (can't think of a problematic 
> example right now though).
> This brings out the question about ordering of `children` in 
> `DocumentSymbol`, lsp doesn't say anything about it today, but during 
> rendering we can just order these based on the `selectionRange` (probably 
> during `build`) and hope that clients will pres

[PATCH] D105988: [OpenCL] NULL introduced prior to v2.0

2021-07-14 Thread Justas Janickas via Phabricator via cfe-commits
Topotuna updated this revision to Diff 358625.
Topotuna added a comment.

Added compile time flags

  -finclude-default-header -fdeclare-opencl-builtins

instead of

  #define NULL ((void*)0)


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

https://reviews.llvm.org/D105988

Files:
  clang/lib/Headers/opencl-c-base.h
  clang/test/SemaOpenCL/null_literal.cl


Index: clang/test/SemaOpenCL/null_literal.cl
===
--- clang/test/SemaOpenCL/null_literal.cl
+++ clang/test/SemaOpenCL/null_literal.cl
@@ -1,8 +1,7 @@
-// RUN: %clang_cc1 -fdeclare-opencl-builtins -finclude-default-header -verify 
%s
-// RUN: %clang_cc1 -cl-std=CL1.0 -fdeclare-opencl-builtins 
-finclude-default-header -verify %s
-// RUN: %clang_cc1 -cl-std=CL1.1 -fdeclare-opencl-builtins 
-finclude-default-header -verify %s
-// RUN: %clang_cc1 -cl-std=CL1.2 -fdeclare-opencl-builtins 
-finclude-default-header -verify %s
-// RUN: %clang_cc1 -cl-std=CL2.0 -DCL20 -fdeclare-opencl-builtins 
-finclude-default-header -verify %s
+// RUN: %clang_cc1 -verify %s
+// RUN: %clang_cc1 -cl-std=CL2.0 -DCL20 -verify %s
+
+#define NULL ((void*)0)
 
 void foo(){
 
Index: clang/lib/Headers/opencl-c-base.h
===
--- clang/lib/Headers/opencl-c-base.h
+++ clang/lib/Headers/opencl-c-base.h
@@ -164,7 +164,7 @@
 typedef double double16 __attribute__((ext_vector_type(16)));
 #endif
 
-#if defined(__OPENCL_CPP_VERSION__) || defined(__OPENCL_C_VERSION__)
+#if defined(__OPENCL_CPP_VERSION__) || (__OPENCL_C_VERSION__ >= CL_VERSION_2_0)
 #define NULL ((void*)0)
 #endif
 


Index: clang/test/SemaOpenCL/null_literal.cl
===
--- clang/test/SemaOpenCL/null_literal.cl
+++ clang/test/SemaOpenCL/null_literal.cl
@@ -1,8 +1,7 @@
-// RUN: %clang_cc1 -fdeclare-opencl-builtins -finclude-default-header -verify %s
-// RUN: %clang_cc1 -cl-std=CL1.0 -fdeclare-opencl-builtins -finclude-default-header -verify %s
-// RUN: %clang_cc1 -cl-std=CL1.1 -fdeclare-opencl-builtins -finclude-default-header -verify %s
-// RUN: %clang_cc1 -cl-std=CL1.2 -fdeclare-opencl-builtins -finclude-default-header -verify %s
-// RUN: %clang_cc1 -cl-std=CL2.0 -DCL20 -fdeclare-opencl-builtins -finclude-default-header -verify %s
+// RUN: %clang_cc1 -verify %s
+// RUN: %clang_cc1 -cl-std=CL2.0 -DCL20 -verify %s
+
+#define NULL ((void*)0)
 
 void foo(){
 
Index: clang/lib/Headers/opencl-c-base.h
===
--- clang/lib/Headers/opencl-c-base.h
+++ clang/lib/Headers/opencl-c-base.h
@@ -164,7 +164,7 @@
 typedef double double16 __attribute__((ext_vector_type(16)));
 #endif
 
-#if defined(__OPENCL_CPP_VERSION__) || defined(__OPENCL_C_VERSION__)
+#if defined(__OPENCL_CPP_VERSION__) || (__OPENCL_C_VERSION__ >= CL_VERSION_2_0)
 #define NULL ((void*)0)
 #endif
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D105973: [ASTMatchers] NFC: Fix the annotation.

2021-07-14 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

The change looks good to me, but you need to regenerate the documentation 
manually. You can do so by running clang/docs/tools/dump_ast_matchers.py.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105973

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


[PATCH] D105988: [OpenCL] NULL introduced prior to v2.0

2021-07-14 Thread Justas Janickas via Phabricator via cfe-commits
Topotuna updated this revision to Diff 358628.
Topotuna added a comment.

Wrong diff file added previously


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

https://reviews.llvm.org/D105988

Files:
  clang/lib/Headers/opencl-c-base.h
  clang/test/SemaOpenCL/null_literal.cl


Index: clang/test/SemaOpenCL/null_literal.cl
===
--- clang/test/SemaOpenCL/null_literal.cl
+++ clang/test/SemaOpenCL/null_literal.cl
@@ -1,7 +1,8 @@
-// RUN: %clang_cc1 -verify %s
-// RUN: %clang_cc1 -cl-std=CL2.0 -DCL20 -verify %s
-
-#define NULL ((void*)0)
+// RUN: %clang_cc1 -fdeclare-opencl-builtins -finclude-default-header -verify 
%s
+// RUN: %clang_cc1 -cl-std=CL1.0 -fdeclare-opencl-builtins 
-finclude-default-header -verify %s
+// RUN: %clang_cc1 -cl-std=CL1.1 -fdeclare-opencl-builtins 
-finclude-default-header -verify %s
+// RUN: %clang_cc1 -cl-std=CL1.2 -fdeclare-opencl-builtins 
-finclude-default-header -verify %s
+// RUN: %clang_cc1 -cl-std=CL2.0 -DCL20 -fdeclare-opencl-builtins 
-finclude-default-header -verify %s
 
 void foo(){
 
Index: clang/lib/Headers/opencl-c-base.h
===
--- clang/lib/Headers/opencl-c-base.h
+++ clang/lib/Headers/opencl-c-base.h
@@ -164,7 +164,7 @@
 typedef double double16 __attribute__((ext_vector_type(16)));
 #endif
 
-#if defined(__OPENCL_CPP_VERSION__) || (__OPENCL_C_VERSION__ >= CL_VERSION_2_0)
+#if defined(__OPENCL_CPP_VERSION__) || defined(__OPENCL_C_VERSION__)
 #define NULL ((void*)0)
 #endif
 


Index: clang/test/SemaOpenCL/null_literal.cl
===
--- clang/test/SemaOpenCL/null_literal.cl
+++ clang/test/SemaOpenCL/null_literal.cl
@@ -1,7 +1,8 @@
-// RUN: %clang_cc1 -verify %s
-// RUN: %clang_cc1 -cl-std=CL2.0 -DCL20 -verify %s
-
-#define NULL ((void*)0)
+// RUN: %clang_cc1 -fdeclare-opencl-builtins -finclude-default-header -verify %s
+// RUN: %clang_cc1 -cl-std=CL1.0 -fdeclare-opencl-builtins -finclude-default-header -verify %s
+// RUN: %clang_cc1 -cl-std=CL1.1 -fdeclare-opencl-builtins -finclude-default-header -verify %s
+// RUN: %clang_cc1 -cl-std=CL1.2 -fdeclare-opencl-builtins -finclude-default-header -verify %s
+// RUN: %clang_cc1 -cl-std=CL2.0 -DCL20 -fdeclare-opencl-builtins -finclude-default-header -verify %s
 
 void foo(){
 
Index: clang/lib/Headers/opencl-c-base.h
===
--- clang/lib/Headers/opencl-c-base.h
+++ clang/lib/Headers/opencl-c-base.h
@@ -164,7 +164,7 @@
 typedef double double16 __attribute__((ext_vector_type(16)));
 #endif
 
-#if defined(__OPENCL_CPP_VERSION__) || (__OPENCL_C_VERSION__ >= CL_VERSION_2_0)
+#if defined(__OPENCL_CPP_VERSION__) || defined(__OPENCL_C_VERSION__)
 #define NULL ((void*)0)
 #endif
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D105981: [AMDGPU][OpenMP] Support linking of math libraries

2021-07-14 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added inline comments.



Comment at: clang/lib/Driver/ToolChains/AMDGPU.cpp:879-889
+  // TODO: There are way too many flags that change this. Do we need to check
+  // them all?
+  bool DAZ = DriverArgs.hasArg(options::OPT_cl_denorms_are_zero) ||
+ getDefaultDenormsAreZeroForTarget(Kind);
+  bool FiniteOnly = DriverArgs.hasArg(options::OPT_cl_finite_math_only);
+
+  bool UnsafeMathOpt =

I agree that we'd better refactor this part as a common function used by 
HIP/OpenMP/OpenCL. However I disagree to let HIP use OpenCL options. HIP uses 
clang generic options or HIP/CUDA shared options to control these flags. I 
think OpenMP may consider using similar options as HIP instead of OpenCL 
options.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105981

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


  1   2   3   >